context
stringlengths
2.52k
185k
gt
stringclasses
1 value
#region File Description //----------------------------------------------------------------------------- // GameplayScreen.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Audio; using System.IO.IsolatedStorage; using System.IO; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Input.Touch; using Microsoft.Devices.Sensors; using GameStateManagement; #endregion namespace CatapultGame { class GameplayScreen : GameScreen { #region Fields // Texture Members Texture2D foregroundTexture; Texture2D cloud1Texture; Texture2D cloud2Texture; Texture2D mountainTexture; Texture2D skyTexture; Texture2D hudBackgroundTexture; Texture2D ammoTypeTexture; Texture2D windArrowTexture; Texture2D defeatTexture; Texture2D victoryTexture; SpriteFont hudFont; // Rendering members Vector2 playerHUDPosition; Vector2 computerHUDPosition; Vector2 windArrowPosition; // Camera related members const float maxCameraSpeed = 10; bool isFlying; // Is the camera flying (after being flicked) Vector2 flightDestination; // The destination to which the camera is flying Point flightDestinationPoint; Vector2 catapultCenterOffset; // Input members GestureSample? currentSample; GestureSample? prevSample; bool isDragging; GestureType? lastGestureType; // Gameplay members Human player; AI computer; Vector2 wind; bool changeTurn; bool isHumanTurn; bool isCameraMoving; bool gameOver; Random random; const int minWind = 0; const int maxWind = 10; const float MinScale = 1f; const float MaxScale = 2f; #endregion #region Properties public int CameraMinXOffset { get { return -(ScaleToCamera(foregroundTexture.Width) - Viewport.Width); } } public int CameraMaxXOffset { get { return 0; } } public int CameraMinYOffset { get { return -(ScaleToCamera(foregroundTexture.Height) - Viewport.Height); } } public int CameraMaxYOffset { get { return ScaleToCamera(skyTexture.Height) - ScaleToCamera(foregroundTexture.Height); } } Vector2 drawOffset; /// <summary> /// Used to offset the camera position /// </summary> public Vector2 DrawOffset { get { //return drawOffset * DrawScale; return drawOffset; } set { player.DrawOffset = value; computer.DrawOffset = value; drawOffset = value; } } float drawScale; /// <summary> /// Used to zoom the camera in and out /// </summary> public float DrawScale { get { return drawScale; } set { player.DrawScale = value; computer.DrawScale = value; drawScale = value; } } public Viewport Viewport { get { return ScreenManager.GraphicsDevice.Viewport; } } /// <summary> /// Returns the coordinate currently at the center of the screen /// </summary> public Vector2 ScreenCenter { get { return new Vector2(Viewport.Width / 2 - DrawOffset.X, Viewport.Height / 2 - DrawOffset.Y); } } Vector2 mountainPosition; public Vector2 MountainPosition { get { return ScaleToCamera(mountainPosition); } } public Vector2 SkyPosition { get { return new Vector2(0, -(ScaleToCamera(skyTexture.Height) - ScaleToCamera(foregroundTexture.Height))); } } Vector2 cloud1Position; /// <summary> /// Used to return the clouds position for drawing purposes, taking scale into /// account. /// </summary> public Vector2 Cloud1Position { get { return cloud1Position * DrawScale; } } Vector2 cloud2Position; /// <summary> /// Used to return the clouds position for drawing purposes, taking scale into /// account. /// </summary> public Vector2 Cloud2Position { get { return cloud2Position * DrawScale; } } #endregion #region Initialization public GameplayScreen() { EnabledGestures = GestureType.FreeDrag | GestureType.DragComplete | GestureType.Flick | GestureType.Tap | GestureType.Pinch | GestureType.PinchComplete; random = new Random(); } #endregion #region Content Loading/Unloading /// <summary> /// Loads the game assets and initializes "players" /// </summary> public override void LoadContent() { base.LoadContent(); // Start the game Start(); } public void LoadAssets() { // Load textures foregroundTexture = Load<Texture2D>("Textures/Backgrounds/gameplay_screen"); cloud1Texture = Load<Texture2D>("Textures/Backgrounds/cloud1"); cloud2Texture = Load<Texture2D>("Textures/Backgrounds/cloud2"); mountainTexture = Load<Texture2D>("Textures/Backgrounds/mountain"); skyTexture = Load<Texture2D>("Textures/Backgrounds/sky"); defeatTexture = Load<Texture2D>("Textures/Backgrounds/defeat"); victoryTexture = Load<Texture2D>("Textures/Backgrounds/victory"); hudBackgroundTexture = Load<Texture2D>("Textures/HUD/hudBackground"); windArrowTexture = Load<Texture2D>("Textures/HUD/windArrow"); ammoTypeTexture = Load<Texture2D>("Textures/HUD/ammoType"); // Load font hudFont = Load<SpriteFont>("Fonts/HUDFont"); // Define initial cloud position cloud1Position = new Vector2(224 - cloud1Texture.Width, 0); cloud2Position = new Vector2(64, 90); // Define initial HUD positions playerHUDPosition = new Vector2(7, 7); computerHUDPosition = new Vector2(613, 7); windArrowPosition = new Vector2(345, 46); mountainPosition = new Vector2(400, 0); isCameraMoving = true; catapultCenterOffset = new Vector2(100, 0); // Initialize human & AI players player = new Human(ScreenManager.Game, ScreenManager.SpriteBatch); player.Initialize(); player.Name = "Player"; computer = new AI(ScreenManager.Game, ScreenManager.SpriteBatch); computer.Initialize(); computer.Name = "Phone"; // Identify enemies player.Enemy = computer; computer.Enemy = player; DrawOffset = new Vector2(-400, 0); DrawScale = 1f; CenterOnPosition(player.Catapult.Position + catapultCenterOffset); } #endregion #region Update /// <summary> /// Runs one frame of update for the game. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> public override void Update(GameTime gameTime, bool otherScreenHasFocus, bool coveredByOtherScreen) { float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds; // Check it one of the players reached 5 and stop the game if ((player.Catapult.GameOver || computer.Catapult.GameOver) && (gameOver == false)) { gameOver = true; if (player.Score > computer.Score) { AudioManager.PlaySound("gameOver_Win"); } else { AudioManager.PlaySound("gameOver_Lose"); } return; } if (isFlying) { if (ScreenCenter == flightDestination) { isFlying = false; } else { // Find the direction in which we need to move to get from the // screen center to our flight destination Vector2 flightVector = flightDestination - ScreenCenter; Vector2 flightMovementVector = flightVector; flightMovementVector.Normalize(); flightMovementVector *= 10; flightMovementVector *= (float)(0.25 * (2 + Math.Log((flightVector.Length() + 0.2)))); if (flightMovementVector.Length() > flightVector.Length()) { DrawOffset -= flightVector; } else { DrawOffset -= flightMovementVector; } CorrectScreenPosition(40, 30); } } else { CorrectScreenPosition(0, 0); } // If Reset flag raised and both catapults are not animating - // active catapult finished the cycle, new turn! if ((player.Catapult.CurrentState == CatapultState.Reset || computer.Catapult.CurrentState == CatapultState.Reset) && !(player.Catapult.AnimationRunning || computer.Catapult.AnimationRunning)) { changeTurn = true; if (player.IsActive == true) // Last turn was a human turn? { CenterOnPosition(computer.Catapult.Position - catapultCenterOffset); player.IsActive = false; computer.IsActive = true; isHumanTurn = false; player.Catapult.CurrentState = CatapultState.Idle; computer.Catapult.CurrentState = CatapultState.Aiming; } else //It was an AI turn { isCameraMoving = true; player.IsActive = true; computer.IsActive = false; isHumanTurn = true; computer.Catapult.CurrentState = CatapultState.Idle; player.Catapult.CurrentState = CatapultState.Idle; } } if (changeTurn) { // Update wind wind = new Vector2(random.Next(-1, 2), random.Next(minWind, maxWind + 1)); // Set new wind value to the players and player.Catapult.Wind = computer.Catapult.Wind = wind.X > 0 ? wind.Y : -wind.Y; changeTurn = false; } // Update the players player.Update(gameTime); computer.Update(gameTime); // Updates the clouds position UpdateClouds(elapsed); base.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen); } #endregion #region Draw /// <summary> /// Draw the game world, effects, and HUD /// </summary> /// <param name="gameTime">The elapsed time since last Draw</param> public override void Draw(GameTime gameTime) { ScreenManager.SpriteBatch.Begin(); // Render all parts of the screen DrawBackground(); DrawComputer(gameTime); DrawPlayer(gameTime); DrawHud(); ScreenManager.SpriteBatch.End(); } #endregion #region Input /// <summary> /// Input helper method provided by GameScreen. Packages up the various input /// values for ease of use. /// </summary> /// <param name="input">The state of the gamepads</param> public override void HandleInput(InputState input) { if (input == null) throw new ArgumentNullException("input"); if (gameOver) { if (input.IsPauseGame(null)) { FinishCurrentGame(); } foreach (GestureSample gestureSample in input.Gestures) { if (gestureSample.GestureType == GestureType.Tap) { FinishCurrentGame(); } } return; } if (input.IsPauseGame(null)) { PauseCurrentGame(); } else if (isCameraMoving) // Handle camera movement { // Read all available gestures foreach (GestureSample gestureSample in input.Gestures) { switch (gestureSample.GestureType) { case GestureType.FreeDrag: if (CatapultTapped(gestureSample.Position)) { // Allow player to fire isCameraMoving = false; CenterOnPosition(player.Catapult.Position + catapultCenterOffset); } else { isDragging = true; // Move screen according to delta Vector2 newOffset = DrawOffset; newOffset += gestureSample.Delta; DrawOffset = ClampDrawOffset(newOffset); } break; case GestureType.DragComplete: // turn off dragging state ResetDragState(); break; case GestureType.Tap: if (isCameraMoving) { isFlying = false; } break; case GestureType.Flick: // Ignore flicks which appear as part of a pinch ending if (lastGestureType != GestureType.PinchComplete) { FlyToPositionNoScale( ScreenCenter - gestureSample.Delta); } break; case GestureType.Pinch: // Store last drag location if (null == prevSample) { prevSample = gestureSample; } else { prevSample = currentSample; } // save the current gesture sample currentSample = gestureSample; float currentLength = (currentSample.Value.Position - currentSample.Value.Position2).Length(); float previousLength = (prevSample.Value.Position - prevSample.Value.Position2).Length(); float scaleChange = (currentLength - previousLength) * 0.05f; Vector2 previousCenter = ScreenCenter; float previousScale = DrawScale; DrawScale += scaleChange; DrawScale = MathHelper.Clamp(DrawScale, MinScale, MaxScale); CenterOnPositionNoScale(previousCenter * DrawScale / previousScale); break; case GestureType.PinchComplete: ResetPinchState(); break; default: break; } lastGestureType = gestureSample.GestureType; } } else if (isHumanTurn && (player.Catapult.CurrentState == CatapultState.Idle || player.Catapult.CurrentState == CatapultState.Aiming)) { // Read all available gestures foreach (GestureSample gestureSample in input.Gestures) { if (gestureSample.GestureType == GestureType.FreeDrag) isDragging = true; else if (gestureSample.GestureType == GestureType.DragComplete) isDragging = false; player.HandleInput(gestureSample); } } } #endregion #region Update Helpers private void UpdateClouds(float elapsedTime) { // Move the clouds according to the wind int windDirection = wind.X > 0 ? 1 : -1; cloud1Position += new Vector2(24.0f, 0.0f) * elapsedTime * windDirection * wind.Y; if (cloud1Position.X > foregroundTexture.Width) cloud1Position.X = -cloud1Texture.Width * 2.0f; else if (cloud1Position.X < -cloud1Texture.Width * 2.0f) cloud1Position.X = foregroundTexture.Width; cloud2Position += new Vector2(16.0f, 0.0f) * elapsedTime * windDirection * wind.Y; if (cloud2Position.X > foregroundTexture.Width) cloud2Position.X = -cloud2Texture.Width * 2.0f; else if (cloud2Position.X < -cloud2Texture.Width * 2.0f) cloud2Position.X = foregroundTexture.Width; } #endregion #region Draw Helpers /// <summary> /// Draws the player's catapult /// </summary> void DrawPlayer(GameTime gameTime) { if (!gameOver) player.Draw(gameTime); } /// <summary> /// Draws the AI's catapult /// </summary> void DrawComputer(GameTime gameTime) { if (!gameOver) computer.Draw(gameTime); } /// <summary> /// Draw the sky, clouds, mountains, etc. /// </summary> private void DrawBackground() { // Clear the background ScreenManager.Game.GraphicsDevice.Clear(Color.Black); // Draw the Sky ScreenManager.SpriteBatch.Draw(skyTexture, SkyPosition + new Vector2(0, DrawOffset.Y), null, Color.White, 0, Vector2.Zero, DrawScale, SpriteEffects.None, 0); // Draw Cloud #1 ScreenManager.SpriteBatch.Draw(cloud1Texture, cloud1Position * DrawScale + DrawOffset, null, Color.White, 0, Vector2.Zero, DrawScale, SpriteEffects.None, 0); // Draw the Mountain ScreenManager.SpriteBatch.Draw(mountainTexture, MountainPosition + DrawOffset, null, Color.White, 0, Vector2.Zero, DrawScale, SpriteEffects.None, 0); // Draw Cloud #2 ScreenManager.SpriteBatch.Draw(cloud2Texture, cloud2Position * DrawScale + DrawOffset, null, Color.White, 0, Vector2.Zero, DrawScale, SpriteEffects.None, 0); // Draw the Castle, trees, and foreground ScreenManager.SpriteBatch.Draw(foregroundTexture, DrawOffset, null, Color.White, 0, Vector2.Zero, DrawScale, SpriteEffects.None, 0); } /// <summary> /// Draw the HUD, which consists of the score elements and the GAME OVER tag. /// </summary> void DrawHud() { if (gameOver) { Texture2D texture; if (player.Score > computer.Score) { texture = victoryTexture; } else { texture = defeatTexture; } ScreenManager.SpriteBatch.Draw( texture, new Vector2(ScreenManager.Game.GraphicsDevice.Viewport.Width / 2 - texture.Width / 2, ScreenManager.Game.GraphicsDevice.Viewport.Height / 2 - texture.Height / 2), Color.White); } else { // Draw Player Hud ScreenManager.SpriteBatch.Draw(hudBackgroundTexture, playerHUDPosition, Color.White); ScreenManager.SpriteBatch.Draw(ammoTypeTexture, playerHUDPosition + new Vector2(33, 35), Color.White); DrawString(hudFont, player.Score.ToString(), playerHUDPosition + new Vector2(123, 35), Color.White); DrawString(hudFont, player.Name, playerHUDPosition + new Vector2(40, 1), Color.Blue); // Draw Computer Hud ScreenManager.SpriteBatch.Draw(hudBackgroundTexture, computerHUDPosition, Color.White); ScreenManager.SpriteBatch.Draw(ammoTypeTexture, computerHUDPosition + new Vector2(33, 35), Color.White); DrawString(hudFont, computer.Score.ToString(), computerHUDPosition + new Vector2(123, 35), Color.White); DrawString(hudFont, computer.Name, computerHUDPosition + new Vector2(40, 1), Color.Red); // Draw Wind direction string text = "WIND"; Vector2 size = hudFont.MeasureString(text); Vector2 windarrowScale = new Vector2(wind.Y / 10, 1); ScreenManager.SpriteBatch.Draw(windArrowTexture, windArrowPosition, null, Color.White, 0, Vector2.Zero, windarrowScale, wind.X > 0 ? SpriteEffects.None : SpriteEffects.FlipHorizontally, 0); DrawString(hudFont, text, windArrowPosition - new Vector2(0, size.Y), Color.Black); if (wind.Y == 0) { text = "NONE"; DrawString(hudFont, text, windArrowPosition, Color.Black); } if (isCameraMoving == false) { if (isHumanTurn) { // Prepare human prompt message text = !isDragging ? "Drag Anywhere to Fire" : "Release to Fire!"; } else { // Prepare AI message text = "I'll get you yet!"; } } else { text = "Drag from your catapult to start shooting"; } size = hudFont.MeasureString(text); DrawString(hudFont, text, new Vector2( ScreenManager.GraphicsDevice.Viewport.Width / 2 - size.X / 2, ScreenManager.GraphicsDevice.Viewport.Height - size.Y), Color.Green); } } /// <summary> /// A simple helper to draw shadowed text. /// </summary> void DrawString(SpriteFont font, string text, Vector2 position, Color color) { ScreenManager.SpriteBatch.DrawString(font, text, new Vector2(position.X + 1, position.Y + 1), Color.Black); ScreenManager.SpriteBatch.DrawString(font, text, position, color); } /// <summary> /// A simple helper to draw shadowed text. /// </summary> void DrawString(SpriteFont font, string text, Vector2 position, Color color, float fontScale) { ScreenManager.SpriteBatch.DrawString(font, text, new Vector2(position.X + 1, position.Y + 1), Color.Black, 0, new Vector2(0, font.LineSpacing / 2), fontScale, SpriteEffects.None, 0); ScreenManager.SpriteBatch.DrawString(font, text, position, color, 0, new Vector2(0, font.LineSpacing / 2), fontScale, SpriteEffects.None, 0); } #endregion #region Input Helpers /// <summary> /// Finish the current game /// </summary> private void FinishCurrentGame() { ExitScreen(); } public void ResetDragState() { isDragging = false; } public void ResetPinchState() { prevSample = null; currentSample = null; } /// <summary> /// Checks if the user tapped his own catapult. /// </summary> /// <param name="vector2">The tap location on the device's display.</param> /// <returns>True if the player's catapult was clicked, /// false otherwise.</returns> private bool CatapultTapped(Vector2 tapPoint) { tapPoint -= DrawOffset; // Take draw offset into account Vector2 catapultPos = player.Catapult.Position * DrawScale; Vector3 min = new Vector3(catapultPos, 0); Vector3 max = new Vector3(catapultPos + new Vector2(player.Catapult.Width * DrawScale, player.Catapult.Height * DrawScale), 0); BoundingBox catapultBox = new BoundingBox(min, max); min = new Vector3(tapPoint.X - ScaleToCamera(10), tapPoint.Y + ScaleToCamera(10), 0); max = new Vector3(tapPoint.X + ScaleToCamera(10), tapPoint.Y - ScaleToCamera(10), 0); BoundingBox tapBox = new BoundingBox(min, max); return catapultBox.Intersects(tapBox); } /// <summary> /// Pause the current game /// </summary> private void PauseCurrentGame() { var pauseMenuBackground = new BackgroundScreen(); if (isDragging) { isDragging = false; player.Catapult.CurrentState = CatapultState.Idle; } ScreenManager.AddScreen(pauseMenuBackground, null); ScreenManager.AddScreen(new PauseScreen(pauseMenuBackground, player, computer), null); } #endregion #region Camera helpers /// <summary> /// Used to scale an integer value according to the current camera zoom /// </summary> /// <param name="value">The value to scale.</param> /// <returns>The scaled value.</returns> public int ScaleToCamera(int value) { return (int)(value * DrawScale); } /// <summary> /// Used to scale a 2D vector according to the current camera zoom /// </summary> /// <param name="value">The vector to scale.</param> /// <returns>The scaled vector.</returns> public Vector2 ScaleToCamera(Vector2 vector) { return vector * DrawScale; } /// <summary> /// Used to cause the screen to fly back into gameworld bounds if the camera /// has panned too far. /// </summary> /// <param name="xTolerance">The distance from the horizontal edge of the /// game world before position correction will occur.</param> /// <param name="yTolerance">The distance from the vertical edge of the /// game world before position correction will occur.</param> private void CorrectScreenPosition(int xTolerance, int yTolerance) { // If we moved beyond the screen bounds, move back Vector2 correctionVector = ScreenCenter; bool needCorrection = false; if (DrawOffset.X > CameraMaxXOffset + xTolerance) { //correctionVector.X = Viewport.Width / 2; correctionVector.X = CameraMaxXOffset + Viewport.Width / 2; needCorrection = true; } else if (DrawOffset.X < CameraMinXOffset - xTolerance) { correctionVector.X = ScaleToCamera(foregroundTexture.Width) - Viewport.Width / 2; needCorrection = true; } if (DrawOffset.Y > CameraMaxYOffset + yTolerance) { correctionVector.Y = SkyPosition.Y + Viewport.Height / 2; needCorrection = true; } else if (DrawOffset.Y < CameraMinYOffset - yTolerance) { correctionVector.Y = ScaleToCamera(foregroundTexture.Height) - Viewport.Height / 2; needCorrection = true; } if (needCorrection) { FlyToPositionNoScale(correctionVector); } } /// <summary> /// Shifts the display so that the designated point is in the center of the /// display, assuming that is possible. /// </summary> /// <param name="centerLocation">The location to center on.</param> public void CenterOnPosition(Vector2 centerLocation) { centerLocation *= DrawScale; CenterOnPositionNoScale(centerLocation); } public void CenterOnPositionNoScale(Vector2 centerLocation) { int viewWidth = ScreenManager.GraphicsDevice.Viewport.Width; int viewHeight = ScreenManager.GraphicsDevice.Viewport.Height; Vector2 newOffset = new Vector2( viewWidth / 2 - centerLocation.X, viewHeight / 2 - centerLocation.Y); DrawOffset = ClampDrawOffset(newOffset); ; } /// <summary> /// Causes the camera to smoothly fly to a specified destination. /// The camera will aim for the destination to be visible on screen. /// </summary> /// <param name="centerLocation">The location to fly to.</param> public void FlyToPosition(Vector2 flightDestination) { flightDestination *= DrawScale; FlyToPositionNoScale(flightDestination); } private void FlyToPositionNoScale(Vector2 flightDestination) { flightDestinationPoint = new Point((int)flightDestination.X, (int)flightDestination.Y); this.flightDestination = flightDestination; isFlying = true; } /// <summary> /// Used to make sure an offset is not outside the bounds of the game world. /// </summary> /// <param name="offset">Offset to clamp.</param> /// <returns>The offset after clamping it to fit inside the /// game world.</returns> private Vector2 ClampDrawOffset(Vector2 offset) { offset.X = MathHelper.Clamp(offset.X, CameraMinXOffset, CameraMaxXOffset); offset.Y = MathHelper.Clamp(offset.Y, CameraMinYOffset, CameraMaxYOffset); return offset; } #endregion #region Gameplay Helpers /// <summary> /// Starts a new game session, setting all game states to initial values. /// </summary> void Start() { // Set initial wind direction wind = Vector2.Zero; isHumanTurn = false; changeTurn = true; computer.Catapult.CurrentState = CatapultState.Reset; } #endregion } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace ContactsManager.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try get sample provided for a specific mediaType, controllerName, actionName and parameterNames. // If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames // If still not found, try get the sample provided for a specific type and mediaType if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create one using <see cref="ObjectGenerator"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // Try create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); sampleObject = objectGenerator.GenerateObject(type); } return sampleObject; } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ActionDescriptor.ReturnType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, e.Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using EffectEditor.EffectComponents; using EffectEditor.EffectComponents.HLSLInformation; namespace EffectEditor.Controls { public partial class ComponentEditor : UserControl { #region Fields #region XML Docs /// <summary> /// The component being edited by this editor /// </summary> #endregion public EffectComponent Component; #region XML Docs /// <summary> /// Used to store shader profile names /// </summary> #endregion private string[] mShaderProfileNames; #region XML Docs /// <summary> /// Called when the component changes /// </summary> #endregion public event EventHandler ComponentChanged; private void OnComponentChanged() { if (ComponentChanged != null) ComponentChanged(this, new EventArgs()); } private Stack<int> mNameSelectionParams = new Stack<int>(); private bool mSuspendComponentSelectionChange = false; #endregion #region Properties #region XML Docs /// <summary> /// Whether or not usage of components in shader code is allowed /// </summary> #endregion [Browsable(true), Category("Shader"), Description("Whether or not usage of components in shader code is allowed")] public bool AllowComponentUsage { get { return componentSelectionBox.Visible; } set { componentSelectionBox.Visible = value; componentSelectionLabel.Visible = value; if (value) { componentFunctionCode.Dock = DockStyle.None; componentFunctionCode.Anchor = ((AnchorStyles)(((( System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); componentFunctionCode.Location = new Point(0, 0); componentFunctionCode.Size = new Size( splitContainer2.Panel1.Width, splitContainer2.Panel1.Height - 27); } else { componentFunctionCode.Anchor = AnchorStyles.None; componentFunctionCode.Dock = DockStyle.Fill; } } } #region XML Docs /// <summary> /// The available components to be used in this editor /// </summary> #endregion [Browsable(false)] public List<EffectComponent> AvailableComponents { set { mSuspendComponentSelectionChange = true; componentSelectionBox.DataSource = null; componentSelectionBox.DataSource = value; componentSelectionBox.SelectedIndex = -1; mSuspendComponentSelectionChange = false; } } #region XML Docs /// <summary> /// Whether or not shader selection is allowed (or just profile selection) /// Also sets exclusivity for vertex/pixel shader availability /// </summary> #endregion [Browsable(true),Category("Shader"),Description("Whether or not shader availability selection is allowed")] public bool AllowShaderSelection { get { return componentAvailabilityPanel.Visible; } set { componentAvailabilityPanel.Visible = value; shaderProfilePanel.Visible = !(componentAvailabilityPanel.Visible); if (!componentAvailabilityPanel.Visible) { // Make sure one shader profile is selected // (Vertex shader will be selected if both are the same) if (vertexShaderCheckbox.Checked == pixelShaderCheckbox.Checked) { vertexShaderCheckbox.Checked = true; pixelShaderCheckbox.Checked = false; } UpdateShaderProfiles(); } } } #region XML Docs /// <summary> /// Whether or not this is vertex-shader available /// (will also disable pixel shader if AllowShaderSelection is false) /// </summary> #endregion [Browsable(true), Category("Shader"), Description("Whether or not component is vertex shader available")] public bool IsVertexShader { get { return vertexShaderCheckbox.Checked; } set { vertexShaderCheckbox.Checked = value; if (!AllowShaderSelection) { pixelShaderCheckbox.Checked = false; UpdateShaderProfiles(); if (SemanticEnabled) UpdateSemantics(); } } } #region XML Docs /// <summary> /// Whether or not this is pixel-shader available /// (will also disable vertex shader if AllowShaderSelection is false) /// </summary> #endregion [Browsable(true), Category("Shader"), Description("Whether or not component is pixel shader available")] public bool IsPixelShader { get { return pixelShaderCheckbox.Checked; } set { pixelShaderCheckbox.Checked = value; if (!AllowShaderSelection) { vertexShaderCheckbox.Checked = false; UpdateShaderProfiles(); if (SemanticEnabled) UpdateSemantics(); } } } #region XML Docs /// <summary> /// Whether or not parameter semantics should be enabled /// </summary> #endregion [Browsable(true), Category("Shader"), Description("Whether or not parameters should have semantics")] public bool SemanticEnabled { get { return componentParameterInputs.SemanticEnabled; } set { componentParameterInputs.SemanticEnabled = value; componentParameterOutputs.SemanticEnabled = value; UpdateSemantics(); } } #endregion #region Constructor public ComponentEditor() { InitializeComponent(); // Populate Vertex and Pixel Shader profiles this.SuspendLayout(); mShaderProfileNames = Enum.GetNames(typeof(Microsoft.Xna.Framework.Graphics.ShaderProfile)); vertexShaderProfileSelector.Items.Clear(); pixelShaderProfileSelector.Items.Clear(); for (int i = 0; i < mShaderProfileNames.Length; i++) { if (mShaderProfileNames[i].Contains("VS")) { vertexShaderProfileSelector.Items.Add(mShaderProfileNames[i]); } if (mShaderProfileNames[i].Contains("PS")) { pixelShaderProfileSelector.Items.Add(mShaderProfileNames[i]); } } this.ResumeLayout(true); // Create a new component EffectComponent newComponent = new EffectComponent(); newComponent.Name = "NewComponent"; SetComponent(newComponent); } #endregion #region Methods #region XML Docs /// <summary> /// Updates available semantics /// </summary> #endregion private void UpdateSemantics() { // Only one list may be used this.SuspendLayout(); componentParameterInputs.Semantics = (vertexShaderCheckbox.Checked) ? Semantics.VertexShader.Input : Semantics.PixelShader.Input; componentParameterOutputs.Semantics = (vertexShaderCheckbox.Checked) ? Semantics.VertexShader.Output : Semantics.PixelShader.Output; this.ResumeLayout(true); } #region XML Docs /// <summary> /// Updates available shader profiles when shader type is exclusive /// </summary> #endregion private void UpdateShaderProfiles() { this.SuspendLayout(); shaderProfileSelector.Items.Clear(); for (int i = 0; i < mShaderProfileNames.Length; i++) { if ((vertexShaderCheckbox.Checked && mShaderProfileNames[i].Contains("VS")) || (pixelShaderCheckbox.Checked && mShaderProfileNames[i].Contains("PS"))) { shaderProfileSelector.Items.Add(mShaderProfileNames[i]); } } this.ResumeLayout(true); } #region XML Docs /// <summary> /// Sets a new component on this editor - and updates parameters /// </summary> /// <param name="component">The component to set</param> #endregion public void SetComponent(EffectComponent component) { if (Component != component) { Component = component; componentNameBox.Text = Component.Name; vertexShaderCheckbox.Checked = Component.AvailableToVertexShader; pixelShaderCheckbox.Checked = Component.AvailableToPixelShader; vertexShaderProfileSelector.Text = Component.MinimumVertexShaderProfile; pixelShaderProfileSelector.Text = Component.MinimumPixelShaderProfile; componentParameterInputs.Parameters = Component.Parameters; componentParameterOutputs.Parameters = Component.ReturnType; componentFunctionCode.Text = Component.Code; if (!AllowShaderSelection) { UpdateShaderProfiles(); } UpdateComponent(false); } } private void UpdateComponent() { UpdateComponent(true); } private void UpdateComponent(bool updateCallback) { componentFunctionStart.Text = Component.OutputStruct() + Environment.NewLine + Component.FunctionStart; componentFunctionEnd.Text = Component.FunctionEnd; if (updateCallback) OnComponentChanged(); } public void SaveNameEditPosition() { mNameSelectionParams.Push(componentNameBox.SelectionLength); mNameSelectionParams.Push(componentNameBox.SelectionStart); } public void RestoreNameEditPosition() { componentNameBox.SelectionStart = mNameSelectionParams.Pop(); componentNameBox.SelectionLength = mNameSelectionParams.Pop(); } #region Events private void componentNameBox_TextChanged(object sender, EventArgs e) { Component.Name = componentNameBox.Text; UpdateComponent(); } private void vertexShaderCheckbox_CheckedChanged(object sender, EventArgs e) { Component.AvailableToVertexShader = vertexShaderCheckbox.Checked; vertexShaderProfileSelector.Enabled = vertexShaderCheckbox.Checked; UpdateComponent(); } private void pixelShaderCheckbox_CheckedChanged(object sender, EventArgs e) { Component.AvailableToPixelShader = pixelShaderCheckbox.Checked; pixelShaderProfileSelector.Enabled = pixelShaderCheckbox.Checked; UpdateComponent(); } private void componentParameterInputs_ParametersChanged(object sender, EventArgs e) { Component.Parameters = componentParameterInputs.Parameters; UpdateComponent(); } private void componentParameterOutputs_ParametersChanged(object sender, EventArgs e) { Component.ReturnType = componentParameterOutputs.Parameters; UpdateComponent(); } private void vertexShaderProfileSelector_SelectedIndexChanged(object sender, EventArgs e) { Component.MinimumVertexShaderProfile = vertexShaderProfileSelector.Text; UpdateComponent(); } private void pixelShaderProfileSelector_SelectedIndexChanged(object sender, EventArgs e) { Component.MinimumPixelShaderProfile = pixelShaderProfileSelector.Text; UpdateComponent(); } private void componentFunctionCode_TextChanged(object sender, EventArgs e) { Component.Code = componentFunctionCode.Text; UpdateComponent(); } #endregion private void componentSelectionBox_SelectedIndexChanged(object sender, EventArgs e) { if (componentSelectionBox.SelectedIndex >= 0 && !mSuspendComponentSelectionChange) { // insert component text EffectComponent component = (EffectComponent)componentSelectionBox.SelectedItem; int start = componentFunctionCode.SelectionStart; string text = componentFunctionCode.Text; string functionCode = component.FunctionHelperString(); text = text.Insert(componentFunctionCode.SelectionStart, functionCode); componentFunctionCode.Text = text; componentFunctionCode.SelectionStart = start; componentFunctionCode.SelectionLength = functionCode.Length; // reset index to -1 componentSelectionBox.SelectedIndex = -1; } } #endregion } }
#if REAL_T_IS_DOUBLE using real_t = System.Double; #else using real_t = System.Single; #endif using System; using System.Collections.Generic; using System.Runtime.CompilerServices; // TODO: Add comments describing what this class does. It is not obvious. namespace Godot { public static partial class GD { public static object Bytes2Var(byte[] bytes, bool allowObjects = false) { return godot_icall_GD_bytes2var(bytes, allowObjects); } public static object Convert(object what, Variant.Type type) { return godot_icall_GD_convert(what, type); } public static real_t Db2Linear(real_t db) { return (real_t)Math.Exp(db * 0.11512925464970228420089957273422); } private static object[] GetPrintParams(object[] parameters) { if (parameters == null) { return new[] { "null" }; } return Array.ConvertAll(parameters, x => x?.ToString() ?? "null"); } public static int Hash(object var) { return godot_icall_GD_hash(var); } public static Object InstanceFromId(ulong instanceId) { return godot_icall_GD_instance_from_id(instanceId); } public static real_t Linear2Db(real_t linear) { return (real_t)(Math.Log(linear) * 8.6858896380650365530225783783321); } public static Resource Load(string path) { return ResourceLoader.Load(path); } public static T Load<T>(string path) where T : class { return ResourceLoader.Load<T>(path); } public static void PushError(string message) { godot_icall_GD_pusherror(message); } public static void PushWarning(string message) { godot_icall_GD_pushwarning(message); } public static void Print(params object[] what) { godot_icall_GD_print(GetPrintParams(what)); } public static void PrintStack() { Print(System.Environment.StackTrace); } public static void PrintErr(params object[] what) { godot_icall_GD_printerr(GetPrintParams(what)); } public static void PrintRaw(params object[] what) { godot_icall_GD_printraw(GetPrintParams(what)); } public static void PrintS(params object[] what) { godot_icall_GD_prints(GetPrintParams(what)); } public static void PrintT(params object[] what) { godot_icall_GD_printt(GetPrintParams(what)); } public static float Randf() { return godot_icall_GD_randf(); } public static uint Randi() { return godot_icall_GD_randi(); } public static void Randomize() { godot_icall_GD_randomize(); } public static double RandRange(double from, double to) { return godot_icall_GD_randf_range(from, to); } public static int RandRange(int from, int to) { return godot_icall_GD_randi_range(from, to); } public static uint RandFromSeed(ref ulong seed) { return godot_icall_GD_rand_seed(seed, out seed); } public static IEnumerable<int> Range(int end) { return Range(0, end, 1); } public static IEnumerable<int> Range(int start, int end) { return Range(start, end, 1); } public static IEnumerable<int> Range(int start, int end, int step) { if (end < start && step > 0) yield break; if (end > start && step < 0) yield break; if (step > 0) { for (int i = start; i < end; i += step) yield return i; } else { for (int i = start; i > end; i += step) yield return i; } } public static void Seed(ulong seed) { godot_icall_GD_seed(seed); } public static string Str(params object[] what) { return godot_icall_GD_str(what); } public static object Str2Var(string str) { return godot_icall_GD_str2var(str); } public static bool TypeExists(StringName type) { return godot_icall_GD_type_exists(StringName.GetPtr(type)); } public static byte[] Var2Bytes(object var, bool fullObjects = false) { return godot_icall_GD_var2bytes(var, fullObjects); } public static string Var2Str(object var) { return godot_icall_GD_var2str(var); } public static Variant.Type TypeToVariantType(Type type) { return godot_icall_TypeToVariantType(type); } [MethodImpl(MethodImplOptions.InternalCall)] internal extern static object godot_icall_GD_bytes2var(byte[] bytes, bool allowObjects); [MethodImpl(MethodImplOptions.InternalCall)] internal extern static object godot_icall_GD_convert(object what, Variant.Type type); [MethodImpl(MethodImplOptions.InternalCall)] internal extern static int godot_icall_GD_hash(object var); [MethodImpl(MethodImplOptions.InternalCall)] internal extern static Object godot_icall_GD_instance_from_id(ulong instanceId); [MethodImpl(MethodImplOptions.InternalCall)] internal extern static void godot_icall_GD_print(object[] what); [MethodImpl(MethodImplOptions.InternalCall)] internal extern static void godot_icall_GD_printerr(object[] what); [MethodImpl(MethodImplOptions.InternalCall)] internal extern static void godot_icall_GD_printraw(object[] what); [MethodImpl(MethodImplOptions.InternalCall)] internal extern static void godot_icall_GD_prints(object[] what); [MethodImpl(MethodImplOptions.InternalCall)] internal extern static void godot_icall_GD_printt(object[] what); [MethodImpl(MethodImplOptions.InternalCall)] internal extern static float godot_icall_GD_randf(); [MethodImpl(MethodImplOptions.InternalCall)] internal extern static uint godot_icall_GD_randi(); [MethodImpl(MethodImplOptions.InternalCall)] internal extern static void godot_icall_GD_randomize(); [MethodImpl(MethodImplOptions.InternalCall)] internal extern static double godot_icall_GD_randf_range(double from, double to); [MethodImpl(MethodImplOptions.InternalCall)] internal extern static int godot_icall_GD_randi_range(int from, int to); [MethodImpl(MethodImplOptions.InternalCall)] internal extern static uint godot_icall_GD_rand_seed(ulong seed, out ulong newSeed); [MethodImpl(MethodImplOptions.InternalCall)] internal extern static void godot_icall_GD_seed(ulong seed); [MethodImpl(MethodImplOptions.InternalCall)] internal extern static string godot_icall_GD_str(object[] what); [MethodImpl(MethodImplOptions.InternalCall)] internal extern static object godot_icall_GD_str2var(string str); [MethodImpl(MethodImplOptions.InternalCall)] internal extern static bool godot_icall_GD_type_exists(IntPtr type); [MethodImpl(MethodImplOptions.InternalCall)] internal extern static byte[] godot_icall_GD_var2bytes(object what, bool fullObjects); [MethodImpl(MethodImplOptions.InternalCall)] internal extern static string godot_icall_GD_var2str(object var); [MethodImpl(MethodImplOptions.InternalCall)] internal extern static void godot_icall_GD_pusherror(string type); [MethodImpl(MethodImplOptions.InternalCall)] internal extern static void godot_icall_GD_pushwarning(string type); [MethodImpl(MethodImplOptions.InternalCall)] private static extern Variant.Type godot_icall_TypeToVariantType(Type type); } }
using System; using System.Collections; using System.IO; using System.Threading; using SpyUO.Packets; namespace SpyUO { public delegate void OnPacket( TimePacket packet ); public class PacketRecorder : IDisposable { public class TypeArguments { private string m_Type; private string m_Arguments; public string Type { get { return m_Type; } set { m_Type = value; } } public string Arguments { get { return m_Arguments; } set { m_Arguments = value; } } } public static Hashtable ItemsTable = new Hashtable(); public static void InitItemsTable( string file ) { StreamReader reader = File.OpenText( file ); string line; while ( (line = reader.ReadLine()) != null ) { line = line.Trim(); if ( line == "" || line.StartsWith( "#" ) ) continue; string[] splt = line.Split( ' ', '\t' ); string[] ids = splt[0].Split( '-' ); int itemId = Int32.Parse( ids[0], System.Globalization.NumberStyles.HexNumber ); int itemIdEnd = ids.Length > 1 ? Int32.Parse( ids[1], System.Globalization.NumberStyles.HexNumber ) : itemId; TypeArguments typeArgu = new TypeArguments(); if ( splt.Length > 1 ) { string[] types = splt[1].Split( '-' ); typeArgu.Type = types[0]; if ( types.Length > 1 ) typeArgu.Arguments = types[1]; } for ( int id = itemId; id <= itemIdEnd; id++ ) { ItemsTable[id] = typeArgu; } } reader.Close(); } private ArrayList m_Packets; private Hashtable m_Items; private Hashtable m_Books; private Timer m_Timer; private ICounterDisplay m_CounterDisplay; public ArrayList Packets { get { return m_Packets; } } public Hashtable Items { get { return m_Items; } } public Hashtable Books { get { return m_Books; } } public Timer Timer { get { return m_Timer; } } public ICounterDisplay CounterDisplay { get { return m_CounterDisplay; } } public event OnPacket OnPacket; public PacketRecorder() : this( null ) { } public PacketRecorder( ICounterDisplay cDisplay ) { m_Packets = new ArrayList(); m_Items = new Hashtable(); m_Books = new Hashtable(); m_CounterDisplay = cDisplay; if ( cDisplay != null ) m_Timer = new Timer( new TimerCallback( TimerCallback ), null, TimeSpan.FromSeconds( 1.0 ), TimeSpan.FromSeconds( 1.0 ) ); } public void Dispose() { if ( m_Timer != null ) { ManualResetEvent disposed = new ManualResetEvent( false ); m_Timer.Dispose( disposed ); disposed.WaitOne(); } } public void PacketPumpDequeue( PacketPump packetPump ) { TimePacket packet = packetPump.Dequeue(); if ( packet != null ) { m_Packets.Add( packet ); UpdateTables( packet ); if ( OnPacket != null ) OnPacket( packet ); } } public void Clear() { m_Packets.Clear(); m_Items.Clear(); m_Books.Clear(); } private class ItemsBlock { private ushort m_ItemId; private uint m_Hue; private string m_Name; private ArrayList m_List; public ushort ItemId { get { return m_ItemId; } } public uint Hue { get { return m_Hue; } } public string Name { get { return m_Name; } } public ArrayList List { get { return m_List; } } public ItemsBlock( ushort itemId, uint hue, string name ) { m_ItemId = itemId; m_Hue = hue; m_Name = name; m_List = new ArrayList(); } public bool IsCompatible( WorldItem packet ) { return packet.ItemId == m_ItemId && packet.Hue == m_Hue; } public void Add( WorldItem packet ) { m_List.Add( packet ); } } private ItemsBlock FindBlock( ArrayList blocks, WorldItem packet ) { foreach ( ItemsBlock block in blocks ) { if ( block.IsCompatible( packet ) ) return block; } return null; } public void ExtractItems( StreamWriter writer ) { ArrayList blocks = new ArrayList(); foreach ( WorldItem item in m_Items.Values ) { ItemsBlock block = FindBlock( blocks, item ); if ( block == null ) { block = new ItemsBlock( item.ItemId, item.Hue, item.ItemIdName ); block.Add( item ); blocks.Add( block ); } else { block.Add( item ); } } foreach ( ItemsBlock block in blocks ) { TypeArguments typeArgu = ItemsTable[(int)block.ItemId] as TypeArguments; if ( typeArgu != null && typeArgu.Type == null ) continue; if ( typeArgu == null ) { typeArgu = new TypeArguments(); typeArgu.Type = "Static"; } string arguments = block.Hue != 0 ? string.Format( "Hue=0x{0:X}", block.Hue ) : ""; if ( arguments.Length > 0 && typeArgu.Arguments != null ) arguments += "; "; arguments += typeArgu.Arguments; writer.WriteLine( "# {0}", block.Name ); writer.WriteLine( "{0} 0x{1:X4}{2}", typeArgu.Type, block.ItemId, arguments.Length > 0 ? string.Format( " ({0})", arguments ) : "" ); foreach ( WorldItem packet in block.List ) writer.WriteLine( "{0} {1} {2}", packet.Position.X, packet.Position.Y, packet.Position.Z ); writer.WriteLine(); } } public void TimerCallback( object state ) { if ( m_CounterDisplay != null ) { DateTime lastTenSeconds = DateTime.Now - TimeSpan.FromSeconds( 10.0 ); int sentPackets = 0, sentPacketsSize = 0; int recvPackets = 0, recvPacketsSize = 0; for ( int i = m_Packets.Count - 1; i > 0; i-- ) { TimePacket tPacket = (TimePacket)m_Packets[i]; if ( tPacket.Time < lastTenSeconds ) break; Packet packet = tPacket.Packet; if ( packet.Send ) { sentPackets++; sentPacketsSize += packet.Data.Length; } else { recvPackets++; recvPacketsSize += packet.Data.Length; } } m_CounterDisplay.DisplayCounter( sentPackets/10, sentPacketsSize/10, recvPackets/10, recvPacketsSize/10 ); } } public class TimePacketBuilder { private bool m_Send; private ArrayList m_Data; private DateTime m_Time; public bool Send { get { return m_Send; } set { m_Send = value; } } public byte[] Data { get { return (byte[])m_Data.ToArray( typeof( byte ) ); } } public int DataLength { get { return m_Data.Count; } } public DateTime Time { get { return m_Time; } set { m_Time = value; } } public TimePacketBuilder() { m_Send = false; m_Data = new ArrayList(); m_Time = DateTime.MinValue; } public void AddData( byte[] data ) { m_Data.AddRange( data ); } public void AddData( byte data ) { m_Data.Add( data ); } public TimePacket ToTimePacket() { Packet packet = Packet.Create( Data, m_Send ); return new TimePacket( packet, m_Time ); } } public void Load( StreamReader reader ) { Clear(); string line; TimePacketBuilder packetBuilder = null; while ( (line = reader.ReadLine()) != null ) { try { line = line.Trim().ToLower(); if ( line == "" ) continue; if ( line.StartsWith( "packet -" ) ) { string[] bytes = line.Substring( 8 ).Trim().Split( ' ' ); foreach ( string s in bytes ) { byte b = Byte.Parse( s, System.Globalization.NumberStyles.HexNumber ); packetBuilder.AddData( b ); } continue; } if ( line.StartsWith( "time -" ) ) { string time = line.Substring( 6 ).Trim(); packetBuilder.Time = DateTime.Parse( time ); continue; } bool def; try { Int32.Parse( line.Substring( 0, 4 ), System.Globalization.NumberStyles.HexNumber ); def = true; } catch { def = false; } if ( def && line[4] == ':' ) { if ( line.StartsWith( "0000" ) && packetBuilder.DataLength != 0 ) { Add( packetBuilder ); packetBuilder = new TimePacketBuilder(); } string[] bytes = line.Substring( 5, 3*0x10 ).Trim().Split( ' ' ); foreach ( string s in bytes ) { byte b = Byte.Parse( s, System.Globalization.NumberStyles.HexNumber ); packetBuilder.AddData( b ); } continue; } if ( line.IndexOf( "send" ) >= 0 || line.IndexOf( "client -> server" ) >= 0 || line.IndexOf( "client->server" ) >= 0 ) { Add( packetBuilder ); packetBuilder = new TimePacketBuilder(); packetBuilder.Send = true; string[] tmp = line.Replace( "-", "" ).Split(); foreach ( string s in tmp ) { try { packetBuilder.Time = DateTime.Parse( s ); break; } catch { } } continue; } if ( line.IndexOf( "recv" ) >= 0 || line.IndexOf( "receive" ) >= 0 || line.IndexOf( "server -> client" ) >= 0 || line.IndexOf( "server->client" ) >= 0 ) { Add( packetBuilder ); packetBuilder = new TimePacketBuilder(); packetBuilder.Send = false; string[] tmp = line.Replace( "-", "" ).Split(); foreach ( string s in tmp ) { try { packetBuilder.Time = DateTime.Parse( s ); break; } catch { } } continue; } if ( line.IndexOf( "client" ) >= 0 ) { Add( packetBuilder ); packetBuilder = new TimePacketBuilder(); packetBuilder.Send = true; string[] tmp = line.Replace( "-", "" ).Split(); foreach ( string s in tmp ) { try { packetBuilder.Time = DateTime.Parse( s ); break; } catch { } } continue; } if ( line.IndexOf( "server" ) >= 0 ) { Add( packetBuilder ); packetBuilder = new TimePacketBuilder(); packetBuilder.Send = false; string[] tmp = line.Replace( "-", "" ).Split(); foreach ( string s in tmp ) { try { packetBuilder.Time = DateTime.Parse( s ); break; } catch { } } continue; } } catch { } } Add( packetBuilder ); } public void LoadBin( BinaryReader reader ) { int version = reader.ReadInt32(); Clear(); int count = reader.ReadInt32(); for ( int i = 0; i < count; i++ ) { bool send = reader.ReadBoolean(); DateTime time = new DateTime( reader.ReadInt64() ); int length = reader.ReadInt32(); byte[] data = reader.ReadBytes( length ); Packet packet = Packet.Create( data, send ); TimePacket tPacket = new TimePacket( packet, time ); m_Packets.Add( tPacket ); UpdateTables( tPacket ); } } private void UpdateTables( TimePacket packet ) { if ( packet.Packet is WorldItem ) { WorldItem item = (WorldItem)packet.Packet; m_Items[item.Serial] = packet.Packet; if ( m_Books[item.Serial] != null ) { ((BookInfo)m_Books[item.Serial]).Item = item; } } else if ( packet.Packet is BookHeader ) { BookHeader header = (BookHeader)packet.Packet; if ( m_Books[header.Serial] != null ) { BookInfo book = (BookInfo)m_Books[header.Serial]; book.Title = header.Title; book.Author = header.Author; book.Writable = header.Writable; if ( book.Lines.Length != header.PagesCount ) book.Lines = new string[header.PagesCount][]; } else { BookInfo book = new BookInfo( header.Serial, header.Title, header.Author, header.Writable, header.PagesCount ); if ( m_Items[book.Serial] != null ) book.Item = (WorldItem)m_Items[book.Serial]; m_Books[book.Serial] = book; } } else if ( packet.Packet is BookPageDetails ) { BookPageDetails details = (BookPageDetails)packet.Packet; if ( m_Books[details.Serial] != null ) { BookInfo book = (BookInfo)m_Books[details.Serial]; for ( int i = 0; i < details.Pages.Length; i++ ) { if ( !details.Pages[i].Request && details.Pages[i].Index - 1 < book.Lines.Length ) { book.Lines[details.Pages[i].Index - 1] = details.Pages[i].Lines; } } } } } public void Add( TimePacketBuilder packetBuilder ) { try { if ( packetBuilder != null && packetBuilder.DataLength > 0 ) { TimePacket packet = packetBuilder.ToTimePacket(); m_Packets.Add( packet ); UpdateTables( packet ); } } catch { } } public void WriteBooks() { using ( StreamWriter writer = File.CreateText( "Prova.cs" ) ) { foreach ( BookInfo book in m_Books.Values ) { book.WriteRunUOClass( writer ); } } } } }
/// This is the only script in this project. /// written in very rough procedural way, needs deep refactoring /// I've added comments to explain the algorithm using UnityEngine; using System.Collections; /// <summary> /// drag this on MainCamera game object in Unity3D scene /// </summary> public class LolController : MonoBehaviour { Vector3 value; // accumulator for accelerator emulation in unity editor WebCamTexture webcam; // to access photo camera of the phone GameObject container; // camera parent int rowSkip = 8; // when comparing two snapshots skip horizontal rows (columns more valuable) float turnpower = 64; // multiplier for yaw movement float sensorsens = 16; // offset multiplier. offset is applied to a previous frame to compare with the current frame bool showConfig = false; // used by gui to show menu with params bool showLog = false; // used by gui to show scheme of difference areas /// <summary> /// GUI to change params and display debug info (matrix of characters) /// </summary> void OnGUI () { GUILayout.BeginArea(new Rect(0, 0, Screen.width/2, Screen.height)); GUILayout.BeginVertical(); GUILayout.BeginHorizontal(); if (GUILayout.Button("Config")) showConfig = !showConfig; GUILayout.Label(" "); GUILayout.Label(" "); GUILayout.Label(" "); GUILayout.Label(" "); GUILayout.Label(" "); GUILayout.EndHorizontal(); if (showConfig) { GUILayout.Label(""); GUILayout.Label(""); GUILayout.Label(""); Slider(1, 300, ref turnpower, "Yaw Speed " + (int)turnpower); GUILayout.Label(""); Slider(2, 64, ref sensorsens, "Sensor Speed " + (int)sensorsens); GUILayout.Label(""); float rowskp = rowSkip; Slider(1, 64, ref rowskp, "Row Skip " + (int)rowskp); GUILayout.Label(""); rowSkip = (int) rowskp; if (rowSkip < 1) rowSkip = 1; if (GUILayout.Button(showLog?"Hide Log":"Show Log")) { showLog = !showLog; showConfig = false; } if (GUILayout.Button("Swap Eyes")) { var p1 = transform.GetChild(0).transform.localPosition; var p2 = transform.GetChild(1).transform.localPosition; var tmp = p1.x; p1.x = p2.x; p2.x = tmp; transform.GetChild(0).transform.localPosition = p1; transform.GetChild(1).transform.localPosition = p2; } } else if (showLog) { if (diffs != null) { for (int y = 0; y < diffs.GetLength(1); y++) { GUILayout.BeginHorizontal(); for (int x = 0; x < diffs.GetLength(0); x++) { if (x == bestX && y == bestY) GUILayout.Label("@" + "\t"); else GUILayout.Label(Did(diffs[x,y]/1000) + "\t"); } GUILayout.EndHorizontal(); } } } GUILayout.EndVertical(); GUILayout.EndArea(); } /// <summary> /// Returns character that should visually display difference /// </summary> string Did(long val) { if (val > 500) return "."; if (val > 250) return ","; if (val > 125) return "-"; if (val > 62) return "+"; if (val > 32) return "o"; return "O"; } /// <summary> /// GUI slider template method /// </summary> void Slider(float min, float max, ref float val, string desc) { GUILayout.BeginHorizontal(); GUILayout.Label(desc); val = GUILayout.HorizontalSlider(val, min, max); GUILayout.EndHorizontal(); } /// <summary> /// Gets monochrome value from RGB (30%/60%/10%) /// </summary> int[] ColorsToLumi(Color32[] colors) { var lumi = new int[colors.Length]; for (int i = 0; i < colors.Length; i++) { lumi[i] = colors[i].r * 3 + colors[i].g * 6 + colors[i].b; } return lumi; } /// <summary> /// This method rotates camera container around Y axis. /// Most complex part here. /// Takes snapshot from camera. /// Takes previous snapshot from memory. /// Shifts previous snapshot with different offsets by X and Y, computes general difference. /// Finds best offset that makes previous frame align with current frame. /// Judging from X offset creates rotation. Y offset is needed for better search of matching position. /// /// pseudo graphical explanation: /// /// current ----I-- /// previous ---I--- /// /// best offset: X+1 /// current ----I-- /// shft.prev. ---I--- /// /// /// IN OTHER WORDS WE MOVE PREVIOUS FRAME OVER CURRENT FRAME UNTIL WE FIND POSITION WHEN TWO FRAMES MATCH /// /// </summary> long[,] diffs; int bestX, bestY; int[] prevPixels; float smoothTP = 0; void DetectYaw() { var currentPixels = ColorsToLumi(webcam.GetPixels32()); if (prevPixels != null) { int ou = (int) (webcam.width / sensorsens); if (ou < 1) ou = 1; int[] xdm = new int[] { -3, -2, -1, 0, 1, 2, 3 }; int[] ydm = new int[] { -3, -2, -1, 0, 1, 2, 3 }; diffs = new long[xdm.Length, ydm.Length]; for (int x = 0; x < xdm.Length; x++) { for (int y = 0; y < ydm.Length; y++) { diffs[x,y] = PixelDifference(currentPixels, prevPixels, xdm[x] * ou, ydm[y] * ou, webcam.width, webcam.height); } } bestX = 0; bestY = 0; long less = long.MaxValue; for (int x = 0; x < xdm.Length; x++) { for (int y = 0; y < ydm.Length; y++) { if (diffs[x,y] < less) { less = diffs[x,y]; bestX = x; bestY = y; } } } float rot = xdm[bestX]; rot += Input.GetAxisRaw("Mouse X") * (Input.GetMouseButton(0) ? 10 : 0); if (less == 0) rot = 0; Smooth (ref smoothTP, 10, ref rot); container.transform.Rotate(Vector3.up, rot * Time.deltaTime * turnpower); } prevPixels = currentPixels; } /// <summary> /// abs(a-b) /// </summary> int absd(int a, int b) { if (a > b) return a - b; if (b > a) return b - a; return 0; } /// <summary> /// accumulates difference for each pixel of two arrays /// </summary> /// <param name="original">current frame</param> /// <param name="shifted">previous frame that will be shifted during comparison with the params below</param> /// <param name="xShift">shift in pixels</param> /// <param name="yShift"></param> /// <param name="width">dimensions (same for both images)</param> /// <param name="height"></param> /// <returns></returns> long PixelDifference(int[] original, int[] shifted, int xShift, int yShift, int width, int height) { long diff = 0; int y = 0; int c = original.Length; int p = 1; while(true) { for (int x = 0; x < width; x++) { int index = x + y * width; // index in array of pixels if (index >= c) return (1000*diff)/p; // if reached last pixel - return result int index2 = (x + xShift) + (y + yShift) * width; // shift index if (index2 >= c) return (1000*diff)/p; // if reached last pixel - return result if (x + xShift > width) break; // skip if shift created position after end of line if (x + xShift < 0) { x += -xShift; continue; } // skip few iterations if shift created position before start of line if (y + yShift > height) break; // same for y axis if (y + yShift < 0) { y += -yShift; continue; } if (index < 0 || index2 < 0) continue; // prevent out of range access // actual comparison and accumulation (in diff) var col1 = original[index]; var col2 = shifted[index2]; diff += absd(col1, col2); p++; // accumulations counter } y += rowSkip; // skipping rows } } /// <summary> /// creates game objects hierarchy with virtual camera, access phone's camera /// I use 32x32 pixel resolution (blured pixels from texture mip map), that's enough and not too heavy /// </summary> void Start () { container = new GameObject(); gameObject.transform.parent = container.transform; gameObject.transform.localPosition = Vector3.zero; container.transform.position = Vector3.up * 2; container.AddComponent<CharacterController>(); webcam = new WebCamTexture(WebCamTexture.devices[0].name, 32, 32); webcam.Play(); } /// <summary> /// Some strange smooth logic that changes two variables at time, can't remember why. /// </summary> void Smooth(ref float acc, float spd, ref float val) { acc = acc * Mathf.Clamp01(1 - Time.deltaTime * spd) + val * (Mathf.Clamp01(Time.deltaTime * spd)); val = acc; } float fspeed = 0; float smoothEAZ = 0, smoothEAX = 0; // controls the camera using accelerometer and DetectYaw algorithm void Update () { #if UNITY_EDITOR value += Vector3.up * Input.GetAxisRaw("Mouse Y") * (Input.GetMouseButton(0) ? 0 : 1); value += Vector3.forward * Input.GetAxisRaw("Mouse Y") * (Input.GetMouseButton(0) ? 1 : 0); value.Normalize(); #else value = Input.acceleration; value.Normalize(); #endif var ea = gameObject.transform.localEulerAngles; ea.z = value.x * -89; ea.x = value.z * -89; Smooth(ref smoothEAZ, 10, ref ea.z); Smooth(ref smoothEAX, 15, ref ea.x); if (value.z < -0.33f) fspeed = 2; if (value.z > 0.33f) fspeed = 0; if (value.z > 0.5f) fspeed = -2; if (fspeed > 0) { fspeed -= Time.deltaTime / 10; if (fspeed < 0) fspeed = 0; } else if (fspeed > 0) { fspeed += Time.deltaTime / 10; if (fspeed > 0) fspeed = 0; } container.GetComponent<CharacterController>(). SimpleMove(container.transform.forward * fspeed * 15 * Time.deltaTime); gameObject.transform.localEulerAngles = ea; DetectYaw(); } }
using CakeMail.RestClient.Resources; using CakeMail.RestClient.Utilities; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using Pathoschild.Http.Client; using Pathoschild.Http.Client.Extensibility; using System; using System.Net; using System.Net.Http; using System.Reflection; namespace CakeMail.RestClient { /// <summary> /// Core class for using the CakeMail Api. /// </summary> public class CakeMailRestClient : ICakeMailRestClient { #region FIELDS private const string CAKEMAIL_BASE_URI = "https://api.wbsrvc.com/"; private static string _version; private readonly bool _mustDisposeHttpClient; private readonly CakeMailClientOptions _options; private readonly ILogger _logger; private HttpClient _httpClient; private Pathoschild.Http.Client.IClient _fluentClient; #endregion #region PROPERTIES /// <summary> /// Gets the Version. /// </summary> /// <value> /// The version. /// </value> public static string Version { get { if (string.IsNullOrEmpty(_version)) { _version = typeof(CakeMailRestClient).GetTypeInfo().Assembly.GetName().Version.ToString(3); #if DEBUG _version = "DEBUG"; #endif } return _version; } } /// <summary> /// Gets the API key provided by CakeMail. /// </summary> public string ApiKey { get; private set; } /// <summary> /// Gets the URL where all API requests are sent. /// </summary> public Uri BaseUrl { get; private set; } /// <summary> /// Gets the <see cref="Campaigns">Campaigns</see> resource. /// </summary> public ICampaigns Campaigns { get; private set; } /// <summary> /// Gets the <see cref="Clients">Clients</see> resource. /// </summary> public IClients Clients { get; private set; } /// <summary> /// Gets the <see cref="Countries">Countries</see> resource. /// </summary> public ICountries Countries { get; private set; } /// <summary> /// Gets the <see cref="Permissions">Permissions</see> resource. /// </summary> public IPermissions Permissions { get; private set; } /// <summary> /// Gets the <see cref="Lists">Lists</see> resource. /// </summary> public ILists Lists { get; private set; } /// <summary> /// Gets the <see cref="Timezones">Timezones</see> resource. /// </summary> public ITimezones Timezones { get; private set; } /// <summary> /// Gets the <see cref="Mailings">Mailings</see> resource. /// </summary> public IMailings Mailings { get; private set; } /// <summary> /// Gets the <see cref="Relays">Relays</see> resource. /// </summary> public IRelays Relays { get; private set; } /// <summary> /// Gets the <see cref="Segments">Segments</see> resource. /// </summary> public ISegments Segments { get; private set; } /// <summary> /// Gets the <see cref="Users">Users</see> resource. /// </summary> public IUsers Users { get; private set; } /// <summary> /// Gets the <see cref="SuppressionLists">SuppressionLists</see> resource. /// </summary> public ISuppressionLists SuppressionLists { get; private set; } /// <summary> /// Gets the <see cref="Templates">Templates</see> resource. /// </summary> public ITemplates Templates { get; private set; } /// <summary> /// Gets the <see cref="Triggers">Triggers</see> resource. /// </summary> public ITriggers Triggers { get; private set; } #endregion #region CONSTRUCTORS AND DESTRUCTORS /// <summary> /// Initializes a new instance of the <see cref="CakeMailRestClient"/> class. /// </summary> /// <param name="apiKey">The API Key received from CakeMail.</param> /// <param name="options">Options for the CakeMail client.</param> /// <param name="logger">Logger.</param> public CakeMailRestClient(string apiKey, CakeMailClientOptions options = null, ILogger logger = null) : this(apiKey, (HttpClient)null, options, logger) { } /// <summary> /// Initializes a new instance of the <see cref="CakeMailRestClient"/> class. /// </summary> /// <param name="apiKey">The API Key received from CakeMail.</param> /// <param name="proxy">Allows you to specify a proxy.</param> /// <param name="options">Options for the CakeMail client.</param> /// <param name="logger">Logger.</param> public CakeMailRestClient(string apiKey, IWebProxy proxy, CakeMailClientOptions options = null, ILogger logger = null) : this(apiKey, new HttpClient(new HttpClientHandler { Proxy = proxy, UseProxy = proxy != null }), options, logger) { } /// <summary> /// Initializes a new instance of the <see cref="CakeMailRestClient"/> class. /// </summary> /// <param name="apiKey">The API Key received from CakeMail.</param> /// <param name="handler">The HTTP handler stack to use for sending requests.</param> /// <param name="options">Options for the CakeMail client.</param> /// <param name="logger">Logger.</param> public CakeMailRestClient(string apiKey, HttpMessageHandler handler, CakeMailClientOptions options = null, ILogger logger = null) : this(apiKey, new HttpClient(handler), true, options, logger) { } /// <summary> /// Initializes a new instance of the <see cref="CakeMailRestClient"/> class. /// </summary> /// <param name="apiKey">The API Key received from CakeMail.</param> /// <param name="httpClient">Allows you to inject your own HttpClient. This is useful, for example, to setup the HtppClient with a proxy.</param> /// <param name="options">Options for the CakeMail client.</param> /// <param name="logger">Logger.</param> public CakeMailRestClient(string apiKey, HttpClient httpClient, CakeMailClientOptions options = null, ILogger logger = null) : this(apiKey, httpClient, false, options, logger) { } private CakeMailRestClient(string apiKey, HttpClient httpClient, bool disposeClient, CakeMailClientOptions options, ILogger logger = null) { _mustDisposeHttpClient = disposeClient; _httpClient = httpClient; _options = options ?? GetDefaultOptions(); _logger = logger ?? NullLogger.Instance; ApiKey = apiKey; BaseUrl = new Uri(CAKEMAIL_BASE_URI); _fluentClient = new FluentClient(this.BaseUrl, httpClient) .SetUserAgent($"CakeMail .NET REST Client/{Version} (+https://github.com/Jericho/CakeMail.RestClient)"); _fluentClient.Filters.Remove<DefaultErrorFilter>(); // Order is important: DiagnosticHandler must be first. _fluentClient.Filters.Add(new DiagnosticHandler(_options.LogLevelSuccessfulCalls, _options.LogLevelFailedCalls)); _fluentClient.Filters.Add(new CakeMailErrorHandler()); _fluentClient.BaseClient.DefaultRequestHeaders.Add("apikey", this.ApiKey); Campaigns = new Campaigns(_fluentClient); Clients = new Clients(_fluentClient); Countries = new Countries(_fluentClient); Permissions = new Permissions(_fluentClient); Lists = new Lists(_fluentClient); Timezones = new Timezones(_fluentClient); Mailings = new Mailings(_fluentClient); Relays = new Relays(_fluentClient); Segments = new Segments(_fluentClient); Users = new Users(_fluentClient); SuppressionLists = new SuppressionLists(_fluentClient); Templates = new Templates(_fluentClient); Triggers = new Triggers(_fluentClient); } /// <summary> /// Finalizes an instance of the <see cref="CakeMailRestClient"/> class. /// </summary> ~CakeMailRestClient() { // The object went out of scope and finalized is called. // Call 'Dispose' to release unmanaged resources // Managed resources will be released when GC runs the next time. Dispose(false); } #endregion #region PUBLIC METHODS /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { // Call 'Dispose' to release resources Dispose(true); // Tell the GC that we have done the cleanup and there is nothing left for the Finalizer to do GC.SuppressFinalize(this); } /// <summary> /// Releases unmanaged and - optionally - managed resources. /// </summary> /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> protected virtual void Dispose(bool disposing) { if (disposing) { ReleaseManagedResources(); } else { // The object went out of scope and the Finalizer has been called. // The GC will take care of releasing managed resources, therefore there is nothing to do here. } ReleaseUnmanagedResources(); } #endregion #region PRIVATE METHODS private void ReleaseManagedResources() { if (_fluentClient != null) { _fluentClient.Dispose(); _fluentClient = null; } if (_httpClient != null && _mustDisposeHttpClient) { _httpClient.Dispose(); _httpClient = null; } } private void ReleaseUnmanagedResources() { // We do not hold references to unmanaged resources } private CakeMailClientOptions GetDefaultOptions() { return new CakeMailClientOptions() { LogLevelSuccessfulCalls = LogLevel.Debug, LogLevelFailedCalls = LogLevel.Error }; } #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. //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // namespace System.Reflection.Emit { using System; using IList = System.Collections.IList; using System.Collections.Generic; using System.Reflection; using System.Security; using System.Diagnostics; using CultureInfo = System.Globalization.CultureInfo; using IResourceWriter = System.Resources.IResourceWriter; using System.IO; using System.Runtime.Versioning; using System.Diagnostics.SymbolStore; using System.Diagnostics.Contracts; // This is a package private class. This class hold all of the managed // data member for AssemblyBuilder. Note that what ever data members added to // this class cannot be accessed from the EE. internal class AssemblyBuilderData { internal AssemblyBuilderData( InternalAssemblyBuilder assembly, String strAssemblyName, AssemblyBuilderAccess access, String dir) { m_assembly = assembly; m_strAssemblyName = strAssemblyName; m_access = access; m_moduleBuilderList = new List<ModuleBuilder>(); m_resWriterList = new List<ResWriterData>(); //Init to null/0 done for you by the CLR. FXCop has spoken if (dir == null && access != AssemblyBuilderAccess.Run) m_strDir = Environment.CurrentDirectory; else m_strDir = dir; m_peFileKind = PEFileKinds.Dll; } // Helper to add a dynamic module into the tracking list internal void AddModule(ModuleBuilder dynModule) { m_moduleBuilderList.Add(dynModule); } // Helper to add a resource information into the tracking list internal void AddResWriter(ResWriterData resData) { m_resWriterList.Add(resData); } // Helper to track CAs to persist onto disk internal void AddCustomAttribute(CustomAttributeBuilder customBuilder) { // make sure we have room for this CA if (m_CABuilders == null) { m_CABuilders = new CustomAttributeBuilder[m_iInitialSize]; } if (m_iCABuilder == m_CABuilders.Length) { CustomAttributeBuilder[] tempCABuilders = new CustomAttributeBuilder[m_iCABuilder * 2]; Array.Copy(m_CABuilders, 0, tempCABuilders, 0, m_iCABuilder); m_CABuilders = tempCABuilders; } m_CABuilders[m_iCABuilder] = customBuilder; m_iCABuilder++; } // Helper to track CAs to persist onto disk internal void AddCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) { // make sure we have room for this CA if (m_CABytes == null) { m_CABytes = new byte[m_iInitialSize][]; m_CACons = new ConstructorInfo[m_iInitialSize]; } if (m_iCAs == m_CABytes.Length) { // enlarge the arrays byte[][] temp = new byte[m_iCAs * 2][]; ConstructorInfo[] tempCon = new ConstructorInfo[m_iCAs * 2]; for (int i=0; i < m_iCAs; i++) { temp[i] = m_CABytes[i]; tempCon[i] = m_CACons[i]; } m_CABytes = temp; m_CACons = tempCon; } byte[] attrs = new byte[binaryAttribute.Length]; Buffer.BlockCopy(binaryAttribute, 0, attrs, 0, binaryAttribute.Length); m_CABytes[m_iCAs] = attrs; m_CACons[m_iCAs] = con; m_iCAs++; } // Helper to calculate unmanaged version info from Assembly's custom attributes. // If DefineUnmanagedVersionInfo is called, the parameter provided will override // the CA's value. // internal void FillUnmanagedVersionInfo() { // Get the lcid set on the assembly name as default if available // Note that if LCID is not avaible from neither AssemblyName or AssemblyCultureAttribute, // it is default to -1 which is treated as language neutral. // CultureInfo locale = m_assembly.GetLocale(); #if FEATURE_USE_LCID if (locale != null) m_nativeVersion.m_lcid = locale.LCID; #endif for (int i = 0; i < m_iCABuilder; i++) { // check for known attributes Type conType = m_CABuilders[i].m_con.DeclaringType; if (m_CABuilders[i].m_constructorArgs.Length == 0 || m_CABuilders[i].m_constructorArgs[0] == null) continue; if (conType.Equals(typeof(System.Reflection.AssemblyCopyrightAttribute))) { // assert that we should only have one argument for this CA and the type should // be a string. // if (m_CABuilders[i].m_constructorArgs.Length != 1) { throw new ArgumentException(Environment.GetResourceString( "Argument_BadCAForUnmngRSC", m_CABuilders[i].m_con.ReflectedType.Name)); } if (m_OverrideUnmanagedVersionInfo == false) { m_nativeVersion.m_strCopyright = m_CABuilders[i].m_constructorArgs[0].ToString(); } } else if (conType.Equals(typeof(System.Reflection.AssemblyTrademarkAttribute))) { // assert that we should only have one argument for this CA and the type should // be a string. // if (m_CABuilders[i].m_constructorArgs.Length != 1) { throw new ArgumentException(Environment.GetResourceString( "Argument_BadCAForUnmngRSC", m_CABuilders[i].m_con.ReflectedType.Name)); } if (m_OverrideUnmanagedVersionInfo == false) { m_nativeVersion.m_strTrademark = m_CABuilders[i].m_constructorArgs[0].ToString(); } } else if (conType.Equals(typeof(System.Reflection.AssemblyProductAttribute))) { if (m_OverrideUnmanagedVersionInfo == false) { // assert that we should only have one argument for this CA and the type should // be a string. // m_nativeVersion.m_strProduct = m_CABuilders[i].m_constructorArgs[0].ToString(); } } else if (conType.Equals(typeof(System.Reflection.AssemblyCompanyAttribute))) { if (m_CABuilders[i].m_constructorArgs.Length != 1) { throw new ArgumentException(Environment.GetResourceString( "Argument_BadCAForUnmngRSC", m_CABuilders[i].m_con.ReflectedType.Name)); } if (m_OverrideUnmanagedVersionInfo == false) { // assert that we should only have one argument for this CA and the type should // be a string. // m_nativeVersion.m_strCompany = m_CABuilders[i].m_constructorArgs[0].ToString(); } } else if (conType.Equals(typeof(System.Reflection.AssemblyDescriptionAttribute))) { if (m_CABuilders[i].m_constructorArgs.Length != 1) { throw new ArgumentException(Environment.GetResourceString( "Argument_BadCAForUnmngRSC", m_CABuilders[i].m_con.ReflectedType.Name)); } m_nativeVersion.m_strDescription = m_CABuilders[i].m_constructorArgs[0].ToString(); } else if (conType.Equals(typeof(System.Reflection.AssemblyTitleAttribute))) { if (m_CABuilders[i].m_constructorArgs.Length != 1) { throw new ArgumentException(Environment.GetResourceString( "Argument_BadCAForUnmngRSC", m_CABuilders[i].m_con.ReflectedType.Name)); } m_nativeVersion.m_strTitle = m_CABuilders[i].m_constructorArgs[0].ToString(); } else if (conType.Equals(typeof(System.Reflection.AssemblyInformationalVersionAttribute))) { if (m_CABuilders[i].m_constructorArgs.Length != 1) { throw new ArgumentException(Environment.GetResourceString( "Argument_BadCAForUnmngRSC", m_CABuilders[i].m_con.ReflectedType.Name)); } if (m_OverrideUnmanagedVersionInfo == false) { m_nativeVersion.m_strProductVersion = m_CABuilders[i].m_constructorArgs[0].ToString(); } } else if (conType.Equals(typeof(System.Reflection.AssemblyCultureAttribute))) { // retrieve the LCID if (m_CABuilders[i].m_constructorArgs.Length != 1) { throw new ArgumentException(Environment.GetResourceString( "Argument_BadCAForUnmngRSC", m_CABuilders[i].m_con.ReflectedType.Name)); } // CultureInfo attribute overrides the lcid from AssemblyName. CultureInfo culture = new CultureInfo(m_CABuilders[i].m_constructorArgs[0].ToString()); #if FEATURE_USE_LCID m_nativeVersion.m_lcid = culture.LCID; #endif } else if (conType.Equals(typeof(System.Reflection.AssemblyFileVersionAttribute))) { if (m_CABuilders[i].m_constructorArgs.Length != 1) { throw new ArgumentException(Environment.GetResourceString( "Argument_BadCAForUnmngRSC", m_CABuilders[i].m_con.ReflectedType.Name)); } if (m_OverrideUnmanagedVersionInfo == false) { m_nativeVersion.m_strFileVersion = m_CABuilders[i].m_constructorArgs[0].ToString(); } } } } // Helper to ensure the resource name is unique underneath assemblyBuilder internal void CheckResNameConflict(String strNewResName) { int size = m_resWriterList.Count; int i; for (i = 0; i < size; i++) { ResWriterData resWriter = m_resWriterList[i]; if (resWriter.m_strName.Equals(strNewResName)) { // Cannot have two resources with the same name throw new ArgumentException(Environment.GetResourceString("Argument_DuplicateResourceName")); } } } // Helper to ensure the module name is unique underneath assemblyBuilder internal void CheckNameConflict(String strNewModuleName) { int size = m_moduleBuilderList.Count; int i; for (i = 0; i < size; i++) { ModuleBuilder moduleBuilder = m_moduleBuilderList[i]; if (moduleBuilder.m_moduleData.m_strModuleName.Equals(strNewModuleName)) { // Cannot have two dynamic modules with the same name throw new ArgumentException(Environment.GetResourceString("Argument_DuplicateModuleName")); } } // Right now dynamic modules can only be added to dynamic assemblies in which // all modules are dynamic. Otherwise we would also need to check the static modules // with this: // if (m_assembly.GetModule(strNewModuleName) != null) // { // // Cannot have two dynamic modules with the same name // throw new ArgumentException(Environment.GetResourceString("Argument_DuplicateModuleName")); // } } // Helper to ensure the type name is unique underneath assemblyBuilder internal void CheckTypeNameConflict(String strTypeName, TypeBuilder enclosingType) { BCLDebug.Log("DYNIL","## DYNIL LOGGING: AssemblyBuilderData.CheckTypeNameConflict( " + strTypeName + " )"); for (int i = 0; i < m_moduleBuilderList.Count; i++) { ModuleBuilder curModule = m_moduleBuilderList[i]; curModule.CheckTypeNameConflict(strTypeName, enclosingType); } // Right now dynamic modules can only be added to dynamic assemblies in which // all modules are dynamic. Otherwise we would also need to check loaded types. // We only need to make this test for non-nested types since any // duplicates in nested types will be caught at the top level. // if (enclosingType == null && m_assembly.GetType(strTypeName, false, false) != null) // { // // Cannot have two types with the same name // throw new ArgumentException(Environment.GetResourceString("Argument_DuplicateTypeName")); // } } // Helper to ensure the file name is unique underneath assemblyBuilder. This includes // modules and resources. // // // internal void CheckFileNameConflict(String strFileName) { int size = m_moduleBuilderList.Count; int i; for (i = 0; i < size; i++) { ModuleBuilder moduleBuilder = m_moduleBuilderList[i]; if (moduleBuilder.m_moduleData.m_strFileName != null) { if (String.Compare(moduleBuilder.m_moduleData.m_strFileName, strFileName, StringComparison.OrdinalIgnoreCase) == 0) { // Cannot have two dynamic module with the same name throw new ArgumentException(Environment.GetResourceString("Argument_DuplicatedFileName")); } } } size = m_resWriterList.Count; for (i = 0; i < size; i++) { ResWriterData resWriter = m_resWriterList[i]; if (resWriter.m_strFileName != null) { if (String.Compare(resWriter.m_strFileName, strFileName, StringComparison.OrdinalIgnoreCase) == 0) { // Cannot have two dynamic module with the same name throw new ArgumentException(Environment.GetResourceString("Argument_DuplicatedFileName")); } } } } // Helper to look up which module that assembly is supposed to be stored at // // // internal ModuleBuilder FindModuleWithFileName(String strFileName) { int size = m_moduleBuilderList.Count; int i; for (i = 0; i < size; i++) { ModuleBuilder moduleBuilder = m_moduleBuilderList[i]; if (moduleBuilder.m_moduleData.m_strFileName != null) { if (String.Compare(moduleBuilder.m_moduleData.m_strFileName, strFileName, StringComparison.OrdinalIgnoreCase) == 0) { return moduleBuilder; } } } return null; } // Helper to look up module by name. // // // internal ModuleBuilder FindModuleWithName(String strName) { int size = m_moduleBuilderList.Count; int i; for (i = 0; i < size; i++) { ModuleBuilder moduleBuilder = m_moduleBuilderList[i]; if (moduleBuilder.m_moduleData.m_strModuleName != null) { if (String.Compare(moduleBuilder.m_moduleData.m_strModuleName, strName, StringComparison.OrdinalIgnoreCase) == 0) return moduleBuilder; } } return null; } // add type to public COMType tracking list internal void AddPublicComType(Type type) { BCLDebug.Log("DYNIL","## DYNIL LOGGING: AssemblyBuilderData.AddPublicComType( " + type.FullName + " )"); if (m_isSaved == true) { // assembly has been saved before! throw new InvalidOperationException(Environment.GetResourceString( "InvalidOperation_CannotAlterAssembly")); } EnsurePublicComTypeCapacity(); m_publicComTypeList[m_iPublicComTypeCount] = type; m_iPublicComTypeCount++; } // add security permission requests internal void AddPermissionRequests( PermissionSet required, PermissionSet optional, PermissionSet refused) { BCLDebug.Log("DYNIL","## DYNIL LOGGING: AssemblyBuilderData.AddPermissionRequests"); if (m_isSaved == true) { // assembly has been saved before! throw new InvalidOperationException(Environment.GetResourceString( "InvalidOperation_CannotAlterAssembly")); } m_RequiredPset = required; m_OptionalPset = optional; m_RefusedPset = refused; } private void EnsurePublicComTypeCapacity() { if (m_publicComTypeList == null) { m_publicComTypeList = new Type[m_iInitialSize]; } if (m_iPublicComTypeCount == m_publicComTypeList.Length) { Type[] tempTypeList = new Type[m_iPublicComTypeCount * 2]; Array.Copy(m_publicComTypeList, 0, tempTypeList, 0, m_iPublicComTypeCount); m_publicComTypeList = tempTypeList; } } internal List<ModuleBuilder> m_moduleBuilderList; internal List<ResWriterData> m_resWriterList; internal String m_strAssemblyName; internal AssemblyBuilderAccess m_access; private InternalAssemblyBuilder m_assembly; internal Type[] m_publicComTypeList; internal int m_iPublicComTypeCount; internal bool m_isSaved; internal const int m_iInitialSize = 16; internal String m_strDir; // hard coding the assembly def token internal const int m_tkAssembly = 0x20000001; // Security permission requests internal PermissionSet m_RequiredPset; internal PermissionSet m_OptionalPset; internal PermissionSet m_RefusedPset; // tracking AssemblyDef's CAs for persistence to disk internal CustomAttributeBuilder[] m_CABuilders; internal int m_iCABuilder; internal byte[][] m_CABytes; internal ConstructorInfo[] m_CACons; internal int m_iCAs; internal PEFileKinds m_peFileKind; // assembly file kind internal MethodInfo m_entryPointMethod; internal Assembly m_ISymWrapperAssembly; // For unmanaged resources internal String m_strResourceFileName; internal byte[] m_resourceBytes; internal NativeVersionInfo m_nativeVersion; internal bool m_hasUnmanagedVersionInfo; internal bool m_OverrideUnmanagedVersionInfo; } /********************************************** * * Internal structure to track the list of ResourceWriter for * AssemblyBuilder & ModuleBuilder. * **********************************************/ internal class ResWriterData { internal ResWriterData( IResourceWriter resWriter, Stream memoryStream, String strName, String strFileName, String strFullFileName, ResourceAttributes attribute) { m_resWriter = resWriter; m_memoryStream = memoryStream; m_strName = strName; m_strFileName = strFileName; m_strFullFileName = strFullFileName; m_nextResWriter = null; m_attribute = attribute; } internal IResourceWriter m_resWriter; internal String m_strName; internal String m_strFileName; internal String m_strFullFileName; internal Stream m_memoryStream; internal ResWriterData m_nextResWriter; internal ResourceAttributes m_attribute; } internal class NativeVersionInfo { internal NativeVersionInfo() { m_strDescription = null; m_strCompany = null; m_strTitle = null; m_strCopyright = null; m_strTrademark = null; m_strProduct = null; m_strProductVersion = null; m_strFileVersion = null; m_lcid = -1; } internal String m_strDescription; internal String m_strCompany; internal String m_strTitle; internal String m_strCopyright; internal String m_strTrademark; internal String m_strProduct; internal String m_strProductVersion; internal String m_strFileVersion; internal int m_lcid; } }
/* Project Orleans Cloud Service SDK ver. 1.0 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. */ using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Globalization; using System.Linq; using Orleans.Runtime.Configuration; namespace Orleans.Runtime { /// <summary> /// Identifies activations that have been idle long enough to be deactivated. /// </summary> internal class ActivationCollector : IActivationCollector { private readonly TimeSpan quantum; private readonly TimeSpan shortestAgeLimit; private readonly ConcurrentDictionary<DateTime, Bucket> buckets; private readonly object nextTicketLock; private DateTime nextTicket; private static readonly List<ActivationData> nothing = new List<ActivationData> { Capacity = 0 }; private readonly TraceLogger logger; public ActivationCollector(ClusterConfiguration config) { if (TimeSpan.Zero == config.Globals.CollectionQuantum) { throw new ArgumentException("Globals.CollectionQuantum cannot be zero.", "config"); } quantum = config.Globals.CollectionQuantum; shortestAgeLimit = config.Globals.Application.ShortestCollectionAgeLimit; buckets = new ConcurrentDictionary<DateTime, Bucket>(); nextTicket = MakeTicketFromDateTime(DateTime.UtcNow); nextTicketLock = new object(); logger = TraceLogger.GetLogger("ActivationCollector", TraceLogger.LoggerType.Runtime); } public TimeSpan Quantum { get { return quantum; } } private int ApproximateCount { get { int sum = 0; foreach (var bucket in buckets.Values) { sum += bucket.ApproximateCount; } return sum; } } // Return the number of activations that were used (touched) in the last recencyPeriod. public int GetNumRecentlyUsed(TimeSpan recencyPeriod) { if (TimeSpan.Zero == shortestAgeLimit) { // Collection has been disabled for some types. return ApproximateCount; } var now = DateTime.UtcNow; int sum = 0; foreach (var bucket in buckets) { // Ticket is the date time when this bucket should be collected (last touched time plus age limit) // For now we take the shortest age limit as an approximation of the per-type age limit. DateTime ticket = bucket.Key; var timeTillCollection = ticket - now; var timeSinceLastUsed = shortestAgeLimit - timeTillCollection; if (timeSinceLastUsed <= recencyPeriod) { sum += bucket.Value.ApproximateCount; } } return sum; } public void ScheduleCollection(ActivationData item) { lock (item) { if (item.IsExemptFromCollection) { return; } TimeSpan timeout = item.CollectionAgeLimit; if (TimeSpan.Zero == timeout) { // either the CollectionAgeLimit hasn't been initialized (will be rectified later) or it's been disabled. return; } DateTime ticket = MakeTicketFromTimeSpan(timeout); if (default(DateTime) != item.CollectionTicket) { throw new InvalidOperationException("Call CancelCollection before calling ScheduleCollection."); } Add(item, ticket); } } public bool TryCancelCollection(ActivationData item) { if (item.IsExemptFromCollection) return false; lock (item) { DateTime ticket = item.CollectionTicket; if (default(DateTime) == ticket) return false; if (IsExpired(ticket)) return false; // first, we attempt to remove the ticket. Bucket bucket; if (!buckets.TryGetValue(ticket, out bucket) || !bucket.TryRemove(item)) return false; } return true; } public bool TryRescheduleCollection(ActivationData item) { if (item.IsExemptFromCollection) return false; lock (item) { if (TryRescheduleCollection_Impl(item, item.CollectionAgeLimit)) return true; item.ResetCollectionTicket(); return false; } } private bool TryRescheduleCollection_Impl(ActivationData item, TimeSpan timeout) { // note: we expect the activation lock to be held. if (default(DateTime) == item.CollectionTicket) return false; ThrowIfTicketIsInvalid(item.CollectionTicket); if (IsExpired(item.CollectionTicket)) return false; DateTime oldTicket = item.CollectionTicket; DateTime newTicket = MakeTicketFromTimeSpan(timeout); // if the ticket value doesn't change, then the source and destination bucket are the same and there's nothing to do. if (newTicket.Equals(oldTicket)) return true; Bucket bucket; if (!buckets.TryGetValue(oldTicket, out bucket) || !bucket.TryRemove(item)) { // fail: item is not associated with currentKey. return false; } // it shouldn't be possible for Add to throw an exception here, as only one concurrent competitor should be able to reach to this point in the method. item.ResetCollectionTicket(); Add(item, newTicket); return true; } private bool DequeueQuantum(out IEnumerable<ActivationData> items, DateTime now) { DateTime key; lock (nextTicketLock) { if (nextTicket > now) { items = null; return false; } key = nextTicket; nextTicket += quantum; } Bucket bucket; if (!buckets.TryRemove(key, out bucket)) { items = nothing; return true; } items = bucket.CancelAll(); return true; } public override string ToString() { var now = DateTime.UtcNow; return string.Format("<#Activations={0}, #Buckets={1}, buckets={2}>", ApproximateCount, buckets.Count, Utils.EnumerableToString( buckets.Values.OrderBy(bucket => bucket.Key), bucket => (Utils.TimeSpanToString(bucket.Key - now) + "->" + bucket.ApproximateCount + " items").ToString(CultureInfo.InvariantCulture))); } /// <summary> /// Scans for activations that are due for collection. /// </summary> /// <returns>A list of activations that are due for collection.</returns> public List<ActivationData> ScanStale() { var now = DateTime.UtcNow; List<ActivationData> result = null; IEnumerable<ActivationData> activations; while (DequeueQuantum(out activations, now)) { // at this point, all tickets associated with activations are cancelled and any attempts to reschedule will fail silently. if the activation is to be reactivated, it's our job to clear the activation's copy of the ticket. foreach (var activation in activations) { lock (activation) { activation.ResetCollectionTicket(); if (activation.State != ActivationState.Valid) { // Do nothing: don't collect, don't reschedule. // The activation can't be in Created or Activating, since we only ScheduleCollection after successfull activation. // If the activation is already in Deactivating or Invalid state, its already being collected or was collected // (both mean a bug, this activation should not be in the collector) // So in any state except for Valid we should just not collect and not reschedule. logger.Warn(ErrorCode.Catalog_ActivationCollector_BadState_1, "ActivationCollector found an activation in a non Valid state. All activation inside the ActivationCollector should be in Valid state. Activation: {0}", activation.ToDetailedString()); } else if (activation.ShouldBeKeptAlive) { // Consider: need to reschedule to what is the remaining time for ShouldBeKeptAlive, not the full CollectionAgeLimit. ScheduleCollection(activation); } else if (!activation.IsInactive) { // This is essentialy a bug, an active activation should not be in the last bucket. logger.Warn(ErrorCode.Catalog_ActivationCollector_BadState_2, "ActivationCollector found an active activation in it's last bucket. This is violation of ActivationCollector invariants. " + "For now going to defer it's collection. Activation: {0}", activation.ToDetailedString()); ScheduleCollection(activation); } else if (!activation.IsStale(now)) { // This is essentialy a bug, a non stale activation should not be in the last bucket. logger.Warn(ErrorCode.Catalog_ActivationCollector_BadState_3, "ActivationCollector found a non stale activation in it's last bucket. This is violation of ActivationCollector invariants. Now: {0}" + "For now going to defer it's collection. Activation: {1}", TraceLogger.PrintDate(now), activation.ToDetailedString()); ScheduleCollection(activation); } else { // Atomically set Deactivating state, to disallow any new requests or new timer ticks to be dispatched on this activation. activation.PrepareForDeactivation(); DecideToCollectActivation(activation, ref result); } } } } return result ?? nothing; } /// <summary> /// Scans for activations that have been idle for the specified age limit. /// </summary> /// <param name="ageLimit">The age limit.</param> /// <returns></returns> public List<ActivationData> ScanAll(TimeSpan ageLimit) { List<ActivationData> result = null; var now = DateTime.UtcNow; int bucketCount = buckets.Count; int i = 0; foreach (var bucket in buckets.Values) { if (i >= bucketCount) break; int notToExceed = bucket.ApproximateCount; int j = 0; foreach (var activation in bucket) { // theoretically, we could iterate forever on the ConcurrentDictionary. we limit ourselves to an approximation of the bucket's Count property to limit the number of iterations we perform. if (j >= notToExceed) break; lock (activation) { if (activation.State != ActivationState.Valid) { // Do nothing: don't collect, don't reschedule. } else if (activation.ShouldBeKeptAlive) { // do nothing } else if (!activation.IsInactive) { // do nothing } else { if (activation.GetIdleness(now) >= ageLimit) { if (bucket.TryCancel(activation)) { // we removed the activation from the collector. it's our responsibility to deactivate it. activation.PrepareForDeactivation(); DecideToCollectActivation(activation, ref result); } // someone else has already deactivated the activation, so there's nothing to do. } else { // activation is not idle long enough for collection. do nothing. } } } ++j; } ++i; } return result ?? nothing; } private static void DecideToCollectActivation(ActivationData activation, ref List<ActivationData> condemned) { if (null == condemned) { condemned = new List<ActivationData> { activation }; } else { condemned.Add(activation); } if (Silo.CurrentSilo.TestHookup.Debug_OnDecideToCollectActivation != null) { Silo.CurrentSilo.TestHookup.Debug_OnDecideToCollectActivation(activation.Grain); } } private static void ThrowIfTicketIsInvalid(DateTime ticket, TimeSpan quantum) { ThrowIfDefault(ticket, "ticket"); if (0 != ticket.Ticks % quantum.Ticks) { throw new ArgumentException(string.Format("invalid ticket ({0})", ticket)); } } private void ThrowIfTicketIsInvalid(DateTime ticket) { ThrowIfTicketIsInvalid(ticket, quantum); } private void ThrowIfExemptFromCollection(ActivationData activation, string name) { if (activation.IsExemptFromCollection) { throw new ArgumentException(string.Format("{0} should not refer to a system target or system grain.", name), name); } } private bool IsExpired(DateTime ticket) { return ticket < nextTicket; } private DateTime MakeTicketFromDateTime(DateTime timestamp) { // round the timestamp to the next quantum. e.g. if the quantum is 1 minute and the timestamp is 3:45:22, then the ticket will be 3:46. note that TimeStamp.Ticks and DateTime.Ticks both return a long. DateTime ticket = new DateTime(((timestamp.Ticks - 1) / quantum.Ticks + 1) * quantum.Ticks); if (ticket < nextTicket) { throw new ArgumentException(string.Format("The earliest collection that can be scheduled from now is for {0}", new DateTime(nextTicket.Ticks - quantum.Ticks + 1))); } return ticket; } private DateTime MakeTicketFromTimeSpan(TimeSpan timeout) { if (timeout < quantum) { throw new ArgumentException(String.Format("timeout must be at least {0}, but it is {1}", quantum, timeout), "timeout"); } return MakeTicketFromDateTime(DateTime.UtcNow + timeout); } private void Add(ActivationData item, DateTime ticket) { // note: we expect the activation lock to be held. item.ResetCollectionCancelledFlag(); Bucket bucket = buckets.GetOrAdd( ticket, key => new Bucket(key, quantum)); bucket.Add(item); item.SetCollectionTicket(ticket); } static private void ThrowIfDefault<T>(T value, string name) where T : IEquatable<T> { if (value.Equals(default(T))) { throw new ArgumentException(string.Format("default({0}) is not allowed in this context.", typeof(T).Name), name); } } private class Bucket : IEnumerable<ActivationData> { private readonly DateTime key; private readonly ConcurrentDictionary<ActivationId, ActivationData> items; public DateTime Key { get { return key; } } public int ApproximateCount { get { return items.Count; } } public Bucket(DateTime key, TimeSpan quantum) { ThrowIfTicketIsInvalid(key, quantum); this.key = key; items = new ConcurrentDictionary<ActivationId, ActivationData>(); } public void Add(ActivationData item) { if (!items.TryAdd(item.ActivationId, item)) { throw new InvalidOperationException("item is already associated with this bucket"); } } public bool TryRemove(ActivationData item) { if (!TryCancel(item)) return false; // actual removal is a memory optimization and isn't technically necessary to cancel the timeout. ActivationData unused; return items.TryRemove(item.ActivationId, out unused); } public bool TryCancel(ActivationData item) { if (!item.TrySetCollectionCancelledFlag()) return false; // we need to null out the ActivationData reference in the bucket in order to ensure that the memory gets collected. if we've succeeded in setting the cancellation flag, then we should have won the right to do this, so we throw an exception if we fail. if (items.TryUpdate(item.ActivationId, null, item)) return true; throw new InvalidOperationException("unexpected failure to cancel deactivation"); } public IEnumerable<ActivationData> CancelAll() { List<ActivationData> result = null; foreach (var pair in items) { // attempt to cancel the item. if we succeed, it wasn't already cancelled and we can return it. otherwise, we silently ignore it. if (pair.Value.TrySetCollectionCancelledFlag()) { if (result == null) { // we only need to ensure there's enough space left for this element and any potential entries. result = new List<ActivationData>(); } result.Add(pair.Value); } } return result ?? nothing; } public IEnumerator<ActivationData> GetEnumerator() { return items.Values.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } } }
// 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.Globalization; using System.Diagnostics; using System.Text; namespace System { // A Version object contains four hierarchical numeric components: major, minor, // build and revision. Build and revision may be unspecified, which is represented // internally as a -1. By definition, an unspecified component matches anything // (both unspecified and specified), and an unspecified component is "less than" any // specified component. [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public sealed class Version : ICloneable, IComparable , IComparable<Version>, IEquatable<Version> { // AssemblyName depends on the order staying the same private readonly int _Major; // Do not rename (binary serialization) private readonly int _Minor; // Do not rename (binary serialization) private readonly int _Build = -1; // Do not rename (binary serialization) private readonly int _Revision = -1; // Do not rename (binary serialization) public Version(int major, int minor, int build, int revision) { if (major < 0) throw new ArgumentOutOfRangeException(nameof(major), SR.ArgumentOutOfRange_Version); if (minor < 0) throw new ArgumentOutOfRangeException(nameof(minor), SR.ArgumentOutOfRange_Version); if (build < 0) throw new ArgumentOutOfRangeException(nameof(build), SR.ArgumentOutOfRange_Version); if (revision < 0) throw new ArgumentOutOfRangeException(nameof(revision), SR.ArgumentOutOfRange_Version); _Major = major; _Minor = minor; _Build = build; _Revision = revision; } public Version(int major, int minor, int build) { if (major < 0) throw new ArgumentOutOfRangeException(nameof(major), SR.ArgumentOutOfRange_Version); if (minor < 0) throw new ArgumentOutOfRangeException(nameof(minor), SR.ArgumentOutOfRange_Version); if (build < 0) throw new ArgumentOutOfRangeException(nameof(build), SR.ArgumentOutOfRange_Version); _Major = major; _Minor = minor; _Build = build; } public Version(int major, int minor) { if (major < 0) throw new ArgumentOutOfRangeException(nameof(major), SR.ArgumentOutOfRange_Version); if (minor < 0) throw new ArgumentOutOfRangeException(nameof(minor), SR.ArgumentOutOfRange_Version); _Major = major; _Minor = minor; } public Version(String version) { Version v = Version.Parse(version); _Major = v.Major; _Minor = v.Minor; _Build = v.Build; _Revision = v.Revision; } public Version() { _Major = 0; _Minor = 0; } private Version(Version version) { Debug.Assert(version != null); _Major = version._Major; _Minor = version._Minor; _Build = version._Build; _Revision = version._Revision; } public object Clone() { return new Version(this); } // Properties for setting and getting version numbers public int Major { get { return _Major; } } public int Minor { get { return _Minor; } } public int Build { get { return _Build; } } public int Revision { get { return _Revision; } } public short MajorRevision { get { return (short)(_Revision >> 16); } } public short MinorRevision { get { return (short)(_Revision & 0xFFFF); } } public int CompareTo(Object version) { if (version == null) { return 1; } Version v = version as Version; if (v == null) { throw new ArgumentException(SR.Arg_MustBeVersion); } return CompareTo(v); } public int CompareTo(Version value) { return object.ReferenceEquals(value, this) ? 0 : object.ReferenceEquals(value, null) ? 1 : _Major != value._Major ? (_Major > value._Major ? 1 : -1) : _Minor != value._Minor ? (_Minor > value._Minor ? 1 : -1) : _Build != value._Build ? (_Build > value._Build ? 1 : -1) : _Revision != value._Revision ? (_Revision > value._Revision ? 1 : -1) : 0; } public override bool Equals(Object obj) { return Equals(obj as Version); } public bool Equals(Version obj) { return object.ReferenceEquals(obj, this) || (!object.ReferenceEquals(obj, null) && _Major == obj._Major && _Minor == obj._Minor && _Build == obj._Build && _Revision == obj._Revision); } public override int GetHashCode() { // Let's assume that most version numbers will be pretty small and just // OR some lower order bits together. int accumulator = 0; accumulator |= (_Major & 0x0000000F) << 28; accumulator |= (_Minor & 0x000000FF) << 20; accumulator |= (_Build & 0x000000FF) << 12; accumulator |= (_Revision & 0x00000FFF); return accumulator; } public override string ToString() => ToString(DefaultFormatFieldCount); public string ToString(int fieldCount) => fieldCount == 0 ? string.Empty : fieldCount == 1 ? _Major.ToString() : StringBuilderCache.GetStringAndRelease(ToCachedStringBuilder(fieldCount)); public bool TryFormat(Span<char> destination, out int charsWritten) => TryFormat(destination, DefaultFormatFieldCount, out charsWritten); public bool TryFormat(Span<char> destination, int fieldCount, out int charsWritten) { if (fieldCount == 0) { charsWritten = 0; return true; } // TODO https://github.com/dotnet/corefx/issues/22403: fieldCount==1 can just use int.TryFormat StringBuilder sb = ToCachedStringBuilder(fieldCount); if (sb.Length <= destination.Length) { sb.CopyTo(0, destination, sb.Length); StringBuilderCache.Release(sb); charsWritten = sb.Length; return true; } StringBuilderCache.Release(sb); charsWritten = 0; return false; } private int DefaultFormatFieldCount => _Build == -1 ? 2 : _Revision == -1 ? 3 : 4; private StringBuilder ToCachedStringBuilder(int fieldCount) { if (fieldCount == 1) { StringBuilder sb = StringBuilderCache.Acquire(); AppendNonNegativeNumber(_Major, sb); return sb; } else if (fieldCount == 2) { StringBuilder sb = StringBuilderCache.Acquire(); AppendNonNegativeNumber(_Major, sb); sb.Append('.'); AppendNonNegativeNumber(_Minor, sb); return sb; } else { if (_Build == -1) { throw new ArgumentException(SR.Format(SR.ArgumentOutOfRange_Bounds_Lower_Upper, "0", "2"), nameof(fieldCount)); } if (fieldCount == 3) { StringBuilder sb = StringBuilderCache.Acquire(); AppendNonNegativeNumber(_Major, sb); sb.Append('.'); AppendNonNegativeNumber(_Minor, sb); sb.Append('.'); AppendNonNegativeNumber(_Build, sb); return sb; } if (_Revision == -1) { throw new ArgumentException(SR.Format(SR.ArgumentOutOfRange_Bounds_Lower_Upper, "0", "3"), nameof(fieldCount)); } if (fieldCount == 4) { StringBuilder sb = StringBuilderCache.Acquire(); AppendNonNegativeNumber(_Major, sb); sb.Append('.'); AppendNonNegativeNumber(_Minor, sb); sb.Append('.'); AppendNonNegativeNumber(_Build, sb); sb.Append('.'); AppendNonNegativeNumber(_Revision, sb); return sb; } throw new ArgumentException(SR.Format(SR.ArgumentOutOfRange_Bounds_Lower_Upper, "0", "4"), nameof(fieldCount)); } } // TODO https://github.com/dotnet/corefx/issues/22616: // Use StringBuilder.Append(int) once it's been updated to use spans internally. // // AppendNonNegativeNumber is an optimization to append a number to a StringBuilder object without // doing any boxing and not even creating intermediate string. // Note: as we always have positive numbers then it is safe to convert the number to string // regardless of the current culture as we'll not have any punctuation marks in the number private static void AppendNonNegativeNumber(int num, StringBuilder sb) { Debug.Assert(num >= 0, "AppendPositiveNumber expect positive numbers"); int index = sb.Length; do { num = Math.DivRem(num, 10, out int remainder); sb.Insert(index, (char)('0' + remainder)); } while (num > 0); } public static Version Parse(string input) { if (input == null) { throw new ArgumentNullException(nameof(input)); } return ParseVersion(input.AsReadOnlySpan(), throwOnFailure: true); } public static Version Parse(ReadOnlySpan<char> input) => ParseVersion(input, throwOnFailure: true); public static bool TryParse(string input, out Version result) { if (input == null) { result = null; return false; } return (result = ParseVersion(input.AsReadOnlySpan(), throwOnFailure: false)) != null; } public static bool TryParse(ReadOnlySpan<char> input, out Version result) => (result = ParseVersion(input, throwOnFailure: false)) != null; private static Version ParseVersion(ReadOnlySpan<char> input, bool throwOnFailure) { // Find the separator between major and minor. It must exist. int majorEnd = input.IndexOf('.'); if (majorEnd < 0) { if (throwOnFailure) throw new ArgumentException(SR.Arg_VersionString, nameof(input)); return null; } // Find the ends of the optional minor and build portions. // We musn't have any separators after build. int buildEnd = -1; int minorEnd = input.IndexOf('.', majorEnd + 1); if (minorEnd != -1) { buildEnd = input.IndexOf('.', minorEnd + 1); if (buildEnd != -1) { if (input.IndexOf('.', buildEnd + 1) != -1) { if (throwOnFailure) throw new ArgumentException(SR.Arg_VersionString, nameof(input)); return null; } } } int major, minor, build, revision; // Parse the major version if (!TryParseComponent(input.Slice(0, majorEnd), nameof(input), throwOnFailure, out major)) { return null; } if (minorEnd != -1) { // If there's more than a major and minor, parse the minor, too. if (!TryParseComponent(input.Slice(majorEnd + 1, minorEnd - majorEnd - 1), nameof(input), throwOnFailure, out minor)) { return null; } if (buildEnd != -1) { // major.minor.build.revision return TryParseComponent(input.Slice(minorEnd + 1, buildEnd - minorEnd - 1), nameof(build), throwOnFailure, out build) && TryParseComponent(input.Slice(buildEnd + 1), nameof(revision), throwOnFailure, out revision) ? new Version(major, minor, build, revision) : null; } else { // major.minor.build return TryParseComponent(input.Slice(minorEnd + 1), nameof(build), throwOnFailure, out build) ? new Version(major, minor, build) : null; } } else { // major.minor return TryParseComponent(input.Slice(majorEnd + 1), nameof(input), throwOnFailure, out minor) ? new Version(major, minor) : null; } } private static bool TryParseComponent(ReadOnlySpan<char> component, string componentName, bool throwOnFailure, out int parsedComponent) { if (throwOnFailure) { if ((parsedComponent = int.Parse(component, NumberStyles.Integer, CultureInfo.InvariantCulture)) < 0) { throw new ArgumentOutOfRangeException(componentName, SR.ArgumentOutOfRange_Version); } return true; } return int.TryParse(component, out parsedComponent, NumberStyles.Integer, CultureInfo.InvariantCulture) && parsedComponent >= 0; } public static bool operator ==(Version v1, Version v2) { if (Object.ReferenceEquals(v1, null)) { return Object.ReferenceEquals(v2, null); } return v1.Equals(v2); } public static bool operator !=(Version v1, Version v2) { return !(v1 == v2); } public static bool operator <(Version v1, Version v2) { if ((Object)v1 == null) throw new ArgumentNullException(nameof(v1)); return (v1.CompareTo(v2) < 0); } public static bool operator <=(Version v1, Version v2) { if ((Object)v1 == null) throw new ArgumentNullException(nameof(v1)); return (v1.CompareTo(v2) <= 0); } public static bool operator >(Version v1, Version v2) { return (v2 < v1); } public static bool operator >=(Version v1, Version v2) { return (v2 <= v1); } } }
// 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.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc.Abstractions; using Microsoft.AspNetCore.Mvc.Infrastructure; using Microsoft.AspNetCore.Routing; using Microsoft.AspNetCore.Routing.Template; using Microsoft.AspNetCore.Routing.Tree; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.ObjectPool; using Moq; using Xunit; namespace Microsoft.AspNetCore.Mvc.Routing { public class AttributeRouteTest { private static readonly RequestDelegate NullHandler = (c) => Task.FromResult(0); // This test verifies that AttributeRoute can respond to changes in the AD collection. It does this // by running a successful request, then removing that action and verifying the next route isn't // successful. [Fact] public async Task AttributeRoute_UsesUpdatedActionDescriptors() { // Arrange ActionDescriptor selected = null; var actions = new List<ActionDescriptor>() { new ActionDescriptor() { AttributeRouteInfo = new AttributeRouteInfo() { Template = "api/Blog/{key1}" }, }, new ActionDescriptor() { AttributeRouteInfo = new AttributeRouteInfo() { Template = "api/Store/Buy/{key2}" }, }, }; Func<ActionDescriptor[], IRouter> handlerFactory = (_) => { var handler = new Mock<IRouter>(); handler .Setup(r => r.RouteAsync(It.IsAny<RouteContext>())) .Returns<RouteContext>(routeContext => { if (routeContext.RouteData.Values.ContainsKey("key1")) { selected = actions[0]; } else if (routeContext.RouteData.Values.ContainsKey("key2")) { selected = actions[1]; } routeContext.Handler = (c) => Task.CompletedTask; return Task.CompletedTask; }); return handler.Object; }; var actionDescriptorProvider = CreateActionDescriptorProvider(actions); var route = CreateRoute(handlerFactory, actionDescriptorProvider.Object); var requestServices = new Mock<IServiceProvider>(MockBehavior.Strict); requestServices .Setup(s => s.GetService(typeof(ILoggerFactory))) .Returns(NullLoggerFactory.Instance); var httpContext = new DefaultHttpContext(); httpContext.Request.Path = new PathString("/api/Store/Buy/5"); httpContext.RequestServices = requestServices.Object; var context = new RouteContext(httpContext); // Act 1 await route.RouteAsync(context); // Assert 1 Assert.NotNull(context.Handler); Assert.Equal("5", context.RouteData.Values["key2"]); Assert.Same(actions[1], selected); // Arrange 2 - remove the action and update the collection selected = null; actions.RemoveAt(1); actionDescriptorProvider .SetupGet(ad => ad.ActionDescriptors) .Returns(new ActionDescriptorCollection(actions, version: 2)); context = new RouteContext(httpContext); // Act 2 await route.RouteAsync(context); // Assert 2 Assert.Null(context.Handler); Assert.Empty(context.RouteData.Values); Assert.Null(selected); } [Fact] public void AttributeRoute_GetEntries_CreatesOutboundEntry() { // Arrange var actions = new List<ActionDescriptor>() { new ActionDescriptor() { AttributeRouteInfo = new AttributeRouteInfo() { Template = "api/Blog/{id}", Name = "BLOG_INDEX", Order = 17, }, RouteValues = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) { { "controller", "Blog" }, { "action", "Index" }, }, }, }; var builder = CreateBuilder(); var actionDescriptorProvider = CreateActionDescriptorProvider(actions); var route = CreateRoute(CreateHandler().Object, actionDescriptorProvider.Object); // Act route.AddEntries(builder, actionDescriptorProvider.Object.ActionDescriptors); // Assert Assert.Collection( builder.OutboundEntries, e => { Assert.Empty(e.Constraints); Assert.Empty(e.Defaults); Assert.Equal(RoutePrecedence.ComputeOutbound(e.RouteTemplate), e.Precedence); Assert.Equal("BLOG_INDEX", e.RouteName); Assert.Equal(17, e.Order); Assert.Equal(ToRouteValueDictionary(actions[0].RouteValues), e.RequiredLinkValues); Assert.Equal("api/Blog/{id}", e.RouteTemplate.TemplateText); }); } [Fact] public void AttributeRoute_GetEntries_CreatesOutboundEntry_WithConstraint() { // Arrange var actions = new List<ActionDescriptor>() { new ActionDescriptor() { AttributeRouteInfo = new AttributeRouteInfo() { Template = "api/Blog/{id:int}", Name = "BLOG_INDEX", Order = 17, }, RouteValues = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) { { "controller", "Blog" }, { "action", "Index" }, }, }, }; var builder = CreateBuilder(); var actionDescriptorProvider = CreateActionDescriptorProvider(actions); var route = CreateRoute(CreateHandler().Object, actionDescriptorProvider.Object); // Act route.AddEntries(builder, actionDescriptorProvider.Object.ActionDescriptors); // Assert Assert.Collection( builder.OutboundEntries, e => { Assert.Single(e.Constraints, kvp => kvp.Key == "id"); Assert.Empty(e.Defaults); Assert.Equal(RoutePrecedence.ComputeOutbound(e.RouteTemplate), e.Precedence); Assert.Equal("BLOG_INDEX", e.RouteName); Assert.Equal(17, e.Order); Assert.Equal(ToRouteValueDictionary(actions[0].RouteValues), e.RequiredLinkValues); Assert.Equal("api/Blog/{id:int}", e.RouteTemplate.TemplateText); }); } [Fact] public void AttributeRoute_GetEntries_CreatesOutboundEntry_WithDefault() { // Arrange var actions = new List<ActionDescriptor>() { new ActionDescriptor() { AttributeRouteInfo = new AttributeRouteInfo() { Template = "api/Blog/{*slug=hello}", Name = "BLOG_INDEX", Order = 17, }, RouteValues = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) { { "controller", "Blog" }, { "action", "Index" }, }, }, }; var builder = CreateBuilder(); var actionDescriptorProvider = CreateActionDescriptorProvider(actions); var route = CreateRoute(CreateHandler().Object, actionDescriptorProvider.Object); // Act route.AddEntries(builder, actionDescriptorProvider.Object.ActionDescriptors); // Assert Assert.Collection( builder.OutboundEntries, e => { Assert.Empty(e.Constraints); Assert.Equal(new RouteValueDictionary(new { slug = "hello" }), e.Defaults); Assert.Equal(RoutePrecedence.ComputeOutbound(e.RouteTemplate), e.Precedence); Assert.Equal("BLOG_INDEX", e.RouteName); Assert.Equal(17, e.Order); Assert.Equal(ToRouteValueDictionary(actions[0].RouteValues), e.RequiredLinkValues); Assert.Equal("api/Blog/{*slug=hello}", e.RouteTemplate.TemplateText); }); } // These actions seem like duplicates, but this is a real case that can happen where two different // actions define the same route info. Link generation happens based on the action name + controller // name. [Fact] public void AttributeRoute_GetEntries_CreatesOutboundEntry_ForEachAction() { // Arrange var actions = new List<ActionDescriptor>() { new ActionDescriptor() { AttributeRouteInfo = new AttributeRouteInfo() { Template = "api/Blog/{id}", Name = "BLOG_INDEX", Order = 17, }, RouteValues = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) { { "controller", "Blog" }, { "action", "Index" }, }, }, new ActionDescriptor() { AttributeRouteInfo = new AttributeRouteInfo() { Template = "api/Blog/{id}", Name = "BLOG_INDEX", Order = 17, }, RouteValues = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) { { "controller", "Blog" }, { "action", "Index2" }, }, }, }; var builder = CreateBuilder(); var actionDescriptorProvider = CreateActionDescriptorProvider(actions); var route = CreateRoute(CreateHandler().Object, actionDescriptorProvider.Object); // Act route.AddEntries(builder, actionDescriptorProvider.Object.ActionDescriptors); // Assert Assert.Collection( builder.OutboundEntries, e => { Assert.Empty(e.Constraints); Assert.Empty(e.Defaults); Assert.Equal(RoutePrecedence.ComputeOutbound(e.RouteTemplate), e.Precedence); Assert.Equal("BLOG_INDEX", e.RouteName); Assert.Equal(17, e.Order); Assert.Equal(ToRouteValueDictionary(actions[0].RouteValues), e.RequiredLinkValues); Assert.Equal("api/Blog/{id}", e.RouteTemplate.TemplateText); }, e => { Assert.Empty(e.Constraints); Assert.Empty(e.Defaults); Assert.Equal(RoutePrecedence.ComputeOutbound(e.RouteTemplate), e.Precedence); Assert.Equal("BLOG_INDEX", e.RouteName); Assert.Equal(17, e.Order); Assert.Equal(ToRouteValueDictionary(actions[1].RouteValues), e.RequiredLinkValues); Assert.Equal("api/Blog/{id}", e.RouteTemplate.TemplateText); }); } [Fact] public void AttributeRoute_GetEntries_CreatesInboundEntry() { // Arrange var actions = new List<ActionDescriptor>() { new ActionDescriptor() { AttributeRouteInfo = new AttributeRouteInfo() { Template = "api/Blog/{id}", Name = "BLOG_INDEX", Order = 17, }, RouteValues = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) { { "controller", "Blog" }, { "action", "Index" }, }, }, }; var builder = CreateBuilder(); var actionDescriptorProvider = CreateActionDescriptorProvider(actions); var route = CreateRoute(CreateHandler().Object, actionDescriptorProvider.Object); // Act route.AddEntries(builder, actionDescriptorProvider.Object.ActionDescriptors); // Assert Assert.Collection( builder.InboundEntries, e => { Assert.Empty(e.Constraints); Assert.Equal(17, e.Order); Assert.Equal(RoutePrecedence.ComputeInbound(e.RouteTemplate), e.Precedence); Assert.Equal("BLOG_INDEX", e.RouteName); Assert.Equal("api/Blog/{id}", e.RouteTemplate.TemplateText); Assert.Empty(e.Defaults); }); } [Fact] public void AttributeRoute_GetEntries_CreatesInboundEntry_WithConstraint() { // Arrange var actions = new List<ActionDescriptor>() { new ActionDescriptor() { AttributeRouteInfo = new AttributeRouteInfo() { Template = "api/Blog/{id:int}", Name = "BLOG_INDEX", Order = 17, }, RouteValues = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) { { "controller", "Blog" }, { "action", "Index" }, }, }, }; var builder = CreateBuilder(); var actionDescriptorProvider = CreateActionDescriptorProvider(actions); var route = CreateRoute(CreateHandler().Object, actionDescriptorProvider.Object); // Act route.AddEntries(builder, actionDescriptorProvider.Object.ActionDescriptors); // Assert Assert.Collection( builder.InboundEntries, e => { Assert.Single(e.Constraints, kvp => kvp.Key == "id"); Assert.Equal(17, e.Order); Assert.Equal(RoutePrecedence.ComputeInbound(e.RouteTemplate), e.Precedence); Assert.Equal("BLOG_INDEX", e.RouteName); Assert.Equal("api/Blog/{id:int}", e.RouteTemplate.TemplateText); Assert.Empty(e.Defaults); }); } [Fact] public void AttributeRoute_GetEntries_CreatesInboundEntry_WithDefault() { // Arrange var actions = new List<ActionDescriptor>() { new ActionDescriptor() { AttributeRouteInfo = new AttributeRouteInfo() { Template = "api/Blog/{*slug=hello}", Name = "BLOG_INDEX", Order = 17, }, RouteValues = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) { { "controller", "Blog" }, { "action", "Index" }, }, }, }; var builder = CreateBuilder(); var actionDescriptorProvider = CreateActionDescriptorProvider(actions); var route = CreateRoute(CreateHandler().Object, actionDescriptorProvider.Object); // Act route.AddEntries(builder, actionDescriptorProvider.Object.ActionDescriptors); // Assert Assert.Collection( builder.InboundEntries, e => { Assert.Empty(e.Constraints); Assert.Equal(17, e.Order); Assert.Equal(RoutePrecedence.ComputeInbound(e.RouteTemplate), e.Precedence); Assert.Equal("BLOG_INDEX", e.RouteName); Assert.Equal("api/Blog/{*slug=hello}", e.RouteTemplate.TemplateText); Assert.Collection( e.Defaults.OrderBy(kvp => kvp.Key), kvp => Assert.Equal(new KeyValuePair<string, object>("slug", "hello"), kvp)); }); } // These actions seem like duplicates, but this is a real case that can happen where two different // actions define the same route info. Link generation happens based on the action name + controller // name. [Fact] public void AttributeRoute_GetEntries_CreatesInboundEntry_CombinesLikeActions() { // Arrange var actions = new List<ActionDescriptor>() { new ActionDescriptor() { AttributeRouteInfo = new AttributeRouteInfo() { Template = "api/Blog/{id}", Name = "BLOG_INDEX", Order = 17, }, RouteValues = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) { { "controller", "Blog" }, { "action", "Index" }, }, }, new ActionDescriptor() { AttributeRouteInfo = new AttributeRouteInfo() { Template = "api/Blog/{id}", Name = "BLOG_INDEX", Order = 17, }, RouteValues = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) { { "controller", "Blog" }, { "action", "Index2" }, }, }, }; var builder = CreateBuilder(); var actionDescriptorProvider = CreateActionDescriptorProvider(actions); var route = CreateRoute(CreateHandler().Object, actionDescriptorProvider.Object); // Act route.AddEntries(builder, actionDescriptorProvider.Object.ActionDescriptors); // Assert Assert.Collection( builder.InboundEntries, e => { Assert.Empty(e.Constraints); Assert.Equal(17, e.Order); Assert.Equal(RoutePrecedence.ComputeInbound(e.RouteTemplate), e.Precedence); Assert.Equal("BLOG_INDEX", e.RouteName); Assert.Equal("api/Blog/{id}", e.RouteTemplate.TemplateText); Assert.Empty(e.Defaults); }); } [Theory] [InlineData("")] [InlineData("GetBlogById")] public void AttributeRoute_ThrowsRouteCreationException_ForConstraintsNotTakingArguments(string routeName) { // Arrange var routeTemplate = "api/Blog/{id:int(10)}"; var actions = new List<ActionDescriptor>() { new ActionDescriptor() { AttributeRouteInfo = new AttributeRouteInfo() { Template = routeTemplate, Name = routeName } }, }; var expectedErrorMessage = "An error occurred while adding a route to the route builder. " + $"Route name '{routeName}' and template '{routeTemplate}'."; var builder = CreateBuilder(); var actionDescriptorProvider = CreateActionDescriptorProvider(actions); var route = CreateRoute(CreateHandler().Object, actionDescriptorProvider.Object); // Act & Assert var exception = Assert.Throws<RouteCreationException>(() => { route.AddEntries(builder, actionDescriptorProvider.Object.ActionDescriptors); }); Assert.Equal(expectedErrorMessage, exception.Message); Assert.IsType<RouteCreationException>(exception.InnerException); } [Fact] public void GetEntries_DoesNotCreateOutboundEntriesForAttributesWithSuppressForLinkGenerationSetToTrue() { // Arrange var actions = new List<ActionDescriptor>() { new ActionDescriptor() { AttributeRouteInfo = new AttributeRouteInfo { Template = "blog/get/{id}", Name = "BLOG_LINK1", SuppressLinkGeneration = true, }, }, new ActionDescriptor() { AttributeRouteInfo = new AttributeRouteInfo { Template = "blog/{snake-cased-name}", Name = "BLOG_INDEX2", }, }, new ActionDescriptor() { AttributeRouteInfo = new AttributeRouteInfo { Template = "blog/", Name = "BLOG_HOME", SuppressPathMatching = true, }, }, }; var builder = CreateBuilder(); var actionDescriptorProvider = CreateActionDescriptorProvider(actions); var route = CreateRoute(CreateHandler().Object, actionDescriptorProvider.Object); // Act route.AddEntries(builder, actionDescriptorProvider.Object.ActionDescriptors); // Assert Assert.Collection( builder.OutboundEntries, e => { Assert.Equal("BLOG_INDEX2", e.RouteName); Assert.Equal("blog/{snake-cased-name}", e.RouteTemplate.TemplateText); }, e => { Assert.Equal("BLOG_HOME", e.RouteName); Assert.Equal("blog/", e.RouteTemplate.TemplateText); }); } [Fact] public void GetEntries_DoesNotCreateOutboundEntriesForAttributesWithSuppressForLinkGenerationSetToTrue_WhenMultipleAttributesHaveTheSameTemplate() { // Arrange var actions = new List<ActionDescriptor>() { new ActionDescriptor() { AttributeRouteInfo = new AttributeRouteInfo { Template = "blog/get/{id}", Name = "BLOG_LINK1", SuppressLinkGeneration = true, }, }, new ActionDescriptor() { AttributeRouteInfo = new AttributeRouteInfo { Template = "blog/get/{id}", Name = "BLOG_LINK2", }, }, new ActionDescriptor() { AttributeRouteInfo = new AttributeRouteInfo { Template = "blog/", Name = "BLOG_HOME", SuppressPathMatching = true, }, }, }; var builder = CreateBuilder(); var actionDescriptorProvider = CreateActionDescriptorProvider(actions); var route = CreateRoute(CreateHandler().Object, actionDescriptorProvider.Object); // Act route.AddEntries(builder, actionDescriptorProvider.Object.ActionDescriptors); // Assert Assert.Collection( builder.OutboundEntries, e => { Assert.Equal("BLOG_LINK2", e.RouteName); Assert.Equal("blog/get/{id}", e.RouteTemplate.TemplateText); }, e => { Assert.Equal("BLOG_HOME", e.RouteName); Assert.Equal("blog/", e.RouteTemplate.TemplateText); }); } [Fact] public void GetEntries_DoesNotCreateInboundEntriesForAttributesWithSuppressForPathMatchingSetToTrue() { // Arrange var actions = new List<ActionDescriptor>() { new ActionDescriptor() { AttributeRouteInfo = new AttributeRouteInfo { Template = "blog/get/{id}", Name = "BLOG_LINK1", SuppressLinkGeneration = true, }, }, new ActionDescriptor() { AttributeRouteInfo = new AttributeRouteInfo { Template = "blog/{snake-cased-name}", Name = "BLOG_LINK2", }, }, new ActionDescriptor() { AttributeRouteInfo = new AttributeRouteInfo { Template = "blog/", Name = "BLOG_HOME", SuppressPathMatching = true, }, }, }; var builder = CreateBuilder(); var actionDescriptorProvider = CreateActionDescriptorProvider(actions); var route = CreateRoute(CreateHandler().Object, actionDescriptorProvider.Object); // Act route.AddEntries(builder, actionDescriptorProvider.Object.ActionDescriptors); // Assert Assert.Collection( builder.InboundEntries, e => { Assert.Equal("BLOG_LINK1", e.RouteName); Assert.Equal("blog/get/{id}", e.RouteTemplate.TemplateText); }, e => { Assert.Equal("BLOG_LINK2", e.RouteName); Assert.Equal("blog/{snake-cased-name}", e.RouteTemplate.TemplateText); }); } [Fact] public void GetEntries_DoesNotCreateInboundEntriesForAttributesWithSuppressForPathMatchingSetToTrue_WhenMultipleAttributesHaveTheSameTemplate() { // Arrange var actions = new List<ActionDescriptor>() { new ActionDescriptor() { AttributeRouteInfo = new AttributeRouteInfo { Template = "blog/get/{id}", Name = "BLOG_LINK1", SuppressPathMatching = true, }, }, new ActionDescriptor() { AttributeRouteInfo = new AttributeRouteInfo { Template = "blog/get/{id}", Name = "BLOG_LINK2", }, }, new ActionDescriptor() { AttributeRouteInfo = new AttributeRouteInfo { Template = "blog/", Name = "BLOG_HOME", SuppressLinkGeneration = true, }, }, }; var builder = CreateBuilder(); var actionDescriptorProvider = CreateActionDescriptorProvider(actions); var route = CreateRoute(CreateHandler().Object, actionDescriptorProvider.Object); // Act route.AddEntries(builder, actionDescriptorProvider.Object.ActionDescriptors); // Assert Assert.Collection( builder.InboundEntries, e => { Assert.Equal("BLOG_LINK2", e.RouteName); Assert.Equal("blog/get/{id}", e.RouteTemplate.TemplateText); }, e => { Assert.Equal("BLOG_HOME", e.RouteName); Assert.Equal("blog/", e.RouteTemplate.TemplateText); }); } private static TreeRouteBuilder CreateBuilder() { var services = new ServiceCollection() .AddSingleton<ILoggerFactory>(NullLoggerFactory.Instance) .AddLogging() .AddRouting() .AddOptions() .BuildServiceProvider(); return services.GetRequiredService<TreeRouteBuilder>(); } private static Mock<IRouter> CreateHandler() { var handler = new Mock<IRouter>(MockBehavior.Strict); handler .Setup(h => h.RouteAsync(It.IsAny<RouteContext>())) .Callback<RouteContext>(c => c.Handler = NullHandler) .Returns(Task.CompletedTask) .Verifiable(); return handler; } private static Mock<IActionDescriptorCollectionProvider> CreateActionDescriptorProvider( IReadOnlyList<ActionDescriptor> actions) { var actionDescriptorProvider = new Mock<IActionDescriptorCollectionProvider>(MockBehavior.Strict); actionDescriptorProvider .SetupGet(ad => ad.ActionDescriptors) .Returns(new ActionDescriptorCollection(actions, version: 1)); return actionDescriptorProvider; } private static AttributeRoute CreateRoute( IRouter handler, IActionDescriptorCollectionProvider actionDescriptorProvider) { return CreateRoute((_) => handler, actionDescriptorProvider); } private static AttributeRoute CreateRoute( Func<ActionDescriptor[], IRouter> handlerFactory, IActionDescriptorCollectionProvider actionDescriptorProvider) { var services = new ServiceCollection() .AddSingleton<ILoggerFactory>(NullLoggerFactory.Instance) .AddLogging() .AddRouting() .AddOptions() .BuildServiceProvider(); return new AttributeRoute(actionDescriptorProvider, services, handlerFactory); } // Needed because new RouteValueDictionary(values) would give us all the properties of // the Dictionary class. private static RouteValueDictionary ToRouteValueDictionary(IDictionary<string, string> values) { var result = new RouteValueDictionary(); foreach (var kvp in values) { result.Add(kvp.Key, kvp.Value); } return result; } } }
// 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.Security.Cryptography.X509Certificates.Tests { public class X509StoreTests { [Fact] public static void OpenMyStore() { using (X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser)) { store.Open(OpenFlags.ReadOnly); } } [Fact] public static void Constructor_DefaultStoreName() { using (X509Store store = new X509Store(StoreLocation.CurrentUser)) { Assert.Equal("My", store.Name); } } [Fact] public static void Constructor_IsNotOpen() { using (X509Store store = new X509Store(StoreLocation.CurrentUser)) { Assert.False(store.IsOpen); } } [Fact] public static void Constructor_DefaultStoreLocation() { using (X509Store store = new X509Store(StoreName.My)) { Assert.Equal(StoreLocation.CurrentUser, store.Location); } using (X509Store store = new X509Store("My")) { Assert.Equal(StoreLocation.CurrentUser, store.Location); } } [PlatformSpecific(TestPlatforms.Windows | TestPlatforms.OSX)] // Not supported via OpenSSL [Fact] public static void Constructor_StoreHandle() { using (X509Store store1 = new X509Store(StoreName.My, StoreLocation.CurrentUser)) { store1.Open(OpenFlags.ReadOnly); bool hadCerts; using (var coll = new ImportedCollection(store1.Certificates)) { // Use >1 instead of >0 in case the one is an ephemeral accident. hadCerts = coll.Collection.Count > 1; Assert.True(coll.Collection.Count >= 0); } using (X509Store store2 = new X509Store(store1.StoreHandle)) { using (var coll = new ImportedCollection(store2.Certificates)) { if (hadCerts) { // Use InRange here instead of True >= 0 so that the error message // is different, and we can diagnose a bit of what state we might have been in. Assert.InRange(coll.Collection.Count, 1, int.MaxValue); } else { Assert.True(coll.Collection.Count >= 0); } } } } } [PlatformSpecific(TestPlatforms.AnyUnix & ~TestPlatforms.OSX)] // API not supported via OpenSSL [Fact] public static void Constructor_StoreHandle_Unix() { using (X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser)) { store.Open(OpenFlags.ReadOnly); Assert.Equal(IntPtr.Zero, store.StoreHandle); } Assert.Throws<PlatformNotSupportedException>(() => new X509Chain(IntPtr.Zero)); } [Fact] public static void Constructor_OpenFlags() { using (X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser, OpenFlags.ReadOnly)) { Assert.True(store.IsOpen); } } [Fact] public static void Constructor_OpenFlags_StoreName() { using (X509Store store = new X509Store("My", StoreLocation.CurrentUser, OpenFlags.ReadOnly)) { Assert.True(store.IsOpen); } } [Fact] public static void Constructor_OpenFlags_OpenAnyway() { using (X509Store store = new X509Store("My", StoreLocation.CurrentUser, OpenFlags.ReadOnly)) { store.Open(OpenFlags.ReadOnly); Assert.True(store.IsOpen); } } [Fact] public static void Constructor_OpenFlags_NonExistingStoreName_Throws() { Assert.ThrowsAny<CryptographicException>(() => new X509Store(new Guid().ToString("D"), StoreLocation.CurrentUser, OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly) ); } [PlatformSpecific(TestPlatforms.Windows | TestPlatforms.OSX)] // StoreHandle not supported via OpenSSL [Fact] public static void TestDispose() { X509Store store; using (store = new X509Store(StoreName.My, StoreLocation.CurrentUser)) { store.Open(OpenFlags.ReadOnly); Assert.NotEqual(IntPtr.Zero, store.StoreHandle); } Assert.Throws<CryptographicException>(() => store.StoreHandle); } [Fact] public static void ReadMyCertificates() { using (X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser)) { store.Open(OpenFlags.ReadOnly); using (var coll = new ImportedCollection(store.Certificates)) { int certCount = coll.Collection.Count; // This assert is just so certCount appears to be used, the test really // is that store.get_Certificates didn't throw. Assert.True(certCount >= 0); } } } [Fact] public static void OpenNotExistent() { using (X509Store store = new X509Store(Guid.NewGuid().ToString("N"), StoreLocation.CurrentUser)) { Assert.ThrowsAny<CryptographicException>(() => store.Open(OpenFlags.OpenExistingOnly)); } } [Fact] public static void Open_IsOpenTrue() { using (X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser)) { store.Open(OpenFlags.ReadOnly); Assert.True(store.IsOpen); } } [Fact] public static void Dispose_IsOpenFalse() { X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser); store.Open(OpenFlags.ReadOnly); store.Dispose(); Assert.False(store.IsOpen); } [Fact] public static void ReOpen_IsOpenTrue() { X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser); store.Open(OpenFlags.ReadOnly); store.Close(); store.Open(OpenFlags.ReadOnly); Assert.True(store.IsOpen); } [Fact] public static void AddReadOnlyThrows() { using (X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser)) using (X509Certificate2 cert = new X509Certificate2(TestData.MsCertificate)) { store.Open(OpenFlags.ReadOnly); using (var coll = new ImportedCollection(store.Certificates)) { // Add only throws when it has to do work. If, for some reason, this certificate // is already present in the CurrentUser\My store, we can't really test this // functionality. if (!coll.Collection.Contains(cert)) { Assert.ThrowsAny<CryptographicException>(() => store.Add(cert)); } } } } [Fact] public static void AddDisposedThrowsCryptographicException() { using (X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser)) using (X509Certificate2 cert = new X509Certificate2(TestData.MsCertificate)) { store.Open(OpenFlags.ReadWrite); cert.Dispose(); Assert.Throws<CryptographicException>(() => store.Add(cert)); } } [Fact] public static void AddReadOnlyThrowsWhenCertificateExists() { using (X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser)) { store.Open(OpenFlags.ReadOnly); X509Certificate2 toAdd = null; // Look through the certificates to find one with no private key to call add on. // (The private key restriction is so that in the event of an "accidental success" // that no potential permissions would be modified) using (var coll = new ImportedCollection(store.Certificates)) { foreach (X509Certificate2 cert in coll.Collection) { if (!cert.HasPrivateKey) { toAdd = cert; break; } } if (toAdd != null) { Assert.ThrowsAny<CryptographicException>(() => store.Add(toAdd)); } } } } [Fact] public static void RemoveReadOnlyThrowsWhenFound() { // This test is unfortunate, in that it will mostly never test. // In order to do so it would have to open the store ReadWrite, put in a known value, // and call Remove on a ReadOnly copy. // // Just calling Remove on the first item found could also work (when the store isn't empty), // but if it fails the cost is too high. // // So what's the purpose of this test, you ask? To record why we're not unit testing it. // And someone could test it manually if they wanted. using (X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser)) using (X509Certificate2 cert = new X509Certificate2(TestData.MsCertificate)) { store.Open(OpenFlags.ReadOnly); using (var coll = new ImportedCollection(store.Certificates)) { if (coll.Collection.Contains(cert)) { Assert.ThrowsAny<CryptographicException>(() => store.Remove(cert)); } } } } /* Placeholder information for these tests until they can be written to run reliably. * Currently such tests would create physical files (Unix) and\or certificates (Windows) * which can collide with other running tests that use the same cert, or from a * test suite running more than once at the same time on the same machine. * Ideally, we use a GUID-named store to aoiv collitions with proper cleanup on Unix and Windows * and\or have lower testing hooks or use Microsoft Fakes Framework to redirect * and encapsulate the actual storage logic so it can be tested, along with mock exceptions * to verify exception handling. * See issue https://github.com/dotnet/corefx/issues/12833 * and https://github.com/dotnet/corefx/issues/12223 [Fact] public static void TestAddAndRemove() {} [Fact] public static void TestAddRangeAndRemoveRange() {} */ [Fact] public static void EnumerateClosedIsEmpty() { using (X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser)) { int count = store.Certificates.Count; Assert.Equal(0, count); } } [Fact] public static void AddClosedThrows() { using (X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser)) using (X509Certificate2 cert = new X509Certificate2(TestData.MsCertificate)) { Assert.ThrowsAny<CryptographicException>(() => store.Add(cert)); } } [Fact] public static void RemoveClosedThrows() { using (X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser)) using (X509Certificate2 cert = new X509Certificate2(TestData.MsCertificate)) { Assert.ThrowsAny<CryptographicException>(() => store.Remove(cert)); } } [Fact] [PlatformSpecific(TestPlatforms.Windows | TestPlatforms.OSX)] public static void OpenMachineMyStore_Supported() { using (X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine)) { store.Open(OpenFlags.ReadOnly); } } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix & ~TestPlatforms.OSX)] public static void OpenMachineMyStore_NotSupported() { using (X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine)) { Exception e = Assert.Throws<CryptographicException>(() => store.Open(OpenFlags.ReadOnly)); Assert.NotNull(e.InnerException); Assert.IsType<PlatformNotSupportedException>(e.InnerException); } } [Theory] [PlatformSpecific(TestPlatforms.AnyUnix & ~TestPlatforms.OSX)] [InlineData(OpenFlags.ReadOnly, false)] [InlineData(OpenFlags.MaxAllowed, false)] [InlineData(OpenFlags.ReadWrite, true)] public static void OpenMachineRootStore_Permissions(OpenFlags permissions, bool shouldThrow) { using (X509Store store = new X509Store(StoreName.Root, StoreLocation.LocalMachine)) { if (shouldThrow) { Exception e = Assert.Throws<CryptographicException>(() => store.Open(permissions)); Assert.NotNull(e.InnerException); Assert.IsType<PlatformNotSupportedException>(e.InnerException); } else { // Assert.DoesNotThrow store.Open(permissions); } } } [Fact] public static void MachineRootStore_NonEmpty() { // This test will fail on systems where the administrator has gone out of their // way to prune the trusted CA list down below this threshold. // // As of 2016-01-25, Ubuntu 14.04 has 169, and CentOS 7.1 has 175, so that'd be // quite a lot of pruning. // // And as of 2016-01-29 we understand the Homebrew-installed root store, with 180. const int MinimumThreshold = 5; using (X509Store store = new X509Store(StoreName.Root, StoreLocation.LocalMachine)) { store.Open(OpenFlags.ReadOnly); using (var storeCerts = new ImportedCollection(store.Certificates)) { int certCount = storeCerts.Collection.Count; Assert.InRange(certCount, MinimumThreshold, int.MaxValue); } } } [Theory] [PlatformSpecific(TestPlatforms.Windows | TestPlatforms.OSX)] [InlineData(StoreLocation.CurrentUser, true)] [InlineData(StoreLocation.LocalMachine, true)] [InlineData(StoreLocation.CurrentUser, false)] [InlineData(StoreLocation.LocalMachine, false)] public static void EnumerateDisallowedStore(StoreLocation location, bool useEnum) { X509Store store = useEnum ? new X509Store(StoreName.Disallowed, location) // Non-normative casing, proving that we aren't case-sensitive (Windows isn't) : new X509Store("disallowed", location); using (store) { store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly); using (var storeCerts = new ImportedCollection(store.Certificates)) { // That's all. We enumerated it. // There might not even be data in it. } } } [Theory] [PlatformSpecific(TestPlatforms.AnyUnix & ~TestPlatforms.OSX)] [InlineData(false, OpenFlags.ReadOnly)] [InlineData(true, OpenFlags.ReadOnly)] [InlineData(false, OpenFlags.ReadWrite)] [InlineData(true, OpenFlags.ReadWrite)] [InlineData(false, OpenFlags.MaxAllowed)] [InlineData(true, OpenFlags.MaxAllowed)] public static void UnixCannotOpenMachineDisallowedStore(bool useEnum, OpenFlags openFlags) { X509Store store = useEnum ? new X509Store(StoreName.Disallowed, StoreLocation.LocalMachine) // Non-normative casing, proving that we aren't case-sensitive (Windows isn't) : new X509Store("disallowed", StoreLocation.LocalMachine); using (store) { Exception e = Assert.Throws<CryptographicException>(() => store.Open(openFlags)); Assert.NotNull(e.InnerException); Assert.IsType<PlatformNotSupportedException>(e.InnerException); Assert.Equal(e.Message, e.InnerException.Message); } } [Theory] [PlatformSpecific(TestPlatforms.AnyUnix & ~TestPlatforms.OSX)] [InlineData(false, OpenFlags.ReadOnly)] [InlineData(true, OpenFlags.ReadOnly)] [InlineData(false, OpenFlags.ReadWrite)] [InlineData(true, OpenFlags.ReadWrite)] [InlineData(false, OpenFlags.MaxAllowed)] [InlineData(true, OpenFlags.MaxAllowed)] public static void UnixCannotModifyDisallowedStore(bool useEnum, OpenFlags openFlags) { X509Store store = useEnum ? new X509Store(StoreName.Disallowed, StoreLocation.CurrentUser) // Non-normative casing, proving that we aren't case-sensitive (Windows isn't) : new X509Store("disallowed", StoreLocation.CurrentUser); using (store) using (X509Certificate2 cert = new X509Certificate2(TestData.Rsa384CertificatePemBytes)) { store.Open(openFlags); Exception e = Assert.Throws<CryptographicException>(() => store.Add(cert)); if (openFlags == OpenFlags.ReadOnly) { Assert.Null(e.InnerException); } else { Assert.NotNull(e.InnerException); Assert.IsType<PlatformNotSupportedException>(e.InnerException); Assert.Equal(e.Message, e.InnerException.Message); } Assert.Equal(0, store.Certificates.Count); } } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/api/http.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Google.Api { /// <summary>Holder for reflection information generated from google/api/http.proto</summary> public static partial class HttpReflection { #region Descriptor /// <summary>File descriptor for google/api/http.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static HttpReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "ChVnb29nbGUvYXBpL2h0dHAucHJvdG8SCmdvb2dsZS5hcGkiKwoESHR0cBIj", "CgVydWxlcxgBIAMoCzIULmdvb2dsZS5hcGkuSHR0cFJ1bGUi6gEKCEh0dHBS", "dWxlEhAKCHNlbGVjdG9yGAEgASgJEg0KA2dldBgCIAEoCUgAEg0KA3B1dBgD", "IAEoCUgAEg4KBHBvc3QYBCABKAlIABIQCgZkZWxldGUYBSABKAlIABIPCgVw", "YXRjaBgGIAEoCUgAEi8KBmN1c3RvbRgIIAEoCzIdLmdvb2dsZS5hcGkuQ3Vz", "dG9tSHR0cFBhdHRlcm5IABIMCgRib2R5GAcgASgJEjEKE2FkZGl0aW9uYWxf", "YmluZGluZ3MYCyADKAsyFC5nb29nbGUuYXBpLkh0dHBSdWxlQgkKB3BhdHRl", "cm4iLwoRQ3VzdG9tSHR0cFBhdHRlcm4SDAoEa2luZBgBIAEoCRIMCgRwYXRo", "GAIgASgJQmoKDmNvbS5nb29nbGUuYXBpQglIdHRwUHJvdG9QAVpBZ29vZ2xl", "LmdvbGFuZy5vcmcvZ2VucHJvdG8vZ29vZ2xlYXBpcy9hcGkvYW5ub3RhdGlv", "bnM7YW5ub3RhdGlvbnP4AQGiAgRHQVBJYgZwcm90bzM=")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Api.Http), global::Google.Api.Http.Parser, new[]{ "Rules" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Api.HttpRule), global::Google.Api.HttpRule.Parser, new[]{ "Selector", "Get", "Put", "Post", "Delete", "Patch", "Custom", "Body", "AdditionalBindings" }, new[]{ "Pattern" }, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Api.CustomHttpPattern), global::Google.Api.CustomHttpPattern.Parser, new[]{ "Kind", "Path" }, null, null, null) })); } #endregion } #region Messages /// <summary> /// Defines the HTTP configuration for a service. It contains a list of /// [HttpRule][google.api.HttpRule], each specifying the mapping of an RPC method /// to one or more HTTP REST API methods. /// </summary> public sealed partial class Http : pb::IMessage<Http> { private static readonly pb::MessageParser<Http> _parser = new pb::MessageParser<Http>(() => new Http()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<Http> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Api.HttpReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Http() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Http(Http other) : this() { rules_ = other.rules_.Clone(); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Http Clone() { return new Http(this); } /// <summary>Field number for the "rules" field.</summary> public const int RulesFieldNumber = 1; private static readonly pb::FieldCodec<global::Google.Api.HttpRule> _repeated_rules_codec = pb::FieldCodec.ForMessage(10, global::Google.Api.HttpRule.Parser); private readonly pbc::RepeatedField<global::Google.Api.HttpRule> rules_ = new pbc::RepeatedField<global::Google.Api.HttpRule>(); /// <summary> /// A list of HTTP configuration rules that apply to individual API methods. /// /// **NOTE:** All service configuration rules follow "last one wins" order. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::Google.Api.HttpRule> Rules { get { return rules_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as Http); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(Http other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if(!rules_.Equals(other.rules_)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; hash ^= rules_.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { rules_.WriteTo(output, _repeated_rules_codec); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; size += rules_.CalculateSize(_repeated_rules_codec); return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(Http other) { if (other == null) { return; } rules_.Add(other.rules_); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { rules_.AddEntriesFrom(input, _repeated_rules_codec); break; } } } } } /// <summary> /// `HttpRule` defines the mapping of an RPC method to one or more HTTP /// REST APIs. The mapping determines what portions of the request /// message are populated from the path, query parameters, or body of /// the HTTP request. The mapping is typically specified as an /// `google.api.http` annotation, see "google/api/annotations.proto" /// for details. /// /// The mapping consists of a field specifying the path template and /// method kind. The path template can refer to fields in the request /// message, as in the example below which describes a REST GET /// operation on a resource collection of messages: /// /// service Messaging { /// rpc GetMessage(GetMessageRequest) returns (Message) { /// option (google.api.http).get = "/v1/messages/{message_id}/{sub.subfield}"; /// } /// } /// message GetMessageRequest { /// message SubMessage { /// string subfield = 1; /// } /// string message_id = 1; // mapped to the URL /// SubMessage sub = 2; // `sub.subfield` is url-mapped /// } /// message Message { /// string text = 1; // content of the resource /// } /// /// The same http annotation can alternatively be expressed inside the /// `GRPC API Configuration` YAML file. /// /// http: /// rules: /// - selector: &lt;proto_package_name>.Messaging.GetMessage /// get: /v1/messages/{message_id}/{sub.subfield} /// /// This definition enables an automatic, bidrectional mapping of HTTP /// JSON to RPC. Example: /// /// HTTP | RPC /// -----|----- /// `GET /v1/messages/123456/foo` | `GetMessage(message_id: "123456" sub: SubMessage(subfield: "foo"))` /// /// In general, not only fields but also field paths can be referenced /// from a path pattern. Fields mapped to the path pattern cannot be /// repeated and must have a primitive (non-message) type. /// /// Any fields in the request message which are not bound by the path /// pattern automatically become (optional) HTTP query /// parameters. Assume the following definition of the request message: /// /// message GetMessageRequest { /// message SubMessage { /// string subfield = 1; /// } /// string message_id = 1; // mapped to the URL /// int64 revision = 2; // becomes a parameter /// SubMessage sub = 3; // `sub.subfield` becomes a parameter /// } /// /// This enables a HTTP JSON to RPC mapping as below: /// /// HTTP | RPC /// -----|----- /// `GET /v1/messages/123456?revision=2&amp;sub.subfield=foo` | `GetMessage(message_id: "123456" revision: 2 sub: SubMessage(subfield: "foo"))` /// /// Note that fields which are mapped to HTTP parameters must have a /// primitive type or a repeated primitive type. Message types are not /// allowed. In the case of a repeated type, the parameter can be /// repeated in the URL, as in `...?param=A&amp;param=B`. /// /// For HTTP method kinds which allow a request body, the `body` field /// specifies the mapping. Consider a REST update method on the /// message resource collection: /// /// service Messaging { /// rpc UpdateMessage(UpdateMessageRequest) returns (Message) { /// option (google.api.http) = { /// put: "/v1/messages/{message_id}" /// body: "message" /// }; /// } /// } /// message UpdateMessageRequest { /// string message_id = 1; // mapped to the URL /// Message message = 2; // mapped to the body /// } /// /// The following HTTP JSON to RPC mapping is enabled, where the /// representation of the JSON in the request body is determined by /// protos JSON encoding: /// /// HTTP | RPC /// -----|----- /// `PUT /v1/messages/123456 { "text": "Hi!" }` | `UpdateMessage(message_id: "123456" message { text: "Hi!" })` /// /// The special name `*` can be used in the body mapping to define that /// every field not bound by the path template should be mapped to the /// request body. This enables the following alternative definition of /// the update method: /// /// service Messaging { /// rpc UpdateMessage(Message) returns (Message) { /// option (google.api.http) = { /// put: "/v1/messages/{message_id}" /// body: "*" /// }; /// } /// } /// message Message { /// string message_id = 1; /// string text = 2; /// } /// /// The following HTTP JSON to RPC mapping is enabled: /// /// HTTP | RPC /// -----|----- /// `PUT /v1/messages/123456 { "text": "Hi!" }` | `UpdateMessage(message_id: "123456" text: "Hi!")` /// /// Note that when using `*` in the body mapping, it is not possible to /// have HTTP parameters, as all fields not bound by the path end in /// the body. This makes this option more rarely used in practice of /// defining REST APIs. The common usage of `*` is in custom methods /// which don't use the URL at all for transferring data. /// /// It is possible to define multiple HTTP methods for one RPC by using /// the `additional_bindings` option. Example: /// /// service Messaging { /// rpc GetMessage(GetMessageRequest) returns (Message) { /// option (google.api.http) = { /// get: "/v1/messages/{message_id}" /// additional_bindings { /// get: "/v1/users/{user_id}/messages/{message_id}" /// } /// }; /// } /// } /// message GetMessageRequest { /// string message_id = 1; /// string user_id = 2; /// } /// /// This enables the following two alternative HTTP JSON to RPC /// mappings: /// /// HTTP | RPC /// -----|----- /// `GET /v1/messages/123456` | `GetMessage(message_id: "123456")` /// `GET /v1/users/me/messages/123456` | `GetMessage(user_id: "me" message_id: "123456")` /// /// # Rules for HTTP mapping /// /// The rules for mapping HTTP path, query parameters, and body fields /// to the request message are as follows: /// /// 1. The `body` field specifies either `*` or a field path, or is /// omitted. If omitted, it assumes there is no HTTP body. /// 2. Leaf fields (recursive expansion of nested messages in the /// request) can be classified into three types: /// (a) Matched in the URL template. /// (b) Covered by body (if body is `*`, everything except (a) fields; /// else everything under the body field) /// (c) All other fields. /// 3. URL query parameters found in the HTTP request are mapped to (c) fields. /// 4. Any body sent with an HTTP request can contain only (b) fields. /// /// The syntax of the path template is as follows: /// /// Template = "/" Segments [ Verb ] ; /// Segments = Segment { "/" Segment } ; /// Segment = "*" | "**" | LITERAL | Variable ; /// Variable = "{" FieldPath [ "=" Segments ] "}" ; /// FieldPath = IDENT { "." IDENT } ; /// Verb = ":" LITERAL ; /// /// The syntax `*` matches a single path segment. It follows the semantics of /// [RFC 6570](https://tools.ietf.org/html/rfc6570) Section 3.2.2 Simple String /// Expansion. /// /// The syntax `**` matches zero or more path segments. It follows the semantics /// of [RFC 6570](https://tools.ietf.org/html/rfc6570) Section 3.2.3 Reserved /// Expansion. NOTE: it must be the last segment in the path except the Verb. /// /// The syntax `LITERAL` matches literal text in the URL path. /// /// The syntax `Variable` matches the entire path as specified by its template; /// this nested template must not contain further variables. If a variable /// matches a single path segment, its template may be omitted, e.g. `{var}` /// is equivalent to `{var=*}`. /// /// NOTE: the field paths in variables and in the `body` must not refer to /// repeated fields or map fields. /// /// Use CustomHttpPattern to specify any HTTP method that is not included in the /// `pattern` field, such as HEAD, or "*" to leave the HTTP method unspecified for /// a given URL path rule. The wild-card rule is useful for services that provide /// content to Web (HTML) clients. /// </summary> public sealed partial class HttpRule : pb::IMessage<HttpRule> { private static readonly pb::MessageParser<HttpRule> _parser = new pb::MessageParser<HttpRule>(() => new HttpRule()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<HttpRule> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Api.HttpReflection.Descriptor.MessageTypes[1]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public HttpRule() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public HttpRule(HttpRule other) : this() { selector_ = other.selector_; body_ = other.body_; additionalBindings_ = other.additionalBindings_.Clone(); switch (other.PatternCase) { case PatternOneofCase.Get: Get = other.Get; break; case PatternOneofCase.Put: Put = other.Put; break; case PatternOneofCase.Post: Post = other.Post; break; case PatternOneofCase.Delete: Delete = other.Delete; break; case PatternOneofCase.Patch: Patch = other.Patch; break; case PatternOneofCase.Custom: Custom = other.Custom.Clone(); break; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public HttpRule Clone() { return new HttpRule(this); } /// <summary>Field number for the "selector" field.</summary> public const int SelectorFieldNumber = 1; private string selector_ = ""; /// <summary> /// Selects methods to which this rule applies. /// /// Refer to [selector][google.api.DocumentationRule.selector] for syntax details. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Selector { get { return selector_; } set { selector_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "get" field.</summary> public const int GetFieldNumber = 2; /// <summary> /// Used for listing and getting information about resources. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Get { get { return patternCase_ == PatternOneofCase.Get ? (string) pattern_ : ""; } set { pattern_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); patternCase_ = PatternOneofCase.Get; } } /// <summary>Field number for the "put" field.</summary> public const int PutFieldNumber = 3; /// <summary> /// Used for updating a resource. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Put { get { return patternCase_ == PatternOneofCase.Put ? (string) pattern_ : ""; } set { pattern_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); patternCase_ = PatternOneofCase.Put; } } /// <summary>Field number for the "post" field.</summary> public const int PostFieldNumber = 4; /// <summary> /// Used for creating a resource. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Post { get { return patternCase_ == PatternOneofCase.Post ? (string) pattern_ : ""; } set { pattern_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); patternCase_ = PatternOneofCase.Post; } } /// <summary>Field number for the "delete" field.</summary> public const int DeleteFieldNumber = 5; /// <summary> /// Used for deleting a resource. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Delete { get { return patternCase_ == PatternOneofCase.Delete ? (string) pattern_ : ""; } set { pattern_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); patternCase_ = PatternOneofCase.Delete; } } /// <summary>Field number for the "patch" field.</summary> public const int PatchFieldNumber = 6; /// <summary> /// Used for updating a resource. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Patch { get { return patternCase_ == PatternOneofCase.Patch ? (string) pattern_ : ""; } set { pattern_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); patternCase_ = PatternOneofCase.Patch; } } /// <summary>Field number for the "custom" field.</summary> public const int CustomFieldNumber = 8; /// <summary> /// Custom pattern is used for defining custom verbs. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Api.CustomHttpPattern Custom { get { return patternCase_ == PatternOneofCase.Custom ? (global::Google.Api.CustomHttpPattern) pattern_ : null; } set { pattern_ = value; patternCase_ = value == null ? PatternOneofCase.None : PatternOneofCase.Custom; } } /// <summary>Field number for the "body" field.</summary> public const int BodyFieldNumber = 7; private string body_ = ""; /// <summary> /// The name of the request field whose value is mapped to the HTTP body, or /// `*` for mapping all fields not captured by the path pattern to the HTTP /// body. NOTE: the referred field must not be a repeated field and must be /// present at the top-level of request message type. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Body { get { return body_; } set { body_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "additional_bindings" field.</summary> public const int AdditionalBindingsFieldNumber = 11; private static readonly pb::FieldCodec<global::Google.Api.HttpRule> _repeated_additionalBindings_codec = pb::FieldCodec.ForMessage(90, global::Google.Api.HttpRule.Parser); private readonly pbc::RepeatedField<global::Google.Api.HttpRule> additionalBindings_ = new pbc::RepeatedField<global::Google.Api.HttpRule>(); /// <summary> /// Additional HTTP bindings for the selector. Nested bindings must /// not contain an `additional_bindings` field themselves (that is, /// the nesting may only be one level deep). /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::Google.Api.HttpRule> AdditionalBindings { get { return additionalBindings_; } } private object pattern_; /// <summary>Enum of possible cases for the "pattern" oneof.</summary> public enum PatternOneofCase { None = 0, Get = 2, Put = 3, Post = 4, Delete = 5, Patch = 6, Custom = 8, } private PatternOneofCase patternCase_ = PatternOneofCase.None; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public PatternOneofCase PatternCase { get { return patternCase_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void ClearPattern() { patternCase_ = PatternOneofCase.None; pattern_ = null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as HttpRule); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(HttpRule other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Selector != other.Selector) return false; if (Get != other.Get) return false; if (Put != other.Put) return false; if (Post != other.Post) return false; if (Delete != other.Delete) return false; if (Patch != other.Patch) return false; if (!object.Equals(Custom, other.Custom)) return false; if (Body != other.Body) return false; if(!additionalBindings_.Equals(other.additionalBindings_)) return false; if (PatternCase != other.PatternCase) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Selector.Length != 0) hash ^= Selector.GetHashCode(); if (patternCase_ == PatternOneofCase.Get) hash ^= Get.GetHashCode(); if (patternCase_ == PatternOneofCase.Put) hash ^= Put.GetHashCode(); if (patternCase_ == PatternOneofCase.Post) hash ^= Post.GetHashCode(); if (patternCase_ == PatternOneofCase.Delete) hash ^= Delete.GetHashCode(); if (patternCase_ == PatternOneofCase.Patch) hash ^= Patch.GetHashCode(); if (patternCase_ == PatternOneofCase.Custom) hash ^= Custom.GetHashCode(); if (Body.Length != 0) hash ^= Body.GetHashCode(); hash ^= additionalBindings_.GetHashCode(); hash ^= (int) patternCase_; return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Selector.Length != 0) { output.WriteRawTag(10); output.WriteString(Selector); } if (patternCase_ == PatternOneofCase.Get) { output.WriteRawTag(18); output.WriteString(Get); } if (patternCase_ == PatternOneofCase.Put) { output.WriteRawTag(26); output.WriteString(Put); } if (patternCase_ == PatternOneofCase.Post) { output.WriteRawTag(34); output.WriteString(Post); } if (patternCase_ == PatternOneofCase.Delete) { output.WriteRawTag(42); output.WriteString(Delete); } if (patternCase_ == PatternOneofCase.Patch) { output.WriteRawTag(50); output.WriteString(Patch); } if (Body.Length != 0) { output.WriteRawTag(58); output.WriteString(Body); } if (patternCase_ == PatternOneofCase.Custom) { output.WriteRawTag(66); output.WriteMessage(Custom); } additionalBindings_.WriteTo(output, _repeated_additionalBindings_codec); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Selector.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Selector); } if (patternCase_ == PatternOneofCase.Get) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Get); } if (patternCase_ == PatternOneofCase.Put) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Put); } if (patternCase_ == PatternOneofCase.Post) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Post); } if (patternCase_ == PatternOneofCase.Delete) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Delete); } if (patternCase_ == PatternOneofCase.Patch) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Patch); } if (patternCase_ == PatternOneofCase.Custom) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Custom); } if (Body.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Body); } size += additionalBindings_.CalculateSize(_repeated_additionalBindings_codec); return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(HttpRule other) { if (other == null) { return; } if (other.Selector.Length != 0) { Selector = other.Selector; } if (other.Body.Length != 0) { Body = other.Body; } additionalBindings_.Add(other.additionalBindings_); switch (other.PatternCase) { case PatternOneofCase.Get: Get = other.Get; break; case PatternOneofCase.Put: Put = other.Put; break; case PatternOneofCase.Post: Post = other.Post; break; case PatternOneofCase.Delete: Delete = other.Delete; break; case PatternOneofCase.Patch: Patch = other.Patch; break; case PatternOneofCase.Custom: Custom = other.Custom; break; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Selector = input.ReadString(); break; } case 18: { Get = input.ReadString(); break; } case 26: { Put = input.ReadString(); break; } case 34: { Post = input.ReadString(); break; } case 42: { Delete = input.ReadString(); break; } case 50: { Patch = input.ReadString(); break; } case 58: { Body = input.ReadString(); break; } case 66: { global::Google.Api.CustomHttpPattern subBuilder = new global::Google.Api.CustomHttpPattern(); if (patternCase_ == PatternOneofCase.Custom) { subBuilder.MergeFrom(Custom); } input.ReadMessage(subBuilder); Custom = subBuilder; break; } case 90: { additionalBindings_.AddEntriesFrom(input, _repeated_additionalBindings_codec); break; } } } } } /// <summary> /// A custom pattern is used for defining custom HTTP verb. /// </summary> public sealed partial class CustomHttpPattern : pb::IMessage<CustomHttpPattern> { private static readonly pb::MessageParser<CustomHttpPattern> _parser = new pb::MessageParser<CustomHttpPattern>(() => new CustomHttpPattern()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<CustomHttpPattern> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Api.HttpReflection.Descriptor.MessageTypes[2]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public CustomHttpPattern() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public CustomHttpPattern(CustomHttpPattern other) : this() { kind_ = other.kind_; path_ = other.path_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public CustomHttpPattern Clone() { return new CustomHttpPattern(this); } /// <summary>Field number for the "kind" field.</summary> public const int KindFieldNumber = 1; private string kind_ = ""; /// <summary> /// The name of this custom HTTP verb. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Kind { get { return kind_; } set { kind_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "path" field.</summary> public const int PathFieldNumber = 2; private string path_ = ""; /// <summary> /// The path matched by this custom verb. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Path { get { return path_; } set { path_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as CustomHttpPattern); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(CustomHttpPattern other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Kind != other.Kind) return false; if (Path != other.Path) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Kind.Length != 0) hash ^= Kind.GetHashCode(); if (Path.Length != 0) hash ^= Path.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Kind.Length != 0) { output.WriteRawTag(10); output.WriteString(Kind); } if (Path.Length != 0) { output.WriteRawTag(18); output.WriteString(Path); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Kind.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Kind); } if (Path.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Path); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(CustomHttpPattern other) { if (other == null) { return; } if (other.Kind.Length != 0) { Kind = other.Kind; } if (other.Path.Length != 0) { Path = other.Path; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Kind = input.ReadString(); break; } case 18: { Path = input.ReadString(); break; } } } } } #endregion } #endregion Designer generated code
using System; using System.IO; using System.Collections.Generic; using RestSharp; using IO.Swagger.Client; using IO.Swagger.Model; namespace IO.Swagger.Api { /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public interface IPairsApi { /// <summary> /// Get pairs /// </summary> /// <remarks> /// Pairs cause measurements with effect measurements grouped over the duration of action after the onset delay. /// </remarks> /// <param name="cause">Original variable name for the explanatory or independent variable</param> /// <param name="effect">Original variable name for the outcome or dependent variable</param> /// <param name="causeSource">Name of data source that the cause measurements should come from</param> /// <param name="causeUnit">Abbreviated name for the unit cause measurements to be returned in</param> /// <param name="delay">Delay before onset of action (in seconds) from the cause variable settings.</param> /// <param name="duration">Duration of action (in seconds) from the cause variable settings.</param> /// <param name="effectSource">Name of data source that the effectmeasurements should come from</param> /// <param name="effectUnit">Abbreviated name for the unit effect measurements to be returned in</param> /// <param name="endTime">The most recent date (in epoch time) for which we should return measurements</param> /// <param name="startTime">The earliest date (in epoch time) for which we should return measurements</param> /// <param name="limit">The LIMIT is used to limit the number of results returned. So if you have 1000 results, but only want to the first 10, you would set this to 10 and offset to 0.</param> /// <param name="offset">Now suppose you wanted to show results 11-20. You&#39;d set the offset to 10 and the limit to 10.</param> /// <param name="sort">Sort by given field. If the field is prefixed with `-, it will sort in descending order.</param> /// <returns></returns> List<Pairs> V1PairsGet (string cause, string effect, string causeSource, string causeUnit, string delay, string duration, string effectSource, string effectUnit, string endTime, string startTime, int? limit, int? offset, int? sort); /// <summary> /// Get pairs /// </summary> /// <remarks> /// Pairs cause measurements with effect measurements grouped over the duration of action after the onset delay. /// </remarks> /// <param name="cause">Original variable name for the explanatory or independent variable</param> /// <param name="effect">Original variable name for the outcome or dependent variable</param> /// <param name="causeSource">Name of data source that the cause measurements should come from</param> /// <param name="causeUnit">Abbreviated name for the unit cause measurements to be returned in</param> /// <param name="delay">Delay before onset of action (in seconds) from the cause variable settings.</param> /// <param name="duration">Duration of action (in seconds) from the cause variable settings.</param> /// <param name="effectSource">Name of data source that the effectmeasurements should come from</param> /// <param name="effectUnit">Abbreviated name for the unit effect measurements to be returned in</param> /// <param name="endTime">The most recent date (in epoch time) for which we should return measurements</param> /// <param name="startTime">The earliest date (in epoch time) for which we should return measurements</param> /// <param name="limit">The LIMIT is used to limit the number of results returned. So if you have 1000 results, but only want to the first 10, you would set this to 10 and offset to 0.</param> /// <param name="offset">Now suppose you wanted to show results 11-20. You&#39;d set the offset to 10 and the limit to 10.</param> /// <param name="sort">Sort by given field. If the field is prefixed with `-, it will sort in descending order.</param> /// <returns></returns> System.Threading.Tasks.Task<List<Pairs>> V1PairsGetAsync (string cause, string effect, string causeSource, string causeUnit, string delay, string duration, string effectSource, string effectUnit, string endTime, string startTime, int? limit, int? offset, int? sort); } /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public class PairsApi : IPairsApi { /// <summary> /// Initializes a new instance of the <see cref="PairsApi"/> class. /// </summary> /// <param name="apiClient"> an instance of ApiClient (optional)</param> /// <returns></returns> public PairsApi(ApiClient apiClient = null) { if (apiClient == null) // use the default one in Configuration this.ApiClient = Configuration.DefaultApiClient; else this.ApiClient = apiClient; } /// <summary> /// Initializes a new instance of the <see cref="PairsApi"/> class. /// </summary> /// <returns></returns> public PairsApi(String basePath) { this.ApiClient = new ApiClient(basePath); } /// <summary> /// Sets the base path of the API client. /// </summary> /// <param name="basePath">The base path</param> /// <value>The base path</value> public void SetBasePath(String basePath) { this.ApiClient.BasePath = basePath; } /// <summary> /// Gets the base path of the API client. /// </summary> /// <value>The base path</value> public String GetBasePath() { return this.ApiClient.BasePath; } /// <summary> /// Gets or sets the API client. /// </summary> /// <value>An instance of the ApiClient</value> public ApiClient ApiClient {get; set;} /// <summary> /// Get pairs Pairs cause measurements with effect measurements grouped over the duration of action after the onset delay. /// </summary> /// <param name="cause">Original variable name for the explanatory or independent variable</param> /// <param name="effect">Original variable name for the outcome or dependent variable</param> /// <param name="causeSource">Name of data source that the cause measurements should come from</param> /// <param name="causeUnit">Abbreviated name for the unit cause measurements to be returned in</param> /// <param name="delay">Delay before onset of action (in seconds) from the cause variable settings.</param> /// <param name="duration">Duration of action (in seconds) from the cause variable settings.</param> /// <param name="effectSource">Name of data source that the effectmeasurements should come from</param> /// <param name="effectUnit">Abbreviated name for the unit effect measurements to be returned in</param> /// <param name="endTime">The most recent date (in epoch time) for which we should return measurements</param> /// <param name="startTime">The earliest date (in epoch time) for which we should return measurements</param> /// <param name="limit">The LIMIT is used to limit the number of results returned. So if you have 1000 results, but only want to the first 10, you would set this to 10 and offset to 0.</param> /// <param name="offset">Now suppose you wanted to show results 11-20. You&#39;d set the offset to 10 and the limit to 10.</param> /// <param name="sort">Sort by given field. If the field is prefixed with `-, it will sort in descending order.</param> /// <returns></returns> public List<Pairs> V1PairsGet (string cause, string effect, string causeSource, string causeUnit, string delay, string duration, string effectSource, string effectUnit, string endTime, string startTime, int? limit, int? offset, int? sort) { // verify the required parameter 'cause' is set if (cause == null) throw new ApiException(400, "Missing required parameter 'cause' when calling V1PairsGet"); // verify the required parameter 'effect' is set if (effect == null) throw new ApiException(400, "Missing required parameter 'effect' when calling V1PairsGet"); var path = "/v1/pairs"; var pathParams = new Dictionary<String, String>(); var queryParams = new Dictionary<String, String>(); var headerParams = new Dictionary<String, String>(); var formParams = new Dictionary<String, String>(); var fileParams = new Dictionary<String, FileParameter>(); String postBody = null; // to determine the Accept header String[] http_header_accepts = new String[] { "application/json" }; String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); if (http_header_accept != null) headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); if (cause != null) queryParams.Add("cause", ApiClient.ParameterToString(cause)); // query parameter if (causeSource != null) queryParams.Add("causeSource", ApiClient.ParameterToString(causeSource)); // query parameter if (causeUnit != null) queryParams.Add("causeUnit", ApiClient.ParameterToString(causeUnit)); // query parameter if (delay != null) queryParams.Add("delay", ApiClient.ParameterToString(delay)); // query parameter if (duration != null) queryParams.Add("duration", ApiClient.ParameterToString(duration)); // query parameter if (effect != null) queryParams.Add("effect", ApiClient.ParameterToString(effect)); // query parameter if (effectSource != null) queryParams.Add("effectSource", ApiClient.ParameterToString(effectSource)); // query parameter if (effectUnit != null) queryParams.Add("effectUnit", ApiClient.ParameterToString(effectUnit)); // query parameter if (endTime != null) queryParams.Add("endTime", ApiClient.ParameterToString(endTime)); // query parameter if (startTime != null) queryParams.Add("startTime", ApiClient.ParameterToString(startTime)); // query parameter if (limit != null) queryParams.Add("limit", ApiClient.ParameterToString(limit)); // query parameter if (offset != null) queryParams.Add("offset", ApiClient.ParameterToString(offset)); // query parameter if (sort != null) queryParams.Add("sort", ApiClient.ParameterToString(sort)); // query parameter // authentication setting, if any String[] authSettings = new String[] { "oauth2" }; // make the HTTP request IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling V1PairsGet: " + response.Content, response.Content); else if (((int)response.StatusCode) == 0) throw new ApiException ((int)response.StatusCode, "Error calling V1PairsGet: " + response.ErrorMessage, response.ErrorMessage); return (List<Pairs>) ApiClient.Deserialize(response.Content, typeof(List<Pairs>), response.Headers); } /// <summary> /// Get pairs Pairs cause measurements with effect measurements grouped over the duration of action after the onset delay. /// </summary> /// <param name="cause">Original variable name for the explanatory or independent variable</param> /// <param name="effect">Original variable name for the outcome or dependent variable</param> /// <param name="causeSource">Name of data source that the cause measurements should come from</param> /// <param name="causeUnit">Abbreviated name for the unit cause measurements to be returned in</param> /// <param name="delay">Delay before onset of action (in seconds) from the cause variable settings.</param> /// <param name="duration">Duration of action (in seconds) from the cause variable settings.</param> /// <param name="effectSource">Name of data source that the effectmeasurements should come from</param> /// <param name="effectUnit">Abbreviated name for the unit effect measurements to be returned in</param> /// <param name="endTime">The most recent date (in epoch time) for which we should return measurements</param> /// <param name="startTime">The earliest date (in epoch time) for which we should return measurements</param> /// <param name="limit">The LIMIT is used to limit the number of results returned. So if you have 1000 results, but only want to the first 10, you would set this to 10 and offset to 0.</param> /// <param name="offset">Now suppose you wanted to show results 11-20. You&#39;d set the offset to 10 and the limit to 10.</param> /// <param name="sort">Sort by given field. If the field is prefixed with `-, it will sort in descending order.</param> /// <returns></returns> public async System.Threading.Tasks.Task<List<Pairs>> V1PairsGetAsync (string cause, string effect, string causeSource, string causeUnit, string delay, string duration, string effectSource, string effectUnit, string endTime, string startTime, int? limit, int? offset, int? sort) { // verify the required parameter 'cause' is set if (cause == null) throw new ApiException(400, "Missing required parameter 'cause' when calling V1PairsGet"); // verify the required parameter 'effect' is set if (effect == null) throw new ApiException(400, "Missing required parameter 'effect' when calling V1PairsGet"); var path = "/v1/pairs"; var pathParams = new Dictionary<String, String>(); var queryParams = new Dictionary<String, String>(); var headerParams = new Dictionary<String, String>(); var formParams = new Dictionary<String, String>(); var fileParams = new Dictionary<String, FileParameter>(); String postBody = null; // to determine the Accept header String[] http_header_accepts = new String[] { "application/json" }; String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); if (http_header_accept != null) headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); if (cause != null) queryParams.Add("cause", ApiClient.ParameterToString(cause)); // query parameter if (causeSource != null) queryParams.Add("causeSource", ApiClient.ParameterToString(causeSource)); // query parameter if (causeUnit != null) queryParams.Add("causeUnit", ApiClient.ParameterToString(causeUnit)); // query parameter if (delay != null) queryParams.Add("delay", ApiClient.ParameterToString(delay)); // query parameter if (duration != null) queryParams.Add("duration", ApiClient.ParameterToString(duration)); // query parameter if (effect != null) queryParams.Add("effect", ApiClient.ParameterToString(effect)); // query parameter if (effectSource != null) queryParams.Add("effectSource", ApiClient.ParameterToString(effectSource)); // query parameter if (effectUnit != null) queryParams.Add("effectUnit", ApiClient.ParameterToString(effectUnit)); // query parameter if (endTime != null) queryParams.Add("endTime", ApiClient.ParameterToString(endTime)); // query parameter if (startTime != null) queryParams.Add("startTime", ApiClient.ParameterToString(startTime)); // query parameter if (limit != null) queryParams.Add("limit", ApiClient.ParameterToString(limit)); // query parameter if (offset != null) queryParams.Add("offset", ApiClient.ParameterToString(offset)); // query parameter if (sort != null) queryParams.Add("sort", ApiClient.ParameterToString(sort)); // query parameter // authentication setting, if any String[] authSettings = new String[] { "oauth2" }; // make the HTTP request IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling V1PairsGet: " + response.Content, response.Content); return (List<Pairs>) ApiClient.Deserialize(response.Content, typeof(List<Pairs>), response.Headers); } } }
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // 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 Microsoft.Azure.Commands.Common.Authentication.Models; using Microsoft.Azure.Commands.Management.Storage.Models; using Microsoft.Azure.Management.Storage; using Microsoft.Azure.Management.Storage.Models; using Microsoft.WindowsAzure.Commands.Common.Storage; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Auth; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Management.Automation; using System.Text; using System.Xml; using System.Xml.Linq; using System.Xml.Serialization; namespace Microsoft.Azure.Commands.Compute.Common { public static class DiagnosticsHelper { private static string EncodedXmlCfg = "xmlCfg"; private static string WadCfg = "WadCfg"; private static string WadCfgBlob = "WadCfgBlob"; private static string StorageAccount = "storageAccount"; private static string Path = "path"; private static string ExpandResourceDirectory = "expandResourceDirectory"; private static string LocalResourceDirectory = "localResourceDirectory"; private static string StorageAccountNameTag = "storageAccountName"; private static string StorageAccountKeyTag = "storageAccountKey"; private static string StorageAccountEndPointTag = "storageAccountEndPoint"; public static string XmlNamespace = "http://schemas.microsoft.com/ServiceHosting/2010/10/DiagnosticsConfiguration"; public static string DiagnosticsConfigurationElemStr = "DiagnosticsConfiguration"; public static string DiagnosticMonitorConfigurationElemStr = "DiagnosticMonitorConfiguration"; public static string PublicConfigElemStr = "PublicConfig"; public static string PrivateConfigElemStr = "PrivateConfig"; public static string StorageAccountElemStr = "StorageAccount"; public static string PrivConfNameAttr = "name"; public static string PrivConfKeyAttr = "key"; public static string PrivConfEndpointAttr = "endpoint"; public static string MetricsElemStr = "Metrics"; public static string MetricsResourceIdAttr = "resourceId"; public static string EventHubElemStr = "EventHub"; public static string EventHubUrlAttr = "Url"; public static string EventHubSharedAccessKeyNameAttr = "SharedAccessKeyName"; public static string EventHubSharedAccessKeyAttr = "SharedAccessKey"; public enum ConfigFileType { Unknown, Json, Xml } public static ConfigFileType GetConfigFileType(string configurationPath) { if (!string.IsNullOrEmpty(configurationPath)) { try { XmlDocument doc = new XmlDocument(); doc.Load(configurationPath); return ConfigFileType.Xml; } catch (XmlException) { } try { JsonConvert.DeserializeObject(File.ReadAllText(configurationPath)); return ConfigFileType.Json; } catch (JsonReaderException) { } } return ConfigFileType.Unknown; } public static Hashtable GetPublicDiagnosticsConfigurationFromFile(string configurationPath, string storageAccountName, string resourceId, Cmdlet cmdlet) { switch (GetConfigFileType(configurationPath)) { case ConfigFileType.Xml: return GetPublicConfigFromXmlFile(configurationPath, storageAccountName, resourceId, cmdlet); case ConfigFileType.Json: return GetPublicConfigFromJsonFile(configurationPath, storageAccountName, resourceId, cmdlet); default: throw new ArgumentException(Properties.Resources.DiagnosticsExtensionInvalidConfigFileFormat); } } private static Hashtable GetPublicConfigFromXmlFile(string configurationPath, string storageAccountName, string resourceId, Cmdlet cmdlet) { var doc = XDocument.Load(configurationPath); var wadCfgElement = doc.Descendants().FirstOrDefault(d => d.Name.LocalName == WadCfg); var wadCfgBlobElement = doc.Descendants().FirstOrDefault(d => d.Name.LocalName == WadCfgBlob); if (wadCfgElement == null && wadCfgBlobElement == null) { throw new ArgumentException(Properties.Resources.DiagnosticsExtensionIaaSConfigElementNotDefinedInXml); } if (wadCfgElement != null) { AutoFillMetricsConfig(wadCfgElement, resourceId, cmdlet); } string originalConfiguration = wadCfgElement != null ? wadCfgElement.ToString() : wadCfgBlobElement.ToString(); string encodedConfiguration = Convert.ToBase64String(Encoding.UTF8.GetBytes(wadCfgElement.ToString().ToCharArray())); // Now extract the local resource directory element var node = doc.Descendants().FirstOrDefault(e => e.Name.LocalName == "LocalResourceDirectory"); string localDirectory = (node != null && node.Attribute(Path) != null) ? node.Attribute(Path).Value : null; string localDirectoryExpand = (node != null && node.Attribute("expandEnvironment") != null) ? node.Attribute("expandEnvironment").Value : null; if (localDirectoryExpand == "0") { localDirectoryExpand = "false"; } if (localDirectoryExpand == "1") { localDirectoryExpand = "true"; } var hashTable = new Hashtable(); hashTable.Add(EncodedXmlCfg, encodedConfiguration); hashTable.Add(StorageAccount, storageAccountName); if (!string.IsNullOrEmpty(localDirectory)) { var localDirectoryHashTable = new Hashtable(); localDirectoryHashTable.Add(Path, localDirectory); localDirectoryHashTable.Add(ExpandResourceDirectory, localDirectoryExpand); hashTable.Add(LocalResourceDirectory, localDirectoryHashTable); } return hashTable; } private static void AutoFillMetricsConfig(XElement wadCfgElement, string resourceId, Cmdlet cmdlet) { if (string.IsNullOrEmpty(resourceId)) { return; } var configurationElem = wadCfgElement.Elements().FirstOrDefault(d => d.Name.LocalName == DiagnosticMonitorConfigurationElemStr); if (configurationElem == null) { throw new ArgumentException(Properties.Resources.DiagnosticsExtensionDiagnosticMonitorConfigurationElementNotDefined); } var metricsElement = configurationElem.Elements().FirstOrDefault(d => d.Name.LocalName == MetricsElemStr); if (metricsElement == null) { XNamespace ns = XmlNamespace; metricsElement = new XElement(ns + MetricsElemStr, new XAttribute(MetricsResourceIdAttr, resourceId)); configurationElem.Add(metricsElement); } else { var resourceIdAttr = metricsElement.Attribute(MetricsResourceIdAttr); if (resourceIdAttr != null && !resourceIdAttr.Value.Equals(resourceId)) { cmdlet.WriteWarning(Properties.Resources.DiagnosticsExtensionMetricsResourceIdNotMatch); } metricsElement.SetAttributeValue(MetricsResourceIdAttr, resourceId); } } private static Hashtable GetPublicConfigFromJsonFile(string configurationPath, string storageAccountName, string resourceId, Cmdlet cmdlet) { var publicConfig = GetPublicConfigJObjectFromJsonFile(configurationPath); var properties = publicConfig.Properties().Select(p => p.Name); var wadCfgProperty = properties.FirstOrDefault(p => p.Equals(WadCfg, StringComparison.OrdinalIgnoreCase)); var wadCfgBlobProperty = properties.FirstOrDefault(p => p.Equals(WadCfgBlob, StringComparison.OrdinalIgnoreCase)); var xmlCfgProperty = properties.FirstOrDefault(p => p.Equals(EncodedXmlCfg, StringComparison.OrdinalIgnoreCase)); var hashTable = new Hashtable(); hashTable.Add(StorageAccount, storageAccountName); if (wadCfgProperty != null && publicConfig[wadCfgProperty] is JObject) { var wadCfgObject = (JObject)publicConfig[wadCfgProperty]; AutoFillMetricsConfig(wadCfgObject, resourceId, cmdlet); hashTable.Add(wadCfgProperty, wadCfgObject); } else if (wadCfgBlobProperty != null) { hashTable.Add(wadCfgBlobProperty, publicConfig[wadCfgBlobProperty]); } else if (xmlCfgProperty != null) { hashTable.Add(xmlCfgProperty, publicConfig[xmlCfgProperty]); } else { throw new ArgumentException(Properties.Resources.DiagnosticsExtensionIaaSConfigElementNotDefinedInJson); } return hashTable; } private static void AutoFillMetricsConfig(JObject wadCfgObject, string resourceId, Cmdlet cmdlet) { if (string.IsNullOrEmpty(resourceId)) { return; } var configObject = wadCfgObject[DiagnosticMonitorConfigurationElemStr] as JObject; if (configObject == null) { throw new ArgumentException(Properties.Resources.DiagnosticsExtensionDiagnosticMonitorConfigurationElementNotDefined); } var metricsObject = configObject[MetricsElemStr] as JObject; if (metricsObject == null) { configObject.Add(new JProperty(MetricsElemStr, new JObject( new JProperty(MetricsResourceIdAttr, resourceId)))); } else { var resourceIdValue = metricsObject[MetricsResourceIdAttr] as JValue; if (resourceIdValue != null && !resourceIdValue.Value.Equals(resourceId)) { cmdlet.WriteWarning(Properties.Resources.DiagnosticsExtensionMetricsResourceIdNotMatch); } metricsObject[MetricsResourceIdAttr] = resourceId; } } public static Hashtable GetPrivateDiagnosticsConfiguration(string configurationPath, string storageAccountName, string storageKey, string endpoint) { var privateConfig = new Hashtable(); var configFileType = GetConfigFileType(configurationPath); if (configFileType == ConfigFileType.Xml) { var doc = XDocument.Load(configurationPath); var privateConfigElement = doc.Descendants().FirstOrDefault(d => d.Name.LocalName == PrivateConfigElemStr); if (privateConfigElement != null) { // Unfortunately, there is no easy way to convert the xml config to json config without involving a schema file. // We take the schema file generated by the .xsd file, and let the serializer doing the conversion work for us. // NOTE: this file need to be updated whenever the private schema is changed. XmlSerializer serializer = new XmlSerializer(typeof(Cis.Monitoring.Wad.PrivateConfigConverter.PrivateConfig)); using (StringReader sr = new StringReader(privateConfigElement.ToString())) { var config = (Cis.Monitoring.Wad.PrivateConfigConverter.PrivateConfig)serializer.Deserialize(sr); // Set the StorageAccount element as null, so it won't appear after serialize to json config.StorageAccount = null; var privateConfigInJson = JsonConvert.SerializeObject(config, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }); privateConfig = JsonConvert.DeserializeObject<Hashtable>(privateConfigInJson); } } } else if (configFileType == ConfigFileType.Json) { // Find the PrivateConfig var jsonConfig = JsonConvert.DeserializeObject<JObject>(File.ReadAllText(configurationPath)); var hasPrivateConfig = jsonConfig.Properties().Any(p => p.Name.Equals(PrivateConfigElemStr)); if (hasPrivateConfig) { privateConfig = JsonConvert.DeserializeObject<Hashtable>(jsonConfig[PrivateConfigElemStr].ToString()); } } privateConfig[StorageAccountNameTag] = storageAccountName; privateConfig[StorageAccountKeyTag] = storageKey; privateConfig[StorageAccountEndPointTag] = endpoint; return privateConfig; } private static void AddEventHubPrivateConfig(Hashtable privateConfig, string configurationPath) { var eventHubUrl = GetConfigValueFromPrivateConfig(configurationPath, EventHubElemStr, EventHubUrlAttr); var eventHubSharedAccessKeyName = GetConfigValueFromPrivateConfig(configurationPath, EventHubElemStr, EventHubSharedAccessKeyNameAttr); var eventHubSharedAccessKey = GetConfigValueFromPrivateConfig(configurationPath, EventHubElemStr, EventHubSharedAccessKeyAttr); if (!string.IsNullOrEmpty(eventHubUrl) || !string.IsNullOrEmpty(eventHubSharedAccessKeyName) || !string.IsNullOrEmpty(eventHubSharedAccessKey)) { var eventHubConfig = new Hashtable(); eventHubConfig.Add(EventHubUrlAttr, eventHubUrl); eventHubConfig.Add(EventHubSharedAccessKeyNameAttr, eventHubSharedAccessKeyName); eventHubConfig.Add(EventHubSharedAccessKeyAttr, eventHubSharedAccessKey); privateConfig.Add(EventHubElemStr, eventHubConfig); } } private static XElement GetPublicConfigXElementFromXmlFile(string configurationPath) { XElement publicConfig = null; if (!string.IsNullOrEmpty(configurationPath)) { var xmlConfig = XElement.Load(configurationPath); if (xmlConfig.Name.LocalName == PublicConfigElemStr) { // The passed in config file is public config publicConfig = xmlConfig; } else if (xmlConfig.Name.LocalName == DiagnosticsConfigurationElemStr) { // The passed in config file is .wadcfgx file publicConfig = xmlConfig.Elements().FirstOrDefault(ele => ele.Name.LocalName == PublicConfigElemStr); } } return publicConfig; } private static JObject GetPublicConfigJObjectFromJsonFile(string configurationPath) { var config = JsonConvert.DeserializeObject<JObject>(File.ReadAllText(configurationPath)); var properties = config.Properties().Select(p => p.Name); // If the json config has the public config as a property, we extract it. Otherwise, the root object is the public config. var publicConfigProperty = properties.FirstOrDefault(p => p.Equals(PublicConfigElemStr, StringComparison.OrdinalIgnoreCase)); var publicConfig = publicConfigProperty == null ? config : config[publicConfigProperty] as JObject; return publicConfig; } /// <summary> /// Get the private config value for a specific attribute. /// The private config looks like this: /// XML: /// <PrivateConfig xmlns="namespace"> /// <StorageAccount name = "name" key="key" endpoint="endpoint" /> /// <EventHub Url = "url" SharedAccessKeyName="sasKeyName" SharedAccessKey="sasKey"/> /// </PrivateConfig> /// /// JSON: /// "PrivateConfig":{ /// "storageAccountName":"name", /// "storageAccountKey":"key", /// "storageAccountEndPoint":"endpoint", /// "EventHub":{ /// "Url":"url", /// "SharedAccessKeyName":"sasKeyName", /// "SharedAccessKey":"sasKey" /// } /// } /// </summary> /// <param name="configurationPath">The path to the configuration file</param> /// <param name="elementName">The element name of the private config. e.g., StorageAccount, EventHub</param> /// <param name="attributeName">The attribute name of the element</param> /// <returns></returns> public static string GetConfigValueFromPrivateConfig(string configurationPath, string elementName, string attributeName) { string value = string.Empty; var configFileType = GetConfigFileType(configurationPath); if (configFileType == ConfigFileType.Xml) { var xmlConfig = XElement.Load(configurationPath); if (xmlConfig.Name.LocalName == DiagnosticsConfigurationElemStr) { var privateConfigElem = xmlConfig.Elements().FirstOrDefault(ele => ele.Name.LocalName == PrivateConfigElemStr); var configElem = privateConfigElem == null ? null : privateConfigElem.Elements().FirstOrDefault(ele => ele.Name.LocalName == elementName); var attribute = configElem == null ? null : configElem.Attributes().FirstOrDefault(a => string.Equals(a.Name.LocalName, attributeName)); value = attribute == null ? null : attribute.Value; } } else if (configFileType == ConfigFileType.Json) { // Find the PrivateConfig var jsonConfig = JsonConvert.DeserializeObject<JObject>(File.ReadAllText(configurationPath)); var properties = jsonConfig.Properties().Select(p => p.Name); var privateConfigProperty = properties.FirstOrDefault(p => p.Equals(PrivateConfigElemStr)); if (privateConfigProperty == null) { return value; } var privateConfig = jsonConfig[privateConfigProperty] as JObject; // Find the target config object corresponding to elementName JObject targetConfig = null; if (elementName == StorageAccountElemStr) { // Special handling as private storage config is flattened targetConfig = privateConfig; var attributeNameMapping = new Dictionary<string, string>() { { PrivConfNameAttr, "storageAccountName" }, { PrivConfKeyAttr, "storageAccountKey" }, { PrivConfEndpointAttr, "storageAccountEndPoint" } }; attributeName = attributeNameMapping.FirstOrDefault(m => m.Key == attributeName).Value; } else { properties = privateConfig.Properties().Select(p => p.Name); var configProperty = properties.FirstOrDefault(p => p.Equals(elementName)); targetConfig = configProperty == null ? null : privateConfig[configProperty] as JObject; } if (targetConfig == null || attributeName == null) { return value; } // Find the config value corresponding to attributeName properties = targetConfig.Properties().Select(p => p.Name); var attributeProperty = properties.FirstOrDefault(p => p.Equals(attributeName)); value = attributeProperty == null ? null : targetConfig[attributeProperty].Value<string>(); } return value; } /// <summary> /// Initialize the storage account name if it's not specified. /// It can be defined in multiple places, we only take the one with higher precedence. And the precedence is: /// 1. The one get from StorageContext parameter /// 2. The one parsed from the diagnostics configuration file /// </summary> public static string InitializeStorageAccountName(AzureStorageContext storageContext = null, string configurationPath = null) { string storageAccountName = null; var configFileType = GetConfigFileType(configurationPath); if (storageContext != null) { storageAccountName = storageContext.StorageAccountName; } else if (configFileType == ConfigFileType.Xml) { var publicConfig = GetPublicConfigXElementFromXmlFile(configurationPath); var storageNode = publicConfig == null ? null : publicConfig.Elements().FirstOrDefault(ele => ele.Name.LocalName == StorageAccountElemStr); storageAccountName = storageNode == null ? null : storageNode.Value; } else if (configFileType == ConfigFileType.Json) { var publicConfig = GetPublicConfigJObjectFromJsonFile(configurationPath); var properties = publicConfig.Properties().Select(p => p.Name); var storageAccountProperty = properties.FirstOrDefault(p => p.Equals(StorageAccount, StringComparison.OrdinalIgnoreCase)); storageAccountName = storageAccountProperty == null ? null : publicConfig[storageAccountProperty].Value<string>(); } return storageAccountName; } /// <summary> /// Initialize the storage account key if it's not specified. /// It can be defined in multiple places, we only take the one with higher precedence. And the precedence is: /// 1. The one we try to resolve within current subscription /// 2. The one defined in PrivateConfig in the configuration file /// </summary> public static string InitializeStorageAccountKey(IStorageManagementClient storageClient, string storageAccountName = null, string configurationPath = null) { string storageAccountKey = null; StorageAccount storageAccount = null; if (TryGetStorageAccount(storageClient, storageAccountName, out storageAccount)) { // Help user retrieve the storage account key var credentials = StorageUtilities.GenerateStorageCredentials(new ARMStorageProvider(storageClient), ARMStorageService.ParseResourceGroupFromId(storageAccount.Id), storageAccount.Name); storageAccountKey = credentials.ExportBase64EncodedKey(); } else { // Use the one defined in PrivateConfig storageAccountKey = GetConfigValueFromPrivateConfig(configurationPath, StorageAccountElemStr, PrivConfKeyAttr); } return storageAccountKey; } /// <summary> /// Initialize the storage account endpoint if it's not specified. /// We can get the value from multiple places, we only take the one with higher precedence. And the precedence is: /// 1. The one get from StorageContext parameter /// 2. The one get from the storage account /// 3. The one get from PrivateConfig element in config file /// 4. The one get from current Azure Environment /// </summary> public static string InitializeStorageAccountEndpoint(string storageAccountName, string storageAccountKey, IStorageManagementClient storageClient, AzureStorageContext storageContext = null, string configurationPath = null, AzureContext defaultContext = null) { string storageAccountEndpoint = null; StorageAccount storageAccount = null; if (storageContext != null) { // Get value from StorageContext storageAccountEndpoint = GetEndpointFromStorageContext(storageContext); } else if (TryGetStorageAccount(storageClient, storageAccountName, out storageAccount)) { // Get value from StorageAccount var endpoints = storageAccount.PrimaryEndpoints; var context = CreateStorageContext(endpoints.Blob, endpoints.Queue, endpoints.Table, endpoints.File, storageAccountName, storageAccountKey); storageAccountEndpoint = GetEndpointFromStorageContext(context); } else if (!string.IsNullOrEmpty( storageAccountEndpoint = GetConfigValueFromPrivateConfig(configurationPath, StorageAccountElemStr, PrivConfEndpointAttr))) { // We can get the value from PrivateConfig } else if (defaultContext != null && defaultContext.Environment != null) { // Get value from default azure environment. Default to use https Uri blobEndpoint = defaultContext.Environment.GetStorageBlobEndpoint(storageAccountName); Uri queueEndpoint = defaultContext.Environment.GetStorageQueueEndpoint(storageAccountName); Uri tableEndpoint = defaultContext.Environment.GetStorageTableEndpoint(storageAccountName); Uri fileEndpoint = defaultContext.Environment.GetStorageFileEndpoint(storageAccountName); var context = CreateStorageContext(blobEndpoint, queueEndpoint, tableEndpoint, fileEndpoint, storageAccountName, storageAccountKey); storageAccountEndpoint = GetEndpointFromStorageContext(context); } return storageAccountEndpoint; } private static bool TryGetStorageAccount(IStorageManagementClient storageClient, string storageAccountName, out StorageAccount storageAccount) { try { var storageAccounts = storageClient.StorageAccounts.List().StorageAccounts; storageAccount = storageAccounts == null ? null : storageAccounts.FirstOrDefault(account => account.Name.Equals(storageAccountName)); } catch { storageAccount = null; } return storageAccount != null; } private static AzureStorageContext CreateStorageContext(Uri blobEndpoint, Uri queueEndpoint, Uri tableEndpoint, Uri fileEndpoint, string storageAccountName, string storageAccountKey) { var credentials = new StorageCredentials(storageAccountName, storageAccountKey); var cloudStorageAccount = new CloudStorageAccount(credentials, blobEndpoint, queueEndpoint, tableEndpoint, fileEndpoint); return new AzureStorageContext(cloudStorageAccount); } private static string GetEndpointFromStorageContext(AzureStorageContext context) { var scheme = context.BlobEndPoint.StartsWith("https://", StringComparison.OrdinalIgnoreCase) ? "https://" : "http://"; return scheme + context.EndPointSuffix; } } }
/***************************************************************************\ * * File: EffectiveValueEntry.cs * * This file describes an entry in the EffectiveValues list held by a * DependencyObject. * * Copyright (C) 2005 by Microsoft Corporation. All rights reserved. * \***************************************************************************/ using MS.Internal.WindowsBase; // FriendAccessAllowed using System.Collections; // IDictionary using System.Diagnostics; // Debug.Assert namespace System.Windows { [FriendAccessAllowed] // Built into Base, also used by Core & Framework. internal struct EffectiveValueEntry { #region InternalMethods internal static EffectiveValueEntry CreateDefaultValueEntry(DependencyProperty dp, object value) { EffectiveValueEntry entry = new EffectiveValueEntry(dp, BaseValueSourceInternal.Default); entry.Value = value; return entry; } internal EffectiveValueEntry(DependencyProperty dp) { _propertyIndex = (short) dp.GlobalIndex; _value = null; _source = (FullValueSource) BaseValueSourceInternal.Unknown; } internal EffectiveValueEntry(DependencyProperty dp, BaseValueSourceInternal valueSource) { _propertyIndex = (short) dp.GlobalIndex; _value = DependencyProperty.UnsetValue; _source = (FullValueSource) valueSource; } internal EffectiveValueEntry(DependencyProperty dp, FullValueSource fullValueSource) { _propertyIndex = (short) dp.GlobalIndex; _value = DependencyProperty.UnsetValue; _source = fullValueSource; } internal void SetExpressionValue(object value, object baseValue) { Debug.Assert(value != DependencyProperty.UnsetValue); ModifiedValue modifiedValue = EnsureModifiedValue(); modifiedValue.ExpressionValue = value; IsExpression = true; IsDeferredReference = value is DeferredReference; Debug.Assert(Object.Equals(modifiedValue.BaseValue, baseValue)); Debug.Assert(!(baseValue is DeferredReference)); Debug.Assert(IsDeferredReference == (value is DeferredReference)); } internal void SetAnimatedValue(object value, object baseValue) { Debug.Assert((value != DependencyProperty.UnsetValue) && !(value is DeferredReference)); ModifiedValue modifiedValue = EnsureModifiedValue(); modifiedValue.AnimatedValue = value; IsAnimated = true; // Animated values should never be deferred IsDeferredReference = false; Debug.Assert(!(modifiedValue.AnimatedValue is DeferredReference)); Debug.Assert(Object.Equals(modifiedValue.BaseValue, baseValue) || Object.Equals(modifiedValue.ExpressionValue, baseValue)); Debug.Assert(!(baseValue is DeferredReference) && ! (modifiedValue.BaseValue is DeferredReference) && ! (modifiedValue.ExpressionValue is DeferredReference)); } internal void SetCoercedValue(object value, object baseValue, bool skipBaseValueChecks, bool coerceWithCurrentValue) { Debug.Assert(value != DependencyProperty.UnsetValue && !((value is DeferredReference) && !coerceWithCurrentValue)); // if this is already a CoercedWithControlValue entry, we are applying a // second coercion (e.g. from the CoerceValueCallback). The baseValue // passed in is the result of the control-value coercion, but for the // purposes of this method we should use the original base value instead. if (IsCoercedWithCurrentValue) { baseValue = ModifiedValue.BaseValue; } ModifiedValue modifiedValue = EnsureModifiedValue(coerceWithCurrentValue); modifiedValue.CoercedValue = value; IsCoerced = true; IsCoercedWithCurrentValue = coerceWithCurrentValue; // The only CoercedValues that can be deferred are Control values. if (coerceWithCurrentValue) { IsDeferredReference = (value is DeferredReference); } else { IsDeferredReference = false; } Debug.Assert(skipBaseValueChecks || Object.Equals(modifiedValue.BaseValue, baseValue) || Object.Equals(modifiedValue.ExpressionValue, baseValue) || Object.Equals(modifiedValue.AnimatedValue, baseValue)); Debug.Assert(!(baseValue is DeferredReference) && ! (modifiedValue.BaseValue is DeferredReference) && ! (modifiedValue.ExpressionValue is DeferredReference) && ! (modifiedValue.AnimatedValue is DeferredReference)); } internal void ResetAnimatedValue() { if (IsAnimated) { ModifiedValue modifiedValue = ModifiedValue; modifiedValue.AnimatedValue = null; IsAnimated = false; if (!HasModifiers) { Value = modifiedValue.BaseValue; } else { // The setter takes care of the IsDeferred flag no need to compute it twice. ComputeIsDeferred(); } } } internal void ResetCoercedValue() { if (IsCoerced) { ModifiedValue modifiedValue = ModifiedValue; modifiedValue.CoercedValue = null; IsCoerced = false; if (!HasModifiers) { Value = modifiedValue.BaseValue; } else { ComputeIsDeferred(); } } } // remove all modifiers, retain value source, and set value to supplied value internal void ResetValue(object value, bool hasExpressionMarker) { _source &= FullValueSource.ValueSourceMask; _value = value; if (hasExpressionMarker) { HasExpressionMarker = true; } else { ComputeIsDeferred(); } Debug.Assert(hasExpressionMarker == (value == DependencyObject.ExpressionInAlternativeStore), "hasExpressionMarker flag must match value"); } // add an expression marker back as the base value for an expression value internal void RestoreExpressionMarker() { if (HasModifiers) { ModifiedValue entry = ModifiedValue; entry.ExpressionValue = entry.BaseValue; entry.BaseValue = DependencyObject.ExpressionInAlternativeStore; _source |= FullValueSource.IsExpression | FullValueSource.HasExpressionMarker; //recompute the isDeferredReference flag as it may have changed ComputeIsDeferred(); } else { object value = Value; Value = DependencyObject.ExpressionInAlternativeStore; SetExpressionValue(value, DependencyObject.ExpressionInAlternativeStore); _source |= FullValueSource.HasExpressionMarker; } } // Computes and set the IsDeferred hint flag. // This take into account all flags and should only be used sparingly. private void ComputeIsDeferred() { bool isDeferredReference = false; if (!HasModifiers) { isDeferredReference = Value is DeferredReference; } else if (ModifiedValue != null) { if (IsCoercedWithCurrentValue) { isDeferredReference = ModifiedValue.CoercedValue is DeferredReference; } else if (IsExpression) { isDeferredReference = ModifiedValue.ExpressionValue is DeferredReference; } // For animated values isDeferred will always be false. } IsDeferredReference = isDeferredReference; } #endregion InternalMethods #region InternalProperties public int PropertyIndex { get { return _propertyIndex; } set { _propertyIndex = (short)value; } } /// <summary> /// If HasModifiers is true then it holds the value /// else it holds the modified value instance /// </summary> internal object Value { get { return _value; } set { _value = value; IsDeferredReference = value is DeferredReference; Debug.Assert(value is DeferredReference == IsDeferredReference); } } internal BaseValueSourceInternal BaseValueSourceInternal { get { return (BaseValueSourceInternal)(_source & FullValueSource.ValueSourceMask); } set { _source = (_source & ~FullValueSource.ValueSourceMask) | (FullValueSource)value; } } internal bool IsDeferredReference { get { // When this flag is true we treat it as a hint rather than a guarantee and update // it if is out of [....]. When the flag is false, however we expect it to guarantee // that the value isn't a DeferredReference. bool isDeferredReference = ReadPrivateFlag(FullValueSource.IsPotentiallyADeferredReference); if (isDeferredReference) { // Check if the value is really a deferred reference ComputeIsDeferred(); isDeferredReference = ReadPrivateFlag(FullValueSource.IsPotentiallyADeferredReference); } return isDeferredReference; } private set { WritePrivateFlag(FullValueSource.IsPotentiallyADeferredReference, value); } } internal bool IsExpression { get { return ReadPrivateFlag(FullValueSource.IsExpression); } private set { WritePrivateFlag(FullValueSource.IsExpression, value); } } internal bool IsAnimated { get { return ReadPrivateFlag(FullValueSource.IsAnimated); } private set { WritePrivateFlag(FullValueSource.IsAnimated, value); } } internal bool IsCoerced { get { return ReadPrivateFlag(FullValueSource.IsCoerced); } private set { WritePrivateFlag(FullValueSource.IsCoerced, value); } } internal bool HasModifiers { get { return (_source & FullValueSource.ModifiersMask) != 0; } } internal FullValueSource FullValueSource { get { return _source; } } internal bool HasExpressionMarker { get { return ReadPrivateFlag(FullValueSource.HasExpressionMarker); } set { WritePrivateFlag(FullValueSource.HasExpressionMarker, value); } } internal bool IsCoercedWithCurrentValue { get { return ReadPrivateFlag(FullValueSource.IsCoercedWithCurrentValue); } set { WritePrivateFlag(FullValueSource.IsCoercedWithCurrentValue, value); } } internal EffectiveValueEntry GetFlattenedEntry(RequestFlags requests) { if ((_source & (FullValueSource.ModifiersMask | FullValueSource.HasExpressionMarker)) == 0) { // If the property does not have any modifiers // then just return the base value. return this; } if (!HasModifiers) { Debug.Assert(HasExpressionMarker); // This is the case when some one stuck an expression into // an alternate store such as a style or a template but the // new value for the expression has not been evaluated yet. // In the intermediate we need to return the default value // for the property. This problem was manifested in DRTDocumentViewer. EffectiveValueEntry unsetEntry = new EffectiveValueEntry(); unsetEntry.BaseValueSourceInternal = BaseValueSourceInternal; unsetEntry.PropertyIndex = PropertyIndex; return unsetEntry; } // else entry has modifiers EffectiveValueEntry entry = new EffectiveValueEntry(); entry.BaseValueSourceInternal = BaseValueSourceInternal; entry.PropertyIndex = PropertyIndex; entry.IsDeferredReference = IsDeferredReference; // If the property has a modifier return the modified value Debug.Assert(ModifiedValue != null); // outside of DO, we flatten modified value ModifiedValue modifiedValue = ModifiedValue; // Note that the modified values have an order of precedence // 1. Coerced Value (including Current value) // 2. Animated Value // 3. Expression Value // Also note that we support any arbitrary combinations of these // modifiers and will yet the precedence metioned above. if (IsCoerced) { if ((requests & RequestFlags.CoercionBaseValue) == 0) { entry.Value = modifiedValue.CoercedValue; } else { // This is the case when CoerceValue tries to query // the old base value for the property if (IsCoercedWithCurrentValue) { entry.Value = modifiedValue.CoercedValue; } else if (IsAnimated && ((requests & RequestFlags.AnimationBaseValue) == 0)) { entry.Value = modifiedValue.AnimatedValue; } else if (IsExpression) { entry.Value = modifiedValue.ExpressionValue; } else { entry.Value = modifiedValue.BaseValue; } } } else if (IsAnimated) { if ((requests & RequestFlags.AnimationBaseValue) == 0) { entry.Value = modifiedValue.AnimatedValue; } else { // This is the case when [UI/Content]Element are // requesting the base value of an animation. if (IsExpression) { entry.Value = modifiedValue.ExpressionValue; } else { entry.Value = modifiedValue.BaseValue; } } } else { Debug.Assert(IsExpression == true); object expressionValue = modifiedValue.ExpressionValue; entry.Value = expressionValue; } Debug.Assert(entry.IsDeferredReference == (entry.Value is DeferredReference), "Value and DeferredReference flag should be in [....]; hitting this may mean that it's time to divide the DeferredReference flag into a set of flags, one for each modifier"); return entry; } internal void SetAnimationBaseValue(object animationBaseValue) { if (!HasModifiers) { Value = animationBaseValue; } else { ModifiedValue modifiedValue = ModifiedValue; if (IsExpression) { modifiedValue.ExpressionValue = animationBaseValue; } else { modifiedValue.BaseValue = animationBaseValue; } //the modified value may be a deferred reference so recompute this flag. ComputeIsDeferred(); } } internal void SetCoersionBaseValue(object coersionBaseValue) { if (!HasModifiers) { Value = coersionBaseValue; } else { ModifiedValue modifiedValue = ModifiedValue; if (IsAnimated) { modifiedValue.AnimatedValue = coersionBaseValue; } else if (IsExpression) { modifiedValue.ExpressionValue = coersionBaseValue; } else { modifiedValue.BaseValue = coersionBaseValue; } //the modified value may be a deferred reference so recompute this flag. ComputeIsDeferred(); } } internal object LocalValue { get { if (BaseValueSourceInternal == BaseValueSourceInternal.Local) { if (!HasModifiers) { Debug.Assert(Value != DependencyProperty.UnsetValue); return Value; } else { Debug.Assert(ModifiedValue != null && ModifiedValue.BaseValue != DependencyProperty.UnsetValue); return ModifiedValue.BaseValue; } } else { return DependencyProperty.UnsetValue; } } set { Debug.Assert(BaseValueSourceInternal == BaseValueSourceInternal.Local, "This can happen only on an entry already having a local value"); if (!HasModifiers) { Debug.Assert(Value != DependencyProperty.UnsetValue); Value = value; } else { Debug.Assert(ModifiedValue != null && ModifiedValue.BaseValue != DependencyProperty.UnsetValue); ModifiedValue.BaseValue = value; } } } internal ModifiedValue ModifiedValue { get { if (_value != null) { return _value as ModifiedValue; } return null; } } private ModifiedValue EnsureModifiedValue(bool useWeakReferenceForBaseValue=false) { ModifiedValue modifiedValue = null; if (_value == null) { _value = modifiedValue = new ModifiedValue(); } else { modifiedValue = _value as ModifiedValue; if (modifiedValue == null) { modifiedValue = new ModifiedValue(); modifiedValue.SetBaseValue(_value, useWeakReferenceForBaseValue); _value = modifiedValue; } } return modifiedValue; } internal void Clear() { _propertyIndex = -1; _value = null; _source = 0; } #endregion InternalProperties #region PrivateMethods private void WritePrivateFlag(FullValueSource bit, bool value) { if (value) { _source |= bit; } else { _source &= ~bit; } } private bool ReadPrivateFlag(FullValueSource bit) { return (_source & bit) != 0; } #endregion PrivateMethods #region Data private object _value; private short _propertyIndex; private FullValueSource _source; #endregion Data } [FriendAccessAllowed] // Built into Base, also used by Core & Framework. internal enum FullValueSource : short { // Bit used to store BaseValueSourceInternal = 0x01 // Bit used to store BaseValueSourceInternal = 0x02 // Bit used to store BaseValueSourceInternal = 0x04 // Bit used to store BaseValueSourceInternal = 0x08 ValueSourceMask = 0x000F, ModifiersMask = 0x0070, IsExpression = 0x0010, IsAnimated = 0x0020, IsCoerced = 0x0040, IsPotentiallyADeferredReference = 0x0080, HasExpressionMarker = 0x0100, IsCoercedWithCurrentValue = 0x200, } // Note that these enum values are arranged in the reverse order of // precendence for these sources. Local value has highest // precedence and Default value has the least. Note that we do not // store default values in the _effectiveValues cache unless it is // being coerced/animated. [FriendAccessAllowed] // Built into Base, also used by Core & Framework. internal enum BaseValueSourceInternal : short { Unknown = 0, Default = 1, Inherited = 2, ThemeStyle = 3, ThemeStyleTrigger = 4, Style = 5, TemplateTrigger = 6, StyleTrigger = 7, ImplicitReference = 8, ParentTemplate = 9, ParentTemplateTrigger = 10, Local = 11, } [FriendAccessAllowed] // Built into Base, also used by Core & Framework. internal class ModifiedValue { #region InternalProperties internal object BaseValue { get { BaseValueWeakReference wr = _baseValue as BaseValueWeakReference; return (wr != null) ? wr.Target : _baseValue; } set { _baseValue = value; } } internal object ExpressionValue { get { return _expressionValue; } set { _expressionValue = value; } } internal object AnimatedValue { get { return _animatedValue; } set { _animatedValue = value; } } internal object CoercedValue { get { return _coercedValue; } set { _coercedValue = value; } } internal void SetBaseValue(object value, bool useWeakReference) { _baseValue = (useWeakReference && !value.GetType().IsValueType) ? new BaseValueWeakReference(value) : value; } #endregion InternalProperties #region Data private object _baseValue; private object _expressionValue; private object _animatedValue; private object _coercedValue; class BaseValueWeakReference : WeakReference { public BaseValueWeakReference(object target) : base(target) {} } #endregion Data } }
// // RectilinearScanLine.cs // MSAGL ScanLine class for Rectilinear Edge Routing line generation. // // Copyright Microsoft Corporation. using System.Diagnostics; using System.Collections.Generic; using Microsoft.Msagl.Core.DataStructures; using Microsoft.Msagl.Core.Geometry; using Microsoft.Msagl.Core.Geometry.Curves; using Microsoft.Msagl.Core.Layout; using Microsoft.Msagl.DebugHelpers; using Microsoft.Msagl.Core; namespace Microsoft.Msagl.Routing.Rectilinear { internal class RectilinearScanLine : IComparer<BasicObstacleSide> { readonly ScanDirection scanDirection; // This is the data structure that allows fast insert/remove of obstacle edges as well as // scanning for next/prev edges along the direction of the scan line. RbTree<BasicObstacleSide> SideTree { get; set; } // Because sides may overlap and thus their relative positions change, retain the current // position, which is set on insertions by parameter, and by Overlap events via SetLinePosition. private Point linePositionAtLastInsertOrRemove; internal RectilinearScanLine(ScanDirection scanDir, Point start) { scanDirection = scanDir; SideTree = new RbTree<BasicObstacleSide>(this); this.linePositionAtLastInsertOrRemove = start; } internal RBNode<BasicObstacleSide> Insert(BasicObstacleSide side, Point scanPos) { DevTraceInfo(1, "prev LinePos = {0}, new LinePos = {1}, inserting side = {2}", this.linePositionAtLastInsertOrRemove, scanPos, side.ToString()); Assert(!scanDirection.IsFlat(side), "Flat sides are not allowed in the scanline"); Assert(null == Find(side), "side already exists in the ScanLine"); this.linePositionAtLastInsertOrRemove = scanPos; // RBTree's internal operations on insert/remove etc. mean the node can't cache the // RBNode returned by insert(); instead we must do find() on each call. But we can // use the returned node to get predecessor/successor. var node = SideTree.Insert(side); DevTraceDump(2); return node; } internal int Count { get { return SideTree.Count; } } internal void Remove(BasicObstacleSide side, Point scanPos) { DevTraceInfo(1, "current linePos = {0}, removing side = {1}", this.linePositionAtLastInsertOrRemove, side.ToString()); Assert(null != Find(side), "side does not exist in the ScanLine"); this.linePositionAtLastInsertOrRemove = scanPos; SideTree.Remove(side); DevTraceDump(2); } internal RBNode<BasicObstacleSide> Find(BasicObstacleSide side) { // Sides that start after the current position cannot be in the scanline. if (-1 == scanDirection.ComparePerpCoord(this.linePositionAtLastInsertOrRemove, side.Start)) { return null; } return SideTree.Find(side); } internal RBNode<BasicObstacleSide> NextLow(BasicObstacleSide side) { return NextLow(Find(side)); } internal RBNode<BasicObstacleSide> NextLow(RBNode<BasicObstacleSide> sideNode) { var pred = SideTree.Previous(sideNode); return pred; } internal RBNode<BasicObstacleSide> NextHigh(BasicObstacleSide side) { return NextHigh(Find(side)); } internal RBNode<BasicObstacleSide> NextHigh(RBNode<BasicObstacleSide> sideNode) { var succ = SideTree.Next(sideNode); return succ; } internal RBNode<BasicObstacleSide> Next(Directions dir, BasicObstacleSide side) { return Next(dir, Find(side)); } internal RBNode<BasicObstacleSide> Next(Directions dir, RBNode<BasicObstacleSide> sideNode) { var succ = (StaticGraphUtility.IsAscending(dir)) ? SideTree.Next(sideNode) : SideTree.Previous(sideNode); return succ; } internal RBNode<BasicObstacleSide> Lowest() { return SideTree.TreeMinimum(); } [Conditional("DEVTRACE")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")] // ReSharper disable InconsistentNaming internal void DevTrace_VerifyConsistency(string descFormat, params object[] descArgs) { // ReSharper restore InconsistentNaming #if DEVTRACE bool retval = true; if (scanLineVerify.IsLevel(1)) { DevTraceInfo(2, "ScanLineConsistencyCheck LinePos = {0}", this.linePositionAtLastInsertOrRemove); BasicObstacleSide prevSide = null; DevTraceInfo(3, "ScanLine dump {0}, count = {1}:", string.Format(descFormat, descArgs), SideTree.Count); foreach (var currentSide in SideTree) { DevTraceInfo(3, currentSide.ToString()); if ((null != prevSide) && (-1 != Compare(prevSide, currentSide))) { scanLineTrace.WriteError(0, "Sides are not strictly increasing:"); scanLineTrace.WriteFollowup(0, prevSide.ToString()); scanLineTrace.WriteFollowup(0, currentSide.ToString()); retval = false; } prevSide = currentSide; } } Assert(retval, "Sides are not strictly increasing"); #endif // DEVTRACE } #region IComparer<BasicObstacleSide> /// <summary> /// For ordering lines along the scanline at segment starts/ends. /// </summary> /// <param name="first"></param> /// <param name="second"></param> /// <returns></returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")] public int Compare(BasicObstacleSide first, BasicObstacleSide second) { ValidateArg.IsNotNull(first, "first"); ValidateArg.IsNotNull(second, "second"); // If these are two sides of the same obstacle then the ordering is obvious. if (first.Obstacle == second.Obstacle) { if (first == second) { return 0; } return (first is LowObstacleSide) ? -1 : 1; } Debug_VerifySidesDoNotIntersect(first, second); // Other than intersecting sides at vertices of the same obstacle, there should be no interior intersections... Point firstIntersect = VisibilityGraphGenerator.ScanLineIntersectSide(this.linePositionAtLastInsertOrRemove, first, scanDirection); Point secondIntersect = VisibilityGraphGenerator.ScanLineIntersectSide(this.linePositionAtLastInsertOrRemove, second, scanDirection); var cmp = firstIntersect.CompareTo(secondIntersect); // ... but we may still have rectangular sides that coincide, or angled sides that are close enough here but // are not detected by the convex-hull overlap calculations. In those cases, we refine the comparison by side // type, with High coming before Low, and then by obstacle ordinal if needed. Because there are no interior // intersections, this ordering will remain valid as long as the side(s) are in the scanline. if (0 == cmp) { bool firstIsLow = first is LowObstacleSide; bool secondIsLow = second is LowObstacleSide; cmp = firstIsLow.CompareTo(secondIsLow); if (0 == cmp) { cmp = first.Obstacle.Ordinal.CompareTo(second.Obstacle.Ordinal); } } DevTraceInfo(4, "Compare {0} @ {1:F5} {2:F5} and {3:F5} {4:F5}: {5} {6}", cmp, firstIntersect.X, firstIntersect.Y, secondIntersect.X, secondIntersect.Y, first, second); return cmp; } [Conditional("DEBUG")] internal static void Debug_VerifySidesDoNotIntersect(BasicObstacleSide side1, BasicObstacleSide side2) { Point intersect; if (!Point.LineLineIntersection(side1.Start, side1.End, side2.Start, side2.End, out intersect)) { return; } // The test for being within the interval is just multiplying to ensure that both subtractions // return same-signed results (including endpoints). var isInterior = ((side1.Start - intersect) * (intersect - side1.End) >= -ApproximateComparer.DistanceEpsilon) && ((side2.Start - intersect) * (intersect - side2.End) >= -ApproximateComparer.DistanceEpsilon); Debug.Assert(!isInterior, "Shouldn't have interior intersections except sides of the same obstacle"); } #endregion // IComparer<BasicObstacleSide> /// <summary> /// </summary> /// <returns></returns> public override string ToString() { return this.linePositionAtLastInsertOrRemove + " " + scanDirection; } [Conditional("DEBUG")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")] void Assert(bool condition, string message) { #if TEST_MSAGL if (!condition) { Test_DumpScanLine(); } #endif // TEST Debug.Assert(condition, message); } #region DevTrace #if DEVTRACE readonly DevTrace scanLineTrace = new DevTrace("Rectilinear_ScanLineTrace", "RectScanLine"); readonly DevTrace scanLineDump = new DevTrace("Rectilinear_ScanLineDump"); readonly DevTrace scanLineVerify = new DevTrace("Rectilinear_ScanLineVerify"); #endif // DEVTRACE [Conditional("DEVTRACE")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")] void DevTraceInfo(int verboseLevel, string format, params object[] args) { #if DEVTRACE scanLineTrace.WriteLineIf(DevTrace.Level.Info, verboseLevel, format, args); #endif // DEVTRACE } [Conditional("DEVTRACE")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")] void DevTraceDump(int verboseLevel) { #if DEVTRACE if (scanLineDump.IsLevel(verboseLevel)) { Test_DumpScanLine(); } #endif // DEVTRACE } #endregion // DevTrace #region DebugCurves [Conditional("TEST_MSAGL")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")] // ReSharper disable InconsistentNaming internal void Test_ShowScanLine() { #if TEST_MSAGL LayoutAlgorithmSettings.ShowDebugCurvesEnumeration(Test_GetScanLineDebugCurves()); #endif // TEST } [Conditional("TEST_MSAGL")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")] internal void Test_DumpScanLine() { #if TEST_MSAGL DebugCurveCollection.WriteToFile(Test_GetScanLineDebugCurves(), StaticGraphUtility.GetDumpFileName("ScanLine")); #endif // TEST } #if TEST_MSAGL internal List<DebugCurve> Test_GetScanLineDebugCurves() { // ReSharper restore InconsistentNaming var debugCurves = new List<DebugCurve>(); // Alternate the colors between green and blue, so that any inconsistency will stand out. // Use red to highlight that. string[] colors = { "green", "blue" }; int index = 0; var bbox = new Rectangle(); BasicObstacleSide prevSide = null; foreach (var currentSide in SideTree) { string color = colors[index]; index ^= 1; if (null == prevSide) { // Create this the first time through; adding to an empty rectangle leaves 0,0. bbox = new Rectangle(currentSide.Start, currentSide.End); } else { if (-1 != Compare(prevSide, currentSide)) { // Note: we toggled the index, so the red replaces the colour whose turn it is now // and will leave the red line bracketed by two sides of the same colour. color = "red"; } bbox.Add(currentSide.Start); bbox.Add(currentSide.End); } debugCurves.Add(new DebugCurve(0.1, color, new LineSegment(currentSide.Start, currentSide.End))); prevSide = currentSide; } // Add the sweep line. Point start = StaticGraphUtility.RectangleBorderIntersect(bbox, this.linePositionAtLastInsertOrRemove, scanDirection.OppositeDirection); Point end = StaticGraphUtility.RectangleBorderIntersect(bbox, this.linePositionAtLastInsertOrRemove, scanDirection.Direction); debugCurves.Add(new DebugCurve(0.025, "black", new LineSegment(start, end))); return debugCurves; } #endif // TEST #endregion // DebugCurves } }
using UnityEngine; using System; using System.Linq; using System.Collections.Generic; namespace NodeEditorFramework { public abstract partial class Node : ScriptableObject {// Host Canvas public NodeCanvas canvas; // Positioning public Vector2 position; private Vector2 autoSize; public Vector2 size { get { return AutoLayout? autoSize : DefaultSize; } } public Rect rect { get { return new Rect (position, size); } } public Rect fullAABBRect { get { return new Rect(position.x - 20, position.y - 20, size.x + 40, size.y + 40); } } // Dynamic connection ports public List<ConnectionPort> dynamicConnectionPorts = new List<ConnectionPort>(); // Static connection ports stored in the actual declaration variables [NonSerialized] public List<ConnectionPort> staticConnectionPorts = new List<ConnectionPort>(); // Representative lists of static port declarations aswell as dynamic ports [NonSerialized] public List<ConnectionPort> connectionPorts = new List<ConnectionPort> (); [NonSerialized] public List<ConnectionPort> inputPorts = new List<ConnectionPort> (); [NonSerialized] public List<ConnectionPort> outputPorts = new List<ConnectionPort> (); [NonSerialized] public List<ConnectionKnob> connectionKnobs = new List<ConnectionKnob> (); [NonSerialized] public List<ConnectionKnob> inputKnobs = new List<ConnectionKnob> (); [NonSerialized] public List<ConnectionKnob> outputKnobs = new List<ConnectionKnob> (); // Calculation graph [HideInInspector] [NonSerialized] public bool calculated = true; // Internal internal Vector2 contentOffset = Vector2.zero; internal Vector2 nodeGUIHeight; internal bool ignoreGUIKnobPlacement; internal bool isClipped; // Style public Color backgroundColor = Color.white; #region Properties and Settings /// <summary> /// Gets the ID of the Node /// </summary> public abstract string GetID { get; } /// <summary> /// Specifies the node title. /// </summary> public virtual string Title { get { #if UNITY_EDITOR return UnityEditor.ObjectNames.NicifyVariableName (GetID); #else return name; #endif } } /// <summary> /// Specifies the default size of the node when automatic resizing is turned off. /// </summary> public virtual Vector2 DefaultSize { get { return new Vector2(200, 100); } } /// <summary> /// Specifies whether the size of this node should be automatically calculated. /// If this is overridden to true, MinSize should be set, too. /// </summary> public virtual bool AutoLayout { get { return false; } } /// <summary> /// Specifies the minimum size the node can have if no content is present. /// </summary> public virtual Vector2 MinSize { get { return new Vector2(100, 50); } } /// <summary> /// Specifies if calculation should continue with the nodes connected to the outputs after the Calculation function returns success /// </summary> public virtual bool ContinueCalculation { get { return true; } } /// <summary> /// Specifies whether GUI requires to be updated even when the node is off-screen /// </summary> public virtual bool ForceGUIDrawOffScreen { get { return false; } } #endregion #region Node Implementation /// <summary> /// Initializes the node with Inputs/Outputs and other data if necessary. /// </summary> protected virtual void OnCreate() {} /// <summary> /// Draws the Node GUI including all controls and potentially Input/Output labels. /// By default, it displays all Input/Output labels. /// </summary> public virtual void NodeGUI () { GUILayout.BeginHorizontal (); GUILayout.BeginVertical (); for (int i = 0; i < inputKnobs.Count; i++) inputKnobs[i].DisplayLayout (); GUILayout.EndVertical (); GUILayout.BeginVertical (); for (int i = 0; i < outputKnobs.Count; i++) outputKnobs[i].DisplayLayout(); GUILayout.EndVertical (); GUILayout.EndHorizontal (); } /// <summary> /// Used to display a custom node property editor in the GUI. /// By default shows the standard NodeGUI. /// </summary> public virtual void DrawNodePropertyEditor (bool isEditorWindow = false) { try { // Draw Node GUI without disturbing knob placement ignoreGUIKnobPlacement = true; NodeEditorGUI.StartNodeGUI(isEditorWindow); GUILayout.BeginVertical(GUI.skin.box); NodeGUI(); GUILayout.EndVertical(); NodeEditorGUI.EndNodeGUI(); } finally { // Be sure to always reset the state to not mess up other GUI code ignoreGUIKnobPlacement = false; } } /// <summary> /// Calculates the outputs of this Node depending on the inputs. /// Returns success /// </summary> public virtual bool Calculate () { return true; } #endregion #region Callbacks /// <summary> /// Callback when the node is deleted /// </summary> protected internal virtual void OnDelete () {} /// <summary> /// Callback when the given port on this node was assigned a new connection /// </summary> protected internal virtual void OnAddConnection (ConnectionPort port, ConnectionPort connection) {} /// <summary> /// Callback when the given port has a connection that was removed. /// </summary> protected internal virtual void OnRemoveConnection (ConnectionPort port, ConnectionPort connection) {} /// <summary> /// Should return all additional ScriptableObjects this Node references /// </summary> public virtual ScriptableObject[] GetScriptableObjects () { return new ScriptableObject[0]; } /// <summary> /// Replaces all references to any ScriptableObjects this Node holds with the cloned versions in the serialization process. /// </summary> protected internal virtual void CopyScriptableObjects (System.Func<ScriptableObject, ScriptableObject> replaceSO) {} #endregion #region General /// <summary> /// Creates a node of the specified ID at pos on the current canvas, optionally auto-connecting the specified output to a matching input /// </summary> public static Node Create (string nodeID, Vector2 pos, ConnectionPort connectingPort = null, bool silent = false, bool init = true) { return Create (nodeID, pos, NodeEditor.curNodeCanvas, connectingPort, silent, init); } /// <summary> /// Creates a node of the specified ID at pos on the specified canvas, optionally auto-connecting the specified output to a matching input /// silent disables any events, init specifies whether OnCreate should be called /// </summary> public static Node Create (string nodeID, Vector2 pos, NodeCanvas hostCanvas, ConnectionPort connectingPort = null, bool silent = false, bool init = true) { if (string.IsNullOrEmpty (nodeID) || hostCanvas == null) throw new ArgumentException (); if (!NodeCanvasManager.CheckCanvasCompability (nodeID, hostCanvas.GetType ())) throw new UnityException ("Cannot create Node with ID '" + nodeID + "' as it is not compatible with the current canavs type (" + hostCanvas.GetType ().ToString () + ")!"); if (!hostCanvas.CanAddNode (nodeID)) throw new UnityException ("Cannot create Node with ID '" + nodeID + "' on the current canvas of type (" + hostCanvas.GetType ().ToString () + ")!"); // Create node from data NodeTypeData data = NodeTypes.getNodeData (nodeID); Node node = (Node)CreateInstance (data.type); if(node == null) return null; // Init node state node.canvas = hostCanvas; node.name = node.Title; node.autoSize = node.DefaultSize; node.position = pos; ConnectionPortManager.UpdateConnectionPorts (node); if (init) node.OnCreate(); if (connectingPort != null) { // Handle auto-connection and link the output to the first compatible input for (int i = 0; i < node.connectionPorts.Count; i++) { if (node.connectionPorts[i].TryApplyConnection (connectingPort, true)) break; } } // Add node to host canvas hostCanvas.nodes.Add (node); if (!silent) { // Callbacks hostCanvas.OnNodeChange(connectingPort != null ? connectingPort.body : node); NodeEditorCallbacks.IssueOnAddNode(node); hostCanvas.Validate(); NodeEditor.RepaintClients(); } #if UNITY_EDITOR if (!silent) { List<ConnectionPort> connectedPorts = new List<ConnectionPort>(); foreach (ConnectionPort port in node.connectionPorts) { // 'Encode' connected ports in one list (double level cannot be serialized) foreach (ConnectionPort conn in port.connections) connectedPorts.Add(conn); connectedPorts.Add(null); } Node createdNode = node; UndoPro.UndoProManager.RecordOperation( () => NodeEditorUndoActions.ReinstateNode(createdNode, connectedPorts), () => NodeEditorUndoActions.RemoveNode(createdNode), "Create Node"); // Make sure the new node is in the memory dump NodeEditorUndoActions.CompleteSOMemoryDump(hostCanvas); } #endif return node; } /// <summary> /// Deletes this Node from it's host canvas and the save file /// </summary> public void Delete (bool silent = false) { if (!canvas.nodes.Contains (this)) throw new UnityException ("The Node " + name + " does not exist on the Canvas " + canvas.name + "!"); if (!silent) NodeEditorCallbacks.IssueOnDeleteNode (this); #if UNITY_EDITOR if (!silent) { List<ConnectionPort> connectedPorts = new List<ConnectionPort>(); foreach (ConnectionPort port in connectionPorts) { // 'Encode' connected ports in one list (double level cannot be serialized) foreach (ConnectionPort conn in port.connections) connectedPorts.Add(conn); connectedPorts.Add(null); } Node deleteNode = this; UndoPro.UndoProManager.RecordOperation( () => NodeEditorUndoActions.RemoveNode(deleteNode), () => NodeEditorUndoActions.ReinstateNode(deleteNode, connectedPorts), "Delete Node"); // Make sure the deleted node is in the memory dump NodeEditorUndoActions.CompleteSOMemoryDump(canvas); } #endif canvas.nodes.Remove(this); for (int i = 0; i < connectionPorts.Count; i++) connectionPorts[i].ClearConnections(true); if (!silent) canvas.Validate (); } #endregion #region Drawing #if UNITY_EDITOR /// <summary> /// If overridden, the Node can draw to the scene view GUI in the Editor. /// </summary> public virtual void OnSceneGUI() { } #endif /// <summary> /// Draws the node frame and calls NodeGUI. Can be overridden to customize drawing. /// </summary> protected internal virtual void DrawNode () { // Create a rect that is adjusted to the editor zoom and pixel perfect Rect nodeRect = rect; Vector2 pos = NodeEditor.curEditorState.zoomPanAdjust + NodeEditor.curEditorState.panOffset; nodeRect.position = new Vector2((int)(nodeRect.x+pos.x), (int)(nodeRect.y+pos.y)); contentOffset = new Vector2 (0, 20); GUI.color = backgroundColor; // Create a headerRect out of the previous rect and draw it, marking the selected node as such by making the header bold Rect headerRect = new Rect (nodeRect.x, nodeRect.y, nodeRect.width, contentOffset.y); GUI.color = backgroundColor; GUI.Box (headerRect, GUIContent.none); GUI.color = Color.white; GUI.Label (headerRect, Title, GUI.skin.GetStyle (NodeEditor.curEditorState.selectedNode == this? "labelBoldCentered" : "labelCentered")); // Begin the body frame around the NodeGUI Rect bodyRect = new Rect (nodeRect.x, nodeRect.y + contentOffset.y, nodeRect.width, nodeRect.height - contentOffset.y); GUI.color = backgroundColor; GUI.BeginGroup (bodyRect, GUI.skin.box); GUI.color = Color.white; bodyRect.position = Vector2.zero; GUILayout.BeginArea (bodyRect); // Call NodeGUI GUI.changed = false; #if UNITY_EDITOR // Record changes done in the GUI function UnityEditor.Undo.RecordObject(this, "Node GUI"); #endif NodeGUI(); #if UNITY_EDITOR // Make sure it doesn't record anything else after this UnityEditor.Undo.FlushUndoRecordObjects(); #endif if(Event.current.type == EventType.Repaint) nodeGUIHeight = GUILayoutUtility.GetLastRect().max + contentOffset; // End NodeGUI frame GUILayout.EndArea (); GUI.EndGroup (); // Automatically node if desired AutoLayoutNode (); } /// <summary> /// Resizes the node to either the MinSize or to fit size of the GUILayout in NodeGUI /// </summary> protected internal virtual void AutoLayoutNode() { if (!AutoLayout || Event.current.type != EventType.Repaint) return; Rect nodeRect = rect; Vector2 size = new Vector2(); size.y = Math.Max(nodeGUIHeight.y, MinSize.y) + 4; // Account for potential knobs that might occupy horizontal space float knobSize = 0; List<ConnectionKnob> verticalKnobs = connectionKnobs.Where (x => x.side == NodeSide.Bottom || x.side == NodeSide.Top).ToList (); if (verticalKnobs.Count > 0) knobSize = verticalKnobs.Max ((ConnectionKnob knob) => knob.GetCanvasSpaceKnob ().xMax - nodeRect.xMin); size.x = Math.Max (knobSize, Math.Max (nodeGUIHeight.x, MinSize.x)); autoSize = size; NodeEditor.RepaintClients (); } /// <summary> /// Draws the connectionKnobs of this node /// </summary> protected internal virtual void DrawKnobs () { for (int i = 0; i < connectionKnobs.Count; i++) connectionKnobs[i].DrawKnob (); } /// <summary> /// Draws the connections from this node's connectionPorts /// </summary> protected internal virtual void DrawConnections () { if (Event.current.type != EventType.Repaint) return; for (int i = 0; i < outputPorts.Count; i++) outputPorts[i].DrawConnections (); } #endregion #region Node Utility /// <summary> /// Tests the node whether the specified position is inside any of the node's elements and returns a potentially focused connection knob. /// </summary> public bool ClickTest(Vector2 position, out ConnectionKnob focusedKnob) { focusedKnob = null; if (rect.Contains(position)) return true; Vector2 dist = position - rect.center; if (Math.Abs(dist.x) > size.x || Math.Abs(dist.y) > size.y) return false; // Quick check if pos is within double the size for (int i = 0; i < connectionKnobs.Count; i++) { // Check if any nodeKnob is focused instead if (connectionKnobs[i].GetCanvasSpaceKnob().Contains(position)) { focusedKnob = connectionKnobs[i]; return true; } } return false; } /// <summary> /// Returns whether the node acts as an input (no inputs or no inputs assigned) /// </summary> public bool isInput() { for (int i = 0; i < inputPorts.Count; i++) { if (inputPorts[i].connected()) return false; } return true; } /// <summary> /// Returns whether the node acts as an output (no outputs or no outputs assigned) /// </summary> public bool isOutput() { for (int i = 0; i < outputPorts.Count; i++) { if (outputPorts[i].connected()) return false; } return true; } /// <summary> /// Returns whether every direct ancestor has been calculated /// </summary> public bool ancestorsCalculated () { for (int i = 0; i < inputPorts.Count; i++) { ConnectionPort port = inputPorts[i]; for (int t = 0; t < port.connections.Count; t++) { if (!port.connections[t].body.calculated) return false; } } return true; } /// <summary> /// Recursively checks whether this node is a child of the other node /// </summary> public bool isChildOf (Node otherNode) { if (otherNode == null || otherNode == this) return false; if (BeginRecursiveSearchLoop ()) return false; for (int i = 0; i < inputPorts.Count; i++) { ConnectionPort port = inputPorts[i]; for (int t = 0; t < port.connections.Count; t++) { Node conBody = port.connections[t].body; if (conBody == otherNode || conBody.isChildOf(otherNode)) { StopRecursiveSearchLoop(); return true; } } } EndRecursiveSearchLoop (); return false; } /// <summary> /// Recursively checks whether this node is in a loop /// </summary> internal bool isInLoop () { if (BeginRecursiveSearchLoop ()) return false; for (int i = 0; i < inputPorts.Count; i++) { ConnectionPort port = inputPorts[i]; for (int t = 0; t < port.connections.Count; t++) { Node conBody = port.connections[t].body; if (conBody == startRecursiveSearchNode || conBody.isInLoop()) { StopRecursiveSearchLoop(); return true; } } } EndRecursiveSearchLoop (); return false; } /// <summary> /// A recursive function to clear all calculations depending on this node. /// Usually does not need to be called manually /// </summary> public void ClearCalculation () { calculated = false; if (BeginRecursiveSearchLoop ()) return; for (int i = 0; i < outputPorts.Count; i++) { ConnectionPort port = outputPorts[i]; if (port is ValueConnectionKnob) (port as ValueConnectionKnob).ResetValue (); for (int t = 0; t < port.connections.Count; t++) { ConnectionPort conPort = port.connections[t]; if (conPort is ValueConnectionKnob) (conPort as ValueConnectionKnob).ResetValue (); conPort.body.ClearCalculation (); } } EndRecursiveSearchLoop (); } #region Recursive Search Helpers [NonSerialized] private static List<Node> recursiveSearchSurpassed = new List<Node> (); [NonSerialized] private static Node startRecursiveSearchNode; // Temporary start node for recursive searches /// <summary> /// Begins the recursive search loop and returns whether this node has already been searched /// </summary> internal bool BeginRecursiveSearchLoop () { if (startRecursiveSearchNode == null) { // Start search if (recursiveSearchSurpassed == null) recursiveSearchSurpassed = new List<Node> (); recursiveSearchSurpassed.Capacity = canvas.nodes.Count; startRecursiveSearchNode = this; } // Check and mark node as searched if (recursiveSearchSurpassed.Contains (this)) return true; recursiveSearchSurpassed.Add (this); return false; } /// <summary> /// Ends the recursive search loop if this was the start node /// </summary> internal void EndRecursiveSearchLoop () { if (startRecursiveSearchNode == this) { // End search recursiveSearchSurpassed.Clear (); startRecursiveSearchNode = null; } } /// <summary> /// Stops the recursive search loop immediately. Call when you found what you needed. /// </summary> internal void StopRecursiveSearchLoop () { recursiveSearchSurpassed.Clear (); startRecursiveSearchNode = null; } #endregion #endregion #region Knob Utility public ConnectionPort CreateConnectionPort(ConnectionPortAttribute specificationAttribute) { ConnectionPort port = specificationAttribute.CreateNew(this); if (port == null) return null; dynamicConnectionPorts.Add(port); ConnectionPortManager.UpdateRepresentativePortLists(this); return port; } public ConnectionKnob CreateConnectionKnob(ConnectionKnobAttribute specificationAttribute) { return (ConnectionKnob)CreateConnectionPort(specificationAttribute); } public ValueConnectionKnob CreateValueConnectionKnob(ValueConnectionKnobAttribute specificationAttribute) { return (ValueConnectionKnob)CreateConnectionPort(specificationAttribute); } public void DeleteConnectionPort(ConnectionPort dynamicPort) { dynamicPort.ClearConnections (); dynamicConnectionPorts.Remove(dynamicPort); DestroyImmediate(dynamicPort); ConnectionPortManager.UpdateRepresentativePortLists(this); } public void DeleteConnectionPort(int dynamicPortIndex) { if (dynamicPortIndex >= 0 && dynamicPortIndex < dynamicConnectionPorts.Count) DeleteConnectionPort(dynamicConnectionPorts[dynamicPortIndex]); } #endregion } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace MoneyBox.Api.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
using System; using System.Threading; using AutoTest.Core.Messaging; using AutoTest.Core.Configuration; using System.IO; using System.Collections.Generic; using System.Linq; using AutoTest.Core.DebugLog; using AutoTest.Messages; namespace AutoTest.Core.Launchers { public class EditorEngineLauncher : IConsumerOf<BuildRunMessage>, IConsumerOf<TestRunMessage>, IConsumerOf<RunStartedMessage>, IConsumerOf<RunFinishedMessage> { private IMessageBus _bus; private string _path = null; private SocketClient _client = null; private SocketClient _eventendpoint = null; private Thread _shutdownWhenDisconnected = null; private bool _eventPointShutdownTriggered = false; public EditorEngineLauncher(IMessageBus bus) { _bus = bus; } public void Connect(string path) { _path = path; if (_client != null &&_client.IsConnected) _client.Disconnect(); _client = null; isConnected(); connectToEventEndpoint(); } public void GoTo(string file, int line, int column) { if (!isConnected()) return; send(string.Format("goto {0}|{1}|{2}", file, line, column)); } public void Consume(BuildRunMessage message) { if (!isConnected()) return; var state = "succeeded"; if (message.Results.ErrorCount > 0) state = "failed"; send( string.Format("autotest.net build \"{0}\" {1}", message.Results.Project, state)); } public void Consume(TestRunMessage message) { if (!isConnected()) return; var state = "succeeded"; if (message.Results.Failed.Length > 0) state = "failed"; send( string.Format("autotest.net testrun \"{0}\" {1} {2}", message.Results.Assembly, message.Results.Runner.ToString(), state)); } public void Consume(RunStartedMessage message) { if (!isConnected()) return; send("autotest.net runstarted"); } public void Consume(RunFinishedMessage message) { if (!isConnected()) return; send( string.Format("autotest.net runfinished {0} {1}", message.Report.NumberOfBuildsFailed, message.Report.NumberOfTestsFailed)); } private object _clientLock = new object(); private bool isConnected() { try { if (_client != null && _client.IsConnected) return true; var instance = new InstanceLocator("EditorEngine").GetInstance(_path); if (instance == null) return false; _client = new SocketClient(); _client.IncomingMessage += Handle_clientIncomingMessage; _client.Connect(instance.Port); if (_client.IsConnected) { startBackgroundShutdownHandler(); return true; } _client = null; return false; } catch (Exception ex) { Debug.WriteError(ex.ToString()); return false; } } private void connectToEventEndpoint() { try { if (_eventendpoint != null && _eventendpoint.IsConnected) return; var instance = new InstanceLocator("OpenIDE.Events").GetInstance(_path); if (instance == null) { return; } _eventendpoint = new SocketClient(); _eventendpoint.IncomingMessage += Handle_eventIncomingMessage; _eventendpoint.Connect(instance.Port); if (_eventendpoint.IsConnected) { startBackgroundShutdownHandler(); return; } _bus.Publish(new ExternalCommandMessage("EditorEngine", "shutdown")); } catch (Exception ex) { Debug.WriteError(ex.ToString()); } } private void startBackgroundShutdownHandler() { if (_shutdownWhenDisconnected != null) return; _shutdownWhenDisconnected = new Thread(exitWhenDisconnected); _shutdownWhenDisconnected.Start(); } private void exitWhenDisconnected() { while (isConnected() && !_eventPointShutdownTriggered) { Thread.Sleep(200); } _bus.Publish(new ExternalCommandMessage("EditorEngine", "shutdown")); } void Handle_clientIncomingMessage(object sender, IncomingMessageArgs e) { Debug.WriteDebug("Dispatching editor message: " + e.Message); _bus.Publish(new ExternalCommandMessage("EditorEngine", e.Message)); } void Handle_eventIncomingMessage(object sender, IncomingMessageArgs e) { if (e.Message == "shutdown") _eventPointShutdownTriggered = true; } private void send(string message) { Debug.WriteDebug("Sending to editor engine: " + message); _client.Send(message); } } class InstanceLocator { private string _instanceFileDirectory; public InstanceLocator(string instanceFileDirectory) { _instanceFileDirectory = instanceFileDirectory; } public Instance GetInstance(string path) { var instances = getInstances(path); return instances.Where(x => path.StartsWith(x.Key) && canConnectTo(x)) .OrderByDescending(x => x.Key.Length) .FirstOrDefault(); } private IEnumerable<Instance> getInstances(string path) { var dir = Path.Combine(Path.GetTempPath(), _instanceFileDirectory); if (Directory.Exists(dir)) { foreach (var file in Directory.GetFiles(dir, "*.pid")) { var instance = Instance.Get(file, File.ReadAllLines(file)); if (instance != null) yield return instance; } } } private bool canConnectTo(Instance info) { var client = new SocketClient(); client.Connect(info.Port); var connected = client.IsConnected; client.Disconnect(); if (!connected) File.Delete(info.File); return connected; } } }
// 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.IO; using System.Linq; using System.Security; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.GeneratedCodeRecognition; using Microsoft.CodeAnalysis.GenerateType; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.ProjectManagement; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.GenerateType { internal class GenerateTypeDialogViewModel : AbstractNotifyPropertyChanged { private Document _document; private INotificationService _notificationService; private IProjectManagementService _projectManagementService; private ISyntaxFactsService _syntaxFactsService; private GenerateTypeDialogOptions _generateTypeDialogOptions; private string _typeName; private bool _isNewFile; private Dictionary<string, Accessibility> _accessListMap; private Dictionary<string, TypeKind> _typeKindMap; private List<string> _csharpAccessList; private List<string> _visualBasicAccessList; private List<string> _csharpTypeKindList; private List<string> _visualBasicTypeKindList; private string _csharpExtension = ".cs"; private string _visualBasicExtension = ".vb"; // reserved names that cannot be a folder name or filename private string[] _reservedKeywords = new string[] { "con", "prn", "aux", "nul", "com1", "com2", "com3", "com4", "com5", "com6", "com7", "com8", "com9", "lpt1", "lpt2", "lpt3", "lpt4", "lpt5", "lpt6", "lpt7", "lpt8", "lpt9", "clock$" }; // Below code details with the Access List and the manipulation public List<string> AccessList { get; } private int _accessSelectIndex; public int AccessSelectIndex { get { return _accessSelectIndex; } set { SetProperty(ref _accessSelectIndex, value); } } private string _selectedAccessibilityString; public string SelectedAccessibilityString { get { return _selectedAccessibilityString; } set { SetProperty(ref _selectedAccessibilityString, value); } } public Accessibility SelectedAccessibility { get { Contract.Assert(_accessListMap.ContainsKey(SelectedAccessibilityString), "The Accessibility Key String not present"); return _accessListMap[SelectedAccessibilityString]; } } private List<string> _kindList; public List<string> KindList { get { return _kindList; } set { SetProperty(ref _kindList, value); } } private int _kindSelectIndex; public int KindSelectIndex { get { return _kindSelectIndex; } set { SetProperty(ref _kindSelectIndex, value); } } private string _selectedTypeKindString; public string SelectedTypeKindString { get { return _selectedTypeKindString; } set { SetProperty(ref _selectedTypeKindString, value); } } public TypeKind SelectedTypeKind { get { Contract.Assert(_typeKindMap.ContainsKey(SelectedTypeKindString), "The TypeKind Key String not present"); return _typeKindMap[SelectedTypeKindString]; } } private void PopulateTypeKind(TypeKind typeKind, string csharpKey, string visualBasicKey) { _typeKindMap.Add(visualBasicKey, typeKind); _typeKindMap.Add(csharpKey, typeKind); _csharpTypeKindList.Add(csharpKey); _visualBasicTypeKindList.Add(visualBasicKey); } private void PopulateTypeKind(TypeKind typeKind, string visualBasicKey) { _typeKindMap.Add(visualBasicKey, typeKind); _visualBasicTypeKindList.Add(visualBasicKey); } private void PopulateAccessList(string key, Accessibility accessibility, string languageName = null) { if (languageName == null) { _csharpAccessList.Add(key); _visualBasicAccessList.Add(key); } else if (languageName == LanguageNames.CSharp) { _csharpAccessList.Add(key); } else { Contract.Assert(languageName == LanguageNames.VisualBasic, "Currently only C# and VB are supported"); _visualBasicAccessList.Add(key); } _accessListMap.Add(key, accessibility); } private void InitialSetup(string languageName) { _accessListMap = new Dictionary<string, Accessibility>(); _typeKindMap = new Dictionary<string, TypeKind>(); _csharpAccessList = new List<string>(); _visualBasicAccessList = new List<string>(); _csharpTypeKindList = new List<string>(); _visualBasicTypeKindList = new List<string>(); // Populate the AccessListMap if (!_generateTypeDialogOptions.IsPublicOnlyAccessibility) { PopulateAccessList("Default", Accessibility.NotApplicable); PopulateAccessList("internal", Accessibility.Internal, LanguageNames.CSharp); PopulateAccessList("Friend", Accessibility.Internal, LanguageNames.VisualBasic); } PopulateAccessList("public", Accessibility.Public, LanguageNames.CSharp); PopulateAccessList("Public", Accessibility.Public, LanguageNames.VisualBasic); // Populate the TypeKind PopulateTypeKind(); } private void PopulateTypeKind() { Contract.Assert(_generateTypeDialogOptions.TypeKindOptions != TypeKindOptions.None); if (TypeKindOptionsHelper.IsClass(_generateTypeDialogOptions.TypeKindOptions)) { PopulateTypeKind(TypeKind.Class, "class", "Class"); } if (TypeKindOptionsHelper.IsEnum(_generateTypeDialogOptions.TypeKindOptions)) { PopulateTypeKind(TypeKind.Enum, "enum", "Enum"); } if (TypeKindOptionsHelper.IsStructure(_generateTypeDialogOptions.TypeKindOptions)) { PopulateTypeKind(TypeKind.Structure, "struct", "Structure"); } if (TypeKindOptionsHelper.IsInterface(_generateTypeDialogOptions.TypeKindOptions)) { PopulateTypeKind(TypeKind.Interface, "interface", "Interface"); } if (TypeKindOptionsHelper.IsDelegate(_generateTypeDialogOptions.TypeKindOptions)) { PopulateTypeKind(TypeKind.Delegate, "delegate", "Delegate"); } if (TypeKindOptionsHelper.IsModule(_generateTypeDialogOptions.TypeKindOptions)) { _shouldChangeTypeKindListSelectedIndex = true; PopulateTypeKind(TypeKind.Module, "Module"); } } internal bool TrySubmit() { if (this.IsNewFile) { var trimmedFileName = FileName.Trim(); // Case : \\Something if (trimmedFileName.StartsWith(@"\\", StringComparison.Ordinal)) { SendFailureNotification(ServicesVSResources.Illegal_characters_in_path); return false; } // Case : something\ if (string.IsNullOrWhiteSpace(trimmedFileName) || trimmedFileName.EndsWith(@"\", StringComparison.Ordinal)) { SendFailureNotification(ServicesVSResources.Path_cannot_have_empty_filename); return false; } if (trimmedFileName.IndexOfAny(Path.GetInvalidPathChars()) >= 0) { SendFailureNotification(ServicesVSResources.Illegal_characters_in_path); return false; } var isRootOfTheProject = trimmedFileName.StartsWith(@"\", StringComparison.Ordinal); string implicitFilePath = null; // Construct the implicit file path if (isRootOfTheProject || this.SelectedProject != _document.Project) { if (!TryGetImplicitFilePath(this.SelectedProject.FilePath ?? string.Empty, ServicesVSResources.Project_Path_is_illegal, out implicitFilePath)) { return false; } } else { if (!TryGetImplicitFilePath(_document.FilePath, ServicesVSResources.DocumentPath_is_illegal, out implicitFilePath)) { return false; } } // Remove the '\' at the beginning if present trimmedFileName = trimmedFileName.StartsWith(@"\", StringComparison.Ordinal) ? trimmedFileName.Substring(1) : trimmedFileName; // Construct the full path of the file to be created this.FullFilePath = implicitFilePath + @"\" + trimmedFileName; try { this.FullFilePath = Path.GetFullPath(this.FullFilePath); } catch (ArgumentNullException e) { SendFailureNotification(e.Message); return false; } catch (ArgumentException e) { SendFailureNotification(e.Message); return false; } catch (SecurityException e) { SendFailureNotification(e.Message); return false; } catch (NotSupportedException e) { SendFailureNotification(e.Message); return false; } catch (PathTooLongException e) { SendFailureNotification(e.Message); return false; } // Path.GetFullPath does not remove the spaces infront of the filename or folder name . So remove it var lastIndexOfSeparatorInFullPath = this.FullFilePath.LastIndexOf('\\'); if (lastIndexOfSeparatorInFullPath != -1) { var fileNameInFullPathInContainers = this.FullFilePath.Split(new[] { '\\' }, StringSplitOptions.RemoveEmptyEntries); this.FullFilePath = string.Join("\\", fileNameInFullPathInContainers.Select(str => str.TrimStart())); } string projectRootPath = null; if (this.SelectedProject.FilePath == null) { projectRootPath = string.Empty; } else if (!TryGetImplicitFilePath(this.SelectedProject.FilePath, ServicesVSResources.Project_Path_is_illegal, out projectRootPath)) { return false; } if (this.FullFilePath.StartsWith(projectRootPath, StringComparison.Ordinal)) { // The new file will be within the root of the project var folderPath = this.FullFilePath.Substring(projectRootPath.Length); var containers = folderPath.Split(new[] { '\\' }, StringSplitOptions.RemoveEmptyEntries); // Folder name was mentioned if (containers.Length > 1) { _fileName = containers.Last(); Folders = new List<string>(containers); Folders.RemoveAt(Folders.Count - 1); if (Folders.Any(folder => !(_syntaxFactsService.IsValidIdentifier(folder) || _syntaxFactsService.IsVerbatimIdentifier(folder)))) { _areFoldersValidIdentifiers = false; } } else if (containers.Length == 1) { // File goes at the root of the Directory _fileName = containers[0]; Folders = null; } else { SendFailureNotification(ServicesVSResources.Illegal_characters_in_path); return false; } } else { // The new file will be outside the root of the project and folders will be null Folders = null; var lastIndexOfSeparator = this.FullFilePath.LastIndexOf('\\'); if (lastIndexOfSeparator == -1) { SendFailureNotification(ServicesVSResources.Illegal_characters_in_path); return false; } _fileName = this.FullFilePath.Substring(lastIndexOfSeparator + 1); } // Check for reserved words in the folder or filename if (this.FullFilePath.Split(new[] { '\\' }, StringSplitOptions.RemoveEmptyEntries).Any(s => _reservedKeywords.Contains(s, StringComparer.OrdinalIgnoreCase))) { SendFailureNotification(ServicesVSResources.File_path_cannot_use_reserved_keywords); return false; } // We check to see if file path of the new file matches the filepath of any other existing file or if the Folders and FileName matches any of the document then // we say that the file already exists. if (this.SelectedProject.Documents.Where(n => n != null).Where(n => n.FilePath == FullFilePath).Any() || (this.Folders != null && this.FileName != null && this.SelectedProject.Documents.Where(n => n.Name != null && n.Folders.Count > 0 && n.Name == this.FileName && this.Folders.SequenceEqual(n.Folders)).Any()) || File.Exists(FullFilePath)) { SendFailureNotification(ServicesVSResources.File_already_exists); return false; } } return true; } private bool TryGetImplicitFilePath(string implicitPathContainer, string message, out string implicitPath) { var indexOfLastSeparator = implicitPathContainer.LastIndexOf('\\'); if (indexOfLastSeparator == -1) { SendFailureNotification(message); implicitPath = null; return false; } implicitPath = implicitPathContainer.Substring(0, indexOfLastSeparator); return true; } private void SendFailureNotification(string message) { _notificationService.SendNotification(message, severity: NotificationSeverity.Information); } private Project _selectedProject; public Project SelectedProject { get { return _selectedProject; } set { var previousProject = _selectedProject; if (SetProperty(ref _selectedProject, value)) { NotifyPropertyChanged("DocumentList"); this.DocumentSelectIndex = 0; this.ProjectSelectIndex = this.ProjectList.FindIndex(p => p.Project == _selectedProject); if (_selectedProject != _document.Project) { // Restrict the Access List Options // 3 in the list represent the Public. 1-based array. this.AccessSelectIndex = this.AccessList.IndexOf("public") == -1 ? this.AccessList.IndexOf("Public") : this.AccessList.IndexOf("public"); Contract.Assert(this.AccessSelectIndex != -1); this.IsAccessListEnabled = false; } else { // Remove restriction this.IsAccessListEnabled = true; } if (previousProject != null && _projectManagementService != null) { this.ProjectFolders = _projectManagementService.GetFolders(this.SelectedProject.Id, this.SelectedProject.Solution.Workspace); } // Update the TypeKindList if required if (previousProject != null && previousProject.Language != _selectedProject.Language) { if (_selectedProject.Language == LanguageNames.CSharp) { var previousSelectedIndex = _kindSelectIndex; this.KindList = _csharpTypeKindList; if (_shouldChangeTypeKindListSelectedIndex) { this.KindSelectIndex = 0; } else { this.KindSelectIndex = previousSelectedIndex; } } else { var previousSelectedIndex = _kindSelectIndex; this.KindList = _visualBasicTypeKindList; if (_shouldChangeTypeKindListSelectedIndex) { this.KindSelectIndex = 0; } else { this.KindSelectIndex = previousSelectedIndex; } } } // Update File Extension UpdateFileNameExtension(); } } } private int _projectSelectIndex; public int ProjectSelectIndex { get { return _projectSelectIndex; } set { SetProperty(ref _projectSelectIndex, value); } } public List<ProjectSelectItem> ProjectList { get; } private Project _previouslyPopulatedProject = null; private List<DocumentSelectItem> _previouslyPopulatedDocumentList = null; public IEnumerable<DocumentSelectItem> GetDocumentList(CancellationToken cancellationToken) { if (_previouslyPopulatedProject == _selectedProject) { return _previouslyPopulatedDocumentList; } _previouslyPopulatedProject = _selectedProject; _previouslyPopulatedDocumentList = new List<DocumentSelectItem>(); // Check for the current project if (_selectedProject == _document.Project) { // populate the current document _previouslyPopulatedDocumentList.Add(new DocumentSelectItem(_document, "<Current File>")); // Set the initial selected Document this.SelectedDocument = _document; // Populate the rest of the documents for the project _previouslyPopulatedDocumentList.AddRange(_document.Project.Documents .Where(d => d != _document && !d.IsGeneratedCode(cancellationToken)) .Select(d => new DocumentSelectItem(d))); } else { _previouslyPopulatedDocumentList.AddRange(_selectedProject.Documents .Where(d => !d.IsGeneratedCode(cancellationToken)) .Select(d => new DocumentSelectItem(d))); this.SelectedDocument = _selectedProject.Documents.FirstOrDefault(); } this.IsExistingFileEnabled = _previouslyPopulatedDocumentList.Count == 0 ? false : true; this.IsNewFile = this.IsExistingFileEnabled ? this.IsNewFile : true; return _previouslyPopulatedDocumentList; } private bool _isExistingFileEnabled = true; public bool IsExistingFileEnabled { get { return _isExistingFileEnabled; } set { SetProperty(ref _isExistingFileEnabled, value); } } private int _documentSelectIndex; public int DocumentSelectIndex { get { return _documentSelectIndex; } set { SetProperty(ref _documentSelectIndex, value); } } private Document _selectedDocument; public Document SelectedDocument { get { return _selectedDocument; } set { SetProperty(ref _selectedDocument, value); } } private string _fileName; public string FileName { get { return _fileName; } set { SetProperty(ref _fileName, value); } } public List<string> Folders; public string TypeName { get { return _typeName; } set { SetProperty(ref _typeName, value); } } public bool IsNewFile { get { return _isNewFile; } set { SetProperty(ref _isNewFile, value); } } public bool IsExistingFile { get { return !_isNewFile; } set { SetProperty(ref _isNewFile, !value); } } private bool _isAccessListEnabled; private bool _shouldChangeTypeKindListSelectedIndex = false; public bool IsAccessListEnabled { get { return _isAccessListEnabled; } set { SetProperty(ref _isAccessListEnabled, value); } } private bool _areFoldersValidIdentifiers = true; public bool AreFoldersValidIdentifiers { get { if (_areFoldersValidIdentifiers) { var workspace = this.SelectedProject.Solution.Workspace as VisualStudioWorkspaceImpl; var project = workspace?.GetHostProject(this.SelectedProject.Id) as AbstractProject; return !(project?.IsWebSite == true); } return false; } } public IList<string> ProjectFolders { get; private set; } public string FullFilePath { get; private set; } internal void UpdateFileNameExtension() { var currentFileName = this.FileName.Trim(); if (!string.IsNullOrWhiteSpace(currentFileName) && !currentFileName.EndsWith("\\", StringComparison.Ordinal)) { if (this.SelectedProject.Language == LanguageNames.CSharp) { // For CSharp currentFileName = UpdateExtension(currentFileName, _csharpExtension, _visualBasicExtension); } else { // For Visual Basic currentFileName = UpdateExtension(currentFileName, _visualBasicExtension, _csharpExtension); } } this.FileName = currentFileName; } private string UpdateExtension(string currentFileName, string desiredFileExtension, string undesiredFileExtension) { if (currentFileName.EndsWith(desiredFileExtension, StringComparison.OrdinalIgnoreCase)) { // No change required return currentFileName; } // Remove the undesired extension if (currentFileName.EndsWith(undesiredFileExtension, StringComparison.OrdinalIgnoreCase)) { currentFileName = currentFileName.Substring(0, currentFileName.Length - undesiredFileExtension.Length); } // Append the desired extension return currentFileName + desiredFileExtension; } internal GenerateTypeDialogViewModel( Document document, INotificationService notificationService, IProjectManagementService projectManagementService, ISyntaxFactsService syntaxFactsService, GenerateTypeDialogOptions generateTypeDialogOptions, string typeName, string fileExtension, bool isNewFile, string accessSelectString, string typeKindSelectString) { _generateTypeDialogOptions = generateTypeDialogOptions; InitialSetup(document.Project.Language); var dependencyGraph = document.Project.Solution.GetProjectDependencyGraph(); // Initialize the dependencies var projectListing = new List<ProjectSelectItem>(); // Populate the project list // Add the current project projectListing.Add(new ProjectSelectItem(document.Project)); // Add the rest of the projects // Adding dependency graph to avoid cyclic dependency projectListing.AddRange(document.Project.Solution.Projects .Where(p => p != document.Project && !dependencyGraph.GetProjectsThatThisProjectTransitivelyDependsOn(p.Id).Contains(document.Project.Id)) .Select(p => new ProjectSelectItem(p))); this.ProjectList = projectListing; const string attributeSuffix = "Attribute"; _typeName = generateTypeDialogOptions.IsAttribute && !typeName.EndsWith(attributeSuffix, StringComparison.Ordinal) ? typeName + attributeSuffix : typeName; this.FileName = typeName + fileExtension; _document = document; this.SelectedProject = document.Project; this.SelectedDocument = document; _notificationService = notificationService; this.AccessList = document.Project.Language == LanguageNames.CSharp ? _csharpAccessList : _visualBasicAccessList; this.AccessSelectIndex = this.AccessList.Contains(accessSelectString) ? this.AccessList.IndexOf(accessSelectString) : 0; this.IsAccessListEnabled = true; this.KindList = document.Project.Language == LanguageNames.CSharp ? _csharpTypeKindList : _visualBasicTypeKindList; this.KindSelectIndex = this.KindList.Contains(typeKindSelectString) ? this.KindList.IndexOf(typeKindSelectString) : 0; this.ProjectSelectIndex = 0; this.DocumentSelectIndex = 0; _isNewFile = isNewFile; _syntaxFactsService = syntaxFactsService; _projectManagementService = projectManagementService; if (projectManagementService != null) { this.ProjectFolders = _projectManagementService.GetFolders(this.SelectedProject.Id, this.SelectedProject.Solution.Workspace); } else { this.ProjectFolders = SpecializedCollections.EmptyList<string>(); } } public class ProjectSelectItem { private Project _project; public string Name { get { return _project.Name; } } public Project Project { get { return _project; } } public ProjectSelectItem(Project project) { _project = project; } } public class DocumentSelectItem { private Document _document; public Document Document { get { return _document; } } private string _name; public string Name { get { return _name; } } public DocumentSelectItem(Document document, string documentName) { _document = document; _name = documentName; } public DocumentSelectItem(Document document) { _document = document; if (document.Folders.Count == 0) { _name = document.Name; } else { _name = string.Join("\\", document.Folders) + "\\" + document.Name; } } } } }
// 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; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using EditorBrowsableState = System.ComponentModel.EditorBrowsableState; using EditorBrowsableAttribute = System.ComponentModel.EditorBrowsableAttribute; #pragma warning disable 0809 //warning CS0809: Obsolete member 'Span<T>.Equals(object)' overrides non-obsolete member 'object.Equals(object)' #if BIT64 using nuint = System.UInt64; #else using nuint = System.UInt32; #endif namespace System { /// <summary> /// Span represents a contiguous region of arbitrary memory. Unlike arrays, it can point to either managed /// or native memory, or to memory allocated on the stack. It is type- and memory-safe. /// </summary> public struct Span<T> { /// <summary>A byref or a native ptr.</summary> private readonly ByReference<T> _pointer; /// <summary>The number of elements this Span contains.</summary> private readonly int _length; /// <summary> /// Creates a new span over the entirety of the target array. /// </summary> /// <param name="array">The target array.</param> /// <exception cref="System.ArgumentNullException">Thrown when <paramref name="array"/> is a null /// reference (Nothing in Visual Basic).</exception> /// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public Span(T[] array) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); if (default(T) == null && array.GetType() != typeof(T[])) ThrowHelper.ThrowArrayTypeMismatchException(); _pointer = new ByReference<T>(ref JitHelpers.GetArrayData(array)); _length = array.Length; } /// <summary> /// Creates a new span over the portion of the target array beginning /// at 'start' index and covering the remainder of the array. /// </summary> /// <param name="array">The target array.</param> /// <param name="start">The index at which to begin the span.</param> /// <exception cref="System.ArgumentNullException">Thrown when <paramref name="array"/> is a null /// reference (Nothing in Visual Basic).</exception> /// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="start"/> is not in the range (&lt;0 or &gt;=Length). /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public Span(T[] array, int start) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); if (default(T) == null && array.GetType() != typeof(T[])) ThrowHelper.ThrowArrayTypeMismatchException(); if ((uint)start > (uint)array.Length) ThrowHelper.ThrowArgumentOutOfRangeException(); _pointer = new ByReference<T>(ref Unsafe.Add(ref JitHelpers.GetArrayData(array), start)); _length = array.Length - start; } /// <summary> /// Creates a new span over the portion of the target array beginning /// at 'start' index and ending at 'end' index (exclusive). /// </summary> /// <param name="array">The target array.</param> /// <param name="start">The index at which to begin the span.</param> /// <param name="length">The number of items in the span.</param> /// <exception cref="System.ArgumentNullException">Thrown when <paramref name="array"/> is a null /// reference (Nothing in Visual Basic).</exception> /// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="start"/> or end index is not in the range (&lt;0 or &gt;=Length). /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public Span(T[] array, int start, int length) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); if (default(T) == null && array.GetType() != typeof(T[])) ThrowHelper.ThrowArrayTypeMismatchException(); if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start)) ThrowHelper.ThrowArgumentOutOfRangeException(); _pointer = new ByReference<T>(ref Unsafe.Add(ref JitHelpers.GetArrayData(array), start)); _length = length; } /// <summary> /// Creates a new span over the target unmanaged buffer. Clearly this /// is quite dangerous, because we are creating arbitrarily typed T's /// out of a void*-typed block of memory. And the length is not checked. /// But if this creation is correct, then all subsequent uses are correct. /// </summary> /// <param name="pointer">An unmanaged pointer to memory.</param> /// <param name="length">The number of <typeparamref name="T"/> elements the memory contains.</param> /// <exception cref="System.ArgumentException"> /// Thrown when <typeparamref name="T"/> is reference type or contains pointers and hence cannot be stored in unmanaged memory. /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="length"/> is negative. /// </exception> [CLSCompliant(false)] [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe Span(void* pointer, int length) { if (RuntimeHelpers.IsReferenceOrContainsReferences<T>()) ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(T)); if (length < 0) ThrowHelper.ThrowArgumentOutOfRangeException(); _pointer = new ByReference<T>(ref Unsafe.As<byte, T>(ref *(byte*)pointer)); _length = length; } /// <summary> /// Create a new span over a portion of a regular managed object. This can be useful /// if part of a managed object represents a "fixed array." This is dangerous because /// "length" is not checked, nor is the fact that "rawPointer" actually lies within the object. /// </summary> /// <param name="obj">The managed object that contains the data to span over.</param> /// <param name="objectData">A reference to data within that object.</param> /// <param name="length">The number of <typeparamref name="T"/> elements the memory contains.</param> /// <exception cref="System.ArgumentNullException"> /// Thrown when the specified object is null. /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="length"/> is negative. /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Span<T> DangerousCreate(object obj, ref T objectData, int length) { if (obj == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.obj); if (length < 0) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length); return new Span<T>(ref objectData, length); } // Constructor for internal use only. [MethodImpl(MethodImplOptions.AggressiveInlining)] internal Span(ref T ptr, int length) { Debug.Assert(length >= 0); _pointer = new ByReference<T>(ref ptr); _length = length; } /// <summary> /// Returns a reference to the 0th element of the Span. If the Span is empty, returns a reference to the location where the 0th element /// would have been stored. Such a reference can be used for pinning but must never be dereferenced. /// </summary> public ref T DangerousGetPinnableReference() { return ref _pointer.Value; } /// <summary> /// The number of items in the span. /// </summary> public int Length => _length; /// <summary> /// Returns true if Length is 0. /// </summary> public bool IsEmpty => _length == 0; /// <summary> /// Returns a reference to specified element of the Span. /// </summary> /// <param name="index"></param> /// <returns></returns> /// <exception cref="System.IndexOutOfRangeException"> /// Thrown when index less than 0 or index greater than or equal to Length /// </exception> public ref T this[int index] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { if ((uint)index >= (uint)_length) ThrowHelper.ThrowIndexOutOfRangeException(); return ref Unsafe.Add(ref _pointer.Value, index); } } /// <summary> /// Clears the contents of this span. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Clear() { if (RuntimeHelpers.IsReferenceOrContainsReferences<T>()) { SpanHelper.ClearWithReferences(ref Unsafe.As<T, IntPtr>(ref _pointer.Value), (nuint)(_length * (Unsafe.SizeOf<T>() / sizeof(nuint)))); } else { SpanHelper.ClearWithoutReferences(ref Unsafe.As<T, byte>(ref _pointer.Value), (nuint)(_length * Unsafe.SizeOf<T>())); } } /// <summary> /// Fills the contents of this span with the given value. /// </summary> public void Fill(T value) { int length = _length; if (length == 0) return; if (Unsafe.SizeOf<T>() == 1) { byte fill = Unsafe.As<T, byte>(ref value); ref byte r = ref Unsafe.As<T, byte>(ref _pointer.Value); Unsafe.InitBlockUnaligned(ref r, fill, (uint)length); } else { ref T r = ref DangerousGetPinnableReference(); // TODO: Create block fill for value types of power of two sizes e.g. 2,4,8,16 // Simple loop unrolling int i = 0; for (; i < (length & ~7); i += 8) { Unsafe.Add<T>(ref r, i + 0) = value; Unsafe.Add<T>(ref r, i + 1) = value; Unsafe.Add<T>(ref r, i + 2) = value; Unsafe.Add<T>(ref r, i + 3) = value; Unsafe.Add<T>(ref r, i + 4) = value; Unsafe.Add<T>(ref r, i + 5) = value; Unsafe.Add<T>(ref r, i + 6) = value; Unsafe.Add<T>(ref r, i + 7) = value; } if (i < (length & ~3)) { Unsafe.Add<T>(ref r, i + 0) = value; Unsafe.Add<T>(ref r, i + 1) = value; Unsafe.Add<T>(ref r, i + 2) = value; Unsafe.Add<T>(ref r, i + 3) = value; i += 4; } for (; i < length; i++) { Unsafe.Add<T>(ref r, i) = value; } } } /// <summary> /// Copies the contents of this span into destination span. If the source /// and destinations overlap, this method behaves as if the original values in /// a temporary location before the destination is overwritten. /// </summary> /// <param name="destination">The span to copy items into.</param> /// <exception cref="System.ArgumentException"> /// Thrown when the destination Span is shorter than the source Span. /// </exception> public void CopyTo(Span<T> destination) { if (!TryCopyTo(destination)) ThrowHelper.ThrowArgumentException_DestinationTooShort(); } /// <summary> /// Copies the contents of this span into destination span. If the source /// and destinations overlap, this method behaves as if the original values in /// a temporary location before the destination is overwritten. /// </summary> /// <param name="destination">The span to copy items into.</param> /// <returns>If the destination span is shorter than the source span, this method /// return false and no data is written to the destination.</returns> public bool TryCopyTo(Span<T> destination) { if ((uint)_length > (uint)destination.Length) return false; SpanHelper.CopyTo<T>(ref destination._pointer.Value, ref _pointer.Value, _length); return true; } /// <summary> /// Returns true if left and right point at the same memory and have the same length. Note that /// this does *not* check to see if the *contents* are equal. /// </summary> public static bool operator ==(Span<T> left, Span<T> right) { return left._length == right._length && Unsafe.AreSame<T>(ref left._pointer.Value, ref right._pointer.Value); } /// <summary> /// Returns false if left and right point at the same memory and have the same length. Note that /// this does *not* check to see if the *contents* are equal. /// </summary> public static bool operator !=(Span<T> left, Span<T> right) => !(left == right); /// <summary> /// This method is not supported as spans cannot be boxed. To compare two spans, use operator==. /// <exception cref="System.NotSupportedException"> /// Always thrown by this method. /// </exception> /// </summary> [Obsolete("Equals() on Span will always throw an exception. Use == instead.")] [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) { ThrowHelper.ThrowNotSupportedException_CannotCallEqualsOnSpan(); // Prevent compiler error CS0161: 'Span<T>.Equals(object)': not all code paths return a value return default(bool); } /// <summary> /// This method is not supported as spans cannot be boxed. /// <exception cref="System.NotSupportedException"> /// Always thrown by this method. /// </exception> /// </summary> [Obsolete("GetHashCode() on Span will always throw an exception.")] [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() { ThrowHelper.ThrowNotSupportedException_CannotCallGetHashCodeOnSpan(); // Prevent compiler error CS0161: 'Span<T>.GetHashCode()': not all code paths return a value return default(int); } /// <summary> /// Defines an implicit conversion of an array to a <see cref="Span{T}"/> /// </summary> public static implicit operator Span<T>(T[] array) => new Span<T>(array); /// <summary> /// Defines an implicit conversion of a <see cref="ArraySegment{T}"/> to a <see cref="Span{T}"/> /// </summary> public static implicit operator Span<T>(ArraySegment<T> arraySegment) => new Span<T>(arraySegment.Array, arraySegment.Offset, arraySegment.Count); /// <summary> /// Defines an implicit conversion of a <see cref="Span{T}"/> to a <see cref="ReadOnlySpan{T}"/> /// </summary> public static implicit operator ReadOnlySpan<T>(Span<T> span) => new ReadOnlySpan<T>(ref span._pointer.Value, span._length); /// <summary> /// Forms a slice out of the given span, beginning at 'start'. /// </summary> /// <param name="start">The index at which to begin this slice.</param> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="start"/> index is not in range (&lt;0 or &gt;=Length). /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public Span<T> Slice(int start) { if ((uint)start > (uint)_length) ThrowHelper.ThrowArgumentOutOfRangeException(); return new Span<T>(ref Unsafe.Add(ref _pointer.Value, start), _length - start); } /// <summary> /// Forms a slice out of the given span, beginning at 'start', of given length /// </summary> /// <param name="start">The index at which to begin this slice.</param> /// <param name="length">The desired length for the slice (exclusive).</param> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="start"/> or end index is not in range (&lt;0 or &gt;=Length). /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public Span<T> Slice(int start, int length) { if ((uint)start > (uint)_length || (uint)length > (uint)(_length - start)) ThrowHelper.ThrowArgumentOutOfRangeException(); return new Span<T>(ref Unsafe.Add(ref _pointer.Value, start), length); } /// <summary> /// Copies the contents of this span into a new array. This heap /// allocates, so should generally be avoided, however it is sometimes /// necessary to bridge the gap with APIs written in terms of arrays. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public T[] ToArray() { if (_length == 0) return Array.Empty<T>(); var destination = new T[_length]; SpanHelper.CopyTo<T>(ref JitHelpers.GetArrayData(destination), ref _pointer.Value, _length); return destination; } // <summary> /// Returns an empty <see cref="Span{T}"/> /// </summary> public static Span<T> Empty => default(Span<T>); } public static class Span { /// <summary> /// Casts a Span of one primitive type <typeparamref name="T"/> to Span of bytes. /// That type may not contain pointers or references. This is checked at runtime in order to preserve type safety. /// </summary> /// <param name="source">The source slice, of type <typeparamref name="T"/>.</param> /// <exception cref="System.ArgumentException"> /// Thrown when <typeparamref name="T"/> contains pointers. /// </exception> public static Span<byte> AsBytes<T>(this Span<T> source) where T : struct { if (RuntimeHelpers.IsReferenceOrContainsReferences<T>()) ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(T)); return new Span<byte>( ref Unsafe.As<T, byte>(ref source.DangerousGetPinnableReference()), checked(source.Length * Unsafe.SizeOf<T>())); } /// <summary> /// Casts a ReadOnlySpan of one primitive type <typeparamref name="T"/> to ReadOnlySpan of bytes. /// That type may not contain pointers or references. This is checked at runtime in order to preserve type safety. /// </summary> /// <param name="source">The source slice, of type <typeparamref name="T"/>.</param> /// <exception cref="System.ArgumentException"> /// Thrown when <typeparamref name="T"/> contains pointers. /// </exception> public static ReadOnlySpan<byte> AsBytes<T>(this ReadOnlySpan<T> source) where T : struct { if (RuntimeHelpers.IsReferenceOrContainsReferences<T>()) ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(T)); return new ReadOnlySpan<byte>( ref Unsafe.As<T, byte>(ref source.DangerousGetPinnableReference()), checked(source.Length * Unsafe.SizeOf<T>())); } /// <summary> /// Casts a Span of one primitive type <typeparamref name="TFrom"/> to another primitive type <typeparamref name="TTo"/>. /// These types may not contain pointers or references. This is checked at runtime in order to preserve type safety. /// </summary> /// <remarks> /// Supported only for platforms that support misaligned memory access. /// </remarks> /// <param name="source">The source slice, of type <typeparamref name="TFrom"/>.</param> /// <exception cref="System.ArgumentException"> /// Thrown when <typeparamref name="TFrom"/> or <typeparamref name="TTo"/> contains pointers. /// </exception> public static Span<TTo> NonPortableCast<TFrom, TTo>(this Span<TFrom> source) where TFrom : struct where TTo : struct { if (RuntimeHelpers.IsReferenceOrContainsReferences<TFrom>()) ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(TFrom)); if (RuntimeHelpers.IsReferenceOrContainsReferences<TTo>()) ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(TTo)); return new Span<TTo>( ref Unsafe.As<TFrom, TTo>(ref source.DangerousGetPinnableReference()), checked((int)((long)source.Length * Unsafe.SizeOf<TFrom>() / Unsafe.SizeOf<TTo>()))); } /// <summary> /// Casts a ReadOnlySpan of one primitive type <typeparamref name="TFrom"/> to another primitive type <typeparamref name="TTo"/>. /// These types may not contain pointers or references. This is checked at runtime in order to preserve type safety. /// </summary> /// <remarks> /// Supported only for platforms that support misaligned memory access. /// </remarks> /// <param name="source">The source slice, of type <typeparamref name="TFrom"/>.</param> /// <exception cref="System.ArgumentException"> /// Thrown when <typeparamref name="TFrom"/> or <typeparamref name="TTo"/> contains pointers. /// </exception> public static ReadOnlySpan<TTo> NonPortableCast<TFrom, TTo>(this ReadOnlySpan<TFrom> source) where TFrom : struct where TTo : struct { if (RuntimeHelpers.IsReferenceOrContainsReferences<TFrom>()) ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(TFrom)); if (RuntimeHelpers.IsReferenceOrContainsReferences<TTo>()) ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(TTo)); return new ReadOnlySpan<TTo>( ref Unsafe.As<TFrom, TTo>(ref source.DangerousGetPinnableReference()), checked((int)((long)source.Length * Unsafe.SizeOf<TFrom>() / Unsafe.SizeOf<TTo>()))); } /// <summary> /// Creates a new readonly span over the portion of the target string. /// </summary> /// <param name="text">The target string.</param> /// <exception cref="System.ArgumentNullException">Thrown when <paramref name="text"/> is a null /// reference (Nothing in Visual Basic).</exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ReadOnlySpan<char> Slice(this string text) { if (text == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.text); return new ReadOnlySpan<char>(ref text.GetFirstCharRef(), text.Length); } /// <summary> /// Creates a new readonly span over the portion of the target string, beginning at 'start'. /// </summary> /// <param name="text">The target string.</param> /// <param name="start">The index at which to begin this slice.</param> /// <exception cref="System.ArgumentNullException">Thrown when <paramref name="text"/> is a null /// reference (Nothing in Visual Basic).</exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="start"/> index is not in range (&lt;0 or &gt;Length). /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ReadOnlySpan<char> Slice(this string text, int start) { if (text == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.text); if ((uint)start > (uint)text.Length) ThrowHelper.ThrowArgumentOutOfRangeException(); return new ReadOnlySpan<char>(ref Unsafe.Add(ref text.GetFirstCharRef(), start), text.Length - start); } /// <summary> /// Creates a new readonly span over the portion of the target string, beginning at <paramref name="start"/>, of given <paramref name="length"/>. /// </summary> /// <param name="text">The target string.</param> /// <param name="start">The index at which to begin this slice.</param> /// <param name="length">The number of items in the span.</param> /// <exception cref="System.ArgumentNullException">Thrown when <paramref name="text"/> is a null /// reference (Nothing in Visual Basic).</exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="start"/> or end index is not in range (&lt;0 or &gt;&eq;Length). /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ReadOnlySpan<char> Slice(this string text, int start, int length) { if (text == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.text); if ((uint)start > (uint)text.Length || (uint)length > (uint)(text.Length - start)) ThrowHelper.ThrowArgumentOutOfRangeException(); return new ReadOnlySpan<char>(ref Unsafe.Add(ref text.GetFirstCharRef(), start), length); } } internal static class SpanHelper { internal static unsafe void CopyTo<T>(ref T destination, ref T source, int elementsCount) { if (elementsCount == 0) return; if (Unsafe.AreSame(ref destination, ref source)) return; if (!RuntimeHelpers.IsReferenceOrContainsReferences<T>()) { fixed (byte* pDestination = &Unsafe.As<T, byte>(ref destination)) { fixed (byte* pSource = &Unsafe.As<T, byte>(ref source)) { #if BIT64 Buffer.Memmove(pDestination, pSource, (ulong)elementsCount * (ulong)Unsafe.SizeOf<T>()); #else Buffer.Memmove(pDestination, pSource, (uint)elementsCount * (uint)Unsafe.SizeOf<T>()); #endif } } } else { if (JitHelpers.ByRefLessThan(ref destination, ref source)) // copy forward { for (int i = 0; i < elementsCount; i++) Unsafe.Add(ref destination, i) = Unsafe.Add(ref source, i); } else // copy backward to avoid overlapping issues { for (int i = elementsCount - 1; i >= 0; i--) Unsafe.Add(ref destination, i) = Unsafe.Add(ref source, i); } } } internal static unsafe void ClearWithoutReferences(ref byte b, nuint byteLength) { if (byteLength == 0) return; // Note: It's important that this switch handles lengths at least up to 22. // See notes below near the main loop for why. // The switch will be very fast since it can be implemented using a jump // table in assembly. See http://stackoverflow.com/a/449297/4077294 for more info. switch (byteLength) { case 1: b = 0; return; case 2: Unsafe.As<byte, short>(ref b) = 0; return; case 3: Unsafe.As<byte, short>(ref b) = 0; Unsafe.Add<byte>(ref b, 2) = 0; return; case 4: Unsafe.As<byte, int>(ref b) = 0; return; case 5: Unsafe.As<byte, int>(ref b) = 0; Unsafe.Add<byte>(ref b, 4) = 0; return; case 6: Unsafe.As<byte, int>(ref b) = 0; Unsafe.As<byte, short>(ref Unsafe.Add<byte>(ref b, 4)) = 0; return; case 7: Unsafe.As<byte, int>(ref b) = 0; Unsafe.As<byte, short>(ref Unsafe.Add<byte>(ref b, 4)) = 0; Unsafe.Add<byte>(ref b, 6) = 0; return; case 8: #if BIT64 Unsafe.As<byte, long>(ref b) = 0; #else Unsafe.As<byte, int>(ref b) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0; #endif return; case 9: #if BIT64 Unsafe.As<byte, long>(ref b) = 0; #else Unsafe.As<byte, int>(ref b) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0; #endif Unsafe.Add<byte>(ref b, 8) = 0; return; case 10: #if BIT64 Unsafe.As<byte, long>(ref b) = 0; #else Unsafe.As<byte, int>(ref b) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0; #endif Unsafe.As<byte, short>(ref Unsafe.Add<byte>(ref b, 8)) = 0; return; case 11: #if BIT64 Unsafe.As<byte, long>(ref b) = 0; #else Unsafe.As<byte, int>(ref b) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0; #endif Unsafe.As<byte, short>(ref Unsafe.Add<byte>(ref b, 8)) = 0; Unsafe.Add<byte>(ref b, 10) = 0; return; case 12: #if BIT64 Unsafe.As<byte, long>(ref b) = 0; #else Unsafe.As<byte, int>(ref b) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0; #endif Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 8)) = 0; return; case 13: #if BIT64 Unsafe.As<byte, long>(ref b) = 0; #else Unsafe.As<byte, int>(ref b) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0; #endif Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 8)) = 0; Unsafe.Add<byte>(ref b, 12) = 0; return; case 14: #if BIT64 Unsafe.As<byte, long>(ref b) = 0; #else Unsafe.As<byte, int>(ref b) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0; #endif Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 8)) = 0; Unsafe.As<byte, short>(ref Unsafe.Add<byte>(ref b, 12)) = 0; return; case 15: #if BIT64 Unsafe.As<byte, long>(ref b) = 0; #else Unsafe.As<byte, int>(ref b) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0; #endif Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 8)) = 0; Unsafe.As<byte, short>(ref Unsafe.Add<byte>(ref b, 12)) = 0; Unsafe.Add<byte>(ref b, 14) = 0; return; case 16: #if BIT64 Unsafe.As<byte, long>(ref b) = 0; Unsafe.As<byte, long>(ref Unsafe.Add<byte>(ref b, 8)) = 0; #else Unsafe.As<byte, int>(ref b) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 8)) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 12)) = 0; #endif return; case 17: #if BIT64 Unsafe.As<byte, long>(ref b) = 0; Unsafe.As<byte, long>(ref Unsafe.Add<byte>(ref b, 8)) = 0; #else Unsafe.As<byte, int>(ref b) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 8)) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 12)) = 0; #endif Unsafe.Add<byte>(ref b, 16) = 0; return; case 18: #if BIT64 Unsafe.As<byte, long>(ref b) = 0; Unsafe.As<byte, long>(ref Unsafe.Add<byte>(ref b, 8)) = 0; #else Unsafe.As<byte, int>(ref b) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 8)) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 12)) = 0; #endif Unsafe.As<byte, short>(ref Unsafe.Add<byte>(ref b, 16)) = 0; return; case 19: #if BIT64 Unsafe.As<byte, long>(ref b) = 0; Unsafe.As<byte, long>(ref Unsafe.Add<byte>(ref b, 8)) = 0; #else Unsafe.As<byte, int>(ref b) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 8)) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 12)) = 0; #endif Unsafe.As<byte, short>(ref Unsafe.Add<byte>(ref b, 16)) = 0; Unsafe.Add<byte>(ref b, 18) = 0; return; case 20: #if BIT64 Unsafe.As<byte, long>(ref b) = 0; Unsafe.As<byte, long>(ref Unsafe.Add<byte>(ref b, 8)) = 0; #else Unsafe.As<byte, int>(ref b) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 8)) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 12)) = 0; #endif Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 16)) = 0; return; case 21: #if BIT64 Unsafe.As<byte, long>(ref b) = 0; Unsafe.As<byte, long>(ref Unsafe.Add<byte>(ref b, 8)) = 0; #else Unsafe.As<byte, int>(ref b) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 8)) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 12)) = 0; #endif Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 16)) = 0; Unsafe.Add<byte>(ref b, 20) = 0; return; case 22: #if BIT64 Unsafe.As<byte, long>(ref b) = 0; Unsafe.As<byte, long>(ref Unsafe.Add<byte>(ref b, 8)) = 0; #else Unsafe.As<byte, int>(ref b) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 8)) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 12)) = 0; #endif Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 16)) = 0; Unsafe.As<byte, short>(ref Unsafe.Add<byte>(ref b, 20)) = 0; return; } // P/Invoke into the native version for large lengths if (byteLength >= 512) goto PInvoke; nuint i = 0; // byte offset at which we're copying if ((Unsafe.As<byte, int>(ref b) & 3) != 0) { if ((Unsafe.As<byte, int>(ref b) & 1) != 0) { Unsafe.AddByteOffset<byte>(ref b, i) = 0; i += 1; if ((Unsafe.As<byte, int>(ref b) & 2) != 0) goto IntAligned; } Unsafe.As<byte, short>(ref Unsafe.AddByteOffset<byte>(ref b, i)) = 0; i += 2; } IntAligned: // On 64-bit IntPtr.Size == 8, so we want to advance to the next 8-aligned address. If // (int)b % 8 is 0, 5, 6, or 7, we will already have advanced by 0, 3, 2, or 1 // bytes to the next aligned address (respectively), so do nothing. On the other hand, // if it is 1, 2, 3, or 4 we will want to copy-and-advance another 4 bytes until // we're aligned. // The thing 1, 2, 3, and 4 have in common that the others don't is that if you // subtract one from them, their 3rd lsb will not be set. Hence, the below check. if (((Unsafe.As<byte, int>(ref b) - 1) & 4) == 0) { Unsafe.As<byte, int>(ref Unsafe.AddByteOffset<byte>(ref b, i)) = 0; i += 4; } nuint end = byteLength - 16; byteLength -= i; // lower 4 bits of byteLength represent how many bytes are left *after* the unrolled loop // We know due to the above switch-case that this loop will always run 1 iteration; max // bytes we clear before checking is 23 (7 to align the pointers, 16 for 1 iteration) so // the switch handles lengths 0-22. Debug.Assert(end >= 7 && i <= end); // This is separated out into a different variable, so the i + 16 addition can be // performed at the start of the pipeline and the loop condition does not have // a dependency on the writes. nuint counter; do { counter = i + 16; // This loop looks very costly since there appear to be a bunch of temporary values // being created with the adds, but the jit (for x86 anyways) will convert each of // these to use memory addressing operands. // So the only cost is a bit of code size, which is made up for by the fact that // we save on writes to b. #if BIT64 Unsafe.As<byte, long>(ref Unsafe.AddByteOffset<byte>(ref b, i)) = 0; Unsafe.As<byte, long>(ref Unsafe.AddByteOffset<byte>(ref b, i + 8)) = 0; #else Unsafe.As<byte, int>(ref Unsafe.AddByteOffset<byte>(ref b, i)) = 0; Unsafe.As<byte, int>(ref Unsafe.AddByteOffset<byte>(ref b, i + 4)) = 0; Unsafe.As<byte, int>(ref Unsafe.AddByteOffset<byte>(ref b, i + 8)) = 0; Unsafe.As<byte, int>(ref Unsafe.AddByteOffset<byte>(ref b, i + 12)) = 0; #endif i = counter; // See notes above for why this wasn't used instead // i += 16; } while (counter <= end); if ((byteLength & 8) != 0) { #if BIT64 Unsafe.As<byte, long>(ref Unsafe.AddByteOffset<byte>(ref b, i)) = 0; #else Unsafe.As<byte, int>(ref Unsafe.AddByteOffset<byte>(ref b, i)) = 0; Unsafe.As<byte, int>(ref Unsafe.AddByteOffset<byte>(ref b, i + 4)) = 0; #endif i += 8; } if ((byteLength & 4) != 0) { Unsafe.As<byte, int>(ref Unsafe.AddByteOffset<byte>(ref b, i)) = 0; i += 4; } if ((byteLength & 2) != 0) { Unsafe.As<byte, short>(ref Unsafe.AddByteOffset<byte>(ref b, i)) = 0; i += 2; } if ((byteLength & 1) != 0) { Unsafe.AddByteOffset<byte>(ref b, i) = 0; // We're not using i after this, so not needed // i += 1; } return; PInvoke: RuntimeImports.RhZeroMemory(ref b, byteLength); } internal static unsafe void ClearWithReferences(ref IntPtr ip, nuint pointerSizeLength) { if (pointerSizeLength == 0) return; // TODO: Perhaps do switch casing to improve small size perf nuint i = 0; nuint n = 0; while ((n = i + 8) <= (pointerSizeLength)) { Unsafe.AddByteOffset<IntPtr>(ref ip, (i + 0) * (nuint)sizeof(IntPtr)) = default(IntPtr); Unsafe.AddByteOffset<IntPtr>(ref ip, (i + 1) * (nuint)sizeof(IntPtr)) = default(IntPtr); Unsafe.AddByteOffset<IntPtr>(ref ip, (i + 2) * (nuint)sizeof(IntPtr)) = default(IntPtr); Unsafe.AddByteOffset<IntPtr>(ref ip, (i + 3) * (nuint)sizeof(IntPtr)) = default(IntPtr); Unsafe.AddByteOffset<IntPtr>(ref ip, (i + 4) * (nuint)sizeof(IntPtr)) = default(IntPtr); Unsafe.AddByteOffset<IntPtr>(ref ip, (i + 5) * (nuint)sizeof(IntPtr)) = default(IntPtr); Unsafe.AddByteOffset<IntPtr>(ref ip, (i + 6) * (nuint)sizeof(IntPtr)) = default(IntPtr); Unsafe.AddByteOffset<IntPtr>(ref ip, (i + 7) * (nuint)sizeof(IntPtr)) = default(IntPtr); i = n; } if ((n = i + 4) <= (pointerSizeLength)) { Unsafe.AddByteOffset<IntPtr>(ref ip, (i + 0) * (nuint)sizeof(IntPtr)) = default(IntPtr); Unsafe.AddByteOffset<IntPtr>(ref ip, (i + 1) * (nuint)sizeof(IntPtr)) = default(IntPtr); Unsafe.AddByteOffset<IntPtr>(ref ip, (i + 2) * (nuint)sizeof(IntPtr)) = default(IntPtr); Unsafe.AddByteOffset<IntPtr>(ref ip, (i + 3) * (nuint)sizeof(IntPtr)) = default(IntPtr); i = n; } if ((n = i + 2) <= (pointerSizeLength)) { Unsafe.AddByteOffset<IntPtr>(ref ip, (i + 0) * (nuint)sizeof(IntPtr)) = default(IntPtr); Unsafe.AddByteOffset<IntPtr>(ref ip, (i + 1) * (nuint)sizeof(IntPtr)) = default(IntPtr); i = n; } if ((i + 1) <= (pointerSizeLength)) { Unsafe.AddByteOffset<IntPtr>(ref ip, (i + 0) * (nuint)sizeof(IntPtr)) = default(IntPtr); } } } }
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; using System.Collections; using System.Collections.Generic; using System.Linq; using Avalonia.Collections; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Controls.Templates; using Avalonia.Data; using Avalonia.Markup.Xaml.Data; using Xunit; namespace Avalonia.Controls.UnitTests.Primitives { public class SelectingItemsControlTests_Multiple { [Fact] public void Setting_SelectedIndex_Should_Add_To_SelectedItems() { var target = new TestSelector { Items = new[] { "foo", "bar" }, Template = Template(), }; target.ApplyTemplate(); target.SelectedIndex = 1; Assert.Equal(new[] { "bar" }, target.SelectedItems.Cast<object>().ToList()); } [Fact] public void Adding_SelectedItems_Should_Set_SelectedIndex() { var target = new TestSelector { Items = new[] { "foo", "bar" }, Template = Template(), }; target.ApplyTemplate(); target.SelectedItems.Add("bar"); Assert.Equal(1, target.SelectedIndex); } [Fact] public void Assigning_SelectedItems_Should_Set_SelectedIndex() { var target = new TestSelector { Items = new[] { "foo", "bar" }, Template = Template(), }; target.ApplyTemplate(); target.SelectedItems = new AvaloniaList<object>("bar"); Assert.Equal(1, target.SelectedIndex); } [Fact] public void Reassigning_SelectedItems_Should_Clear_Selection() { var target = new TestSelector { Items = new[] { "foo", "bar" }, Template = Template(), }; target.ApplyTemplate(); target.SelectedItems.Add("bar"); target.SelectedItems = new AvaloniaList<object>(); Assert.Equal(-1, target.SelectedIndex); Assert.Null(target.SelectedItem); } [Fact] public void Adding_First_SelectedItem_Should_Raise_SelectedIndex_SelectedItem_Changed() { var target = new TestSelector { Items = new[] { "foo", "bar" }, Template = Template(), }; bool indexRaised = false; bool itemRaised = false; target.PropertyChanged += (s, e) => { indexRaised |= e.Property.Name == "SelectedIndex" && (int)e.OldValue == -1 && (int)e.NewValue == 1; itemRaised |= e.Property.Name == "SelectedItem" && (string)e.OldValue == null && (string)e.NewValue == "bar"; }; target.ApplyTemplate(); target.SelectedItems.Add("bar"); Assert.True(indexRaised); Assert.True(itemRaised); } [Fact] public void Adding_Subsequent_SelectedItems_Should_Not_Raise_SelectedIndex_SelectedItem_Changed() { var target = new TestSelector { Items = new[] { "foo", "bar" }, Template = Template(), }; target.ApplyTemplate(); target.SelectedItems.Add("foo"); bool raised = false; target.PropertyChanged += (s, e) => raised |= e.Property.Name == "SelectedIndex" || e.Property.Name == "SelectedItem"; target.SelectedItems.Add("bar"); Assert.False(raised); } [Fact] public void Removing_Last_SelectedItem_Should_Raise_SelectedIndex_Changed() { var target = new TestSelector { Items = new[] { "foo", "bar" }, Template = Template(), }; target.ApplyTemplate(); target.SelectedItems.Add("foo"); bool raised = false; target.PropertyChanged += (s, e) => raised |= e.Property.Name == "SelectedIndex" && (int)e.OldValue == 0 && (int)e.NewValue == -1; target.SelectedItems.RemoveAt(0); Assert.True(raised); } [Fact] public void Adding_SelectedItems_Should_Set_Item_IsSelected() { var items = new[] { new ListBoxItem(), new ListBoxItem(), new ListBoxItem(), }; var target = new TestSelector { Items = items, Template = Template(), }; target.ApplyTemplate(); target.Presenter.ApplyTemplate(); target.SelectedItems.Add(items[0]); target.SelectedItems.Add(items[1]); var foo = target.Presenter.Panel.Children[0]; Assert.True(items[0].IsSelected); Assert.True(items[1].IsSelected); Assert.False(items[2].IsSelected); } [Fact] public void Assigning_SelectedItems_Should_Set_Item_IsSelected() { var items = new[] { new ListBoxItem(), new ListBoxItem(), new ListBoxItem(), }; var target = new TestSelector { Items = items, Template = Template(), }; target.ApplyTemplate(); target.Presenter.ApplyTemplate(); target.SelectedItems = new AvaloniaList<object> { items[0], items[1] }; Assert.True(items[0].IsSelected); Assert.True(items[1].IsSelected); Assert.False(items[2].IsSelected); } [Fact] public void Removing_SelectedItems_Should_Clear_Item_IsSelected() { var items = new[] { new ListBoxItem(), new ListBoxItem(), new ListBoxItem(), }; var target = new TestSelector { Items = items, Template = Template(), }; target.ApplyTemplate(); target.Presenter.ApplyTemplate(); target.SelectedItems.Add(items[0]); target.SelectedItems.Add(items[1]); target.SelectedItems.Remove(items[1]); Assert.True(items[0].IsSelected); Assert.False(items[1].IsSelected); } [Fact] public void Reassigning_SelectedItems_Should_Clear_Item_IsSelected() { var items = new[] { new ListBoxItem(), new ListBoxItem(), new ListBoxItem(), }; var target = new TestSelector { Items = items, Template = Template(), }; target.ApplyTemplate(); target.SelectedItems.Add(items[0]); target.SelectedItems.Add(items[1]); target.SelectedItems = new AvaloniaList<object> { items[0], items[1] }; Assert.False(items[0].IsSelected); Assert.False(items[1].IsSelected); } [Fact] public void Replacing_First_SelectedItem_Should_Update_SelectedItem_SelectedIndex() { var items = new[] { new ListBoxItem(), new ListBoxItem(), new ListBoxItem(), }; var target = new TestSelector { Items = items, Template = Template(), }; target.ApplyTemplate(); target.Presenter.ApplyTemplate(); target.SelectedIndex = 1; target.SelectedItems[0] = items[2]; Assert.Equal(2, target.SelectedIndex); Assert.Equal(items[2], target.SelectedItem); Assert.False(items[0].IsSelected); Assert.False(items[1].IsSelected); Assert.True(items[2].IsSelected); } [Fact] public void Range_Select_Should_Select_Range() { var target = new TestSelector { Items = new[] { "foo", "bar", "baz", "qux", "qiz", "lol", }, SelectionMode = SelectionMode.Multiple, Template = Template(), }; target.ApplyTemplate(); target.SelectedIndex = 1; target.SelectRange(3); Assert.Equal(new[] { "bar", "baz", "qux" }, target.SelectedItems.Cast<object>().ToList()); } [Fact] public void Range_Select_Backwards_Should_Select_Range() { var target = new TestSelector { Items = new[] { "foo", "bar", "baz", "qux", "qiz", "lol", }, SelectionMode = SelectionMode.Multiple, Template = Template(), }; target.ApplyTemplate(); target.SelectedIndex = 3; target.SelectRange(1); Assert.Equal(new[] { "qux", "baz", "bar" }, target.SelectedItems.Cast<object>().ToList()); } [Fact] public void Second_Range_Select_Backwards_Should_Select_From_Original_Selection() { var target = new TestSelector { Items = new[] { "foo", "bar", "baz", "qux", "qiz", "lol", }, SelectionMode = SelectionMode.Multiple, Template = Template(), }; target.ApplyTemplate(); target.SelectedIndex = 2; target.SelectRange(5); target.SelectRange(4); Assert.Equal(new[] { "baz", "qux", "qiz" }, target.SelectedItems.Cast<object>().ToList()); } [Fact] public void Suprious_SelectedIndex_Changes_Should_Not_Be_Triggered() { var target = new TestSelector { Items = new[] { "foo", "bar", "baz" }, Template = Template(), }; target.ApplyTemplate(); var selectedIndexes = new List<int>(); target.GetObservable(TestSelector.SelectedIndexProperty).Subscribe(x => selectedIndexes.Add(x)); target.SelectedItems = new AvaloniaList<object> { "bar", "baz" }; target.SelectedItem = "foo"; Assert.Equal(0, target.SelectedIndex); Assert.Equal(new[] { -1, 1, 0 }, selectedIndexes); } /// <summary> /// Tests a problem discovered with ListBox with selection. /// </summary> /// <remarks> /// - Items is bound to DataContext first, followed by say SelectedIndex /// - When the ListBox is removed from the visual tree, DataContext becomes null (as it's /// inherited) /// - This changes Items to null, which changes SelectedIndex to null as there are no /// longer any items /// - However, the news that DataContext is now null hasn't yet reached the SelectedItems /// binding and so the unselection is sent back to the ViewModel /// /// This is a similar problem to that tested by XamlBindingTest.Should_Not_Write_To_Old_DataContext. /// However, that tests a general property binding problem: here we are writing directly /// to the SelectedItems collection - not via a binding - so it's something that the /// binding system cannot solve. Instead we solve it by not clearing SelectedItems when /// DataContext is in the process of changing. /// </remarks> [Fact] public void Should_Not_Write_To_Old_DataContext() { var vm = new OldDataContextViewModel(); var target = new TestSelector(); var itemsBinding = new Binding { Path = "Items", Mode = BindingMode.OneWay, }; var selectedItemsBinding = new Binding { Path = "SelectedItems", Mode = BindingMode.OneWay, }; // Bind Items and SelectedItems to the VM. target.Bind(TestSelector.ItemsProperty, itemsBinding); target.Bind(TestSelector.SelectedItemsProperty, selectedItemsBinding); // Set DataContext and SelectedIndex target.DataContext = vm; target.SelectedIndex = 1; // Make sure SelectedItems are written back to VM. Assert.Equal(new[] { "bar" }, vm.SelectedItems); // Clear DataContext and ensure that SelectedItems is still set in the VM. target.DataContext = null; Assert.Equal(new[] { "bar" }, vm.SelectedItems); // Ensure target's SelectedItems is now clear. Assert.Empty(target.SelectedItems); } [Fact] public void Unbound_SelectedItems_Should_Be_Cleared_When_DataContext_Cleared() { var data = new { Items = new[] { "foo", "bar", "baz" }, }; var target = new TestSelector { DataContext = data, Template = Template(), }; var itemsBinding = new Binding { Path = "Items" }; target.Bind(TestSelector.ItemsProperty, itemsBinding); Assert.Same(data.Items, target.Items); target.SelectedItems.Add("bar"); target.DataContext = null; Assert.Empty(target.SelectedItems); } [Fact] public void Adding_To_SelectedItems_Should_Raise_SelectionChanged() { var items = new[] { "foo", "bar", "baz" }; var target = new TestSelector { DataContext = items, Template = Template(), }; var called = false; target.SelectionChanged += (s, e) => { Assert.Equal(new[] { "bar" }, e.AddedItems.Cast<object>().ToList()); Assert.Empty(e.RemovedItems); called = true; }; target.SelectedItems.Add("bar"); Assert.True(called); } [Fact] public void Removing_From_SelectedItems_Should_Raise_SelectionChanged() { var items = new[] { "foo", "bar", "baz" }; var target = new TestSelector { Items = items, Template = Template(), SelectedItem = "bar", }; var called = false; target.SelectionChanged += (s, e) => { Assert.Equal(new[] { "bar" }, e.RemovedItems.Cast<object>().ToList()); Assert.Empty(e.AddedItems); called = true; }; target.SelectedItems.Remove("bar"); Assert.True(called); } [Fact] public void Assigning_SelectedItems_Should_Raise_SelectionChanged() { var items = new[] { "foo", "bar", "baz" }; var target = new TestSelector { Items = items, Template = Template(), SelectedItem = "bar", }; var called = false; target.SelectionChanged += (s, e) => { Assert.Equal(new[] { "foo", "baz" }, e.AddedItems.Cast<object>()); Assert.Equal(new[] { "bar" }, e.RemovedItems.Cast<object>()); called = true; }; target.ApplyTemplate(); target.Presenter.ApplyTemplate(); target.SelectedItems = new AvaloniaList<object>("foo", "baz"); Assert.True(called); } private FuncControlTemplate Template() { return new FuncControlTemplate<SelectingItemsControl>(control => new ItemsPresenter { Name = "PART_ItemsPresenter", [~ItemsPresenter.ItemsProperty] = control[~ItemsControl.ItemsProperty], [~ItemsPresenter.ItemsPanelProperty] = control[~ItemsControl.ItemsPanelProperty], }); } private class TestSelector : SelectingItemsControl { public static readonly new AvaloniaProperty<IList> SelectedItemsProperty = SelectingItemsControl.SelectedItemsProperty; public new IList SelectedItems { get { return base.SelectedItems; } set { base.SelectedItems = value; } } public new SelectionMode SelectionMode { get { return base.SelectionMode; } set { base.SelectionMode = value; } } public void SelectRange(int index) { UpdateSelection(index, true, true); } } private class OldDataContextViewModel { public OldDataContextViewModel() { Items = new List<string> { "foo", "bar" }; SelectedItems = new List<string>(); } public List<string> Items { get; } public List<string> SelectedItems { get; } } } }
// ------------------------------------------------------------------------------ // Copyright (c) 2014 Microsoft Corporation // // 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. // ------------------------------------------------------------------------------ namespace Microsoft.Live.UnitTests { using System; using System.Collections; using System.Collections.Generic; #if NETFX_CORE using Microsoft.VisualStudio.TestPlatform.UnitTestFramework; #elif WINDOWS_PHONE || WEB || DESKTOP using Microsoft.VisualStudio.TestTools.UnitTesting; #else #error This platform needs to be handled. #endif [TestClass] public class DynamicDictionaryTest { #region DynamicObject tests [TestMethod] public void TestTryGetMemberKeyExists() { var dynamicDictionary = new DynamicDictionary(); dynamicDictionary["foo"] = "bar"; dynamic d = dynamicDictionary; Assert.AreEqual("bar", d.foo); } [TestMethod] public void TestTryGetMemberKeyDoesNotExists() { var dynamicDictionary = new DynamicDictionary(); dynamic d = dynamicDictionary; Assert.IsNull(d.foo); } [TestMethod] public void TestTrySetMemberKeyDoesNotExistYet() { var dynamicDictionary = new DynamicDictionary(); dynamic d = dynamicDictionary; d.foo = "bar"; Assert.AreEqual("bar", d.foo); } [TestMethod] public void TestTrySetMemberKeyAlreadyExists() { var dynamicDictionary = new DynamicDictionary(); dynamic d = dynamicDictionary; d["foo"] = "bar"; d.foo = "bar2"; Assert.AreEqual("bar2", d.foo); } #endregion #region IDictionary<string, object> tests [TestMethod] public void TestAdd() { var d = new DynamicDictionary(); d.Add("key", "value"); Assert.AreEqual("value", d["key"]); } [TestMethod] public void TestContainsKey() { var d = new DynamicDictionary(); d.Add("key", "value"); Assert.IsTrue(d.ContainsKey("key"), "Did not contain key: \"key\""); } [TestMethod] public void TestRemove() { var d = new DynamicDictionary(); d.Add("key", "value"); Assert.IsTrue(d.Remove("key"), "Did not remove key: \"key\""); } [TestMethod] public void TestTryGetValueKeyExists() { var d = new DynamicDictionary(); d.Add("key", "value"); object value; Assert.IsTrue( d.TryGetValue("key", out value), "Expected true to trying to get a value for an existing key."); Assert.AreEqual("value", value); } [TestMethod] public void TestTryGetValueKeyDoesNotExist() { var d = new DynamicDictionary(); object value; Assert.IsFalse( d.TryGetValue("key", out value), "Expected false to trying to get a value for a non exisiting key."); Assert.IsNull( value, "Retrieved a Non null value for a key that doesn't exist."); } [TestMethod] public void TestValuesFromEmptyDynamicDictionary() { var d = new DynamicDictionary(); ICollection<object> values = d.Values; Assert.AreEqual(0, values.Count); } [TestMethod] public void TestValuesFromEmptyDynamicDictionaryThatOnceHadItemsInIt() { var d = new DynamicDictionary(); ICollection<object> values = d.Values; Assert.AreEqual(0, values.Count); } [TestMethod] public void TestValuesFromNonEmptyDynamicDictionary() { var d = new DynamicDictionary(); d["foo"] = "bar"; ICollection<object> values = d.Values; Assert.AreEqual(1, values.Count); foreach (object value in values) { Assert.AreEqual("bar", value); } } [TestMethod] public void TestValuesSeeIfModifyingTheReturnValuesAffectsTheOriginalDynamicDictionary() { var d = new DynamicDictionary(); d["foo"] = "bar"; ICollection<object> values = d.Values; try { values.Clear(); Assert.Fail("Did not throw a NotSupportedException. The values collection was allowed to be modified."); } catch (NotSupportedException) { } Assert.AreEqual(1, values.Count); Assert.AreEqual(1, d.Count); } [TestMethod] public void TestSquareBacesOperator() { var d = new DynamicDictionary(); d["foo"] = "bar"; Assert.AreEqual("bar", d["foo"]); } [TestMethod] public void TestSquareBacesOperatorKeyDoesNotExist() { var d = new DynamicDictionary(); try { object value = d["foo"]; Assert.Fail("Did not receive KeyNotFoundException for a key that doesn't exist."); } catch (KeyNotFoundException) { } } [TestMethod] public void TestAddKeyValuePair() { var d = new DynamicDictionary(); d.Add(new KeyValuePair<string, object>("foo", "bar")); Assert.AreEqual("bar", d["foo"]); } [TestMethod] public void TestClearNonEmptyList() { var d = new DynamicDictionary(); d.Add(new KeyValuePair<string, object>("foo", "bar")); d.Clear(); Assert.AreEqual(0, d.Count); } [TestMethod] public void TestClearEmptyList() { var d = new DynamicDictionary(); d.Clear(); Assert.AreEqual(0, d.Count); } [TestMethod] public void TestContainsKeyValuePairThatExists() { var d = new DynamicDictionary(); d.Add("key", "value"); Assert.IsTrue(d.Contains(new KeyValuePair<string, object>("key", "value"))); } [TestMethod] public void TestContainsKeyValuePairThatDoesNotExists() { var d = new DynamicDictionary(); d.Add("foo", "bar"); Assert.IsFalse(d.Contains(new KeyValuePair<string, object>("key", "value"))); } [TestMethod] public void TestCopyToKeyValuePair() { var d = new DynamicDictionary(); d.Add("foo", "bar"); var array = new KeyValuePair<string, object>[d.Count]; d.CopyTo(array, 0); KeyValuePair<string, object> pair = array[0]; Assert.AreEqual("foo", pair.Key); Assert.AreEqual("bar", pair.Value); } [TestMethod] public void TestCount() { var d = new DynamicDictionary(); Assert.AreEqual(0, d.Count); d.Add("key", "value"); Assert.AreEqual(1, d.Count); d.Remove("key"); Assert.AreEqual(0, d.Count); } [TestMethod] public void TestIsReadOnly() { var d = new DynamicDictionary(); Assert.IsFalse(d.IsReadOnly); } [TestMethod] public void TestRemoveKeyValuePair() { var d = new DynamicDictionary(); d.Add("key", "value"); Assert.IsTrue(d.Remove(new KeyValuePair<string, object>("key", "value"))); Assert.AreEqual(0, d.Count); } [TestMethod] public void TestGetEnumerator() { var d = new DynamicDictionary(); d.Add("key", "value"); IEnumerator enumerator = d.GetEnumerator(); int count = 0; while (enumerator.MoveNext()) { var pair = (KeyValuePair<string, object>) enumerator.Current; Assert.AreEqual("key", pair.Key); Assert.AreEqual("value", pair.Value); count += 1; } Assert.AreEqual(1, count, "Enumerator did not move through the right number of items."); } #endregion } }
//----------------------------------------------------------------------- // <copyright file="ActorProcessor.cs" company="Akka.NET Project"> // Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using Akka.Actor; using Akka.Event; using Akka.Pattern; using Akka.Streams.Actors; using Reactive.Streams; namespace Akka.Streams.Implementation { internal static class ActorProcessor { public static ActorProcessor<TIn, TOut> Create<TIn, TOut>(IActorRef impl) { var p = new ActorProcessor<TIn, TOut>(impl); // Resolve cyclic dependency with actor. This MUST be the first message no matter what. impl.Tell(new ExposedPublisher(p)); return p; } } internal class ActorProcessor<TIn, TOut> : ActorPublisher<TOut>, IProcessor<TIn, TOut> { public ActorProcessor(IActorRef impl) : base(impl) { } public void OnNext(TIn element) => OnNext((object)element); public void OnSubscribe(ISubscription subscription) { ReactiveStreamsCompliance.RequireNonNullSubscription(subscription); Impl.Tell(new OnSubscribe(subscription)); } public void OnNext(object element) { ReactiveStreamsCompliance.RequireNonNullElement(element); Impl.Tell(new OnNext(element)); } public void OnError(Exception cause) { ReactiveStreamsCompliance.RequireNonNullException(cause); Impl.Tell(new OnError(cause)); } public void OnComplete() => Impl.Tell(Actors.OnComplete.Instance); } internal abstract class BatchingInputBuffer : IInputs { public readonly int Count; public readonly IPump Pump; private readonly object[] _inputBuffer; private readonly int _indexMask; private ISubscription _upstream; private int _inputBufferElements; private int _nextInputElementCursor; private bool _isUpstreamCompleted; private int _batchRemaining; protected BatchingInputBuffer(int count, IPump pump) { if (count <= 0) throw new ArgumentException("Buffer Count must be > 0"); if ((count & (count - 1)) != 0) throw new ArgumentException("Buffer Count must be power of two"); // TODO: buffer and batch sizing heuristics Count = count; Pump = pump; _indexMask = count - 1; _inputBuffer = new object[count]; _batchRemaining = RequestBatchSize; SubReceive = new SubReceive(WaitingForUpstream); NeedsInput = DefaultInputTransferStates.NeedsInput(this); NeedsInputOrComplete = DefaultInputTransferStates.NeedsInputOrComplete(this); } private int RequestBatchSize => Math.Max(1, _inputBuffer.Length / 2); public override string ToString() => $"BatchingInputBuffer(Count={Count}, elems={_inputBufferElements}, completed={_isUpstreamCompleted}, remaining={_batchRemaining})"; public virtual SubReceive SubReceive { get; } public virtual object DequeueInputElement() { var elem = _inputBuffer[_nextInputElementCursor]; _inputBuffer[_nextInputElementCursor] = null; _batchRemaining--; if (_batchRemaining == 0 && !_isUpstreamCompleted) { _upstream.Request(RequestBatchSize); _batchRemaining = RequestBatchSize; } _inputBufferElements--; _nextInputElementCursor++; _nextInputElementCursor &= _indexMask; return elem; } protected virtual void EnqueueInputElement(object element) { if (IsOpen) { if (_inputBufferElements == Count) throw new IllegalStateException("Input buffer overrun"); _inputBuffer[(_nextInputElementCursor + _inputBufferElements) & _indexMask] = element; _inputBufferElements++; } Pump.Pump(); } public virtual void Cancel() { if (!_isUpstreamCompleted) { _isUpstreamCompleted = true; if (!ReferenceEquals(_upstream, null)) _upstream.Cancel(); Clear(); } } private void Clear() { _inputBuffer.Initialize(); _inputBufferElements = 0; } public TransferState NeedsInput { get; } public TransferState NeedsInputOrComplete { get; } public bool IsClosed => _isUpstreamCompleted; public bool IsOpen => !IsClosed; public bool AreInputsDepleted => _isUpstreamCompleted && _inputBufferElements == 0; public bool AreInputsAvailable => _inputBufferElements > 0; protected virtual void OnComplete() { _isUpstreamCompleted = true; SubReceive.Become(Completed); Pump.Pump(); } protected virtual void OnSubscribe(ISubscription subscription) { if (subscription == null) throw new ArgumentException("OnSubscribe require subscription not to be null"); if (_isUpstreamCompleted) subscription.Cancel(); else { _upstream = subscription; // prefetch _upstream.Request(_inputBuffer.Length); SubReceive.Become(UpstreamRunning); } Pump.GotUpstreamSubscription(); } protected virtual void OnError(Exception e) { _isUpstreamCompleted = true; SubReceive.Become(Completed); InputOnError(e); } protected virtual bool WaitingForUpstream(object message) { if (message is OnComplete) OnComplete(); else if (message is OnSubscribe) OnSubscribe(((OnSubscribe)message).Subscription); else if (message is OnError) OnError(((OnError)message).Cause); else return false; return true; } protected virtual bool UpstreamRunning(object message) { if (message is OnNext) EnqueueInputElement(((OnNext)message).Element); else if (message is OnComplete) OnComplete(); else if (message is OnSubscribe) ((OnSubscribe)message).Subscription.Cancel(); else if (message is OnError) OnError(((OnError)message).Cause); else return false; return true; } protected virtual bool Completed(object message) { if (message is OnSubscribe) throw new IllegalStateException("OnSubscribe called after OnError or OnComplete"); return false; } protected virtual void InputOnError(Exception e) => Clear(); } internal class SimpleOutputs : IOutputs { public readonly IActorRef Actor; public readonly IPump Pump; protected IActorPublisher ExposedPublisher; protected IUntypedSubscriber Subscriber; protected long DownstreamDemand; protected bool IsDownstreamCompleted; public SimpleOutputs(IActorRef actor, IPump pump) { Actor = actor; Pump = pump; SubReceive = new SubReceive(WaitingExposedPublisher); NeedsDemand = DefaultOutputTransferStates.NeedsDemand(this); NeedsDemandOrCancel = DefaultOutputTransferStates.NeedsDemandOrCancel(this); } public bool IsSubscribed => Subscriber != null; public virtual SubReceive SubReceive { get; } public TransferState NeedsDemand { get; } public TransferState NeedsDemandOrCancel { get; } public long DemandCount => DownstreamDemand; public bool IsDemandAvailable => DownstreamDemand > 0; public void EnqueueOutputElement(object element) { ReactiveStreamsCompliance.RequireNonNullElement(element); DownstreamDemand--; ReactiveStreamsCompliance.TryOnNext(Subscriber, element); } public virtual void Complete() { if (!IsDownstreamCompleted) { IsDownstreamCompleted = true; if (!ReferenceEquals(ExposedPublisher, null)) ExposedPublisher.Shutdown(null); if (!ReferenceEquals(Subscriber, null)) ReactiveStreamsCompliance.TryOnComplete(Subscriber); } } public virtual void Cancel() { if (!IsDownstreamCompleted) { IsDownstreamCompleted = true; if (!ReferenceEquals(ExposedPublisher, null)) ExposedPublisher.Shutdown(null); } } public virtual void Error(Exception e) { if (!IsDownstreamCompleted) { IsDownstreamCompleted = true; if (!ReferenceEquals(ExposedPublisher, null)) ExposedPublisher.Shutdown(e); if (!ReferenceEquals(Subscriber, null) && !(e is ISpecViolation)) ReactiveStreamsCompliance.TryOnError(Subscriber, e); } } public bool IsClosed => IsDownstreamCompleted && !ReferenceEquals(Subscriber, null); public bool IsOpen => !IsClosed; protected ISubscription CreateSubscription() => ActorSubscription.Create(Actor, Subscriber); private void SubscribePending(IEnumerable<IUntypedSubscriber> subscribers) { foreach (var subscriber in subscribers) { if (ReferenceEquals(Subscriber, null)) { Subscriber = subscriber; ReactiveStreamsCompliance.TryOnSubscribe(subscriber, CreateSubscription()); } else ReactiveStreamsCompliance.RejectAdditionalSubscriber(subscriber, GetType().Name); } } protected bool WaitingExposedPublisher(object message) { if (message is ExposedPublisher) { ExposedPublisher = ((ExposedPublisher)message).Publisher; SubReceive.Become(DownstreamRunning); return true; } throw new IllegalStateException( $"The first message must be [{typeof (ExposedPublisher)}] but was [{message}]"); } protected bool DownstreamRunning(object message) { if (message is SubscribePending) SubscribePending(ExposedPublisher.TakePendingSubscribers()); else if (message is RequestMore) { var requestMore = (RequestMore)message; if (requestMore.Demand < 1) Error(ReactiveStreamsCompliance.NumberOfElementsInRequestMustBePositiveException); else { DownstreamDemand += requestMore.Demand; if (DownstreamDemand < 1) DownstreamDemand = long.MaxValue; // Long overflow, Reactive Streams Spec 3:17: effectively unbounded Pump.Pump(); } } else if (message is Cancel) { IsDownstreamCompleted = true; ExposedPublisher.Shutdown(new NormalShutdownException(string.Empty)); Pump.Pump(); } else return false; return true; } } internal abstract class ActorProcessorImpl : ActorBase, IPump { #region Internal classes private sealed class InternalBatchingInputBuffer : BatchingInputBuffer { private readonly ActorProcessorImpl _impl; public InternalBatchingInputBuffer(int count, ActorProcessorImpl impl) : base(count, impl) { _impl = impl; } protected override void InputOnError(Exception e) => _impl.OnError(e); } private sealed class InternalExposedPublisherReceive : ExposedPublisherReceive { private readonly ActorProcessorImpl _self; public InternalExposedPublisherReceive(Receive activeReceive, Action<object> unhandled, ActorProcessorImpl self) : base(activeReceive, unhandled) { _self = self; } internal override void ReceiveExposedPublisher(ExposedPublisher publisher) { _self.PrimaryOutputs.SubReceive.CurrentReceive(publisher); Context.Become(ActiveReceive); } } #endregion public readonly ActorMaterializerSettings Settings; protected virtual IInputs PrimaryInputs { get; } protected virtual IOutputs PrimaryOutputs { get; } private ILoggingAdapter _log; protected ActorProcessorImpl(ActorMaterializerSettings settings) { Settings = settings; PrimaryInputs = new InternalBatchingInputBuffer(settings.InitialInputBufferSize, this); PrimaryOutputs = new SimpleOutputs(Self, this); _receive = new InternalExposedPublisherReceive(ActiveReceive, Unhandled, this); this.Init(); } protected ILoggingAdapter Log => _log ?? (_log = Context.GetLogger()); public TransferState TransferState { get; set; } public Action CurrentAction { get; set; } public bool IsPumpFinished => this.IsPumpFinished(); private readonly ExposedPublisherReceive _receive; /// <summary> /// Subclass may override <see cref="ActiveReceive"/> /// </summary> protected sealed override bool Receive(object message) => _receive.Apply(message); protected virtual bool ActiveReceive(object message) => PrimaryInputs.SubReceive.CurrentReceive(message) || PrimaryOutputs.SubReceive.CurrentReceive(message); public void InitialPhase(int waitForUpstream, TransferPhase andThen) => Pumps.InitialPhase(this, waitForUpstream, andThen); public void WaitForUpstream(int waitForUpstream) => Pumps.WaitForUpstream(this, waitForUpstream); public void GotUpstreamSubscription() => Pumps.GotUpstreamSubscription(this); public void NextPhase(TransferPhase phase) => Pumps.NextPhase(this, phase); public void Pump() => Pumps.Pump(this); public void PumpFailed(Exception e) => Fail(e); public virtual void PumpFinished() { PrimaryInputs.Cancel(); PrimaryOutputs.Complete(); Context.Stop(Self); } protected virtual void OnError(Exception e) => Fail(e); protected virtual void Fail(Exception e) { if (Settings.IsDebugLogging) Log.Debug("Failed due to: {0}", e.Message); PrimaryInputs.Cancel(); PrimaryOutputs.Error(e); Context.Stop(Self); } protected override void PostStop() { PrimaryInputs.Cancel(); PrimaryOutputs.Error(new AbruptTerminationException(Self)); } protected override void PostRestart(Exception reason) { base.PostRestart(reason); throw new IllegalStateException("This actor cannot be restarted", reason); } } }
using System; using System.Collections.Generic; using System.Linq; using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; using P3Net.Kraken.Diagnostics; using P3Net.Kraken.UnitTesting; namespace Tests.P3Net.Kraken.Diagnostics { [TestClass] public class IntegralArgumentConstraintExtensionsTests : UnitTest { #region SByte #region IsGreaterThanOrEqualToZero [TestMethod] public void IsGreaterThanOrEqualToZero_SByte_IsTrue () { var target = new ArgumentConstraint<sbyte>(new Argument<sbyte>("a", 10)); target.IsGreaterThanOrEqualToZero(); } [TestMethod] public void IsGreaterThanOrEqualToZero_SByte_IsFalse () { var target = new ArgumentConstraint<sbyte>(new Argument<sbyte>("a", -10)); Action work = () => target.IsGreaterThanOrEqualToZero(); work.Should().Throw<ArgumentOutOfRangeException>(); } [TestMethod] public void IsGreaterThanOrEqualToZero_SByte_IsZero () { var target = new ArgumentConstraint<sbyte>(new Argument<sbyte>("a", 0)); target.IsGreaterThanOrEqualToZero(); } [TestMethod] public void IsGreaterThanOrEqualToZero_SByte_WithMessage () { var target = new ArgumentConstraint<sbyte>(new Argument<sbyte>("a", -10)); Action work = () => target.IsGreaterThanOrEqualToZero("Testing"); work.Should().Throw<ArgumentOutOfRangeException>().ContainingMessage("Testing"); } #endregion #region IsGreaterThanZero [TestMethod] public void IsGreaterThanZero_SByte_IsTrue () { var target = new ArgumentConstraint<sbyte>(new Argument<sbyte>("a", 10)); target.IsGreaterThanZero(); } [TestMethod] public void IsGreaterThanZero_SByte_IsFalse () { var target = new ArgumentConstraint<sbyte>(new Argument<sbyte>("a", -10)); Action work = () => target.IsGreaterThanZero(); work.Should().Throw<ArgumentOutOfRangeException>(); } [TestMethod] public void IsGreaterThanZero_SByte_IsZero () { var target = new ArgumentConstraint<sbyte>(new Argument<sbyte>("a", 0)); Action work = () => target.IsGreaterThanZero(); work.Should().Throw<ArgumentOutOfRangeException>(); } [TestMethod] public void IsGreaterThanZero_SByte_WithMessage () { var target = new ArgumentConstraint<sbyte>(new Argument<sbyte>("a", -10)); Action work = () => target.IsGreaterThanZero("Testing"); work.Should().Throw<ArgumentOutOfRangeException>().ContainingMessage("Testing"); } #endregion #region IsLessThanOrEqualToZero [TestMethod] public void IsLessThanOrEqualToZero_SByte_IsTrue () { var target = new ArgumentConstraint<sbyte>(new Argument<sbyte>("a", -10)); target.IsLessThanOrEqualToZero(); } [TestMethod] public void IsLessThanOrEqualToZero_SByte_IsFalse () { var target = new ArgumentConstraint<sbyte>(new Argument<sbyte>("a", 10)); Action work = () => target.IsLessThanOrEqualToZero(); work.Should().Throw<ArgumentOutOfRangeException>(); } [TestMethod] public void IsLessThanOrEqualToZero_SByte_IsZero () { var target = new ArgumentConstraint<sbyte>(new Argument<sbyte>("a", 0)); target.IsLessThanOrEqualToZero(); } [TestMethod] public void IsLessThanOrEqualToZero_SByte_WithMessage () { var target = new ArgumentConstraint<sbyte>(new Argument<sbyte>("a", 10)); Action work = () => target.IsLessThanOrEqualToZero("Testing"); work.Should().Throw<ArgumentOutOfRangeException>().ContainingMessage("Testing"); } #endregion #region IsLessThanZero [TestMethod] public void IsLessThanZero_SByte_IsTrue () { var target = new ArgumentConstraint<sbyte>(new Argument<sbyte>("a", -10)); target.IsLessThanZero(); } [TestMethod] public void IsLessThanZero_SByte_IsFalse () { var target = new ArgumentConstraint<sbyte>(new Argument<sbyte>("a", 10)); Action work = () => target.IsLessThanZero(); work.Should().Throw<ArgumentOutOfRangeException>(); } [TestMethod] public void IsLessThanZero_SByte_IsZero () { var target = new ArgumentConstraint<sbyte>(new Argument<sbyte>("a", 0)); Action work = () => target.IsLessThanZero(); work.Should().Throw<ArgumentOutOfRangeException>(); } [TestMethod] public void IsLessThanZero_SByte_WithMessage () { var target = new ArgumentConstraint<sbyte>(new Argument<sbyte>("a", 10)); Action work = () => target.IsLessThanZero("Testing"); work.Should().Throw<ArgumentOutOfRangeException>().ContainingMessage("Testing"); } #endregion #region IsNotZero [TestMethod] public void IsNotZero_SByte_IsTrue () { var target = new ArgumentConstraint<sbyte>(new Argument<sbyte>("a", 10)); target.IsNotZero(); } [TestMethod] public void IsNotZero_SByte_IsFalse () { var target = new ArgumentConstraint<sbyte>(new Argument<sbyte>("a", 0)); Action work = () => target.IsNotZero(); work.Should().Throw<ArgumentOutOfRangeException>(); } [TestMethod] public void IsNotZero_SByte_WithMessage () { var target = new ArgumentConstraint<sbyte>(new Argument<sbyte>("a", 0)); Action work = () => target.IsNotZero("Testing"); work.Should().Throw<ArgumentOutOfRangeException>().ContainingMessage("Testing"); } #endregion #region IsZero [TestMethod] public void IsZero_SByte_IsTrue () { var target = new ArgumentConstraint<sbyte>(new Argument<sbyte>("a", 0)); target.IsZero(); } [TestMethod] public void IsZero_SByte_IsFalse () { var target = new ArgumentConstraint<sbyte>(new Argument<sbyte>("a", 10)); Action work = () => target.IsZero(); work.Should().Throw<ArgumentOutOfRangeException>(); } [TestMethod] public void IsZero_SByte_WithMessage () { var target = new ArgumentConstraint<sbyte>(new Argument<sbyte>("a", 10)); Action work = () => target.IsZero("Testing"); work.Should().Throw<ArgumentOutOfRangeException>().ContainingMessage("Testing"); } #endregion #endregion #region Int16 #region IsGreaterThanOrEqualToZero [TestMethod] public void IsGreaterThanOrEqualToZero_Int16_IsTrue () { var target = new ArgumentConstraint<short>(new Argument<short>("a", 10)); target.IsGreaterThanOrEqualToZero(); } [TestMethod] public void IsGreaterThanOrEqualToZero_Int16_IsFalse () { var target = new ArgumentConstraint<short>(new Argument<short>("a", -10)); Action work = () => target.IsGreaterThanOrEqualToZero(); work.Should().Throw<ArgumentOutOfRangeException>(); } [TestMethod] public void IsGreaterThanOrEqualToZero_Int16_IsZero () { var target = new ArgumentConstraint<short>(new Argument<short>("a", 0)); target.IsGreaterThanOrEqualToZero(); } [TestMethod] public void IsGreaterThanOrEqualToZero_Int16_WithMessage () { var target = new ArgumentConstraint<short>(new Argument<short>("a", -10)); Action work = () => target.IsGreaterThanOrEqualToZero("Testing"); work.Should().Throw<ArgumentOutOfRangeException>().ContainingMessage("Testing"); } #endregion #region IsGreaterThanZero [TestMethod] public void IsGreaterThanZero_Int16_IsTrue () { var target = new ArgumentConstraint<short>(new Argument<short>("a", 10)); target.IsGreaterThanZero(); } [TestMethod] public void IsGreaterThanZero_Int16_IsFalse () { var target = new ArgumentConstraint<short>(new Argument<short>("a", -10)); Action work = () => target.IsGreaterThanZero(); work.Should().Throw<ArgumentOutOfRangeException>(); } [TestMethod] public void IsGreaterThanZero_Int16_IsZero () { var target = new ArgumentConstraint<short>(new Argument<short>("a", 0)); Action work = () => target.IsGreaterThanZero(); work.Should().Throw<ArgumentOutOfRangeException>(); } [TestMethod] public void IsGreaterThanZero_Int16_WithMessage () { var target = new ArgumentConstraint<short>(new Argument<short>("a", -10)); Action work = () => target.IsGreaterThanZero("Testing"); work.Should().Throw<ArgumentOutOfRangeException>().ContainingMessage("Testing"); } #endregion #region IsLessThanOrEqualToZero [TestMethod] public void IsLessThanOrEqualToZero_Int16_IsTrue () { var target = new ArgumentConstraint<short>(new Argument<short>("a", -10)); target.IsLessThanOrEqualToZero(); } [TestMethod] public void IsLessThanOrEqualToZero_Int16_IsFalse () { var target = new ArgumentConstraint<short>(new Argument<short>("a", 10)); Action work = () => target.IsLessThanOrEqualToZero(); work.Should().Throw<ArgumentOutOfRangeException>(); } [TestMethod] public void IsLessThanOrEqualToZero_Int16_IsZero () { var target = new ArgumentConstraint<short>(new Argument<short>("a", 0)); target.IsLessThanOrEqualToZero(); } [TestMethod] public void IsLessThanOrEqualToZero_Int16_WithMessage () { var target = new ArgumentConstraint<short>(new Argument<short>("a", 10)); Action work = () => target.IsLessThanOrEqualToZero("Testing"); work.Should().Throw<ArgumentOutOfRangeException>().ContainingMessage("Testing"); } #endregion #region IsLessThanZero [TestMethod] public void IsLessThanZero_Int16_IsTrue () { var target = new ArgumentConstraint<short>(new Argument<short>("a", -10)); target.IsLessThanZero(); } [TestMethod] public void IsLessThanZero_Int16_IsFalse () { var target = new ArgumentConstraint<short>(new Argument<short>("a", 10)); Action work = () => target.IsLessThanZero(); work.Should().Throw<ArgumentOutOfRangeException>(); } [TestMethod] public void IsLessThanZero_Int16_IsZero () { var target = new ArgumentConstraint<short>(new Argument<short>("a", 0)); Action work = () => target.IsLessThanZero(); work.Should().Throw<ArgumentOutOfRangeException>(); } [TestMethod] public void IsLessThanZero_Int16_WithMessage () { var target = new ArgumentConstraint<short>(new Argument<short>("a", 10)); Action work = () => target.IsLessThanZero("Testing"); work.Should().Throw<ArgumentOutOfRangeException>().ContainingMessage("Testing"); } #endregion #region IsNotZero [TestMethod] public void IsNotZero_Int16_IsTrue () { var target = new ArgumentConstraint<short>(new Argument<short>("a", 10)); target.IsNotZero(); } [TestMethod] public void IsNotZero_Int16_IsFalse () { var target = new ArgumentConstraint<short>(new Argument<short>("a", 0)); Action work = () => target.IsNotZero(); work.Should().Throw<ArgumentOutOfRangeException>(); } [TestMethod] public void IsNotZero_Int16_WithMessage () { var target = new ArgumentConstraint<short>(new Argument<short>("a", 0)); Action work = () => target.IsNotZero("Testing"); work.Should().Throw<ArgumentOutOfRangeException>().ContainingMessage("Testing"); } #endregion #region IsZero [TestMethod] public void IsZero_Int16_IsTrue () { var target = new ArgumentConstraint<short>(new Argument<short>("a", 0)); target.IsZero(); } [TestMethod] public void IsZero_Int16_IsFalse () { var target = new ArgumentConstraint<short>(new Argument<short>("a", 10)); Action work = () => target.IsZero(); work.Should().Throw<ArgumentOutOfRangeException>(); } [TestMethod] public void IsZero_Int16_WithMessage () { var target = new ArgumentConstraint<short>(new Argument<short>("a", 10)); Action work = () => target.IsZero("Testing"); work.Should().Throw<ArgumentOutOfRangeException>().ContainingMessage("Testing"); } #endregion #endregion #region Int32 #region IsGreaterThanOrEqualToZero [TestMethod] public void IsGreaterThanOrEqualToZero_Int32_IsTrue () { var target = new ArgumentConstraint<int>(new Argument<int>("a", 10)); target.IsGreaterThanOrEqualToZero(); } [TestMethod] public void IsGreaterThanOrEqualToZero_Int32_IsFalse () { var target = new ArgumentConstraint<int>(new Argument<int>("a", -10)); Action work = () => target.IsGreaterThanOrEqualToZero(); work.Should().Throw<ArgumentOutOfRangeException>(); } [TestMethod] public void IsGreaterThanOrEqualToZero_Int32_IsZero () { var target = new ArgumentConstraint<int>(new Argument<int>("a", 0)); target.IsGreaterThanOrEqualToZero(); } [TestMethod] public void IsGreaterThanOrEqualToZero_Int32_WithMessage () { var target = new ArgumentConstraint<int>(new Argument<int>("a", -10)); Action work = () => target.IsGreaterThanOrEqualToZero("Testing"); work.Should().Throw<ArgumentOutOfRangeException>().ContainingMessage("Testing"); } #endregion #region IsGreaterThanZero [TestMethod] public void IsGreaterThanZero_Int32_IsTrue () { var target = new ArgumentConstraint<int>(new Argument<int>("a", 10)); target.IsGreaterThanZero(); } [TestMethod] public void IsGreaterThanZero_Int32_IsFalse () { var target = new ArgumentConstraint<int>(new Argument<int>("a", -10)); Action work = () => target.IsGreaterThanZero(); work.Should().Throw<ArgumentOutOfRangeException>(); } [TestMethod] public void IsGreaterThanZero_Int32_IsZero () { var target = new ArgumentConstraint<int>(new Argument<int>("a", 0)); Action work = () => target.IsGreaterThanZero(); work.Should().Throw<ArgumentOutOfRangeException>(); } [TestMethod] public void IsGreaterThanZero_Int32_WithMessage () { var target = new ArgumentConstraint<int>(new Argument<int>("a", -10)); Action work = () => target.IsGreaterThanZero("Testing"); work.Should().Throw<ArgumentOutOfRangeException>().ContainingMessage("Testing"); } #endregion #region IsLessThanOrEqualToZero [TestMethod] public void IsLessThanOrEqualToZero_Int32_IsTrue () { var target = new ArgumentConstraint<int>(new Argument<int>("a", -10)); target.IsLessThanOrEqualToZero(); } [TestMethod] public void IsLessThanOrEqualToZero_Int32_IsFalse () { var target = new ArgumentConstraint<int>(new Argument<int>("a", 10)); Action work = () => target.IsLessThanOrEqualToZero(); work.Should().Throw<ArgumentOutOfRangeException>(); } [TestMethod] public void IsLessThanOrEqualToZero_Int32_IsZero () { var target = new ArgumentConstraint<int>(new Argument<int>("a", 0)); target.IsLessThanOrEqualToZero(); } [TestMethod] public void IsLessThanOrEqualToZero_Int32_WithMessage () { var target = new ArgumentConstraint<int>(new Argument<int>("a", 10)); Action work = () => target.IsLessThanOrEqualToZero("Testing"); work.Should().Throw<ArgumentOutOfRangeException>().ContainingMessage("Testing"); } #endregion #region IsLessThanZero [TestMethod] public void IsLessThanZero_Int32_IsTrue () { var target = new ArgumentConstraint<int>(new Argument<int>("a", -10)); target.IsLessThanZero(); } [TestMethod] public void IsLessThanZero_Int32_IsFalse () { var target = new ArgumentConstraint<int>(new Argument<int>("a", 10)); Action work = () => target.IsLessThanZero(); work.Should().Throw<ArgumentOutOfRangeException>(); } [TestMethod] public void IsLessThanZero_Int32_IsZero () { var target = new ArgumentConstraint<int>(new Argument<int>("a", 0)); Action work = () => target.IsLessThanZero(); work.Should().Throw<ArgumentOutOfRangeException>(); } [TestMethod] public void IsLessThanZero_Int32_WithMessage () { var target = new ArgumentConstraint<int>(new Argument<int>("a", 10)); Action work = () => target.IsLessThanZero("Testing"); work.Should().Throw<ArgumentOutOfRangeException>().ContainingMessage("Testing"); } #endregion #region IsNotZero [TestMethod] public void IsNotZero_Int32_IsTrue () { var target = new ArgumentConstraint<int>(new Argument<int>("a", 10)); target.IsNotZero(); } [TestMethod] public void IsNotZero_Int32_IsFalse () { var target = new ArgumentConstraint<int>(new Argument<int>("a", 0)); Action work = () => target.IsNotZero(); work.Should().Throw<ArgumentOutOfRangeException>(); } [TestMethod] public void IsNotZero_Int32_WithMessage () { var target = new ArgumentConstraint<int>(new Argument<int>("a", 0)); Action work = () => target.IsNotZero("Testing"); work.Should().Throw<ArgumentOutOfRangeException>().ContainingMessage("Testing"); } #endregion #region IsZero [TestMethod] public void IsZero_Int32_IsTrue () { var target = new ArgumentConstraint<int>(new Argument<int>("a", 0)); target.IsZero(); } [TestMethod] public void IsZero_Int32_IsFalse () { var target = new ArgumentConstraint<int>(new Argument<int>("a", 10)); Action work = () => target.IsZero(); work.Should().Throw<ArgumentOutOfRangeException>(); } [TestMethod] public void IsZero_Int32_WithMessage () { var target = new ArgumentConstraint<int>(new Argument<int>("a", 10)); Action work = () => target.IsZero("Testing"); work.Should().Throw<ArgumentOutOfRangeException>().ContainingMessage("Testing"); } #endregion #endregion #region Int64 #region IsGreaterThanOrEqualToZero [TestMethod] public void IsGreaterThanOrEqualToZero_Int64_IsTrue () { var target = new ArgumentConstraint<long>(new Argument<long>("a", 10)); target.IsGreaterThanOrEqualToZero(); } [TestMethod] public void IsGreaterThanOrEqualToZero_Int64_IsFalse () { var target = new ArgumentConstraint<long>(new Argument<long>("a", -10)); Action work = () => target.IsGreaterThanOrEqualToZero(); work.Should().Throw<ArgumentOutOfRangeException>(); } [TestMethod] public void IsGreaterThanOrEqualToZero_Int64_IsZero () { var target = new ArgumentConstraint<long>(new Argument<long>("a", 0)); target.IsGreaterThanOrEqualToZero(); } [TestMethod] public void IsGreaterThanOrEqualToZero_Int64_WithMessage () { var target = new ArgumentConstraint<long>(new Argument<long>("a", -10)); Action work = () => target.IsGreaterThanOrEqualToZero("Testing"); work.Should().Throw<ArgumentOutOfRangeException>().ContainingMessage("Testing"); } #endregion #region IsGreaterThanZero [TestMethod] public void IsGreaterThanZero_Int64_IsTrue () { var target = new ArgumentConstraint<long>(new Argument<long>("a", 10)); target.IsGreaterThanZero(); } [TestMethod] public void IsGreaterThanZero_Int64_IsFalse () { var target = new ArgumentConstraint<long>(new Argument<long>("a", -10)); Action work = () => target.IsGreaterThanZero(); work.Should().Throw<ArgumentOutOfRangeException>(); } [TestMethod] public void IsGreaterThanZero_Int64_IsZero () { var target = new ArgumentConstraint<long>(new Argument<long>("a", 0)); Action work = () => target.IsGreaterThanZero(); work.Should().Throw<ArgumentOutOfRangeException>(); } [TestMethod] public void IsGreaterThanZero_Int64_WithMessage () { var target = new ArgumentConstraint<long>(new Argument<long>("a", -10)); Action work = () => target.IsGreaterThanZero("Testing"); work.Should().Throw<ArgumentOutOfRangeException>().ContainingMessage("Testing"); } #endregion #region IsLessThanOrEqualToZero [TestMethod] public void IsLessThanOrEqualToZero_Int64_IsTrue () { var target = new ArgumentConstraint<long>(new Argument<long>("a", -10)); target.IsLessThanOrEqualToZero(); } [TestMethod] public void IsLessThanOrEqualToZero_Int64_IsFalse () { var target = new ArgumentConstraint<long>(new Argument<long>("a", 10)); Action work = () => target.IsLessThanOrEqualToZero(); work.Should().Throw<ArgumentOutOfRangeException>(); } [TestMethod] public void IsLessThanOrEqualToZero_Int64_IsZero () { var target = new ArgumentConstraint<long>(new Argument<long>("a", 0)); target.IsLessThanOrEqualToZero(); } [TestMethod] public void IsLessThanOrEqualToZero_Int64_WithMessage () { var target = new ArgumentConstraint<long>(new Argument<long>("a", 10)); Action work = () => target.IsLessThanOrEqualToZero("Testing"); work.Should().Throw<ArgumentOutOfRangeException>().ContainingMessage("Testing"); } #endregion #region IsLessThanZero [TestMethod] public void IsLessThanZero_Int64_IsTrue () { var target = new ArgumentConstraint<long>(new Argument<long>("a", -10)); target.IsLessThanZero(); } [TestMethod] public void IsLessThanZero_Int64_IsFalse () { var target = new ArgumentConstraint<long>(new Argument<long>("a", 10)); Action work = () => target.IsLessThanZero(); work.Should().Throw<ArgumentOutOfRangeException>(); } [TestMethod] public void IsLessThanZero_Int64_IsZero () { var target = new ArgumentConstraint<long>(new Argument<long>("a", 0)); Action work = () => target.IsLessThanZero(); work.Should().Throw<ArgumentOutOfRangeException>(); } [TestMethod] public void IsLessThanZero_Int64_WithMessage () { var target = new ArgumentConstraint<long>(new Argument<long>("a", 10)); Action work = () => target.IsLessThanZero("Testing"); work.Should().Throw<ArgumentOutOfRangeException>().ContainingMessage("Testing"); } #endregion #region IsNotZero [TestMethod] public void IsNotZero_Int64_IsTrue () { var target = new ArgumentConstraint<long>(new Argument<long>("a", 10)); target.IsNotZero(); } [TestMethod] public void IsNotZero_Int64_IsFalse () { var target = new ArgumentConstraint<long>(new Argument<long>("a", 0)); Action work = () => target.IsNotZero(); work.Should().Throw<ArgumentOutOfRangeException>(); } [TestMethod] public void IsNotZero_Int64_WithMessage () { var target = new ArgumentConstraint<long>(new Argument<long>("a", 0)); Action work = () => target.IsNotZero("Testing"); work.Should().Throw<ArgumentOutOfRangeException>().ContainingMessage("Testing"); } #endregion #region IsZero [TestMethod] public void IsZero_Int64_IsTrue () { var target = new ArgumentConstraint<long>(new Argument<long>("a", 0)); target.IsZero(); } [TestMethod] public void IsZero_Int64_IsFalse () { var target = new ArgumentConstraint<long>(new Argument<long>("a", 10)); Action work = () => target.IsZero(); work.Should().Throw<ArgumentOutOfRangeException>(); } [TestMethod] public void IsZero_Int64_WithMessage () { var target = new ArgumentConstraint<long>(new Argument<long>("a", 10)); Action work = () => target.IsZero("Testing"); work.Should().Throw<ArgumentOutOfRangeException>().ContainingMessage("Testing"); } #endregion #endregion #region Byte #region IsNotZero [TestMethod] public void IsNotZero_Byte_IsTrue () { var target = new ArgumentConstraint<byte>(new Argument<byte>("a", 10)); target.IsNotZero(); } [TestMethod] public void IsNotZero_Byte_IsFalse () { var target = new ArgumentConstraint<byte>(new Argument<byte>("a", 0)); Action work = () => target.IsNotZero(); work.Should().Throw<ArgumentOutOfRangeException>(); } [TestMethod] public void IsNotZero_Byte_WithMessage () { var target = new ArgumentConstraint<byte>(new Argument<byte>("a", 0)); Action work = () => target.IsNotZero("Testing"); work.Should().Throw<ArgumentOutOfRangeException>().ContainingMessage("Testing"); } #endregion #region IsZero [TestMethod] public void IsZero_Byte_IsTrue () { var target = new ArgumentConstraint<byte>(new Argument<byte>("a", 0)); target.IsZero(); } [TestMethod] public void IsZero_Byte_IsFalse () { var target = new ArgumentConstraint<byte>(new Argument<byte>("a", 10)); Action work = () => target.IsZero(); work.Should().Throw<ArgumentOutOfRangeException>(); } [TestMethod] public void IsZero_Byte_WithMessage () { var target = new ArgumentConstraint<byte>(new Argument<byte>("a", 10)); Action work = () => target.IsZero("Testing"); work.Should().Throw<ArgumentOutOfRangeException>().ContainingMessage("Testing"); } #endregion #endregion #region UInt16 #region IsNotZero [TestMethod] public void IsNotZero_UInt16_IsTrue () { var target = new ArgumentConstraint<ushort>(new Argument<ushort>("a", 10)); target.IsNotZero(); } [TestMethod] public void IsNotZero_UInt16_IsFalse () { var target = new ArgumentConstraint<ushort>(new Argument<ushort>("a", 0)); Action work = () => target.IsNotZero(); work.Should().Throw<ArgumentOutOfRangeException>(); } [TestMethod] public void IsNotZero_UInt16_WithMessage () { var target = new ArgumentConstraint<ushort>(new Argument<ushort>("a", 0)); Action work = () => target.IsNotZero("Testing"); work.Should().Throw<ArgumentOutOfRangeException>().ContainingMessage("Testing"); } #endregion #region IsZero [TestMethod] public void IsZero_UInt16_IsTrue () { var target = new ArgumentConstraint<ushort>(new Argument<ushort>("a", 0)); target.IsZero(); } [TestMethod] public void IsZero_UInt16_IsFalse () { var target = new ArgumentConstraint<ushort>(new Argument<ushort>("a", 10)); Action work = () => target.IsZero(); work.Should().Throw<ArgumentOutOfRangeException>(); } [TestMethod] public void IsZero_UInt16_WithMessage () { var target = new ArgumentConstraint<ushort>(new Argument<ushort>("a", 10)); Action work = () => target.IsZero("Testing"); work.Should().Throw<ArgumentOutOfRangeException>().ContainingMessage("Testing"); } #endregion #endregion #region UInt32 #region IsNotZero [TestMethod] public void IsNotZero_UInt32_IsTrue () { var target = new ArgumentConstraint<uint>(new Argument<uint>("a", 10)); target.IsNotZero(); } [TestMethod] public void IsNotZero_UInt32_IsFalse () { var target = new ArgumentConstraint<uint>(new Argument<uint>("a", 0)); Action work = () => target.IsNotZero(); work.Should().Throw<ArgumentOutOfRangeException>(); } [TestMethod] public void IsNotZero_UInt32_WithMessage () { var target = new ArgumentConstraint<uint>(new Argument<uint>("a", 0)); Action work = () => target.IsNotZero("Testing"); work.Should().Throw<ArgumentOutOfRangeException>().ContainingMessage("Testing"); } #endregion #region IsZero [TestMethod] public void IsZero_UInt32_IsTrue () { var target = new ArgumentConstraint<uint>(new Argument<uint>("a", 0)); target.IsZero(); } [TestMethod] public void IsZero_UInt32_IsFalse () { var target = new ArgumentConstraint<uint>(new Argument<uint>("a", 10)); Action work = () => target.IsZero(); work.Should().Throw<ArgumentOutOfRangeException>(); } [TestMethod] public void IsZero_UInt32_WithMessage () { var target = new ArgumentConstraint<uint>(new Argument<uint>("a", 10)); Action work = () => target.IsZero("Testing"); work.Should().Throw<ArgumentOutOfRangeException>().ContainingMessage("Testing"); } #endregion #endregion #region UInt64 #region IsNotZero [TestMethod] public void IsNotZero_UInt64_IsTrue () { var target = new ArgumentConstraint<ulong>(new Argument<ulong>("a", 10)); target.IsNotZero(); } [TestMethod] public void IsNotZero_UInt64_IsFalse () { var target = new ArgumentConstraint<ulong>(new Argument<ulong>("a", 0)); Action work = () => target.IsNotZero(); work.Should().Throw<ArgumentOutOfRangeException>(); } [TestMethod] public void IsNotZero_UInt64_WithMessage () { var target = new ArgumentConstraint<ulong>(new Argument<ulong>("a", 0)); Action work = () => target.IsNotZero("Testing"); work.Should().Throw<ArgumentOutOfRangeException>().ContainingMessage("Testing"); } #endregion #region IsZero [TestMethod] public void IsZero_UInt64_IsTrue () { var target = new ArgumentConstraint<ulong>(new Argument<ulong>("a", 0)); target.IsZero(); } [TestMethod] public void IsZero_UInt64_IsFalse () { var target = new ArgumentConstraint<ulong>(new Argument<ulong>("a", 10)); Action work = () => target.IsZero(); work.Should().Throw<ArgumentOutOfRangeException>(); } [TestMethod] public void IsZero_UInt64_WithMessage () { var target = new ArgumentConstraint<ulong>(new Argument<ulong>("a", 10)); Action work = () => target.IsZero("Testing"); work.Should().Throw<ArgumentOutOfRangeException>().ContainingMessage("Testing"); } #endregion #endregion } }
/* * Copyright (c) 2013 Calvin Rien * * Based on the JSON parser by Patrick van Bergen * http://techblog.procurios.nl/k/618/news/view/14605/14863/How-do-I-write-my-own-parser-for-JSON.html * * Simplified it so that it doesn't throw exceptions * and can be used in Unity iPhone with maximum code stripping. * * 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; using System.Collections.Generic; using System.IO; using System.Text; namespace Microsoft.Azure.Engagement.Unity.MiniJSON { // Example usage: // // using UnityEngine; // using System.Collections; // using System.Collections.Generic; // using MiniJSON; // // public class MiniJSONTest : MonoBehaviour { // void Start () { // var jsonString = "{ \"array\": [1.44,2,3], " + // "\"object\": {\"key1\":\"value1\", \"key2\":256}, " + // "\"string\": \"The quick brown fox \\\"jumps\\\" over the lazy dog \", " + // "\"unicode\": \"\\u3041 Men\u00fa sesi\u00f3n\", " + // "\"int\": 65536, " + // "\"float\": 3.1415926, " + // "\"bool\": true, " + // "\"null\": null }"; // // var dict = Json.Deserialize(jsonString) as Dictionary<string,object>; // // Debug.Log("deserialized: " + dict.GetType()); // Debug.Log("dict['array'][0]: " + ((List<object>) dict["array"])[0]); // Debug.Log("dict['string']: " + (string) dict["string"]); // Debug.Log("dict['float']: " + (double) dict["float"]); // floats come out as doubles // Debug.Log("dict['int']: " + (long) dict["int"]); // ints come out as longs // Debug.Log("dict['unicode']: " + (string) dict["unicode"]); // // var str = Json.Serialize(dict); // // Debug.Log("serialized: " + str); // } // } /// <summary> /// This class encodes and decodes JSON strings. /// Spec. details, see http://www.json.org/ /// /// JSON uses Arrays and Objects. These correspond here to the datatypes IList and IDictionary. /// All numbers are parsed to doubles. /// </summary> public static class Json { /// <summary> /// Parses the string json into a value /// </summary> /// <param name="json">A JSON string.</param> /// <returns>An List&lt;object&gt;, a Dictionary&lt;string, object&gt;, a double, an integer,a string, null, true, or false</returns> public static object Deserialize(string json) { // save the string for debug information if (json == null) { return null; } return Parser.Parse(json); } sealed class Parser : IDisposable { const string WORD_BREAK = "{}[],:\""; public static bool IsWordBreak(char c) { return Char.IsWhiteSpace(c) || WORD_BREAK.IndexOf(c) != -1; } enum TOKEN { NONE, CURLY_OPEN, CURLY_CLOSE, SQUARED_OPEN, SQUARED_CLOSE, COLON, COMMA, STRING, NUMBER, TRUE, FALSE, NULL }; StringReader json; Parser(string jsonString) { json = new StringReader(jsonString); } public static object Parse(string jsonString) { using (var instance = new Parser(jsonString)) { return instance.ParseValue(); } } public void Dispose() { json.Dispose(); json = null; } Dictionary<string, object> ParseObject() { Dictionary<string, object> table = new Dictionary<string, object>(); // ditch opening brace json.Read(); // { while (true) { switch (NextToken) { case TOKEN.NONE: return null; case TOKEN.COMMA: continue; case TOKEN.CURLY_CLOSE: return table; default: // name string name = ParseString(); if (name == null) { return null; } // : if (NextToken != TOKEN.COLON) { return null; } // ditch the colon json.Read(); // value table[name] = ParseValue(); break; } } } List<object> ParseArray() { List<object> array = new List<object>(); // ditch opening bracket json.Read(); // [ var parsing = true; while (parsing) { TOKEN nextToken = NextToken; switch (nextToken) { case TOKEN.NONE: return null; case TOKEN.COMMA: continue; case TOKEN.SQUARED_CLOSE: parsing = false; break; default: object value = ParseByToken(nextToken); array.Add(value); break; } } return array; } object ParseValue() { TOKEN nextToken = NextToken; return ParseByToken(nextToken); } object ParseByToken(TOKEN token) { switch (token) { case TOKEN.STRING: return ParseString(); case TOKEN.NUMBER: return ParseNumber(); case TOKEN.CURLY_OPEN: return ParseObject(); case TOKEN.SQUARED_OPEN: return ParseArray(); case TOKEN.TRUE: return true; case TOKEN.FALSE: return false; case TOKEN.NULL: return null; default: return null; } } string ParseString() { StringBuilder s = new StringBuilder(); char c; // ditch opening quote json.Read(); bool parsing = true; while (parsing) { if (json.Peek() == -1) { parsing = false; break; } c = NextChar; switch (c) { case '"': parsing = false; break; case '\\': if (json.Peek() == -1) { parsing = false; break; } c = NextChar; switch (c) { case '"': case '\\': case '/': s.Append(c); break; case 'b': s.Append('\b'); break; case 'f': s.Append('\f'); break; case 'n': s.Append('\n'); break; case 'r': s.Append('\r'); break; case 't': s.Append('\t'); break; case 'u': var hex = new char[4]; for (int i=0; i< 4; i++) { hex[i] = NextChar; } s.Append((char) Convert.ToInt32(new string(hex), 16)); break; } break; default: s.Append(c); break; } } return s.ToString(); } object ParseNumber() { string number = NextWord; if (number.IndexOf('.') == -1) { long parsedInt; Int64.TryParse(number, out parsedInt); return parsedInt; } double parsedDouble; Double.TryParse(number, out parsedDouble); return parsedDouble; } void EatWhitespace() { while (Char.IsWhiteSpace(PeekChar)) { json.Read(); if (json.Peek() == -1) { break; } } } char PeekChar { get { return Convert.ToChar(json.Peek()); } } char NextChar { get { return Convert.ToChar(json.Read()); } } string NextWord { get { StringBuilder word = new StringBuilder(); while (!IsWordBreak(PeekChar)) { word.Append(NextChar); if (json.Peek() == -1) { break; } } return word.ToString(); } } TOKEN NextToken { get { EatWhitespace(); if (json.Peek() == -1) { return TOKEN.NONE; } switch (PeekChar) { case '{': return TOKEN.CURLY_OPEN; case '}': json.Read(); return TOKEN.CURLY_CLOSE; case '[': return TOKEN.SQUARED_OPEN; case ']': json.Read(); return TOKEN.SQUARED_CLOSE; case ',': json.Read(); return TOKEN.COMMA; case '"': return TOKEN.STRING; case ':': return TOKEN.COLON; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '-': return TOKEN.NUMBER; } switch (NextWord) { case "false": return TOKEN.FALSE; case "true": return TOKEN.TRUE; case "null": return TOKEN.NULL; } return TOKEN.NONE; } } } /// <summary> /// Converts a IDictionary / IList object or a simple type (string, int, etc.) into a JSON string /// </summary> /// <param name="json">A Dictionary&lt;string, object&gt; / List&lt;object&gt;</param> /// <returns>A JSON encoded string, or null if object 'json' is not serializable</returns> public static string Serialize(object obj) { return Serializer.Serialize(obj); } sealed class Serializer { StringBuilder builder; Serializer() { builder = new StringBuilder(); } public static string Serialize(object obj) { var instance = new Serializer(); instance.SerializeValue(obj); return instance.builder.ToString(); } void SerializeValue(object value) { IList asList; IDictionary asDict; string asStr; if (value == null) { builder.Append("null"); } else if ((asStr = value as string) != null) { SerializeString(asStr); } else if (value is bool) { builder.Append((bool) value ? "true" : "false"); } else if ((asList = value as IList) != null) { SerializeArray(asList); } else if ((asDict = value as IDictionary) != null) { SerializeObject(asDict); } else if (value is char) { SerializeString(new string((char) value, 1)); } else { SerializeOther(value); } } void SerializeObject(IDictionary obj) { bool first = true; builder.Append('{'); foreach (object e in obj.Keys) { if (!first) { builder.Append(','); } SerializeString(e.ToString()); builder.Append(':'); SerializeValue(obj[e]); first = false; } builder.Append('}'); } void SerializeArray(IList anArray) { builder.Append('['); bool first = true; foreach (object obj in anArray) { if (!first) { builder.Append(','); } SerializeValue(obj); first = false; } builder.Append(']'); } void SerializeString(string str) { builder.Append('\"'); char[] charArray = str.ToCharArray(); foreach (var c in charArray) { switch (c) { case '"': builder.Append("\\\""); break; case '\\': builder.Append("\\\\"); break; case '\b': builder.Append("\\b"); break; case '\f': builder.Append("\\f"); break; case '\n': builder.Append("\\n"); break; case '\r': builder.Append("\\r"); break; case '\t': builder.Append("\\t"); break; default: int codepoint = Convert.ToInt32(c); if ((codepoint >= 32) && (codepoint <= 126)) { builder.Append(c); } else { builder.Append("\\u"); builder.Append(codepoint.ToString("x4")); } break; } } builder.Append('\"'); } void SerializeOther(object value) { // NOTE: decimals lose precision during serialization. // They always have, I'm just letting you know. // Previously floats and doubles lost precision too. if (value is float) { builder.Append(((float) value).ToString("R")); } else if (value is int || value is uint || value is long || value is sbyte || value is byte || value is short || value is ushort || value is ulong) { builder.Append(value); } else if (value is double || value is decimal) { builder.Append(Convert.ToDouble(value).ToString("R")); } else { SerializeString(value.ToString()); } } } } }
// 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 0.17.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Compute { using System.Threading.Tasks; using Microsoft.Rest.Azure; using Models; /// <summary> /// Extension methods for VirtualMachineImagesOperations. /// </summary> public static partial class VirtualMachineImagesOperationsExtensions { /// <summary> /// Gets a virtual machine image. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='location'> /// </param> /// <param name='publisherName'> /// </param> /// <param name='offer'> /// </param> /// <param name='skus'> /// </param> /// <param name='version'> /// </param> public static VirtualMachineImage Get(this IVirtualMachineImagesOperations operations, string location, string publisherName, string offer, string skus, string version) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IVirtualMachineImagesOperations)s).GetAsync(location, publisherName, offer, skus, version), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets a virtual machine image. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='location'> /// </param> /// <param name='publisherName'> /// </param> /// <param name='offer'> /// </param> /// <param name='skus'> /// </param> /// <param name='version'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<VirtualMachineImage> GetAsync(this IVirtualMachineImagesOperations operations, string location, string publisherName, string offer, string skus, string version, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(location, publisherName, offer, skus, version, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets a list of virtual machine images. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='location'> /// </param> /// <param name='publisherName'> /// </param> /// <param name='offer'> /// </param> /// <param name='skus'> /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> public static System.Collections.Generic.IList<VirtualMachineImageResource> List(this IVirtualMachineImagesOperations operations, string location, string publisherName, string offer, string skus, Microsoft.Rest.Azure.OData.ODataQuery<VirtualMachineImageResource> odataQuery = default(Microsoft.Rest.Azure.OData.ODataQuery<VirtualMachineImageResource>)) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IVirtualMachineImagesOperations)s).ListAsync(location, publisherName, offer, skus, odataQuery), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets a list of virtual machine images. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='location'> /// </param> /// <param name='publisherName'> /// </param> /// <param name='offer'> /// </param> /// <param name='skus'> /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<System.Collections.Generic.IList<VirtualMachineImageResource>> ListAsync(this IVirtualMachineImagesOperations operations, string location, string publisherName, string offer, string skus, Microsoft.Rest.Azure.OData.ODataQuery<VirtualMachineImageResource> odataQuery = default(Microsoft.Rest.Azure.OData.ODataQuery<VirtualMachineImageResource>), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.ListWithHttpMessagesAsync(location, publisherName, offer, skus, odataQuery, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets a list of virtual machine image offers. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='location'> /// </param> /// <param name='publisherName'> /// </param> public static System.Collections.Generic.IList<VirtualMachineImageResource> ListOffers(this IVirtualMachineImagesOperations operations, string location, string publisherName) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IVirtualMachineImagesOperations)s).ListOffersAsync(location, publisherName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets a list of virtual machine image offers. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='location'> /// </param> /// <param name='publisherName'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<System.Collections.Generic.IList<VirtualMachineImageResource>> ListOffersAsync(this IVirtualMachineImagesOperations operations, string location, string publisherName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.ListOffersWithHttpMessagesAsync(location, publisherName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets a list of virtual machine image publishers. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='location'> /// </param> public static System.Collections.Generic.IList<VirtualMachineImageResource> ListPublishers(this IVirtualMachineImagesOperations operations, string location) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IVirtualMachineImagesOperations)s).ListPublishersAsync(location), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets a list of virtual machine image publishers. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='location'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<System.Collections.Generic.IList<VirtualMachineImageResource>> ListPublishersAsync(this IVirtualMachineImagesOperations operations, string location, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.ListPublishersWithHttpMessagesAsync(location, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets a list of virtual machine image skus. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='location'> /// </param> /// <param name='publisherName'> /// </param> /// <param name='offer'> /// </param> public static System.Collections.Generic.IList<VirtualMachineImageResource> ListSkus(this IVirtualMachineImagesOperations operations, string location, string publisherName, string offer) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IVirtualMachineImagesOperations)s).ListSkusAsync(location, publisherName, offer), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets a list of virtual machine image skus. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='location'> /// </param> /// <param name='publisherName'> /// </param> /// <param name='offer'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<System.Collections.Generic.IList<VirtualMachineImageResource>> ListSkusAsync(this IVirtualMachineImagesOperations operations, string location, string publisherName, string offer, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.ListSkusWithHttpMessagesAsync(location, publisherName, offer, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
// SymbolSetDumper.cs // Script#/Core/Compiler // This source code is subject to terms and conditions of the Apache License, Version 2.0. // using System; using System.Collections; using System.CodeDom.Compiler; using System.Diagnostics; using System.IO; namespace ScriptSharp.ScriptModel { #if DEBUG internal sealed class SymbolSetDumper { private IndentedTextWriter _writer; public SymbolSetDumper(TextWriter writer) { Debug.Assert(writer != null); _writer = new IndentedTextWriter(writer, " "); } private void DumpClass(ClassSymbol classSymbol) { _writer.Write("Extension Methods: "); _writer.WriteLine(classSymbol.IsExtenderClass); if (classSymbol.BaseClass != null) { _writer.Write("BaseClass: "); _writer.WriteLine(classSymbol.BaseClass.Name); } if (classSymbol.Interfaces != null) { _writer.WriteLine("Interfaces:"); _writer.Indent++; foreach (InterfaceSymbol interfaceSymbol in classSymbol.Interfaces) { _writer.WriteLine(interfaceSymbol.Name); } _writer.Indent--; } if (classSymbol.Constructor != null) { _writer.WriteLine("Constructor:"); _writer.Indent++; DumpSymbol(classSymbol.Constructor); _writer.Indent--; } if (classSymbol.StaticConstructor != null) { _writer.WriteLine("StaticConstructor:"); _writer.Indent++; DumpSymbol(classSymbol.StaticConstructor); _writer.Indent--; } if (classSymbol.Indexer != null) { _writer.WriteLine("Indexer:"); _writer.Indent++; DumpSymbol(classSymbol.Indexer); _writer.Indent--; } } private void DumpConstructor(ConstructorSymbol ctorSymbol) { if (ctorSymbol.Parameters != null) { _writer.Write("Parameters:"); _writer.Indent++; foreach (ParameterSymbol paramSymbol in ctorSymbol.Parameters) { DumpSymbol(paramSymbol); } _writer.Indent--; } } private void DumpDelegate(DelegateSymbol delegateSymbol) { } private void DumpEnumeration(EnumerationSymbol enumSymbol) { _writer.Write("Flags: "); _writer.WriteLine(enumSymbol.Flags); } private void DumpEnumerationField(EnumerationFieldSymbol enumFieldSymbol) { } private void DumpEvent(EventSymbol eventSymbol) { } private void DumpField(FieldSymbol fieldSymbol) { } private void DumpIndexer(IndexerSymbol indexerSymbol) { _writer.Write("ReadOnly: "); _writer.WriteLine(indexerSymbol.IsReadOnly); _writer.Write("Abstract: "); _writer.WriteLine(indexerSymbol.IsAbstract); } private void DumpInterface(InterfaceSymbol interfaceSymbol) { } private void DumpMember(MemberSymbol memberSymbol) { _writer.Indent++; _writer.Write("AssociatedType: "); _writer.WriteLine(memberSymbol.AssociatedType.Name); _writer.Write("Visibility: "); _writer.WriteLine(memberSymbol.Visibility.ToString()); _writer.Write("Generated Name: "); _writer.WriteLine(memberSymbol.GeneratedName); if (memberSymbol.InterfaceMember != null) { _writer.Write("Associated Interface Member: "); _writer.Write(memberSymbol.InterfaceMember.Parent.Name); _writer.Write("."); _writer.WriteLine(memberSymbol.InterfaceMember.Name); } switch (memberSymbol.Type) { case SymbolType.Field: DumpField((FieldSymbol)memberSymbol); break; case SymbolType.EnumerationField: DumpEnumerationField((EnumerationFieldSymbol)memberSymbol); break; case SymbolType.Constructor: DumpConstructor((ConstructorSymbol)memberSymbol); break; case SymbolType.Property: DumpProperty((PropertySymbol)memberSymbol); break; case SymbolType.Indexer: DumpIndexer((IndexerSymbol)memberSymbol); break; case SymbolType.Event: DumpEvent((EventSymbol)memberSymbol); break; case SymbolType.Method: DumpMethod((MethodSymbol)memberSymbol); break; } _writer.Indent--; } private void DumpMethod(MethodSymbol methodSymbol) { _writer.Write("Abstract: "); _writer.WriteLine(methodSymbol.IsAbstract); if (methodSymbol.Conditions != null) { _writer.WriteLine("Conditions:"); _writer.Indent++; foreach (string condition in methodSymbol.Conditions) { _writer.WriteLine(condition); } _writer.Indent--; } if (methodSymbol.Parameters != null) { _writer.WriteLine("Parameters:"); _writer.Indent++; foreach (ParameterSymbol paramSymbol in methodSymbol.Parameters) { DumpSymbol(paramSymbol); } _writer.Indent--; } } private void DumpNamespace(NamespaceSymbol namespaceSymbol) { _writer.Write("HasApplicationTypes: "); _writer.WriteLine(namespaceSymbol.HasApplicationTypes); _writer.WriteLine("Types:"); _writer.Indent++; ArrayList types = new ArrayList(namespaceSymbol.Types.Count); foreach (TypeSymbol type in namespaceSymbol.Types) { types.Add(type); } types.Sort(new SymbolComparer()); foreach (TypeSymbol type in types) { DumpSymbol(type); } _writer.Indent--; } private void DumpParameter(ParameterSymbol parameterSymbol) { _writer.Write("AssociatedType: "); _writer.WriteLine(parameterSymbol.ValueType.Name); _writer.Write("Mode: "); _writer.WriteLine(parameterSymbol.Mode.ToString()); } private void DumpProperty(PropertySymbol propertySymbol) { _writer.Write("ReadOnly: "); _writer.WriteLine(propertySymbol.IsReadOnly); _writer.Write("Abstract: "); _writer.WriteLine(propertySymbol.IsAbstract); } private void DumpSymbol(Symbol symbol) { _writer.Write(symbol.Type.ToString()); _writer.Write(": "); _writer.WriteLine(symbol.Name); switch (symbol.Type) { case SymbolType.Namespace: DumpNamespace((NamespaceSymbol)symbol); break; case SymbolType.Class: case SymbolType.Interface: case SymbolType.Enumeration: case SymbolType.Delegate: case SymbolType.Record: DumpType((TypeSymbol)symbol); break; case SymbolType.Field: case SymbolType.EnumerationField: case SymbolType.Constructor: case SymbolType.Property: case SymbolType.Indexer: case SymbolType.Event: case SymbolType.Method: DumpMember((MemberSymbol)symbol); break; case SymbolType.Parameter: DumpParameter((ParameterSymbol)symbol); break; } } public void DumpSymbols(SymbolSet symbols) { ArrayList namespaces = new ArrayList(symbols.Namespaces.Count); foreach (NamespaceSymbol ns in symbols.Namespaces) { namespaces.Add(ns); } namespaces.Sort(new SymbolComparer()); foreach (NamespaceSymbol ns in namespaces) { DumpSymbol(ns); _writer.WriteLine(); } } private void DumpType(TypeSymbol typeSymbol) { _writer.Indent++; _writer.Write("Application Type: "); _writer.WriteLine(typeSymbol.IsApplicationType); _writer.Write("Public: "); _writer.WriteLine(typeSymbol.IsPublic); _writer.Write("Generated Name: "); _writer.WriteLine(typeSymbol.GeneratedName); switch (typeSymbol.Type) { case SymbolType.Class: case SymbolType.Record: DumpClass((ClassSymbol)typeSymbol); break; case SymbolType.Interface: DumpInterface((InterfaceSymbol)typeSymbol); break; case SymbolType.Enumeration: DumpEnumeration((EnumerationSymbol)typeSymbol); break; case SymbolType.Delegate: DumpDelegate((DelegateSymbol)typeSymbol); break; } _writer.WriteLine("Members:"); _writer.Indent++; foreach (MemberSymbol member in typeSymbol.Members) { DumpSymbol(member); } _writer.Indent--; _writer.WriteLine(); _writer.Indent--; } private sealed class SymbolComparer : IComparer { public int Compare(object x, object y) { return String.Compare(((Symbol)x).Name, ((Symbol)y).Name); } } } #endif // DEBUG }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Management.Automation.Internal; using System.Runtime.Serialization; using System.Security.Permissions; namespace System.Management.Automation.Remoting { /// <summary> /// This enum defines the error message ids used by the resource manager to get /// localized messages. /// /// Related error ids are organized in a pre-defined range of values. /// </summary> internal enum PSRemotingErrorId : uint { // OS related 1-9 DefaultRemotingExceptionMessage = 0, OutOfMemory = 1, // Pipeline related range: 10-99 PipelineIdsDoNotMatch = 10, PipelineNotFoundOnServer = 11, PipelineStopped = 12, // Runspace, Host, UI and RawUI related range: 200-299 RunspaceAlreadyExists = 200, RunspaceIdsDoNotMatch = 201, RemoteRunspaceOpenFailed = 202, RunspaceCannotBeFound = 203, ResponsePromptIdCannotBeFound = 204, RemoteHostCallFailed = 205, RemoteHostMethodNotImplemented = 206, RemoteHostDataEncodingNotSupported = 207, RemoteHostDataDecodingNotSupported = 208, NestedPipelineNotSupported = 209, RelativeUriForRunspacePathNotSupported = 210, RemoteHostDecodingFailed = 211, MustBeAdminToOverrideThreadOptions = 212, RemoteHostPromptForCredentialModifiedCaption = 213, RemoteHostPromptForCredentialModifiedMessage = 214, RemoteHostReadLineAsSecureStringPrompt = 215, RemoteHostGetBufferContents = 216, RemoteHostPromptSecureStringPrompt = 217, WinPERemotingNotSupported = 218, // reserved range: 300-399 // Encoding/Decoding and fragmentation related range: 400-499 ReceivedUnsupportedRemoteHostCall = 400, ReceivedUnsupportedAction = 401, ReceivedUnsupportedDataType = 402, MissingDestination = 403, MissingTarget = 404, MissingRunspaceId = 405, MissingDataType = 406, MissingCallId = 407, MissingMethodName = 408, MissingIsStartFragment = 409, MissingProperty = 410, ObjectIdsNotMatching = 411, FragmentIdsNotInSequence = 412, ObjectIsTooBig = 413, MissingIsEndFragment = 414, DeserializedObjectIsNull = 415, BlobLengthNotInRange = 416, DecodingErrorForErrorRecord = 417, DecodingErrorForPipelineStateInfo = 418, DecodingErrorForRunspaceStateInfo = 419, ReceivedUnsupportedRemotingTargetInterfaceType = 420, UnknownTargetClass = 421, MissingTargetClass = 422, DecodingErrorForRunspacePoolStateInfo = 423, DecodingErrorForMinRunspaces = 424, DecodingErrorForMaxRunspaces = 425, DecodingErrorForPowerShellStateInfo = 426, DecodingErrorForThreadOptions = 427, CantCastPropertyToExpectedType = 428, CantCastRemotingDataToPSObject = 429, CantCastCommandToPSObject = 430, CantCastParameterToPSObject = 431, ObjectIdCannotBeLessThanZero = 432, NotEnoughHeaderForRemoteDataObject = 433, // reserved range: 500-599 // Remote Session related range: 600-699 RemotingDestinationNotForMe = 600, ClientNegotiationTimeout = 601, ClientNegotiationFailed = 602, ServerRequestedToCloseSession = 603, ServerNegotiationFailed = 604, ServerNegotiationTimeout = 605, ClientRequestedToCloseSession = 606, FatalErrorCausingClose = 607, ClientKeyExchangeFailed = 608, ServerKeyExchangeFailed = 609, ClientNotFoundCapabilityProperties = 610, ServerNotFoundCapabilityProperties = 611, // reserved range: 700-799 // Transport related range: 800-899 ConnectFailed = 801, CloseIsCalled = 802, ForceClosed = 803, CloseFailed = 804, CloseCompleted = 805, UnsupportedWaitHandleType = 806, ReceivedDataStreamIsNotStdout = 807, StdInIsNotOpen = 808, NativeWriteFileFailed = 809, NativeReadFileFailed = 810, InvalidSchemeValue = 811, ClientReceiveFailed = 812, ClientSendFailed = 813, CommandHandleIsNull = 814, StdInCannotBeSetToNoWait = 815, PortIsOutOfRange = 816, ServerProcessExited = 817, CannotGetStdInHandle = 818, CannotGetStdOutHandle = 819, CannotGetStdErrHandle = 820, CannotSetStdInHandle = 821, CannotSetStdOutHandle = 822, CannotSetStdErrHandle = 823, InvalidConfigurationName = 824, ConnectSkipCheckFailed = 825, // Error codes added to support new WSMan Fan-In Model API CreateSessionFailed = 851, CreateExFailed = 853, ConnectExCallBackError = 854, SendExFailed = 855, SendExCallBackError = 856, ReceiveExFailed = 857, ReceiveExCallBackError = 858, RunShellCommandExFailed = 859, RunShellCommandExCallBackError = 860, CommandSendExFailed = 861, CommandSendExCallBackError = 862, CommandReceiveExFailed = 863, CommandReceiveExCallBackError = 864, CloseExCallBackError = 866, // END: Error codes added to support new WSMan Fan-In Model API // BEGIN: Error IDs introduced for URI redirection RedirectedURINotWellFormatted = 867, URIEndPointNotResolved = 868, // END: Error IDs introduced for URI redirection // BEGIN: Error IDs introduced for Quota Management ReceivedObjectSizeExceededMaximumClient = 869, ReceivedDataSizeExceededMaximumClient = 870, ReceivedObjectSizeExceededMaximumServer = 871, ReceivedDataSizeExceededMaximumServer = 872, // END: Error IDs introduced for Quota Management // BEGIN: Error IDs introduced for startup script StartupScriptThrewTerminatingError = 873, // END: Error IDs introduced for startup script TroubleShootingHelpTopic = 874, // BEGIN: Error IDs introduced for disconnect/reconnect DisconnectShellExFailed = 875, DisconnectShellExCallBackErrr = 876, ReconnectShellExFailed = 877, ReconnectShellExCallBackErrr = 878, // END: Error IDs introduced for disconnect/reconnect // Cmdlets related range: 900-999 RemoteRunspaceInfoHasDuplicates = 900, RemoteRunspaceInfoLimitExceeded = 901, RemoteRunspaceOpenUnknownState = 902, UriSpecifiedNotValid = 903, RemoteRunspaceClosed = 904, RemoteRunspaceNotAvailableForSpecifiedComputer = 905, RemoteRunspaceNotAvailableForSpecifiedRunspaceId = 906, StopPSJobWhatIfTarget = 907, InvalidJobStateGeneral = 909, JobWithSpecifiedNameNotFound = 910, JobWithSpecifiedInstanceIdNotFound = 911, JobWithSpecifiedSessionIdNotFound = 912, JobWithSpecifiedNameNotCompleted = 913, JobWithSpecifiedSessionIdNotCompleted = 914, JobWithSpecifiedInstanceIdNotCompleted = 915, RemovePSJobWhatIfTarget = 916, ComputerNameParamNotSupported = 917, RunspaceParamNotSupported = 918, RemoteRunspaceNotAvailableForSpecifiedName = 919, RemoteRunspaceNotAvailableForSpecifiedSessionId = 920, ItemNotFoundInRepository = 921, CannotRemoveJob = 922, NewRunspaceAmbiguousAuthentication = 923, WildCardErrorFilePathParameter = 924, FilePathNotFromFileSystemProvider = 925, FilePathShouldPS1Extension = 926, PSSessionConfigurationName = 927, PSSessionAppName = 928, // Custom Shell commands CSCDoubleParameterOutOfRange = 929, URIRedirectionReported = 930, NoMoreInputWrites = 931, InvalidComputerName = 932, ProxyAmbiguousAuthentication = 933, ProxyCredentialWithoutAccess = 934, // Start-PSSession related error codes. PushedRunspaceMustBeOpen = 951, HostDoesNotSupportPushRunspace = 952, RemoteRunspaceHasMultipleMatchesForSpecifiedRunspaceId = 953, RemoteRunspaceHasMultipleMatchesForSpecifiedSessionId = 954, RemoteRunspaceHasMultipleMatchesForSpecifiedName = 955, RemoteRunspaceDoesNotSupportPushRunspace = 956, HostInNestedPrompt = 957, InvalidVMId = 959, InvalidVMNameNoVM = 960, InvalidVMNameMultipleVM = 961, HyperVModuleNotAvailable = 962, InvalidUsername = 963, InvalidCredential = 964, VMSessionConnectFailed = 965, InvalidContainerId = 966, CannotCreateProcessInContainer = 967, CannotTerminateProcessInContainer = 968, ContainersFeatureNotEnabled = 969, RemoteSessionHyperVSocketServerConstructorFailure = 970, ContainerSessionConnectFailed = 973, RemoteSessionHyperVSocketClientConstructorSetSocketOptionFailure = 974, InvalidVMState = 975, // Invoke-Command related error codes. InvalidVMIdNotSingle = 981, InvalidVMNameNotSingle = 982, // SessionState Description related messages WsmanMaxRedirectionCountVariableDescription = 1001, PSDefaultSessionOptionDescription = 1002, PSSenderInfoDescription = 1004, // IPC for Background jobs related errors: 2000 IPCUnknownNodeType = 2001, IPCInsufficientDataforElement = 2002, IPCWrongAttributeCountForDataElement = 2003, IPCOnlyTextExpectedInDataElement = 2004, IPCWrongAttributeCountForElement = 2005, IPCUnknownElementReceived = 2006, IPCSupportsOnlyDefaultAuth = 2007, IPCWowComponentNotPresent = 2008, IPCServerProcessReportedError = 2100, IPCServerProcessExited = 2101, IPCErrorProcessingServerData = 2102, IPCUnknownCommandGuid = 2103, IPCNoSignalForSession = 2104, IPCSignalTimedOut = 2105, IPCCloseTimedOut = 2106, IPCExceptionLaunchingProcess = 2107, } /// <summary> /// This static class defines the resource base name used by remoting errors. /// It also provides a convenience method to get the localized strings. /// </summary> internal static class PSRemotingErrorInvariants { /// <summary> /// This method is a convenience method to retrieve the localized string. /// </summary> /// <param name="resourceString"> /// This parameter holds the string in the resource file. /// </param> /// <param name="args"> /// Optional parameters required by the resource string formating information. /// </param> /// <returns> /// The formatted localized string. /// </returns> internal static string FormatResourceString(string resourceString, params object[] args) { string resourceFormatedString = StringUtil.Format(resourceString, args); return resourceFormatedString; } } /// <summary> /// This exception is used by remoting code to indicated a data structure handler related error. /// </summary> [Serializable] public class PSRemotingDataStructureException : RuntimeException { #region Constructors /// <summary> /// Default constructor. /// </summary> public PSRemotingDataStructureException() : base(PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.DefaultRemotingExceptionMessage, typeof(PSRemotingDataStructureException).FullName)) { SetDefaultErrorRecord(); } /// <summary> /// This constuctor takes a localized string as the error message. /// </summary> /// <param name="message"> /// A localized string as an error message. /// </param> public PSRemotingDataStructureException(string message) : base(message) { SetDefaultErrorRecord(); } /// <summary> /// This constuctor takes a localized string as the error message, and an inner exception. /// </summary> /// <param name="message"> /// A localized string as an error message. /// </param> /// <param name="innerException"> /// Inner exception. /// </param> public PSRemotingDataStructureException(string message, Exception innerException) : base(message, innerException) { SetDefaultErrorRecord(); } /// <summary> /// This constructor takes an error id and optional parameters. /// </summary> /// <param name="resourceString"> /// The resource string in the base resource file. /// </param> /// <param name="args"> /// Optional parameters required to format the resource string. /// </param> internal PSRemotingDataStructureException(string resourceString, params object[] args) : base(PSRemotingErrorInvariants.FormatResourceString(resourceString, args)) { SetDefaultErrorRecord(); } /// <summary> /// This constuctor takes an inner exception and an error id. /// </summary> /// <param name="innerException"> /// Inner exception. /// </param> /// <param name="resourceString"> /// The resource string in the base resource file. /// </param> /// <param name="args"> /// Optional parameters required to format the resource string. /// </param> internal PSRemotingDataStructureException(Exception innerException, string resourceString, params object[] args) : base(PSRemotingErrorInvariants.FormatResourceString(resourceString, args), innerException) { SetDefaultErrorRecord(); } /// <summary> /// This constructor is required by serialization. /// </summary> /// <param name="info"></param> /// <param name="context"></param> protected PSRemotingDataStructureException(SerializationInfo info, StreamingContext context) : base(info, context) { } #endregion Constructors /// <summary> /// Set the default ErrorRecord. /// </summary> private void SetDefaultErrorRecord() { SetErrorCategory(ErrorCategory.ResourceUnavailable); SetErrorId(typeof(PSRemotingDataStructureException).FullName); } } /// <summary> /// This exception is used by remoting code to indicate an error condition in network operations. /// </summary> [Serializable] public class PSRemotingTransportException : RuntimeException { private int _errorCode; private string _transportMessage; #region Constructors /// <summary> /// This is the default constructor. /// </summary> public PSRemotingTransportException() : base(PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.DefaultRemotingExceptionMessage, typeof(PSRemotingTransportException).FullName)) { SetDefaultErrorRecord(); } /// <summary> /// This constructor takes a localized error message. /// </summary> /// <param name="message"> /// A localized error message. /// </param> public PSRemotingTransportException(string message) : base(message) { SetDefaultErrorRecord(); } /// <summary> /// This constructor takes a localized message and an inner exception. /// </summary> /// <param name="message"> /// Localized error message. /// </param> /// <param name="innerException"> /// Inner exception. /// </param> public PSRemotingTransportException(string message, Exception innerException) : base(message, innerException) { SetDefaultErrorRecord(); } /// <summary> /// This constructor takes an error id and optional parameters. /// </summary> /// <param name="errorId"> /// The error id in the base resource file. /// </param> /// <param name="resourceString"> /// The resource string in the base resource file. /// </param> /// <param name="args"> /// Optional parameters required to format the resource string. /// </param> internal PSRemotingTransportException(PSRemotingErrorId errorId, string resourceString, params object[] args) : base(PSRemotingErrorInvariants.FormatResourceString(resourceString, args)) { SetDefaultErrorRecord(); _errorCode = (int)errorId; } /// <summary> /// This constuctor takes an inner exception and an error id. /// </summary> /// <param name="innerException"> /// Inner exception. /// </param> /// <param name="resourceString"> /// The resource string in the base resource file. /// </param> /// <param name="args"> /// Optional parameters required to format the resource string. /// </param> internal PSRemotingTransportException(Exception innerException, string resourceString, params object[] args) : base(PSRemotingErrorInvariants.FormatResourceString(resourceString, args), innerException) { SetDefaultErrorRecord(); } /// <summary> /// This constructor is required by serialization. /// </summary> /// <param name="info"></param> /// <param name="context"></param> /// <exception cref="ArgumentNullException"> /// 1. info is null. /// </exception> protected PSRemotingTransportException(SerializationInfo info, StreamingContext context) : base(info, context) { if (info == null) { throw new PSArgumentNullException(nameof(info)); } _errorCode = info.GetInt32("ErrorCode"); _transportMessage = info.GetString("TransportMessage"); } #endregion Constructors /// <summary> /// Serializes the exception data. /// </summary> /// <param name="info">Serialization information.</param> /// <param name="context">Streaming context.</param> public override void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) { throw new PSArgumentNullException(nameof(info)); } base.GetObjectData(info, context); // If there are simple fields, serialize them with info.AddValue info.AddValue("ErrorCode", _errorCode); info.AddValue("TransportMessage", _transportMessage); } /// <summary> /// Set the default ErrorRecord. /// </summary> protected void SetDefaultErrorRecord() { SetErrorCategory(ErrorCategory.ResourceUnavailable); SetErrorId(typeof(PSRemotingDataStructureException).FullName); } /// <summary> /// The error code from native library API call. /// </summary> public int ErrorCode { get { return _errorCode; } set { _errorCode = value; } } /// <summary> /// This the message from the native transport layer. /// </summary> public string TransportMessage { get { return _transportMessage; } set { _transportMessage = value; } } } /// <summary> /// This exception is used by PowerShell's remoting infrastructure to notify a URI redirection /// exception. /// </summary> [Serializable] public class PSRemotingTransportRedirectException : PSRemotingTransportException { #region Constructor /// <summary> /// This is the default constructor. /// </summary> public PSRemotingTransportRedirectException() : base(PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.DefaultRemotingExceptionMessage, typeof(PSRemotingTransportRedirectException).FullName)) { SetDefaultErrorRecord(); } /// <summary> /// This constructor takes a localized error message. /// </summary> /// <param name="message"> /// A localized error message. /// </param> public PSRemotingTransportRedirectException(string message) : base(message) { } /// <summary> /// This constructor takes a localized message and an inner exception. /// </summary> /// <param name="message"> /// Localized error message. /// </param> /// <param name="innerException"> /// Inner exception. /// </param> public PSRemotingTransportRedirectException(string message, Exception innerException) : base(message, innerException) { } /// <summary> /// This constuctor takes an inner exception and an error id. /// </summary> /// <param name="innerException"> /// Inner exception. /// </param> /// <param name="resourceString"> /// The resource string in the base resource file. /// </param> /// <param name="args"> /// Optional parameters required to format the resource string. /// </param> internal PSRemotingTransportRedirectException(Exception innerException, string resourceString, params object[] args) : base(innerException, resourceString, args) { } /// <summary> /// This constructor is required by serialization. /// </summary> /// <param name="info"></param> /// <param name="context"></param> /// <exception cref="ArgumentNullException"> /// 1. info is null. /// </exception> protected PSRemotingTransportRedirectException(SerializationInfo info, StreamingContext context) : base(info, context) { if (info == null) { throw new PSArgumentNullException(nameof(info)); } RedirectLocation = info.GetString("RedirectLocation"); } /// <summary> /// This constructor takes an redirect URI, error id and optional parameters. /// </summary> /// <param name="redirectLocation"> /// String specifying a redirect location. /// </param> /// <param name="errorId"> /// The error id in the base resource file. /// </param> /// <param name="resourceString"> /// The resource string in the base resource file. /// </param> /// <param name="args"> /// Optional parameters required to format the resource string. /// </param> internal PSRemotingTransportRedirectException(string redirectLocation, PSRemotingErrorId errorId, string resourceString, params object[] args) : base(errorId, resourceString, args) { RedirectLocation = redirectLocation; } #endregion #region Public overrides /// <summary> /// Serializes the exception data. /// </summary> /// <param name="info">Serialization information.</param> /// <param name="context">Streaming context.</param> public override void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) { throw new PSArgumentNullException(nameof(info)); } base.GetObjectData(info, context); // If there are simple fields, serialize them with info.AddValue info.AddValue("RedirectLocation", RedirectLocation); } #endregion #region Properties /// <summary> /// String specifying a redirect location. /// </summary> public string RedirectLocation { get; } #endregion } /// <summary> /// This exception is used by PowerShell Direct errors. /// </summary> [Serializable] public class PSDirectException : RuntimeException { #region Constructor /// <summary> /// This constuctor takes a localized string as the error message. /// </summary> /// <param name="message"> /// A localized string as an error message. /// </param> public PSDirectException(string message) : base(message) { } #endregion Constructor } }
using System; using RLToolkit.Logger; namespace RLToolkit.Extensions { /// <summary> /// Class that will add a 'single-only' functionality to the Gtk.ToggleButton /// </summary> public class ToggleButtonExclusiveSelectionGroup { private Gtk.ToggleButton[] controlList = new Gtk.ToggleButton[0]; private int selected = -1; /// <summary> /// Method to append a ToggleButton in the control array /// </summary> /// <param name="input">the ToggleButton to add</param> /// <returns>true if the button has been added</returns> public bool Append(Gtk.ToggleButton input) { if (FindInGroup(input) != -1) { // already exist this.Log().Warn("Cannot add the same control twice. Aborting"); return false; } // add to the list this.Log().Debug("Adding a control to the control list"); Gtk.ToggleButton[] newArray = new Gtk.ToggleButton[controlList.Length+1]; for (int i = 0; i<controlList.Length; i++) { newArray[i] = controlList[i]; } newArray[controlList.Length] = input; // replace the list with the new one controlList = newArray; return true; } /// <summary> /// Method to remove a control from the control Array, using the index in the array /// </summary> /// <param name="index">Index to remove</param> /// <returns>True if the button has been removed</returns> /// <remarks>Will unselect the current selection. (to prevent keeping ghost selection)</remarks> public bool Remove(int index) { // validation if (index < 0) { this.Log().Warn("Index to remove is outside of bound (negative), check for errors."); return false; } if (index >= controlList.Length) { this.Log().Warn("Index to remove is outside of bound (positive), check for errors."); return false; } // unselect everything Unselect(); // removal this.Log().Debug("Trying to remove the control"); Gtk.ToggleButton[] newArray = new Gtk.ToggleButton[controlList.Length-1]; for (int i = 0; i<index; i++) { newArray[i] = controlList[i]; } for (int i = (index+1); i<controlList.Length; i++) { newArray[i-1] = controlList[i]; } // swap the list this.Log().Debug("Swapping the list with the new one"); controlList = newArray; return true; } /// <summary> /// Method that removes a control from the control array, using the control itself /// </summary> /// <param name="input">The control to remove</param> /// <returns>True if the control has been removed</returns> /// <remarks>Will unselect the current selection. (to prevent keeping ghost selection)</remarks> public bool Remove(Gtk.ToggleButton input) { int index = FindInGroup(input); if (index == -1) { this.Log().Info("Trying to remove a control that doesn't exist."); return false; } // use the real select method return Remove(index); } /// <summary> /// Method to remove all the controls from the control array /// </summary> /// <remarks>Will unselect the current selection. (to prevent keeping ghost selection)</remarks> public void RemoveAll() { this.Log().Debug("Removed all controls from the list."); Unselect(); controlList = new Gtk.ToggleButton[0]; } /// <summary> /// Method to toggle a specific control using it index. /// </summary> /// <param name="index">The index of the control in the array to turn on.</param> /// <returns>True, if the selection is successful</returns> /// <remarks>Will unselect the current selection if there is.</remarks> public bool Select(int index) { if (selected == index) { this.Log().Debug("Trying to select the same index."); return false; } // unselect the old selection only if something is selected if (selected > -1) { if (!SetSelection(selected, false)) { this.Log().Debug("An Error occured while trying to deselect the previously selected button."); return false; } } // select the new one selected = index; if (!SetSelection(index, true)) { this.Log().Debug("An Erro occured while trying to select the new button."); return false; } // everything went well return true; } /// <summary> /// Method to toggle a specific control. /// </summary> /// <param name="input">The control to Toggle 'ON'</param> /// <returns>True, if the selection is successful</returns> /// <remarks>Will unselect the current selection if there is.</remarks> public bool Select(Gtk.ToggleButton input) { int index = FindInGroup(input); if (index == -1) { this.Log().Info("Trying to select a control that doesn't exist."); return false; } // use the real select method return Select(index); } /// <summary> /// Method to unselect the whole group /// </summary> /// <returns>True, if the selection is unselected, False if nothing selected.</returns> public bool Unselect() { if (selected == -1) { this.Log().Debug("Trying to deselect while nothing selected."); return false; } // unselecting this.Log().Debug("Deselecting all buttons."); SetSelection(selected, false); selected = -1; return true; } /// <summary> /// Method to return the number of button in the control array. /// </summary> /// <returns>The count of controls</returns> public int GetCountButton() { return controlList.Length; } /// <summary> /// Method that will return the index of a control if found, in the Control Array /// </summary> /// <returns>The index of the control in the group, 0-based, -1 if not found.</returns> /// <param name="input">The control to find.</param> public int FindInGroup(Gtk.ToggleButton input) { this.Log().Debug("Trying to find input: " + input.Name); for (int i = 0; i<controlList.Length; i++) { if (input == controlList[i]) { this.Log().Debug("Control found."); return i; } } this.Log().Debug("Control not found."); return -1; } private bool SetSelection(int index, bool state) { if (index < 0) { this.Log().Warn("Index is outside of bound (negative), check for errors."); return false; } if (index >= controlList.Length) { this.Log().Warn("Index is outside of bound (positive), check for errors."); return false; } this.Log().Debug("Setting control state to " + state.ToString()); controlList[index].Active = state; return true; } } }
// // EditActions.cs // // Author: // Jonathan Pobst <monkey@jpobst.com> // // Copyright (c) 2010 Jonathan Pobst // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using Gtk; using Cairo; namespace Pinta.Core { public class EditActions { public Gtk.Action Undo { get; private set; } public Gtk.Action Redo { get; private set; } public Gtk.Action Cut { get; private set; } public Gtk.Action Copy { get; private set; } public Gtk.Action Paste { get; private set; } public Gtk.Action PasteIntoNewLayer { get; private set; } public Gtk.Action PasteIntoNewImage { get; private set; } public Gtk.Action EraseSelection { get; private set; } public Gtk.Action FillSelection { get; private set; } public Gtk.Action InvertSelection { get; private set; } public Gtk.Action SelectAll { get; private set; } public Gtk.Action Deselect { get; private set; } public EditActions () { Gtk.IconFactory fact = new Gtk.IconFactory (); fact.Add ("Menu.Edit.Deselect.png", new Gtk.IconSet (PintaCore.Resources.GetIcon ("Menu.Edit.Deselect.png"))); fact.Add ("Menu.Edit.EraseSelection.png", new Gtk.IconSet (PintaCore.Resources.GetIcon ("Menu.Edit.EraseSelection.png"))); fact.Add ("Menu.Edit.FillSelection.png", new Gtk.IconSet (PintaCore.Resources.GetIcon ("Menu.Edit.FillSelection.png"))); fact.Add ("Menu.Edit.InvertSelection.png", new Gtk.IconSet (PintaCore.Resources.GetIcon ("Menu.Edit.InvertSelection.png"))); fact.Add ("Menu.Edit.SelectAll.png", new Gtk.IconSet (PintaCore.Resources.GetIcon ("Menu.Edit.SelectAll.png"))); fact.AddDefault (); Undo = new Gtk.Action ("Undo", Mono.Unix.Catalog.GetString ("Undo"), null, "gtk-undo"); Redo = new Gtk.Action ("Redo", Mono.Unix.Catalog.GetString ("Redo"), null, "gtk-redo"); Cut = new Gtk.Action ("Cut", Mono.Unix.Catalog.GetString ("Cut"), null, "gtk-cut"); Copy = new Gtk.Action ("Copy", Mono.Unix.Catalog.GetString ("Copy"), null, "gtk-copy"); Paste = new Gtk.Action ("Paste", Mono.Unix.Catalog.GetString ("Paste"), null, "gtk-paste"); PasteIntoNewLayer = new Gtk.Action ("PasteIntoNewLayer", Mono.Unix.Catalog.GetString ("Paste Into New Layer"), null, "gtk-paste"); PasteIntoNewImage = new Gtk.Action ("PasteIntoNewImage", Mono.Unix.Catalog.GetString ("Paste Into New Image"), null, "gtk-paste"); EraseSelection = new Gtk.Action ("EraseSelection", Mono.Unix.Catalog.GetString ("Erase Selection"), null, "Menu.Edit.EraseSelection.png"); FillSelection = new Gtk.Action ("FillSelection", Mono.Unix.Catalog.GetString ("Fill Selection"), null, "Menu.Edit.FillSelection.png"); InvertSelection = new Gtk.Action ("InvertSelection", Mono.Unix.Catalog.GetString ("Invert Selection"), null, "Menu.Edit.InvertSelection.png"); SelectAll = new Gtk.Action ("SelectAll", Mono.Unix.Catalog.GetString ("Select All"), null, "Menu.Edit.SelectAll.png"); Deselect = new Gtk.Action ("Deselect", Mono.Unix.Catalog.GetString ("Deselect"), null, "Menu.Edit.Deselect.png"); Undo.Sensitive = false; Redo.Sensitive = false; PasteIntoNewImage.Sensitive = false; InvertSelection.Sensitive = false; Deselect.Sensitive = false; EraseSelection.Sensitive = false; FillSelection.Sensitive = false; } #region Initialization public void CreateMainMenu (Gtk.Menu menu) { menu.Remove (menu.Children[1]); menu.Append (Undo.CreateAcceleratedMenuItem (Gdk.Key.Z, Gdk.ModifierType.ControlMask)); menu.Append (Redo.CreateAcceleratedMenuItem (Gdk.Key.Y, Gdk.ModifierType.ControlMask)); menu.AppendSeparator (); menu.Append (Cut.CreateAcceleratedMenuItem (Gdk.Key.X, Gdk.ModifierType.ControlMask)); menu.Append (Copy.CreateAcceleratedMenuItem (Gdk.Key.C, Gdk.ModifierType.ControlMask)); menu.Append (Paste.CreateAcceleratedMenuItem (Gdk.Key.V, Gdk.ModifierType.ControlMask)); menu.Append (PasteIntoNewLayer.CreateAcceleratedMenuItem (Gdk.Key.V, Gdk.ModifierType.ShiftMask)); //menu.Append (PasteIntoNewImage.CreateAcceleratedMenuItem (Gdk.Key.V, Gdk.ModifierType.Mod1Mask)); menu.AppendSeparator (); menu.Append (EraseSelection.CreateAcceleratedMenuItem (Gdk.Key.Delete, Gdk.ModifierType.None)); menu.Append (FillSelection.CreateAcceleratedMenuItem (Gdk.Key.BackSpace, Gdk.ModifierType.None)); //menu.Append (InvertSelection.CreateAcceleratedMenuItem (Gdk.Key.I, Gdk.ModifierType.ControlMask)); menu.Append (SelectAll.CreateAcceleratedMenuItem (Gdk.Key.A, Gdk.ModifierType.ControlMask)); menu.Append (Deselect.CreateAcceleratedMenuItem (Gdk.Key.D, Gdk.ModifierType.ControlMask)); } public void CreateHistoryWindowToolBar (Gtk.Toolbar toolbar) { toolbar.AppendItem (Undo.CreateToolBarItem ()); toolbar.AppendItem (Redo.CreateToolBarItem ()); } public void RegisterHandlers () { Deselect.Activated += HandlePintaCoreActionsEditDeselectActivated; EraseSelection.Activated += HandlePintaCoreActionsEditEraseSelectionActivated; SelectAll.Activated += HandlePintaCoreActionsEditSelectAllActivated; FillSelection.Activated += HandlePintaCoreActionsEditFillSelectionActivated; PasteIntoNewLayer.Activated += HandlerPintaCoreActionsEditPasteIntoNewLayerActivated; Paste.Activated += HandlerPintaCoreActionsEditPasteActivated; Copy.Activated += HandlerPintaCoreActionsEditCopyActivated; Undo.Activated += HandlerPintaCoreActionsEditUndoActivated; Redo.Activated += HandlerPintaCoreActionsEditRedoActivated; Cut.Activated += HandlerPintaCoreActionsEditCutActivated; } #endregion #region Action Handlers private void HandlePintaCoreActionsEditFillSelectionActivated (object sender, EventArgs e) { PintaCore.Layers.FinishSelection (); Cairo.ImageSurface old = PintaCore.Layers.CurrentLayer.Surface.Clone (); using (Cairo.Context g = new Cairo.Context (PintaCore.Layers.CurrentLayer.Surface)) { g.AppendPath (PintaCore.Layers.SelectionPath); g.FillRule = Cairo.FillRule.EvenOdd; g.Color = PintaCore.Palette.PrimaryColor; g.Fill (); } PintaCore.Workspace.Invalidate (); PintaCore.History.PushNewItem (new SimpleHistoryItem ("Menu.Edit.FillSelection.png", Mono.Unix.Catalog.GetString ("Fill Selection"), old, PintaCore.Layers.CurrentLayerIndex)); } private void HandlePintaCoreActionsEditSelectAllActivated (object sender, EventArgs e) { PintaCore.Layers.FinishSelection (); SelectionHistoryItem hist = new SelectionHistoryItem ("Menu.Edit.SelectAll.png", Mono.Unix.Catalog.GetString ("Select All")); hist.TakeSnapshot (); PintaCore.Layers.ResetSelectionPath (); PintaCore.Layers.ShowSelection = true; PintaCore.History.PushNewItem (hist); PintaCore.Workspace.Invalidate (); } private void HandlePintaCoreActionsEditEraseSelectionActivated (object sender, EventArgs e) { PintaCore.Layers.FinishSelection (); Cairo.ImageSurface old = PintaCore.Layers.CurrentLayer.Surface.Clone (); using (Cairo.Context g = new Cairo.Context (PintaCore.Layers.CurrentLayer.Surface)) { g.AppendPath (PintaCore.Layers.SelectionPath); g.FillRule = Cairo.FillRule.EvenOdd; g.Operator = Cairo.Operator.Clear; g.Fill (); } PintaCore.Workspace.Invalidate (); PintaCore.History.PushNewItem (new SimpleHistoryItem ("Menu.Edit.EraseSelection.png", Mono.Unix.Catalog.GetString ("Erase Selection"), old, PintaCore.Layers.CurrentLayerIndex)); } private void HandlePintaCoreActionsEditDeselectActivated (object sender, EventArgs e) { PintaCore.Layers.FinishSelection (); SelectionHistoryItem hist = new SelectionHistoryItem ("Menu.Edit.Deselect.png", Mono.Unix.Catalog.GetString ("Deselect")); hist.TakeSnapshot (); PintaCore.Layers.ResetSelectionPath (); PintaCore.History.PushNewItem (hist); PintaCore.Workspace.Invalidate (); } private void HandlerPintaCoreActionsEditPasteIntoNewLayerActivated (object sender, EventArgs e) { PintaCore.Layers.FinishSelection (); Gtk.Clipboard cb = Gtk.Clipboard.Get (Gdk.Atom.Intern ("CLIPBOARD", false)); Gdk.Pixbuf image = cb.WaitForImage (); // TODO: Message window saying no image on clipboard if (image == null) return; Layer l = PintaCore.Layers.AddNewLayer (string.Empty); using (Cairo.Context g = new Cairo.Context (l.Surface)) g.DrawPixbuf (image, new Cairo.Point (0, 0)); // Make new layer the current layer PintaCore.Layers.SetCurrentLayer (l); PintaCore.Workspace.Invalidate (); AddLayerHistoryItem hist = new AddLayerHistoryItem ("gtk-paste", Mono.Unix.Catalog.GetString ("Paste Into New Layer"), PintaCore.Layers.IndexOf (l)); PintaCore.History.PushNewItem (hist); } private void HandlerPintaCoreActionsEditPasteActivated (object sender, EventArgs e) { PintaCore.Layers.FinishSelection (); Cairo.ImageSurface old = PintaCore.Layers.CurrentLayer.Surface.Clone (); Gtk.Clipboard cb = Gtk.Clipboard.Get (Gdk.Atom.Intern ("CLIPBOARD", false)); Gdk.Pixbuf image = cb.WaitForImage (); if (image == null) return; Path p; using (Cairo.Context g = new Cairo.Context (PintaCore.Layers.CurrentLayer.Surface)) { g.DrawPixbuf (image, new Cairo.Point (0, 0)); p = g.CreateRectanglePath (new Rectangle (0, 0, image.Width, image.Height)); } PintaCore.Layers.SelectionPath = p; PintaCore.Layers.ShowSelection = true; PintaCore.Workspace.Invalidate (); PintaCore.History.PushNewItem (new SimpleHistoryItem ("gtk-paste", Mono.Unix.Catalog.GetString ("Paste"), old, PintaCore.Layers.CurrentLayerIndex)); } private void HandlerPintaCoreActionsEditCopyActivated (object sender, EventArgs e) { PintaCore.Layers.FinishSelection (); ImageSurface src = PintaCore.Layers.GetClippedLayer (PintaCore.Layers.CurrentLayerIndex); Gdk.Rectangle rect = PintaCore.Layers.SelectionPath.GetBounds (); ImageSurface dest = new ImageSurface (Format.Argb32, rect.Width, rect.Height); using (Context g = new Context (dest)) { g.SetSourceSurface (src, -rect.X, -rect.Y); g.Paint (); } Gtk.Clipboard cb = Gtk.Clipboard.Get (Gdk.Atom.Intern ("CLIPBOARD", false)); cb.Image = dest.ToPixbuf (); (src as IDisposable).Dispose (); (dest as IDisposable).Dispose (); } private void HandlerPintaCoreActionsEditCutActivated (object sender, EventArgs e) { PintaCore.Layers.FinishSelection (); // Copy selection HandlerPintaCoreActionsEditCopyActivated (sender, e); // Erase selection Cairo.ImageSurface old = PintaCore.Layers.CurrentLayer.Surface.Clone (); using (Cairo.Context g = new Cairo.Context (PintaCore.Layers.CurrentLayer.Surface)) { g.AppendPath (PintaCore.Layers.SelectionPath); g.FillRule = Cairo.FillRule.EvenOdd; g.Operator = Cairo.Operator.Clear; g.Fill (); } PintaCore.Workspace.Invalidate (); PintaCore.History.PushNewItem (new SimpleHistoryItem ("Menu.Edit.EraseSelection.png", Mono.Unix.Catalog.GetString ("Cut"), old, PintaCore.Layers.CurrentLayerIndex)); } private void HandlerPintaCoreActionsEditUndoActivated (object sender, EventArgs e) { PintaCore.History.Undo (); } private void HandlerPintaCoreActionsEditRedoActivated (object sender, EventArgs e) { PintaCore.History.Redo (); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void CompareOrderedDouble() { var test = new SimpleBinaryOpTest__CompareOrderedDouble(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__CompareOrderedDouble { private const int VectorSize = 16; private const int ElementCount = VectorSize / sizeof(Double); private static Double[] _data1 = new Double[ElementCount]; private static Double[] _data2 = new Double[ElementCount]; private static Vector128<Double> _clsVar1; private static Vector128<Double> _clsVar2; private Vector128<Double> _fld1; private Vector128<Double> _fld2; private SimpleBinaryOpTest__DataTable<Double> _dataTable; static SimpleBinaryOpTest__CompareOrderedDouble() { var random = new Random(); for (var i = 0; i < ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); _data2[i] = (double)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data2[0]), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data1[0]), VectorSize); } public SimpleBinaryOpTest__CompareOrderedDouble() { Succeeded = true; var random = new Random(); for (var i = 0; i < ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); _data2[i] = (double)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); _data2[i] = (double)(random.NextDouble()); } _dataTable = new SimpleBinaryOpTest__DataTable<Double>(_data1, _data2, new Double[ElementCount], VectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Sse2.CompareOrdered( Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Sse2.CompareOrdered( Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Sse2.CompareOrdered( Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareOrdered), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareOrdered), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareOrdered), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Sse2.CompareOrdered( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr); var result = Sse2.CompareOrdered(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var left = Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)); var result = Sse2.CompareOrdered(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var left = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)); var result = Sse2.CompareOrdered(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleBinaryOpTest__CompareOrderedDouble(); var result = Sse2.CompareOrdered(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Sse2.CompareOrdered(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<Double> left, Vector128<Double> right, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[ElementCount]; Double[] inArray2 = new Double[ElementCount]; Double[] outArray = new Double[ElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[ElementCount]; Double[] inArray2 = new Double[ElementCount]; Double[] outArray = new Double[ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Double[] left, Double[] right, Double[] result, [CallerMemberName] string method = "") { if (BitConverter.DoubleToInt64Bits(result[0]) != ((!double.IsNaN(left[0]) && !double.IsNaN(right[0])) ? -1 : 0)) { Succeeded = false; } else { for (var i = 1; i < left.Length; i++) { if (BitConverter.DoubleToInt64Bits(result[i]) != ((!double.IsNaN(left[i]) && !double.IsNaN(right[i])) ? -1 : 0)) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Sse2)}.{nameof(Sse2.CompareOrdered)}<Double>: {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
using System; using System.Drawing; using System.Windows.Forms; using XPTable.Events; using XPTable.Win32; namespace XPTable.Models { /// <summary> /// Summary description for ShowColumnsDialog. /// </summary> internal partial class ShowColumnsDialog : Form { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; private ColumnModel model = null; private Label label1; private Button upButton; private Button downButton; private Button showButton; private Button hideButton; private Label label2; private TextBox widthTextBox; private CheckBox autoSizeCheckBox; private GroupBox groupBox1; private Button okButton; private Button cancelButton; private Table columnTable; /// <summary> /// /// </summary> public ShowColumnsDialog() { InitializeComponent(); } /// <summary> /// /// </summary> /// <param name="model"></param> /// <returns></returns> public void AddColumns(ColumnModel model) { this.model = model; CellStyle cellStyle = new CellStyle(); cellStyle.Padding = new CellPadding(6, 0, 0, 0); this.columnTable.BeginUpdate(); for (int i=0; i<model.Columns.Count; i++) { Row row = new Row(); Cell cell = new Cell(model.Columns[i].Text, model.Columns[i].Visible); cell.Tag = model.Columns[i].Width; cell.CellStyle = cellStyle; row.Cells.Add(cell); this.columnTable.TableModel.Rows.Add(row); } this.columnTable.SelectionChanged += new Events.SelectionEventHandler(OnSelectionChanged); this.columnTable.CellCheckChanged += new Events.CellCheckBoxEventHandler(OnCellCheckChanged); if (this.columnTable.VScroll) { this.columnTable.ColumnModel.Columns[0].Width -= SystemInformation.VerticalScrollBarWidth; } if (this.columnTable.TableModel.Rows.Count > 0) { this.columnTable.TableModel.Selections.SelectCell(0, 0); this.showButton.Enabled = !this.model.Columns[0].Visible; this.hideButton.Enabled = this.model.Columns[0].Visible; this.widthTextBox.Text = this.model.Columns[0].Width.ToString(); } this.columnTable.EndUpdate(); } /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OnShowClick(object sender, System.EventArgs e) { int[] indicies = this.columnTable.SelectedIndicies; if (indicies.Length > 0) { this.columnTable.TableModel[indicies[0], 0].Checked = true; this.hideButton.Focus(); } } /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OnHideClick(object sender, System.EventArgs e) { int[] indicies = this.columnTable.SelectedIndicies; if (indicies.Length > 0) { this.columnTable.TableModel[indicies[0], 0].Checked = false; this.showButton.Focus(); } } /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OnOkClick(object sender, EventArgs e) { int[] indicies = this.columnTable.SelectedIndicies; if (indicies.Length > 0) { if (this.widthTextBox.Text.Length == 0) { this.columnTable.TableModel[indicies[0], 0].Tag = Column.MinimumWidth; } else { int width = Convert.ToInt32(this.widthTextBox.Text); if (width < Column.MinimumWidth) { this.columnTable.TableModel[indicies[0], 0].Tag = Column.MinimumWidth; } else { this.columnTable.TableModel[indicies[0], 0].Tag = width; } } } for (int i=0; i<this.columnTable.TableModel.Rows.Count; i++) { this.model.Columns[i].Visible = this.columnTable.TableModel[i, 0].Checked; this.model.Columns[i].Width = (int) this.columnTable.TableModel[i, 0].Tag; } this.Close(); } /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OnSelectionChanged(object sender, SelectionEventArgs e) { if (e.OldSelectedIndicies.Length > 0) { if (this.widthTextBox.Text.Length == 0) { this.columnTable.TableModel[e.OldSelectedIndicies[0], 0].Tag = Column.MinimumWidth; } else { int width = Convert.ToInt32(this.widthTextBox.Text); if (width < Column.MinimumWidth) { this.columnTable.TableModel[e.OldSelectedIndicies[0], 0].Tag = Column.MinimumWidth; } else { this.columnTable.TableModel[e.OldSelectedIndicies[0], 0].Tag = width; } } } if (e.NewSelectedIndicies.Length > 0) { this.showButton.Enabled = !this.columnTable.TableModel[e.NewSelectedIndicies[0], 0].Checked; this.hideButton.Enabled = this.columnTable.TableModel[e.NewSelectedIndicies[0], 0].Checked; this.widthTextBox.Text = this.columnTable.TableModel[e.NewSelectedIndicies[0], 0].Tag.ToString(); } else { this.showButton.Enabled = false; this.hideButton.Enabled = false; this.widthTextBox.Text = "0"; } } /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OnCellCheckChanged(object sender, CellCheckBoxEventArgs e) { this.showButton.Enabled = !e.Cell.Checked; this.hideButton.Enabled = e.Cell.Checked; } /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OnWidthKeyPress(object sender, KeyPressEventArgs e) { // allow all digit and delete keys if (char.IsDigit(e.KeyChar) || e.KeyChar == AsciiChars.Backspace || e.KeyChar == AsciiChars.Delete) { return; } // block all keypresses without modifier keys pressed if ((ModifierKeys & (Keys.Alt | Keys.Control)) == Keys.None) { e.Handled = true; NativeMethods.MessageBeep(0 /*MB_OK*/); } } } }
using System.Diagnostics.CodeAnalysis; using System.Linq; using Content.Server.Administration.Logs; using Content.Server.Chemistry.EntitySystems; using Content.Server.Clothing.Components; using Content.Server.Fluids.Components; using Content.Shared.Chemistry.Components; using Content.Shared.Chemistry.Reagent; using Content.Shared.Database; using Content.Shared.FixedPoint; using Content.Shared.Inventory.Events; using Content.Shared.Throwing; using Content.Shared.Verbs; using JetBrains.Annotations; using Robust.Shared.Map; using Robust.Shared.Prototypes; namespace Content.Server.Fluids.EntitySystems; [UsedImplicitly] public sealed class SpillableSystem : EntitySystem { [Dependency] private readonly SolutionContainerSystem _solutionContainerSystem = default!; [Dependency] private readonly PuddleSystem _puddleSystem = default!; [Dependency] private readonly IMapManager _mapManager = default!; [Dependency] private readonly IPrototypeManager _prototypeManager = default!; [Dependency] private readonly EntityLookupSystem _entityLookup = default!; [Dependency] private readonly AdminLogSystem _logSystem = default!; public override void Initialize() { base.Initialize(); SubscribeLocalEvent<SpillableComponent, LandEvent>(SpillOnLand); SubscribeLocalEvent<SpillableComponent, GetVerbsEvent<Verb>>(AddSpillVerb); SubscribeLocalEvent<SpillableComponent, GotEquippedEvent>(OnGotEquipped); } private void OnGotEquipped(EntityUid uid, SpillableComponent component, GotEquippedEvent args) { if (!component.SpillWorn) return; if (!TryComp(uid, out ClothingComponent? clothing)) return; // check if entity was actually used as clothing // not just taken in pockets or something var isCorrectSlot = clothing.SlotFlags.HasFlag(args.SlotFlags); if (!isCorrectSlot) return; if (!_solutionContainerSystem.TryGetSolution(uid, component.SolutionName, out var solution)) return; if (solution.TotalVolume == 0) return; // spill all solution on the player var drainedSolution = _solutionContainerSystem.Drain(uid, solution, solution.DrainAvailable); SpillAt(args.Equipee, drainedSolution, "PuddleSmear"); } /// <summary> /// Spills the specified solution at the entity's location if possible. /// </summary> /// <param name="uid"> /// The entity to use as a location to spill the solution at. /// </param> /// <param name="solution">Initial solution for the prototype.</param> /// <param name="prototype">The prototype to use.</param> /// <param name="sound">Play the spill sound.</param> /// <param name="combine">Whether to attempt to merge with existing puddles</param> /// <param name="transformComponent">Optional Transform component</param> /// <returns>The puddle if one was created, null otherwise.</returns> public PuddleComponent? SpillAt(EntityUid uid, Solution solution, string prototype, bool sound = true, bool combine = true, TransformComponent? transformComponent = null) { return !Resolve(uid, ref transformComponent, false) ? null : SpillAt(solution, transformComponent.Coordinates, prototype, sound: sound, combine: combine); } private void SpillOnLand(EntityUid uid, SpillableComponent component, LandEvent args) { if (!_solutionContainerSystem.TryGetSolution(uid, component.SolutionName, out var solution)) return; if (args.User != null) { _logSystem.Add(LogType.Landed, $"{ToPrettyString(uid):entity} spilled a solution {SolutionContainerSystem.ToPrettyString(solution):solution} on landing"); } var drainedSolution = _solutionContainerSystem.Drain(uid, solution, solution.DrainAvailable); SpillAt(drainedSolution, EntityManager.GetComponent<TransformComponent>(uid).Coordinates, "PuddleSmear"); } private void AddSpillVerb(EntityUid uid, SpillableComponent component, GetVerbsEvent<Verb> args) { if (!args.CanAccess || !args.CanInteract) return; if (!_solutionContainerSystem.TryGetDrainableSolution(args.Target, out var solution)) return; if (solution.DrainAvailable == FixedPoint2.Zero) return; Verb verb = new(); verb.Text = Loc.GetString("spill-target-verb-get-data-text"); // TODO VERB ICONS spill icon? pouring out a glass/beaker? verb.Act = () => { var puddleSolution = _solutionContainerSystem.SplitSolution(args.Target, solution, solution.DrainAvailable); SpillAt(puddleSolution, Transform(args.Target).Coordinates, "PuddleSmear"); }; verb.Impact = LogImpact.Medium; // dangerous reagent reaction are logged separately. args.Verbs.Add(verb); } /// <summary> /// Spills solution at the specified grid coordinates. /// </summary> /// <param name="solution">Initial solution for the prototype.</param> /// <param name="coordinates">The coordinates to spill the solution at.</param> /// <param name="prototype">The prototype to use.</param> /// <param name="overflow">If the puddle overflow will be calculated. Defaults to true.</param> /// <param name="sound">Whether or not to play the spill sound.</param> /// <param name="combine">Whether to attempt to merge with existing puddles</param> /// <returns>The puddle if one was created, null otherwise.</returns> public PuddleComponent? SpillAt(Solution solution, EntityCoordinates coordinates, string prototype, bool overflow = true, bool sound = true, bool combine = true) { if (solution.TotalVolume == 0) return null; if (!_mapManager.TryGetGrid(coordinates.GetGridId(EntityManager), out var mapGrid)) return null; // Let's not spill to space. return SpillAt(mapGrid.GetTileRef(coordinates), solution, prototype, overflow, sound, combine: combine); } public bool TryGetPuddle(TileRef tileRef, [NotNullWhen(true)] out PuddleComponent? puddle) { foreach (var entity in _entityLookup.GetEntitiesIntersecting(tileRef)) { if (EntityManager.TryGetComponent(entity, out PuddleComponent? p)) { puddle = p; return true; } } puddle = null; return false; } public PuddleComponent? SpillAt(TileRef tileRef, Solution solution, string prototype, bool overflow = true, bool sound = true, bool noTileReact = false, bool combine = true) { if (solution.TotalVolume <= 0) return null; // If space return early, let that spill go out into the void if (tileRef.Tile.IsEmpty) return null; var gridId = tileRef.GridIndex; if (!_mapManager.TryGetGrid(gridId, out var mapGrid)) return null; // Let's not spill to invalid grids. if (!noTileReact) { // First, do all tile reactions for (var i = 0; i < solution.Contents.Count; i++) { var (reagentId, quantity) = solution.Contents[i]; var proto = _prototypeManager.Index<ReagentPrototype>(reagentId); var removed = proto.ReactionTile(tileRef, quantity); if (removed <= FixedPoint2.Zero) continue; solution.RemoveReagent(reagentId, removed); } } // Tile reactions used up everything. if (solution.CurrentVolume == FixedPoint2.Zero) return null; // Get normalized co-ordinate for spill location and spill it in the centre // TODO: Does SnapGrid or something else already do this? var spillGridCoords = mapGrid.GridTileToWorld(tileRef.GridIndices); var startEntity = EntityUid.Invalid; PuddleComponent? puddleComponent = null; if (combine) { var spillEntities = _entityLookup.GetEntitiesIntersecting(tileRef).ToArray(); foreach (var spillEntity in spillEntities) { if (!EntityManager.TryGetComponent(spillEntity, out puddleComponent)) continue; if (!overflow && _puddleSystem.WouldOverflow(puddleComponent.Owner, solution, puddleComponent)) return null; if (!_puddleSystem.TryAddSolution(puddleComponent.Owner, solution, sound, overflow)) continue; startEntity = puddleComponent.Owner; break; } } if (startEntity != EntityUid.Invalid) return puddleComponent; startEntity = EntityManager.SpawnEntity(prototype, spillGridCoords); puddleComponent = EntityManager.EnsureComponent<PuddleComponent>(startEntity); _puddleSystem.TryAddSolution(startEntity, solution, sound, overflow); return puddleComponent; } }
// Copyright (c) 2012, Event Store LLP // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // Neither the name of the Event Store LLP nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Threading; using EventStore.Common.Log; using EventStore.Common.Utils; using EventStore.Core.Data; using EventStore.Core.DataStructures; using EventStore.Core.Exceptions; using EventStore.Core.Settings; using EventStore.Core.Util; namespace EventStore.Core.Index { public enum FileType: byte { PTableFile = 1, ChunkFile = 2 } public partial class PTable : ISearchTable, IDisposable { public const int IndexEntrySize = sizeof(int) + sizeof(int) + sizeof(long); public const int MD5Size = 16; public const byte Version = 1; public const int DefaultBufferSize = 8192; public const int DefaultSequentialBufferSize = 65536; private static readonly ILogger Log = LogManager.GetLoggerFor<PTable>(); public Guid Id { get { return _id; } } public int Count { get { return _count; } } public string Filename { get { return _filename; } } private readonly Guid _id; private readonly string _filename; private readonly int _count; private readonly Midpoint[] _midpoints; private readonly ulong _minEntry, _maxEntry; private readonly ObjectPool<WorkItem> _workItems; private readonly ManualResetEventSlim _destroyEvent = new ManualResetEventSlim(false); private volatile bool _deleteFile; private PTable(string filename, Guid id, int initialReaders = ESConsts.PTableInitialReaderCount, int maxReaders = ESConsts.PTableMaxReaderCount, int depth = 16) { Ensure.NotNullOrEmpty(filename, "filename"); Ensure.NotEmptyGuid(id, "id"); Ensure.Positive(maxReaders, "maxReaders"); Ensure.Nonnegative(depth, "depth"); if (!File.Exists(filename)) throw new CorruptIndexException(new PTableNotFoundException(filename)); _id = id; _filename = filename; Log.Trace("Loading PTable '{0}' started...", Path.GetFileName(Filename)); var sw = Stopwatch.StartNew(); _count = (int)((new FileInfo(_filename).Length - PTableHeader.Size - MD5Size) / IndexEntrySize); File.SetAttributes(_filename, FileAttributes.ReadOnly | FileAttributes.NotContentIndexed); _workItems = new ObjectPool<WorkItem>(string.Format("PTable {0} work items", _id), initialReaders, maxReaders, () => new WorkItem(filename, DefaultBufferSize), workItem => workItem.Dispose(), pool => OnAllWorkItemsDisposed()); var readerWorkItem = GetWorkItem(); try { readerWorkItem.Stream.Seek(0, SeekOrigin.Begin); var header = PTableHeader.FromStream(readerWorkItem.Stream); if (header.Version != Version) throw new CorruptIndexException(new WrongFileVersionException(_filename, header.Version, Version)); if (Count == 0) { _minEntry = ulong.MaxValue; _maxEntry = ulong.MinValue; } else { _minEntry = ReadEntry(Count - 1, readerWorkItem).Key; _maxEntry = ReadEntry(0, readerWorkItem).Key; } } catch (Exception) { Dispose(); throw; } finally { ReturnWorkItem(readerWorkItem); } try { _midpoints = CacheMidpoints(depth); } catch (PossibleToHandleOutOfMemoryException) { Log.Error("Was unable to create midpoints for PTable '{0}' ({1} entries, depth {2} requested). " + "Performance hit possible. OOM Exception.", Path.GetFileName(Filename), Count, depth); } Log.Trace("Loading PTable '{0}' ({1} entries, cache depth {2}) done in {3}.", Path.GetFileName(Filename), Count, depth, sw.Elapsed); } internal Midpoint[] CacheMidpoints(int depth) { if (depth < 0 || depth > 30) throw new ArgumentOutOfRangeException("depth"); var count = Count; if (count == 0 || depth == 0) return null; //TODO GFY can make slightly faster with a sequential worker. var workItem = GetWorkItem(); try { int midpointsCount; Midpoint[] midpoints; try { midpointsCount = Math.Max(2, Math.Min(1 << depth, count)); midpoints = new Midpoint[midpointsCount]; } catch (OutOfMemoryException exc) { throw new PossibleToHandleOutOfMemoryException("Failed to allocate memory for Midpoint cache.", exc); } workItem.Stream.Position = PTableHeader.Size; for (int k = 0; k < midpointsCount; ++k) { var nextIndex = (long)k * (count - 1) / (midpointsCount - 1); ReadUntil(PTableHeader.Size + IndexEntrySize*nextIndex, workItem.Stream); midpoints[k] = new Midpoint(ReadNextNoSeek(workItem).Key, (int)nextIndex); } return midpoints; } finally { ReturnWorkItem(workItem); } } private static readonly byte[] TmpBuf = new byte[DefaultBufferSize]; private static void ReadUntil(long nextPos, FileStream fileStream) { long toRead = nextPos - fileStream.Position; if (toRead < 0) { fileStream.Seek(nextPos, SeekOrigin.Begin); return; } while (toRead > 0) { var localReadCount = Math.Min(toRead, TmpBuf.Length); fileStream.Read(TmpBuf, 0, (int)localReadCount); toRead -= localReadCount; } } public void VerifyFileHash() { var sw = Stopwatch.StartNew(); Log.Trace("Verifying file hash of PTable '{0}' started...", Path.GetFileName(Filename)); var workItem = GetWorkItem(); try { workItem.Stream.Position = 0; var hash = MD5Hash.GetHashFor(workItem.Stream, 0, workItem.Stream.Length - MD5Size); var fileHash = new byte[MD5Size]; workItem.Stream.Read(fileHash, 0, MD5Size); if (hash == null) throw new CorruptIndexException(new HashValidationException("Calculated MD5 hash is null!")); if (fileHash.Length != hash.Length) throw new CorruptIndexException(new HashValidationException( string.Format("Hash sizes differ! FileHash({0}): {1}, hash({2}): {3}.", fileHash.Length, BitConverter.ToString(fileHash), hash.Length, BitConverter.ToString(hash)))); for (int i = 0; i < fileHash.Length; i++) { if (fileHash[i] != hash[i]) throw new CorruptIndexException(new HashValidationException( string.Format("Hashes are different! FileHash: {0}, hash: {1}.", BitConverter.ToString(fileHash), BitConverter.ToString(hash)))); } } finally { ReturnWorkItem(workItem); } Log.Trace("Verifying file hash of PTable '{0}' ({1} entries) done in {2}.", Path.GetFileName(Filename), Count, sw.Elapsed); } public IEnumerable<IndexEntry> IterateAllInOrder() { var workItem = GetWorkItem(); try { workItem.Stream.Position = PTableHeader.Size; for (int i = 0, n = Count; i < n; i++) { yield return ReadNextNoSeek(workItem); } } finally { ReturnWorkItem(workItem); } } public bool TryGetOneValue(uint stream, int number, out long position) { IndexEntry entry; if (TryGetLargestEntry(stream, number, number, out entry)) { position = entry.Position; return true; } position = -1; return false; } public bool TryGetLatestEntry(uint stream, out IndexEntry entry) { return TryGetLargestEntry(stream, 0, int.MaxValue, out entry); } private bool TryGetLargestEntry(uint stream, int startNumber, int endNumber, out IndexEntry entry) { Ensure.Nonnegative(startNumber, "startNumber"); Ensure.Nonnegative(endNumber, "endNumber"); entry = TableIndex.InvalidIndexEntry; var startKey = BuildKey(stream, startNumber); var endKey = BuildKey(stream, endNumber); //if (_midpoints != null && (startKey > _midpoints[0].Key || endKey < _midpoints[_midpoints.Length - 1].Key)) if (startKey > _maxEntry || endKey < _minEntry) return false; var workItem = GetWorkItem(); try { var recordRange = LocateRecordRange(endKey); int low = recordRange.Lower; int high = recordRange.Upper; while (low < high) { var mid = low + (high - low) / 2; IndexEntry midpoint = ReadEntry(mid, workItem); if (midpoint.Key > endKey) low = mid + 1; else high = mid; } var candEntry = ReadEntry(high, workItem); if (candEntry.Key > endKey) throw new Exception(string.Format("candEntry.Key {0} > startKey {1}, stream {2}, startNum {3}, endNum {4}, PTable: {5}.", candEntry.Key, startKey, stream, startNumber, endNumber, Filename)); if (candEntry.Key < startKey) return false; entry = candEntry; return true; } finally { ReturnWorkItem(workItem); } } public bool TryGetOldestEntry(uint stream, out IndexEntry entry) { return TryGetSmallestEntry(stream, 0, int.MaxValue, out entry); } private bool TryGetSmallestEntry(uint stream, int startNumber, int endNumber, out IndexEntry entry) { Ensure.Nonnegative(startNumber, "startNumber"); Ensure.Nonnegative(endNumber, "endNumber"); entry = TableIndex.InvalidIndexEntry; var startKey = BuildKey(stream, startNumber); var endKey = BuildKey(stream, endNumber); if (startKey > _maxEntry || endKey < _minEntry) return false; var workItem = GetWorkItem(); try { var recordRange = LocateRecordRange(startKey); int low = recordRange.Lower; int high = recordRange.Upper; while (low < high) { var mid = low + (high - low + 1) / 2; IndexEntry midpoint = ReadEntry(mid, workItem); if (midpoint.Key < startKey) high = mid - 1; else low = mid; } var candEntry = ReadEntry(high, workItem); if (candEntry.Key < startKey) throw new Exception(string.Format("candEntry.Key {0} < startKey {1}, stream {2}, startNum {3}, endNum {4}, PTable: {5}.", candEntry.Key, startKey, stream, startNumber, endNumber, Filename)); if (candEntry.Key > endKey) return false; entry = candEntry; return true; } finally { ReturnWorkItem(workItem); } } public IEnumerable<IndexEntry> GetRange(uint stream, int startNumber, int endNumber) { Ensure.Nonnegative(startNumber, "startNumber"); Ensure.Nonnegative(endNumber, "endNumber"); var result = new List<IndexEntry>(); var startKey = BuildKey(stream, startNumber); var endKey = BuildKey(stream, endNumber); //if (_midpoints != null && (startKey > _midpoints[0].Key || endKey < _midpoints[_midpoints.Length - 1].Key)) if (startKey > _maxEntry || endKey < _minEntry) return result; var workItem = GetWorkItem(); try { var recordRange = LocateRecordRange(endKey); int low = recordRange.Lower; int high = recordRange.Upper; while (low < high) { var mid = low + (high - low) / 2; IndexEntry midpoint = ReadEntry(mid, workItem); if (midpoint.Key <= endKey) high = mid; else low = mid + 1; } PositionAtEntry(high, workItem); for (int i=high, n=Count; i<n; ++i) { IndexEntry entry = ReadNextNoSeek(workItem); if (entry.Key > endKey) throw new Exception(string.Format("enty.Key {0} > endKey {1}, stream {2}, startNum {3}, endNum {4}, PTable: {5}.", entry.Key, endKey, stream, startNumber, endNumber, Filename)); if (entry.Key < startKey) return result; result.Add(entry); } return result; } finally { ReturnWorkItem(workItem); } } private static ulong BuildKey(uint stream, int version) { return ((uint)version) | (((ulong)stream) << 32); } private Range LocateRecordRange(ulong stream) { var midpoints = _midpoints; if (midpoints == null) return new Range(0, Count-1); int lowerMidpoint = LowerMidpointBound(midpoints, stream); int upperMidpoint = UpperMidpointBound(midpoints, stream); return new Range(midpoints[lowerMidpoint].ItemIndex, midpoints[upperMidpoint].ItemIndex); } private int LowerMidpointBound(Midpoint[] midpoints, ulong stream) { int l = 0; int r = midpoints.Length - 1; while (l < r) { int m = l + (r - l + 1) / 2; if (midpoints[m].Key > stream) l = m; else r = m - 1; } return l; } private int UpperMidpointBound(Midpoint[] midpoints, ulong stream) { int l = 0; int r = midpoints.Length - 1; while (l < r) { int m = l + (r - l) / 2; if (midpoints[m].Key < stream) r = m; else l = m + 1; } return r; } private static void PositionAtEntry(int indexNum, WorkItem workItem) { workItem.Stream.Seek(IndexEntrySize * (long)indexNum + PTableHeader.Size, SeekOrigin.Begin); } private static IndexEntry ReadEntry(int indexNum, WorkItem workItem) { workItem.Stream.Seek(IndexEntrySize*(long)indexNum + PTableHeader.Size, SeekOrigin.Begin); return ReadNextNoSeek(workItem); } private static IndexEntry ReadNextNoSeek(WorkItem workItem) { //workItem.Stream.Read(workItem.Buffer, 0, IndexEntrySize); //var entry = (IndexEntry)Marshal.PtrToStructure(workItem.BufferHandle.AddrOfPinnedObject(), typeof(IndexEntry)); //return entry; return new IndexEntry(workItem.Reader.ReadUInt64(), workItem.Reader.ReadInt64()); } private WorkItem GetWorkItem() { try { return _workItems.Get(); } catch (ObjectPoolDisposingException) { throw new FileBeingDeletedException(); } catch (ObjectPoolMaxLimitReachedException) { throw new Exception("Unable to acquire work item."); } } private void ReturnWorkItem(WorkItem workItem) { _workItems.Return(workItem); } public void MarkForDestruction() { _deleteFile = true; _workItems.MarkForDisposal(); } public void Dispose() { _deleteFile = false; _workItems.MarkForDisposal(); } private void OnAllWorkItemsDisposed() { File.SetAttributes(_filename, FileAttributes.Normal); if (_deleteFile) File.Delete(_filename); _destroyEvent.Set(); } public void WaitForDisposal(int timeout) { if (!_destroyEvent.Wait(timeout)) throw new TimeoutException(); } public void WaitForDisposal(TimeSpan timeout) { if (!_destroyEvent.Wait(timeout)) throw new TimeoutException(); } internal struct Midpoint { public readonly ulong Key; public readonly int ItemIndex; public Midpoint(ulong key, int itemIndex) { Key = key; ItemIndex = itemIndex; } } private class WorkItem: IDisposable { public readonly FileStream Stream; public readonly BinaryReader Reader; public WorkItem(string filename, int bufferSize) { Stream = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize, FileOptions.RandomAccess); Reader = new BinaryReader(Stream); } ~WorkItem() { Dispose(false); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } private void Dispose(bool disposing) { if (disposing) { Stream.Dispose(); Reader.Dispose(); } } } } }
using System; using System.Data; using System.Configuration; using System.Collections; using System.Collections.Generic; using System.IO; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using Vevo.WebAppLib; using Vevo; using Vevo.Reports; using Vevo.Reports.Exporters; public partial class AdminAdvanced_MainControls_ReportSearch : AdminAdvancedBaseUserControl { #region Private private static DateTime _startSearchDate; private static DateTime _endSearchDate; private GridViewHelper GridHelper { get { if (ViewState["GridHelper"] == null) ViewState["GridHelper"] = new GridViewHelper( uxGrid, "Total", GridViewHelper.Direction.DESC ); return (GridViewHelper) ViewState["GridHelper"]; } } private void PopulateControls() { if (!IsAdminModifiable()) { uxExportButton.Visible = false; } uxPeriodDrop.DataSource = ReportFilterUtilities.GetPeriodList(); uxPeriodDrop.DataBind(); uxPeriodDrop.SelectedIndex = 5; uxNumberItemsDrop.DataSource = ReportFilterUtilities.GetNumberOfItemsList(); uxNumberItemsDrop.DataBind(); uxPeriodDrop.Attributes.Add( "onchange", "GetCustomDate(this.value,'" + uxSetDate.ClientID + "')" ); } private void setCustomDateDisplay() { if (uxPeriodDrop.SelectedItem.ToString() == "Custom") { uxSetDate.Style.Add( "display", "block" ); } else { uxSetDate.Style.Add( "display", "none" ); } } private void setTitle() { if (uxPeriodDrop.SelectedItem.ToString() == "Custom") { uxTitleLabel.Text = "Search Report ( From " + uxStartDateCalendarPopup.SelectedDate.ToShortDateString() + " To " + uxEndDateCalendarPopUp.SelectedDate.ToShortDateString() + ")"; } else { uxTitleLabel.Text = "Search Report (" + uxPeriodDrop.SelectedItem.ToString() + ")"; } } private bool VerifyCustomInput( out string errorMessage ) { if (String.IsNullOrEmpty( uxStartDateCalendarPopup.SelectedDateText ) && String.IsNullOrEmpty( uxEndDateCalendarPopUp.SelectedDateText )) { errorMessage = "Please selected Date"; return false; } if (_endSearchDate < _startSearchDate) { errorMessage = "Start date cannot greater than End date"; return false; } errorMessage = String.Empty; return true; } private void LoadCustomInput() { if (String.IsNullOrEmpty( uxStartDateCalendarPopup.SelectedDateText ) && !String.IsNullOrEmpty( uxEndDateCalendarPopUp.SelectedDateText )) { _endSearchDate = uxEndDateCalendarPopUp.SelectedDate; _startSearchDate = _endSearchDate; } else if (!String.IsNullOrEmpty( uxStartDateCalendarPopup.SelectedDateText ) && String.IsNullOrEmpty( uxEndDateCalendarPopUp.SelectedDateText )) { _startSearchDate = uxStartDateCalendarPopup.SelectedDate; _endSearchDate = _startSearchDate; } else { _startSearchDate = uxStartDateCalendarPopup.SelectedDate; _endSearchDate = uxEndDateCalendarPopUp.SelectedDate; } } private void RefreshGrid() { if (!MainContext.IsPostBack) uxPagingControl.ItemsPerPages = AdminConfig.OrderItemsPerPage; int totalItems; PeriodType period = ReportFilterUtilities.ConvertToPeriodType( uxPeriodDrop.SelectedValue ); if (period == PeriodType.Custom) { string errorMessage; if (VerifyCustomInput( out errorMessage )) { LoadCustomInput(); } else { uxMessage.DisplayError( errorMessage ); uxMessage1.Visible = false; return; } } else { ReportFilterUtilities.GetOrderDateRange( period, out _startSearchDate, out _endSearchDate ); } SearchReportBuilder searchReportBuilder = new SearchReportBuilder(); DataTable table = searchReportBuilder.GetSearchReportData( GridHelper.GetFullSortText(), uxNumberItemsDrop.SelectedItem.ToString(), period, _startSearchDate, _endSearchDate, uxPagingControl.StartIndex, uxPagingControl.EndIndex, out totalItems ); if (table.Rows.Count > 0) { uxTitleLabel.Visible = true; setTitle(); } else { uxTitleLabel.Visible = false; } uxPagingControl.NumberOfPages = (int) Math.Ceiling( (double) totalItems / uxPagingControl.ItemsPerPages ); uxGrid.DataSource = table; uxGrid.DataBind(); setCustomDateDisplay(); } private void uxGrid_RefreshHandler( object sender, EventArgs e ) { RefreshGrid(); } #endregion #region Protected protected void Page_Load( object sender, EventArgs e ) { uxPagingControl.BubbleEvent += new EventHandler( uxGrid_RefreshHandler ); if (!MainContext.IsPostBack) { PopulateControls(); RefreshGrid(); } if (uxPeriodDrop.SelectedItem.ToString() == "Custom") { uxSetDate.Style.Add( "display", "block" ); } else { uxSetDate.Style.Add( "display", "none" ); } } protected void uxRefreshButton_Click( object sender, EventArgs e ) { ViewState["GridHelper"] = new GridViewHelper( uxGrid, "Total", GridViewHelper.Direction.DESC ); uxPagingControl.CurrentPage = 1; RefreshGrid(); uxFileNameLink.Text = ""; uxFileNameLink.NavigateUrl = ""; setCustomDateDisplay(); } protected void uxGrid_Sorting( object sender, GridViewSortEventArgs e ) { GridHelper.SelectSorting( e.SortExpression ); RefreshGrid(); } protected void uxExportButton_Click( object sender, EventArgs e ) { string message, message1, filePhysicalPathName, fileNameLinkText, fileNameLinkURL; filePhysicalPathName = Server.MapPath( "../" ); SearchReportExporter exporter = new SearchReportExporter(); fileNameLinkURL = exporter.ExportSearchReportData( ReportFilterUtilities.ConvertToPeriodType( uxPeriodDrop.SelectedValue ), uxNumberItemsDrop.SelectedItem.ToString(), filePhysicalPathName, _startSearchDate, _endSearchDate, out message, out message1, out fileNameLinkText ); if (String.IsNullOrEmpty( fileNameLinkURL )) { uxMessage.DisplayError( message ); uxMessage1.Visible = false; uxFileNameLink.Text = fileNameLinkText; uxFileNameLink.NavigateUrl = fileNameLinkURL; } else { uxMessage.DisplayMessage( message ); uxMessage1.Visible = true; uxMessage1.DisplayMessageNoNewLIne( message1 ); uxFileNameLink.Text = fileNameLinkText; uxFileNameLink.NavigateUrl = fileNameLinkURL; uxFileNameLink.Target = "_blank"; } setCustomDateDisplay(); } #endregion }
// DataEditor.cs // using jQueryApi; using jQueryApi.UI; using jQueryApi.UI.Widgets; using Slick; using SparkleXrm.CustomBinding; using System; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.CompilerServices; using Xrm; using Xrm.Sdk; using Xrm.Sdk.Metadata; namespace SparkleXrm.GridEditor { public class XrmLookupEditorOptions { public Action<string, Action<EntityCollection>> queryCommand; // searchTerm, queryCallBack public string nameAttribute; public string idAttribute; public string typeCodeAttribute; public string[] columns; public bool showImage = true; public bool showFooter = false; public XrmLookupEditorButton footerButton = null; public bool useQuickCreate = false; } public class XrmLookupEditorButton { public string Label = ""; public string Tooltip = ""; public Action<object> OnClick; public string Image = null; } public class XrmLookupEditor : GridEditorBase { public static EditorFactory LookupEditor; static XrmLookupEditor() { LookupEditor = delegate(EditorArguments args) { XrmLookupEditor editor = new XrmLookupEditor(args); return editor; }; } // Formatter to show a lookup with hyperlink public static string Formatter(int row, int cell, object value, Column columnDef, object dataContext) { if (value != null) { //TOOO: Add an onlclick handler to the grid to handle the lookup links EntityReference entityRef = (EntityReference)value; return "<a href='#' class='sparkle-lookup-link' entityid='" + entityRef.Id +"' typename='" + entityRef.LogicalName + "'>" + XmlHelper.Encode(entityRef.Name) +"</a>"; } else return ""; } private jQueryObject _input; private jQueryObject _container; private AutoCompleteObject _autoComplete; private bool _searchOpen = false; private EntityReference _value = new EntityReference(null, null, String.Empty); private EntityReference _originalValue = new EntityReference(null, null, String.Empty); private int totalRecordsReturned; public XrmLookupEditor(EditorArguments args) : base(args) { XrmLookupEditor self = this; _args = args; _container = jQuery.FromHtml("<div><table class='inline-edit-container' cellspacing='0' cellpadding='0'><tr><td><INPUT type=text class='sparkle-input-inline' /></td><td class='lookup-button-td'><input type=button class='sparkle-lookup-button' /></td></tr></table></div>"); _container.AppendTo(_args.Container); jQueryObject inputField = _container.Find(".sparkle-input-inline"); jQueryObject selectButton = _container.Find(".sparkle-lookup-button"); _input = inputField; _input.Focus().Select(); _autoComplete = inputField.Plugin<AutoCompleteObject>(); AutoCompleteOptions options = new AutoCompleteOptions(); options.Position = new Dictionary<string, object>("collision", "fit"); options.MinLength = 100000; options.Delay = 0; // TODO- set to something that makes sense XrmLookupEditorOptions editorOptions = (XrmLookupEditorOptions)args.Column.Options; bool justSelected = false; options.Select = delegate(jQueryEvent e, AutoCompleteSelectEvent uiEvent) { if (_value == null) _value = new EntityReference(null,null,null); // Note we assume that the binding has added an array of string items AutoCompleteItem item = (AutoCompleteItem)uiEvent.Item; EntityReference itemRef = (EntityReference)item.Value; if (itemRef.LogicalName == "footerlink") { XrmLookupEditorButton button = editorOptions.footerButton; button.OnClick(item); } else { string value = item.Label; _input.Value(value); _value.Id = itemRef.Id; _value.Name = itemRef.Name; _value.LogicalName = ((EntityReference)item.Value).LogicalName; justSelected = true; } Script.Literal("return false;"); }; options.Focus = delegate(jQueryEvent e, AutoCompleteFocusEvent uiEvent) { // Prevent the value being updated in the text box as we scroll through the results Script.Literal("return false;"); }; options.Open = delegate(jQueryEvent e, jQueryObject o) { self._searchOpen = true; if (editorOptions.showFooter && totalRecordsReturned>0) { WidgetObject menu = (WidgetObject)Script.Literal("{0}.autocomplete({1})", _input, "widget"); AddFooter(menu,totalRecordsReturned); } }; options.Close = delegate(jQueryEvent e, jQueryObject o) { self._searchOpen = false; WidgetObject menu = (WidgetObject)Script.Literal("{0}.autocomplete({1})", _input, "widget"); jQueryObject footer = menu.Next(); if (footer.Length > 0 || footer.HasClass("sparkle-menu-footer")) { footer.Hide(); } }; // If there multiple names, add them to the columnAttributes string[] columns = editorOptions.nameAttribute.Split(","); if (columns.Length > 1) { editorOptions.columns = columns; editorOptions.nameAttribute = columns[0]; } // wire up source to CRM search Action<AutoCompleteRequest, Action<AutoCompleteItem[]>> queryDelegate = delegate(AutoCompleteRequest request, Action<AutoCompleteItem[]> response) { // Get the option set values editorOptions.queryCommand(request.Term, delegate(EntityCollection fetchResult) { if (fetchResult.TotalRecordCount > fetchResult.Entities.Count) { totalRecordsReturned = fetchResult.TotalRecordCount; } else { totalRecordsReturned = fetchResult.Entities.Count; } int recordsFound = fetchResult.Entities.Count; bool noRecordsFound = recordsFound == 0; XrmLookupEditorButton button = editorOptions.footerButton; bool footerButton = (button != null); AutoCompleteItem[] results = new AutoCompleteItem[recordsFound + (footerButton ? 1 : 0) + (noRecordsFound ? 1 :0) ]; for (int i = 0; i < recordsFound; i++) { results[i] = new AutoCompleteItem(); results[i].Label = (string)fetchResult.Entities[i].GetAttributeValue(editorOptions.nameAttribute); EntityReference id = new EntityReference(null, null, null); id.Name = results[i].Label; id.LogicalName = fetchResult.Entities[i].LogicalName; id.Id = (Guid)fetchResult.Entities[i].GetAttributeValue(editorOptions.idAttribute); results[i].Value = id; XrmLookupBinding.GetExtraColumns(editorOptions.columns, fetchResult, results, i); string typeCodeName = fetchResult.Entities[i].LogicalName; // Get the type code from the name to find the icon if (!string.IsNullOrEmpty(editorOptions.typeCodeAttribute)) { typeCodeName = fetchResult.Entities[i].GetAttributeValue(editorOptions.typeCodeAttribute).ToString(); } if (editorOptions.showImage) { results[i].Image = MetadataCache.GetSmallIconUrl(typeCodeName); } } int itemsCount = recordsFound; if (noRecordsFound) { AutoCompleteItem noRecordsItem = new AutoCompleteItem(); noRecordsItem.Label = SparkleResourceStrings.NoRecordsFound; results[itemsCount] = noRecordsItem; itemsCount++; } if (footerButton) { // Add the add new AutoCompleteItem addNewLink = new AutoCompleteItem(); addNewLink.Label = button.Label; addNewLink.Image = button.Image; addNewLink.ColumnValues = null; addNewLink.Value = new Entity("footerlink"); results[itemsCount] = addNewLink; } response(results); // Disable it now so typing doesn't trigger a search AutoCompleteOptions disableOption = new AutoCompleteOptions(); disableOption.MinLength = 100000; _autoComplete.AutoComplete(disableOption); }); }; options.Source = queryDelegate; inputField = _autoComplete.AutoComplete(options); RenderItemDelegate autoCompleteDelegates = ((RenderItemDelegate)Script.Literal("{0}.data('ui-autocomplete')", inputField)); autoCompleteDelegates._renderItem = delegate(object ul, AutoCompleteItem item) { if(item.Value==item.Label) { return (object)jQuery.Select("<li class='ui-state-disabled'>"+item.Label+"</li>").AppendTo((jQueryObject)ul); } string itemHtml = "<a class='sparkle-menu-item'>"; // Allow for no image by passing false to 'ShowImage' on the XrmLookupEditorOptions options if (item.Image != null) { itemHtml += "<span class='sparkle-menu-item-img'><img src='" + item.Image + "'/></span>"; } itemHtml += "<span class='sparkle-menu-item-label'>" + item.Label + "</span><br/>"; if (item.ColumnValues != null && item.ColumnValues.Length > 0) { foreach (string value in item.ColumnValues) { itemHtml += "<span class='sparkle-menu-item-moreinfo'>" + value + "</span>"; } } itemHtml += "</a>"; return (object)jQuery.Select("<li>").Append(itemHtml).AppendTo((jQueryObject)ul); }; // Add the click binding to show the drop down selectButton.Click(delegate(jQueryEvent e) { AutoCompleteOptions enableOption = new AutoCompleteOptions(); enableOption.MinLength = 0; _autoComplete.AutoComplete(enableOption); _autoComplete.AutoComplete(AutoCompleteMethod.Search, inputField.GetValue()); }); // Bind return to searching _input.Keydown(delegate(jQueryEvent e) { if (e.Which == 13 && !justSelected) // Return pressed - but we want to do a search not move to the next cell { if (inputField.GetValue().Length > 0) selectButton.Click(); else { // Set value to null _value = null; return; } } else if (e.Which == 13) { return; } if (self._searchOpen) { switch (e.Which) { case 9: case 13: // Return case 38: // Up - don't navigate - but use the dropdown to select search results case 40: // Down - don't navigate - but use the dropdown to select search results e.PreventDefault(); e.StopPropagation(); break; } } else { switch (e.Which) { case 13: // Return e.PreventDefault(); e.StopPropagation(); break; } } justSelected = false; }); } public static void AddFooter(WidgetObject menu, int recordCount) { jQueryObject footer = menu.Next(); if (footer.Length == 0 || !footer.HasClass("sparkle-menu-footer")) { footer = jQuery.FromHtml("<div class='sparkle-menu-footer ui-front'></div>"); menu.Parent().Append(footer); } if (footer != null) { footer.Html(""); jQueryObject footerContent = jQuery.FromHtml("<span class='sparkle-menu-footer-content'></span>"); jQueryObject footerLeft = jQuery.FromHtml("<span class='sparkle-menu-footer-left'></span>"); jQueryObject footerRight = jQuery.FromHtml("<span class='sparkle-menu-footer-right'></span>"); footerContent.Append(footerLeft); footerContent.Append(footerRight); footerLeft.Append(String.Format(SparkleResourceStrings.LookupFooter, recordCount)); footer.Append(footerContent); } jQueryPosition pos = menu.Position(); int height = menu.GetHeight(); int width = menu.GetWidth(); if (footer != null && footer.Length > 0) { footer.Show(); footer.CSS("top", (pos.Top + height + 4).ToString() + "px"); footer.CSS("left", (pos.Left).ToString() + "px"); footer.Width(width); } } public override void Destroy() { _input.Plugin<AutoCompleteObject>().AutoComplete(AutoCompleteMethod.Close); _input.Plugin<AutoCompleteObject>().AutoComplete(AutoCompleteMethod.Destroy); _container.Remove(); _autoComplete.Remove(); _autoComplete = null; } public override void Show() { } public override void Hide() { } public override void Position(jQueryPosition position) { } public override void Focus() { _input.Focus(); } public override void LoadValue(Dictionary<string, object> item) { _originalValue = (EntityReference)item[_args.Column.Field]; if (_originalValue != null) { _value = new EntityReference(_originalValue.Id, _originalValue.LogicalName, _originalValue.Name); _input.Value(_originalValue.Name); } } public override object SerializeValue() { // Ensure that the value is returned as null if the id is null if (_value!=null && _value.Id == null) return null; else return _value; } public override void ApplyValue(Dictionary<string, object> item, object state) { item[_args.Column.Field] = state; this.RaiseOnChange(item); } public override bool IsValueChanged() { if (_originalValue != null && _value != null) { string lvalue = _originalValue.Id!=null ? _originalValue.Id.ToString() : ""; string rvalue = _value.Id!=null ? _value.Id.ToString() : ""; return lvalue != rvalue; } else { return ((_originalValue!=null) || (_value!=null)); } } public static Column BindColumn(Column column, Action<string, Action<EntityCollection>> queryCommand, string idAttribute, string nameAttribute, string typeCodeAttribute) { column.Editor = LookupEditor; XrmLookupEditorOptions currencyLookupOptions = new XrmLookupEditorOptions(); currencyLookupOptions.queryCommand = queryCommand; currencyLookupOptions.idAttribute = idAttribute; currencyLookupOptions.nameAttribute = nameAttribute; currencyLookupOptions.typeCodeAttribute = typeCodeAttribute; column.Options = currencyLookupOptions; column.Formatter = XrmLookupEditor.Formatter; return column; } public static Column BindReadOnlyColumn(Column column,string typeCodeAttribute) { XrmLookupEditorOptions currencyLookupOptions = new XrmLookupEditorOptions(); currencyLookupOptions.typeCodeAttribute = typeCodeAttribute; column.Options = currencyLookupOptions; column.Formatter = XrmLookupEditor.Formatter; return column; } } [Imported] public class RenderItemDelegate : jQueryObject { public Func<object, AutoCompleteItem, object> _renderItem; public Func<object, List<AutoCompleteItem>, object> _renderMenu; public Action _resizeMenu; } [Imported] [IgnoreNamespace] [ScriptName("Object")] public class AutoCompleteItem { public string Label; public object Value; public string Image; public object Data; public string[] ColumnValues; } [Imported] [IgnoreNamespace] [ScriptName("Object")] public class AutoCompleteRequest { public string Term; } }
using System; using System.Collections.Generic; using System.Xml; using Commons.Xml.Relaxng; using SIL.Lift.Parsing; using SIL.Progress; namespace SIL.Lift.Validation { [Flags] public enum ValidationOptions { CheckLIFT = 1, CheckGUIDs =2, All = 0xFFFF }; /// <summary> /// Provide progress reporting for validation. /// </summary> /// <remarks>TODO: provide a single IProgressReport interface for SIL.Lift (or SIL.Core?).</remarks> public interface IValidationProgress { ///<summary> /// Get/set the progress message. ///</summary> string Status { set; get; } ///<summary> /// Advance the progress bar n steps. ///</summary> void Step(int n); /// <summary> /// Set the number of steps in the progress bar. /// </summary> int MaxRange { set; get; } } /// <summary> /// Trivial, nonfunctional implementation of IValidationProgress. /// </summary> /// <remarks> /// TODO: provide a single IProgressReport interface for SIL.Lift (or SIL.Core?), and a single trivial /// implementation thereof. /// </remarks> public class NullValidationProgress : IValidationProgress { private string _status = String.Empty; private int _max = 20; private int _step; #region IValidationProgress Members /// <summary> /// Get/set the status message string. /// </summary> public string Status { get { return _status; } set { _status = value; } } /// <summary> /// Advance the progress bar by n steps. /// </summary> public void Step(int n) { _step += n; } /// <summary> /// Get/set the number of steps in the progress bar. /// </summary> public int MaxRange { get { return _max; } set { _max = value; } } #endregion } ///<summary> /// This class provides validation (via built-in RNG schema) of a LIFT file. ///</summary> public class Validator { ///<summary> /// Parse the given LIFT file and return a string containing all the validation errors /// (if any). Progress reporting is supported. ///</summary> public static string GetAnyValidationErrors(string path, IValidationProgress progress, ValidationOptions validationOptions) { string errors = ""; if ((validationOptions & ValidationOptions.CheckLIFT) != 0) { errors += GetSchemaValidationErrors(path, progress); } if ((validationOptions & ValidationOptions.CheckGUIDs) != 0) { errors += GetDuplicateGuidErrors(path, progress); } return errors; } private static string GetDuplicateGuidErrors(string path, IValidationProgress progress) { progress.Status = "Checking for duplicate guids..."; string errors=""; HashSet<string> guids = new HashSet<string>(); using (XmlTextReader reader = new XmlTextReader(path)) { try { while (reader.Read()) { if (reader.HasAttributes) { var guid = reader.GetAttribute("guid"); if (!string.IsNullOrEmpty(guid)) { if (guids.Contains(guid)) { errors += Environment.NewLine + "Found duplicate GUID (Globally Unique Identifier): " + guid+". All GUIDs must be unique."; } else { guids.Add(guid); } } } } } catch (Exception error) { errors += error.Message; } } return errors; } ///<summary> /// Validate the LIFT file contained in the XmlTextReader. Progress reporting is /// supported. ///</summary> static private string GetSchemaValidationErrors(string path,IValidationProgress progress) { using (XmlTextReader documentReader = new XmlTextReader(path)) { progress.Status = "Checking for Schema errors..."; var resourceStream = typeof (LiftMultiText).Assembly.GetManifestResourceStream("SIL.Lift.Validation.lift.rng"); if (resourceStream == null) throw new Exception(); RelaxngValidatingReader reader = new RelaxngValidatingReader( documentReader, new XmlTextReader(resourceStream)); reader.ReportDetails = true; string lastGuy = "lift"; int line = 0; int step = 0; if (progress != null) { try { if (documentReader.BaseURI != null) { string sFilePath = documentReader.BaseURI.Replace("file://", ""); if (sFilePath.StartsWith("/")) { // On Microsoft Windows, the BaseURI may be "file:///C:/foo/bar.lift" if (sFilePath.Length > 3 && Char.IsLetter(sFilePath[1]) && sFilePath[2] == ':' && sFilePath[3] == '/') { sFilePath = sFilePath.Substring(1); } } System.IO.FileInfo fi = new System.IO.FileInfo(sFilePath); // Unfortunately, XmlTextReader gives access to only line numbers, // not actual file positions while reading. A check of 8 Flex // generated LIFT files showed a range of 43.9 - 52.1 chars per // line. The biatah sample distributed with WeSay has an average // of only 23.1 chars per line. We'll compromise by guessing 33. // The alternative is to read the entire file to get the actual // line count. int maxline = (int) (fi.Length/33); if (maxline < 8) progress.MaxRange = 8; else if (maxline < 100) progress.MaxRange = maxline; else progress.MaxRange = 100; step = (maxline + 99)/100; } if (step <= 0) step = 1; } catch { step = 100; } } try { while (!reader.EOF) { // Debug.WriteLine(reader.v reader.Read(); lastGuy = reader.Name; if (progress != null && reader.LineNumber != line) { line = reader.LineNumber; if (line%step == 0) progress.Step(1); } } } catch (Exception e) { if (reader.Name == "version" && (lastGuy == "lift" || lastGuy == "")) { return String.Format( "This file claims to be version {0} of LIFT, but this version of the program uses version {1}", reader.Value, LiftVersion); } string m = string.Format("{0}\r\nError near: {1} {2} '{3}'", e.Message, lastGuy, reader.Name, reader.Value); return m; } return null; } } ///<summary> /// Get the LIFT version handled by this code in the form of a string. ///</summary> public static string LiftVersion { get { return "0.13"; } } ///<summary> /// Check the given LIFT file for validity, throwing an exception if an error is found. /// Progress reporting is supported. ///</summary> ///<exception cref="LiftFormatException"></exception> public static void CheckLiftWithPossibleThrow(string pathToLiftFile) { string errors = GetAnyValidationErrors(pathToLiftFile, new NullValidationProgress(), ValidationOptions.All); if (!String.IsNullOrEmpty(errors)) { errors = string.Format("Sorry, the dictionary file at {0} does not conform to the current version of the LIFT format ({1}). The RNG validator said: {2}.\r\n\r\n If this file was generated by a program such as Lexique Pro, FieldWorks, or WeSay it's very important that you notify the relevant developers of the problem.", pathToLiftFile, LiftVersion, errors); throw new LiftFormatException(errors); } } ///<summary> /// Get the LIFT version of the given file, throwing an exception if it cannot be found. ///</summary> ///<exception cref="LiftFormatException"></exception> public static string GetLiftVersion(string pathToLift) { string liftVersionOfRequestedFile = String.Empty; XmlReaderSettings readerSettings = new XmlReaderSettings(); readerSettings.ValidationType = ValidationType.None; readerSettings.IgnoreComments = true; using (XmlReader reader = XmlReader.Create(pathToLift, readerSettings)) { if (reader.IsStartElement("lift")) liftVersionOfRequestedFile = reader.GetAttribute("version"); } if (String.IsNullOrEmpty(liftVersionOfRequestedFile)) { throw new LiftFormatException(String.Format("Cannot import {0} because this was not recognized as well-formed LIFT file (missing version).", pathToLift)); } return liftVersionOfRequestedFile; } } /// <summary> /// I don't know how I ended up with these different progress models, but anyhow this adapts from the normal, log-based one to the Validation one needed by the validator. /// </summary> public class ValidationProgress : IValidationProgress { private readonly IProgress _progress; public ValidationProgress(IProgress progress) { _progress = progress; } public string Status { get { return "not supported"; } set{ _progress.WriteStatus(value);} } public void Step(int n) { } public int MaxRange { get; set; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; namespace System.Net { internal static partial class HttpKnownHeaderNames { /// <summary> /// Gets a known header name string from a matching char[] array segment, using a case-sensitive /// ordinal comparison. Used to avoid allocating new strings for known header names. /// </summary> public static bool TryGetHeaderName(char[] array, int startIndex, int length, out string name) { CharArrayHelpers.DebugAssertArrayInputs(array, startIndex, length); return TryGetHeaderName( array, startIndex, length, (arr, index) => arr[index], (known, arr, start, len) => CharArrayHelpers.EqualsOrdinal(known, arr, start, len), out name); } /// <summary> /// Gets a known header name string from a matching IntPtr buffer, using a case-sensitive /// ordinal comparison. Used to avoid allocating new strings for known header names. /// </summary> public static unsafe bool TryGetHeaderName(IntPtr buffer, int length, out string name) { Debug.Assert(length >= 0); if (buffer == IntPtr.Zero) { name = null; return false; } // We always pass 0 for the startIndex, as buffer should already point to the start. const int startIndex = 0; return TryGetHeaderName( buffer, startIndex, length, (buf, index) => (char)((byte*)buf)[index], (known, buf, start, len) => EqualsOrdinal(known, buf, len), out name); } private static bool TryGetHeaderName<T>( T key, int startIndex, int length, Func<T, int, char> charAt, Func<string, T, int, int, bool> equals, out string name) { Debug.Assert(key != null); Debug.Assert(startIndex >= 0); Debug.Assert(length >= 0); Debug.Assert(charAt != null); Debug.Assert(equals != null); // When adding a new constant, add it to HttpKnownHeaderNames.cs as well. // The lookup works as follows: first switch on the length of the passed-in key. // // - If there is only one known header of that length, set potentialHeader to that known header // and goto TryMatch to see if the key fully matches potentialHeader. // // - If there are more than one known headers of that length, switch on a unique char from that // set of same-length known headers. Typically this will be the first char, but some sets of // same-length known headers do not have unique chars in the first position, so a char in a // position further in the strings is used. If the char from the key matches one of the // known headers, set potentialHeader to that known header and goto TryMatch to see if the key // fully matches potentialHeader. // // - Otherwise, there is no match, so set the out param to null and return false. // // Matching is case-sensitive: we only want to return a known header that exactly matches the key. string potentialHeader = null; switch (length) { case 2: potentialHeader = TE; goto TryMatch; // TE case 3: switch (charAt(key, startIndex)) { case 'A': potentialHeader = Age; goto TryMatch; // [A]ge case 'P': potentialHeader = P3P; goto TryMatch; // [P]3P case 'T': potentialHeader = TSV; goto TryMatch; // [T]SV case 'V': potentialHeader = Via; goto TryMatch; // [V]ia } break; case 4: switch (charAt(key, startIndex)) { case 'D': potentialHeader = Date; goto TryMatch; // [D]ate case 'E': potentialHeader = ETag; goto TryMatch; // [E]Tag case 'F': potentialHeader = From; goto TryMatch; // [F]rom case 'H': potentialHeader = Host; goto TryMatch; // [H]ost case 'L': potentialHeader = Link; goto TryMatch; // [L]ink case 'V': potentialHeader = Vary; goto TryMatch; // [V]ary } break; case 5: switch (charAt(key, startIndex)) { case 'A': potentialHeader = Allow; goto TryMatch; // [A]llow case 'R': potentialHeader = Range; goto TryMatch; // [R]ange } break; case 6: switch (charAt(key, startIndex)) { case 'A': potentialHeader = Accept; goto TryMatch; // [A]ccept case 'C': potentialHeader = Cookie; goto TryMatch; // [C]ookie case 'E': potentialHeader = Expect; goto TryMatch; // [E]xpect case 'O': potentialHeader = Origin; goto TryMatch; // [O]rigin case 'P': potentialHeader = Pragma; goto TryMatch; // [P]ragma case 'S': potentialHeader = Server; goto TryMatch; // [S]erver } break; case 7: switch (charAt(key, startIndex)) { case 'A': potentialHeader = AltSvc; goto TryMatch; // [A]lt-Svc case 'C': potentialHeader = Cookie2; goto TryMatch; // [C]ookie2 case 'E': potentialHeader = Expires; goto TryMatch; // [E]xpires case 'R': potentialHeader = Referer; goto TryMatch; // [R]eferer case 'T': potentialHeader = Trailer; goto TryMatch; // [T]railer case 'U': potentialHeader = Upgrade; goto TryMatch; // [U]pgrade case 'W': potentialHeader = Warning; goto TryMatch; // [W]arning } break; case 8: switch (charAt(key, startIndex + 3)) { case 'M': potentialHeader = IfMatch; goto TryMatch; // If-[M]atch case 'R': potentialHeader = IfRange; goto TryMatch; // If-[R]ange case 'a': potentialHeader = Location; goto TryMatch; // Loc[a]tion } break; case 10: switch (charAt(key, startIndex)) { case 'C': potentialHeader = Connection; goto TryMatch; // [C]onnection case 'K': potentialHeader = KeepAlive; goto TryMatch; // [K]eep-Alive case 'S': potentialHeader = SetCookie; goto TryMatch; // [S]et-Cookie case 'U': potentialHeader = UserAgent; goto TryMatch; // [U]ser-Agent } break; case 11: switch (charAt(key, startIndex)) { case 'C': potentialHeader = ContentMD5; goto TryMatch; // [C]ontent-MD5 case 'R': potentialHeader = RetryAfter; goto TryMatch; // [R]etry-After case 'S': potentialHeader = SetCookie2; goto TryMatch; // [S]et-Cookie2 } break; case 12: switch (charAt(key, startIndex + 2)) { case 'c': potentialHeader = AcceptPatch; goto TryMatch; // Ac[c]ept-Patch case 'n': potentialHeader = ContentType; goto TryMatch; // Co[n]tent-Type case 'x': potentialHeader = MaxForwards; goto TryMatch; // Ma[x]-Forwards case 'M': potentialHeader = XMSEdgeRef; goto TryMatch; // X-[M]SEdge-Ref case 'P': potentialHeader = XPoweredBy; goto TryMatch; // X-[P]owered-By case 'R': potentialHeader = XRequestID; goto TryMatch; // X-[R]equest-ID } break; case 13: switch (charAt(key, startIndex + 6)) { case '-': potentialHeader = AcceptRanges; goto TryMatch; // Accept[-]Ranges case 'i': potentialHeader = Authorization; goto TryMatch; // Author[i]zation case 'C': potentialHeader = CacheControl; goto TryMatch; // Cache-[C]ontrol case 't': potentialHeader = ContentRange; goto TryMatch; // Conten[t]-Range case 'e': potentialHeader = IfNoneMatch; goto TryMatch; // If-Non[e]-Match case 'o': potentialHeader = LastModified; goto TryMatch; // Last-M[o]dified } break; case 14: switch (charAt(key, startIndex)) { case 'A': potentialHeader = AcceptCharset; goto TryMatch; // [A]ccept-Charset case 'C': potentialHeader = ContentLength; goto TryMatch; // [C]ontent-Length } break; case 15: switch (charAt(key, startIndex + 7)) { case '-': potentialHeader = XFrameOptions; goto TryMatch; // X-Frame[-]Options case 'm': potentialHeader = XUACompatible; goto TryMatch; // X-UA-Co[m]patible case 'E': potentialHeader = AcceptEncoding; goto TryMatch; // Accept-[E]ncoding case 'K': potentialHeader = PublicKeyPins; goto TryMatch; // Public-[K]ey-Pins case 'L': potentialHeader = AcceptLanguage; goto TryMatch; // Accept-[L]anguage } break; case 16: switch (charAt(key, startIndex + 11)) { case 'o': potentialHeader = ContentEncoding; goto TryMatch; // Content-Enc[o]ding case 'g': potentialHeader = ContentLanguage; goto TryMatch; // Content-Lan[g]uage case 'a': potentialHeader = ContentLocation; goto TryMatch; // Content-Loc[a]tion case 'c': potentialHeader = ProxyConnection; goto TryMatch; // Proxy-Conne[c]tion case 'i': potentialHeader = WWWAuthenticate; goto TryMatch; // WWW-Authent[i]cate case 'r': potentialHeader = XAspNetVersion; goto TryMatch; // X-AspNet-Ve[r]sion } break; case 17: switch (charAt(key, startIndex)) { case 'I': potentialHeader = IfModifiedSince; goto TryMatch; // [I]f-Modified-Since case 'S': potentialHeader = SecWebSocketKey; goto TryMatch; // [S]ec-WebSocket-Key case 'T': potentialHeader = TransferEncoding; goto TryMatch; // [T]ransfer-Encoding } break; case 18: switch (charAt(key, startIndex)) { case 'P': potentialHeader = ProxyAuthenticate; goto TryMatch; // [P]roxy-Authenticate case 'X': potentialHeader = XContentDuration; goto TryMatch; // [X]-Content-Duration } break; case 19: switch (charAt(key, startIndex)) { case 'C': potentialHeader = ContentDisposition; goto TryMatch; // [C]ontent-Disposition case 'I': potentialHeader = IfUnmodifiedSince; goto TryMatch; // [I]f-Unmodified-Since case 'P': potentialHeader = ProxyAuthorization; goto TryMatch; // [P]roxy-Authorization } break; case 20: potentialHeader = SecWebSocketAccept; goto TryMatch; // Sec-WebSocket-Accept case 21: potentialHeader = SecWebSocketVersion; goto TryMatch; // Sec-WebSocket-Version case 22: switch (charAt(key, startIndex)) { case 'A': potentialHeader = AccessControlMaxAge; goto TryMatch; // [A]ccess-Control-Max-Age case 'S': potentialHeader = SecWebSocketProtocol; goto TryMatch; // [S]ec-WebSocket-Protocol case 'X': potentialHeader = XContentTypeOptions; goto TryMatch; // [X]-Content-Type-Options } break; case 23: potentialHeader = ContentSecurityPolicy; goto TryMatch; // Content-Security-Policy case 24: potentialHeader = SecWebSocketExtensions; goto TryMatch; // Sec-WebSocket-Extensions case 25: switch (charAt(key, startIndex)) { case 'S': potentialHeader = StrictTransportSecurity; goto TryMatch; // [S]trict-Transport-Security case 'U': potentialHeader = UpgradeInsecureRequests; goto TryMatch; // [U]pgrade-Insecure-Requests } break; case 27: potentialHeader = AccessControlAllowOrigin; goto TryMatch; // Access-Control-Allow-Origin case 28: switch (charAt(key, startIndex + 21)) { case 'H': potentialHeader = AccessControlAllowHeaders; goto TryMatch; // Access-Control-Allow-[H]eaders case 'M': potentialHeader = AccessControlAllowMethods; goto TryMatch; // Access-Control-Allow-[M]ethods } break; case 29: potentialHeader = AccessControlExposeHeaders; goto TryMatch; // Access-Control-Expose-Headers case 32: potentialHeader = AccessControlAllowCredentials; goto TryMatch; // Access-Control-Allow-Credentials } name = null; return false; TryMatch: Debug.Assert(potentialHeader != null); return TryMatch(potentialHeader, key, startIndex, length, equals, out name); } /// <summary> /// Returns true if <paramref name="known"/> matches the <paramref name="key"/> char[] array segment, /// using an ordinal comparison. /// </summary> private static bool TryMatch<T>(string known, T key, int startIndex, int length, Func<string, T, int, int, bool> equals, out string name) { Debug.Assert(known != null); Debug.Assert(known.Length > 0); Debug.Assert(startIndex >= 0); Debug.Assert(length > 0); Debug.Assert(equals != null); // The lengths should be equal because this method is only called // from within a "switch (length) { ... }". Debug.Assert(known.Length == length); if (equals(known, key, startIndex, length)) { name = known; return true; } name = null; return false; } private static unsafe bool EqualsOrdinal(string left, IntPtr right, int rightLength) { Debug.Assert(left != null); Debug.Assert(right != IntPtr.Zero); Debug.Assert(rightLength > 0); // At this point the lengths have already been determined to be equal. Debug.Assert(left.Length == rightLength); byte* pRight = (byte*)right; for (int i = 0; i < left.Length; i++) { if (left[i] != pRight[i]) { return false; } } return true; } } }
using System; using System.ComponentModel; using System.Windows.Input; using Android.Util; using Android.Views; using Vapolia.Droid.Lib.Effects; using Vapolia.Lib.Ui; using Xamarin.Forms; using Xamarin.Forms.Internals; using Xamarin.Forms.Platform.Android; using View = Android.Views.View; [assembly: ResolutionGroupName("Vapolia")] [assembly: ExportEffect(typeof(PlatformGestureEffect), nameof(PlatformGestureEffect))] namespace Vapolia.Droid.Lib.Effects { [Preserve (Conditional=true, AllMembers = true)] public class PlatformGestureEffect : PlatformEffect { private GestureDetector? gestureRecognizer; private readonly InternalGestureDetector tapDetector; private DisplayMetrics displayMetrics; private object commandParameter; /// <summary> /// Take a Point parameter /// Except panPointCommand which takes a PanEventArgs parameter /// </summary> private ICommand? tapPointCommand, panPointCommand, doubleTapPointCommand, longPressPointCommand; /// <summary> /// No parameter /// </summary> private ICommand? tapCommand, panCommand, doubleTapCommand, longPressCommand, swipeLeftCommand, swipeRightCommand, swipeTopCommand, swipeBottomCommand; /// <summary> /// 1 parameter: PinchEventArgs /// </summary> private ICommand pinchCommand; public static void Init() { } public PlatformGestureEffect() { tapDetector = new InternalGestureDetector { SwipeThresholdInPoints = 40, TapAction = motionEvent => { if (tapPointCommand != null) { var x = motionEvent.GetX(); var y = motionEvent.GetY(); var point = PxToDp(new Point(x,y)); if (tapPointCommand.CanExecute(point)) tapPointCommand.Execute(point); } if(tapCommand != null) { if (tapCommand.CanExecute(commandParameter)) tapCommand.Execute(commandParameter); } }, DoubleTapAction = motionEvent => { if (doubleTapPointCommand != null) { var x = motionEvent.GetX(); var y = motionEvent.GetY(); var point = PxToDp(new Point(x, y)); if (doubleTapPointCommand.CanExecute(point)) doubleTapPointCommand.Execute(point); } if (doubleTapCommand != null) { if (doubleTapCommand.CanExecute(commandParameter)) doubleTapCommand.Execute(commandParameter); } }, SwipeLeftAction = motionEvent => { if (swipeLeftCommand != null) { if (swipeLeftCommand.CanExecute(commandParameter)) swipeLeftCommand.Execute(commandParameter); } }, SwipeRightAction = motionEvent => { if (swipeRightCommand != null) { if (swipeRightCommand.CanExecute(commandParameter)) swipeRightCommand.Execute(commandParameter); } }, SwipeTopAction = motionEvent => { if (swipeTopCommand != null) { if (swipeTopCommand.CanExecute(commandParameter)) swipeTopCommand.Execute(commandParameter); } }, SwipeBottomAction = motionEvent => { if (swipeBottomCommand != null) { if (swipeBottomCommand.CanExecute(commandParameter)) swipeBottomCommand.Execute(commandParameter); } }, PanAction = (initialDown, currentMove) => { var continueGesture = true; if (panPointCommand != null) { var x = currentMove.GetX(); var y = currentMove.GetY(); var point = PxToDp(new Point(x, y)); var status = currentMove.Action switch { MotionEventActions.Down => GestureStatus.Started, MotionEventActions.Move => GestureStatus.Running, MotionEventActions.Up => GestureStatus.Completed, MotionEventActions.Cancel => GestureStatus.Canceled, _ => GestureStatus.Canceled }; var parameter = new PanEventArgs(status,point); if (panPointCommand.CanExecute(parameter)) panPointCommand.Execute(parameter); if (parameter.CancelGesture) continueGesture = false; } if (panCommand != null) { if (panCommand.CanExecute(commandParameter)) panCommand.Execute(commandParameter); } return continueGesture; }, PinchAction = (initialDown, currentMove) => { if (pinchCommand != null) { var origin0 = PxToDp(new Point(initialDown.GetX(0), initialDown.GetY(0))); var origin1 = PxToDp(new Point(initialDown.GetX(1), initialDown.GetY(1))); var current0 = PxToDp(new Point(currentMove.GetX(0), currentMove.GetY(0))); var current1 = PxToDp(new Point(currentMove.GetX(1), currentMove.GetY(1))); var status = currentMove.Action switch { MotionEventActions.Down => GestureStatus.Started, MotionEventActions.Move => GestureStatus.Running, MotionEventActions.Up => GestureStatus.Completed, MotionEventActions.Cancel => GestureStatus.Canceled, _ => GestureStatus.Canceled }; var parameters = new PinchEventArgs(status, (current0, current1), (origin0, origin1)); if (pinchCommand.CanExecute(parameters)) pinchCommand.Execute(parameters); } }, LongPressAction = motionEvent => { if (longPressPointCommand != null) { var x = motionEvent.GetX(); var y = motionEvent.GetY(); var point = PxToDp(new Point(x, y)); if (longPressPointCommand.CanExecute(point)) longPressPointCommand.Execute(point); } if (longPressCommand != null) { if (longPressCommand.CanExecute(commandParameter)) longPressCommand.Execute(commandParameter); } }, }; } private Point PxToDp(Point point) { point.X = point.X / displayMetrics.Density; point.Y = point.Y / displayMetrics.Density; return point; } protected override void OnElementPropertyChanged(PropertyChangedEventArgs args) { tapCommand = Gesture.GetTapCommand(Element); panCommand = Gesture.GetPanCommand(Element); pinchCommand = Gesture.GetPinchCommand(Element); tapDetector.IsPinchImmediate = Gesture.GetIsPinchImmediate(Element); tapDetector.IsPanImmediate = Gesture.GetIsPanImmediate(Element); doubleTapCommand = Gesture.GetDoubleTapCommand(Element); longPressCommand = Gesture.GetLongPressCommand(Element); swipeLeftCommand = Gesture.GetSwipeLeftCommand(Element); swipeRightCommand = Gesture.GetSwipeRightCommand(Element); swipeTopCommand = Gesture.GetSwipeTopCommand(Element); swipeBottomCommand = Gesture.GetSwipeBottomCommand(Element); tapPointCommand = Gesture.GetTapPointCommand(Element); panPointCommand = Gesture.GetPanPointCommand(Element); doubleTapPointCommand = Gesture.GetDoubleTapPointCommand(Element); longPressPointCommand = Gesture.GetLongPressPointCommand(Element); tapDetector.SwipeThresholdInPoints = Gesture.GetSwipeThreshold(Element); commandParameter = Gesture.GetCommandParameter(Element); } protected override void OnAttached() { var control = Control ?? Container; var context = control.Context; displayMetrics = context.Resources.DisplayMetrics; tapDetector.Density = displayMetrics.Density; if (gestureRecognizer == null) gestureRecognizer = new ExtendedGestureDetector(context, tapDetector); control.Touch += ControlOnTouch; control.Clickable = true; OnElementPropertyChanged(new PropertyChangedEventArgs(String.Empty)); } private void ControlOnTouch(object sender, View.TouchEventArgs touchEventArgs) { gestureRecognizer?.OnTouchEvent(touchEventArgs.Event); touchEventArgs.Handled = false; } protected override void OnDetached() { var control = Control ?? Container; control.Touch -= ControlOnTouch; var g = gestureRecognizer; gestureRecognizer = null; g?.Dispose(); displayMetrics = null; } sealed class ExtendedGestureDetector : GestureDetector { IExtendedGestureListener? myGestureListener; [Preserve] protected ExtendedGestureDetector(IntPtr javaRef, Android.Runtime.JniHandleOwnership transfert) : base(javaRef, transfert) { } public ExtendedGestureDetector(Android.Content.Context context, GestureDetector.IOnGestureListener listener) : base(context, listener) { if (listener is IExtendedGestureListener my) myGestureListener = my; } public override bool OnTouchEvent(MotionEvent? e) { if (myGestureListener != null && e?.Action == MotionEventActions.Up) myGestureListener.OnUp(e); return base.OnTouchEvent(e); } } interface IExtendedGestureListener { void OnUp(MotionEvent? e); } sealed class InternalGestureDetector : GestureDetector.SimpleOnGestureListener, IExtendedGestureListener { private MotionEvent? pinchInitialDown; public int SwipeThresholdInPoints { get; set; } public bool IsPanImmediate { get; set; } public bool IsPinchImmediate { get; set; } public Action<MotionEvent>? TapAction { get; set; } public Action<MotionEvent>? DoubleTapAction { get; set; } public Action<MotionEvent>? SwipeLeftAction { get; set; } public Action<MotionEvent>? SwipeRightAction { get; set; } public Action<MotionEvent>? SwipeTopAction { get; set; } public Action<MotionEvent>? SwipeBottomAction { get; set; } public Func<MotionEvent, MotionEvent?, bool>? PanAction { get; set; } public Action<MotionEvent, MotionEvent?>? PinchAction { get; set; } public Action<MotionEvent>? LongPressAction { get; set; } public float Density { get; set; } public override bool OnDoubleTap(MotionEvent? e) { DoubleTapAction?.Invoke(e); return true; } public override bool OnSingleTapUp(MotionEvent? e) { TapAction?.Invoke(e); return true; } public override void OnLongPress(MotionEvent? e) { LongPressAction?.Invoke(e); } public override bool OnDown(MotionEvent? e) { if (e!=null && IsPanImmediate && e.PointerCount == 1 && PanAction != null) return PanAction.Invoke(e, e); if (e != null && IsPinchImmediate && e.PointerCount == 2 && PinchAction != null) { PinchAction?.Invoke(e, e); return true; } return false; } public void OnUp(MotionEvent? e) { if(e != null) PanAction?.Invoke(e, e); pinchInitialDown = null; } public override bool OnScroll(MotionEvent? initialDown, MotionEvent? currentMove, float distanceX, float distanceY) { if (initialDown != null && currentMove != null) { //Switch to pinch if (pinchInitialDown == null && initialDown.PointerCount == 1 && currentMove.PointerCount == 2) pinchInitialDown = MotionEvent.Obtain(currentMove); if(currentMove.PointerCount == 1 && PanAction != null) return PanAction.Invoke(initialDown, currentMove); if (currentMove.PointerCount == 2 && PinchAction != null && pinchInitialDown != null) { PinchAction.Invoke(pinchInitialDown, currentMove); return true; } } return false; } public override bool OnFling(MotionEvent? e1, MotionEvent? e2, float velocityX, float velocityY) { if (e1 == null || e2 == null) return false; var dx = e2.RawX - e1.RawX; var dy = e2.RawY - e1.RawY; if (Math.Abs(dx) > SwipeThresholdInPoints * Density) { if(dx>0) SwipeRightAction?.Invoke(e2); else SwipeLeftAction?.Invoke(e2); } else if (Math.Abs(dy) > SwipeThresholdInPoints * Density) { if (dy > 0) SwipeBottomAction?.Invoke(e2); else SwipeTopAction?.Invoke(e2); } return true; } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Globalization; using System.Runtime.CompilerServices; namespace System.Numerics { /// <summary> /// A structure encapsulating a 3D Plane /// </summary> public struct Plane : IEquatable<Plane> { /// <summary> /// The normal vector of the Plane. /// </summary> public Vector3 Normal; /// <summary> /// The distance of the Plane along its normal from the origin. /// </summary> public float D; /// <summary> /// Constructs a Plane from the X, Y, and Z components of its normal, and its distance from the origin on that normal. /// </summary> /// <param name="x">The X-component of the normal.</param> /// <param name="y">The Y-component of the normal.</param> /// <param name="z">The Z-component of the normal.</param> /// <param name="d">The distance of the Plane along its normal from the origin.</param> public Plane(float x, float y, float z, float d) { Normal = new Vector3(x, y, z); this.D = d; } /// <summary> /// Constructs a Plane from the given normal and distance along the normal from the origin. /// </summary> /// <param name="normal">The Plane's normal vector.</param> /// <param name="d">The Plane's distance from the origin along its normal vector.</param> public Plane(Vector3 normal, float d) { this.Normal = normal; this.D = d; } /// <summary> /// Constructs a Plane from the given Vector4. /// </summary> /// <param name="value">A vector whose first 3 elements descrip the normal vector, /// and whose W component defines the distance along that normal from the origin.</param> public Plane(Vector4 value) { Normal = new Vector3(value.X, value.Y, value.Z); D = value.W; } /// <summary> /// Creates a Plane that contains the three given points. /// </summary> /// <param name="point1">The first point defining the Plane.</param> /// <param name="point2">The second point defining the Plane.</param> /// <param name="point3">The third point defining the Plane.</param> /// <returns>The Plane containing the three points.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Plane CreateFromVertices(Vector3 point1, Vector3 point2, Vector3 point3) { if (Vector.IsHardwareAccelerated) { Vector3 a = point2 - point1; Vector3 b = point3 - point1; // N = Cross(a, b) Vector3 n = Vector3.Cross(a, b); Vector3 normal = Vector3.Normalize(n); // D = - Dot(N, point1) float d = -Vector3.Dot(normal, point1); return new Plane(normal, d); } else { float ax = point2.X - point1.X; float ay = point2.Y - point1.Y; float az = point2.Z - point1.Z; float bx = point3.X - point1.X; float by = point3.Y - point1.Y; float bz = point3.Z - point1.Z; // N=Cross(a,b) float nx = ay * bz - az * by; float ny = az * bx - ax * bz; float nz = ax * by - ay * bx; // Normalize(N) float ls = nx * nx + ny * ny + nz * nz; float invNorm = 1.0f / (float)Math.Sqrt((double)ls); Vector3 normal = new Vector3( nx * invNorm, ny * invNorm, nz * invNorm); return new Plane( normal, -(normal.X * point1.X + normal.Y * point1.Y + normal.Z * point1.Z)); } } /// <summary> /// Creates a new Plane whose normal vector is the source Plane's normal vector normalized. /// </summary> /// <param name="value">The source Plane.</param> /// <returns>The normalized Plane.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Plane Normalize(Plane value) { const float FLT_EPSILON = 1.192092896e-07f; // smallest such that 1.0+FLT_EPSILON != 1.0 if (Vector.IsHardwareAccelerated) { float normalLengthSquared = value.Normal.LengthSquared(); if (Math.Abs(normalLengthSquared - 1.0f) < FLT_EPSILON) { // It already normalized, so we don't need to farther process. return value; } float normalLength = (float)Math.Sqrt(normalLengthSquared); return new Plane( value.Normal / normalLength, value.D / normalLength); } else { float f = value.Normal.X * value.Normal.X + value.Normal.Y * value.Normal.Y + value.Normal.Z * value.Normal.Z; if (Math.Abs(f - 1.0f) < FLT_EPSILON) { return value; // It already normalized, so we don't need to further process. } float fInv = 1.0f / (float)Math.Sqrt(f); return new Plane( value.Normal.X * fInv, value.Normal.Y * fInv, value.Normal.Z * fInv, value.D * fInv); } } /// <summary> /// Transforms a normalized Plane by a Matrix. /// </summary> /// <param name="plane"> The normalized Plane to transform. /// This Plane must already be normalized, so that its Normal vector is of unit length, before this method is called.</param> /// <param name="matrix">The transformation matrix to apply to the Plane.</param> /// <returns>The transformed Plane.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Plane Transform(Plane plane, Matrix4x4 matrix) { Matrix4x4 m; Matrix4x4.Invert(matrix, out m); float x = plane.Normal.X, y = plane.Normal.Y, z = plane.Normal.Z, w = plane.D; return new Plane( x * m.M11 + y * m.M12 + z * m.M13 + w * m.M14, x * m.M21 + y * m.M22 + z * m.M23 + w * m.M24, x * m.M31 + y * m.M32 + z * m.M33 + w * m.M34, x * m.M41 + y * m.M42 + z * m.M43 + w * m.M44); } /// <summary> /// Transforms a normalized Plane by a Quaternion rotation. /// </summary> /// <param name="plane"> The normalized Plane to transform. /// This Plane must already be normalized, so that its Normal vector is of unit length, before this method is called.</param> /// <param name="rotation">The Quaternion rotation to apply to the Plane.</param> /// <returns>A new Plane that results from applying the rotation.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Plane Transform(Plane plane, Quaternion rotation) { // Compute rotation matrix. float x2 = rotation.X + rotation.X; float y2 = rotation.Y + rotation.Y; float z2 = rotation.Z + rotation.Z; float wx2 = rotation.W * x2; float wy2 = rotation.W * y2; float wz2 = rotation.W * z2; float xx2 = rotation.X * x2; float xy2 = rotation.X * y2; float xz2 = rotation.X * z2; float yy2 = rotation.Y * y2; float yz2 = rotation.Y * z2; float zz2 = rotation.Z * z2; float m11 = 1.0f - yy2 - zz2; float m21 = xy2 - wz2; float m31 = xz2 + wy2; float m12 = xy2 + wz2; float m22 = 1.0f - xx2 - zz2; float m32 = yz2 - wx2; float m13 = xz2 - wy2; float m23 = yz2 + wx2; float m33 = 1.0f - xx2 - yy2; float x = plane.Normal.X, y = plane.Normal.Y, z = plane.Normal.Z; return new Plane( x * m11 + y * m21 + z * m31, x * m12 + y * m22 + z * m32, x * m13 + y * m23 + z * m33, plane.D); } /// <summary> /// Calculates the dot product of a Plane and Vector4. /// </summary> /// <param name="plane">The Plane.</param> /// <param name="value">The Vector4.</param> /// <returns>The dot product.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Dot(Plane plane, Vector4 value) { return plane.Normal.X * value.X + plane.Normal.Y * value.Y + plane.Normal.Z * value.Z + plane.D * value.W; } /// <summary> /// Returns the dot product of a specified Vector3 and the normal vector of this Plane plus the distance (D) value of the Plane. /// </summary> /// <param name="plane">The plane.</param> /// <param name="value">The Vector3.</param> /// <returns>The resulting value.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float DotCoordinate(Plane plane, Vector3 value) { if (Vector.IsHardwareAccelerated) { return Vector3.Dot(plane.Normal, value) + plane.D; } else { return plane.Normal.X * value.X + plane.Normal.Y * value.Y + plane.Normal.Z * value.Z + plane.D; } } /// <summary> /// Returns the dot product of a specified Vector3 and the Normal vector of this Plane. /// </summary> /// <param name="plane">The plane.</param> /// <param name="value">The Vector3.</param> /// <returns>The resulting dot product.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float DotNormal(Plane plane, Vector3 value) { if (Vector.IsHardwareAccelerated) { return Vector3.Dot(plane.Normal, value); } else { return plane.Normal.X * value.X + plane.Normal.Y * value.Y + plane.Normal.Z * value.Z; } } /// <summary> /// Returns a boolean indicating whether the two given Planes are equal. /// </summary> /// <param name="value1">The first Plane to compare.</param> /// <param name="value2">The second Plane to compare.</param> /// <returns>True if the Planes are equal; False otherwise.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(Plane value1, Plane value2) { return (value1.Normal.X == value2.Normal.X && value1.Normal.Y == value2.Normal.Y && value1.Normal.Z == value2.Normal.Z && value1.D == value2.D); } /// <summary> /// Returns a boolean indicating whether the two given Planes are not equal. /// </summary> /// <param name="value1">The first Plane to compare.</param> /// <param name="value2">The second Plane to compare.</param> /// <returns>True if the Planes are not equal; False if they are equal.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(Plane value1, Plane value2) { return (value1.Normal.X != value2.Normal.X || value1.Normal.Y != value2.Normal.Y || value1.Normal.Z != value2.Normal.Z || value1.D != value2.D); } /// <summary> /// Returns a boolean indicating whether the given Plane is equal to this Plane instance. /// </summary> /// <param name="other">The Plane to compare this instance to.</param> /// <returns>True if the other Plane is equal to this instance; False otherwise.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Equals(Plane other) { if (Vector.IsHardwareAccelerated) { return this.Normal.Equals(other.Normal) && this.D == other.D; } else { return (Normal.X == other.Normal.X && Normal.Y == other.Normal.Y && Normal.Z == other.Normal.Z && D == other.D); } } /// <summary> /// Returns a boolean indicating whether the given Object is equal to this Plane instance. /// </summary> /// <param name="obj">The Object to compare against.</param> /// <returns>True if the Object is equal to this Plane; False otherwise.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public override bool Equals(object obj) { if (obj is Plane) { return Equals((Plane)obj); } return false; } /// <summary> /// Returns a String representing this Plane instance. /// </summary> /// <returns>The string representation.</returns> public override string ToString() { CultureInfo ci = CultureInfo.CurrentCulture; return String.Format(ci, "{{Normal:{0} D:{1}}}", Normal.ToString(), D.ToString(ci)); } /// <summary> /// Returns the hash code for this instance. /// </summary> /// <returns>The hash code.</returns> public override int GetHashCode() { return Normal.GetHashCode() + D.GetHashCode(); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.IO; using System.Linq; using JetBrains.Annotations; using osu.Framework.Audio; using osu.Framework.Audio.Track; using osu.Framework.Graphics.Textures; using osu.Framework.IO.Stores; using osu.Framework.Lists; using osu.Framework.Logging; using osu.Framework.Platform; using osu.Framework.Statistics; using osu.Framework.Testing; using osu.Game.Beatmaps.Formats; using osu.Game.Database; using osu.Game.IO; using osu.Game.Skinning; using osu.Game.Storyboards; namespace osu.Game.Beatmaps { public class WorkingBeatmapCache : IBeatmapResourceProvider, IWorkingBeatmapCache { private readonly WeakList<BeatmapManagerWorkingBeatmap> workingCache = new WeakList<BeatmapManagerWorkingBeatmap>(); /// <summary> /// A default representation of a WorkingBeatmap to use when no beatmap is available. /// </summary> public readonly WorkingBeatmap DefaultBeatmap; private readonly AudioManager audioManager; private readonly IResourceStore<byte[]> resources; private readonly LargeTextureStore largeTextureStore; private readonly ITrackStore trackStore; private readonly IResourceStore<byte[]> files; [CanBeNull] private readonly GameHost host; public WorkingBeatmapCache(ITrackStore trackStore, AudioManager audioManager, IResourceStore<byte[]> resources, IResourceStore<byte[]> files, WorkingBeatmap defaultBeatmap = null, GameHost host = null) { DefaultBeatmap = defaultBeatmap; this.audioManager = audioManager; this.resources = resources; this.host = host; this.files = files; largeTextureStore = new LargeTextureStore(host?.CreateTextureLoaderStore(files)); this.trackStore = trackStore; } public void Invalidate(BeatmapSetInfo info) { foreach (var b in info.Beatmaps) Invalidate(b); } public void Invalidate(BeatmapInfo info) { lock (workingCache) { var working = workingCache.FirstOrDefault(w => info.Equals(w.BeatmapInfo)); if (working != null) { Logger.Log($"Invalidating working beatmap cache for {info}"); workingCache.Remove(working); } } } public virtual WorkingBeatmap GetWorkingBeatmap(BeatmapInfo beatmapInfo) { if (beatmapInfo?.BeatmapSet == null) return DefaultBeatmap; lock (workingCache) { var working = workingCache.FirstOrDefault(w => beatmapInfo.Equals(w.BeatmapInfo)); if (working != null) return working; beatmapInfo = beatmapInfo.Detach(); workingCache.Add(working = new BeatmapManagerWorkingBeatmap(beatmapInfo, this)); // best effort; may be higher than expected. GlobalStatistics.Get<int>("Beatmaps", $"Cached {nameof(WorkingBeatmap)}s").Value = workingCache.Count(); return working; } } #region IResourceStorageProvider TextureStore IBeatmapResourceProvider.LargeTextureStore => largeTextureStore; ITrackStore IBeatmapResourceProvider.Tracks => trackStore; AudioManager IStorageResourceProvider.AudioManager => audioManager; RealmAccess IStorageResourceProvider.RealmAccess => null; IResourceStore<byte[]> IStorageResourceProvider.Files => files; IResourceStore<byte[]> IStorageResourceProvider.Resources => resources; IResourceStore<TextureUpload> IStorageResourceProvider.CreateTextureLoaderStore(IResourceStore<byte[]> underlyingStore) => host?.CreateTextureLoaderStore(underlyingStore); #endregion [ExcludeFromDynamicCompile] private class BeatmapManagerWorkingBeatmap : WorkingBeatmap { [NotNull] private readonly IBeatmapResourceProvider resources; public BeatmapManagerWorkingBeatmap(BeatmapInfo beatmapInfo, [NotNull] IBeatmapResourceProvider resources) : base(beatmapInfo, resources.AudioManager) { this.resources = resources; } protected override IBeatmap GetBeatmap() { if (BeatmapInfo.Path == null) return new Beatmap { BeatmapInfo = BeatmapInfo }; try { using (var stream = new LineBufferedReader(GetStream(BeatmapSetInfo.GetPathForFile(BeatmapInfo.Path)))) return Decoder.GetDecoder<Beatmap>(stream).Decode(stream); } catch (Exception e) { Logger.Error(e, "Beatmap failed to load"); return null; } } protected override Texture GetBackground() { if (string.IsNullOrEmpty(Metadata?.BackgroundFile)) return null; try { return resources.LargeTextureStore.Get(BeatmapSetInfo.GetPathForFile(Metadata.BackgroundFile)); } catch (Exception e) { Logger.Error(e, "Background failed to load"); return null; } } protected override Track GetBeatmapTrack() { if (string.IsNullOrEmpty(Metadata?.AudioFile)) return null; try { return resources.Tracks.Get(BeatmapSetInfo.GetPathForFile(Metadata.AudioFile)); } catch (Exception e) { Logger.Error(e, "Track failed to load"); return null; } } protected override Waveform GetWaveform() { if (string.IsNullOrEmpty(Metadata?.AudioFile)) return null; try { var trackData = GetStream(BeatmapSetInfo.GetPathForFile(Metadata.AudioFile)); return trackData == null ? null : new Waveform(trackData); } catch (Exception e) { Logger.Error(e, "Waveform failed to load"); return null; } } protected override Storyboard GetStoryboard() { Storyboard storyboard; if (BeatmapInfo.Path == null) return new Storyboard(); try { using (var stream = new LineBufferedReader(GetStream(BeatmapSetInfo.GetPathForFile(BeatmapInfo.Path)))) { var decoder = Decoder.GetDecoder<Storyboard>(stream); string storyboardFilename = BeatmapSetInfo?.Files.FirstOrDefault(f => f.Filename.EndsWith(".osb", StringComparison.OrdinalIgnoreCase))?.Filename; // todo: support loading from both set-wide storyboard *and* beatmap specific. if (string.IsNullOrEmpty(storyboardFilename)) storyboard = decoder.Decode(stream); else { using (var secondaryStream = new LineBufferedReader(GetStream(BeatmapSetInfo.GetPathForFile(storyboardFilename)))) storyboard = decoder.Decode(stream, secondaryStream); } } } catch (Exception e) { Logger.Error(e, "Storyboard failed to load"); storyboard = new Storyboard(); } storyboard.BeatmapInfo = BeatmapInfo; return storyboard; } protected internal override ISkin GetSkin() { try { return new LegacyBeatmapSkin(BeatmapInfo, resources.Files, resources); } catch (Exception e) { Logger.Error(e, "Skin failed to load"); return null; } } public override Stream GetStream(string storagePath) => resources.Files.GetStream(storagePath); } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Linq; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using Abp.Collections.Extensions; using Abp.Data; using Abp.Domain.Entities; using Abp.Domain.Repositories; using Abp.Reflection; using Microsoft.EntityFrameworkCore; namespace Abp.EntityFrameworkCore.Repositories { /// <summary> /// Implements IRepository for Entity Framework. /// </summary> /// <typeparam name="TDbContext">DbContext which contains <typeparamref name="TEntity"/>.</typeparam> /// <typeparam name="TEntity">Type of the Entity for this repository</typeparam> /// <typeparam name="TPrimaryKey">Primary key of the entity</typeparam> public class EfCoreRepositoryBase<TDbContext, TEntity, TPrimaryKey> : AbpRepositoryBase<TEntity, TPrimaryKey>, ISupportsExplicitLoading<TEntity, TPrimaryKey>, IRepositoryWithDbContext where TEntity : class, IEntity<TPrimaryKey> where TDbContext : DbContext { /// <summary> /// Gets EF DbContext object. /// </summary> public virtual async Task<TDbContext> GetContextAsync() { return await _dbContextProvider.GetDbContextAsync(MultiTenancySide); } /// <summary> /// Gets EF DbContext object. /// </summary> public virtual TDbContext GetContext() { return _dbContextProvider.GetDbContext(MultiTenancySide); } /// <summary> /// Gets DbSet for given entity. /// </summary> public virtual async Task<DbSet<TEntity>> GetTableAsync() { var context = await GetContextAsync(); return context.Set<TEntity>(); } /// <summary> /// Gets DbSet for given entity. /// </summary> public virtual DbSet<TEntity> GetTable() { var context = GetContext(); return context.Set<TEntity>(); } /// <summary> /// Gets DbQuery for given entity. /// </summary> public virtual async Task<DbSet<TEntity>> GetDbQueryTableAsync() { return (await GetContextAsync()).Set<TEntity>(); } /// <summary> /// Gets DbQuery for given entity. /// </summary> public virtual DbSet<TEntity> GetDbQueryTable() { return GetContext().Set<TEntity>(); } private static readonly ConcurrentDictionary<Type, bool> EntityIsDbQuery = new ConcurrentDictionary<Type, bool>(); protected virtual IQueryable<TEntity> GetQueryable() { if (EntityIsDbQuery.GetOrAdd(typeof(TEntity), key => GetContext().GetType().GetProperties().Any(property => ReflectionHelper.IsAssignableToGenericType(property.PropertyType, typeof(DbSet<>)) && ReflectionHelper.IsAssignableToGenericType(property.PropertyType.GenericTypeArguments[0], typeof(IEntity<>)) && property.PropertyType.GetGenericArguments().Any(x => x == typeof(TEntity))))) { return GetDbQueryTable().AsQueryable(); } return GetTable().AsQueryable(); } protected virtual async Task<IQueryable<TEntity>> GetQueryableAsync() { if (EntityIsDbQuery.GetOrAdd(typeof(TEntity), key => GetContext().GetType().GetProperties().Any(property => ReflectionHelper.IsAssignableToGenericType(property.PropertyType, typeof(DbSet<>)) && ReflectionHelper.IsAssignableToGenericType(property.PropertyType.GenericTypeArguments[0], typeof(IEntity<>)) && property.PropertyType.GetGenericArguments().Any(x => x == typeof(TEntity))))) { return (await GetDbQueryTableAsync()).AsQueryable(); } return (await GetTableAsync()).AsQueryable(); } public virtual DbTransaction GetTransaction() { return (DbTransaction) TransactionProvider?.GetActiveTransaction(new ActiveTransactionProviderArgs { {"ContextType", typeof(TDbContext)}, {"MultiTenancySide", MultiTenancySide} }); } public virtual async Task<DbTransaction> GetTransactionAsync() { if (TransactionProvider == null) { return null; } var transaction = await TransactionProvider.GetActiveTransactionAsync(new ActiveTransactionProviderArgs { {"ContextType", typeof(TDbContext)}, {"MultiTenancySide", MultiTenancySide} }); return (DbTransaction) transaction; } public virtual DbConnection GetConnection() { var connection = GetContext().Database.GetDbConnection(); if (connection.State != ConnectionState.Open) { connection.Open(); } return connection; } public virtual async Task<DbConnection> GetConnectionAsync() { var context = await GetContextAsync(); var connection = context.Database.GetDbConnection(); if (connection.State != ConnectionState.Open) { await connection.OpenAsync(); } return connection; } public IActiveTransactionProvider TransactionProvider { private get; set; } private readonly IDbContextProvider<TDbContext> _dbContextProvider; /// <summary> /// Constructor /// </summary> /// <param name="dbContextProvider"></param> public EfCoreRepositoryBase(IDbContextProvider<TDbContext> dbContextProvider) { _dbContextProvider = dbContextProvider; } public override IQueryable<TEntity> GetAll() { return GetAllIncluding(); } public override async Task<IQueryable<TEntity>> GetAllAsync() { return await GetAllIncludingAsync(); } public override IQueryable<TEntity> GetAllIncluding( params Expression<Func<TEntity, object>>[] propertySelectors) { var query = GetQueryable(); if (propertySelectors.IsNullOrEmpty()) { return query; } foreach (var propertySelector in propertySelectors) { query = query.Include(propertySelector); } return query; } public override async Task<IQueryable<TEntity>> GetAllIncludingAsync( params Expression<Func<TEntity, object>>[] propertySelectors) { var query = await GetQueryableAsync(); if (propertySelectors.IsNullOrEmpty()) { return query; } foreach (var propertySelector in propertySelectors) { query = query.Include(propertySelector); } return query; } public override async Task<List<TEntity>> GetAllListAsync() { return await (await GetAllAsync()).ToListAsync(CancellationTokenProvider.Token); } public override async Task<List<TEntity>> GetAllListAsync(Expression<Func<TEntity, bool>> predicate) { return await (await GetAllAsync()).Where(predicate).ToListAsync(CancellationTokenProvider.Token); } public override async Task<TEntity> SingleAsync(Expression<Func<TEntity, bool>> predicate) { return await (await GetAllAsync()).SingleAsync(predicate, CancellationTokenProvider.Token); } public override async Task<TEntity> FirstOrDefaultAsync(TPrimaryKey id) { return await (await GetAllAsync()).FirstOrDefaultAsync( CreateEqualityExpressionForId(id), CancellationTokenProvider.Token ); } public override async Task<TEntity> FirstOrDefaultAsync(Expression<Func<TEntity, bool>> predicate) { return await (await GetAllAsync()).FirstOrDefaultAsync(predicate, CancellationTokenProvider.Token); } public override TEntity Insert(TEntity entity) { return GetTable().Add(entity).Entity; } public override Task<TEntity> InsertAsync(TEntity entity) { return Task.FromResult(Insert(entity)); } public override TPrimaryKey InsertAndGetId(TEntity entity) { entity = Insert(entity); if (MayHaveTemporaryKey(entity) || entity.IsTransient()) { GetContext().SaveChanges(); } return entity.Id; } public override async Task<TPrimaryKey> InsertAndGetIdAsync(TEntity entity) { entity = await InsertAsync(entity); if (MayHaveTemporaryKey(entity) || entity.IsTransient()) { var context = await GetContextAsync(); await context.SaveChangesAsync(CancellationTokenProvider.Token); } return entity.Id; } public override TPrimaryKey InsertOrUpdateAndGetId(TEntity entity) { entity = InsertOrUpdate(entity); if (MayHaveTemporaryKey(entity) || entity.IsTransient()) { GetContext().SaveChanges(); } return entity.Id; } public override async Task<TPrimaryKey> InsertOrUpdateAndGetIdAsync(TEntity entity) { entity = await InsertOrUpdateAsync(entity); if (MayHaveTemporaryKey(entity) || entity.IsTransient()) { var context = await GetContextAsync(); await context.SaveChangesAsync(CancellationTokenProvider.Token); } return entity.Id; } public override TEntity Update(TEntity entity) { AttachIfNot(entity); GetContext().Entry(entity).State = EntityState.Modified; return entity; } public override Task<TEntity> UpdateAsync(TEntity entity) { entity = Update(entity); return Task.FromResult(entity); } public override void Delete(TEntity entity) { AttachIfNot(entity); GetTable().Remove(entity); } public override void Delete(TPrimaryKey id) { var entity = GetFromChangeTrackerOrNull(id); if (entity != null) { Delete(entity); return; } entity = FirstOrDefault(id); if (entity != null) { Delete(entity); return; } //Could not found the entity, do nothing. } public override async Task<int> CountAsync() { return await (await GetAllAsync()).CountAsync(CancellationTokenProvider.Token); } public override async Task<int> CountAsync(Expression<Func<TEntity, bool>> predicate) { return await (await GetAllAsync()).Where(predicate).CountAsync(CancellationTokenProvider.Token); } public override async Task<long> LongCountAsync() { return await (await GetAllAsync()).LongCountAsync(CancellationTokenProvider.Token); } public override async Task<long> LongCountAsync(Expression<Func<TEntity, bool>> predicate) { return await (await GetAllAsync()).Where(predicate).LongCountAsync(CancellationTokenProvider.Token); } protected virtual void AttachIfNot(TEntity entity) { var entry = GetContext().ChangeTracker.Entries().FirstOrDefault(ent => ent.Entity == entity); if (entry != null) { return; } GetTable().Attach(entity); } public DbContext GetDbContext() { return GetContext(); } public async Task<DbContext> GetDbContextAsync() { return await GetContextAsync(); } public async Task EnsureCollectionLoadedAsync<TProperty>( TEntity entity, Expression<Func<TEntity, IEnumerable<TProperty>>> collectionExpression, CancellationToken cancellationToken) where TProperty : class { var context = await GetContextAsync(); await context.Entry(entity).Collection(collectionExpression).LoadAsync(cancellationToken); } public void EnsureCollectionLoaded<TProperty>( TEntity entity, Expression<Func<TEntity, IEnumerable<TProperty>>> collectionExpression, CancellationToken cancellationToken) where TProperty : class { GetContext().Entry(entity).Collection(collectionExpression).Load(); } public async Task EnsurePropertyLoadedAsync<TProperty>( TEntity entity, Expression<Func<TEntity, TProperty>> propertyExpression, CancellationToken cancellationToken) where TProperty : class { var context = await GetContextAsync(); await context.Entry(entity).Reference(propertyExpression).LoadAsync(cancellationToken); } public void EnsurePropertyLoaded<TProperty>( TEntity entity, Expression<Func<TEntity, TProperty>> propertyExpression, CancellationToken cancellationToken) where TProperty : class { GetContext().Entry(entity).Reference(propertyExpression).Load(); } private TEntity GetFromChangeTrackerOrNull(TPrimaryKey id) { var entry = GetContext().ChangeTracker.Entries() .FirstOrDefault( ent => ent.Entity is TEntity && EqualityComparer<TPrimaryKey>.Default.Equals(id, (ent.Entity as TEntity).Id) ); return entry?.Entity as TEntity; } private static bool MayHaveTemporaryKey(TEntity entity) { if (typeof(TPrimaryKey) == typeof(byte)) { return true; } if (typeof(TPrimaryKey) == typeof(int)) { return Convert.ToInt32(entity.Id) <= 0; } if (typeof(TPrimaryKey) == typeof(long)) { return Convert.ToInt64(entity.Id) <= 0; } return false; } } }
using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; using System.ComponentModel; namespace WeifenLuo.WinFormsUI.Docking { using WeifenLuo.WinFormsUI.ThemeVS2013Blue; internal class VS2013BlueDockPaneStrip : DockPaneStripBase { private class TabVS2013Light : Tab { public TabVS2013Light(IDockContent content) : base(content) { } private int m_tabX; public int TabX { get { return m_tabX; } set { m_tabX = value; } } private int m_tabWidth; public int TabWidth { get { return m_tabWidth; } set { m_tabWidth = value; } } private int m_maxWidth; public int MaxWidth { get { return m_maxWidth; } set { m_maxWidth = value; } } private bool m_flag; protected internal bool Flag { get { return m_flag; } set { m_flag = value; } } } protected override Tab CreateTab(IDockContent content) { return new TabVS2013Light(content); } private sealed class InertButton : InertButtonBase { private Bitmap m_image0, m_image1; public InertButton(Bitmap image0, Bitmap image1) : base() { m_image0 = image0; m_image1 = image1; } private int m_imageCategory = 0; public int ImageCategory { get { return m_imageCategory; } set { if (m_imageCategory == value) return; m_imageCategory = value; Invalidate(); } } public override Bitmap Image { get { return ImageCategory == 0 ? m_image0 : m_image1; } } } #region Constants private const int _ToolWindowStripGapTop = 0; private const int _ToolWindowStripGapBottom = 1; private const int _ToolWindowStripGapLeft = 0; private const int _ToolWindowStripGapRight = 0; private const int _ToolWindowImageHeight = 16; private const int _ToolWindowImageWidth = 0;//16; private const int _ToolWindowImageGapTop = 3; private const int _ToolWindowImageGapBottom = 1; private const int _ToolWindowImageGapLeft = 2; private const int _ToolWindowImageGapRight = 0; private const int _ToolWindowTextGapRight = 3; private const int _ToolWindowTabSeperatorGapTop = 3; private const int _ToolWindowTabSeperatorGapBottom = 3; private const int _DocumentStripGapTop = 0; private const int _DocumentStripGapBottom = 0; private const int _DocumentTabMaxWidth = 200; private const int _DocumentButtonGapTop = 3; private const int _DocumentButtonGapBottom = 3; private const int _DocumentButtonGapBetween = 0; private const int _DocumentButtonGapRight = 3; private const int _DocumentTabGapTop = 0;//3; private const int _DocumentTabGapLeft = 0;//3; private const int _DocumentTabGapRight = 0;//3; private const int _DocumentIconGapBottom = 2;//2; private const int _DocumentIconGapLeft = 8; private const int _DocumentIconGapRight = 0; private const int _DocumentIconHeight = 16; private const int _DocumentIconWidth = 16; private const int _DocumentTextGapRight = 6; #endregion #region Members private ContextMenuStrip m_selectMenu; private static Bitmap m_imageButtonClose; private InertButton m_buttonClose; private static Bitmap m_imageButtonWindowList; private static Bitmap m_imageButtonWindowListOverflow; private InertButton m_buttonWindowList; private IContainer m_components; private ToolTip m_toolTip; private Font m_font; private Font m_boldFont; private int m_startDisplayingTab = 0; private int m_endDisplayingTab = 0; private int m_firstDisplayingTab = 0; private bool m_documentTabsOverflow = false; private static string m_toolTipSelect; private static string m_toolTipClose; private bool m_closeButtonVisible = false; private Rectangle _activeClose; private int _selectMenuMargin = 5; #endregion #region Properties private Rectangle TabStripRectangle { get { if (Appearance == DockPane.AppearanceStyle.Document) return TabStripRectangle_Document; else return TabStripRectangle_ToolWindow; } } private Rectangle TabStripRectangle_ToolWindow { get { Rectangle rect = ClientRectangle; return new Rectangle(rect.X, rect.Top + ToolWindowStripGapTop, rect.Width, rect.Height - ToolWindowStripGapTop - ToolWindowStripGapBottom); } } private Rectangle TabStripRectangle_Document { get { Rectangle rect = ClientRectangle; return new Rectangle(rect.X, rect.Top + DocumentStripGapTop, rect.Width, rect.Height + DocumentStripGapTop - ToolWindowStripGapBottom); } } private Rectangle TabsRectangle { get { if (Appearance == DockPane.AppearanceStyle.ToolWindow) return TabStripRectangle; Rectangle rectWindow = TabStripRectangle; int x = rectWindow.X; int y = rectWindow.Y; int width = rectWindow.Width; int height = rectWindow.Height; x += DocumentTabGapLeft; width -= DocumentTabGapLeft + DocumentTabGapRight + DocumentButtonGapRight + ButtonClose.Width + ButtonWindowList.Width + 2 * DocumentButtonGapBetween; return new Rectangle(x, y, width, height); } } private ContextMenuStrip SelectMenu { get { return m_selectMenu; } } public int SelectMenuMargin { get { return _selectMenuMargin; } set { _selectMenuMargin = value; } } private static Bitmap ImageButtonClose { get { if (m_imageButtonClose == null) m_imageButtonClose = Resources.DockPane_Close; return m_imageButtonClose; } } private InertButton ButtonClose { get { if (m_buttonClose == null) { m_buttonClose = new InertButton(ImageButtonClose, ImageButtonClose); m_toolTip.SetToolTip(m_buttonClose, ToolTipClose); m_buttonClose.Click += new EventHandler(Close_Click); Controls.Add(m_buttonClose); } return m_buttonClose; } } private static Bitmap ImageButtonWindowList { get { if (m_imageButtonWindowList == null) m_imageButtonWindowList = ThemeVS2012Light.Resources.DockPane_Option; return m_imageButtonWindowList; } } private static Bitmap ImageButtonWindowListOverflow { get { if (m_imageButtonWindowListOverflow == null) m_imageButtonWindowListOverflow = ThemeVS2012Light.Resources.DockPane_OptionOverflow; return m_imageButtonWindowListOverflow; } } private InertButton ButtonWindowList { get { if (m_buttonWindowList == null) { m_buttonWindowList = new InertButton(ImageButtonWindowList, ImageButtonWindowListOverflow); m_toolTip.SetToolTip(m_buttonWindowList, ToolTipSelect); m_buttonWindowList.Click += new EventHandler(WindowList_Click); Controls.Add(m_buttonWindowList); } return m_buttonWindowList; } } private static GraphicsPath GraphicsPath { get { return VS2012LightAutoHideStrip.GraphicsPath; } } private IContainer Components { get { return m_components; } } public Font TextFont { get { return DockPane.DockPanel.Skin.DockPaneStripSkin.TextFont; } } private Font BoldFont { get { if (IsDisposed) return null; if (m_boldFont == null) { m_font = TextFont; m_boldFont = new Font(TextFont, FontStyle.Bold); } else if (m_font != TextFont) { m_boldFont.Dispose(); m_font = TextFont; m_boldFont = new Font(TextFont, FontStyle.Bold); } return m_boldFont; } } private int StartDisplayingTab { get { return m_startDisplayingTab; } set { m_startDisplayingTab = value; Invalidate(); } } private int EndDisplayingTab { get { return m_endDisplayingTab; } set { m_endDisplayingTab = value; } } private int FirstDisplayingTab { get { return m_firstDisplayingTab; } set { m_firstDisplayingTab = value; } } private bool DocumentTabsOverflow { set { if (m_documentTabsOverflow == value) return; m_documentTabsOverflow = value; if (value) ButtonWindowList.ImageCategory = 1; else ButtonWindowList.ImageCategory = 0; } } #region Customizable Properties private static int ToolWindowStripGapTop { get { return _ToolWindowStripGapTop; } } private static int ToolWindowStripGapBottom { get { return _ToolWindowStripGapBottom; } } private static int ToolWindowStripGapLeft { get { return _ToolWindowStripGapLeft; } } private static int ToolWindowStripGapRight { get { return _ToolWindowStripGapRight; } } private static int ToolWindowImageHeight { get { return _ToolWindowImageHeight; } } private static int ToolWindowImageWidth { get { return _ToolWindowImageWidth; } } private static int ToolWindowImageGapTop { get { return _ToolWindowImageGapTop; } } private static int ToolWindowImageGapBottom { get { return _ToolWindowImageGapBottom; } } private static int ToolWindowImageGapLeft { get { return _ToolWindowImageGapLeft; } } private static int ToolWindowImageGapRight { get { return _ToolWindowImageGapRight; } } private static int ToolWindowTextGapRight { get { return _ToolWindowTextGapRight; } } private static int ToolWindowTabSeperatorGapTop { get { return _ToolWindowTabSeperatorGapTop; } } private static int ToolWindowTabSeperatorGapBottom { get { return _ToolWindowTabSeperatorGapBottom; } } private static string ToolTipClose { get { if (m_toolTipClose == null) m_toolTipClose = Strings.DockPaneStrip_ToolTipClose; return m_toolTipClose; } } private static string ToolTipSelect { get { if (m_toolTipSelect == null) m_toolTipSelect = Strings.DockPaneStrip_ToolTipWindowList; return m_toolTipSelect; } } private TextFormatFlags ToolWindowTextFormat { get { TextFormatFlags textFormat = TextFormatFlags.EndEllipsis | TextFormatFlags.HorizontalCenter | TextFormatFlags.SingleLine | TextFormatFlags.VerticalCenter; if (RightToLeft == RightToLeft.Yes) return textFormat | TextFormatFlags.RightToLeft | TextFormatFlags.Right; else return textFormat; } } private static int DocumentStripGapTop { get { return _DocumentStripGapTop; } } private static int DocumentStripGapBottom { get { return _DocumentStripGapBottom; } } private TextFormatFlags DocumentTextFormat { get { TextFormatFlags textFormat = TextFormatFlags.EndEllipsis | TextFormatFlags.SingleLine | TextFormatFlags.VerticalCenter | TextFormatFlags.HorizontalCenter; if (RightToLeft == RightToLeft.Yes) return textFormat | TextFormatFlags.RightToLeft; else return textFormat; } } private static int DocumentTabMaxWidth { get { return _DocumentTabMaxWidth; } } private static int DocumentButtonGapTop { get { return _DocumentButtonGapTop; } } private static int DocumentButtonGapBottom { get { return _DocumentButtonGapBottom; } } private static int DocumentButtonGapBetween { get { return _DocumentButtonGapBetween; } } private static int DocumentButtonGapRight { get { return _DocumentButtonGapRight; } } private static int DocumentTabGapTop { get { return _DocumentTabGapTop; } } private static int DocumentTabGapLeft { get { return _DocumentTabGapLeft; } } private static int DocumentTabGapRight { get { return _DocumentTabGapRight; } } private static int DocumentIconGapBottom { get { return _DocumentIconGapBottom; } } private static int DocumentIconGapLeft { get { return _DocumentIconGapLeft; } } private static int DocumentIconGapRight { get { return _DocumentIconGapRight; } } private static int DocumentIconWidth { get { return _DocumentIconWidth; } } private static int DocumentIconHeight { get { return _DocumentIconHeight; } } private static int DocumentTextGapRight { get { return _DocumentTextGapRight; } } private static Pen PenToolWindowTabBorder { get { return SystemPens.ControlDark; } } private static Pen PenDocumentTabActiveBorder { get { return SystemPens.ControlDarkDark; } } private static Pen PenDocumentTabInactiveBorder { get { return SystemPens.GrayText; } } #endregion #endregion public VS2013BlueDockPaneStrip(DockPane pane) : base(pane) { SetStyle(ControlStyles.ResizeRedraw | ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, true); SuspendLayout(); m_components = new Container(); m_toolTip = new ToolTip(Components); m_selectMenu = new ContextMenuStrip(Components); ResumeLayout(); } protected override void Dispose(bool disposing) { if (disposing) { Components.Dispose(); if (m_boldFont != null) { m_boldFont.Dispose(); m_boldFont = null; } } base.Dispose(disposing); } protected override int MeasureHeight() { if (Appearance == DockPane.AppearanceStyle.ToolWindow) return MeasureHeight_ToolWindow(); else return MeasureHeight_Document(); } private int MeasureHeight_ToolWindow() { if (DockPane.IsAutoHide || Tabs.Count <= 1) return 0; int height = Math.Max(TextFont.Height, ToolWindowImageHeight + ToolWindowImageGapTop + ToolWindowImageGapBottom) + ToolWindowStripGapTop + ToolWindowStripGapBottom; return height; } private int MeasureHeight_Document() { int height = Math.Max(TextFont.Height + DocumentTabGapTop, ButtonClose.Height + DocumentButtonGapTop + DocumentButtonGapBottom) + DocumentStripGapBottom + DocumentStripGapTop; return height; } protected override void OnPaint(PaintEventArgs e) { Rectangle rect = TabsRectangle; DockPanelGradient gradient = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.DockStripGradient; if (Appearance == DockPane.AppearanceStyle.Document) { rect.X -= DocumentTabGapLeft; // Add these values back in so that the DockStrip color is drawn // beneath the close button and window list button. // It is possible depending on the DockPanel DocumentStyle to have // a Document without a DockStrip. rect.Width += DocumentTabGapLeft + DocumentTabGapRight + DocumentButtonGapRight + ButtonClose.Width + ButtonWindowList.Width; } else { gradient = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.DockStripGradient; } Color startColor = gradient.StartColor; Color endColor = gradient.EndColor; LinearGradientMode gradientMode = gradient.LinearGradientMode; DrawingRoutines.SafelyDrawLinearGradient(rect, startColor, endColor, gradientMode, e.Graphics); base.OnPaint(e); CalculateTabs(); if (Appearance == DockPane.AppearanceStyle.Document && DockPane.ActiveContent != null) { if (EnsureDocumentTabVisible(DockPane.ActiveContent, false)) CalculateTabs(); } DrawTabStrip(e.Graphics); } protected override void OnRefreshChanges() { SetInertButtons(); Invalidate(); } public override GraphicsPath GetOutline(int index) { if (Appearance == DockPane.AppearanceStyle.Document) return GetOutline_Document(index); else return GetOutline_ToolWindow(index); } private GraphicsPath GetOutline_Document(int index) { Rectangle rectTab = GetTabRectangle(index); rectTab.X -= rectTab.Height / 2; rectTab.Intersect(TabsRectangle); rectTab = RectangleToScreen(DrawHelper.RtlTransform(this, rectTab)); Rectangle rectPaneClient = DockPane.RectangleToScreen(DockPane.ClientRectangle); GraphicsPath path = new GraphicsPath(); GraphicsPath pathTab = GetTabOutline_Document(Tabs[index], true, true, true); path.AddPath(pathTab, true); if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) { path.AddLine(rectTab.Right, rectTab.Top, rectPaneClient.Right, rectTab.Top); path.AddLine(rectPaneClient.Right, rectTab.Top, rectPaneClient.Right, rectPaneClient.Top); path.AddLine(rectPaneClient.Right, rectPaneClient.Top, rectPaneClient.Left, rectPaneClient.Top); path.AddLine(rectPaneClient.Left, rectPaneClient.Top, rectPaneClient.Left, rectTab.Top); path.AddLine(rectPaneClient.Left, rectTab.Top, rectTab.Right, rectTab.Top); } else { path.AddLine(rectTab.Right, rectTab.Bottom, rectPaneClient.Right, rectTab.Bottom); path.AddLine(rectPaneClient.Right, rectTab.Bottom, rectPaneClient.Right, rectPaneClient.Bottom); path.AddLine(rectPaneClient.Right, rectPaneClient.Bottom, rectPaneClient.Left, rectPaneClient.Bottom); path.AddLine(rectPaneClient.Left, rectPaneClient.Bottom, rectPaneClient.Left, rectTab.Bottom); path.AddLine(rectPaneClient.Left, rectTab.Bottom, rectTab.Right, rectTab.Bottom); } return path; } private GraphicsPath GetOutline_ToolWindow(int index) { Rectangle rectTab = GetTabRectangle(index); rectTab.Intersect(TabsRectangle); rectTab = RectangleToScreen(DrawHelper.RtlTransform(this, rectTab)); Rectangle rectPaneClient = DockPane.RectangleToScreen(DockPane.ClientRectangle); GraphicsPath path = new GraphicsPath(); GraphicsPath pathTab = GetTabOutline(Tabs[index], true, true); path.AddPath(pathTab, true); path.AddLine(rectTab.Left, rectTab.Top, rectPaneClient.Left, rectTab.Top); path.AddLine(rectPaneClient.Left, rectTab.Top, rectPaneClient.Left, rectPaneClient.Top); path.AddLine(rectPaneClient.Left, rectPaneClient.Top, rectPaneClient.Right, rectPaneClient.Top); path.AddLine(rectPaneClient.Right, rectPaneClient.Top, rectPaneClient.Right, rectTab.Top); path.AddLine(rectPaneClient.Right, rectTab.Top, rectTab.Right, rectTab.Top); return path; } private void CalculateTabs() { if (Appearance == DockPane.AppearanceStyle.ToolWindow) CalculateTabs_ToolWindow(); else CalculateTabs_Document(); } private void CalculateTabs_ToolWindow() { if (Tabs.Count <= 1 || DockPane.IsAutoHide) return; Rectangle rectTabStrip = TabStripRectangle; // Calculate tab widths int countTabs = Tabs.Count; foreach (TabVS2013Light tab in Tabs) { tab.MaxWidth = GetMaxTabWidth(Tabs.IndexOf(tab)); tab.Flag = false; } // Set tab whose max width less than average width bool anyWidthWithinAverage = true; int totalWidth = rectTabStrip.Width - ToolWindowStripGapLeft - ToolWindowStripGapRight; int totalAllocatedWidth = 0; int averageWidth = totalWidth / countTabs; int remainedTabs = countTabs; for (anyWidthWithinAverage = true; anyWidthWithinAverage && remainedTabs > 0; ) { anyWidthWithinAverage = false; foreach (TabVS2013Light tab in Tabs) { if (tab.Flag) continue; if (tab.MaxWidth <= averageWidth) { tab.Flag = true; tab.TabWidth = tab.MaxWidth; totalAllocatedWidth += tab.TabWidth; anyWidthWithinAverage = true; remainedTabs--; } } if (remainedTabs != 0) averageWidth = (totalWidth - totalAllocatedWidth) / remainedTabs; } // If any tab width not set yet, set it to the average width if (remainedTabs > 0) { int roundUpWidth = (totalWidth - totalAllocatedWidth) - (averageWidth * remainedTabs); foreach (TabVS2013Light tab in Tabs) { if (tab.Flag) continue; tab.Flag = true; if (roundUpWidth > 0) { tab.TabWidth = averageWidth + 1; roundUpWidth--; } else tab.TabWidth = averageWidth; } } // Set the X position of the tabs int x = rectTabStrip.X + ToolWindowStripGapLeft; foreach (TabVS2013Light tab in Tabs) { tab.TabX = x; x += tab.TabWidth; } } private bool CalculateDocumentTab(Rectangle rectTabStrip, ref int x, int index) { bool overflow = false; var tab = Tabs[index] as TabVS2013Light; tab.MaxWidth = GetMaxTabWidth(index); int width = Math.Min(tab.MaxWidth, DocumentTabMaxWidth); if (x + width < rectTabStrip.Right || index == StartDisplayingTab) { tab.TabX = x; tab.TabWidth = width; EndDisplayingTab = index; } else { tab.TabX = 0; tab.TabWidth = 0; overflow = true; } x += width; return overflow; } /// <summary> /// Calculate which tabs are displayed and in what order. /// </summary> private void CalculateTabs_Document() { if (m_startDisplayingTab >= Tabs.Count) m_startDisplayingTab = 0; Rectangle rectTabStrip = TabsRectangle; int x = rectTabStrip.X; //+ rectTabStrip.Height / 2; bool overflow = false; // Originally all new documents that were considered overflow // (not enough pane strip space to show all tabs) were added to // the far left (assuming not right to left) and the tabs on the // right were dropped from view. If StartDisplayingTab is not 0 // then we are dealing with making sure a specific tab is kept in focus. if (m_startDisplayingTab > 0) { int tempX = x; var tab = Tabs[m_startDisplayingTab] as TabVS2013Light; tab.MaxWidth = GetMaxTabWidth(m_startDisplayingTab); // Add the active tab and tabs to the left for (int i = StartDisplayingTab; i >= 0; i--) CalculateDocumentTab(rectTabStrip, ref tempX, i); // Store which tab is the first one displayed so that it // will be drawn correctly (without part of the tab cut off) FirstDisplayingTab = EndDisplayingTab; tempX = x; // Reset X location because we are starting over // Start with the first tab displayed - name is a little misleading. // Loop through each tab and set its location. If there is not enough // room for all of them overflow will be returned. for (int i = EndDisplayingTab; i < Tabs.Count; i++) overflow = CalculateDocumentTab(rectTabStrip, ref tempX, i); // If not all tabs are shown then we have an overflow. if (FirstDisplayingTab != 0) overflow = true; } else { for (int i = StartDisplayingTab; i < Tabs.Count; i++) overflow = CalculateDocumentTab(rectTabStrip, ref x, i); for (int i = 0; i < StartDisplayingTab; i++) overflow = CalculateDocumentTab(rectTabStrip, ref x, i); FirstDisplayingTab = StartDisplayingTab; } if (!overflow) { m_startDisplayingTab = 0; FirstDisplayingTab = 0; x = rectTabStrip.X;// +rectTabStrip.Height / 2; foreach (TabVS2013Light tab in Tabs) { tab.TabX = x; x += tab.TabWidth; } } DocumentTabsOverflow = overflow; } protected override void EnsureTabVisible(IDockContent content) { if (Appearance != DockPane.AppearanceStyle.Document || !Tabs.Contains(content)) return; CalculateTabs(); EnsureDocumentTabVisible(content, true); } private bool EnsureDocumentTabVisible(IDockContent content, bool repaint) { int index = Tabs.IndexOf(content); var tab = Tabs[index] as TabVS2013Light; if (tab.TabWidth != 0) return false; StartDisplayingTab = index; if (repaint) Invalidate(); return true; } private int GetMaxTabWidth(int index) { if (Appearance == DockPane.AppearanceStyle.ToolWindow) return GetMaxTabWidth_ToolWindow(index); else return GetMaxTabWidth_Document(index); } private int GetMaxTabWidth_ToolWindow(int index) { IDockContent content = Tabs[index].Content; Size sizeString = TextRenderer.MeasureText(content.DockHandler.TabText, TextFont); return ToolWindowImageWidth + sizeString.Width + ToolWindowImageGapLeft + ToolWindowImageGapRight + ToolWindowTextGapRight; } private const int TAB_CLOSE_BUTTON_WIDTH = 30; private int GetMaxTabWidth_Document(int index) { IDockContent content = Tabs[index].Content; int height = GetTabRectangle_Document(index).Height; Size sizeText = TextRenderer.MeasureText(content.DockHandler.TabText, BoldFont, new Size(DocumentTabMaxWidth, height), DocumentTextFormat); int width; if (DockPane.DockPanel.ShowDocumentIcon) width = sizeText.Width + DocumentIconWidth + DocumentIconGapLeft + DocumentIconGapRight + DocumentTextGapRight; else width = sizeText.Width + DocumentIconGapLeft + DocumentTextGapRight; width += TAB_CLOSE_BUTTON_WIDTH; return width; } private void DrawTabStrip(Graphics g) { if (Appearance == DockPane.AppearanceStyle.Document) DrawTabStrip_Document(g); else DrawTabStrip_ToolWindow(g); } private void DrawTabStrip_Document(Graphics g) { int count = Tabs.Count; if (count == 0) return; Rectangle rectTabStrip = TabStripRectangle; rectTabStrip.Height += 1; // Draw the tabs Rectangle rectTabOnly = TabsRectangle; Rectangle rectTab = Rectangle.Empty; TabVS2013Light tabActive = null; g.SetClip(DrawHelper.RtlTransform(this, rectTabOnly)); for (int i = 0; i < count; i++) { rectTab = GetTabRectangle(i); if (Tabs[i].Content == DockPane.ActiveContent) { tabActive = Tabs[i] as TabVS2013Light; continue; } if (rectTab.IntersectsWith(rectTabOnly)) DrawTab(g, Tabs[i] as TabVS2013Light, rectTab); } g.SetClip(rectTabStrip); if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) g.DrawLine(PenDocumentTabActiveBorder, rectTabStrip.Left, rectTabStrip.Top + 1, rectTabStrip.Right, rectTabStrip.Top + 1); else { Color tabUnderLineColor; if (tabActive != null && DockPane.IsActiveDocumentPane) tabUnderLineColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.StartColor; else tabUnderLineColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.EndColor; g.DrawLine(new Pen(tabUnderLineColor, 4), rectTabStrip.Left, rectTabStrip.Bottom, rectTabStrip.Right, rectTabStrip.Bottom); } g.SetClip(DrawHelper.RtlTransform(this, rectTabOnly)); if (tabActive != null) { rectTab = GetTabRectangle(Tabs.IndexOf(tabActive)); if (rectTab.IntersectsWith(rectTabOnly)) { rectTab.Intersect(rectTabOnly); DrawTab(g, tabActive, rectTab); } } } private void DrawTabStrip_ToolWindow(Graphics g) { Rectangle rectTabStrip = TabStripRectangle; g.DrawLine(PenToolWindowTabBorder, rectTabStrip.Left, rectTabStrip.Top, rectTabStrip.Right, rectTabStrip.Top); for (int i = 0; i < Tabs.Count; i++) DrawTab(g, Tabs[i] as TabVS2013Light, GetTabRectangle(i)); } private Rectangle GetTabRectangle(int index) { if (Appearance == DockPane.AppearanceStyle.ToolWindow) return GetTabRectangle_ToolWindow(index); else return GetTabRectangle_Document(index); } private Rectangle GetTabRectangle_ToolWindow(int index) { Rectangle rectTabStrip = TabStripRectangle; TabVS2013Light tab = (TabVS2013Light)(Tabs[index]); return new Rectangle(tab.TabX, rectTabStrip.Y, tab.TabWidth, rectTabStrip.Height); } private Rectangle GetTabRectangle_Document(int index) { Rectangle rectTabStrip = TabStripRectangle; var tab = (TabVS2013Light)Tabs[index]; Rectangle rect = new Rectangle(); rect.X = tab.TabX; rect.Width = tab.TabWidth; rect.Height = rectTabStrip.Height - DocumentTabGapTop; if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) rect.Y = rectTabStrip.Y + DocumentStripGapBottom; else rect.Y = rectTabStrip.Y + DocumentTabGapTop; return rect; } private void DrawTab(Graphics g, TabVS2013Light tab, Rectangle rect) { if (Appearance == DockPane.AppearanceStyle.ToolWindow) DrawTab_ToolWindow(g, tab, rect); else DrawTab_Document(g, tab, rect); } private GraphicsPath GetTabOutline(Tab tab, bool rtlTransform, bool toScreen) { if (Appearance == DockPane.AppearanceStyle.ToolWindow) return GetTabOutline_ToolWindow(tab, rtlTransform, toScreen); else return GetTabOutline_Document(tab, rtlTransform, toScreen, false); } private GraphicsPath GetTabOutline_ToolWindow(Tab tab, bool rtlTransform, bool toScreen) { Rectangle rect = GetTabRectangle(Tabs.IndexOf(tab)); if (rtlTransform) rect = DrawHelper.RtlTransform(this, rect); if (toScreen) rect = RectangleToScreen(rect); DrawHelper.GetRoundedCornerTab(GraphicsPath, rect, false); return GraphicsPath; } private GraphicsPath GetTabOutline_Document(Tab tab, bool rtlTransform, bool toScreen, bool full) { GraphicsPath.Reset(); Rectangle rect = GetTabRectangle(Tabs.IndexOf(tab)); // Shorten TabOutline so it doesn't get overdrawn by icons next to it rect.Intersect(TabsRectangle); rect.Width--; if (rtlTransform) rect = DrawHelper.RtlTransform(this, rect); if (toScreen) rect = RectangleToScreen(rect); GraphicsPath.AddRectangle(rect); return GraphicsPath; } private void DrawTab_ToolWindow(Graphics g, TabVS2013Light tab, Rectangle rect) { rect.Y += 1; Rectangle rectIcon = new Rectangle( rect.X + ToolWindowImageGapLeft, rect.Y - 1 + rect.Height - ToolWindowImageGapBottom - ToolWindowImageHeight, ToolWindowImageWidth, ToolWindowImageHeight); Rectangle rectText = rectIcon; rectText.X += rectIcon.Width + ToolWindowImageGapRight; rectText.Width = rect.Width - rectIcon.Width - ToolWindowImageGapLeft - ToolWindowImageGapRight - ToolWindowTextGapRight; Rectangle rectTab = DrawHelper.RtlTransform(this, rect); rectText = DrawHelper.RtlTransform(this, rectText); rectIcon = DrawHelper.RtlTransform(this, rectIcon); if (DockPane.ActiveContent == tab.Content && ((DockContent)tab.Content).IsActivated) { Color startColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.StartColor; Color endColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.EndColor; LinearGradientMode gradientMode = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.LinearGradientMode; g.FillRectangle(new LinearGradientBrush(rectTab, startColor, endColor, gradientMode), rect); Color textColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.TextColor; TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, textColor, ToolWindowTextFormat); } else { Color textColor; if (tab.Content == DockPane.MouseOverTab) textColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.HoverTabGradient.TextColor; else textColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveTabGradient.TextColor; TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, textColor, ToolWindowTextFormat); } g.DrawLine(PenToolWindowTabBorder, rect.X + rect.Width - 1, rect.Y, rect.X + rect.Width - 1, rect.Height); if (rectTab.Contains(rectIcon)) g.DrawIcon(tab.Content.DockHandler.Icon, rectIcon); } private void DrawTab_Document(Graphics g, TabVS2013Light tab, Rectangle rect) { if (tab.TabWidth == 0) return; var rectCloseButton = GetCloseButtonRect(rect); Rectangle rectIcon = new Rectangle( rect.X + DocumentIconGapLeft, rect.Y + rect.Height - DocumentIconGapBottom - DocumentIconHeight, DocumentIconWidth, DocumentIconHeight); Rectangle rectText = rectIcon; if (DockPane.DockPanel.ShowDocumentIcon) { rectText.X += rectIcon.Width + DocumentIconGapRight; rectText.Y = rect.Y; rectText.Width = rect.Width - rectIcon.Width - DocumentIconGapLeft - DocumentIconGapRight - DocumentTextGapRight - rectCloseButton.Width; rectText.Height = rect.Height; } else rectText.Width = rect.Width - DocumentIconGapLeft - DocumentTextGapRight - rectCloseButton.Width; Rectangle rectTab = DrawHelper.RtlTransform(this, rect); Rectangle rectBack = DrawHelper.RtlTransform(this, rect); rectBack.Width += rect.X; rectBack.X = 0; rectText = DrawHelper.RtlTransform(this, rectText); rectIcon = DrawHelper.RtlTransform(this, rectIcon); Color activeColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.StartColor; Color lostFocusColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.EndColor; Color inactiveColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.StartColor; Color mouseHoverColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.HoverTabGradient.EndColor; Color activeText = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.TextColor; Color inactiveText = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.TextColor; Color lostFocusText = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.TextColor; Color mouseHoverText = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.HoverTabGradient.TextColor; if (DockPane.ActiveContent == tab.Content) { if (DockPane.IsActiveDocumentPane) { g.FillRectangle(new SolidBrush(activeColor), rect); TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, activeText, DocumentTextFormat); g.DrawImage(rectCloseButton == ActiveClose ? Resources.ActiveTabHover_Close : Resources.ActiveTab_Close, rectCloseButton); } else { g.FillRectangle(new SolidBrush(lostFocusColor), rect); TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, lostFocusText, DocumentTextFormat); g.DrawImage(rectCloseButton == ActiveClose ? Resources.ActiveTabHover_Close : Resources.LostFocusTab_Close, rectCloseButton); } } else { if (tab.Content == DockPane.MouseOverTab) { g.FillRectangle(new SolidBrush(mouseHoverColor), rect); TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, mouseHoverText, DocumentTextFormat); g.DrawImage(Resources.ActiveTabHover_Close, rectCloseButton); } else { g.FillRectangle(new SolidBrush(inactiveColor), rect); TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, inactiveText, DocumentTextFormat); } } if (rectTab.Contains(rectIcon) && DockPane.DockPanel.ShowDocumentIcon) g.DrawIcon(tab.Content.DockHandler.Icon, rectIcon); } protected override void OnMouseClick(MouseEventArgs e) { base.OnMouseClick(e); if (e.Button != MouseButtons.Left || Appearance != DockPane.AppearanceStyle.Document) return; var indexHit = HitTest(); if (indexHit > -1) TabCloseButtonHit(indexHit); } private void TabCloseButtonHit(int index) { var mousePos = PointToClient(MousePosition); var tabRect = GetTabRectangle(index); var closeButtonRect = GetCloseButtonRect(tabRect); var mouseRect = new Rectangle(mousePos, new Size(1, 1)); if (closeButtonRect.IntersectsWith(mouseRect)) DockPane.CloseActiveContent(); } private Rectangle GetCloseButtonRect(Rectangle rectTab) { if (Appearance != Docking.DockPane.AppearanceStyle.Document) { return Rectangle.Empty; } const int gap = 3; const int imageSize = 15; return new Rectangle(rectTab.X + rectTab.Width - imageSize - gap, rectTab.Y + gap, imageSize, imageSize); } private void WindowList_Click(object sender, EventArgs e) { SelectMenu.Items.Clear(); foreach (TabVS2013Light tab in Tabs) { IDockContent content = tab.Content; ToolStripItem item = SelectMenu.Items.Add(content.DockHandler.TabText, content.DockHandler.Icon.ToBitmap()); item.Tag = tab.Content; item.Click += new EventHandler(ContextMenuItem_Click); } var workingArea = Screen.GetWorkingArea(ButtonWindowList.PointToScreen(new Point(ButtonWindowList.Width / 2, ButtonWindowList.Height / 2))); var menu = new Rectangle(ButtonWindowList.PointToScreen(new Point(0, ButtonWindowList.Location.Y + ButtonWindowList.Height)), SelectMenu.Size); var menuMargined = new Rectangle(menu.X - SelectMenuMargin, menu.Y - SelectMenuMargin, menu.Width + SelectMenuMargin, menu.Height + SelectMenuMargin); if (workingArea.Contains(menuMargined)) { SelectMenu.Show(menu.Location); } else { var newPoint = menu.Location; newPoint.X = DrawHelper.Balance(SelectMenu.Width, SelectMenuMargin, newPoint.X, workingArea.Left, workingArea.Right); newPoint.Y = DrawHelper.Balance(SelectMenu.Size.Height, SelectMenuMargin, newPoint.Y, workingArea.Top, workingArea.Bottom); var button = ButtonWindowList.PointToScreen(new Point(0, ButtonWindowList.Height)); if (newPoint.Y < button.Y) { // flip the menu up to be above the button. newPoint.Y = button.Y - ButtonWindowList.Height; SelectMenu.Show(newPoint, ToolStripDropDownDirection.AboveRight); } else { SelectMenu.Show(newPoint); } } } private void ContextMenuItem_Click(object sender, EventArgs e) { ToolStripMenuItem item = sender as ToolStripMenuItem; if (item != null) { IDockContent content = (IDockContent)item.Tag; DockPane.ActiveContent = content; } } private void SetInertButtons() { if (Appearance == DockPane.AppearanceStyle.ToolWindow) { if (m_buttonClose != null) m_buttonClose.Left = -m_buttonClose.Width; if (m_buttonWindowList != null) m_buttonWindowList.Left = -m_buttonWindowList.Width; } else { ButtonClose.Enabled = false; m_closeButtonVisible = false; ButtonClose.Visible = m_closeButtonVisible; ButtonClose.RefreshChanges(); ButtonWindowList.RefreshChanges(); } } protected override void OnLayout(LayoutEventArgs levent) { if (Appearance == DockPane.AppearanceStyle.Document) { LayoutButtons(); OnRefreshChanges(); } base.OnLayout(levent); } private void LayoutButtons() { Rectangle rectTabStrip = TabStripRectangle; // Set position and size of the buttons int buttonWidth = ButtonClose.Image.Width; int buttonHeight = ButtonClose.Image.Height; int height = rectTabStrip.Height - DocumentButtonGapTop - DocumentButtonGapBottom; if (buttonHeight < height) { buttonWidth = buttonWidth * (height / buttonHeight); buttonHeight = height; } Size buttonSize = new Size(buttonWidth, buttonHeight); int x = rectTabStrip.X + rectTabStrip.Width - DocumentTabGapLeft - DocumentButtonGapRight - buttonWidth; int y = rectTabStrip.Y + DocumentButtonGapTop; Point point = new Point(x, y); ButtonClose.Bounds = DrawHelper.RtlTransform(this, new Rectangle(point, buttonSize)); // If the close button is not visible draw the window list button overtop. // Otherwise it is drawn to the left of the close button. if (m_closeButtonVisible) point.Offset(-(DocumentButtonGapBetween + buttonWidth), 0); ButtonWindowList.Bounds = DrawHelper.RtlTransform(this, new Rectangle(point, buttonSize)); } private void Close_Click(object sender, EventArgs e) { DockPane.CloseActiveContent(); } protected override int HitTest(Point ptMouse) { if (!TabsRectangle.Contains(ptMouse)) return -1; foreach (Tab tab in Tabs) { GraphicsPath path = GetTabOutline(tab, true, false); if (path.IsVisible(ptMouse)) return Tabs.IndexOf(tab); } return -1; } protected override Rectangle GetTabBounds(Tab tab) { GraphicsPath path = GetTabOutline(tab, true, false); RectangleF rectangle = path.GetBounds(); return new Rectangle((int)rectangle.Left, (int)rectangle.Top, (int)rectangle.Width, (int)rectangle.Height); } private Rectangle ActiveClose { get { return _activeClose; } } private bool SetActiveClose(Rectangle rectangle) { if (_activeClose == rectangle) return false; _activeClose = rectangle; return true; } private bool SetMouseOverTab(IDockContent content) { if (DockPane.MouseOverTab == content) return false; DockPane.MouseOverTab = content; return true; } protected override void OnMouseHover(EventArgs e) { int index = HitTest(PointToClient(MousePosition)); string toolTip = string.Empty; base.OnMouseHover(e); bool tabUpdate = false; bool buttonUpdate = false; if (index != -1) { var tab = Tabs[index] as TabVS2013Light; if (Appearance == DockPane.AppearanceStyle.ToolWindow || Appearance == DockPane.AppearanceStyle.Document) { tabUpdate = SetMouseOverTab(tab.Content == DockPane.ActiveContent ? null : tab.Content); } if (!String.IsNullOrEmpty(tab.Content.DockHandler.ToolTipText)) toolTip = tab.Content.DockHandler.ToolTipText; else if (tab.MaxWidth > tab.TabWidth) toolTip = tab.Content.DockHandler.TabText; var mousePos = PointToClient(MousePosition); var tabRect = GetTabRectangle(index); var closeButtonRect = GetCloseButtonRect(tabRect); var mouseRect = new Rectangle(mousePos, new Size(1, 1)); buttonUpdate = SetActiveClose(closeButtonRect.IntersectsWith(mouseRect) ? closeButtonRect : Rectangle.Empty); } else { tabUpdate = SetMouseOverTab(null); buttonUpdate = SetActiveClose(Rectangle.Empty); } if (tabUpdate || buttonUpdate) Invalidate(); if (m_toolTip.GetToolTip(this) != toolTip) { m_toolTip.Active = false; m_toolTip.SetToolTip(this, toolTip); m_toolTip.Active = true; } // requires further tracking of mouse hover behavior, ResetMouseEventArgs(); } protected override void OnMouseLeave(EventArgs e) { var tabUpdate = SetMouseOverTab(null); var buttonUpdate = SetActiveClose(Rectangle.Empty); if (tabUpdate || buttonUpdate) Invalidate(); base.OnMouseLeave(e); } protected override void OnRightToLeftChanged(EventArgs e) { base.OnRightToLeftChanged(e); PerformLayout(); } } }
// 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.Data.Common; using System.Data.ProviderBase; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace System.Data.OleDb { public sealed class OleDbTransaction : DbTransaction { private readonly OleDbTransaction _parentTransaction; // strong reference to keep parent alive private readonly System.Data.IsolationLevel _isolationLevel; private WeakReference _nestedTransaction; // child transactions private WrappedTransaction _transaction; internal OleDbConnection _parentConnection; private sealed class WrappedTransaction : WrappedIUnknown { private bool _mustComplete; internal WrappedTransaction(UnsafeNativeMethods.ITransactionLocal transaction, int isolevel, out OleDbHResult hr) : base(transaction) { int transactionLevel = 0; RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { hr = transaction.StartTransaction(isolevel, 0, IntPtr.Zero, out transactionLevel); if (0 <= hr) { _mustComplete = true; } } } internal bool MustComplete { get { return _mustComplete; } } internal OleDbHResult Abort() { Debug.Assert(_mustComplete, "transaction already completed"); OleDbHResult hr; bool mustRelease = false; RuntimeHelpers.PrepareConstrainedRegions(); try { DangerousAddRef(ref mustRelease); RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { hr = (OleDbHResult)NativeOledbWrapper.ITransactionAbort(DangerousGetHandle()); _mustComplete = false; } } finally { if (mustRelease) { DangerousRelease(); } } return hr; } internal OleDbHResult Commit() { Debug.Assert(_mustComplete, "transaction already completed"); OleDbHResult hr; bool mustRelease = false; RuntimeHelpers.PrepareConstrainedRegions(); try { DangerousAddRef(ref mustRelease); RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { hr = (OleDbHResult)NativeOledbWrapper.ITransactionCommit(DangerousGetHandle()); if ((0 <= (int)hr) || (OleDbHResult.XACT_E_NOTRANSACTION == hr)) { _mustComplete = false; } } } finally { if (mustRelease) { DangerousRelease(); } } return hr; } override protected bool ReleaseHandle() { if (_mustComplete && (IntPtr.Zero != base.handle)) { OleDbHResult hr = (OleDbHResult)NativeOledbWrapper.ITransactionAbort(base.handle); _mustComplete = false; } return base.ReleaseHandle(); } } internal OleDbTransaction(OleDbConnection connection, OleDbTransaction transaction, IsolationLevel isolevel) { _parentConnection = connection; _parentTransaction = transaction; switch (isolevel) { case IsolationLevel.Unspecified: // OLE DB doesn't support this isolevel on local transactions isolevel = IsolationLevel.ReadCommitted; break; case IsolationLevel.Chaos: case IsolationLevel.ReadUncommitted: case IsolationLevel.ReadCommitted: case IsolationLevel.RepeatableRead: case IsolationLevel.Serializable: case IsolationLevel.Snapshot: break; default: throw ADP.InvalidIsolationLevel(isolevel); } _isolationLevel = isolevel; } new public OleDbConnection Connection { get { return _parentConnection; } } override protected DbConnection DbConnection { get { return Connection; } } override public IsolationLevel IsolationLevel { get { if (null == _transaction) { throw ADP.TransactionZombied(this); } return _isolationLevel; } } internal OleDbTransaction Parent { get { return _parentTransaction; } } public OleDbTransaction Begin(IsolationLevel isolevel) { if (null == _transaction) { throw ADP.TransactionZombied(this); } else if ((null != _nestedTransaction) && _nestedTransaction.IsAlive) { throw ADP.ParallelTransactionsNotSupported(Connection); } // either the connection will be open or this will be a zombie OleDbTransaction transaction = new OleDbTransaction(_parentConnection, this, isolevel); _nestedTransaction = new WeakReference(transaction, false); UnsafeNativeMethods.ITransactionLocal wrapper = null; try { wrapper = (UnsafeNativeMethods.ITransactionLocal)_transaction.ComWrapper(); transaction.BeginInternal(wrapper); } finally { if (null != wrapper) { Marshal.ReleaseComObject(wrapper); } } return transaction; } public OleDbTransaction Begin() { return Begin(IsolationLevel.ReadCommitted); } internal void BeginInternal(UnsafeNativeMethods.ITransactionLocal transaction) { OleDbHResult hr; _transaction = new WrappedTransaction(transaction, (int)_isolationLevel, out hr); if (hr < 0) { _transaction.Dispose(); _transaction = null; ProcessResults(hr); } } override public void Commit() { if (null == _transaction) { throw ADP.TransactionZombied(this); } CommitInternal(); } private void CommitInternal() { if (null == _transaction) { return; } if (null != _nestedTransaction) { OleDbTransaction transaction = (OleDbTransaction)_nestedTransaction.Target; if ((null != transaction) && _nestedTransaction.IsAlive) { transaction.CommitInternal(); } _nestedTransaction = null; } OleDbHResult hr = _transaction.Commit(); if (!_transaction.MustComplete) { _transaction.Dispose(); _transaction = null; DisposeManaged(); } if (hr < 0) { // if an exception is thrown, user can try to commit their transaction again ProcessResults(hr); } } /*public OleDbCommand CreateCommand() { OleDbCommand cmd = Connection.CreateCommand(); cmd.Transaction = this; return cmd; } IDbCommand IDbTransaction.CreateCommand() { return CreateCommand(); }*/ protected override void Dispose(bool disposing) { if (disposing) { DisposeManaged(); RollbackInternal(false); } base.Dispose(disposing); } private void DisposeManaged() { if (null != _parentTransaction) { _parentTransaction._nestedTransaction = null; //_parentTransaction = null; } else if (null != _parentConnection) { _parentConnection.LocalTransaction = null; } _parentConnection = null; } private void ProcessResults(OleDbHResult hr) { Exception e = OleDbConnection.ProcessResults(hr, _parentConnection, this); if (null != e) { throw e; } } override public void Rollback() { if (null == _transaction) { throw ADP.TransactionZombied(this); } DisposeManaged(); RollbackInternal(true); // no recover if this throws an exception } /*protected virtual*/ internal OleDbHResult RollbackInternal(bool exceptionHandling) { OleDbHResult hr = 0; if (null != _transaction) { if (null != _nestedTransaction) { OleDbTransaction transaction = (OleDbTransaction)_nestedTransaction.Target; if ((null != transaction) && _nestedTransaction.IsAlive) { hr = transaction.RollbackInternal(exceptionHandling); if (exceptionHandling && (hr < 0)) { SafeNativeMethods.Wrapper.ClearErrorInfo(); return hr; } } _nestedTransaction = null; } hr = _transaction.Abort(); _transaction.Dispose(); _transaction = null; if (hr < 0) { if (exceptionHandling) { ProcessResults(hr); } else { SafeNativeMethods.Wrapper.ClearErrorInfo(); } } } return hr; } static internal OleDbTransaction TransactionLast(OleDbTransaction head) { if (null != head._nestedTransaction) { OleDbTransaction current = (OleDbTransaction)head._nestedTransaction.Target; if ((null != current) && head._nestedTransaction.IsAlive) { return TransactionLast(current); } } return head; } static internal OleDbTransaction TransactionUpdate(OleDbTransaction transaction) { if ((null != transaction) && (null == transaction._transaction)) { return null; } return transaction; } } }
#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; using System.Collections.Generic; using System.Globalization; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Serialization; using Newtonsoft.Json.Tests.TestObjects; using Newtonsoft.Json.Utilities; #if !NETFX_CORE using NUnit.Framework; #else using Microsoft.VisualStudio.TestPlatform.UnitTestFramework; using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute; using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute; #endif using Newtonsoft.Json.Schema; using System.IO; using Newtonsoft.Json.Linq; using System.Text; using Extensions = Newtonsoft.Json.Schema.Extensions; #if NET20 using Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; #endif namespace Newtonsoft.Json.Tests.Schema { [TestFixture] public class JsonSchemaGeneratorTests : TestFixtureBase { [Test] public void Generate_GenericDictionary() { JsonSchemaGenerator generator = new JsonSchemaGenerator(); JsonSchema schema = generator.Generate(typeof(Dictionary<string, List<string>>)); string json = schema.ToString(); Assert.AreEqual(@"{ ""type"": ""object"", ""additionalProperties"": { ""type"": [ ""array"", ""null"" ], ""items"": { ""type"": [ ""string"", ""null"" ] } } }", json); Dictionary<string, List<string>> value = new Dictionary<string, List<string>> { { "HasValue", new List<string>() { "first", "second", null } }, { "NoValue", null } }; string valueJson = JsonConvert.SerializeObject(value, Formatting.Indented); JObject o = JObject.Parse(valueJson); Assert.IsTrue(o.IsValid(schema)); } #if !(NETFX_CORE || PORTABLE || PORTABLE40) [Test] public void Generate_DefaultValueAttributeTestClass() { JsonSchemaGenerator generator = new JsonSchemaGenerator(); JsonSchema schema = generator.Generate(typeof(DefaultValueAttributeTestClass)); string json = schema.ToString(); Assert.AreEqual(@"{ ""description"": ""DefaultValueAttributeTestClass description!"", ""type"": ""object"", ""additionalProperties"": false, ""properties"": { ""TestField1"": { ""required"": true, ""type"": ""integer"", ""default"": 21 }, ""TestProperty1"": { ""required"": true, ""type"": [ ""string"", ""null"" ], ""default"": ""TestProperty1Value"" } } }", json); } #endif [Test] public void Generate_Person() { JsonSchemaGenerator generator = new JsonSchemaGenerator(); JsonSchema schema = generator.Generate(typeof(Person)); string json = schema.ToString(); Assert.AreEqual(@"{ ""id"": ""Person"", ""title"": ""Title!"", ""description"": ""JsonObjectAttribute description!"", ""type"": ""object"", ""properties"": { ""Name"": { ""required"": true, ""type"": [ ""string"", ""null"" ] }, ""BirthDate"": { ""required"": true, ""type"": ""string"" }, ""LastModified"": { ""required"": true, ""type"": ""string"" } } }", json); } [Test] public void Generate_UserNullable() { JsonSchemaGenerator generator = new JsonSchemaGenerator(); JsonSchema schema = generator.Generate(typeof(UserNullable)); string json = schema.ToString(); Assert.AreEqual(@"{ ""type"": ""object"", ""properties"": { ""Id"": { ""required"": true, ""type"": ""string"" }, ""FName"": { ""required"": true, ""type"": [ ""string"", ""null"" ] }, ""LName"": { ""required"": true, ""type"": [ ""string"", ""null"" ] }, ""RoleId"": { ""required"": true, ""type"": ""integer"" }, ""NullableRoleId"": { ""required"": true, ""type"": [ ""integer"", ""null"" ] }, ""NullRoleId"": { ""required"": true, ""type"": [ ""integer"", ""null"" ] }, ""Active"": { ""required"": true, ""type"": [ ""boolean"", ""null"" ] } } }", json); } [Test] public void Generate_RequiredMembersClass() { JsonSchemaGenerator generator = new JsonSchemaGenerator(); JsonSchema schema = generator.Generate(typeof(RequiredMembersClass)); Assert.AreEqual(JsonSchemaType.String, schema.Properties["FirstName"].Type); Assert.AreEqual(JsonSchemaType.String | JsonSchemaType.Null, schema.Properties["MiddleName"].Type); Assert.AreEqual(JsonSchemaType.String | JsonSchemaType.Null, schema.Properties["LastName"].Type); Assert.AreEqual(JsonSchemaType.String, schema.Properties["BirthDate"].Type); } [Test] public void Generate_Store() { JsonSchemaGenerator generator = new JsonSchemaGenerator(); JsonSchema schema = generator.Generate(typeof(Store)); Assert.AreEqual(11, schema.Properties.Count); JsonSchema productArraySchema = schema.Properties["product"]; JsonSchema productSchema = productArraySchema.Items[0]; Assert.AreEqual(4, productSchema.Properties.Count); } [Test] public void MissingSchemaIdHandlingTest() { JsonSchemaGenerator generator = new JsonSchemaGenerator(); JsonSchema schema = generator.Generate(typeof(Store)); Assert.AreEqual(null, schema.Id); generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName; schema = generator.Generate(typeof(Store)); Assert.AreEqual(typeof(Store).FullName, schema.Id); generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseAssemblyQualifiedName; schema = generator.Generate(typeof(Store)); Assert.AreEqual(typeof(Store).AssemblyQualifiedName, schema.Id); } [Test] public void CircularReferenceError() { ExceptionAssert.Throws<Exception>(@"Unresolved circular reference for type 'Newtonsoft.Json.Tests.TestObjects.CircularReferenceClass'. Explicitly define an Id for the type using a JsonObject/JsonArray attribute or automatically generate a type Id using the UndefinedSchemaIdHandling property.", () => { JsonSchemaGenerator generator = new JsonSchemaGenerator(); generator.Generate(typeof(CircularReferenceClass)); }); } [Test] public void CircularReferenceWithTypeNameId() { JsonSchemaGenerator generator = new JsonSchemaGenerator(); generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName; JsonSchema schema = generator.Generate(typeof(CircularReferenceClass), true); Assert.AreEqual(JsonSchemaType.String, schema.Properties["Name"].Type); Assert.AreEqual(typeof(CircularReferenceClass).FullName, schema.Id); Assert.AreEqual(JsonSchemaType.Object | JsonSchemaType.Null, schema.Properties["Child"].Type); Assert.AreEqual(schema, schema.Properties["Child"]); } [Test] public void CircularReferenceWithExplicitId() { JsonSchemaGenerator generator = new JsonSchemaGenerator(); JsonSchema schema = generator.Generate(typeof(CircularReferenceWithIdClass)); Assert.AreEqual(JsonSchemaType.String | JsonSchemaType.Null, schema.Properties["Name"].Type); Assert.AreEqual("MyExplicitId", schema.Id); Assert.AreEqual(JsonSchemaType.Object | JsonSchemaType.Null, schema.Properties["Child"].Type); Assert.AreEqual(schema, schema.Properties["Child"]); } [Test] public void GenerateSchemaForType() { JsonSchemaGenerator generator = new JsonSchemaGenerator(); generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName; JsonSchema schema = generator.Generate(typeof(Type)); Assert.AreEqual(JsonSchemaType.String, schema.Type); string json = JsonConvert.SerializeObject(typeof(Version), Formatting.Indented); JValue v = new JValue(json); Assert.IsTrue(v.IsValid(schema)); } #if !(NETFX_CORE || PORTABLE || PORTABLE40) [Test] public void GenerateSchemaForISerializable() { JsonSchemaGenerator generator = new JsonSchemaGenerator(); generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName; JsonSchema schema = generator.Generate(typeof(Exception)); Assert.AreEqual(JsonSchemaType.Object, schema.Type); Assert.AreEqual(true, schema.AllowAdditionalProperties); Assert.AreEqual(null, schema.Properties); } #endif #if !(NETFX_CORE || PORTABLE || PORTABLE40) [Test] public void GenerateSchemaForDBNull() { JsonSchemaGenerator generator = new JsonSchemaGenerator(); generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName; JsonSchema schema = generator.Generate(typeof(DBNull)); Assert.AreEqual(JsonSchemaType.Null, schema.Type); } public class CustomDirectoryInfoMapper : DefaultContractResolver { public CustomDirectoryInfoMapper() : base(true) { } protected override JsonContract CreateContract(Type objectType) { if (objectType == typeof(DirectoryInfo)) return base.CreateObjectContract(objectType); return base.CreateContract(objectType); } protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization) { IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization); JsonPropertyCollection c = new JsonPropertyCollection(type); c.AddRange(properties.Where(m => m.PropertyName != "Root")); return c; } } [Test] public void GenerateSchemaForDirectoryInfo() { JsonSchemaGenerator generator = new JsonSchemaGenerator(); generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName; generator.ContractResolver = new CustomDirectoryInfoMapper { #if !(NETFX_CORE || PORTABLE) IgnoreSerializableAttribute = true #endif }; JsonSchema schema = generator.Generate(typeof(DirectoryInfo), true); string json = schema.ToString(); Assert.AreEqual(@"{ ""id"": ""System.IO.DirectoryInfo"", ""required"": true, ""type"": [ ""object"", ""null"" ], ""additionalProperties"": false, ""properties"": { ""Name"": { ""required"": true, ""type"": [ ""string"", ""null"" ] }, ""Parent"": { ""$ref"": ""System.IO.DirectoryInfo"" }, ""Exists"": { ""required"": true, ""type"": ""boolean"" }, ""FullName"": { ""required"": true, ""type"": [ ""string"", ""null"" ] }, ""Extension"": { ""required"": true, ""type"": [ ""string"", ""null"" ] }, ""CreationTime"": { ""required"": true, ""type"": ""string"" }, ""CreationTimeUtc"": { ""required"": true, ""type"": ""string"" }, ""LastAccessTime"": { ""required"": true, ""type"": ""string"" }, ""LastAccessTimeUtc"": { ""required"": true, ""type"": ""string"" }, ""LastWriteTime"": { ""required"": true, ""type"": ""string"" }, ""LastWriteTimeUtc"": { ""required"": true, ""type"": ""string"" }, ""Attributes"": { ""required"": true, ""type"": ""integer"" } } }", json); DirectoryInfo temp = new DirectoryInfo(@"c:\temp"); JTokenWriter jsonWriter = new JTokenWriter(); JsonSerializer serializer = new JsonSerializer(); serializer.Converters.Add(new IsoDateTimeConverter()); serializer.ContractResolver = new CustomDirectoryInfoMapper { #if !(NETFX_CORE || PORTABLE) IgnoreSerializableInterface = true #endif }; serializer.Serialize(jsonWriter, temp); List<string> errors = new List<string>(); jsonWriter.Token.Validate(schema, (sender, args) => errors.Add(args.Message)); Assert.AreEqual(0, errors.Count); } #endif [Test] public void GenerateSchemaCamelCase() { JsonSchemaGenerator generator = new JsonSchemaGenerator(); generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName; generator.ContractResolver = new CamelCasePropertyNamesContractResolver() { #if !(NETFX_CORE || PORTABLE || PORTABLE40) IgnoreSerializableAttribute = true #endif }; JsonSchema schema = generator.Generate(typeof(Version), true); string json = schema.ToString(); Assert.AreEqual(@"{ ""id"": ""System.Version"", ""type"": [ ""object"", ""null"" ], ""additionalProperties"": false, ""properties"": { ""major"": { ""required"": true, ""type"": ""integer"" }, ""minor"": { ""required"": true, ""type"": ""integer"" }, ""build"": { ""required"": true, ""type"": ""integer"" }, ""revision"": { ""required"": true, ""type"": ""integer"" }, ""majorRevision"": { ""required"": true, ""type"": ""integer"" }, ""minorRevision"": { ""required"": true, ""type"": ""integer"" } } }", json); } #if !(NETFX_CORE || PORTABLE || PORTABLE40) [Test] public void GenerateSchemaSerializable() { JsonSchemaGenerator generator = new JsonSchemaGenerator(); generator.ContractResolver = new DefaultContractResolver { IgnoreSerializableAttribute = false }; generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName; JsonSchema schema = generator.Generate(typeof(Version), true); string json = schema.ToString(); Assert.AreEqual(@"{ ""id"": ""System.Version"", ""type"": [ ""object"", ""null"" ], ""additionalProperties"": false, ""properties"": { ""_Major"": { ""required"": true, ""type"": ""integer"" }, ""_Minor"": { ""required"": true, ""type"": ""integer"" }, ""_Build"": { ""required"": true, ""type"": ""integer"" }, ""_Revision"": { ""required"": true, ""type"": ""integer"" } } }", json); JTokenWriter jsonWriter = new JTokenWriter(); JsonSerializer serializer = new JsonSerializer(); serializer.ContractResolver = new DefaultContractResolver { IgnoreSerializableAttribute = false }; serializer.Serialize(jsonWriter, new Version(1, 2, 3, 4)); List<string> errors = new List<string>(); jsonWriter.Token.Validate(schema, (sender, args) => errors.Add(args.Message)); Assert.AreEqual(0, errors.Count); Assert.AreEqual(@"{ ""_Major"": 1, ""_Minor"": 2, ""_Build"": 3, ""_Revision"": 4 }", jsonWriter.Token.ToString()); Version version = jsonWriter.Token.ToObject<Version>(serializer); Assert.AreEqual(1, version.Major); Assert.AreEqual(2, version.Minor); Assert.AreEqual(3, version.Build); Assert.AreEqual(4, version.Revision); } #endif public enum SortTypeFlag { No = 0, Asc = 1, Desc = -1 } public class X { public SortTypeFlag x; } [Test] public void GenerateSchemaWithNegativeEnum() { JsonSchemaGenerator jsonSchemaGenerator = new JsonSchemaGenerator(); JsonSchema schema = jsonSchemaGenerator.Generate(typeof(X)); string json = schema.ToString(); Assert.AreEqual(@"{ ""type"": ""object"", ""properties"": { ""x"": { ""required"": true, ""type"": ""integer"", ""enum"": [ 0, 1, -1 ] } } }", json); } [Test] public void CircularCollectionReferences() { Type type = typeof(Workspace); JsonSchemaGenerator jsonSchemaGenerator = new JsonSchemaGenerator(); jsonSchemaGenerator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName; JsonSchema jsonSchema = jsonSchemaGenerator.Generate(type); // should succeed Assert.IsNotNull(jsonSchema); } [Test] public void CircularReferenceWithMixedRequires() { JsonSchemaGenerator jsonSchemaGenerator = new JsonSchemaGenerator(); jsonSchemaGenerator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName; JsonSchema jsonSchema = jsonSchemaGenerator.Generate(typeof(CircularReferenceClass)); string json = jsonSchema.ToString(); Assert.AreEqual(@"{ ""id"": ""Newtonsoft.Json.Tests.TestObjects.CircularReferenceClass"", ""type"": [ ""object"", ""null"" ], ""properties"": { ""Name"": { ""required"": true, ""type"": ""string"" }, ""Child"": { ""$ref"": ""Newtonsoft.Json.Tests.TestObjects.CircularReferenceClass"" } } }", json); } [Test] public void JsonPropertyWithHandlingValues() { JsonSchemaGenerator jsonSchemaGenerator = new JsonSchemaGenerator(); jsonSchemaGenerator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName; JsonSchema jsonSchema = jsonSchemaGenerator.Generate(typeof(JsonPropertyWithHandlingValues)); string json = jsonSchema.ToString(); Assert.AreEqual(@"{ ""id"": ""Newtonsoft.Json.Tests.TestObjects.JsonPropertyWithHandlingValues"", ""required"": true, ""type"": [ ""object"", ""null"" ], ""properties"": { ""DefaultValueHandlingIgnoreProperty"": { ""type"": [ ""string"", ""null"" ], ""default"": ""Default!"" }, ""DefaultValueHandlingIncludeProperty"": { ""required"": true, ""type"": [ ""string"", ""null"" ], ""default"": ""Default!"" }, ""DefaultValueHandlingPopulateProperty"": { ""required"": true, ""type"": [ ""string"", ""null"" ], ""default"": ""Default!"" }, ""DefaultValueHandlingIgnoreAndPopulateProperty"": { ""type"": [ ""string"", ""null"" ], ""default"": ""Default!"" }, ""NullValueHandlingIgnoreProperty"": { ""type"": [ ""string"", ""null"" ] }, ""NullValueHandlingIncludeProperty"": { ""required"": true, ""type"": [ ""string"", ""null"" ] }, ""ReferenceLoopHandlingErrorProperty"": { ""$ref"": ""Newtonsoft.Json.Tests.TestObjects.JsonPropertyWithHandlingValues"" }, ""ReferenceLoopHandlingIgnoreProperty"": { ""$ref"": ""Newtonsoft.Json.Tests.TestObjects.JsonPropertyWithHandlingValues"" }, ""ReferenceLoopHandlingSerializeProperty"": { ""$ref"": ""Newtonsoft.Json.Tests.TestObjects.JsonPropertyWithHandlingValues"" } } }", json); } [Test] public void GenerateForNullableInt32() { JsonSchemaGenerator jsonSchemaGenerator = new JsonSchemaGenerator(); JsonSchema jsonSchema = jsonSchemaGenerator.Generate(typeof(NullableInt32TestClass)); string json = jsonSchema.ToString(); Assert.AreEqual(@"{ ""type"": ""object"", ""properties"": { ""Value"": { ""required"": true, ""type"": [ ""integer"", ""null"" ] } } }", json); } } public class NullableInt32TestClass { public int? Value { get; set; } } public class DMDSLBase { public String Comment; } public class Workspace : DMDSLBase { public ControlFlowItemCollection Jobs = new ControlFlowItemCollection(); } public class ControlFlowItemBase : DMDSLBase { public String Name; } public class ControlFlowItem : ControlFlowItemBase //A Job { public TaskCollection Tasks = new TaskCollection(); public ContainerCollection Containers = new ContainerCollection(); } public class ControlFlowItemCollection : List<ControlFlowItem> { } public class Task : ControlFlowItemBase { public DataFlowTaskCollection DataFlowTasks = new DataFlowTaskCollection(); public BulkInsertTaskCollection BulkInsertTask = new BulkInsertTaskCollection(); } public class TaskCollection : List<Task> { } public class Container : ControlFlowItemBase { public ControlFlowItemCollection ContainerJobs = new ControlFlowItemCollection(); } public class ContainerCollection : List<Container> { } public class DataFlowTask_DSL : ControlFlowItemBase { } public class DataFlowTaskCollection : List<DataFlowTask_DSL> { } public class SequenceContainer_DSL : Container { } public class BulkInsertTaskCollection : List<BulkInsertTask_DSL> { } public class BulkInsertTask_DSL { } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace HoundRace.Web.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using TestFirst.Net.Lang; using TestFirst.Net.Util; namespace TestFirst.Net.Performance { public class SimpleLoadRunner : PerformanceSuite.ILoadRunner { private readonly int m_numThreads; private readonly TimeSpan m_delayBetweenTests; private readonly double m_testDelayVariance; private readonly PerformanceSuite.ITestProvider m_testProvider; private readonly TimeSpan m_runFor; private readonly bool m_failOnError; private readonly ThreadPriority m_threadPriority; private readonly TimeSpan m_threadStartDelay; private readonly double m_threadStartDelayVariance; private DateTime m_endAt; private List<ActionCompleteThread> m_threads = new List<ActionCompleteThread>(); private SimpleLoadRunner(PerformanceSuite.ITestProvider testProvider, int numThreads, TimeSpan runFor, TimeSpan delayBetweenTests, bool failOnError, ThreadPriority threadPriority, TimeSpan threadStartDelay, double threadStartDelayVariance, double testDelayVariance) { m_testProvider = testProvider; m_numThreads = numThreads; m_delayBetweenTests = delayBetweenTests; m_failOnError = failOnError; m_threadPriority = threadPriority; m_threadStartDelay = threadStartDelay; m_threadStartDelayVariance = threadStartDelayVariance; m_testDelayVariance = testDelayVariance; m_runFor = runFor; } public static Builder With() { return new Builder(); } public void BeforeInvoke() { // throw new NotImplementedException(); } public void AfterInvoke() { // throw new NotImplementedException(); } public void Start(PerformanceSuite.PerfTestContext ctxt, IPerformanceTestRunnerListener runListener) { m_endAt = DateTime.Now.Add(m_runFor); m_threads.Clear(); m_threads = new List<ActionCompleteThread>(); for (var i = 01; i < m_numThreads; i++) { var threadListener = new TestListenerAdapter(runListener, ctxt); var threadAction = NewInvokeTestAction(threadListener); m_threads.Add(new ActionCompleteThread(threadAction.Invoke).Where(t => t.Priority = m_threadPriority)); } m_threads.ForEach(t => t.Start()); // wait for runners to complete while (DateTime.Now < m_endAt && m_threads.Any(t => !t.Completed)) { Thread.Sleep(1000); } m_threads.ForEach(t => t.Abort()); } public void Abort() { m_threads.ForEach(t => t.Abort()); } private Action NewInvokeTestAction(IPerformanceTestListener listener) { return () => { if (m_threadStartDelay.TotalMilliseconds > 0 && m_threadStartDelayVariance > 0) { var r = new System.Random(); // ensure some random variance in the start time of each thread var delayStart = r.NextDouble() * (m_threadStartDelayVariance * m_threadStartDelay.TotalMilliseconds); if (delayStart > 0) { Thread.Sleep((int)delayStart); } } while (DateTime.Now < m_endAt) { try { var testAction = m_testProvider.Next(); testAction.InvokeTest(listener); } catch (Exception e) { listener.OnError(e); if (m_failOnError) { throw; } } if (m_delayBetweenTests.TotalMilliseconds > 0) { if (m_testDelayVariance > 0) { var r = new System.Random(); // ensure some random variance in the delay between tests to smooth the load var delay = r.NextDouble() * (m_testDelayVariance * m_delayBetweenTests.TotalMilliseconds); if (delay > 0) { Thread.Sleep((int)delay); } } else { Thread.Sleep(m_delayBetweenTests); } } } }; } public class Builder : IBuilder<PerformanceSuite.ILoadRunner> { private int m_numThreads = 1; private TimeSpan m_delayBetweenThreads = TimeSpan.FromSeconds(1); private PerformanceSuite.ITestProvider m_testProvider; private TimeSpan? m_runFor; private bool m_failOnError = true; private ThreadPriority m_threadPriority = ThreadPriority.Normal; private TimeSpan m_startDelay = TimeSpan.FromSeconds(0); private double m_startDelayVariance; private double m_testDelayVariance; public PerformanceSuite.ILoadRunner Build() { PreConditions.AssertNotNull(m_testProvider, "TestProvider"); PreConditions.AssertTrue(m_numThreads > 0, "num threads must be > 0"); PreConditions.AssertNotNull(m_runFor, "expect time to run for"); PreConditions.AssertTrue(m_startDelayVariance >= 0 && m_startDelayVariance <= 1, "expect thread start delay variance to be between 0 and 1"); PreConditions.AssertTrue(m_testDelayVariance >= 0 && m_testDelayVariance <= 1, "expect test delay variance to be between 0 and 1"); return new SimpleLoadRunner( numThreads: m_numThreads, delayBetweenTests: m_delayBetweenThreads, testDelayVariance: m_testDelayVariance, runFor: m_runFor.GetValueOrDefault(), threadPriority: m_threadPriority, threadStartDelay: m_startDelay, threadStartDelayVariance: m_startDelayVariance, failOnError: m_failOnError, testProvider: m_testProvider); } public Builder NumThreads(int numThreads) { PreConditions.AssertTrue(numThreads > 0, "Num threads must be > 0 but was " + numThreads); m_numThreads = numThreads; return this; } public Builder RunFor(TimeSpan time) { m_runFor = time; return this; } public TimeSpanBuilder<Builder> StartDelay(double delay) { return new TimeSpanBuilder<Builder>(delay, StartDelay); } public Builder StartDelay(TimeSpan time) { m_startDelay = time; return this; } public Builder StartDelayVariance(double variance) { m_startDelayVariance = variance; return this; } public Builder Priority(ThreadPriority priority) { m_threadPriority = priority; return this; } public Builder FailOnError(bool b) { m_failOnError = b; return this; } public Builder Tests(params IPerformanceTest[] tests) { Tests(RoundRobbin.With().Tests(tests)); return this; } public Builder Tests(IBuilder<PerformanceSuite.ITestProvider> testProviderBuilder) { Tests(testProviderBuilder.Build()); return this; } public Builder Tests(PerformanceSuite.ITestProvider testProvider) { m_testProvider = testProvider; return this; } public TimeSpanBuilder<Builder> DelayBetweenTests(double delay) { return new TimeSpanBuilder<Builder>(delay, DelayBetweenTests); } public Builder DelayBetweenTests(TimeSpan delay) { m_delayBetweenThreads = delay; return this; } public Builder DelayBetweenTestsVariance(double variance) { m_testDelayVariance = variance; return this; } public TimeSpanBuilder<Builder> RunFor(double time) { return new TimeSpanBuilder<Builder>(time, RunFor); } } } }
// Copyright (C) 2014 Stephan Bouchard - All Rights Reserved // This code can only be used under the standard Unity Asset Store End User License Agreement // A Copy of the EULA APPENDIX 1 is available at http://unity3d.com/company/legal/as_terms using UnityEngine; using UnityEditor; using System.Threading; using System.IO; namespace TMPro.EditorUtilities { public static class TMPro_DistanceTransform { private static EventWaitHandle[] _WaitHandles; private static Color[] Output; private static System.Diagnostics.Stopwatch timer; private class Pixel { public float alpha; public float distance; public int dX, dY; public Vector2 gradient; } private static Pixel[] innerMask; private static Pixel[] outerMask; // Use this for initialization public static void Generate(Color[] Source, int width, int height, int Spread, int ScaleDownFactor) { // Setup Timer for debug purposes timer = new System.Diagnostics.Stopwatch(); timer.Start(); // Pixel Arrays which will contain the results of the distance transform of the Inner & Outer masks. innerMask = new Pixel[width * height]; outerMask = new Pixel[width * height]; // Event Handler for ThreadPool. _WaitHandles = new EventWaitHandle[] { new AutoResetEvent(false), new AutoResetEvent(false) }; // Calculate Distance Transform for Inner Mask ThreadPool.QueueUserWorkItem(InnerMask => { //System.TimeSpan timeStamp = timer.Elapsed; innerMask = Calculate3X3EDT(Source, 1, width, height, Spread); //Debug.Log("Inner Mask processed in [" + (timer.Elapsed - timeStamp) + "]"); _WaitHandles[0].Set(); }); // Calculate Distance Transform for Outer Mask ThreadPool.QueueUserWorkItem(OuterMask => { //System.TimeSpan timeStamp = timer.Elapsed; outerMask = Calculate3X3EDT(Source, 0, width, height, Spread); //Debug.Log("Outer Mask processed in [" + (timer.Elapsed - timeStamp) + "]"); _WaitHandles[1].Set(); }); WaitHandle.WaitAll(_WaitHandles); // Wait for both Threads to be completed. //Debug.Log("Inner & Outer Mask Processing Completed."); //string logfile = string.Empty; // The final Ouput passed back to the Font Editor Window Output = new Color[width / ScaleDownFactor * height / ScaleDownFactor]; // Store Resulting process of Inner and Outer Mask in Output and apply downscaling factor float scale = 1f / Spread; int s1 = ScaleDownFactor / 2; int ScaledDownWidth = width / ScaleDownFactor; //timeStamp = timer.Elapsed; for (int y = s1; y < height; y += ScaleDownFactor) { for (int x = s1; x < width; x += ScaleDownFactor) { int x1 = (x - s1) / ScaleDownFactor; int y1 = (y - s1) / ScaleDownFactor; float inner0 = Mathf.Clamp01(innerMask[x + y * width].distance * scale); float outer0 = Mathf.Clamp01(outerMask[x + y * width].distance * scale); //if (ScaleDownFactor > 1) //{ // float inner1 = Mathf.Clamp01(innerMask[(x - 1) + y * width].distance * scale); // float inner2 = Mathf.Clamp01(innerMask[x + (y - 1) * width].distance * scale); // float inner3 = Mathf.Clamp01(innerMask[(x - 1) + (y - 1) * width].distance * scale); // float outer1 = Mathf.Clamp01(outerMask[(x - 1) + y * width].distance * scale); // float outer2 = Mathf.Clamp01(outerMask[x + (y - 1) * width].distance * scale); // float outer3 = Mathf.Clamp01(outerMask[(x - 1) + (y - 1) * width].distance * scale); // inner0 = (inner0 + inner1 + inner2 + inner3) / 4; // outer0 = (outer0 + outer1 + outer2 + outer3) / 4; //} //if (ScaleDownFactor > 1) //{ // int dx0 = x; int dy0 = y; // // Find smallest Inner distance // float inner_dst = innerMask[x + y * width].distance; // // Check dst against (x - 1, y) // if (inner_dst > innerMask[(x - 1) + y * width].distance) // { // dx0 = x - 1; dy0 = y; // inner_dst = innerMask[(x - 1) + y * width].distance; // } // // Check dst against (x - 1, y - 1) // if (inner_dst > innerMask[(x - 1) + (y - 1) * width].distance) // { // dx0 = x - 1; dy0 = y - 1; // inner_dst = innerMask[(x - 1) + (y - 1) * width].distance; // } // // Check dst against (x, y - 1) // if (inner_dst > innerMask[x + (y - 1) * width].distance) // { // dx0 = x; dy0 = y - 1; // inner_dst = innerMask[x + (y - 1) * width].distance; // } // int dX = innerMask[dx0 + dy0 * width].dX; // int dY = innerMask[dx0 + dy0 * width].dY; // float delta = ApproximateEdgeDelta(dX, dY, innerMask[(x + dX) + (y + dY) * width].alpha); // inner0 = Mathf.Sqrt((dX + 0.5f * Mathf.Sign(dX)) * (dX + 0.5f * Mathf.Sign(dX)) + (dY + 0.5f * Mathf.Sign(dY)) * (dY + 0.5f * Mathf.Sign(dY))) + delta; // inner0 = Mathf.Clamp01(inner0 * scale); // //float outer_dst = 0; // dx0 = x; dy0 = y; // // Find smallest Inner distance // float outer_dst = outerMask[x + y * width].distance; // // Check dst against (x - 1, y) // if (outer_dst > outerMask[(x - 1) + y * width].distance) // { // dx0 = x - 1; dy0 = y; // outer_dst = outerMask[(x - 1) + y * width].distance; // } // // Check dst against (x - 1, y - 1) // if (outer_dst > outerMask[(x - 1) + (y - 1) * width].distance) // { // dx0 = x - 1; dy0 = y - 1; // outer_dst = outerMask[(x - 1) + (y - 1) * width].distance; // } // // Check dst against (x, y - 1) // if (outer_dst > outerMask[x + (y - 1) * width].distance) // { // dx0 = x; dy0 = y - 1; // outer_dst = outerMask[x + (y - 1) * width].distance; // } // dX = outerMask[dx0 + dy0 * width].dX; // dY = outerMask[dx0 + dy0 * width].dY; // delta = ApproximateEdgeDelta(dX, dY, outerMask[(x + dX) + (y + dY) * width].alpha); // outer0 = Mathf.Sqrt((dX + 0.5f * Mathf.Sign(dX)) * (dX + 0.5f * Mathf.Sign(dX)) + (dY + 0.5f * Mathf.Sign(dY)) * (dY + 0.5f * Mathf.Sign(dY))) + delta; // outer0 = Mathf.Clamp01(outer0 * scale); // //Debug.Log("Min Outer Distance for (" + x + "," + y + ") at (" + dx0 + "," + dy0 + ") is " + outer0 + " with dX/dY (" + outerMask[dx0 + dy0 * width].dX + "," + outerMask[dx0 + dy0 * width].dY + ")"); //} if (ScaleDownFactor > 1) { inner0 = innerMask[x + y * width].distance; float inner1 = innerMask[(x - 1) + y * width].distance; float inner2 = innerMask[x + (y - 1) * width].distance; float inner3 = innerMask[(x - 1) + (y - 1) * width].distance; outer0 = outerMask[x + y * width].distance; float outer1 = outerMask[(x - 1) + y * width].distance; float outer2 = outerMask[x + (y - 1) * width].distance; float outer3 = outerMask[(x - 1) + (y - 1) * width].distance; inner0 = Mathf.Clamp01((inner0 + inner1 + inner2 + inner3) / 4 * scale); outer0 = Mathf.Clamp01((outer0 + outer1 + outer2 + outer3) / 4 * scale); } ///Debug.Log(inner + " " + outer); float alpha = 0.5f + (inner0 - outer0) * 0.5f; //Debug.Log("(" + x + "," + y + ") Dx/Dy (" + outerMask[x + y * width].dX + "," + outerMask[x + y * width].dY + ") Scale Distance: " + d); Output[x1 + y1 * ScaledDownWidth] = new Color(0, 0, 0, alpha); //logfile += "(" + x + "," + y + ")\t\t\tDistance: " + Mathf.Max(innerMask[x + y * width].distance, outerMask[x + y * width].distance).ToString("f6") + "\t DxDy (" + outerMask[x + y * width].dX + "," + outerMask[x + y * width].dY + ")\t\t Inner: " + inner0.ToString("f4") + "\t\t Outer: " + outer0.ToString("f4") + "\t\t Alpha: " + alpha.ToString("f4") + "\n"; } //logfile += "\n"; } //Debug.Log("Output processed in [" + (timer.Elapsed - timeStamp) + "]"); // Free up allocations for pixel arrays innerMask = null; outerMask = null; timer.Stop(); Debug.Log("Distance Transform process took: [" + timer.Elapsed + "]."); TMPro_EventManager.ON_COMPUTE_DT_EVENT(null, new Compute_DT_EventArgs(Compute_DistanceTransform_EventTypes.Completed, Output));// Generate Event to notify and share results with Font Editor Window. //var pngData = DistanceMap.EncodeToPNG(); //File.WriteAllText("Assets/Logs/Distance Calcs.txt", logfile); //File.WriteAllBytes("Assets/Textures/New Texture.png", pngData); } // Compute Edge Delta can be imbeded into private static void ComputeEdgeGradient(Pixel p, Color[] colors, int mask, int index, int width) { // NOTE: Still need to add check against Pixel being along the edges which would fail float sqrt2 = 1.41421356f; // Mathf.Sqrt(2f); if (index < width + 1 || index > colors.Length - width - 2) return; // estimate gradient of edge pixel using surrounding pixels if (mask == 1) { float g = -(1f - colors[index - 1 - width].a) - (1f - colors[index - 1 + width].a) + (1f - colors[index + 1 - width].a) + (1f - colors[index + 1 + width].a); p.gradient.x = g + (1f - colors[index + 1].a) - (1f - colors[index - 1].a) * sqrt2; p.gradient.y = g + (1f - colors[index + width].a) - (1f - colors[index - width].a) * sqrt2; p.gradient.Normalize(); } else { float g = -colors[index - 1 - width].a - colors[index - 1 + width].a + colors[index + 1 - width].a + colors[index + 1 + width].a; p.gradient.x = g + (colors[index + 1].a) - (colors[index - 1].a) * sqrt2; p.gradient.y = g + (colors[index + width].a) - (colors[index - width].a) * sqrt2; p.gradient.Normalize(); } } private static float ApproximateEdgeDelta(float gx, float gy, float a) { // (gx, gy) can be either the local pixel gradient or the direction to the pixel //return 0.5f - a; if (gx == 0f || gy == 0f) { // linear function is correct if both gx and gy are zero // and still fair if only one of them is zero return 0.5f - a; } // normalize (gx, gy) float length = Mathf.Sqrt(gx * gx + gy * gy); gx = gx / length; gy = gy / length; // reduce symmetrical equation to first octant only // gx >= 0, gy >= 0, gx >= gy gx = Mathf.Abs(gx); gy = Mathf.Abs(gy); if (gx < gy) { float temp = gx; gx = gy; gy = temp; } // compute delta float a1 = 0.5f * gy / gx; if (a < a1) { // 0 <= a < a1 return 0.5f * (gx + gy) - Mathf.Sqrt(2f * gx * gy * a); } if (a < (1f - a1)) { // a1 <= a <= 1 - a1 return (0.5f - a) * gx; } // 1-a1 < a <= 1 return -0.5f * (gx + gy) + Mathf.Sqrt(2f * gx * gy * (1f - a)); } private static Pixel[] Calculate3X3EDT(Color[] input, int mask, int width, int height, int spread) { int inf = width * height; Pixel[] maskOutput = new Pixel[inf]; Pixel p1; // Test Pixel being considered as potential closest. int pRx = 0, pRy = 0; // Forward Scan & Initialization for (int y = 0; y < height; y++) { if (mask == 0f) { float pct = (float)y / (height - 1); TMPro_EventManager.ON_COMPUTE_DT_EVENT(null, new Compute_DT_EventArgs(Compute_DistanceTransform_EventTypes.Processing, pct)); //Debug.Log("Phase I pct [" + pct + "]"); } for (int x = 0; x < width; x++) { int index = x + y * width; Pixel p = new Pixel(); maskOutput[index] = p; //Check which Mask is being processed. Propagation makes it possible to generate the mask in-line with Algorithm p.alpha = mask == 0 ? input[index].a : 1f - input[index].a; float pF; if (p.alpha <= 0) pF = inf; else if (p.alpha < 1) { // Distance set to EdgeGradient for AA Pixels. No further processing needed for them. ComputeEdgeGradient(p, input, mask, index, width); pF = ApproximateEdgeDelta(p.gradient.x, p.gradient.y, p.alpha); p.dX = 0; p.dY = 0; p.distance = pF; continue; } else { // Distance set to Zero for Alpha = 1; No further processing needed for them. pF = 0; p.dX = 0; p.dY = 0; p.distance = 0; continue; } // Scan Lower Neighbour if (y > 0) { p1 = maskOutput[index - width]; if (p1.distance != inf) { int dX = p1.dX; int dY = p1.dY - 1; float delta = ApproximateEdgeDelta(dX, dY, maskOutput[index + dX + dY * width].alpha); float qF = Mathf.Sqrt(dX * dX + dY * dY) + delta; if (qF < pF) { pF = qF; pRx = dX; pRy = dY; } } } // Scan Left Neighbour if (x > 0) { p1 = maskOutput[index - 1]; if (p1.distance != inf) { int dX = p1.dX - 1; int dY = p1.dY; float delta = ApproximateEdgeDelta(dX, dY, maskOutput[index + dX + dY * width].alpha); float qF = Mathf.Sqrt(dX * dX + dY * dY) + delta; if (qF < pF) { pF = qF; pRx = dX; pRy = dY; } } } // Scan Lower-Left Neighbour if (x > 0 && y > 0) { p1 = maskOutput[index - 1 - width]; if (p1.distance != inf) { int dX = p1.dX - 1; int dY = p1.dY - 1; float delta = ApproximateEdgeDelta(dX, dY, maskOutput[index + dX + dY * width].alpha); float qF = Mathf.Sqrt(dX * dX + dY * dY) + delta; if (qF < pF) { pF = qF; pRx = dX; pRy = dY; } } } // Scan Lower-Right Neighbour if (x < width - 1 && y > 0) { p1 = maskOutput[index + 1 - width]; if (p1.distance != inf) { int dX = p1.dX + 1; int dY = p1.dY - 1; float delta = ApproximateEdgeDelta(dX, dY, maskOutput[index + dX + dY * width].alpha); float qF = Mathf.Sqrt(dX * dX + dY * dY) + delta; if (qF < pF) { pF = qF; pRx = dX; pRy = dY; } } } p.distance = pF; p.dX = pRx; p.dY = pRy; } } // Backward Scan & Initialization for (int y = height - 1; y >= 0; y--) { if (mask == 0f) { float pct = ((height - 1) - (float)y) / (height - 1); TMPro_EventManager.ON_COMPUTE_DT_EVENT(null, new Compute_DT_EventArgs(Compute_DistanceTransform_EventTypes.Processing, pct)); //Debug.Log("Phase II pct [" + pct + "]"); } for (int x = width - 1; x >= 0; x--) { int index = x + y * width; Pixel p = maskOutput[index]; if (p.alpha > 0 && p.alpha < 1 || p.distance == 0) { continue; } float pF = p.distance; pRx = p.dX; pRy = p.dY; // Scan Upper Neighbour if (y < height - 1) { p1 = maskOutput[index + width]; if (p1.distance != inf) { int dX = p1.dX; int dY = p1.dY + 1; float delta = ApproximateEdgeDelta(dX, dY, maskOutput[index + dX + dY * width].alpha); float qF = Mathf.Sqrt(dX * dX + dY * dY) + delta; if (qF <= pF) { pF = qF; pRx = dX; pRy = dY; } } } // Scan Right Neighbour if (x < width - 1) { p1 = maskOutput[index + 1]; if (p1.distance != inf) { int dX = p1.dX + 1; int dY = p1.dY; float delta = ApproximateEdgeDelta(dX, dY, maskOutput[index + dX + dY * width].alpha); float qF = Mathf.Sqrt(dX * dX + dY * dY) + delta; if (qF < pF) { pF = qF; pRx = dX; pRy = dY; } } } // Scan Upper-Right Neighbour if (x < width - 1 && y < height - 1) { p1 = maskOutput[index + 1 + width]; if (p1.distance != inf) { int dX = p1.dX + 1; int dY = p1.dY + 1; float delta = ApproximateEdgeDelta(dX, dY, maskOutput[index + dX + dY * width].alpha); float qF = Mathf.Sqrt(dX * dX + dY * dY) + delta; if (qF < pF) { pF = qF; pRx = dX; pRy = dY; } } } // Scan Upper-Left Neighboud if (x > 0 && y < height - 1) { p1 = maskOutput[index - 1 + width]; if (p1.distance != inf) { int dX = p1.dX - 1; int dY = p1.dY + 1; float delta = ApproximateEdgeDelta(dX, dY, maskOutput[index + dX + dY * width].alpha); float qF = Mathf.Sqrt(dX * dX + dY * dY) + delta; if (qF < pF) { pF = qF; pRx = dX; pRy = dY; } } } p.distance = pF; p.dX = pRx; p.dY = pRy; } } return maskOutput; } } }
// 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 class ReferenceEqual : ReferenceEqualityTests { [Theory] [PerCompilationType(nameof(ReferenceObjectsData))] public void TrueOnSame(object item, bool useInterpreter) { Expression exp = Expression.ReferenceEqual( Expression.Constant(item, item.GetType()), Expression.Constant(item, item.GetType()) ); Assert.True(Expression.Lambda<Func<bool>>(exp).Compile(useInterpreter)()); } [Theory] [PerCompilationType(nameof(ReferenceTypesData))] public void TrueOnBothNull(Type type, bool useInterpreter) { Expression exp = Expression.ReferenceEqual( Expression.Constant(null, type), Expression.Constant(null, type) ); Assert.True(Expression.Lambda<Func<bool>>(exp).Compile(useInterpreter)()); } [Theory] [PerCompilationType(nameof(ReferenceObjectsData))] public void FalseIfLeftNull(object item, bool useInterpreter) { Expression exp = Expression.ReferenceEqual( Expression.Constant(null, item.GetType()), Expression.Constant(item, item.GetType()) ); Assert.False(Expression.Lambda<Func<bool>>(exp).Compile(useInterpreter)()); } [Theory] [PerCompilationType(nameof(ReferenceObjectsData))] public void FalseIfRightNull(object item, bool useInterpreter) { Expression exp = Expression.ReferenceEqual( Expression.Constant(item, item.GetType()), Expression.Constant(null, item.GetType()) ); Assert.False(Expression.Lambda<Func<bool>>(exp).Compile(useInterpreter)()); } [Theory] [PerCompilationType(nameof(DifferentObjects))] public void FalseIfDifferentObjectsAsObject(object x, object y, bool useInterpreter) { Expression exp = Expression.ReferenceEqual( Expression.Constant(x, typeof(object)), Expression.Constant(y, typeof(object)) ); Assert.False(Expression.Lambda<Func<bool>>(exp).Compile(useInterpreter)()); } [Theory] [PerCompilationType(nameof(DifferentObjects))] public void FalseIfDifferentObjectsOwnType(object x, object y, bool useInterpreter) { Expression exp = Expression.ReferenceEqual( Expression.Constant(x), Expression.Constant(y) ); Assert.False(Expression.Lambda<Func<bool>>(exp).Compile(useInterpreter)()); } [Theory] [MemberData(nameof(LeftValueType))] [MemberData(nameof(RightValueType))] [MemberData(nameof(BothValueType))] public void ThrowsOnValueTypeArguments(object x, object y) { Expression xExp = Expression.Constant(x); Expression yExp = Expression.Constant(y); Assert.Throws<InvalidOperationException>(() => Expression.ReferenceEqual(xExp, yExp)); } [Theory] [MemberData(nameof(UnassignablePairs))] public void ThrowsOnUnassignablePairs(object x, object y) { Expression xExp = Expression.Constant(x); Expression yExp = Expression.Constant(y); Assert.Throws<InvalidOperationException>(() => Expression.ReferenceEqual(xExp, yExp)); } [Theory] [PerCompilationType(nameof(ComparableValuesData))] public void TrueOnSameViaInterface(object item, bool useInterpreter) { Expression exp = Expression.ReferenceEqual( Expression.Constant(item, typeof(IComparable)), Expression.Constant(item, typeof(IComparable)) ); Assert.True(Expression.Lambda<Func<bool>>(exp).Compile(useInterpreter)()); } [Theory] [PerCompilationType(nameof(DifferentComparableValues))] public void FalseOnDifferentViaInterface(object x, object y, bool useInterpreter) { Expression exp = Expression.ReferenceEqual( Expression.Constant(x, typeof(IComparable)), Expression.Constant(y, typeof(IComparable)) ); Assert.False(Expression.Lambda<Func<bool>>(exp).Compile(useInterpreter)()); } [Theory] [PerCompilationType(nameof(ComparableReferenceTypesData))] public void TrueOnSameLeftViaInterface(object item, bool useInterpreter) { Expression exp = Expression.ReferenceEqual( Expression.Constant(item, typeof(IComparable)), Expression.Constant(item) ); Assert.True(Expression.Lambda<Func<bool>>(exp).Compile(useInterpreter)()); } [Theory] [PerCompilationType(nameof(ComparableReferenceTypesData))] public void TrueOnSameRightViaInterface(object item, bool useInterpreter) { Expression exp = Expression.ReferenceEqual( Expression.Constant(item), Expression.Constant(item, typeof(IComparable)) ); Assert.True(Expression.Lambda<Func<bool>>(exp).Compile(useInterpreter)()); } [Fact] public void CannotReduce() { Expression exp = Expression.ReferenceEqual(Expression.Constant(""), Expression.Constant("")); Assert.False(exp.CanReduce); Assert.Same(exp, exp.Reduce()); Assert.Throws<ArgumentException>(null, () => exp.ReduceAndCheck()); } [Fact] public void ThrowsOnLeftNull() { Assert.Throws<ArgumentNullException>("left", () => Expression.ReferenceEqual(null, Expression.Constant(""))); } [Fact] public void ThrowsOnRightNull() { Assert.Throws<ArgumentNullException>("right", () => Expression.ReferenceEqual(Expression.Constant(""), null)); } [Fact] public static void ThrowsOnLeftUnreadable() { Expression value = Expression.Property(null, typeof(Unreadable<string>), "WriteOnly"); Assert.Throws<ArgumentException>("left", () => Expression.ReferenceEqual(value, Expression.Constant(""))); } [Fact] public static void ThrowsOnRightUnreadable() { Expression value = Expression.Property(null, typeof(Unreadable<string>), "WriteOnly"); Assert.Throws<ArgumentException>("right", () => Expression.ReferenceEqual(Expression.Constant(""), value)); } [Fact] public void Update() { Expression e1 = Expression.Constant("bar"); Expression e2 = Expression.Constant("foo"); Expression e3 = Expression.Constant("qux"); BinaryExpression eq = Expression.ReferenceEqual(e1, e2); Assert.Same(eq, eq.Update(e1, null, e2)); BinaryExpression eq1 = eq.Update(e1, null, e3); Assert.Equal(ExpressionType.Equal, eq1.NodeType); Assert.Same(e1, eq1.Left); Assert.Same(e3, eq1.Right); Assert.Null(eq1.Conversion); Assert.Null(eq1.Method); BinaryExpression eq2 = eq.Update(e3, null, e2); Assert.Equal(ExpressionType.Equal, eq2.NodeType); Assert.Same(e3, eq2.Left); Assert.Same(e2, eq2.Right); Assert.Null(eq2.Conversion); Assert.Null(eq2.Method); } } }
// // Author: // Jb Evain (jbevain@gmail.com) // // Copyright (c) 2008 - 2015 Jb Evain // Copyright (c) 2008 - 2011 Novell, Inc. // // Licensed under the MIT/X11 license. // using System; using System.Text; using Mono.Cecil.Metadata; namespace Mono.Cecil { class TypeParser { class Type { public const int Ptr = -1; public const int ByRef = -2; public const int SzArray = -3; public string type_fullname; public string [] nested_names; public int arity; public int [] specs; public Type [] generic_arguments; public string assembly; } readonly string fullname; readonly int length; int position; TypeParser (string fullname) { this.fullname = fullname; this.length = fullname.Length; } Type ParseType (bool fq_name) { var type = new Type (); type.type_fullname = ParsePart (); type.nested_names = ParseNestedNames (); if (TryGetArity (type)) type.generic_arguments = ParseGenericArguments (type.arity); type.specs = ParseSpecs (); if (fq_name) type.assembly = ParseAssemblyName (); return type; } static bool TryGetArity (Type type) { int arity = 0; TryAddArity (type.type_fullname, ref arity); var nested_names = type.nested_names; if (!nested_names.IsNullOrEmpty ()) { for (int i = 0; i < nested_names.Length; i++) TryAddArity (nested_names [i], ref arity); } type.arity = arity; return arity > 0; } static bool TryGetArity (string name, out int arity) { arity = 0; var index = name.LastIndexOf ('`'); if (index == -1) return false; return ParseInt32 (name.Substring (index + 1), out arity); } static bool ParseInt32 (string value, out int result) { #if CF try { result = int.Parse (value); return true; } catch { result = 0; return false; } #else return int.TryParse (value, out result); #endif } static void TryAddArity (string name, ref int arity) { int type_arity; if (!TryGetArity (name, out type_arity)) return; arity += type_arity; } string ParsePart () { var part = new StringBuilder (); while (position < length && !IsDelimiter (fullname [position])) { if (fullname [position] == '\\') position++; part.Append (fullname [position++]); } return part.ToString (); } static bool IsDelimiter (char chr) { return "+,[]*&".IndexOf (chr) != -1; } void TryParseWhiteSpace () { while (position < length && Char.IsWhiteSpace (fullname [position])) position++; } string [] ParseNestedNames () { string [] nested_names = null; while (TryParse ('+')) Add (ref nested_names, ParsePart ()); return nested_names; } bool TryParse (char chr) { if (position < length && fullname [position] == chr) { position++; return true; } return false; } static void Add<T> (ref T [] array, T item) { if (array == null) { array = new [] { item }; return; } array = array.Resize (array.Length + 1); array [array.Length - 1] = item; } int [] ParseSpecs () { int [] specs = null; while (position < length) { switch (fullname [position]) { case '*': position++; Add (ref specs, Type.Ptr); break; case '&': position++; Add (ref specs, Type.ByRef); break; case '[': position++; switch (fullname [position]) { case ']': position++; Add (ref specs, Type.SzArray); break; case '*': position++; Add (ref specs, 1); break; default: var rank = 1; while (TryParse (',')) rank++; Add (ref specs, rank); TryParse (']'); break; } break; default: return specs; } } return specs; } Type [] ParseGenericArguments (int arity) { Type [] generic_arguments = null; if (position == length || fullname [position] != '[') return generic_arguments; TryParse ('['); for (int i = 0; i < arity; i++) { var fq_argument = TryParse ('['); Add (ref generic_arguments, ParseType (fq_argument)); if (fq_argument) TryParse (']'); TryParse (','); TryParseWhiteSpace (); } TryParse (']'); return generic_arguments; } string ParseAssemblyName () { if (!TryParse (',')) return string.Empty; TryParseWhiteSpace (); var start = position; while (position < length) { var chr = fullname [position]; if (chr == '[' || chr == ']') break; position++; } return fullname.Substring (start, position - start); } public static TypeReference ParseType (ModuleDefinition module, string fullname) { if (string.IsNullOrEmpty (fullname)) return null; var parser = new TypeParser (fullname); return GetTypeReference (module, parser.ParseType (true)); } static TypeReference GetTypeReference (ModuleDefinition module, Type type_info) { TypeReference type; if (!TryGetDefinition (module, type_info, out type)) type = CreateReference (type_info, module, GetMetadataScope (module, type_info)); return CreateSpecs (type, type_info); } static TypeReference CreateSpecs (TypeReference type, Type type_info) { type = TryCreateGenericInstanceType (type, type_info); var specs = type_info.specs; if (specs.IsNullOrEmpty ()) return type; for (int i = 0; i < specs.Length; i++) { switch (specs [i]) { case Type.Ptr: type = new PointerType (type); break; case Type.ByRef: type = new ByReferenceType (type); break; case Type.SzArray: type = new ArrayType (type); break; default: var array = new ArrayType (type); array.Dimensions.Clear (); for (int j = 0; j < specs [i]; j++) array.Dimensions.Add (new ArrayDimension ()); type = array; break; } } return type; } static TypeReference TryCreateGenericInstanceType (TypeReference type, Type type_info) { var generic_arguments = type_info.generic_arguments; if (generic_arguments.IsNullOrEmpty ()) return type; var instance = new GenericInstanceType (type); var instance_arguments = instance.GenericArguments; for (int i = 0; i < generic_arguments.Length; i++) instance_arguments.Add (GetTypeReference (type.Module, generic_arguments [i])); return instance; } public static void SplitFullName (string fullname, out string @namespace, out string name) { var last_dot = fullname.LastIndexOf ('.'); if (last_dot == -1) { @namespace = string.Empty; name = fullname; } else { @namespace = fullname.Substring (0, last_dot); name = fullname.Substring (last_dot + 1); } } static TypeReference CreateReference (Type type_info, ModuleDefinition module, IMetadataScope scope) { string @namespace, name; SplitFullName (type_info.type_fullname, out @namespace, out name); var type = new TypeReference (@namespace, name, module, scope); MetadataSystem.TryProcessPrimitiveTypeReference (type); AdjustGenericParameters (type); var nested_names = type_info.nested_names; if (nested_names.IsNullOrEmpty ()) return type; for (int i = 0; i < nested_names.Length; i++) { type = new TypeReference (string.Empty, nested_names [i], module, null) { DeclaringType = type, }; AdjustGenericParameters (type); } return type; } static void AdjustGenericParameters (TypeReference type) { int arity; if (!TryGetArity (type.Name, out arity)) return; for (int i = 0; i < arity; i++) type.GenericParameters.Add (new GenericParameter (type)); } static IMetadataScope GetMetadataScope (ModuleDefinition module, Type type_info) { if (string.IsNullOrEmpty (type_info.assembly)) return module.TypeSystem.Corlib; return MatchReference (module, AssemblyNameReference.Parse (type_info.assembly)); } static AssemblyNameReference MatchReference (ModuleDefinition module, AssemblyNameReference pattern) { var references = module.AssemblyReferences; for (int i = 0; i < references.Count; i++) { var reference = references [i]; if (reference.FullName == pattern.FullName) return reference; } return pattern; } static bool TryGetDefinition (ModuleDefinition module, Type type_info, out TypeReference type) { type = null; if (!TryCurrentModule (module, type_info)) return false; var typedef = module.GetType (type_info.type_fullname); if (typedef == null) return false; var nested_names = type_info.nested_names; if (!nested_names.IsNullOrEmpty ()) { for (int i = 0; i < nested_names.Length; i++) typedef = typedef.GetNestedType (nested_names [i]); } type = typedef; return true; } static bool TryCurrentModule (ModuleDefinition module, Type type_info) { if (string.IsNullOrEmpty (type_info.assembly)) return true; if (module.assembly != null && module.assembly.Name.FullName == type_info.assembly) return true; return false; } public static string ToParseable (TypeReference type) { if (type == null) return null; var name = new StringBuilder (); AppendType (type, name, true, true); return name.ToString (); } static void AppendNamePart (string part, StringBuilder name) { foreach (var c in part) { if (IsDelimiter (c)) name.Append ('\\'); name.Append (c); } } static void AppendType (TypeReference type, StringBuilder name, bool fq_name, bool top_level) { var declaring_type = type.DeclaringType; if (declaring_type != null) { AppendType (declaring_type, name, false, top_level); name.Append ('+'); } var @namespace = type.Namespace; if (!string.IsNullOrEmpty (@namespace)) { AppendNamePart (@namespace, name); name.Append ('.'); } AppendNamePart (type.GetElementType ().Name, name); if (!fq_name) return; if (type.IsTypeSpecification ()) AppendTypeSpecification ((TypeSpecification) type, name); if (RequiresFullyQualifiedName (type, top_level)) { name.Append (", "); name.Append (GetScopeFullName (type)); } } static string GetScopeFullName (TypeReference type) { var scope = type.Scope; switch (scope.MetadataScopeType) { case MetadataScopeType.AssemblyNameReference: return ((AssemblyNameReference) scope).FullName; case MetadataScopeType.ModuleDefinition: return ((ModuleDefinition) scope).Assembly.Name.FullName; } throw new ArgumentException (); } static void AppendTypeSpecification (TypeSpecification type, StringBuilder name) { if (type.ElementType.IsTypeSpecification ()) AppendTypeSpecification ((TypeSpecification) type.ElementType, name); switch (type.etype) { case ElementType.Ptr: name.Append ('*'); break; case ElementType.ByRef: name.Append ('&'); break; case ElementType.SzArray: case ElementType.Array: var array = (ArrayType) type; if (array.IsVector) { name.Append ("[]"); } else { name.Append ('['); for (int i = 1; i < array.Rank; i++) name.Append (','); name.Append (']'); } break; case ElementType.GenericInst: var instance = (GenericInstanceType) type; var arguments = instance.GenericArguments; name.Append ('['); for (int i = 0; i < arguments.Count; i++) { if (i > 0) name.Append (','); var argument = arguments [i]; var requires_fqname = argument.Scope != argument.Module; if (requires_fqname) name.Append ('['); AppendType (argument, name, true, false); if (requires_fqname) name.Append (']'); } name.Append (']'); break; default: return; } } static bool RequiresFullyQualifiedName (TypeReference type, bool top_level) { if (type.Scope == type.Module) return false; if (type.Scope.Name == "mscorlib" && top_level) return false; return true; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace entdemo.website.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Diagnostics; using Codentia.Common.Data; using Codentia.Common.Helper; using Codentia.Test.Generator; using Codentia.Test.Reflector; using NUnit.Framework; namespace Codentia.Test.Helper { /// <summary> /// Class for doing common NUnit methods /// </summary> public class NUnitHelper { /// <summary> /// Do the standard negative tests for integers and strings /// integer - 0, -1 and non-existant /// string - null, empty, optionally length if default value is ~~N where N is length to be measured, and optional non-existant value to check for /// </summary> /// <param name="database">the database</param> /// <param name="assemblyName">Assembly dll name e.g. Codentia.Test.Test.dll</param> /// <param name="className">Fully qualified class name e.g. Codentia.Test.Test.TestClass</param> /// <param name="methodName">Method Name e.g. OneCheckedStringParamWithLength</param> /// <param name="defaultValues">comma delimited name/value pairs with = e.g. myId1=[TestTable1],myId2=[TestTable3] - use [] for the table for existant and non-existant ids</param> /// <param name="omittedParameters">comma delimited list of int or string parameters to be omitted from negative tests</param> public static void DoNegativeTests(string database, string assemblyName, string className, string methodName, string defaultValues, string omittedParameters) { DoNegativeTests(database, assemblyName, className, methodName, null, defaultValues, omittedParameters); } /// <summary> /// Do the standard negative tests for integers and strings /// integer - 0, -1 and non-existant /// string - null, empty, optionally length if default value is ~~N~~ where N is length to be measured, and optional non-existant value to check for with pattern $$NONEXISTANTSTRING$$ /// </summary> /// <param name="database">the database</param> /// <param name="assemblyName">Assembly dll name e.g. Codentia.Test.Test.dll</param> /// <param name="className">Fully qualified class name e.g. Codentia.Test.Test.TestClass</param> /// <param name="methodName">Method Name e.g. OneCheckedStringParamWithLength</param> /// <param name="signature">For uses with overloads - comma delimited list of types to match overload being tested</param> /// <param name="defaultValues">comma delimited name/value pairs with = e.g. myId1=[TestTable1],myId2=[TestTable3] - use [] for the table for existant and non-existant ids</param> /// <param name="omittedParameters">comma delimited list of int or string parameters to be omitted from negative tests</param> public static void DoNegativeTests(string database, string assemblyName, string className, string methodName, string signature, string defaultValues, string omittedParameters) { ParameterCheckHelper.CheckIsValidString(database, "database", false); ParameterCheckHelper.CheckIsValidString(assemblyName, "assemblyName", false); ParameterCheckHelper.CheckIsValidString(className, "className", false); ParameterCheckHelper.CheckIsValidString(methodName, "methodName", false); Method method = new Method(database, assemblyName, className, methodName, signature, defaultValues, omittedParameters); for (int i = 0; i < method.ParameterDataTable.Rows.Count; i++) { DataRow dr = method.ParameterDataTable.Rows[i]; if (Convert.ToBoolean(dr["omitted"]) == false) { DoAllNegativeTestsForParameter(method, dr); } } } /// <summary> /// Unit Test Data Checker /// </summary> /// <param name="database">the database</param> /// <param name="alwaysClearDownData">always clear down data</param> /// <param name="clearDownAllData">if true, clear down all data, otherwise use just the tables in xmlTableList</param> /// <param name="xmlTableListFilePath">(optional) filepath of an xml document root cleardowntables, element name - cleardowntable</param> /// <returns>bool - true if data cleared down, otherwise false</returns> public static bool UnitTestDataChecker(string database, bool alwaysClearDownData, bool clearDownAllData, string xmlTableListFilePath) { return UnitTestDataChecker(database, alwaysClearDownData, clearDownAllData, AssemblyHelper.GetCallingAssemblyName(new StackTrace()), xmlTableListFilePath); } /// <summary> /// Is the data in a position to be cleared down? /// <para></para> /// The conditions are :- /// <para></para> /// 1) If no system test table exists - return true /// <para></para> /// 2) If the system test table exists /// <para></para> /// a) if the windows temp file exists and the checkguid inside is different to the one is the system test table - return true /// <para></para> /// b) if checkguid is same in table and file but the configured [CleardownDataThresholdSeconds] threshold has passed - return true /// <para></para> /// 3) otherwise return false /// </summary> /// <param name="database">the database</param> /// <param name="callingAssembly">the name of the assembly calling the wrapper procedure e.g. my.blah.dll</param> /// <returns>bool - true if data needs to be cleared down, otherwise false</returns> internal static bool IsCandidateForClearDown(string database, string callingAssembly) { if (DbSystem.DoesUserTableExist(database, SqlHelper.SystemCheckTable) == false) { return true; } else { Dictionary<Guid, DateTime> dict = SqlHelper.ReadSystemCheckTable(database); IEnumerator<Guid> ie = dict.Keys.GetEnumerator(); ie.MoveNext(); Guid checkGuid = ie.Current; DateTime checkDateTime = dict[ie.Current]; if (FileHelper.DoesWindowsTempFileExist(callingAssembly, checkGuid.ToString()) == false) { return true; } else { int cleardownDataThresholdSeconds = 180; if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["CleardownDataThresholdSeconds"])) { cleardownDataThresholdSeconds = Convert.ToInt32(ConfigurationManager.AppSettings["CleardownDataThresholdSeconds"]); } if (checkDateTime.AddSeconds(cleardownDataThresholdSeconds) < DateTime.Now) { return true; } } } return false; } private static bool UnitTestDataChecker(string database, bool alwaysClearDownData, bool clearDownAllData, string callingAssembly, string xmlTableListFilePath) { bool clearDown = alwaysClearDownData; if (alwaysClearDownData == false) { clearDown = IsCandidateForClearDown(database, callingAssembly); } if (clearDown) { SqlHelper.ClearDataInDatabase(database, clearDownAllData, xmlTableListFilePath); } return clearDown; } private static void DoAllNegativeTestsForParameter(Method method, DataRow paramRow) { string paramType = Convert.ToString(paramRow["type"]); switch (paramType) { case "System.Int32": DoIntegerTests(method, paramRow); break; case "System.String": DoStringTests(method, paramRow); break; case "System.Byte": DoByteTests(method, paramRow); break; } } private static void DoIntegerTests(Method method, DataRow paramRow) { string name = Convert.ToString(paramRow["name"]); string defaultValue = Convert.ToString(paramRow["defaultValue"]); string paramType = Convert.ToString(paramRow["type"]); // 0 object[] arguments = method.GetArgumentArray(name, "0"); string expectedMessage = string.Format("{0}: 0 is not valid", name); string conditionMessage = string.Format("Param: {0}, Value: {1}", name, "0"); DoAssert(method, arguments, expectedMessage, conditionMessage); // -1 arguments = method.GetArgumentArray(name, "-1"); expectedMessage = string.Format("{0}: -1 is not valid", name); conditionMessage = string.Format("Param: {0}, Value: {1}", name, "-1"); DoAssert(method, arguments, expectedMessage, conditionMessage); // non-existant if (defaultValue.Contains("[") && defaultValue.Contains("]")) { string nonExistantValue = SqlHelper.GetDatabaseNonExistantValueFromToken(method.Database, defaultValue); arguments = method.GetArgumentArray(name, nonExistantValue); expectedMessage = string.Format("{0}: {1} does not exist", name, nonExistantValue); conditionMessage = string.Format("Param: {0}, Value: {1}", name, nonExistantValue); DoAssert(method, arguments, expectedMessage, conditionMessage); } } private static void DoStringTests(Method method, DataRow paramRow) { string name = Convert.ToString(paramRow["name"]); string defaultValue = Convert.ToString(paramRow["defaultValue"]); // empty object[] arguments = method.GetArgumentArray(name, string.Empty); string expectedMessage = string.Format("{0} is not specified", name); string conditionMessage = string.Format("Param: {0}, Value: {1}", name, "empty"); DoAssert(method, arguments, expectedMessage, conditionMessage); if (!method.IsOverload) { // null arguments = method.GetArgumentArray(name, null); expectedMessage = string.Format("{0} is not specified", name); conditionMessage = string.Format("Param: {0}, Value: {1}", name, "null"); DoAssert(method, arguments, expectedMessage, conditionMessage); } if (defaultValue.Contains("~~")) { int maxChars = Convert.ToInt32(ExtractStringValue(defaultValue, "~~")); string useValue = DataGenerator.GenerateRandomString(maxChars + 1); arguments = method.GetArgumentArray(name, useValue); expectedMessage = string.Format("{0} exceeds maxLength {1} as it has {2} chars", name, maxChars, maxChars + 1); conditionMessage = string.Format("Param: {0}, Value: {1}", name, useValue); DoAssert(method, arguments, expectedMessage, conditionMessage); } if (defaultValue.Contains("$$")) { string useValue = ExtractStringValue(defaultValue, "$$"); arguments = method.GetArgumentArray(name, useValue); expectedMessage = string.Format("{0}: {1} does not exist", name, useValue); conditionMessage = string.Format("Param: {0}, Value: {1}", name, useValue); DoAssert(method, arguments, expectedMessage, conditionMessage); } } private static void DoByteTests(Method method, DataRow paramRow) { string name = Convert.ToString(paramRow["name"]); string defaultValue = Convert.ToString(paramRow["defaultValue"]); string paramType = Convert.ToString(paramRow["type"]); // 0 object[] arguments = method.GetArgumentArray(name, "0"); string expectedMessage = string.Format("{0}: 0 is not valid", name); string conditionMessage = string.Format("Param: {0}, Value: {1}", name, "0"); DoAssert(method, arguments, expectedMessage, conditionMessage); } private static string ExtractStringValue(string value, string token) { string retVal = value; int startPos = retVal.IndexOf(token); if (startPos > -1) { retVal = retVal.Substring(startPos + 2, retVal.Length - (startPos + 2)); } int endPos = retVal.IndexOf(token); if (endPos > -1) { retVal = retVal.Substring(0, endPos); } return retVal; } [Test] private static void DoAssert(Method method, object[] arguments, string expectedMessage, string testConditionMessage) { string message = string.Empty; try { method.Invoke(arguments); } catch (Exception ex) { message = ex.InnerException.Message; } string outputLine = string.Format("DoAssert: Method: {0}, Test Condition: {1} - FAILED - {2}", method.Name, testConditionMessage, message); if (expectedMessage == message) { outputLine = string.Format("DoAssert: Method: {0}, Test Condition: {1} - PASSED", method.Name, testConditionMessage); } Console.WriteLine(outputLine); Assert.That(message, Is.EqualTo(expectedMessage)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Globalization; using System.Runtime; using System.Runtime.CompilerServices; using System.Text; using Internal.Runtime.Augments; using Internal.Reflection.Augments; namespace System { [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public abstract class Enum : ValueType, IComparable, IFormattable, IConvertible { public int CompareTo(Object target) { if (target == null) return 1; if (target == this) return 0; if (this.EETypePtr != target.EETypePtr) { throw new ArgumentException(SR.Format(SR.Arg_EnumAndObjectMustBeSameType, target.GetType().ToString(), this.GetType().ToString())); } ref byte pThisValue = ref this.GetRawData(); ref byte pTargetValue = ref target.GetRawData(); switch (this.EETypePtr.CorElementType) { case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I1: return (Unsafe.As<byte, sbyte>(ref pThisValue) == Unsafe.As<byte, sbyte>(ref pTargetValue)) ? 0 : (Unsafe.As<byte, sbyte>(ref pThisValue) < Unsafe.As<byte, sbyte>(ref pTargetValue)) ? -1 : 1; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U1: case RuntimeImports.RhCorElementType.ELEMENT_TYPE_BOOLEAN: return (Unsafe.As<byte, byte>(ref pThisValue) == Unsafe.As<byte, byte>(ref pTargetValue)) ? 0 : (Unsafe.As<byte, byte>(ref pThisValue) < Unsafe.As<byte, byte>(ref pTargetValue)) ? -1 : 1; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I2: return (Unsafe.As<byte, short>(ref pThisValue) == Unsafe.As<byte, short>(ref pTargetValue)) ? 0 : (Unsafe.As<byte, short>(ref pThisValue) < Unsafe.As<byte, short>(ref pTargetValue)) ? -1 : 1; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U2: case RuntimeImports.RhCorElementType.ELEMENT_TYPE_CHAR: return (Unsafe.As<byte, ushort>(ref pThisValue) == Unsafe.As<byte, ushort>(ref pTargetValue)) ? 0 : (Unsafe.As<byte, ushort>(ref pThisValue) < Unsafe.As<byte, ushort>(ref pTargetValue)) ? -1 : 1; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I4: return (Unsafe.As<byte, int>(ref pThisValue) == Unsafe.As<byte, int>(ref pTargetValue)) ? 0 : (Unsafe.As<byte, int>(ref pThisValue) < Unsafe.As<byte, int>(ref pTargetValue)) ? -1 : 1; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U4: return (Unsafe.As<byte, uint>(ref pThisValue) == Unsafe.As<byte, uint>(ref pTargetValue)) ? 0 : (Unsafe.As<byte, uint>(ref pThisValue) < Unsafe.As<byte, uint>(ref pTargetValue)) ? -1 : 1; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I8: return (Unsafe.As<byte, long>(ref pThisValue) == Unsafe.As<byte, long>(ref pTargetValue)) ? 0 : (Unsafe.As<byte, long>(ref pThisValue) < Unsafe.As<byte, long>(ref pTargetValue)) ? -1 : 1; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U8: return (Unsafe.As<byte, ulong>(ref pThisValue) == Unsafe.As<byte, ulong>(ref pTargetValue)) ? 0 : (Unsafe.As<byte, ulong>(ref pThisValue) < Unsafe.As<byte, ulong>(ref pTargetValue)) ? -1 : 1; default: Environment.FailFast("Unexpected enum underlying type"); return 0; } } public override bool Equals(Object obj) { if (obj == null) return false; EETypePtr eeType = this.EETypePtr; if (!eeType.FastEquals(obj.EETypePtr)) return false; ref byte pThisValue = ref this.GetRawData(); ref byte pOtherValue = ref obj.GetRawData(); RuntimeImports.RhCorElementTypeInfo corElementTypeInfo = eeType.CorElementTypeInfo; switch (corElementTypeInfo.Log2OfSize) { case 0: return Unsafe.As<byte, byte>(ref pThisValue) == Unsafe.As<byte, byte>(ref pOtherValue); case 1: return Unsafe.As<byte, ushort>(ref pThisValue) == Unsafe.As<byte, ushort>(ref pOtherValue); case 2: return Unsafe.As<byte, uint>(ref pThisValue) == Unsafe.As<byte, uint>(ref pOtherValue); case 3: return Unsafe.As<byte, ulong>(ref pThisValue) == Unsafe.As<byte, ulong>(ref pOtherValue); default: Environment.FailFast("Unexpected enum underlying type"); return false; } } public override int GetHashCode() { ref byte pValue = ref this.GetRawData(); switch (this.EETypePtr.CorElementType) { case RuntimeImports.RhCorElementType.ELEMENT_TYPE_BOOLEAN: return Unsafe.As<byte, bool>(ref pValue).GetHashCode(); case RuntimeImports.RhCorElementType.ELEMENT_TYPE_CHAR: return Unsafe.As<byte, char>(ref pValue).GetHashCode(); case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I1: return Unsafe.As<byte, sbyte>(ref pValue).GetHashCode(); case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U1: return Unsafe.As<byte, byte>(ref pValue).GetHashCode(); case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I2: return Unsafe.As<byte, short>(ref pValue).GetHashCode(); case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U2: return Unsafe.As<byte, ushort>(ref pValue).GetHashCode(); case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I4: return Unsafe.As<byte, int>(ref pValue).GetHashCode(); case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U4: return Unsafe.As<byte, uint>(ref pValue).GetHashCode(); case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I8: return Unsafe.As<byte, long>(ref pValue).GetHashCode(); case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U8: return Unsafe.As<byte, ulong>(ref pValue).GetHashCode(); default: Environment.FailFast("Unexpected enum underlying type"); return 0; } } public static String Format(Type enumType, Object value, String format) { if (enumType == null) throw new ArgumentNullException(nameof(enumType)); if (!enumType.IsEnum) throw new ArgumentException(SR.Arg_MustBeEnum, nameof(enumType)); if (value == null) throw new ArgumentNullException(nameof(value)); if (format == null) throw new ArgumentNullException(nameof(format)); if (!enumType.IsRuntimeImplemented()) throw new ArgumentException(SR.Arg_MustBeType, nameof(enumType)); EnumInfo enumInfo = GetEnumInfo(enumType); if (value is Enum) { EETypePtr enumTypeEEType; if ((!enumType.TryGetEEType(out enumTypeEEType)) || enumTypeEEType != value.EETypePtr) throw new ArgumentException(SR.Format(SR.Arg_EnumAndObjectMustBeSameType, value.GetType().ToString(), enumType.ToString())); } else { if (value.EETypePtr != enumInfo.UnderlyingType.TypeHandle.ToEETypePtr()) throw new ArgumentException(SR.Format(SR.Arg_EnumFormatUnderlyingTypeAndObjectMustBeSameType, value.GetType().ToString(), enumInfo.UnderlyingType.ToString())); } return Format(enumInfo, value, format); } private static String Format(EnumInfo enumInfo, Object value, String format) { ulong rawValue; if (!TryGetUnboxedValueOfEnumOrInteger(value, out rawValue)) { Debug.Assert(false, "Caller was expected to do enough validation to avoid reaching this."); throw new ArgumentException(); } if (format.Length != 1) { // all acceptable format string are of length 1 throw new FormatException(SR.Format_InvalidEnumFormatSpecification); } char formatCh = format[0]; if (formatCh == 'D' || formatCh == 'd') { return DoFormatD(rawValue, value.EETypePtr.CorElementType); } if (formatCh == 'X' || formatCh == 'x') { return DoFormatX(rawValue, value.EETypePtr.CorElementType); } if (formatCh == 'G' || formatCh == 'g') { return DoFormatG(enumInfo, rawValue); } if (formatCh == 'F' || formatCh == 'f') { return DoFormatF(enumInfo, rawValue); } throw new FormatException(SR.Format_InvalidEnumFormatSpecification); } // // Helper for Enum.Format(,,"d") // private static String DoFormatD(ulong rawValue, RuntimeImports.RhCorElementType corElementType) { switch (corElementType) { case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I1: { SByte result = (SByte)rawValue; return result.ToString(); } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U1: { Byte result = (Byte)rawValue; return result.ToString(); } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_BOOLEAN: { // direct cast from bool to byte is not allowed bool b = (rawValue != 0); return b.ToString(); } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I2: { Int16 result = (Int16)rawValue; return result.ToString(); } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U2: { UInt16 result = (UInt16)rawValue; return result.ToString(); } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_CHAR: { Char result = (Char)rawValue; return result.ToString(); } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U4: { UInt32 result = (UInt32)rawValue; return result.ToString(); } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I4: { Int32 result = (Int32)rawValue; return result.ToString(); } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U8: { UInt64 result = (UInt64)rawValue; return result.ToString(); } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I8: { Int64 result = (Int64)rawValue; return result.ToString(); } default: Debug.Assert(false, "Invalid Object type in Format"); throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType); } } // // Helper for Enum.Format(,,"x") // private static String DoFormatX(ulong rawValue, RuntimeImports.RhCorElementType corElementType) { switch (corElementType) { case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I1: { Byte result = (byte)(sbyte)rawValue; return result.ToString("X2", null); } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U1: { Byte result = (byte)rawValue; return result.ToString("X2", null); } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_BOOLEAN: { // direct cast from bool to byte is not allowed Byte result = (byte)rawValue; return result.ToString("X2", null); } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I2: { UInt16 result = (UInt16)(Int16)rawValue; return result.ToString("X4", null); } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U2: { UInt16 result = (UInt16)rawValue; return result.ToString("X4", null); } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_CHAR: { UInt16 result = (UInt16)(Char)rawValue; return result.ToString("X4", null); } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U4: { UInt32 result = (UInt32)rawValue; return result.ToString("X8", null); } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I4: { UInt32 result = (UInt32)(int)rawValue; return result.ToString("X8", null); } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U8: { UInt64 result = (UInt64)rawValue; return result.ToString("X16", null); } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I8: { UInt64 result = (UInt64)(Int64)rawValue; return result.ToString("X16", null); } default: Debug.Assert(false, "Invalid Object type in Format"); throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType); } } // // Helper for Enum.Format(,,"g") // private static String DoFormatG(EnumInfo enumInfo, ulong rawValue) { Debug.Assert(enumInfo != null); if (!enumInfo.HasFlagsAttribute) // Not marked with Flags attribute { // Try to see if its one of the enum values, then we return a String back else the value String name = GetNameIfAny(enumInfo, rawValue); if (name == null) return DoFormatD(rawValue, enumInfo.UnderlyingType.TypeHandle.ToEETypePtr().CorElementType); else return name; } else // These are flags OR'ed together (We treat everything as unsigned types) { return DoFormatF(enumInfo, rawValue); } } // // Helper for Enum.Format(,,"f") // private static String DoFormatF(EnumInfo enumInfo, ulong rawValue) { Debug.Assert(enumInfo != null); // These values are sorted by value. Don't change this KeyValuePair<String, ulong>[] namesAndValues = enumInfo.NamesAndValues; int index = namesAndValues.Length - 1; StringBuilder retval = new StringBuilder(); bool firstTime = true; ulong result = rawValue; // We will not optimize this code further to keep it maintainable. There are some boundary checks that can be applied // to minimize the comparsions required. This code works the same for the best/worst case. In general the number of // items in an enum are sufficiently small and not worth the optimization. while (index >= 0) { if ((index == 0) && (namesAndValues[index].Value == 0)) break; if ((result & namesAndValues[index].Value) == namesAndValues[index].Value) { result -= namesAndValues[index].Value; if (!firstTime) retval.Insert(0, ", "); retval.Insert(0, namesAndValues[index].Key); firstTime = false; } index--; } // We were unable to represent this number as a bitwise or of valid flags if (result != 0) return DoFormatD(rawValue, enumInfo.UnderlyingType.TypeHandle.ToEETypePtr().CorElementType); // For the case when we have zero if (rawValue == 0) { if (namesAndValues.Length > 0 && namesAndValues[0].Value == 0) return namesAndValues[0].Key; // Zero was one of the enum values. else return "0"; } else return retval.ToString(); // Built a list of matching names. Return it. } internal Object GetValue() { ref byte pValue = ref this.GetRawData(); switch (this.EETypePtr.CorElementType) { case RuntimeImports.RhCorElementType.ELEMENT_TYPE_BOOLEAN: return Unsafe.As<byte, bool>(ref pValue); case RuntimeImports.RhCorElementType.ELEMENT_TYPE_CHAR: return Unsafe.As<byte, char>(ref pValue); case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I1: return Unsafe.As<byte, sbyte>(ref pValue); case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U1: return Unsafe.As<byte, byte>(ref pValue); case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I2: return Unsafe.As<byte, short>(ref pValue); case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U2: return Unsafe.As<byte, ushort>(ref pValue); case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I4: return Unsafe.As<byte, int>(ref pValue); case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U4: return Unsafe.As<byte, uint>(ref pValue); case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I8: return Unsafe.As<byte, long>(ref pValue); case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U8: return Unsafe.As<byte, ulong>(ref pValue); default: Environment.FailFast("Unexpected enum underlying type"); return 0; } } public static String GetName(Type enumType, Object value) { if (enumType == null) throw new ArgumentNullException(nameof(enumType)); if (!enumType.IsRuntimeImplemented()) return enumType.GetEnumName(value); if (value == null) throw new ArgumentNullException(nameof(value)); ulong rawValue; if (!TryGetUnboxedValueOfEnumOrInteger(value, out rawValue)) throw new ArgumentException(SR.Arg_MustBeEnumBaseTypeOrEnum, nameof(value)); // For desktop compatibility, do not bounce an incoming integer that's the wrong size. // Do a value-preserving cast of both it and the enum values and do a 64-bit compare. if (!enumType.IsEnum) throw new ArgumentException(SR.Arg_MustBeEnum); EnumInfo enumInfo = GetEnumInfo(enumType); String nameOrNull = GetNameIfAny(enumInfo, rawValue); return nameOrNull; } public static String[] GetNames(Type enumType) { if (enumType == null) throw new ArgumentNullException(nameof(enumType)); if (!enumType.IsRuntimeImplemented()) return enumType.GetEnumNames(); if (!enumType.IsEnum) throw new ArgumentException(SR.Arg_MustBeEnum); KeyValuePair<String, ulong>[] namesAndValues = GetEnumInfo(enumType).NamesAndValues; String[] names = new String[namesAndValues.Length]; for (int i = 0; i < namesAndValues.Length; i++) names[i] = namesAndValues[i].Key; return names; } public static Type GetUnderlyingType(Type enumType) { if (enumType == null) throw new ArgumentNullException(nameof(enumType)); if (!enumType.IsRuntimeImplemented()) return enumType.GetEnumUnderlyingType(); if (!enumType.IsEnum) throw new ArgumentException(SR.Arg_MustBeEnum, nameof(enumType)); return GetEnumInfo(enumType).UnderlyingType; } public static Array GetValues(Type enumType) { if (enumType == null) throw new ArgumentNullException(nameof(enumType)); if (!enumType.IsRuntimeImplemented()) return enumType.GetEnumValues(); if (!enumType.IsEnum) throw new ArgumentException(SR.Arg_MustBeEnum); Array values = GetEnumInfo(enumType).Values; int count = values.Length; Array result = Array.CreateInstance(enumType, count); Array.CopyImplValueTypeArrayNoInnerGcRefs(values, 0, result, 0, count); return result; } public Boolean HasFlag(Enum flag) { if (flag == null) throw new ArgumentNullException(nameof(flag)); Contract.EndContractBlock(); if (!(this.EETypePtr == flag.EETypePtr)) throw new ArgumentException(SR.Format(SR.Argument_EnumTypeDoesNotMatch, flag.GetType(), this.GetType())); ref byte pThisValue = ref this.GetRawData(); ref byte pFlagValue = ref flag.GetRawData(); switch (this.EETypePtr.CorElementTypeInfo.Log2OfSize) { case 0: return (Unsafe.As<byte, byte>(ref pThisValue) & Unsafe.As<byte, byte>(ref pFlagValue)) == Unsafe.As<byte, byte>(ref pFlagValue); case 1: return (Unsafe.As<byte, ushort>(ref pThisValue) & Unsafe.As<byte, ushort>(ref pFlagValue)) == Unsafe.As<byte, ushort>(ref pFlagValue); case 2: return (Unsafe.As<byte, uint>(ref pThisValue) & Unsafe.As<byte, uint>(ref pFlagValue)) == Unsafe.As<byte, uint>(ref pFlagValue); case 3: return (Unsafe.As<byte, ulong>(ref pThisValue) & Unsafe.As<byte, ulong>(ref pFlagValue)) == Unsafe.As<byte, ulong>(ref pFlagValue); default: Environment.FailFast("Unexpected enum underlying type"); return false; } } public static bool IsDefined(Type enumType, Object value) { if (enumType == null) throw new ArgumentNullException(nameof(enumType)); if (!enumType.IsRuntimeImplemented()) return enumType.IsEnumDefined(value); if (value == null) throw new ArgumentNullException(nameof(value)); if (value.EETypePtr == EETypePtr.EETypePtrOf<string>()) { if (!enumType.IsEnum) throw new ArgumentException(SR.Arg_MustBeEnum); EnumInfo enumInfo = GetEnumInfo(enumType); foreach (KeyValuePair<String, ulong> kv in enumInfo.NamesAndValues) { if (value.Equals(kv.Key)) return true; } return false; } else { ulong rawValue; if (!TryGetUnboxedValueOfEnumOrInteger(value, out rawValue)) { if (Type.IsIntegerType(value.GetType())) throw new ArgumentException(SR.Format(SR.Arg_EnumUnderlyingTypeAndObjectMustBeSameType, value.GetType(), Enum.GetUnderlyingType(enumType))); else throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType); } EnumInfo enumInfo = null; if (value is Enum) { if (!ValueTypeMatchesEnumType(enumType, value)) throw new ArgumentException(SR.Format(SR.Arg_EnumAndObjectMustBeSameType, value.GetType(), enumType)); } else { if (!enumType.IsEnum) throw new ArgumentException(SR.Arg_MustBeEnum); enumInfo = GetEnumInfo(enumType); if (!(enumInfo.UnderlyingType.TypeHandle.ToEETypePtr() == value.EETypePtr)) throw new ArgumentException(SR.Format(SR.Arg_EnumUnderlyingTypeAndObjectMustBeSameType, value.GetType(), enumInfo.UnderlyingType)); } if (enumInfo == null) { if (!enumType.IsEnum) throw new ArgumentException(SR.Arg_MustBeEnum); enumInfo = GetEnumInfo(enumType); } String nameOrNull = GetNameIfAny(enumInfo, rawValue); return nameOrNull != null; } } public static Object Parse(Type enumType, String value) { return Parse(enumType, value, ignoreCase: false); } public static Object Parse(Type enumType, String value, bool ignoreCase) { Object result; Exception exception; if (!TryParseEnum(enumType, value, ignoreCase, out result, out exception)) throw exception; return result; } public static TEnum Parse<TEnum>(String value) where TEnum : struct { return Parse<TEnum>(value, ignoreCase: false); } public static TEnum Parse<TEnum>(String value, bool ignoreCase) where TEnum : struct { Object result; Exception exception; if (!TryParseEnum(typeof(TEnum), value, ignoreCase, out result, out exception)) throw exception; return (TEnum)result; } // // Non-boxing overloads for Enum.ToObject(). // // The underlying integer type of the enum does not have to match the type of "value." If // the enum type is larger, this api does a value-preserving widening if possible (or a 2's complement // conversion if not.) If the enum type is smaller, the api discards the higher order bits. // Either way, no exception is thrown upon overflow. // [CLSCompliant(false)] public static object ToObject(Type enumType, sbyte value) => ToObjectWorker(enumType, value); public static object ToObject(Type enumType, byte value) => ToObjectWorker(enumType, value); [CLSCompliant(false)] public static object ToObject(Type enumType, ushort value) => ToObjectWorker(enumType, value); public static object ToObject(Type enumType, short value) => ToObjectWorker(enumType, value); [CLSCompliant(false)] public static object ToObject(Type enumType, uint value) => ToObjectWorker(enumType, value); public static object ToObject(Type enumType, int value) => ToObjectWorker(enumType, value); [CLSCompliant(false)] public static object ToObject(Type enumType, ulong value) => ToObjectWorker(enumType, (long)value); public static object ToObject(Type enumType, long value) => ToObjectWorker(enumType, value); // These are needed to service ToObject(Type, Object). private static object ToObject(Type enumType, char value) => ToObjectWorker(enumType, value); private static object ToObject(Type enumType, bool value) => ToObjectWorker(enumType, value ? 1 : 0); // Common helper for the non-boxing Enum.ToObject() overloads. private static object ToObjectWorker(Type enumType, long value) { if (enumType == null) throw new ArgumentNullException(nameof(enumType)); if (!enumType.IsEnum) throw new ArgumentException(SR.Arg_MustBeEnum, nameof(enumType)); if (!enumType.IsRuntimeImplemented()) throw new ArgumentException(SR.Arg_MustBeType, nameof(enumType)); // Check for the unfortunate "typeof(Outer<>).InnerEnum" corner case. if (enumType.ContainsGenericParameters) throw new InvalidOperationException(SR.Format(SR.Arg_OpenType, enumType.ToString())); EETypePtr enumEEType = enumType.TypeHandle.ToEETypePtr(); unsafe { byte* pValue = (byte*)&value; AdjustForEndianness(ref pValue, enumEEType); return RuntimeImports.RhBox(enumEEType, pValue); } } public static Object ToObject(Type enumType, Object value) { if (value == null) throw new ArgumentNullException(nameof(value)); Contract.EndContractBlock(); // Delegate rest of error checking to the other functions TypeCode typeCode = Convert.GetTypeCode(value); switch (typeCode) { case TypeCode.Int32: return ToObject(enumType, (int)value); case TypeCode.SByte: return ToObject(enumType, (sbyte)value); case TypeCode.Int16: return ToObject(enumType, (short)value); case TypeCode.Int64: return ToObject(enumType, (long)value); case TypeCode.UInt32: return ToObject(enumType, (uint)value); case TypeCode.Byte: return ToObject(enumType, (byte)value); case TypeCode.UInt16: return ToObject(enumType, (ushort)value); case TypeCode.UInt64: return ToObject(enumType, (ulong)value); case TypeCode.Char: return ToObject(enumType, (char)value); case TypeCode.Boolean: return ToObject(enumType, (bool)value); default: // All unsigned types will be directly cast throw new ArgumentException(SR.Arg_MustBeEnumBaseTypeOrEnum, nameof(value)); } } public static bool TryParse(Type enumType, String value, bool ignoreCase, out Object result) { Exception exception; return TryParseEnum(enumType, value, ignoreCase, out result, out exception); } public static bool TryParse(Type enumType, String value, out Object result) { Exception exception; return TryParseEnum(enumType, value, false, out result, out exception); } public static bool TryParse<TEnum>(String value, bool ignoreCase, out TEnum result) where TEnum : struct { Exception exception; Object tempResult; if (!TryParseEnum(typeof(TEnum), value, ignoreCase, out tempResult, out exception)) { result = default(TEnum); return false; } result = (TEnum)tempResult; return true; } public static bool TryParse<TEnum>(String value, out TEnum result) where TEnum : struct { return TryParse<TEnum>(value, false, out result); } public override String ToString() { try { return this.ToString("G"); } catch (Exception) { return this.LastResortToString; } } public String ToString(String format) { if (format == null || format.Length == 0) format = "G"; EnumInfo enumInfo = GetEnumInfo(this.GetType()); // Project N port note: If Reflection info isn't available, fallback to ToString() which will substitute a numeric value for the "correct" output. // This scenario has been hit frequently when throwing exceptions formatted with error strings containing enum substitations. // To avoid replacing the masking the actual exception with an uninteresting MissingMetadataException, we choose instead // to return a base-effort string. if (enumInfo == null) return this.LastResortToString; return Format(enumInfo, this, format); } public String ToString(String format, IFormatProvider provider) { return ToString(format); } [Obsolete("The provider argument is not used. Please use ToString().")] public String ToString(IFormatProvider provider) { return ToString(); } private static EnumInfo GetEnumInfo(Type enumType) { Debug.Assert(enumType != null); Debug.Assert(enumType.IsRuntimeImplemented()); Debug.Assert(enumType.IsEnum); return ReflectionAugments.ReflectionCoreCallbacks.GetEnumInfo(enumType); } // // Checks if value.GetType() matches enumType exactly. // private static bool ValueTypeMatchesEnumType(Type enumType, Object value) { EETypePtr enumEEType; if (!enumType.TryGetEEType(out enumEEType)) return false; if (!(enumEEType == value.EETypePtr)) return false; return true; } // Exported for use by legacy user-defined Type Enum apis. internal static ulong ToUInt64(object value) { ulong result; if (!TryGetUnboxedValueOfEnumOrInteger(value, out result)) throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType); return result; } // // Note: This works on both Enum's and underlying integer values. // // // This returns the underlying enum values as "ulong" regardless of the actual underlying type. Signed integral // types get sign-extended into the 64-bit value, unsigned types get zero-extended. // // The return value is "bool" if "value" is not an enum or an "integer type" as defined by the BCL Enum apis. // private static bool TryGetUnboxedValueOfEnumOrInteger(Object value, out ulong result) { EETypePtr eeType = value.EETypePtr; // For now, this check is required to flush out pointers. if (!eeType.IsDefType) { result = 0; return false; } RuntimeImports.RhCorElementType corElementType = eeType.CorElementType; ref byte pValue = ref value.GetRawData(); switch (corElementType) { case RuntimeImports.RhCorElementType.ELEMENT_TYPE_BOOLEAN: result = Unsafe.As<byte, bool>(ref pValue) ? 1UL : 0UL; return true; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_CHAR: result = (ulong)(long)Unsafe.As<byte, char>(ref pValue); return true; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I1: result = (ulong)(long)Unsafe.As<byte, sbyte>(ref pValue); return true; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U1: result = (ulong)(long)Unsafe.As<byte, byte>(ref pValue); return true; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I2: result = (ulong)(long)Unsafe.As<byte, short>(ref pValue); return true; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U2: result = (ulong)(long)Unsafe.As<byte, ushort>(ref pValue); return true; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I4: result = (ulong)(long)Unsafe.As<byte, int>(ref pValue); return true; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U4: result = (ulong)(long)Unsafe.As<byte, uint>(ref pValue); return true; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I8: result = (ulong)(long)Unsafe.As<byte, long>(ref pValue); return true; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U8: result = (ulong)(long)Unsafe.As<byte, ulong>(ref pValue); return true; default: result = 0; return false; } } // // Look up a name for rawValue if a matching one exists. Returns null if no matching name exists. // private static String GetNameIfAny(EnumInfo enumInfo, ulong rawValue) { KeyValuePair<String, ulong>[] namesAndValues = enumInfo.NamesAndValues; KeyValuePair<String, ulong> searchKey = new KeyValuePair<String, ulong>(null, rawValue); int index = Array.BinarySearch<KeyValuePair<String, ulong>>(namesAndValues, searchKey, s_nameAndValueComparer); if (index < 0) return null; return namesAndValues[index].Key; } // // Common funnel for Enum.Parse methods. // private static bool TryParseEnum(Type enumType, String value, bool ignoreCase, out Object result, out Exception exception) { exception = null; result = null; if (enumType == null) throw new ArgumentNullException(nameof(enumType)); if (!enumType.IsRuntimeImplemented()) throw new ArgumentException(SR.Arg_MustBeType, nameof(enumType)); if (!enumType.IsEnum) throw new ArgumentException(SR.Arg_MustBeEnum, nameof(enumType)); if (value == null) { exception = new ArgumentNullException(nameof(value)); return false; } int firstNonWhitespaceIndex = -1; for (int i = 0; i < value.Length; i++) { if (!char.IsWhiteSpace(value[i])) { firstNonWhitespaceIndex = i; break; } } if (firstNonWhitespaceIndex == -1) { exception = new ArgumentException(SR.Arg_MustContainEnumInfo); return false; } // Check for the unfortunate "typeof(Outer<>).InnerEnum" corner case. if (enumType.ContainsGenericParameters) throw new InvalidOperationException(SR.Format(SR.Arg_OpenType, enumType.ToString())); EETypePtr enumEEType = enumType.TypeHandle.ToEETypePtr(); if (TryParseAsInteger(enumEEType, value, firstNonWhitespaceIndex, out result)) return true; if (StillLooksLikeInteger(value, firstNonWhitespaceIndex)) { exception = new OverflowException(); return false; } // Parse as string. Now (and only now) do we look for metadata information. EnumInfo enumInfo = GetEnumInfo(enumType); ulong v = 0; // Port note: The docs are silent on how multiple matches are resolved when doing case-insensitive parses. // The desktop's ad-hoc behavior is to pick the one with the smallest value after doing a value-preserving cast // to a ulong, so we'll follow that here. StringComparison comparison = ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; KeyValuePair<String, ulong>[] actualNamesAndValues = enumInfo.NamesAndValues; int valueIndex = firstNonWhitespaceIndex; while (valueIndex <= value.Length) // '=' is to handle invalid case of an ending comma { // Find the next separator, if there is one, otherwise the end of the string. int endIndex = value.IndexOf(',', valueIndex); if (endIndex == -1) { endIndex = value.Length; } // Shift the starting and ending indices to eliminate whitespace int endIndexNoWhitespace = endIndex; while (valueIndex < endIndex && char.IsWhiteSpace(value[valueIndex])) valueIndex++; while (endIndexNoWhitespace > valueIndex && char.IsWhiteSpace(value[endIndexNoWhitespace - 1])) endIndexNoWhitespace--; int valueSubstringLength = endIndexNoWhitespace - valueIndex; // Try to match this substring against each enum name bool foundMatch = false; foreach (KeyValuePair<String, ulong> kv in actualNamesAndValues) { String actualName = kv.Key; if (actualName.Length == valueSubstringLength && String.Compare(actualName, 0, value, valueIndex, valueSubstringLength, comparison) == 0) { v |= kv.Value; foundMatch = true; break; } } if (!foundMatch) { exception = new ArgumentException(SR.Format(SR.Arg_EnumValueNotFound, value)); return false; } // Move our pointer to the ending index to go again. valueIndex = endIndex + 1; } unsafe { result = RuntimeImports.RhBox(enumEEType, &v); //@todo: Not compatible with big-endian platforms. } return true; } private static bool TryParseAsInteger(EETypePtr enumEEType, String value, int valueOffset, out Object result) { Debug.Assert(value != null, "Expected non-null value"); Debug.Assert(value.Length > 0, "Expected non-empty value"); Debug.Assert(valueOffset >= 0 && valueOffset < value.Length, "Expected valueOffset to be within value"); result = null; char firstNonWhitespaceChar = value[valueOffset]; if (!(Char.IsDigit(firstNonWhitespaceChar) || firstNonWhitespaceChar == '+' || firstNonWhitespaceChar == '-')) return false; RuntimeImports.RhCorElementType corElementType = enumEEType.CorElementType; value = value.Trim(); unsafe { switch (corElementType) { case RuntimeImports.RhCorElementType.ELEMENT_TYPE_BOOLEAN: { Boolean v; if (!Boolean.TryParse(value, out v)) return false; result = RuntimeImports.RhBox(enumEEType, &v); return true; } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_CHAR: { Char v; if (!Char.TryParse(value, out v)) return false; result = RuntimeImports.RhBox(enumEEType, &v); return true; } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I1: { SByte v; if (!SByte.TryParse(value, out v)) return false; result = RuntimeImports.RhBox(enumEEType, &v); return true; } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U1: { Byte v; if (!Byte.TryParse(value, out v)) return false; result = RuntimeImports.RhBox(enumEEType, &v); return true; } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I2: { Int16 v; if (!Int16.TryParse(value, out v)) return false; result = RuntimeImports.RhBox(enumEEType, &v); return true; } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U2: { UInt16 v; if (!UInt16.TryParse(value, out v)) return false; result = RuntimeImports.RhBox(enumEEType, &v); return true; } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I4: { Int32 v; if (!Int32.TryParse(value, out v)) return false; result = RuntimeImports.RhBox(enumEEType, &v); return true; } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U4: { UInt32 v; if (!UInt32.TryParse(value, out v)) return false; result = RuntimeImports.RhBox(enumEEType, &v); return true; } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I8: { Int64 v; if (!Int64.TryParse(value, out v)) return false; result = RuntimeImports.RhBox(enumEEType, &v); return true; } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U8: { UInt64 v; if (!UInt64.TryParse(value, out v)) return false; result = RuntimeImports.RhBox(enumEEType, &v); return true; } default: throw new NotSupportedException(); } } } private static bool StillLooksLikeInteger(String value, int index) { if (index != value.Length && (value[index] == '-' || value[index] == '+')) { index++; } if (index == value.Length || !char.IsDigit(value[index])) return false; index++; while (index != value.Length && char.IsDigit(value[index])) { index++; } while (index != value.Length && char.IsWhiteSpace(value[index])) { index++; } return index == value.Length; } [Conditional("BIGENDIAN")] private static unsafe void AdjustForEndianness(ref byte* pValue, EETypePtr enumEEType) { // On Debug builds, include the big-endian code to help deter bitrot (the "Conditional("BIGENDIAN")" will prevent it from executing on little-endian). // On Release builds, exclude code to deter IL bloat and toolchain work. #if BIGENDIAN || DEBUG RuntimeImports.RhCorElementType corElementType = enumEEType.CorElementType; switch (corElementType) { case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I1: case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U1: pValue += sizeof(long) - sizeof(byte); break; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I2: case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U2: pValue += sizeof(long) - sizeof(short); break; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I4: case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U4: pValue += sizeof(long) - sizeof(int); break; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I8: case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U8: break; default: throw new NotSupportedException(); } #endif //BIGENDIAN || DEBUG } // // Sort comparer for NamesAndValues // private class NamesAndValueComparer : IComparer<KeyValuePair<String, ulong>> { public int Compare(KeyValuePair<String, ulong> kv1, KeyValuePair<String, ulong> kv2) { ulong x = kv1.Value; ulong y = kv2.Value; if (x < y) return -1; else if (x > y) return 1; else return 0; } } private static NamesAndValueComparer s_nameAndValueComparer = new NamesAndValueComparer(); private String LastResortToString { get { return String.Format("{0}", GetValue()); } } #region IConvertible public TypeCode GetTypeCode() { Type enumType = this.GetType(); Type underlyingType = GetUnderlyingType(enumType); if (underlyingType == typeof(Int32)) { return TypeCode.Int32; } if (underlyingType == typeof(sbyte)) { return TypeCode.SByte; } if (underlyingType == typeof(Int16)) { return TypeCode.Int16; } if (underlyingType == typeof(Int64)) { return TypeCode.Int64; } if (underlyingType == typeof(UInt32)) { return TypeCode.UInt32; } if (underlyingType == typeof(byte)) { return TypeCode.Byte; } if (underlyingType == typeof(UInt16)) { return TypeCode.UInt16; } if (underlyingType == typeof(UInt64)) { return TypeCode.UInt64; } if (underlyingType == typeof(Boolean)) { return TypeCode.Boolean; } if (underlyingType == typeof(Char)) { return TypeCode.Char; } Debug.Assert(false, "Unknown underlying type."); throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType); } bool IConvertible.ToBoolean(IFormatProvider provider) { return Convert.ToBoolean(GetValue(), CultureInfo.CurrentCulture); } char IConvertible.ToChar(IFormatProvider provider) { return Convert.ToChar(GetValue(), CultureInfo.CurrentCulture); } sbyte IConvertible.ToSByte(IFormatProvider provider) { return Convert.ToSByte(GetValue(), CultureInfo.CurrentCulture); } byte IConvertible.ToByte(IFormatProvider provider) { return Convert.ToByte(GetValue(), CultureInfo.CurrentCulture); } short IConvertible.ToInt16(IFormatProvider provider) { return Convert.ToInt16(GetValue(), CultureInfo.CurrentCulture); } ushort IConvertible.ToUInt16(IFormatProvider provider) { return Convert.ToUInt16(GetValue(), CultureInfo.CurrentCulture); } int IConvertible.ToInt32(IFormatProvider provider) { return Convert.ToInt32(GetValue(), CultureInfo.CurrentCulture); } uint IConvertible.ToUInt32(IFormatProvider provider) { return Convert.ToUInt32(GetValue(), CultureInfo.CurrentCulture); } long IConvertible.ToInt64(IFormatProvider provider) { return Convert.ToInt64(GetValue(), CultureInfo.CurrentCulture); } ulong IConvertible.ToUInt64(IFormatProvider provider) { return Convert.ToUInt64(GetValue(), CultureInfo.CurrentCulture); } float IConvertible.ToSingle(IFormatProvider provider) { return Convert.ToSingle(GetValue(), CultureInfo.CurrentCulture); } double IConvertible.ToDouble(IFormatProvider provider) { return Convert.ToDouble(GetValue(), CultureInfo.CurrentCulture); } Decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(GetValue(), CultureInfo.CurrentCulture); } DateTime IConvertible.ToDateTime(IFormatProvider provider) { throw new InvalidCastException(String.Format(SR.InvalidCast_FromTo, "Enum", "DateTime")); } Object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } #endregion } }
using System; using System.Text; using System.Data; using FirebirdSql.Data.FirebirdClient; namespace MyMeta.Firebird { #if ENTERPRISE using System.Runtime.InteropServices; [ComVisible(true), ClassInterface(ClassInterfaceType.AutoDual), ComDefaultInterface(typeof(IParameters))] #endif public class FirebirdParameters : Parameters { internal DataColumn f_TypeNameComplete = null; public FirebirdParameters() { } override internal void LoadAll() { try { FbConnection cn = new FirebirdSql.Data.FirebirdClient.FbConnection(this._dbRoot.ConnectionString); FbDataAdapter adapter = new FbDataAdapter(BuildSql(this.Procedure.Name), cn); DataTable metaData = new DataTable(); adapter.Fill(metaData); metaData.Columns["PARAMETER_DIRECTION"].ColumnName = "PARAMETER_TYPE"; PopulateArray(metaData); FixupDataTypes(metaData); } catch(Exception ex) { string m = ex.Message; } } private void FixupDataTypes(DataTable metaData) { FbConnection cn = null; try { int dialect = 1; cn = new FirebirdSql.Data.FirebirdClient.FbConnection(this._dbRoot.ConnectionString); cn.Open(); try { FbConnectionStringBuilder cnString = new FbConnectionStringBuilder(cn.ConnectionString); dialect = cnString.Dialect; } catch {} int count = this._array.Count; Parameter p = null; if(count > 0) { // Dimension Data string dimSelect = "select r.rdb$field_name AS Name , d.rdb$dimension as DIM, d.rdb$lower_bound as L, d.rdb$upper_bound as U from rdb$fields f, rdb$field_dimensions d, rdb$relation_fields r where r.rdb$relation_name='" + this.Procedure.Name + "' and f.rdb$field_name = d.rdb$field_name and f.rdb$field_name=r.rdb$field_source order by d.rdb$dimension;"; FbDataAdapter dimAdapter = new FbDataAdapter(dimSelect, cn); DataTable dimTable = new DataTable(); dimAdapter.Fill(dimTable); p = this._array[0] as Parameter; f_TypeName = new DataColumn("TYPE_NAME", typeof(string)); p._row.Table.Columns.Add(f_TypeName); f_TypeNameComplete = new DataColumn("TYPE_NAME_COMPLETE", typeof(string)); p._row.Table.Columns.Add(f_TypeNameComplete); short ftype = 0; short dim = 0; DataRowCollection rows = metaData.Rows; for( int index = 0; index < count; index++) { p = (Parameter)this[index]; if(p._row["NUMERIC_PRECISION"] == System.DBNull.Value) { p._row["NUMERIC_PRECISION"] = p._row["PARAMETER_SIZE"]; } p._row["PARAMETER_NAME"] = (p._row["PARAMETER_NAME"] as String).Trim(); int dir = (int)p._row["PARAMETER_TYPE"]; p._row["PARAMETER_TYPE"] = dir == 0 ? 1 : 3; // Step 1: DataTypeName ftype = (short)rows[index]["FIELD_TYPE"]; switch(ftype) { case 7: p._row["TYPE_NAME"] = "SMALLINT"; break; case 8: p._row["TYPE_NAME"] = "INTEGER"; break; case 9: p._row["TYPE_NAME"] = "QUAD"; break; case 10: p._row["TYPE_NAME"] = "FLOAT"; break; case 11: p._row["TYPE_NAME"] = "DOUBLE PRECISION"; break; case 12: p._row["TYPE_NAME"] = "DATE"; break; case 13: p._row["TYPE_NAME"] = "TIME"; break; case 14: p._row["TYPE_NAME"] = "CHAR"; break; case 16: if(p.NumericScale < 0) p._row["TYPE_NAME"] = "NUMERIC"; else p._row["TYPE_NAME"] = "BIGINT"; break; case 27: p._row["TYPE_NAME"] = "DOUBLE PRECISION"; break; case 35: if(dialect > 2) { p._row["TYPE_NAME"] = "TIMESTAMP"; } else { p._row["TYPE_NAME"] = "DATE"; } break; case 37: p._row["TYPE_NAME"] = "VARCHAR"; break; case 40: p._row["TYPE_NAME"] = "CSTRING"; break; case 261: short subtype = (short)rows[index]["PARAMETER_SUB_TYPE"]; switch(subtype) { case 0: p._row["TYPE_NAME"] = "BLOB(BINARY)"; break; case 1: p._row["TYPE_NAME"] = "BLOB(TEXT)"; break; default: p._row["TYPE_NAME"] = "BLOB(UNKNOWN)"; break; } break; } int scale = p.NumericScale; if(scale < 0) { p._row["TYPE_NAME"] = "NUMERIC"; p._row["NUMERIC_SCALE"] = Math.Abs(scale); } // Step 2: DataTypeNameComplete string s = p._row["TYPE_NAME"] as string; switch(s) { case "VARCHAR": case "CHAR": p._row["TYPE_NAME_COMPLETE"] = s + "(" + p.CharacterMaxLength + ")"; break; case "NUMERIC": switch((int)p._row["PARAMETER_SIZE"]) { case 2: p._row["TYPE_NAME_COMPLETE"] = s + "(4, " + p.NumericScale.ToString() + ")"; break; case 4: p._row["TYPE_NAME_COMPLETE"] = s + "(9, " + p.NumericScale.ToString() + ")"; break; case 8: p._row["TYPE_NAME_COMPLETE"] = s + "(15, " + p.NumericScale.ToString() + ")"; break; default: p._row["TYPE_NAME_COMPLETE"] = "NUMERIC(18,0)"; break; } break; case "BLOB(TEXT)": case "BLOB(BINARY)": p._row["TYPE_NAME_COMPLETE"] = "BLOB"; break; default: p._row["TYPE_NAME_COMPLETE"] = s; break; } s = p._row["TYPE_NAME_COMPLETE"] as string; dim = 0; object o = rows[index]["DIM"]; if(o != DBNull.Value) { dim = (short)o; } if(dim > 0) { dimTable.DefaultView.RowFilter = "Name = '" + p.Name + "'"; dimTable.DefaultView.Sort = "DIM"; string a = "["; bool bFirst = true; foreach(DataRowView vrow in dimTable.DefaultView) { DataRow row = vrow.Row; if(!bFirst) a += ","; a += row["L"].ToString() + ":" + row["U"].ToString(); bFirst = false; } a += "]"; p._row["TYPE_NAME_COMPLETE"] = s + a; p._row["TYPE_NAME"] = p._row["TYPE_NAME"] + ":A"; } } } } catch(Exception ex) { string e = ex.Message; } if(cn != null) { cn.Close(); } } private string BuildSql(string procedureName) { StringBuilder sql = new StringBuilder(); sql.Append( @"SELECT " + "pp.rdb$procedure_name AS PROCEDURE_NAME, " + "pp.rdb$parameter_name AS PARAMETER_NAME, " + "fld.rdb$field_sub_type AS PARAMETER_SUB_TYPE, " + "pp.rdb$parameter_number AS ORDINAL_POSITION, " + "cast(pp.rdb$parameter_type AS integer) AS PARAMETER_DIRECTION, " + "cast(fld.rdb$field_length AS integer) AS PARAMETER_SIZE, " + "cast(fld.rdb$field_precision AS integer) AS NUMERIC_PRECISION, " + "cast(fld.rdb$field_scale AS integer) AS NUMERIC_SCALE, " + "cs.rdb$character_set_name AS CHARACTER_SET_NAME, " + "coll.rdb$collation_name AS COLLATION_NAME, " + "pp.rdb$description AS DESCRIPTION, " + "fld.rdb$field_type AS FIELD_TYPE, " + "d.rdb$dimension AS DIM " + "FROM " + "rdb$procedure_parameters pp " + "left join rdb$fields fld ON pp.rdb$field_source = fld.rdb$field_name " + "left join rdb$field_dimensions d ON fld.rdb$field_name = d.rdb$field_name " + "left join rdb$character_sets cs ON cs.rdb$character_set_id = fld.rdb$character_set_id " + "left join rdb$collations coll ON (coll.rdb$collation_id = fld.rdb$collation_id AND coll.rdb$character_set_id = fld.rdb$character_set_id) " + "WHERE pp.rdb$procedure_name = '" + procedureName + "'" + " ORDER BY pp.rdb$procedure_name, pp.rdb$parameter_type, pp.rdb$parameter_number"); return sql.ToString(); } } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; namespace DalSic { /// <summary> /// Strongly-typed collection for the SysAntecedenteEnfermedad class. /// </summary> [Serializable] public partial class SysAntecedenteEnfermedadCollection : ActiveList<SysAntecedenteEnfermedad, SysAntecedenteEnfermedadCollection> { public SysAntecedenteEnfermedadCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>SysAntecedenteEnfermedadCollection</returns> public SysAntecedenteEnfermedadCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { SysAntecedenteEnfermedad o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the Sys_AntecedenteEnfermedad table. /// </summary> [Serializable] public partial class SysAntecedenteEnfermedad : ActiveRecord<SysAntecedenteEnfermedad>, IActiveRecord { #region .ctors and Default Settings public SysAntecedenteEnfermedad() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public SysAntecedenteEnfermedad(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public SysAntecedenteEnfermedad(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public SysAntecedenteEnfermedad(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("Sys_AntecedenteEnfermedad", TableType.Table, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarIdAntecedenteEnfermedad = new TableSchema.TableColumn(schema); colvarIdAntecedenteEnfermedad.ColumnName = "idAntecedenteEnfermedad"; colvarIdAntecedenteEnfermedad.DataType = DbType.Int32; colvarIdAntecedenteEnfermedad.MaxLength = 0; colvarIdAntecedenteEnfermedad.AutoIncrement = true; colvarIdAntecedenteEnfermedad.IsNullable = false; colvarIdAntecedenteEnfermedad.IsPrimaryKey = true; colvarIdAntecedenteEnfermedad.IsForeignKey = false; colvarIdAntecedenteEnfermedad.IsReadOnly = false; colvarIdAntecedenteEnfermedad.DefaultSetting = @""; colvarIdAntecedenteEnfermedad.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdAntecedenteEnfermedad); TableSchema.TableColumn colvarIdEfector = new TableSchema.TableColumn(schema); colvarIdEfector.ColumnName = "idEfector"; colvarIdEfector.DataType = DbType.Int32; colvarIdEfector.MaxLength = 0; colvarIdEfector.AutoIncrement = false; colvarIdEfector.IsNullable = false; colvarIdEfector.IsPrimaryKey = false; colvarIdEfector.IsForeignKey = false; colvarIdEfector.IsReadOnly = false; colvarIdEfector.DefaultSetting = @""; colvarIdEfector.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdEfector); TableSchema.TableColumn colvarIdPaciente = new TableSchema.TableColumn(schema); colvarIdPaciente.ColumnName = "idPaciente"; colvarIdPaciente.DataType = DbType.Int32; colvarIdPaciente.MaxLength = 0; colvarIdPaciente.AutoIncrement = false; colvarIdPaciente.IsNullable = false; colvarIdPaciente.IsPrimaryKey = false; colvarIdPaciente.IsForeignKey = true; colvarIdPaciente.IsReadOnly = false; colvarIdPaciente.DefaultSetting = @""; colvarIdPaciente.ForeignKeyTableName = "Sys_Paciente"; schema.Columns.Add(colvarIdPaciente); TableSchema.TableColumn colvarFechaRegistro = new TableSchema.TableColumn(schema); colvarFechaRegistro.ColumnName = "FechaRegistro"; colvarFechaRegistro.DataType = DbType.DateTime; colvarFechaRegistro.MaxLength = 0; colvarFechaRegistro.AutoIncrement = false; colvarFechaRegistro.IsNullable = false; colvarFechaRegistro.IsPrimaryKey = false; colvarFechaRegistro.IsForeignKey = false; colvarFechaRegistro.IsReadOnly = false; colvarFechaRegistro.DefaultSetting = @""; colvarFechaRegistro.ForeignKeyTableName = ""; schema.Columns.Add(colvarFechaRegistro); TableSchema.TableColumn colvarFamiliar = new TableSchema.TableColumn(schema); colvarFamiliar.ColumnName = "Familiar"; colvarFamiliar.DataType = DbType.Boolean; colvarFamiliar.MaxLength = 0; colvarFamiliar.AutoIncrement = false; colvarFamiliar.IsNullable = true; colvarFamiliar.IsPrimaryKey = false; colvarFamiliar.IsForeignKey = false; colvarFamiliar.IsReadOnly = false; colvarFamiliar.DefaultSetting = @""; colvarFamiliar.ForeignKeyTableName = ""; schema.Columns.Add(colvarFamiliar); TableSchema.TableColumn colvarTipoParentezco = new TableSchema.TableColumn(schema); colvarTipoParentezco.ColumnName = "TipoParentezco"; colvarTipoParentezco.DataType = DbType.AnsiString; colvarTipoParentezco.MaxLength = 50; colvarTipoParentezco.AutoIncrement = false; colvarTipoParentezco.IsNullable = true; colvarTipoParentezco.IsPrimaryKey = false; colvarTipoParentezco.IsForeignKey = false; colvarTipoParentezco.IsReadOnly = false; colvarTipoParentezco.DefaultSetting = @""; colvarTipoParentezco.ForeignKeyTableName = ""; schema.Columns.Add(colvarTipoParentezco); TableSchema.TableColumn colvarCODCIE10 = new TableSchema.TableColumn(schema); colvarCODCIE10.ColumnName = "CODCIE10"; colvarCODCIE10.DataType = DbType.Int32; colvarCODCIE10.MaxLength = 0; colvarCODCIE10.AutoIncrement = false; colvarCODCIE10.IsNullable = false; colvarCODCIE10.IsPrimaryKey = false; colvarCODCIE10.IsForeignKey = true; colvarCODCIE10.IsReadOnly = false; colvarCODCIE10.DefaultSetting = @""; colvarCODCIE10.ForeignKeyTableName = "Sys_CIE10"; schema.Columns.Add(colvarCODCIE10); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("Sys_AntecedenteEnfermedad",schema); } } #endregion #region Props [XmlAttribute("IdAntecedenteEnfermedad")] [Bindable(true)] public int IdAntecedenteEnfermedad { get { return GetColumnValue<int>(Columns.IdAntecedenteEnfermedad); } set { SetColumnValue(Columns.IdAntecedenteEnfermedad, value); } } [XmlAttribute("IdEfector")] [Bindable(true)] public int IdEfector { get { return GetColumnValue<int>(Columns.IdEfector); } set { SetColumnValue(Columns.IdEfector, value); } } [XmlAttribute("IdPaciente")] [Bindable(true)] public int IdPaciente { get { return GetColumnValue<int>(Columns.IdPaciente); } set { SetColumnValue(Columns.IdPaciente, value); } } [XmlAttribute("FechaRegistro")] [Bindable(true)] public DateTime FechaRegistro { get { return GetColumnValue<DateTime>(Columns.FechaRegistro); } set { SetColumnValue(Columns.FechaRegistro, value); } } [XmlAttribute("Familiar")] [Bindable(true)] public bool? Familiar { get { return GetColumnValue<bool?>(Columns.Familiar); } set { SetColumnValue(Columns.Familiar, value); } } [XmlAttribute("TipoParentezco")] [Bindable(true)] public string TipoParentezco { get { return GetColumnValue<string>(Columns.TipoParentezco); } set { SetColumnValue(Columns.TipoParentezco, value); } } [XmlAttribute("CODCIE10")] [Bindable(true)] public int CODCIE10 { get { return GetColumnValue<int>(Columns.CODCIE10); } set { SetColumnValue(Columns.CODCIE10, value); } } #endregion #region ForeignKey Properties /// <summary> /// Returns a SysCIE10 ActiveRecord object related to this SysAntecedenteEnfermedad /// /// </summary> public DalSic.SysCIE10 SysCIE10 { get { return DalSic.SysCIE10.FetchByID(this.CODCIE10); } set { SetColumnValue("CODCIE10", value.Id); } } /// <summary> /// Returns a SysPaciente ActiveRecord object related to this SysAntecedenteEnfermedad /// /// </summary> public DalSic.SysPaciente SysPaciente { get { return DalSic.SysPaciente.FetchByID(this.IdPaciente); } set { SetColumnValue("idPaciente", value.IdPaciente); } } #endregion //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(int varIdEfector,int varIdPaciente,DateTime varFechaRegistro,bool? varFamiliar,string varTipoParentezco,int varCODCIE10) { SysAntecedenteEnfermedad item = new SysAntecedenteEnfermedad(); item.IdEfector = varIdEfector; item.IdPaciente = varIdPaciente; item.FechaRegistro = varFechaRegistro; item.Familiar = varFamiliar; item.TipoParentezco = varTipoParentezco; item.CODCIE10 = varCODCIE10; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(int varIdAntecedenteEnfermedad,int varIdEfector,int varIdPaciente,DateTime varFechaRegistro,bool? varFamiliar,string varTipoParentezco,int varCODCIE10) { SysAntecedenteEnfermedad item = new SysAntecedenteEnfermedad(); item.IdAntecedenteEnfermedad = varIdAntecedenteEnfermedad; item.IdEfector = varIdEfector; item.IdPaciente = varIdPaciente; item.FechaRegistro = varFechaRegistro; item.Familiar = varFamiliar; item.TipoParentezco = varTipoParentezco; item.CODCIE10 = varCODCIE10; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn IdAntecedenteEnfermedadColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn IdEfectorColumn { get { return Schema.Columns[1]; } } public static TableSchema.TableColumn IdPacienteColumn { get { return Schema.Columns[2]; } } public static TableSchema.TableColumn FechaRegistroColumn { get { return Schema.Columns[3]; } } public static TableSchema.TableColumn FamiliarColumn { get { return Schema.Columns[4]; } } public static TableSchema.TableColumn TipoParentezcoColumn { get { return Schema.Columns[5]; } } public static TableSchema.TableColumn CODCIE10Column { get { return Schema.Columns[6]; } } #endregion #region Columns Struct public struct Columns { public static string IdAntecedenteEnfermedad = @"idAntecedenteEnfermedad"; public static string IdEfector = @"idEfector"; public static string IdPaciente = @"idPaciente"; public static string FechaRegistro = @"FechaRegistro"; public static string Familiar = @"Familiar"; public static string TipoParentezco = @"TipoParentezco"; public static string CODCIE10 = @"CODCIE10"; } #endregion #region Update PK Collections #endregion #region Deep Save #endregion } }
using System.Diagnostics; using Exceptionless.Core.Repositories; using Exceptionless.DateTimeExtensions; using Exceptionless.Helpers; using Exceptionless.Core.Models; using Exceptionless.Core.Models.Data; using Exceptionless.Tests.Utility; using Foundatio.Repositories; using Foundatio.Repositories.Utility; using Foundatio.Utility; using Xunit; using Xunit.Abstractions; using LogLevel = Microsoft.Extensions.Logging.LogLevel; namespace Exceptionless.Tests.Repositories; public sealed class EventRepositoryTests : IntegrationTestsBase { private readonly IEventRepository _repository; private readonly IStackRepository _stackRepository; public EventRepositoryTests(ITestOutputHelper output, AppWebHostFactory factory) : base(output, factory) { _repository = GetService<IEventRepository>(); _stackRepository = GetService<IStackRepository>(); } [Fact(Skip = "https://github.com/elastic/elasticsearch-net/issues/2463")] public async Task GetAsync() { Log.SetLogLevel<EventRepository>(LogLevel.Trace); var ev = await _repository.AddAsync(new PersistentEvent { CreatedUtc = SystemClock.UtcNow, Date = new DateTimeOffset(SystemClock.UtcNow.Date, TimeSpan.Zero), OrganizationId = TestConstants.OrganizationId, ProjectId = TestConstants.ProjectId, StackId = TestConstants.StackId, Type = Event.KnownTypes.Log, Count = Int32.MaxValue, Value = Decimal.MaxValue, Geo = "40,-70" }); Assert.Equal(ev, await _repository.GetByIdAsync(ev.Id)); } [Fact(Skip = "Performance Testing")] public async Task GetAsyncPerformanceAsync() { var ev = await _repository.AddAsync(new RandomEventGenerator().GeneratePersistent()); await RefreshDataAsync(); Assert.Equal(1, await _repository.CountAsync()); var sw = Stopwatch.StartNew(); const int MAX_ITERATIONS = 100; for (int i = 0; i < MAX_ITERATIONS; i++) { Assert.NotNull(await _repository.GetByIdAsync(ev.Id)); } sw.Stop(); _logger.LogInformation("{Duration:g}", sw.Elapsed); } [Fact] public async Task GetPagedAsync() { var events = new List<PersistentEvent>(); for (int i = 0; i < 6; i++) events.Add(EventData.GenerateEvent(projectId: TestConstants.ProjectId, organizationId: TestConstants.OrganizationId, stackId: TestConstants.StackId, occurrenceDate: SystemClock.UtcNow.Subtract(TimeSpan.FromMinutes(i)))); await _repository.AddAsync(events); await RefreshDataAsync(); Assert.Equal(events.Count, await _repository.CountAsync()); var results = await _repository.GetByOrganizationIdAsync(TestConstants.OrganizationId, o => o.PageNumber(2).PageLimit(2)); Assert.Equal(2, results.Documents.Count); Assert.Equal(results.Documents.First().Id, events[2].Id); Assert.Equal(results.Documents.Last().Id, events[3].Id); results = await _repository.GetByOrganizationIdAsync(TestConstants.OrganizationId, o => o.PageNumber(3).PageLimit(2)); Assert.Equal(2, results.Documents.Count); Assert.Equal(results.Documents.First().Id, events[4].Id); Assert.Equal(results.Documents.Last().Id, events[5].Id); } [Fact] public async Task GetPreviousEventIdInStackTestAsync() { await CreateDataAsync(); Log.SetLogLevel<StackRepository>(LogLevel.Trace); Log.SetLogLevel<EventRepository>(LogLevel.Trace); _logger.LogDebug("Actual order:"); foreach (var t in _ids) _logger.LogDebug("{Id}: {Date}", t.Item1, t.Item2.ToLongTimeString()); _logger.LogDebug(""); _logger.LogDebug("Sorted order:"); var sortedIds = _ids.OrderBy(t => t.Item2.Ticks).ThenBy(t => t.Item1).ToList(); foreach (var t in sortedIds) _logger.LogDebug("{Id}: {Date}", t.Item1, t.Item2.ToLongTimeString()); _logger.LogDebug(""); _logger.LogDebug("Tests:"); await RefreshDataAsync(); Assert.Equal(_ids.Count, await _repository.CountAsync()); for (int i = 0; i < sortedIds.Count; i++) { _logger.LogDebug("Current - {Id}: {Date}", sortedIds[i].Item1, sortedIds[i].Item2.ToLongTimeString()); if (i == 0) Assert.Null((await _repository.GetPreviousAndNextEventIdsAsync(sortedIds[i].Item1)).Previous); else Assert.Equal(sortedIds[i - 1].Item1, (await _repository.GetPreviousAndNextEventIdsAsync(sortedIds[i].Item1)).Previous); } } [Fact] public async Task GetNextEventIdInStackTestAsync() { await CreateDataAsync(); _logger.LogDebug("Actual order:"); foreach (var t in _ids) _logger.LogDebug("{Id}: {Date}", t.Item1, t.Item2.ToLongTimeString()); _logger.LogDebug(""); _logger.LogDebug("Sorted order:"); var sortedIds = _ids.OrderBy(t => t.Item2.Ticks).ThenBy(t => t.Item1).ToList(); foreach (var t in sortedIds) _logger.LogDebug("{Id}: {Date}", t.Item1, t.Item2.ToLongTimeString()); _logger.LogDebug(""); _logger.LogDebug("Tests:"); await RefreshDataAsync(); Assert.Equal(_ids.Count, await _repository.CountAsync()); for (int i = 0; i < sortedIds.Count; i++) { _logger.LogDebug("Current - {Id}: {Date}", sortedIds[i].Item1, sortedIds[i].Item2.ToLongTimeString()); string nextId = (await _repository.GetPreviousAndNextEventIdsAsync(sortedIds[i].Item1)).Next; if (i == sortedIds.Count - 1) Assert.Null(nextId); else Assert.Equal(sortedIds[i + 1].Item1, nextId); } } [Fact] public async Task CanGetPreviousAndNExtEventIdWithFilterTestAsync() { await CreateDataAsync(); Log.SetLogLevel<StackRepository>(LogLevel.Trace); Log.SetLogLevel<EventRepository>(LogLevel.Trace); var sortedIds = _ids.OrderBy(t => t.Item2.Ticks).ThenBy(t => t.Item1).ToList(); var result = await _repository.GetPreviousAndNextEventIdsAsync(sortedIds[1].Item1); Assert.Equal(sortedIds[0].Item1, result.Previous); Assert.Equal(sortedIds[2].Item1, result.Next); } [Fact] public async Task GetByReferenceIdAsync() { string referenceId = ObjectId.GenerateNewId().ToString(); await _repository.AddAsync(EventData.GenerateEvents(3, TestConstants.OrganizationId, TestConstants.ProjectId, TestConstants.StackId2, referenceId: referenceId).ToList()); await RefreshDataAsync(); var results = await _repository.GetByReferenceIdAsync(TestConstants.ProjectId, referenceId); Assert.True(results.Total > 0); Assert.NotNull(results.Documents.First()); Assert.Equal(referenceId, results.Documents.First().ReferenceId); } [Fact] public async Task GetOpenSessionsAsync() { var firstEvent = SystemClock.OffsetNow.Subtract(TimeSpan.FromMinutes(35)); var sessionLastActive35MinAgo = EventData.GenerateEvent(TestConstants.OrganizationId, TestConstants.ProjectId, TestConstants.StackId2, occurrenceDate: firstEvent, type: Event.KnownTypes.Session, sessionId: "opensession", generateData: false); var sessionLastActive34MinAgo = EventData.GenerateEvent(TestConstants.OrganizationId, TestConstants.ProjectId, TestConstants.StackId2, occurrenceDate: firstEvent, type: Event.KnownTypes.Session, sessionId: "opensession2", generateData: false); sessionLastActive34MinAgo.UpdateSessionStart(firstEvent.UtcDateTime.AddMinutes(1)); var sessionLastActive5MinAgo = EventData.GenerateEvent(TestConstants.OrganizationId, TestConstants.ProjectId, TestConstants.StackId2, occurrenceDate: firstEvent, type: Event.KnownTypes.Session, sessionId: "opensession3", generateData: false); sessionLastActive5MinAgo.UpdateSessionStart(firstEvent.UtcDateTime.AddMinutes(30)); var closedSession = EventData.GenerateEvent(TestConstants.OrganizationId, TestConstants.ProjectId, TestConstants.StackId2, occurrenceDate: firstEvent, type: Event.KnownTypes.Session, sessionId: "opensession", generateData: false); closedSession.UpdateSessionStart(firstEvent.UtcDateTime.AddMinutes(5), true); var events = new List<PersistentEvent> { sessionLastActive35MinAgo, sessionLastActive34MinAgo, sessionLastActive5MinAgo, closedSession }; await _repository.AddAsync(events); await RefreshDataAsync(); var results = await _repository.GetOpenSessionsAsync(SystemClock.UtcNow.SubtractMinutes(30)); Assert.Equal(3, results.Total); } [Fact] public async Task RemoveAllByClientIpAndDateAsync() { const string _clientIpAddress = "123.123.12.255"; const int NUMBER_OF_EVENTS_TO_CREATE = 50; var events = EventData.GenerateEvents(NUMBER_OF_EVENTS_TO_CREATE, TestConstants.OrganizationId, TestConstants.ProjectId, TestConstants.StackId2, startDate: SystemClock.UtcNow.SubtractDays(2), endDate: SystemClock.UtcNow).ToList(); events.ForEach(e => e.AddRequestInfo(new RequestInfo { ClientIpAddress = _clientIpAddress })); await _repository.AddAsync(events); await RefreshDataAsync(); events = (await _repository.GetByProjectIdAsync(TestConstants.ProjectId, o => o.PageLimit(NUMBER_OF_EVENTS_TO_CREATE))).Documents.ToList(); Assert.Equal(NUMBER_OF_EVENTS_TO_CREATE, events.Count); events.ForEach(e => { var ri = e.GetRequestInfo(); Assert.NotNull(ri); Assert.Equal(_clientIpAddress, ri.ClientIpAddress); }); await _repository.RemoveAllAsync(TestConstants.OrganizationId, _clientIpAddress, SystemClock.UtcNow.SubtractDays(3), SystemClock.UtcNow.AddDays(2)); await RefreshDataAsync(); events = (await _repository.GetByProjectIdAsync(TestConstants.ProjectId, o => o.PageLimit(NUMBER_OF_EVENTS_TO_CREATE))).Documents.ToList(); Assert.Empty(events); } private readonly List<Tuple<string, DateTime>> _ids = new List<Tuple<string, DateTime>>(); private async Task CreateDataAsync() { var baseDate = SystemClock.UtcNow.SubtractHours(1); var occurrenceDateStart = baseDate.AddMinutes(-30); var occurrenceDateMid = baseDate; var occurrenceDateEnd = baseDate.AddMinutes(30); await _stackRepository.AddAsync(StackData.GenerateStack(id: TestConstants.StackId, organizationId: TestConstants.OrganizationId, projectId: TestConstants.ProjectId)); var occurrenceDates = new List<DateTime> { occurrenceDateStart, occurrenceDateEnd, baseDate.AddMinutes(-10), baseDate.AddMinutes(-20), occurrenceDateMid, occurrenceDateMid, occurrenceDateMid, baseDate.AddMinutes(20), baseDate.AddMinutes(10), baseDate.AddSeconds(1), occurrenceDateEnd, occurrenceDateStart }; foreach (var date in occurrenceDates) { var ev = await _repository.AddAsync(EventData.GenerateEvent(projectId: TestConstants.ProjectId, organizationId: TestConstants.OrganizationId, stackId: TestConstants.StackId, occurrenceDate: date)); _ids.Add(Tuple.Create(ev.Id, date)); } await RefreshDataAsync(); } }
using KellermanSoftware.CompareNetObjects; using Microsoft.EntityFrameworkCore; using NetTopologySuite; using Newtonsoft.Json; using OCM.API.Common.Model; using OCM.API.Common.Model.Extended; using OCM.Core.Data; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; namespace OCM.API.Common { public class OCMAPIException : Exception { public OCMAPIException(string message) : base(message) { } } public struct ValidationResult { public int? ItemId { get; set; } public bool IsValid { get; set; } public string Message { get; set; } public object Item { get; set; } } public class POIManager { private const int DefaultPolylineSearchDistanceKM = 5; private const int DefaultLatLngSearchDistanceKM = 1000; public bool LoadUserComments = false; public POIManager() { LoadUserComments = false; } public POIDetailsCache GetFromCache(int id, string path) { try { string cachePath = path + "\\POI_" + id + ".json"; if (System.IO.File.Exists(cachePath)) { POIDetailsCache cachedPOI = JsonConvert.DeserializeObject<POIDetailsCache>(System.IO.File.ReadAllText(cachePath)); TimeSpan timeSinceCache = DateTime.UtcNow - cachedPOI.DateCached; if (timeSinceCache.TotalDays > 14) return null; return cachedPOI; } } catch (Exception) { } return null; } public void CachePOIDetails(string path, Model.ChargePoint poi, List<Model.ChargePoint> nearbyPOI = null) { try { string cachePath = path + "\\POI_" + poi.ID + ".json"; if (!System.IO.File.Exists(cachePath)) { POIDetailsCache cachedPOI = new POIDetailsCache { POI = poi, DateCached = DateTime.UtcNow, POIListNearby = nearbyPOI }; System.IO.File.WriteAllText(cachePath, JsonConvert.SerializeObject(cachedPOI)); } } catch (Exception) { ; ;//caching failed } } public async Task<Model.ChargePoint> Get(int id) { return await this.Get(id, false); } public async Task<Model.ChargePoint> GetFullDetails(int id) { return await this.Get(id, true, false, true); } public async Task<Model.ChargePoint> GetCopy(int id, bool resetAddress = true) { var poi = await this.Get(id, false); poi.ID = 0; poi.MediaItems = null; poi.UserComments = null; poi.AddressInfo.ID = 0; if (resetAddress) { poi.AddressInfo.Title = ""; poi.AddressInfo.AddressLine1 = ""; poi.AddressInfo.AddressLine2 = ""; poi.AddressInfo.AccessComments = ""; poi.AddressInfo.GeneralComments = ""; } poi.DataProvider = null; poi.DataProviderID = null; poi.DataProvidersReference = null; poi.DataQualityLevel = null; poi.OperatorsReference = null; poi.DateCreated = DateTime.UtcNow; poi.DateLastConfirmed = null; poi.DateLastStatusUpdate = null; poi.DatePlanned = null; poi.UUID = null; foreach (var conn in poi.Connections) { conn.ID = 0; conn.Reference = null; } return poi; } public async Task<Model.ChargePoint> Get(int id, bool includeExtendedInfo, bool allowDiskCache = false, bool allowMirrorDB = false) { var refData = await new ReferenceDataManager().GetCoreReferenceDataAsync(); if (allowMirrorDB) { var p = await CacheProviderMongoDB.DefaultInstance.GetPOI(id); if (p != null) { return p; } } try { var dataModel = new OCMEntities(); var item = dataModel.ChargePoints.Find(id); var poi = Model.Extensions.ChargePoint.FromDataModel(item, includeExtendedInfo, includeExtendedInfo, includeExtendedInfo, true, refData); return poi; } catch (Exception) { //POI not found matching id return null; } } /// <summary> /// Populates extended properties (reference data etc) of a simple POI from data model, useful for previewing as a fully populated new/edited poi /// </summary> /// <param name="poi"></param> /// <returns></returns> public Model.ChargePoint PreviewPopulatedPOIFromModel(Model.ChargePoint poi, Model.CoreReferenceData refData) { var dataModel = new OCMEntities(); var dataPreviewPOI = PopulateChargePoint_SimpleToData(poi, dataModel); return Model.Extensions.ChargePoint.FromDataModel(dataPreviewPOI, refData); } /// <summary> /// Check if user can edit given POI with review/approval from another editor /// </summary> /// <param name="poi"></param> /// <param name="user"></param> /// <returns></returns> public static bool CanUserEditPOI(Model.ChargePoint poi, Model.User user) { if (user == null || poi == null) return false; int? countryId = (poi.AddressInfo != null && poi.AddressInfo.Country != null) ? (int?)poi.AddressInfo.Country.ID : null; if (UserManager.IsUserAdministrator(user) || UserManager.HasUserPermission(user, null, PermissionLevel.Editor) || (countryId != null && UserManager.HasUserPermission(user, countryId, PermissionLevel.Editor))) { return true; } else { return false; } } [DbFunctionAttribute("OCM.Core.Data.OCMEntities.Store", "udf_GetDistanceFromLatLonKM")] public static double? GetDistanceFromLatLonKM(double? Latitude1, double? Longitude1, double? Latitude2, double? Longitude2) { //implements dummy call for entity framework mapping to corresponding SQL function throw new NotSupportedException("Direct calls are not supported."); } public IEnumerable<Model.ChargePoint> GetPOIList(APIRequestParams filter) { return GetPOIListAsync(filter).Result; } public static IQueryable<OCM.Core.Data.ChargePoint> ApplyQueryFilters(APIRequestParams filter, IQueryable<OCM.Core.Data.ChargePoint> poiList) { int greaterThanId = 0; // workaround mongodb linq conversion bug if (filter.GreaterThanId.HasValue) greaterThanId = filter.GreaterThanId.Value; if (filter.OperatorIDs?.Any() == true) { poiList = poiList.Where(c => filter.OperatorIDs.Contains((int)c.OperatorId)); } if (filter.SubmissionStatusTypeID == null) { // default to published submissions poiList = poiList.Where(c => c.SubmissionStatusTypeId == (int)StandardSubmissionStatusTypes.Imported_Published || c.SubmissionStatusTypeId == (int)StandardSubmissionStatusTypes.Submitted_Published); } else if (filter.SubmissionStatusTypeID > 0) { //specific submission status poiList = poiList.Where(c => c.SubmissionStatusTypeId == filter.SubmissionStatusTypeID); } else if (filter.SubmissionStatusTypeID == 0) { //use all pois regardless of submission status } // exclude any delisted POIs poiList = poiList.Where(c => c.SubmissionStatusTypeId != (int)StandardSubmissionStatusTypes.Delisted_NotPublicInformation); // deprecated filter by operator name if (filter.OperatorName != null) { poiList = poiList.Where(c => c.Operator.Title == filter.OperatorName); } if (filter.IsOpenData != null) { poiList = poiList.Where(c => (filter.IsOpenData == true && c.DataProvider.IsOpenDataLicensed == true) || (filter.IsOpenData == false && c.DataProvider.IsOpenDataLicensed != true)); } if (filter.GreaterThanId.HasValue == true) { poiList = poiList.Where(c => filter.GreaterThanId.HasValue && c.Id > greaterThanId); } // depreceated filter by dataprovider name if (filter.DataProviderName != null) { poiList = poiList.Where(c => c.DataProvider.Title == filter.DataProviderName); } if (filter.CountryIDs?.Any() == true) { poiList = poiList.Where(c => filter.CountryIDs.Contains((int)c.AddressInfo.CountryId)); } if (filter.ChargePointIDs?.Any() == true) { poiList = poiList.Where(c => filter.ChargePointIDs.Contains((int)c.Id)); } if (filter.UsageTypeIDs?.Any() == true) { poiList = poiList.Where(c => filter.UsageTypeIDs.Contains((int)c.UsageTypeId)); } if (filter.StatusTypeIDs?.Any() == true) { poiList = poiList.Where(c => filter.StatusTypeIDs.Contains((int)c.StatusTypeId)); } // exclude any decomissioned items poiList = poiList.Where(c => c.StatusTypeId != (int)StandardStatusTypes.RemovedDecomissioned); if (filter.DataProviderIDs?.Any() == true) { poiList = poiList.Where(c => filter.DataProviderIDs.Contains((int)c.DataProviderId)); } if (filter.Postcodes?.Any() == true) { poiList = poiList.Where(c => filter.Postcodes.Contains(c.AddressInfo.Postcode)); } if (filter.ChangesFromDate != null) { poiList = poiList.Where(c => c.DateLastStatusUpdate >= filter.ChangesFromDate.Value); } if (filter.CreatedFromDate != null) { poiList = poiList.Where(c => c.DateCreated >= filter.CreatedFromDate.Value); } //where level of detail is greater than 1 we decide how much to return based on the given level of detail (1-10) Level 10 will return the least amount of data and is suitable for a global overview if (filter.LevelOfDetail > 1) { //return progressively less matching results (across whole data set) as requested Level Of Detail gets higher if (filter.LevelOfDetail > 3) { filter.LevelOfDetail = 1; //highest priority LOD } else { filter.LevelOfDetail = 2; //include next level priority items } poiList = poiList.Where(c => c.LevelOfDetail <= filter.LevelOfDetail); } //apply connectionInfo filters, all filters must match a distinct connection within the charge point, rather than any filter matching any connectioninfo if (filter.ConnectionType != null) { poiList = poiList.Where(c => c.ConnectionInfos.Any(conn => conn.ConnectionType.Title == filter.ConnectionType)); } if (filter.MinPowerKW != null) { poiList = poiList.Where(c => c.ConnectionInfos.Any(conn => conn.PowerKw >= filter.MinPowerKW)); } if (filter.MaxPowerKW != null) { poiList = poiList.Where(c => c.ConnectionInfos.Any(conn => conn.PowerKw <= filter.MaxPowerKW)); } if (filter.ConnectionTypeIDs?.Any() == true) { poiList = poiList.Where(c => c.ConnectionInfos.Any(conn => conn.ConnectionTypeId != null && filter.ConnectionTypeIDs.Contains((int)conn.ConnectionTypeId))); } if (filter.LevelIDs?.Any() == true) { poiList = poiList.Where(c => c.ConnectionInfos.Any(conn => conn.LevelTypeId != null && filter.LevelIDs.Contains((int)conn.LevelTypeId))); } poiList = poiList.Where(c => c.AddressInfo != null); return poiList; } /// <summary> /// For given query/output settings, return list of charge points. May be a cached response. /// </summary> /// <param name="settings"></param> /// <returns></returns> public async Task<IEnumerable<Model.ChargePoint>> GetPOIListAsync(APIRequestParams filterParams, Model.CoreReferenceData refData = null) { // clone filter settings to remove mutation side effects in callers var filter = JsonConvert.DeserializeObject<APIRequestParams>(JsonConvert.SerializeObject(filterParams)); var geometryFactory = NtsGeometryServices.Instance.CreateGeometryFactory(srid: GeoManager.StandardSRID); var stopwatch = Stopwatch.StartNew(); filter.EnableCaching = false; IEnumerable<Model.ChargePoint> dataList = null; if (filter.AllowMirrorDB) { try { dataList = await CacheProviderMongoDB.DefaultInstance.GetPOIListAsync(filter); if (dataList != null) { return dataList; } } catch (Exception exp) { //failed to query mirror db, will now fallback to sql server if dataList is null //mostly likely because cache is being refreshed while querying System.Diagnostics.Debug.WriteLine("Failed to query MongoDB cache: " + exp.ToString()); } } //if dataList is null we didn't get any cache DB results, use SQL DB if (dataList == null && filter.AllowDataStoreDB) { if (refData == null) { using (var refDataManager = new ReferenceDataManager()) { refData = await refDataManager.GetCoreReferenceDataAsync(); } } int maxResults = filter.MaxResults; this.LoadUserComments = filter.IncludeComments; bool requiresDistance = false; if (filter.Latitude != null && filter.Longitude != null) { requiresDistance = true; } dataList = new List<Model.ChargePoint>(); var dataModel = new OCMEntities(); //if distance filter provided in miles, convert to KM before use if (filter.DistanceUnit == Model.DistanceUnit.Miles && filter.Distance != null) { filter.Distance = GeoManager.ConvertMilesToKM((double)filter.Distance); } var poiList = ApplyQueryFilters(filter, dataModel.ChargePoints.AsQueryable()); /////////// //filter by points along polyline or bounding box if ( (filter.Polyline != null && filter.Polyline.Any()) || (filter.BoundingBox != null && filter.BoundingBox.Any()) || (filter.Polygon != null && filter.Polygon.Any()) ) { //override lat.long specified in search, use polyline or bounding box instead filter.Latitude = null; filter.Longitude = null; //filter by location within polyline expanded to a polygon (by search distance) IEnumerable<LatLon> searchPolygon = null; if (filter.Polyline != null && filter.Polyline.Any()) { if (filter.Distance == null) filter.Distance = DefaultPolylineSearchDistanceKM; searchPolygon = OCM.Core.Util.PolylineEncoder.SearchPolygonFromPolyLine(filter.Polyline, (double)filter.Distance); } if (filter.BoundingBox != null && filter.BoundingBox.Any()) { var polyPoints = Core.Util.PolylineEncoder.ConvertPointsToBoundingBox(filter.BoundingBox) .Coordinates .Select(p => new LatLon { Latitude = p.Y, Longitude = p.X }).AsEnumerable(); searchPolygon = polyPoints; } if (filter.Polygon != null && filter.Polygon.Any()) { searchPolygon = filter.Polygon; } //invalidate any further use of distance as filter because polyline/bounding box takes precedence filter.Distance = null; requiresDistance = false; int numPoints = searchPolygon.Count(); string polygonText = ""; foreach (var p in searchPolygon) { polygonText += p.Longitude + " " + p.Latitude; #if DEBUG System.Diagnostics.Debug.WriteLine(" {lat: " + p.Latitude + ", lng: " + p.Longitude + "},"); #endif polygonText += ", "; } //close polygon var closingPoint = searchPolygon.First(); polygonText += closingPoint.Longitude + " " + closingPoint.Latitude; string polygonWKT = "POLYGON((" + polygonText + "))"; #if DEBUG System.Diagnostics.Debug.WriteLine(polygonWKT); #endif try { var polygon = new NetTopologySuite.IO.WKTReader(geometryFactory.GeometryServices).Read(polygonWKT); polygon.SRID = GeoManager.StandardSRID; poiList = poiList.Where(q => q.AddressInfo.SpatialPosition.Intersects(polygon)); } catch (ArgumentException) { System.Diagnostics.Debug.WriteLine("Search Polygon is invalid"); } } NetTopologySuite.Geometries.Point searchPos = null; if (requiresDistance && filter.Latitude != null && filter.Longitude != null) { searchPos = geometryFactory.CreatePoint(new NetTopologySuite.Geometries.Coordinate((double)filter.Longitude, (double)filter.Latitude)); if (filter.Distance == null) filter.Distance = DefaultLatLngSearchDistanceKM; } //compute/filter by distance (if required) var filteredList = from c in poiList where (requiresDistance == false) || ( requiresDistance == true && (filter.Latitude != null && filter.Longitude != null) && (filter.Distance == null || (filter.Distance != null && searchPos != null && c.AddressInfo.SpatialPosition.Distance(searchPos) / 1000 < filter.Distance ) ) ) select new { c, DistanceKM = (requiresDistance ? c.AddressInfo.SpatialPosition.Distance(searchPos) / 1000 : (double?)null) }; if (requiresDistance) { //if distance was a required output, sort results by distance filteredList = filteredList.OrderBy(d => d.DistanceKM); } else { if (filter.SortBy == "created_asc") { filteredList = filteredList.OrderBy(p => p.c.DateCreated); } else if (filter.SortBy == "modified_asc") { filteredList = filteredList.OrderBy(p => p.c.DateLastStatusUpdate); } else if (filter.SortBy == "id_asc") { filteredList = filteredList.OrderBy(p => p.c.DateCreated); } else { filteredList = filteredList.OrderByDescending(p => p.c.Id); } } var additionalFilteredList = await filteredList .Take(maxResults) .ToListAsync(); stopwatch.Stop(); System.Diagnostics.Debug.WriteLine("Total query time (ms): " + stopwatch.ElapsedMilliseconds.ToString()); stopwatch.Restart(); var poiResults = new List<Model.ChargePoint>(maxResults); foreach (var item in additionalFilteredList) { //note: if include comments is enabled, media items and metadata values are also included Model.ChargePoint c = Model.Extensions.ChargePoint.FromDataModel(item.c, filter.IncludeComments, filter.IncludeComments, filter.IncludeComments, !filter.IsCompactOutput, refData); if (requiresDistance && c.AddressInfo != null) { c.AddressInfo.Distance = item.DistanceKM; if (filter.DistanceUnit == Model.DistanceUnit.Miles && c.AddressInfo.Distance != null) { c.AddressInfo.Distance = GeoManager.ConvertKMToMiles(c.AddressInfo.Distance); } c.AddressInfo.DistanceUnit = filter.DistanceUnit; } if (filter.IsLegacyAPICall && !(filter.APIVersion >= 2)) { //for legacy callers, produce artificial list of Charger items #pragma warning disable 612 //suppress obsolete warning if (c.Chargers == null || c.Chargers.Count == 0) { if (c.Connections != null) { var chargerList = new List<Common.Model.ChargerInfo>(); foreach (var con in c.Connections) { if (con.Level != null) { if (!chargerList.Exists(l => l.ChargerType == con.Level)) { chargerList.Add(new Common.Model.ChargerInfo() { ChargerType = con.Level }); } } } chargerList = chargerList.Distinct().ToList(); c.Chargers = chargerList; } } } #pragma warning restore 612 if (c != null) { poiResults.Add(c); } } //System.Diagnostics.Debug.WriteLine("POI List filter time: " + stopwatch.ElapsedMilliseconds + "ms for " + dataList.Count + " results"); return poiResults; } else { return new List<Model.ChargePoint>(); } } /// <summary> /// for given charge point, return list of similar charge points based on location/title etc with approx similarity /// </summary> /// <param name="poi"></param> /// <returns></returns> public List<Model.ChargePoint> FindSimilar(Model.ChargePoint poi, Model.CoreReferenceData refData) { List<Model.ChargePoint> list = new List<Model.ChargePoint>(); OCMEntities dataModel = new OCMEntities(); //find similar locations (excluding same cp) var similarData = dataModel.ChargePoints.Where(c => c.Id != poi.ID && c.ParentChargePointId == null //exclude under review and delisted charge points && (c.SubmissionStatusTypeId == null || c.SubmissionStatusTypeId == 100 || c.SubmissionStatusTypeId == 200) && ( c.AddressInfoId == poi.AddressInfo.ID || c.AddressInfo.Postcode == poi.AddressInfo.Postcode || c.AddressInfo.AddressLine1 == poi.AddressInfo.AddressLine1 || c.AddressInfo.Title == poi.AddressInfo.Title ) ); foreach (var item in similarData) { Model.ChargePoint c = Model.Extensions.ChargePoint.FromDataModel(item, refData); if (c != null) { int percentageSimilarity = 0; if (c.AddressInfo.ID == poi.AddressInfo.ID) percentageSimilarity += 75; if (c.AddressInfo.Postcode == poi.AddressInfo.Postcode) percentageSimilarity += 20; if (c.AddressInfo.AddressLine1 == poi.AddressInfo.AddressLine1) percentageSimilarity += 50; if (c.AddressInfo.Title == poi.AddressInfo.Title) percentageSimilarity += 25; if (percentageSimilarity > 100) percentageSimilarity = 99; c.PercentageSimilarity = percentageSimilarity; list.Add(c); } } return list; } public static ValidationResult IsValid(Model.ChargePoint cp) { //determine if the basic CP details are valid as a submission or edit if (cp.AddressInfo == null) return new ValidationResult { IsValid = false, Message = "AddressInfo is required", Item = cp }; if (String.IsNullOrEmpty(cp.AddressInfo.Title)) return new ValidationResult { IsValid = false, Message = "AddressInfo requires a Title", Item = cp }; ; if (String.IsNullOrEmpty(cp.AddressInfo.AddressLine1) && String.IsNullOrEmpty(cp.AddressInfo.AddressLine2)) return new ValidationResult { IsValid = false, Message = "AddressInfo requires basic (nearest) address information", Item = cp }; ; if (cp.AddressInfo.Country == null && cp.AddressInfo.CountryID == null) return new ValidationResult { IsValid = false, Message = "AddressInfo requires a Country", Item = cp }; if (cp.AddressInfo.Latitude == 0 && cp.AddressInfo.Longitude == 0) return new ValidationResult { IsValid = false, Message = "AddressInfo requires latitude and longitude", Item = cp }; double lat = (double)cp.AddressInfo.Latitude; double lon = (double)cp.AddressInfo.Longitude; if (lat < -90 || lat > 90) return new ValidationResult { IsValid = false, Message = "AddressInfo latitude is out of range", Item = cp }; if (lon < -180 || lon > 180) return new ValidationResult { IsValid = false, Message = "AddressInfo longitude is out of range", Item = cp }; ; // workaround (really requires very accurate country lookups) if country is indicated as australia but lat/long is out of bound then user has left country as default in UI dropdown list if (cp.AddressInfo.CountryID == 18 && !(lon > 110 && lon < 161 && lat > -45.46 && lat < -9)) { return new ValidationResult { IsValid = false, Message = "AddressInfo position is not in the selected country (Australia)", Item = cp }; } if (cp.Connections == null || cp.Connections?.Count == 0) return new ValidationResult { IsValid = false, Message = "One or more Connections required", Item = cp }; //otherwise, looks basically valid return new ValidationResult { IsValid = true, Message = "Passed basic validation", Item = cp }; } private static string GetDisplayName(Type dataType, string fieldName) { var attr = (DisplayAttribute)dataType.GetProperty(fieldName).GetCustomAttributes(typeof(DisplayAttribute), true).SingleOrDefault(); if (attr == null) { var metadataType = (MetadataTypeAttribute)dataType.GetCustomAttributes(typeof(MetadataTypeAttribute), true).FirstOrDefault(); if (metadataType != null) { var property = metadataType.MetadataClassType.GetProperty(fieldName); if (property != null) { attr = (DisplayAttribute)property.GetCustomAttributes(typeof(DisplayAttribute), true).SingleOrDefault(); } } } return (attr != null) ? attr.Name : String.Empty; } public bool HasDifferences(Model.ChargePoint poiA, Model.ChargePoint poiB) { var diffList = CheckDifferences(poiA, poiB); if (diffList.Count == 0) { return false; } else { return true; } } public List<DiffItem> CheckDifferences(Model.ChargePoint poiA, Model.ChargePoint poiB, bool useObjectCompare = true) { var diffList = new List<DiffItem>(); if (poiA == null && poiB == null) { return diffList; } if (poiA == null && poiB != null) { diffList.Add(new DiffItem { Context = "POI", ValueA = null, ValueB = "New" }); return diffList; } if (poiB == null && poiA != null) { diffList.Add(new DiffItem { Context = "POI", ValueA = "New", ValueB = null }); return diffList; } if (useObjectCompare) { var objectComparison = new CompareLogic(new ComparisonConfig { CompareChildren = true, MaxDifferences = 1000 }); var exclusionList = new string[] { "UUID", "MediaItems", "UserComments", "DateCreated", "DateLastStatusUpdate", ".DataProvider.DateLastImported", ".DataProvider.WebsiteURL", ".DataProvider.DataProviderStatusType", ".DataProvider.Comments", ".DataProvider.License", ".StatusType.IsOperational", ".ConnectionType.FormalName", ".ConnectionType.IsDiscontinued", ".ConnectionType.IsObsolete", ".CurrentType.Description", ".Level.Comments", ".AddressInfoID", ".AddressInfo.ID", ".AddressInfo.Distance", ".AddressInfo.DistanceUnit", ".AddressInfo.DistanceUnit.DistanceUnit", ".SubmissionStatus.IsLive", ".OperatorInfo.WebsiteURL", ".OperatorInfo.PhonePrimaryContact", ".OperatorInfo.IsPrivateIndividual", ".OperatorInfo.ContactEmail", ".OperatorInfo.FaultReportEmail", ".UsageType.IsPayAtLocation", ".UsageType.IsMembershipRequired", ".UsageType.IsAccessKeyRequired", ".DataProvider.DataProviderStatusType.ID", ".DataProvider.DataProviderStatusType.Title" }; objectComparison.Config.MembersToIgnore.AddRange(exclusionList); var comparisonResult = objectComparison.Compare(poiA, poiB); if (!comparisonResult.AreEqual) { //clean up differences we want to exclude foreach (var exclusionSuffix in exclusionList) { comparisonResult.Differences.RemoveAll(e => e.PropertyName.EndsWith(exclusionSuffix)); } diffList.AddRange(comparisonResult.Differences.Select(difference => new DiffItem { Context = difference.PropertyName, ValueA = difference.Object1Value, ValueB = difference.Object2Value })); //remove items which only vary on null vs "" diffList.RemoveAll(d => (String.IsNullOrWhiteSpace(d.ValueA) || d.ValueA == "(null)") && (String.IsNullOrWhiteSpace(d.ValueB) || d.ValueB == "(null)")); //remove items which are in fact the same diffList.RemoveAll(d => d.ValueA == d.ValueB); } } else { //perform non-automate diff check CompareSimpleRefDataItem(diffList, "Data Provider", poiA.DataProviderID, poiB.DataProviderID, (SimpleReferenceDataType)poiA.DataProvider, (SimpleReferenceDataType)poiB.DataProvider); CompareSimpleRefDataItem(diffList, "Network/Operator", poiA.OperatorID, poiB.OperatorID, poiA.OperatorInfo, poiB.OperatorInfo); CompareSimpleRefDataItem(diffList, "Operational Status", poiA.StatusTypeID, poiB.StatusTypeID, poiA.StatusType, poiB.StatusType); CompareSimpleRefDataItem(diffList, "Usage Type", poiA.UsageTypeID, poiB.UsageTypeID, poiA.UsageType, poiB.UsageType); CompareSimpleRefDataItem(diffList, "Submission Status", poiA.SubmissionStatusTypeID, poiB.SubmissionStatusTypeID, poiA.SubmissionStatus, poiB.SubmissionStatus); CompareSimpleProperty(diffList, "Data Providers Reference", poiA.DataProvidersReference, poiB.DataProvidersReference); CompareSimpleProperty(diffList, "Data Quality Level", poiA.DataQualityLevel, poiB.DataQualityLevel); CompareSimpleProperty(diffList, "Number Of Points", poiA.NumberOfPoints, poiB.NumberOfPoints); CompareSimpleProperty(diffList, "Usage Cost", poiA.UsageCost, poiB.UsageCost); CompareSimpleProperty(diffList, "Address", poiA.GetAddressSummary(false, true), poiB.GetAddressSummary(false, true)); CompareSimpleProperty(diffList, "General Comments", poiA.GeneralComments, poiB.GeneralComments); CompareSimpleProperty(diffList, "Address : Access Comments", poiA.AddressInfo.AccessComments, poiB.AddressInfo.AccessComments); } return diffList; } private void CompareSimpleRefDataItem(List<DiffItem> diffList, string displayName, int? ID1, int? ID2, SimpleReferenceDataType refData1, SimpleReferenceDataType refData2) { if (ID1 != ID2) diffList.Add(new DiffItem { DisplayName = displayName, Context = displayName, ValueA = (refData1 != null ? refData1.Title : ""), ValueB = (refData2 != null ? refData2.Title : "") }); } private void CompareSimpleProperty(List<DiffItem> diffList, string displayName, object val1, object val2) { //check if object values are different, if so add to diff list if ( (val1 != null && val2 == null && !String.IsNullOrEmpty(val1.ToString())) || (val1 == null && val2 != null && !String.IsNullOrEmpty(val2.ToString())) || (val1 != null && val2 != null && val1.ToString() != val2.ToString()) ) { diffList.Add(new DiffItem { DisplayName = displayName, Context = displayName, ValueA = (val1 != null ? val1.ToString() : ""), ValueB = (val2 != null ? val2.ToString() : "") }); } } /// <summary> /// Populate AddressInfo data from settings in a simple AddressInfo object /// </summary> public Core.Data.AddressInfo PopulateAddressInfo_SimpleToData(Model.AddressInfo simpleAddressInfo, Core.Data.AddressInfo dataAddressInfo, OCMEntities dataModel) { if (simpleAddressInfo != null && dataAddressInfo == null) dataAddressInfo = new Core.Data.AddressInfo(); if (simpleAddressInfo != null && dataAddressInfo != null) { dataAddressInfo.Title = simpleAddressInfo.Title; dataAddressInfo.AddressLine1 = simpleAddressInfo.AddressLine1; dataAddressInfo.AddressLine2 = simpleAddressInfo.AddressLine2; dataAddressInfo.Town = simpleAddressInfo.Town; dataAddressInfo.StateOrProvince = simpleAddressInfo.StateOrProvince; dataAddressInfo.Postcode = simpleAddressInfo.Postcode; if (simpleAddressInfo.CountryID > 0 || (simpleAddressInfo.Country != null && simpleAddressInfo.Country.ID > 0)) { int countryId = (simpleAddressInfo.CountryID != null ? (int)simpleAddressInfo.CountryID : simpleAddressInfo.Country.ID); dataAddressInfo.Country = dataModel.Countries.FirstOrDefault(c => c.Id == countryId); dataAddressInfo.CountryId = dataAddressInfo.Country.Id; } dataAddressInfo.Latitude = simpleAddressInfo.Latitude; dataAddressInfo.Longitude = simpleAddressInfo.Longitude; dataAddressInfo.ContactTelephone1 = simpleAddressInfo.ContactTelephone1; dataAddressInfo.ContactTelephone2 = simpleAddressInfo.ContactTelephone2; dataAddressInfo.ContactEmail = simpleAddressInfo.ContactEmail; dataAddressInfo.AccessComments = simpleAddressInfo.AccessComments; #pragma warning disable 612 //suppress obsolete warning dataAddressInfo.GeneralComments = simpleAddressInfo.GeneralComments; #pragma warning restore 612 //suppress obsolete warning dataAddressInfo.RelatedUrl = simpleAddressInfo.RelatedURL; } return dataAddressInfo; } public OCM.Core.Data.ChargePoint PopulateChargePoint_SimpleToData(Model.ChargePoint simplePOI, OCM.Core.Data.OCMEntities dataModel) { var dataPOI = new OCM.Core.Data.ChargePoint(); if (simplePOI.ID > 0 && simplePOI.UUID != null) { IQueryable<Core.Data.ChargePoint> dataPOISet = dataModel.ChargePoints .Include(a1 => a1.DataProvider) .Include(a1 => a1.Operator) .Include(a1 => a1.UsageType) .Include(a1 => a1.StatusType) .Include(a1 => a1.AddressInfo) .ThenInclude(a => a.Country) .Include(a1 => a1.ConnectionInfos) .Include(a1 => a1.MetadataValues) .ThenInclude(m => m.MetadataFieldOption) .Include(a1 => a1.UserComments) .ThenInclude(c => c.User) .Include(a1 => a1.UserComments) .Include(a1 => a1.MediaItems) .ThenInclude(c => c.User); dataPOI = dataPOISet.FirstOrDefault(cp => cp.Id == simplePOI.ID && cp.Uuid.ToUpper() == simplePOI.UUID.ToUpper()); } if (String.IsNullOrEmpty(dataPOI.Uuid)) dataPOI.Uuid = Guid.NewGuid().ToString().ToUpper(); //if required, set the parent charge point id if (simplePOI.ParentChargePointID != null) { //dataChargePoint.ParentChargePoint = dataModel.ChargePoints.FirstOrDefault(c=>c.ID==simpleChargePoint.ParentChargePointID); dataPOI.ParentChargePointId = simplePOI.ParentChargePointID; } else { dataPOI.ParentChargePoint = null; dataPOI.ParentChargePointId = null; } if (simplePOI.DataProviderID > 0 || (simplePOI.DataProvider != null && simplePOI.DataProvider.ID >= 0)) { int providerId = (simplePOI.DataProviderID != null ? (int)simplePOI.DataProviderID : simplePOI.DataProvider.ID); try { dataPOI.DataProvider = dataModel.DataProviders.First(d => d.Id == providerId); dataPOI.DataProviderId = dataPOI.DataProvider.Id; } catch (Exception exp) { //unknown operator throw new OCMAPIException("Unknown Data Provider Specified:" + providerId + " " + exp.ToString()); } } else { //set to ocm contributor by default dataPOI.DataProvider = dataModel.DataProviders.First(d => d.Id == (int)StandardDataProviders.OpenChargeMapContrib); dataPOI.DataProviderId = dataPOI.DataProvider.Id; } dataPOI.DataProvidersReference = simplePOI.DataProvidersReference; if (simplePOI.OperatorID >= 1 || (simplePOI.OperatorInfo != null && simplePOI.OperatorInfo.ID >= 0)) { int operatorId = (simplePOI.OperatorID != null ? (int)simplePOI.OperatorID : simplePOI.OperatorInfo.ID); try { dataPOI.Operator = dataModel.Operators.First(o => o.Id == operatorId); dataPOI.OperatorId = dataPOI.Operator.Id; } catch (Exception) { //unknown operator throw new OCMAPIException("Unknown Network Operator Specified:" + operatorId); } } else { dataPOI.Operator = null; dataPOI.OperatorId = null; } dataPOI.OperatorsReference = simplePOI.OperatorsReference; if (simplePOI.UsageTypeID >= 0 || (simplePOI.UsageType != null && simplePOI.UsageType.ID >= 0)) { int usageTypeId = (simplePOI.UsageTypeID != null ? (int)simplePOI.UsageTypeID : simplePOI.UsageType.ID); try { dataPOI.UsageType = dataModel.UsageTypes.First(u => u.Id == usageTypeId); dataPOI.UsageTypeId = dataPOI.UsageType.Id; } catch (Exception) { //unknown usage type throw new OCMAPIException("Unknown Usage Type Specified:" + usageTypeId); } } else { dataPOI.UsageType = null; dataPOI.UsageTypeId = null; } if (dataPOI.AddressInfo == null && simplePOI.AddressInfo.ID > 0) { var addressInfo = dataModel.ChargePoints.FirstOrDefault(cp => cp.Id == simplePOI.ID).AddressInfo; if (addressInfo.Id == simplePOI.AddressInfo.ID) dataPOI.AddressInfo = addressInfo; } dataPOI.AddressInfo = PopulateAddressInfo_SimpleToData(simplePOI.AddressInfo, dataPOI.AddressInfo, dataModel); dataPOI.NumberOfPoints = simplePOI.NumberOfPoints; dataPOI.GeneralComments = simplePOI.GeneralComments; dataPOI.DatePlanned = simplePOI.DatePlanned; dataPOI.UsageCost = simplePOI.UsageCost; if (simplePOI.DateLastStatusUpdate != null) { dataPOI.DateLastStatusUpdate = DateTime.UtcNow; } else { dataPOI.DateLastStatusUpdate = DateTime.UtcNow; } if (simplePOI.DataQualityLevel != null && simplePOI.DataQualityLevel > 0) { if (simplePOI.DataQualityLevel > 5) simplePOI.DataQualityLevel = 5; dataPOI.DataQualityLevel = simplePOI.DataQualityLevel; } else { dataPOI.DataQualityLevel = 1; } if (simplePOI.DateCreated != null) { dataPOI.DateCreated = simplePOI.DateCreated; } else { if (dataPOI.DateCreated == null) dataPOI.DateCreated = DateTime.UtcNow; } var updateConnectionList = new List<OCM.Core.Data.ConnectionInfo>(); var deleteList = new List<OCM.Core.Data.ConnectionInfo>(); if (simplePOI.Connections != null) { foreach (var c in simplePOI.Connections) { var connectionInfo = new Core.Data.ConnectionInfo(); //edit existing, if required if (c.ID > 0) connectionInfo = dataModel.ConnectionInfos.FirstOrDefault(con => con.Id == c.ID && con.ChargePointId == dataPOI.Id); if (connectionInfo == null) { //connection is stale info, start new c.ID = 0; connectionInfo = new Core.Data.ConnectionInfo(); } connectionInfo.Reference = c.Reference; connectionInfo.Comments = c.Comments; connectionInfo.Amps = c.Amps; connectionInfo.Voltage = c.Voltage; connectionInfo.Quantity = c.Quantity; connectionInfo.PowerKw = c.PowerKW; if (c.ConnectionTypeID >= 0 || (c.ConnectionType != null && c.ConnectionType.ID >= 0)) { int connectionTypeId = (c.ConnectionTypeID != null ? (int)c.ConnectionTypeID : c.ConnectionType.ID); try { connectionInfo.ConnectionType = dataModel.ConnectionTypes.First(ct => ct.Id == connectionTypeId); connectionInfo.ConnectionTypeId = connectionInfo.ConnectionType.Id; } catch (Exception) { throw new OCMAPIException("Unknown Connection Type Specified"); } } else { connectionInfo.ConnectionType = null; connectionInfo.ConnectionTypeId = 0; } if (c.LevelID >= 1 || (c.Level != null && c.Level.ID >= 1)) { int levelId = (c.LevelID != null ? (int)c.LevelID : c.Level.ID); try { connectionInfo.LevelType = dataModel.ChargerTypes.First(chg => chg.Id == levelId); connectionInfo.LevelTypeId = connectionInfo.LevelTypeId; } catch (Exception) { throw new OCMAPIException("Unknown Charger Level Specified"); } } else { connectionInfo.LevelType = null; connectionInfo.LevelTypeId = null; } if (c.CurrentTypeID >= 10 || (c.CurrentType != null && c.CurrentType.ID >= 10)) { int currentTypeId = (c.CurrentTypeID != null ? (int)c.CurrentTypeID : c.CurrentType.ID); try { connectionInfo.CurrentType = dataModel.CurrentTypes.First(chg => chg.Id == currentTypeId); connectionInfo.CurrentTypeId = connectionInfo.CurrentType.Id; } catch (Exception) { throw new OCMAPIException("Unknown Current Type Specified"); } } else { connectionInfo.CurrentType = null; connectionInfo.CurrentTypeId = null; } if (c.StatusTypeID >= 0 || (c.StatusType != null && c.StatusType.ID >= 0)) { int statusTypeId = (c.StatusTypeID != null ? (int)c.StatusTypeID : c.StatusType.ID); try { connectionInfo.StatusType = dataModel.StatusTypes.First(s => s.Id == statusTypeId); connectionInfo.StatusTypeId = connectionInfo.StatusType.Id; } catch (Exception) { throw new OCMAPIException("Unknown Status Type Specified"); } } else { connectionInfo.StatusType = null; connectionInfo.StatusTypeId = null; } bool addConnection = false; //detect if connection details are non-blank/unknown before adding if ( !String.IsNullOrEmpty(connectionInfo.Reference) || !String.IsNullOrEmpty(connectionInfo.Comments) || connectionInfo.Amps != null || connectionInfo.Voltage != null || connectionInfo.PowerKw != null || (connectionInfo.ConnectionType != null && connectionInfo.ConnectionType.Id > 0) || (connectionInfo.StatusType != null && connectionInfo.StatusTypeId > 0) || (connectionInfo.LevelType != null && connectionInfo.LevelType.Id > 1) || (connectionInfo.CurrentType != null && connectionInfo.CurrentType.Id > 0) || (connectionInfo.Quantity != null && connectionInfo.Quantity > 1) ) { addConnection = true; if (connectionInfo.ChargePoint == null) connectionInfo.ChargePoint = dataPOI; } if (addConnection) { //if adding a new connection (not an update) add to model if (c.ID <= 0 || dataPOI.ConnectionInfos.Count == 0) { dataPOI.ConnectionInfos.Add(connectionInfo); } //track final list of connections being added/updated -- will then be used to delete by difference updateConnectionList.Add(connectionInfo); } else { //remove an existing connection no longer required //if (c.ID > 0) { if (connectionInfo.ChargePoint == null) connectionInfo.ChargePoint = dataPOI; deleteList.Add(connectionInfo); //dataChargePoint.Connections.Remove(connectionInfo); } } } } //find existing connections not in updated/added list, add to delete if (dataPOI.ConnectionInfos != null) { foreach (var con in dataPOI.ConnectionInfos) { if (!updateConnectionList.Any(i => i.Id == con.Id)) { if (!deleteList.Contains(con)) { deleteList.Add(con); } } } } //finally clean up deleted items foreach (var item in deleteList) { if (item.Id > 0) { //dataModel.ConnectionInfos.Remove(item); dataPOI.ConnectionInfos.Remove(item); } } if (dataPOI.MetadataValues == null) { dataPOI.MetadataValues = new List<OCM.Core.Data.MetadataValue>(); //add metadata values } if (simplePOI.MetadataValues != null) { foreach (var m in simplePOI.MetadataValues) { var existingValue = dataPOI.MetadataValues.FirstOrDefault(v => v.Id == m.ID); if (existingValue != null) { existingValue.ItemValue = m.ItemValue; } else { var newValue = new OCM.Core.Data.MetadataValue() { ChargePointId = dataPOI.Id, ItemValue = m.ItemValue, MetadataFieldId = m.MetadataFieldID, MetadataField = dataModel.MetadataFields.FirstOrDefault(f => f.Id == m.MetadataFieldID) }; dataPOI.MetadataValues.Add(newValue); } } } //TODO:clean up unused metadata values if (simplePOI.StatusTypeID != null || simplePOI.StatusType != null) { if (simplePOI.StatusTypeID == null && simplePOI.StatusType != null) simplePOI.StatusTypeID = simplePOI.StatusType.ID; dataPOI.StatusTypeId = simplePOI.StatusTypeID; dataPOI.StatusType = dataModel.StatusTypes.FirstOrDefault(s => s.Id == simplePOI.StatusTypeID); } else { dataPOI.StatusType = null; dataPOI.StatusTypeId = null; } if (simplePOI.SubmissionStatusTypeID != null || simplePOI.SubmissionStatus != null) { if (simplePOI.SubmissionStatusTypeID == null & simplePOI.SubmissionStatus != null) simplePOI.SubmissionStatusTypeID = simplePOI.SubmissionStatus.ID; dataPOI.SubmissionStatusType = dataModel.SubmissionStatusTypes.First(s => s.Id == simplePOI.SubmissionStatusTypeID); dataPOI.SubmissionStatusTypeId = simplePOI.SubmissionStatusTypeID; } else { dataPOI.SubmissionStatusTypeId = null; dataPOI.SubmissionStatusType = null; // dataModel.SubmissionStatusTypes.First(s => s.ID == (int)StandardSubmissionStatusTypes.Submitted_UnderReview); } return dataPOI; } /// <summary> /// used to replace a POI from an external source with a new OCM provided POI, updated POI must still be saved after to store association /// </summary> /// <param name="oldPOI"></param> /// <param name="updatedPOI"></param> public int SupersedePOI(OCMEntities dataModel, Model.ChargePoint oldPOI, Model.ChargePoint updatedPOI) { //When applying an edit to imported or externally provided data: //Save old item with new POI ID, Submission Status: Delisted - Superseded By Edit //Save edit over old POI ID, with Contributor set to OCM, Parent POI ID set to new (old) POI ID //This means that comments/photos/metadata etc for the old POI are preserved against the new POI //zero existing ids we want to move to superseded poi (otherwise existing items will be updated) oldPOI.ID = 0; oldPOI.UUID = null; if (oldPOI.AddressInfo != null) oldPOI.AddressInfo.ID = 0; if (oldPOI.Connections != null) { foreach (var connection in oldPOI.Connections) { connection.ID = 0; } } oldPOI.SubmissionStatus = null; oldPOI.SubmissionStatusTypeID = (int)StandardSubmissionStatusTypes.Delisted_SupersededByUpdate; var supersededPOIData = this.PopulateChargePoint_SimpleToData(oldPOI, dataModel); supersededPOIData.DateLastStatusUpdate = DateTime.UtcNow; dataModel.ChargePoints.Add(supersededPOIData); dataModel.SaveChanges(); //associate updated poi with older parent poi, set OCM as data provider updatedPOI.ParentChargePointID = supersededPOIData.Id; updatedPOI.DataProvider = null; updatedPOI.DataProvidersReference = null; updatedPOI.DataProviderID = (int)StandardDataProviders.OpenChargeMapContrib; //return new ID for the archived version of the POI return supersededPOIData.Id; } } }
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 Microsoft.Xna.Framework.Net; using Microsoft.Xna.Framework.Storage; using SpriteLib; namespace XNAGame2D { public class Game1 : Microsoft.Xna.Framework.Game { GraphicsDeviceManager graphics; SpriteBatch spriteBatch; public Game1() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; } /// <summary> /// Allows the game to perform any initialization it needs to before starting to run. /// This is where it can query for any required services and load any non-graphic /// related content. Calling base.Initialize will enumerate through any components /// and initialize them as well. /// </summary> protected override void Initialize() { // TODO: Add your initialization logic here base.Initialize(); } /// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> /// Model myModel; float aspectRatio; // Set the coordinates to draw the sprite at. Sprite Front = new Sprite(Vector2.Zero); Sprite Back = new Sprite(Vector2.Zero); Sprite Left = new Sprite(Vector2.Zero); Sprite Right = new Sprite(Vector2.Zero); //Sprite Sheet Array private Texture2D One; private Texture2D Two; private Texture2D Three; private Texture2D Four; private Texture2D Five; private Texture2D Six; private Texture2D[] FrontSprites; private Texture2D[] BackSprites; //Font Initialization private Vector2 loadingPosition = new Vector2(150, 120); private SpriteFont font; //Sprite Sort Mode private SpriteSortMode sortMode = SpriteSortMode.FrontToBack; //Sprite Blend Mode private SpriteBlendMode blendMode = SpriteBlendMode.AlphaBlend; protected override void LoadContent() { myModel = Content.Load<Model>("Models\\sphere"); aspectRatio = (float)graphics.GraphicsDevice.Viewport.Width / (float)graphics.GraphicsDevice.Viewport.Height; One = Content.Load<Texture2D>(@"Front\IMG00000"); Two = Content.Load<Texture2D>(@"Front\IMG00001"); Three = Content.Load<Texture2D>(@"Front\IMG00002"); Four = Content.Load<Texture2D>(@"Front\IMG00003"); Five = Content.Load<Texture2D>(@"Front\IMG00004"); Six = Content.Load<Texture2D>(@"Front\IMG00005"); FrontSprites = new Texture2D[6]; FrontSprites[0] = One; FrontSprites[1] = Two; FrontSprites[2] = Three; FrontSprites[3] = Four; FrontSprites[4] = Five; FrontSprites[5] = Six; One = Content.Load<Texture2D>(@"Back\IMG00000"); Two = Content.Load<Texture2D>(@"Back\IMG00001"); Three = Content.Load<Texture2D>(@"Back\IMG00002"); Four = Content.Load<Texture2D>(@"Back\IMG00003"); Five = Content.Load<Texture2D>(@"Back\IMG00004"); Six = Content.Load<Texture2D>(@"Back\IMG00005"); BackSprites = new Texture2D[6]; BackSprites[0] = One; BackSprites[1] = Two; BackSprites[2] = Three; BackSprites[3] = Four; BackSprites[4] = Five; BackSprites[5] = Six; // Create a new SpriteBatch, which can be used to draw textures. font = Content.Load<SpriteFont>(@"Fonts\Arial"); spriteBatch = new SpriteBatch(GraphicsDevice); Front.setTexture(Content.Load<Texture2D>(@"Marle (Front)")); Front.setSpeed(new Vector2(150.0f, 150.0f)); Back.setTexture(Content.Load<Texture2D>(@"Marle (Back)")); Back.setSpeed(new Vector2(44.0f, 44.0f)); Left.setTexture(Content.Load<Texture2D>(@"Marle (Left)")); //Left.setSpeed(new Vector2(25.0f, 25.0f)); Right.setTexture(Content.Load<Texture2D>(@"sonic")); Right.setSpeed(new Vector2(74.0f, 74.0f)); // TODO: use this.Content to load your game content here } /// <summary> /// UnloadContent will be called once per game and is the place to unload /// all content. /// </summary> protected override void UnloadContent() { // TODO: Unload any non ContentManager content here } /// <summary> /// Allows the game to run logic such as updating the world, /// checking for collisions, gathering input, and playing audio. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> /// //private int frame = 0; protected override void Update(GameTime gameTime) { modelRotation += (float)gameTime.ElapsedGameTime.TotalMilliseconds * MathHelper.ToRadians(0.1f); // Allows the game to exit if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) this.Exit(); if (Keyboard.GetState().IsKeyDown(Keys.Escape)){ this.Exit(); } if (Keyboard.GetState().IsKeyDown(Keys.Right)) { Left.setTexture(Content.Load<Texture2D>(@"Marle (Right)")); Left.setPosition(new Vector2((Left.getPosition().X + 1.0f), Left.getPosition().Y)); } if (Keyboard.GetState().IsKeyDown(Keys.Down)) { Left.Animate(ref FrontSprites, 10); Left.setPosition(new Vector2(Left.getPosition().X, Left.getPosition().Y + 1.0f)); } if (Keyboard.GetState().IsKeyDown(Keys.Left)) { Left.setTexture(Content.Load<Texture2D>(@"Marle (Left)")); Left.setPosition(new Vector2((Left.getPosition().X - 1.0f), Left.getPosition().Y)); } if (Keyboard.GetState().IsKeyDown(Keys.Up)) { Left.Animate(ref BackSprites, 10); Left.setPosition(new Vector2((Left.getPosition().X), Left.getPosition().Y - 1.0f)); } /*if (Left.getPosition().X == 0.0f) { Left.setTexture(Content.Load<Texture2D>(@"Marle (Front)")); }*/ // Move the sprite around. UpdateSprite(gameTime); base.Update(gameTime); } /// <summary> /// This is called when the game should draw itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> /// Vector3 modelPosition = Vector3.Zero; float modelRotation = 0.0f; float wheelVal = 0.0f; float wheelVal2 = 0.0f; // Set the position of the camera in world space, for our view matrix. Vector3 cameraPosition = new Vector3(0.0f, 50.0f, 100.0f); protected override void Draw(GameTime gameTime) { wheelVal = (float)Mouse.GetState().ScrollWheelValue; //Display Font here GraphicsDevice.Clear(Color.White); Matrix[] transforms = new Matrix[myModel.Bones.Count]; myModel.CopyAbsoluteBoneTransformsTo(transforms); // Draw the model. A model can have multiple meshes, so loop. foreach (ModelMesh mesh in myModel.Meshes) { // This is where the mesh orientation is set, as well as our camera and projection. foreach (BasicEffect effect in mesh.Effects) { effect.EnableDefaultLighting(); effect.World = transforms[mesh.ParentBone.Index] * Matrix.CreateRotationY(modelRotation) * Matrix.CreateTranslation(modelPosition); effect.View = Matrix.CreateLookAt(cameraPosition, Vector3.Zero, Vector3.Up); effect.Projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45.0f), aspectRatio, 1.0f, 10000.0f); } /*if (modelPosition.Y < (float)graphics.GraphicsDevice.Viewport.Height) { modelPosition += new Vector3(0.0f, 1.0f, 0.0f); } else { modelPosition -= new Vector3(0.0f, 1.0f, 0.0f); }*/ // Draw the mesh, using the effects set above. mesh.Draw(); } spriteBatch.Begin(blendMode, sortMode, SaveStateMode.None); spriteBatch.DrawString(font, "Val1: " + wheelVal.ToString() + " Val2: " + wheelVal2.ToString() + " ", loadingPosition, Color.Black); spriteBatch.Draw(Front.getTexture(), Front.getPosition(), Color.White); spriteBatch.Draw(Back.getTexture(), Back.getPosition(), Color.White); spriteBatch.Draw(Left.getTexture(), Left.getPosition(), Color.White); spriteBatch.Draw(Right.getTexture(), Right.getPosition(), Color.White); spriteBatch.End(); if (wheelVal > wheelVal2) { cameraPosition.Z += (float)wheelVal; } if (wheelVal < wheelVal2) { cameraPosition.Z -= (float)wheelVal; } wheelVal2 = wheelVal; // Draw the sprite. //Begin must be called before anything is drawn //SpriteSortMode.FrontToBack //Draw Font base.Draw(gameTime); // TODO: Add your drawing code here } int EO = 0; void UpdateSprite(GameTime gameTime) { // Move the sprite by speed, scaled by elapsed time. Front.setPosition(Front.getPosition() + Front.getSpeed() * (float)gameTime.ElapsedGameTime.TotalSeconds); Back.setPosition(Back.getPosition() + Back.getSpeed() * (float)gameTime.ElapsedGameTime.TotalSeconds); //Left.setPosition(Left.getPosition() + Left.getSpeed() * (float)gameTime.ElapsedGameTime.TotalSeconds); Right.setPosition(Right.getPosition() + Right.getSpeed() * (float)gameTime.ElapsedGameTime.TotalSeconds); int MaxX = graphics.GraphicsDevice.Viewport.Width - Front.getTexture().Width; int MinX = 0; int MaxY = graphics.GraphicsDevice.Viewport.Height - Front.getTexture().Height; int MinY = 0; // Check for bounce. Front.bounceX(MaxX, MinX); Front.bounceY(MaxY, MinY); Back.bounceX(MaxX, MinX); Back.bounceY(MaxY, MinY); Left.bounceX(MaxX, MinX); Left.bounceY(MaxY, MinY); Right.bounceX(MaxX, MinX); Right.bounceY(MaxY, MinY); //Accel Vector2 Accel = new Vector2((float)50.0, (float)50.0); if (EO == 0) { Front.setSpeed(Front.getSpeed() + Accel); Back.setSpeed(Back.getSpeed() + Accel); //Left.setSpeed(Left.getSpeed() + Accel); Right.setSpeed(Right.getSpeed() + Accel); EO = 1; } //Deccel Vector2 Deccel = new Vector2((float)50.0, (float)50.0); if (EO == 1) { Front.setSpeed(Front.getSpeed() + Deccel); Back.setSpeed(Back.getSpeed() + Deccel); //Left.setSpeed(Left.getSpeed() + Deccel); Right.setSpeed(Right.getSpeed() + Deccel); EO = 0; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Reflection; using Xunit; namespace System.Linq.Expressions.Tests { public static class LiftedSubtractCheckedNullableTests { #region Test methods [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedSubtractCheckedNullableByteTest(bool useInterpreter) { byte?[] values = new byte?[] { null, 0, 1, byte.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifySubtractCheckedNullableByte(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedSubtractCheckedNullableCharTest(bool useInterpreter) { char?[] values = new char?[] { null, '\0', '\b', 'A', '\uffff' }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifySubtractCheckedNullableChar(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedSubtractCheckedNullableDecimalTest(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++) { for (int j = 0; j < values.Length; j++) { VerifySubtractCheckedNullableDecimal(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedSubtractCheckedNullableDoubleTest(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++) { for (int j = 0; j < values.Length; j++) { VerifySubtractCheckedNullableDouble(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedSubtractCheckedNullableFloatTest(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++) { for (int j = 0; j < values.Length; j++) { VerifySubtractCheckedNullableFloat(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedSubtractCheckedNullableIntTest(bool useInterpreter) { int?[] values = new int?[] { null, 0, 1, -1, int.MinValue, int.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifySubtractCheckedNullableInt(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedSubtractCheckedNullableLongTest(bool useInterpreter) { long?[] values = new long?[] { null, 0, 1, -1, long.MinValue, long.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifySubtractCheckedNullableLong(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedSubtractCheckedNullableSByteTest(bool useInterpreter) { sbyte?[] values = new sbyte?[] { null, 0, 1, -1, sbyte.MinValue, sbyte.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifySubtractCheckedNullableSByte(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedSubtractCheckedNullableShortTest(bool useInterpreter) { short?[] values = new short?[] { null, 0, 1, -1, short.MinValue, short.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifySubtractCheckedNullableShort(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedSubtractCheckedNullableUIntTest(bool useInterpreter) { uint?[] values = new uint?[] { null, 0, 1, uint.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifySubtractCheckedNullableUInt(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedSubtractCheckedNullableULongTest(bool useInterpreter) { ulong?[] values = new ulong?[] { null, 0, 1, ulong.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifySubtractCheckedNullableULong(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedSubtractCheckedNullableUShortTest(bool useInterpreter) { ushort?[] values = new ushort?[] { null, 0, 1, ushort.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifySubtractCheckedNullableUShort(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedSubtractCheckedNullableNumberTest(bool useInterpreter) { Number?[] values = new Number?[] { null, new Number(0), new Number(1), Number.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifySubtractCheckedNullableNumber(values[i], values[j], useInterpreter); } } } #endregion #region Helpers public static byte SubtractCheckedNullableByte(byte a, byte b) { return checked((byte)(a - b)); } public static char SubtractCheckedNullableChar(char a, char b) { return checked((char)(a - b)); } public static decimal SubtractCheckedNullableDecimal(decimal a, decimal b) { return checked(a - b); } public static double SubtractCheckedNullableDouble(double a, double b) { return checked(a - b); } public static float SubtractCheckedNullableFloat(float a, float b) { return checked(a - b); } public static int SubtractCheckedNullableInt(int a, int b) { return checked(a - b); } public static long SubtractCheckedNullableLong(long a, long b) { return checked(a - b); } public static sbyte SubtractCheckedNullableSByte(sbyte a, sbyte b) { return checked((sbyte)(a - b)); } public static short SubtractCheckedNullableShort(short a, short b) { return checked((short)(a - b)); } public static uint SubtractCheckedNullableUInt(uint a, uint b) { return checked(a - b); } public static ulong SubtractCheckedNullableULong(ulong a, ulong b) { return checked(a - b); } public static ushort SubtractCheckedNullableUShort(ushort a, ushort b) { return checked((ushort)(a - b)); } #endregion #region Test verifiers private static void VerifySubtractCheckedNullableByte(byte? a, byte? b, bool useInterpreter) { Expression<Func<byte?>> e = Expression.Lambda<Func<byte?>>( Expression.SubtractChecked( Expression.Constant(a, typeof(byte?)), Expression.Constant(b, typeof(byte?)), typeof(LiftedSubtractCheckedNullableTests).GetTypeInfo().GetDeclaredMethod("SubtractCheckedNullableByte"))); Func<byte?> f = e.Compile(useInterpreter); if (a < b) Assert.Throws<OverflowException>(() => f()); else Assert.Equal(checked((byte?)(a - b)), f()); } private static void VerifySubtractCheckedNullableChar(char? a, char? b, bool useInterpreter) { Expression<Func<char?>> e = Expression.Lambda<Func<char?>>( Expression.SubtractChecked( Expression.Constant(a, typeof(char?)), Expression.Constant(b, typeof(char?)), typeof(LiftedSubtractCheckedNullableTests).GetTypeInfo().GetDeclaredMethod("SubtractCheckedNullableChar"))); Func<char?> f = e.Compile(useInterpreter); if (a < b) Assert.Throws<OverflowException>(() => f()); else Assert.Equal(checked((char?)(a - b)), f()); } private static void VerifySubtractCheckedNullableDecimal(decimal? a, decimal? b, bool useInterpreter) { Expression<Func<decimal?>> e = Expression.Lambda<Func<decimal?>>( Expression.SubtractChecked( Expression.Constant(a, typeof(decimal?)), Expression.Constant(b, typeof(decimal?)), typeof(LiftedSubtractCheckedNullableTests).GetTypeInfo().GetDeclaredMethod("SubtractCheckedNullableDecimal"))); Func<decimal?> f = e.Compile(useInterpreter); decimal? expected = default(decimal); try { expected = checked(a - b); } catch (OverflowException) { Assert.Throws<OverflowException>(() => f()); return; } Assert.Equal(expected, f()); } private static void VerifySubtractCheckedNullableDouble(double? a, double? b, bool useInterpreter) { Expression<Func<double?>> e = Expression.Lambda<Func<double?>>( Expression.SubtractChecked( Expression.Constant(a, typeof(double?)), Expression.Constant(b, typeof(double?)), typeof(LiftedSubtractCheckedNullableTests).GetTypeInfo().GetDeclaredMethod("SubtractCheckedNullableDouble"))); Func<double?> f = e.Compile(useInterpreter); Assert.Equal(a - b, f()); } private static void VerifySubtractCheckedNullableFloat(float? a, float? b, bool useInterpreter) { Expression<Func<float?>> e = Expression.Lambda<Func<float?>>( Expression.SubtractChecked( Expression.Constant(a, typeof(float?)), Expression.Constant(b, typeof(float?)), typeof(LiftedSubtractCheckedNullableTests).GetTypeInfo().GetDeclaredMethod("SubtractCheckedNullableFloat"))); Func<float?> f = e.Compile(useInterpreter); Assert.Equal(a - b, f()); } private static void VerifySubtractCheckedNullableInt(int? a, int? b, bool useInterpreter) { Expression<Func<int?>> e = Expression.Lambda<Func<int?>>( Expression.SubtractChecked( Expression.Constant(a, typeof(int?)), Expression.Constant(b, typeof(int?)), typeof(LiftedSubtractCheckedNullableTests).GetTypeInfo().GetDeclaredMethod("SubtractCheckedNullableInt"))); Func<int?> f = e.Compile(useInterpreter); long? expected = (long?)a - b; if (expected < int.MinValue | expected > int.MaxValue) Assert.Throws<OverflowException>(() => f()); else Assert.Equal((int?)expected, f()); } private static void VerifySubtractCheckedNullableLong(long? a, long? b, bool useInterpreter) { Expression<Func<long?>> e = Expression.Lambda<Func<long?>>( Expression.SubtractChecked( Expression.Constant(a, typeof(long?)), Expression.Constant(b, typeof(long?)), typeof(LiftedSubtractCheckedNullableTests).GetTypeInfo().GetDeclaredMethod("SubtractCheckedNullableLong"))); Func<long?> f = e.Compile(useInterpreter); long? expected = null; try { expected = checked(a - b); } catch (OverflowException) { Assert.Throws<OverflowException>(() => f()); return; } Assert.Equal(expected, f()); } private static void VerifySubtractCheckedNullableSByte(sbyte? a, sbyte? b, bool useInterpreter) { Expression<Func<sbyte?>> e = Expression.Lambda<Func<sbyte?>>( Expression.SubtractChecked( Expression.Constant(a, typeof(sbyte?)), Expression.Constant(b, typeof(sbyte?)), typeof(LiftedSubtractCheckedNullableTests).GetTypeInfo().GetDeclaredMethod("SubtractCheckedNullableSByte"))); Func<sbyte?> f = e.Compile(useInterpreter); int? expected = a - b; if (expected < sbyte.MinValue | expected > sbyte.MaxValue) Assert.Throws<OverflowException>(() => f()); else Assert.Equal(expected, f()); } private static void VerifySubtractCheckedNullableShort(short? a, short? b, bool useInterpreter) { Expression<Func<short?>> e = Expression.Lambda<Func<short?>>( Expression.SubtractChecked( Expression.Constant(a, typeof(short?)), Expression.Constant(b, typeof(short?)), typeof(LiftedSubtractCheckedNullableTests).GetTypeInfo().GetDeclaredMethod("SubtractCheckedNullableShort"))); Func<short?> f = e.Compile(useInterpreter); int? expected = a - b; if (expected < short.MinValue | expected > short.MaxValue) Assert.Throws<OverflowException>(() => f()); else Assert.Equal(expected, f()); } private static void VerifySubtractCheckedNullableUInt(uint? a, uint? b, bool useInterpreter) { Expression<Func<uint?>> e = Expression.Lambda<Func<uint?>>( Expression.SubtractChecked( Expression.Constant(a, typeof(uint?)), Expression.Constant(b, typeof(uint?)), typeof(LiftedSubtractCheckedNullableTests).GetTypeInfo().GetDeclaredMethod("SubtractCheckedNullableUInt"))); Func<uint?> f = e.Compile(useInterpreter); if (a < b) Assert.Throws<OverflowException>(() => f()); else Assert.Equal(a - b, f()); } private static void VerifySubtractCheckedNullableULong(ulong? a, ulong? b, bool useInterpreter) { Expression<Func<ulong?>> e = Expression.Lambda<Func<ulong?>>( Expression.SubtractChecked( Expression.Constant(a, typeof(ulong?)), Expression.Constant(b, typeof(ulong?)), typeof(LiftedSubtractCheckedNullableTests).GetTypeInfo().GetDeclaredMethod("SubtractCheckedNullableULong"))); Func<ulong?> f = e.Compile(useInterpreter); if (a < b) Assert.Throws<OverflowException>(() => f()); else Assert.Equal(a - b, f()); } private static void VerifySubtractCheckedNullableUShort(ushort? a, ushort? b, bool useInterpreter) { Expression<Func<ushort?>> e = Expression.Lambda<Func<ushort?>>( Expression.SubtractChecked( Expression.Constant(a, typeof(ushort?)), Expression.Constant(b, typeof(ushort?)), typeof(LiftedSubtractCheckedNullableTests).GetTypeInfo().GetDeclaredMethod("SubtractCheckedNullableUShort"))); Func<ushort?> f = e.Compile(useInterpreter); if (a < b) Assert.Throws<OverflowException>(() => f()); else Assert.Equal(a - b, f()); } private static void VerifySubtractCheckedNullableNumber(Number? a, Number? b, bool useInterpreter) { Expression<Func<Number?>> e = Expression.Lambda<Func<Number?>>( Expression.Subtract( Expression.Constant(a, typeof(Number?)), Expression.Constant(b, typeof(Number?)))); Assert.Equal(typeof(Number?), e.Body.Type); Func<Number?> f = e.Compile(useInterpreter); Number? expected = a - b; Assert.Equal(expected, f()); // NB: checked behavior doesn't apply to non-primitive types } #endregion } }
// // Encog(tm) Core v3.3 - .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.Linq; using System.Text; using Encog.MathUtil; using Encog.Util.KMeans; namespace Encog.ML.Data.Basic { /// <summary> /// This class implements a data object that can hold complex numbers. It /// implements the interface MLData, so it can be used with nearly any Encog /// machine learning method. However, not all Encog machine learning methods /// are designed to work with complex numbers. A Encog machine learning method /// that does not support complex numbers will only be dealing with the /// real-number portion of the complex number. /// </summary> [Serializable] public class BasicMLComplexData : IMLComplexData { /// <summary> /// The data held by this object. /// </summary> private ComplexNumber[] _data; /// <summary> /// Construct this object with the specified data. Use only real numbers. /// </summary> /// <param name="d">The data to construct this object with.</param> public BasicMLComplexData(double[] d) : this(d.Length) { } /// <summary> /// Construct this object with the specified data. Use complex numbers. /// </summary> /// <param name="d">The data to construct this object with.</param> public BasicMLComplexData(ComplexNumber[] d) { _data = d; } /// <summary> /// Construct this object with blank data and a specified size. /// </summary> /// <param name="size">The amount of data to store.</param> public BasicMLComplexData(int size) { _data = new ComplexNumber[size]; } /// <summary> /// Construct a new BasicMLData object from an existing one. This makes a /// copy of an array. If MLData is not complex, then only reals will be /// created. /// </summary> /// <param name="d">The object to be copied.</param> public BasicMLComplexData(IMLData d) { if (d is IMLComplexData) { var c = (IMLComplexData) d; for (int i = 0; i < d.Count; i++) { _data[i] = new ComplexNumber(c.GetComplexData(i)); } } else { for (int i = 0; i < d.Count; i++) { _data[i] = new ComplexNumber(d[i], 0); } } } #region IMLComplexData Members /// <summary> /// Clear all values to zero. /// </summary> public void Clear() { for (int i = 0; i < _data.Length; i++) { _data[i] = new ComplexNumber(0, 0); } } /// <inheritdoc/> public Object Clone() { return new BasicMLComplexData(this); } /// <summary> /// The complex numbers. /// </summary> public ComplexNumber[] ComplexData { get { return _data; } set { _data = value; } } /// <inheritdoc/> public ComplexNumber GetComplexData(int index) { return _data[index]; } /// <summary> /// Set a data element to a complex number. /// </summary> /// <param name="index">The index to set.</param> /// <param name="d">The complex number.</param> public void SetComplexData(int index, ComplexNumber d) { _data[index] = d; } /// <summary> /// Set the complex data array. /// </summary> /// <param name="d">A new complex data array.</param> public void SetComplexData(ComplexNumber[] d) { _data = d; } /// <summary> /// Access the data by index. /// </summary> /// <param name="x">The index to access.</param> /// <returns></returns> public virtual double this[int x] { get { return _data[x].Real; } set { _data[x] = new ComplexNumber(value, 0); } } /// <summary> /// Get the data as an array. /// </summary> public virtual double[] Data { get { var d = new double[_data.Length]; for (int i = 0; i < d.Length; i++) { d[i] = _data[i].Real; } return d; } set { for (int i = 0; i < value.Length; i++) { _data[i] = new ComplexNumber(value[i], 0); } } } /// <inheritdoc/> public int Count { get { return _data.Count(); } } #endregion /// <inheritdoc/> public override String ToString() { var builder = new StringBuilder("["); builder.Append(GetType().Name); builder.Append(":"); for (int i = 0; i < _data.Length; i++) { if (i != 0) { builder.Append(','); } builder.Append(_data[i].ToString()); } builder.Append("]"); return builder.ToString(); } /// <summary> /// Not supported. /// </summary> /// <returns>Nothing.</returns> public ICentroid<IMLData> CreateCentroid() { return null; } public void CopyTo(double[] target, int targetIndex, int count) { for(int i = 0; i < count; i++) target[i + targetIndex] = _data[i].Real; } } }
// Copyright (c) 2013-2018 SIL International // This software is licensed under the MIT License (http://opensource.org/licenses/MIT) using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Windows.Forms; using SIL.Keyboarding; namespace SIL.Windows.Forms.Keyboarding.Windows { /// <summary> /// Class for handling Windows system keyboards /// </summary> internal class WinKeyboardAdaptor : IKeyboardRetrievingAdaptor { public bool IsApplicable => true; public IKeyboardSwitchingAdaptor SwitchingAdaptor { get; private set; } public WinKeyboardAdaptor() { try { ProcessorProfiles = new TfInputProcessorProfilesClass(); } catch (InvalidCastException) { ProcessorProfiles = null; return; } // ProfileMgr will be null on Windows XP - the interface got introduced in Vista ProfileManager = ProcessorProfiles as ITfInputProcessorProfileMgr; SwitchingAdaptor = new WindowsKeyboardSwitchingAdapter(); } private static string GetDisplayName(string layout, string locale) { return $"{layout} - {locale}"; } private IEnumerable<Tuple<TfInputProcessorProfile, ushort, IntPtr>> GetInputMethodsThroughWinApi() { int countKeyboardLayouts = Win32.GetKeyboardLayoutList(0, IntPtr.Zero); if (countKeyboardLayouts == 0) yield break; IntPtr keyboardLayouts = Marshal.AllocCoTaskMem(countKeyboardLayouts * IntPtr.Size); try { Win32.GetKeyboardLayoutList(countKeyboardLayouts, keyboardLayouts); IntPtr current = keyboardLayouts; var elemSize = (ulong)IntPtr.Size; for (int i = 0; i < countKeyboardLayouts; i++) { var hkl = (IntPtr)Marshal.ReadInt32(current); yield return Tuple.Create(new TfInputProcessorProfile(), HklToLangId(hkl), hkl); current = (IntPtr)((ulong)current + elemSize); } } finally { Marshal.FreeCoTaskMem(keyboardLayouts); } } private static ushort HklToLangId(IntPtr hkl) { return (ushort)((uint)hkl & 0xffff); } public void UpdateAvailableKeyboards() { var curKeyboards = KeyboardController.Instance.Keyboards.OfType<WinKeyboardDescription>().ToDictionary(kd => kd.Id); foreach (InputLanguage inputLanguage in InputLanguage.InstalledInputLanguages) { var keyboardId = $"{inputLanguage.Culture.Name}_{inputLanguage.LayoutName}"; var keyboardLayoutName = GetBestAvailableKeyboardName(inputLanguage); CultureInfo culture; string cultureName; try { culture = new CultureInfo(inputLanguage.Culture.Name); cultureName = culture.DisplayName; } catch (CultureNotFoundException) { // This can happen for old versions of Keyman that created a custom culture that is invalid to .Net. // Also see http://stackoverflow.com/a/24820530/4953232 culture = new CultureInfo("en-US"); cultureName = "[Unknown Language]"; } WinKeyboardDescription existingKeyboard; if (curKeyboards.TryGetValue(keyboardId, out existingKeyboard)) { if (!existingKeyboard.IsAvailable) { existingKeyboard.SetIsAvailable(true); existingKeyboard.SetLocalizedName(keyboardLayoutName.LocalizedName); } curKeyboards.Remove(keyboardId); } else { // Prevent a keyboard with this id from being registered again. // Potentially, id's are duplicated. e.g. A Keyman keyboard linked to a windows one. // For now we simply ignore this second registration. // A future enhancement would be to include knowledge of the driver in the Keyboard definition so // we could choose the best one to register. KeyboardDescription keyboard; if (!KeyboardController.Instance.Keyboards.TryGet(keyboardId, out keyboard)) { KeyboardController.Instance.Keyboards.Add( new WinKeyboardDescription(keyboardId, GetDisplayName(keyboardLayoutName.LocalizedName, cultureName), keyboardLayoutName.Name, inputLanguage.Culture.Name, true, new InputLanguageWrapper(inputLanguage), this)); } } } // Set each unhanandled keyboard to unavailable foreach (var existingKeyboard in curKeyboards.Values) { existingKeyboard.SetIsAvailable(false); } } private LayoutName GetBestAvailableKeyboardName(InputLanguage inputLanguage) { try { var profilesEnumerator = ProfileManager.EnumProfiles((short)inputLanguage.Culture.KeyboardLayoutId); TfInputProcessorProfile[] profiles = new TfInputProcessorProfile[1]; while (profilesEnumerator.Next(1, profiles) == 1) { // We only deal with keyboards; skip other input methods if (profiles[0].CatId != Guids.Consts.TfcatTipKeyboard) continue; if ((profiles[0].Flags & TfIppFlags.Enabled) == 0) continue; if (profiles[0].Hkl == IntPtr.Zero && profiles[0].ProfileType != TfProfileType.Illegal) { return new LayoutName(inputLanguage.LayoutName, ProcessorProfiles.GetLanguageProfileDescription(ref profiles[0].ClsId, profiles[0].LangId, ref profiles[0].GuidProfile)); } } } catch (Exception e) { Debug.WriteLine($"Error looking up keyboards for language {inputLanguage.Culture.Name} - {(short)inputLanguage.Culture.KeyboardLayoutId}"); } return new LayoutName(inputLanguage.LayoutName, inputLanguage.Culture.DisplayName); } public ITfInputProcessorProfiles ProcessorProfiles { get; set; } public ITfInputProcessorProfileMgr ProfileManager { get; set; } #region IKeyboardRetrievingAdaptor Members /// <summary> /// The type of keyboards this adaptor handles: system or other (like Keyman, ibus...) /// </summary> public KeyboardAdaptorType Type => KeyboardAdaptorType.System; public void Initialize() { UpdateAvailableKeyboards(); } /// <summary> /// Creates and returns a keyboard definition object based on the ID. /// Note that this method is used when we do NOT have a matching available keyboard. /// Therefore we can presume that the created one is NOT available. /// </summary> public KeyboardDescription CreateKeyboardDefinition(string id) { string layout, locale; KeyboardController.GetLayoutAndLocaleFromLanguageId(id, out layout, out locale); string cultureName; var inputLanguage = WinKeyboardUtils.GetInputLanguage(locale, layout, out cultureName); return new WinKeyboardDescription(id, GetDisplayName(layout, cultureName), layout, cultureName, false, inputLanguage, this); } public bool CanHandleFormat(KeyboardFormat format) { switch (format) { case KeyboardFormat.Msklc: case KeyboardFormat.Unknown: return true; } return false; } public Action GetKeyboardSetupAction() { return () => { using (Process.Start(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "control.exe"), "input.dll")) {} }; } public bool IsSecondaryKeyboardSetupApplication => false; #endregion #region IDisposable & Co. implementation // Region last reviewed: never /// <summary> /// See if the object has been disposed. /// </summary> public bool IsDisposed { get; private set; } /// <summary> /// Finalizer, in case client doesn't dispose it. /// Force Dispose(false) if not already called (i.e. m_isDisposed is true) /// </summary> /// <remarks> /// In case some clients forget to dispose it directly. /// </remarks> ~WinKeyboardAdaptor() { Dispose(false); // The base class finalizer is called automatically. } /// <summary/> /// <remarks>Must not be virtual.</remarks> public void Dispose() { Dispose(true); // This object will be cleaned up by the Dispose method. // Therefore, you should call GC.SupressFinalize to // take this object off the finalization queue // and prevent finalization code for this object // from executing a second time. GC.SuppressFinalize(this); } /// <summary> /// Executes in two distinct scenarios. /// /// 1. If disposing is true, the method has been called directly /// or indirectly by a user's code via the Dispose method. /// Both managed and unmanaged resources can be disposed. /// /// 2. If disposing is false, the method has been called by the /// runtime from inside the finalizer and you should not reference (access) /// other managed objects, as they already have been garbage collected. /// Only unmanaged resources can be disposed. /// </summary> /// <param name="disposing"></param> /// <remarks> /// If any exceptions are thrown, that is fine. /// If the method is being done in a finalizer, it will be ignored. /// If it is thrown by client code calling Dispose, /// it needs to be handled by fixing the bug. /// /// If subclasses override this method, they should call the base implementation. /// </remarks> protected virtual void Dispose(bool disposing) { Debug.WriteLineIf(!disposing, "****************** " + GetType().Name + " 'disposing' is false. ******************"); // Must not be run more than once. (SwitchingAdaptor as IDisposable)?.Dispose(); // Dispose unmanaged resources here, whether disposing is true or false. IsDisposed = true; } #endregion IDisposable & Co. implementation } }
// 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. using System; using System.IO; using System.Drawing.Imaging; using System.Diagnostics.Contracts; namespace System.Drawing { // Summary: // Encapsulates a GDI+ bitmap, which consists of the pixel data for a graphics // image and its attributes. A System.Drawing.Bitmap is an object used to work // with images defined by pixel data. //[Serializable] //[ComVisible(true)] //[Editor("System.Drawing.Design.BitmapEditor, System.Drawing.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof(UITypeEditor))] public sealed class Bitmap //: Image { // Summary: // Initializes a new instance of the System.Drawing.Bitmap class from the specified // existing image. // // Parameters: // original: // The System.Drawing.Image from which to create the new System.Drawing.Bitmap. public Bitmap(Image original) { Contract.Requires(original != null); } // // Summary: // Initializes a new instance of the System.Drawing.Bitmap class from the specified // data stream. // // Parameters: // stream: // The data stream used to load the image. // // Exceptions: // System.ArgumentException: // stream does not contain image data or is null.-or-stream contains a PNG image // file with a single dimension greater than 65,535 pixels. public Bitmap(Stream stream) { Contract.Requires(stream != null); } // // Summary: // Initializes a new instance of the System.Drawing.Bitmap class from the specified // file. // // Parameters: // filename: // The name of the bitmap file. //public Bitmap(string filename); // // Summary: // Initializes a new instance of the System.Drawing.Bitmap class from the specified // existing image, scaled to the specified size. // // Parameters: // original: // The System.Drawing.Image from which to create the new System.Drawing.Bitmap. // // newSize: // The System.Drawing.Size structure that represent the size of the new System.Drawing.Bitmap. // // Exceptions: // System.Exception: // The operation failed. public Bitmap(Image original, Size newSize) { Contract.Requires(original != null); } // // Summary: // Initializes a new instance of the System.Drawing.Bitmap class with the specified // size. // // Parameters: // width: // The width, in pixels, of the new System.Drawing.Bitmap. // // height: // The height, in pixels, of the new System.Drawing.Bitmap. // // Exceptions: // System.Exception: // The operation failed. //public Bitmap(int width, int height); // // Summary: // Initializes a new instance of the System.Drawing.Bitmap class from the specified // data stream. // // Parameters: // stream: // The data stream used to load the image. // // useIcm: // true to use color correction for this System.Drawing.Bitmap; otherwise, false. // // Exceptions: // System.ArgumentException: // stream does not contain image data or is null.-or-stream contains a PNG image // file with a single dimension greater than 65,535 pixels. //public Bitmap(Stream stream, bool useIcm); // // Summary: // Initializes a new instance of the System.Drawing.Bitmap class from the specified // file. // // Parameters: // filename: // The name of the bitmap file. // // useIcm: // true to use color correction for this System.Drawing.Bitmap; otherwise, false. //public Bitmap(string filename, bool useIcm); // // Summary: // Initializes a new instance of the System.Drawing.Bitmap class from a specified // resource. // // Parameters: // type: // The class used to extract the resource. // // resource: // The name of the resource. //public Bitmap(Type type, string resource); // // Summary: // Initializes a new instance of the System.Drawing.Bitmap class from the specified // existing image, scaled to the specified size. // // Parameters: // original: // The System.Drawing.Image from which to create the new System.Drawing.Bitmap. // // width: // The width, in pixels, of the new System.Drawing.Bitmap. // // height: // The height, in pixels, of the new System.Drawing.Bitmap. // // Exceptions: // System.Exception: // The operation failed. //public Bitmap(Image original, int width, int height); // // Summary: // Initializes a new instance of the System.Drawing.Bitmap class with the specified // size and with the resolution of the specified System.Drawing.Graphics object. // // Parameters: // width: // The width, in pixels, of the new System.Drawing.Bitmap. // // height: // The height, in pixels, of the new System.Drawing.Bitmap. // // g: // The System.Drawing.Graphics object that specifies the resolution for the // new System.Drawing.Bitmap. // // Exceptions: // System.ArgumentNullException: // g is null. public Bitmap(int width, int height, Graphics g) { Contract.Requires(g != null); } // // Summary: // Initializes a new instance of the System.Drawing.Bitmap class with the specified // size and format. // // Parameters: // width: // The width, in pixels, of the new System.Drawing.Bitmap. // // height: // The height, in pixels, of the new System.Drawing.Bitmap. // // format: // The System.Drawing.Imaging.PixelFormat enumeration for the new System.Drawing.Bitmap. //public Bitmap(int width, int height, PixelFormat format); // // Summary: // Initializes a new instance of the System.Drawing.Bitmap class with the specified // size, pixel format, and pixel data. // // Parameters: // width: // The width, in pixels, of the new System.Drawing.Bitmap. // // height: // The height, in pixels, of the new System.Drawing.Bitmap. // // stride: // Integer that specifies the byte offset between the beginning of one scan // line and the next. This is usually (but not necessarily) the number of bytes // in the pixel format (for example, 2 for 16 bits per pixel) multiplied by // the width of the bitmap. The value passed to this parameter must be a multiple // of four.. // // format: // The System.Drawing.Imaging.PixelFormat enumeration for the new System.Drawing.Bitmap. // // scan0: // Pointer to an array of bytes that contains the pixel data. //public Bitmap(int width, int height, int stride, PixelFormat format, IntPtr scan0); // Summary: // Creates a copy of the section of this System.Drawing.Bitmap defined by System.Drawing.Rectangle // structure and with a specified System.Drawing.Imaging.PixelFormat enumeration. // // Parameters: // rect: // Defines the portion of this System.Drawing.Bitmap to copy. Coordinates are // relative to this System.Drawing.Bitmap. // // format: // Specifies the System.Drawing.Imaging.PixelFormat enumeration for the destination // System.Drawing.Bitmap. // // Returns: // The new System.Drawing.Bitmap that this method creates. // // Exceptions: // System.OutOfMemoryException: // rect is outside of the source bitmap bounds. // // System.ArgumentException: // The height or width of rect is 0. //public Bitmap Clone(Rectangle rect, PixelFormat format) //{ // Contract.Ensures(Contract.Result<Bitmap>() != null); // return default(Bitmap); //} // // Summary: // Creates a copy of the section of this System.Drawing.Bitmap defined with // a specified System.Drawing.Imaging.PixelFormat enumeration. // // Parameters: // rect: // Defines the portion of this System.Drawing.Bitmap to copy. // // format: // Specifies the System.Drawing.Imaging.PixelFormat enumeration for the destination // System.Drawing.Bitmap. // // Returns: // The System.Drawing.Bitmap that this method creates. // // Exceptions: // System.OutOfMemoryException: // rect is outside of the source bitmap bounds. // // System.ArgumentException: // The height or width of rect is 0. //public Bitmap Clone(RectangleF rect, PixelFormat format); // // Summary: // Creates a System.Drawing.Bitmap from a Windows handle to an icon. // // Parameters: // hicon: // A handle to an icon. // // Returns: // The System.Drawing.Bitmap that this method creates. public static Bitmap FromHicon(IntPtr hicon) { Contract.Ensures(Contract.Result<Bitmap>() != null); return default(Bitmap); } // // Summary: // Creates a System.Drawing.Bitmap from the specified Windows resource. // // Parameters: // hinstance: // A handle to an instance of the executable file that contains the resource. // // bitmapName: // A string containing the name of the resource bitmap. // // Returns: // The System.Drawing.Bitmap that this method creates. public static Bitmap FromResource(IntPtr hinstance, string bitmapName) { Contract.Ensures(Contract.Result<Bitmap>() != null); return default(Bitmap); } // // Summary: // Creates a GDI bitmap object from this System.Drawing.Bitmap. // // Returns: // A handle to the GDI bitmap object that this method creates. // // Exceptions: // System.ArgumentException: // The height or width of the bitmap is greater than System.Int16.MaxValue. // // System.Exception: // The operation failed. //[EditorBrowsable(EditorBrowsableState.Advanced)] //public IntPtr GetHbitmap(); // // Summary: // Creates a GDI bitmap object from this System.Drawing.Bitmap. // // Parameters: // background: // A System.Drawing.Color structure that specifies the background color. This // parameter is ignored if the bitmap is totally opaque. // // Returns: // A handle to the GDI bitmap object that this method creates. // // Exceptions: // System.ArgumentException: // The height or width of the bitmap is greater than System.Int16.MaxValue. // // System.Exception: // The operation failed. //[EditorBrowsable(EditorBrowsableState.Advanced)] //public IntPtr GetHbitmap(Color background); // // Summary: // Returns the handle to an icon. // // Returns: // A Windows handle to an icon with the same image as the System.Drawing.Bitmap. // // Exceptions: // System.Exception: // The operation failed. //[EditorBrowsable(EditorBrowsableState.Advanced)] //public IntPtr GetHicon(); // // Summary: // Gets the color of the specified pixel in this System.Drawing.Bitmap. // // Parameters: // x: // The x-coordinate of the pixel to retrieve. // // y: // The y-coordinate of the pixel to retrieve. // // Returns: // A System.Drawing.Color structure that represents the color of the specified // pixel. // // Exceptions: // System.ArgumentOutOfRangeException: // x is less than 0, or greater than or equal to System.Drawing.Image.Width. // ory is less than 0, or greater than or equal to System.Drawing.Image.Height // // System.Exception: // The operation failed. public Color GetPixel(int x, int y) { Contract.Requires(x >= 0); Contract.Requires(y>= 0); return default(Color); } // // Summary: // Locks a System.Drawing.Bitmap into system memory. // // Parameters: // rect: // A System.Drawing.Rectangle structure specifying the portion of the System.Drawing.Bitmap // to lock. // // flags: // An System.Drawing.Imaging.ImageLockMode enumeration specifying the access // level (read/write) for the System.Drawing.Bitmap. // // format: // A System.Drawing.Imaging.PixelFormat enumeration specifying the data format // of this System.Drawing.Bitmap. // // Returns: // A System.Drawing.Imaging.BitmapData containing information about this lock // operation. // // Exceptions: // System.ArgumentException: // The System.Drawing.Imaging.PixelFormat is not a specific bits-per-pixel value.-or-The // incorrect System.Drawing.Imaging.PixelFormat is passed in for a bitmap. // // System.Exception: // The operation failed. public BitmapData LockBits(Rectangle rect, ImageLockMode flags, PixelFormat format) { Contract.Ensures(Contract.Result<BitmapData>() != null); return default(BitmapData); } // // Summary: // Locks a System.Drawing.Bitmap into system memory // // Parameters: // rect: // A rectangle structure specifying the portion of the System.Drawing.Bitmap // to lock. // // flags: // One of the System.Drawing.Imaging.ImageLockMode values specifying the access // level (read/write) for the System.Drawing.Bitmap. // // format: // One of the System.Drawing.Imaging.PixelFormat values indicating the data // format of the System.Drawing.Bitmap. // // bitmapData: // A System.Drawing.Imaging.BitmapData containing information about the lock // operation. // // Returns: // A System.Drawing.Imaging.BitmapData containing information about the lock // operation. // // Exceptions: // System.ArgumentException: // System.Drawing.Imaging.PixelFormat value is not a specific bits-per-pixel // value.-or-The incorrect System.Drawing.Imaging.PixelFormat is passed in for // a bitmap. // // System.Exception: // The operation failed. public BitmapData LockBits(Rectangle rect, ImageLockMode flags, PixelFormat format, BitmapData bitmapData) { Contract.Ensures(Contract.Result<BitmapData>() != null); return default(BitmapData); } // // Summary: // Makes the default transparent color transparent for this System.Drawing.Bitmap. // // Returns: // This method does not return a value. // // Exceptions: // System.InvalidOperationException: // The image format of the System.Drawing.Bitmap is an icon format. // // System.Exception: // The operation failed. //public void MakeTransparent(); // // Summary: // Makes the specified color transparent for this System.Drawing.Bitmap. // // Parameters: // transparentColor: // The System.Drawing.Color structure that represents the color to make transparent. // // Exceptions: // System.InvalidOperationException: // The image format of the System.Drawing.Bitmap is an icon format. // // System.Exception: // The operation failed. //public void MakeTransparent(Color transparentColor); // // Summary: // Sets the color of the specified pixel in this System.Drawing.Bitmap. // // Parameters: // x: // The x-coordinate of the pixel to set. // // y: // The y-coordinate of the pixel to set. // // color: // A System.Drawing.Color structure that represents the color to assign to the // specified pixel. // // Returns: // This method does not return a value. // // Exceptions: // System.Exception: // The operation failed. //public void SetPixel(int x, int y, Color color); // // Summary: // Sets the resolution for this System.Drawing.Bitmap. // // Parameters: // xDpi: // The horizontal resolution, in dots per inch, of the System.Drawing.Bitmap. // // yDpi: // The vertical resolution, in dots per inch, of the System.Drawing.Bitmap. // // Exceptions: // System.Exception: // The operation failed. //public void SetResolution(float xDpi, float yDpi); // // Summary: // Unlocks this System.Drawing.Bitmap from system memory. // // Parameters: // bitmapdata: // A System.Drawing.Imaging.BitmapData specifying information about the lock // operation. // // Exceptions: // System.Exception: // The operation failed. //public void UnlockBits(BitmapData bitmapdata); } }
// ******************************************************************************************************** // Product Name: DotSpatial.Projection // Description: The basic module for MapWindow version 6.0 // ******************************************************************************************************** // // The Original Code is from MapWindow.dll version 6.0 // // The Initial Developer of this Original Code is Ted Dunsford. Created 8/14/2009 4:07:32 PM // // Contributor(s): (Open source contributors should list themselves and their modifications here). // Name | Date | Comment // --------------------|------------|------------------------------------------------------------ // Ted Dunsford | 5/3/2010 | Updated project to DotSpatial.Projection and license to LGPL // ******************************************************************************************************** #pragma warning disable 1591 namespace DotSpatial.Projections.GeographicCategories { /// <summary> /// CountySystems /// </summary> public class CountySystems : CoordinateSystemCategory { #region Private Variables public readonly ProjectionInfo NAD1983HARNAdjMNAnoka; public readonly ProjectionInfo NAD1983HARNAdjMNBecker; public readonly ProjectionInfo NAD1983HARNAdjMNBeltramiNorth; public readonly ProjectionInfo NAD1983HARNAdjMNBeltramiSouth; public readonly ProjectionInfo NAD1983HARNAdjMNBenton; public readonly ProjectionInfo NAD1983HARNAdjMNBigStone; public readonly ProjectionInfo NAD1983HARNAdjMNBlueEarth; public readonly ProjectionInfo NAD1983HARNAdjMNBrown; public readonly ProjectionInfo NAD1983HARNAdjMNCarlton; public readonly ProjectionInfo NAD1983HARNAdjMNCarver; public readonly ProjectionInfo NAD1983HARNAdjMNCassNorth; public readonly ProjectionInfo NAD1983HARNAdjMNCassSouth; public readonly ProjectionInfo NAD1983HARNAdjMNChippewa; public readonly ProjectionInfo NAD1983HARNAdjMNChisago; public readonly ProjectionInfo NAD1983HARNAdjMNCookNorth; public readonly ProjectionInfo NAD1983HARNAdjMNCookSouth; public readonly ProjectionInfo NAD1983HARNAdjMNCottonwood; public readonly ProjectionInfo NAD1983HARNAdjMNCrowWing; public readonly ProjectionInfo NAD1983HARNAdjMNDakota; public readonly ProjectionInfo NAD1983HARNAdjMNDodge; public readonly ProjectionInfo NAD1983HARNAdjMNDouglas; public readonly ProjectionInfo NAD1983HARNAdjMNFaribault; public readonly ProjectionInfo NAD1983HARNAdjMNFillmore; public readonly ProjectionInfo NAD1983HARNAdjMNFreeborn; public readonly ProjectionInfo NAD1983HARNAdjMNGoodhue; public readonly ProjectionInfo NAD1983HARNAdjMNGrant; public readonly ProjectionInfo NAD1983HARNAdjMNHennepin; public readonly ProjectionInfo NAD1983HARNAdjMNHouston; public readonly ProjectionInfo NAD1983HARNAdjMNIsanti; public readonly ProjectionInfo NAD1983HARNAdjMNItascaNorth; public readonly ProjectionInfo NAD1983HARNAdjMNItascaSouth; public readonly ProjectionInfo NAD1983HARNAdjMNJackson; public readonly ProjectionInfo NAD1983HARNAdjMNKanabec; public readonly ProjectionInfo NAD1983HARNAdjMNKandiyohi; public readonly ProjectionInfo NAD1983HARNAdjMNKittson; public readonly ProjectionInfo NAD1983HARNAdjMNKoochiching; public readonly ProjectionInfo NAD1983HARNAdjMNLacQuiParle; public readonly ProjectionInfo NAD1983HARNAdjMNLakeoftheWoodsNorth; public readonly ProjectionInfo NAD1983HARNAdjMNLakeoftheWoodsSouth; public readonly ProjectionInfo NAD1983HARNAdjMNLeSueur; public readonly ProjectionInfo NAD1983HARNAdjMNLincoln; public readonly ProjectionInfo NAD1983HARNAdjMNLyon; public readonly ProjectionInfo NAD1983HARNAdjMNMahnomen; public readonly ProjectionInfo NAD1983HARNAdjMNMarshall; public readonly ProjectionInfo NAD1983HARNAdjMNMartin; public readonly ProjectionInfo NAD1983HARNAdjMNMcLeod; public readonly ProjectionInfo NAD1983HARNAdjMNMeeker; public readonly ProjectionInfo NAD1983HARNAdjMNMorrison; public readonly ProjectionInfo NAD1983HARNAdjMNMower; public readonly ProjectionInfo NAD1983HARNAdjMNMurray; public readonly ProjectionInfo NAD1983HARNAdjMNNicollet; public readonly ProjectionInfo NAD1983HARNAdjMNNobles; public readonly ProjectionInfo NAD1983HARNAdjMNNorman; public readonly ProjectionInfo NAD1983HARNAdjMNOlmsted; public readonly ProjectionInfo NAD1983HARNAdjMNOttertail; public readonly ProjectionInfo NAD1983HARNAdjMNPennington; public readonly ProjectionInfo NAD1983HARNAdjMNPine; public readonly ProjectionInfo NAD1983HARNAdjMNPipestone; public readonly ProjectionInfo NAD1983HARNAdjMNPolk; public readonly ProjectionInfo NAD1983HARNAdjMNPope; public readonly ProjectionInfo NAD1983HARNAdjMNRamsey; public readonly ProjectionInfo NAD1983HARNAdjMNRedLake; public readonly ProjectionInfo NAD1983HARNAdjMNRedwood; public readonly ProjectionInfo NAD1983HARNAdjMNRenville; public readonly ProjectionInfo NAD1983HARNAdjMNRice; public readonly ProjectionInfo NAD1983HARNAdjMNRock; public readonly ProjectionInfo NAD1983HARNAdjMNRoseau; public readonly ProjectionInfo NAD1983HARNAdjMNScott; public readonly ProjectionInfo NAD1983HARNAdjMNSherburne; public readonly ProjectionInfo NAD1983HARNAdjMNSibley; public readonly ProjectionInfo NAD1983HARNAdjMNStLouisCentral; public readonly ProjectionInfo NAD1983HARNAdjMNStLouisNorth; public readonly ProjectionInfo NAD1983HARNAdjMNStLouisSouth; public readonly ProjectionInfo NAD1983HARNAdjMNStearns; public readonly ProjectionInfo NAD1983HARNAdjMNSteele; public readonly ProjectionInfo NAD1983HARNAdjMNStevens; public readonly ProjectionInfo NAD1983HARNAdjMNSwift; public readonly ProjectionInfo NAD1983HARNAdjMNTodd; public readonly ProjectionInfo NAD1983HARNAdjMNTraverse; public readonly ProjectionInfo NAD1983HARNAdjMNWabasha; public readonly ProjectionInfo NAD1983HARNAdjMNWadena; public readonly ProjectionInfo NAD1983HARNAdjMNWaseca; public readonly ProjectionInfo NAD1983HARNAdjMNWatonwan; public readonly ProjectionInfo NAD1983HARNAdjMNWinona; public readonly ProjectionInfo NAD1983HARNAdjMNWright; public readonly ProjectionInfo NAD1983HARNAdjMNYellowMedicine; public readonly ProjectionInfo NAD1983HARNAdjWIAdams; public readonly ProjectionInfo NAD1983HARNAdjWIAshland; public readonly ProjectionInfo NAD1983HARNAdjWIBarron; public readonly ProjectionInfo NAD1983HARNAdjWIBayfield; public readonly ProjectionInfo NAD1983HARNAdjWIBrown; public readonly ProjectionInfo NAD1983HARNAdjWIBuffalo; public readonly ProjectionInfo NAD1983HARNAdjWIBurnett; public readonly ProjectionInfo NAD1983HARNAdjWICalumet; public readonly ProjectionInfo NAD1983HARNAdjWIChippewa; public readonly ProjectionInfo NAD1983HARNAdjWIClark; public readonly ProjectionInfo NAD1983HARNAdjWIColumbia; public readonly ProjectionInfo NAD1983HARNAdjWICrawford; public readonly ProjectionInfo NAD1983HARNAdjWIDane; public readonly ProjectionInfo NAD1983HARNAdjWIDodge; public readonly ProjectionInfo NAD1983HARNAdjWIDoor; public readonly ProjectionInfo NAD1983HARNAdjWIDouglas; public readonly ProjectionInfo NAD1983HARNAdjWIDunn; public readonly ProjectionInfo NAD1983HARNAdjWIEauClaire; public readonly ProjectionInfo NAD1983HARNAdjWIFlorence; public readonly ProjectionInfo NAD1983HARNAdjWIFondduLac; public readonly ProjectionInfo NAD1983HARNAdjWIForest; public readonly ProjectionInfo NAD1983HARNAdjWIGrant; public readonly ProjectionInfo NAD1983HARNAdjWIGreen; public readonly ProjectionInfo NAD1983HARNAdjWIGreenLake; public readonly ProjectionInfo NAD1983HARNAdjWIIowa; public readonly ProjectionInfo NAD1983HARNAdjWIIron; public readonly ProjectionInfo NAD1983HARNAdjWIJackson; public readonly ProjectionInfo NAD1983HARNAdjWIJefferson; public readonly ProjectionInfo NAD1983HARNAdjWIJuneau; public readonly ProjectionInfo NAD1983HARNAdjWIKenosha; public readonly ProjectionInfo NAD1983HARNAdjWIKewaunee; public readonly ProjectionInfo NAD1983HARNAdjWILaCrosse; public readonly ProjectionInfo NAD1983HARNAdjWILafayette; public readonly ProjectionInfo NAD1983HARNAdjWILanglade; public readonly ProjectionInfo NAD1983HARNAdjWILincoln; public readonly ProjectionInfo NAD1983HARNAdjWIManitowoc; public readonly ProjectionInfo NAD1983HARNAdjWIMarathon; public readonly ProjectionInfo NAD1983HARNAdjWIMarinette; public readonly ProjectionInfo NAD1983HARNAdjWIMarquette; public readonly ProjectionInfo NAD1983HARNAdjWIMenominee; public readonly ProjectionInfo NAD1983HARNAdjWIMilwaukee; public readonly ProjectionInfo NAD1983HARNAdjWIMonroe; public readonly ProjectionInfo NAD1983HARNAdjWIOconto; public readonly ProjectionInfo NAD1983HARNAdjWIOneida; public readonly ProjectionInfo NAD1983HARNAdjWIOutagamie; public readonly ProjectionInfo NAD1983HARNAdjWIOzaukee; public readonly ProjectionInfo NAD1983HARNAdjWIPepin; public readonly ProjectionInfo NAD1983HARNAdjWIPierce; public readonly ProjectionInfo NAD1983HARNAdjWIPolk; public readonly ProjectionInfo NAD1983HARNAdjWIPortage; public readonly ProjectionInfo NAD1983HARNAdjWIPrice; public readonly ProjectionInfo NAD1983HARNAdjWIRacine; public readonly ProjectionInfo NAD1983HARNAdjWIRichland; public readonly ProjectionInfo NAD1983HARNAdjWIRock; public readonly ProjectionInfo NAD1983HARNAdjWIRusk; public readonly ProjectionInfo NAD1983HARNAdjWISauk; public readonly ProjectionInfo NAD1983HARNAdjWISawyer; public readonly ProjectionInfo NAD1983HARNAdjWIShawano; public readonly ProjectionInfo NAD1983HARNAdjWISheboygan; public readonly ProjectionInfo NAD1983HARNAdjWIStCroix; public readonly ProjectionInfo NAD1983HARNAdjWITaylor; public readonly ProjectionInfo NAD1983HARNAdjWITrempealeau; public readonly ProjectionInfo NAD1983HARNAdjWIVernon; public readonly ProjectionInfo NAD1983HARNAdjWIVilas; public readonly ProjectionInfo NAD1983HARNAdjWIWalworth; public readonly ProjectionInfo NAD1983HARNAdjWIWashburn; public readonly ProjectionInfo NAD1983HARNAdjWIWashington; public readonly ProjectionInfo NAD1983HARNAdjWIWaukesha; public readonly ProjectionInfo NAD1983HARNAdjWIWaupaca; public readonly ProjectionInfo NAD1983HARNAdjWIWaushara; public readonly ProjectionInfo NAD1983HARNAdjWIWinnebago; public readonly ProjectionInfo NAD1983HARNAdjWIWood; #endregion #region Constructors /// <summary> /// Creates a new instance of CountySystems /// </summary> public CountySystems() { NAD1983HARNAdjMNAnoka = ProjectionInfo.FromProj4String("+proj=longlat +a=6378418.941 +b=6357033.309845551 +no_defs "); NAD1983HARNAdjMNBecker = ProjectionInfo.FromProj4String("+proj=longlat +a=6378586.581 +b=6357200.387780368 +no_defs "); NAD1983HARNAdjMNBeltramiNorth = ProjectionInfo.FromProj4String("+proj=longlat +a=6378505.809 +b=6357119.886593593 +no_defs "); NAD1983HARNAdjMNBeltramiSouth = ProjectionInfo.FromProj4String("+proj=longlat +a=6378544.823 +b=6357158.769787037 +no_defs "); NAD1983HARNAdjMNBenton = ProjectionInfo.FromProj4String("+proj=longlat +a=6378490.569 +b=6357104.697690427 +no_defs "); NAD1983HARNAdjMNBigStone = ProjectionInfo.FromProj4String("+proj=longlat +a=6378470.757 +b=6357084.952116313 +no_defs "); NAD1983HARNAdjMNBlueEarth = ProjectionInfo.FromProj4String("+proj=longlat +a=6378403.701 +b=6357018.120942386 +no_defs "); NAD1983HARNAdjMNBrown = ProjectionInfo.FromProj4String("+proj=longlat +a=6378434.181 +b=6357048.498748716 +no_defs "); NAD1983HARNAdjMNCarlton = ProjectionInfo.FromProj4String("+proj=longlat +a=6378454.907 +b=6357069.155258362 +no_defs "); NAD1983HARNAdjMNCarver = ProjectionInfo.FromProj4String("+proj=longlat +a=6378400.653 +b=6357015.083161753 +no_defs "); NAD1983HARNAdjMNCassNorth = ProjectionInfo.FromProj4String("+proj=longlat +a=6378567.378 +b=6357181.249164391 +no_defs "); NAD1983HARNAdjMNCassSouth = ProjectionInfo.FromProj4String("+proj=longlat +a=6378546.957 +b=6357160.89663214 +no_defs "); NAD1983HARNAdjMNChippewa = ProjectionInfo.FromProj4String("+proj=longlat +a=6378476.853 +b=6357091.027677579 +no_defs "); NAD1983HARNAdjMNChisago = ProjectionInfo.FromProj4String("+proj=longlat +a=6378411.321000001 +b=6357025.715393969 +no_defs "); NAD1983HARNAdjMNCookNorth = ProjectionInfo.FromProj4String("+proj=longlat +a=6378647.541 +b=6357261.14339303 +no_defs "); NAD1983HARNAdjMNCookSouth = ProjectionInfo.FromProj4String("+proj=longlat +a=6378647.541 +b=6357261.14339303 +no_defs "); NAD1983HARNAdjMNCottonwood = ProjectionInfo.FromProj4String("+proj=longlat +a=6378514.953 +b=6357128.999935492 +no_defs "); NAD1983HARNAdjMNCrowWing = ProjectionInfo.FromProj4String("+proj=longlat +a=6378546.957 +b=6357160.89663214 +no_defs "); NAD1983HARNAdjMNDakota = ProjectionInfo.FromProj4String("+proj=longlat +a=6378421.989 +b=6357036.347626184 +no_defs "); NAD1983HARNAdjMNDodge = ProjectionInfo.FromProj4String("+proj=longlat +a=6378481.425 +b=6357095.584348529 +no_defs "); NAD1983HARNAdjMNDouglas = ProjectionInfo.FromProj4String("+proj=longlat +a=6378518.001 +b=6357132.037716125 +no_defs "); NAD1983HARNAdjMNFaribault = ProjectionInfo.FromProj4String("+proj=longlat +a=6378521.049 +b=6357135.075496757 +no_defs "); NAD1983HARNAdjMNFillmore = ProjectionInfo.FromProj4String("+proj=longlat +a=6378464.661 +b=6357078.876555047 +no_defs "); NAD1983HARNAdjMNFreeborn = ProjectionInfo.FromProj4String("+proj=longlat +a=6378521.049 +b=6357135.075496757 +no_defs "); NAD1983HARNAdjMNGoodhue = ProjectionInfo.FromProj4String("+proj=longlat +a=6378434.181 +b=6357048.498748716 +no_defs "); NAD1983HARNAdjMNGrant = ProjectionInfo.FromProj4String("+proj=longlat +a=6378518.001 +b=6357132.037716125 +no_defs "); NAD1983HARNAdjMNHennepin = ProjectionInfo.FromProj4String("+proj=longlat +a=6378418.941 +b=6357033.309845551 +no_defs "); NAD1983HARNAdjMNHouston = ProjectionInfo.FromProj4String("+proj=longlat +a=6378436.619 +b=6357050.928574564 +no_defs "); NAD1983HARNAdjMNIsanti = ProjectionInfo.FromProj4String("+proj=longlat +a=6378411.321000001 +b=6357025.715393969 +no_defs "); NAD1983HARNAdjMNItascaNorth = ProjectionInfo.FromProj4String("+proj=longlat +a=6378574.389 +b=6357188.236657837 +no_defs "); NAD1983HARNAdjMNItascaSouth = ProjectionInfo.FromProj4String("+proj=longlat +a=6378574.389 +b=6357188.236657837 +no_defs "); NAD1983HARNAdjMNJackson = ProjectionInfo.FromProj4String("+proj=longlat +a=6378521.049 +b=6357135.075496757 +no_defs "); NAD1983HARNAdjMNKanabec = ProjectionInfo.FromProj4String("+proj=longlat +a=6378472.281 +b=6357086.47100663 +no_defs "); NAD1983HARNAdjMNKandiyohi = ProjectionInfo.FromProj4String("+proj=longlat +a=6378498.189 +b=6357112.29214201 +no_defs "); NAD1983HARNAdjMNKittson = ProjectionInfo.FromProj4String("+proj=longlat +a=6378449.421 +b=6357063.687651882 +no_defs "); NAD1983HARNAdjMNKoochiching = ProjectionInfo.FromProj4String("+proj=longlat +a=6378525.621 +b=6357139.632167708 +no_defs "); NAD1983HARNAdjMNLacQuiParle = ProjectionInfo.FromProj4String("+proj=longlat +a=6378476.853 +b=6357091.027677579 +no_defs "); NAD1983HARNAdjMNLakeoftheWoodsNorth = ProjectionInfo.FromProj4String("+proj=longlat +a=6378466.185 +b=6357080.395445363 +no_defs "); NAD1983HARNAdjMNLakeoftheWoodsSouth = ProjectionInfo.FromProj4String("+proj=longlat +a=6378496.665 +b=6357110.773251694 +no_defs "); NAD1983HARNAdjMNLeSueur = ProjectionInfo.FromProj4String("+proj=longlat +a=6378434.181 +b=6357048.498748716 +no_defs "); NAD1983HARNAdjMNLincoln = ProjectionInfo.FromProj4String("+proj=longlat +a=6378643.579 +b=6357257.194676865 +no_defs "); NAD1983HARNAdjMNLyon = ProjectionInfo.FromProj4String("+proj=longlat +a=6378559.758 +b=6357173.65471281 +no_defs "); NAD1983HARNAdjMNMahnomen = ProjectionInfo.FromProj4String("+proj=longlat +a=6378586.581 +b=6357200.387780368 +no_defs "); NAD1983HARNAdjMNMarshall = ProjectionInfo.FromProj4String("+proj=longlat +a=6378441.801 +b=6357056.093200299 +no_defs "); NAD1983HARNAdjMNMartin = ProjectionInfo.FromProj4String("+proj=longlat +a=6378521.049 +b=6357135.075496757 +no_defs "); NAD1983HARNAdjMNMcLeod = ProjectionInfo.FromProj4String("+proj=longlat +a=6378414.369 +b=6357028.753174601 +no_defs "); NAD1983HARNAdjMNMeeker = ProjectionInfo.FromProj4String("+proj=longlat +a=6378498.189 +b=6357112.29214201 +no_defs "); NAD1983HARNAdjMNMorrison = ProjectionInfo.FromProj4String("+proj=longlat +a=6378502.761 +b=6357116.84881296 +no_defs "); NAD1983HARNAdjMNMower = ProjectionInfo.FromProj4String("+proj=longlat +a=6378521.049 +b=6357135.075496757 +no_defs "); NAD1983HARNAdjMNMurray = ProjectionInfo.FromProj4String("+proj=longlat +a=6378617.061 +b=6357230.765586698 +no_defs "); NAD1983HARNAdjMNNicollet = ProjectionInfo.FromProj4String("+proj=longlat +a=6378403.701 +b=6357018.120942386 +no_defs "); NAD1983HARNAdjMNNobles = ProjectionInfo.FromProj4String("+proj=longlat +a=6378624.681 +b=6357238.360038281 +no_defs "); NAD1983HARNAdjMNNorman = ProjectionInfo.FromProj4String("+proj=longlat +a=6378468.623 +b=6357082.825271211 +no_defs "); NAD1983HARNAdjMNOlmsted = ProjectionInfo.FromProj4String("+proj=longlat +a=6378481.425 +b=6357095.584348529 +no_defs "); NAD1983HARNAdjMNOttertail = ProjectionInfo.FromProj4String("+proj=longlat +a=6378525.621 +b=6357139.632167708 +no_defs "); NAD1983HARNAdjMNPennington = ProjectionInfo.FromProj4String("+proj=longlat +a=6378445.763 +b=6357060.041916464 +no_defs "); NAD1983HARNAdjMNPine = ProjectionInfo.FromProj4String("+proj=longlat +a=6378472.281 +b=6357086.47100663 +no_defs "); NAD1983HARNAdjMNPipestone = ProjectionInfo.FromProj4String("+proj=longlat +a=6378670.401 +b=6357283.926747777 +no_defs "); NAD1983HARNAdjMNPolk = ProjectionInfo.FromProj4String("+proj=longlat +a=6378445.763 +b=6357060.041916464 +no_defs "); NAD1983HARNAdjMNPope = ProjectionInfo.FromProj4String("+proj=longlat +a=6378502.761 +b=6357116.84881296 +no_defs "); NAD1983HARNAdjMNRamsey = ProjectionInfo.FromProj4String("+proj=longlat +a=6378418.941 +b=6357033.309845551 +no_defs "); NAD1983HARNAdjMNRedLake = ProjectionInfo.FromProj4String("+proj=longlat +a=6378445.763 +b=6357060.041916464 +no_defs "); NAD1983HARNAdjMNRedwood = ProjectionInfo.FromProj4String("+proj=longlat +a=6378438.753 +b=6357053.055419666 +no_defs "); NAD1983HARNAdjMNRenville = ProjectionInfo.FromProj4String("+proj=longlat +a=6378414.369 +b=6357028.753174601 +no_defs "); NAD1983HARNAdjMNRice = ProjectionInfo.FromProj4String("+proj=longlat +a=6378434.181 +b=6357048.498748716 +no_defs "); NAD1983HARNAdjMNRock = ProjectionInfo.FromProj4String("+proj=longlat +a=6378624.681 +b=6357238.360038281 +no_defs "); NAD1983HARNAdjMNRoseau = ProjectionInfo.FromProj4String("+proj=longlat +a=6378449.421 +b=6357063.687651882 +no_defs "); NAD1983HARNAdjMNScott = ProjectionInfo.FromProj4String("+proj=longlat +a=6378421.989 +b=6357036.347626184 +no_defs "); NAD1983HARNAdjMNSherburne = ProjectionInfo.FromProj4String("+proj=longlat +a=6378443.325 +b=6357057.612090616 +no_defs "); NAD1983HARNAdjMNSibley = ProjectionInfo.FromProj4String("+proj=longlat +a=6378414.369 +b=6357028.753174601 +no_defs "); NAD1983HARNAdjMNStLouisCentral = ProjectionInfo.FromProj4String("+proj=longlat +a=6378605.783 +b=6357219.525399698 +no_defs "); NAD1983HARNAdjMNStLouisNorth = ProjectionInfo.FromProj4String("+proj=longlat +a=6378543.909 +b=6357157.858851505 +no_defs "); NAD1983HARNAdjMNStLouisSouth = ProjectionInfo.FromProj4String("+proj=longlat +a=6378540.861 +b=6357154.821070872 +no_defs "); NAD1983HARNAdjMNStearns = ProjectionInfo.FromProj4String("+proj=longlat +a=6378502.761 +b=6357116.84881296 +no_defs "); NAD1983HARNAdjMNSteele = ProjectionInfo.FromProj4String("+proj=longlat +a=6378481.425 +b=6357095.584348529 +no_defs "); NAD1983HARNAdjMNStevens = ProjectionInfo.FromProj4String("+proj=longlat +a=6378502.761 +b=6357116.84881296 +no_defs "); NAD1983HARNAdjMNSwift = ProjectionInfo.FromProj4String("+proj=longlat +a=6378470.757 +b=6357084.952116313 +no_defs "); NAD1983HARNAdjMNTodd = ProjectionInfo.FromProj4String("+proj=longlat +a=6378548.481 +b=6357162.415522455 +no_defs "); NAD1983HARNAdjMNTraverse = ProjectionInfo.FromProj4String("+proj=longlat +a=6378463.746 +b=6357077.964622869 +no_defs "); NAD1983HARNAdjMNWabasha = ProjectionInfo.FromProj4String("+proj=longlat +a=6378426.561 +b=6357040.904297134 +no_defs "); NAD1983HARNAdjMNWadena = ProjectionInfo.FromProj4String("+proj=longlat +a=6378546.957 +b=6357160.89663214 +no_defs "); NAD1983HARNAdjMNWaseca = ProjectionInfo.FromProj4String("+proj=longlat +a=6378481.425 +b=6357095.584348529 +no_defs "); NAD1983HARNAdjMNWatonwan = ProjectionInfo.FromProj4String("+proj=longlat +a=6378514.953 +b=6357128.999935492 +no_defs "); NAD1983HARNAdjMNWinona = ProjectionInfo.FromProj4String("+proj=longlat +a=6378453.688 +b=6357067.940345438 +no_defs "); NAD1983HARNAdjMNWright = ProjectionInfo.FromProj4String("+proj=longlat +a=6378443.325 +b=6357057.612090616 +no_defs "); NAD1983HARNAdjMNYellowMedicine = ProjectionInfo.FromProj4String("+proj=longlat +a=6378530.193 +b=6357144.188838657 +no_defs "); NAD1983HARNAdjWIAdams = ProjectionInfo.FromProj4String("+proj=longlat +a=6378376.271 +b=6356991.5851403 +no_defs "); NAD1983HARNAdjWIAshland = ProjectionInfo.FromProj4String("+proj=longlat +a=6378471.92 +b=6357087.2341403 +no_defs "); NAD1983HARNAdjWIBarron = ProjectionInfo.FromProj4String("+proj=longlat +a=6378472.931 +b=6357088.2451403 +no_defs "); NAD1983HARNAdjWIBayfield = ProjectionInfo.FromProj4String("+proj=longlat +a=6378411.351 +b=6357026.6651403 +no_defs "); NAD1983HARNAdjWIBrown = ProjectionInfo.FromProj4String("+proj=longlat +ellps=GRS80 +no_defs "); NAD1983HARNAdjWIBuffalo = ProjectionInfo.FromProj4String("+proj=longlat +a=6378380.991 +b=6356996.305140301 +no_defs "); NAD1983HARNAdjWIBurnett = ProjectionInfo.FromProj4String("+proj=longlat +a=6378414.96 +b=6357030.2741403 +no_defs "); NAD1983HARNAdjWICalumet = ProjectionInfo.FromProj4String("+proj=longlat +a=6378345.09 +b=6356960.4041403 +no_defs "); NAD1983HARNAdjWIChippewa = ProjectionInfo.FromProj4String("+proj=longlat +a=6378412.542 +b=6357027.856140301 +no_defs "); NAD1983HARNAdjWIClark = ProjectionInfo.FromProj4String("+proj=longlat +a=6378470.401 +b=6357085.7151403 +no_defs "); NAD1983HARNAdjWIColumbia = ProjectionInfo.FromProj4String("+proj=longlat +a=6378376.331 +b=6356991.645140301 +no_defs "); NAD1983HARNAdjWICrawford = ProjectionInfo.FromProj4String("+proj=longlat +a=6378379.031 +b=6356994.345140301 +no_defs "); NAD1983HARNAdjWIDane = ProjectionInfo.FromProj4String("+proj=longlat +a=6378407.621 +b=6357022.935140301 +no_defs "); NAD1983HARNAdjWIDodge = ProjectionInfo.FromProj4String("+proj=longlat +a=6378376.811 +b=6356992.1251403 +no_defs "); NAD1983HARNAdjWIDoor = ProjectionInfo.FromProj4String("+proj=longlat +a=6378313.92 +b=6356929.2341403 +no_defs "); NAD1983HARNAdjWIDouglas = ProjectionInfo.FromProj4String("+proj=longlat +a=6378414.93 +b=6357030.2441403 +no_defs "); NAD1983HARNAdjWIDunn = ProjectionInfo.FromProj4String("+proj=longlat +a=6378413.021 +b=6357028.3351403 +no_defs "); NAD1983HARNAdjWIEauClaire = ProjectionInfo.FromProj4String("+proj=longlat +a=6378380.381 +b=6356995.6951403 +no_defs "); NAD1983HARNAdjWIFlorence = ProjectionInfo.FromProj4String("+proj=longlat +a=6378530.851 +b=6357146.1651403 +no_defs "); NAD1983HARNAdjWIFondduLac = ProjectionInfo.FromProj4String("+proj=longlat +a=6378345.09 +b=6356960.4041403 +no_defs "); NAD1983HARNAdjWIForest = ProjectionInfo.FromProj4String("+proj=longlat +a=6378591.521 +b=6357206.8351403 +no_defs "); NAD1983HARNAdjWIGrant = ProjectionInfo.FromProj4String("+proj=longlat +a=6378378.881 +b=6356994.1951403 +no_defs "); NAD1983HARNAdjWIGreen = ProjectionInfo.FromProj4String("+proj=longlat +a=6378408.481 +b=6357023.7951403 +no_defs "); NAD1983HARNAdjWIGreenLake = ProjectionInfo.FromProj4String("+proj=longlat +a=6378375.601 +b=6356990.9151403 +no_defs "); NAD1983HARNAdjWIIowa = ProjectionInfo.FromProj4String("+proj=longlat +a=6378408.041 +b=6357023.355140301 +no_defs "); NAD1983HARNAdjWIIron = ProjectionInfo.FromProj4String("+proj=longlat +a=6378655.071000001 +b=6357270.385140301 +no_defs "); NAD1983HARNAdjWIJackson = ProjectionInfo.FromProj4String("+proj=longlat +a=6378409.151 +b=6357024.4651403 +no_defs "); NAD1983HARNAdjWIJefferson = ProjectionInfo.FromProj4String("+proj=longlat +a=6378376.811 +b=6356992.1251403 +no_defs "); NAD1983HARNAdjWIJuneau = ProjectionInfo.FromProj4String("+proj=longlat +a=6378376.271 +b=6356991.5851403 +no_defs "); NAD1983HARNAdjWIKenosha = ProjectionInfo.FromProj4String("+proj=longlat +a=6378315.7 +b=6356931.014140301 +no_defs "); NAD1983HARNAdjWIKewaunee = ProjectionInfo.FromProj4String("+proj=longlat +a=6378285.86 +b=6356901.174140301 +no_defs "); NAD1983HARNAdjWILaCrosse = ProjectionInfo.FromProj4String("+proj=longlat +a=6378379.301 +b=6356994.6151403 +no_defs "); NAD1983HARNAdjWILafayette = ProjectionInfo.FromProj4String("+proj=longlat +a=6378408.481 +b=6357023.7951403 +no_defs "); NAD1983HARNAdjWILanglade = ProjectionInfo.FromProj4String("+proj=longlat +a=6378560.121 +b=6357175.435140301 +no_defs "); NAD1983HARNAdjWILincoln = ProjectionInfo.FromProj4String("+proj=longlat +a=6378531.821000001 +b=6357147.135140301 +no_defs "); NAD1983HARNAdjWIManitowoc = ProjectionInfo.FromProj4String("+proj=longlat +a=6378285.86 +b=6356901.174140301 +no_defs "); NAD1983HARNAdjWIMarathon = ProjectionInfo.FromProj4String("+proj=longlat +a=6378500.6 +b=6357115.9141403 +no_defs "); NAD1983HARNAdjWIMarinette = ProjectionInfo.FromProj4String("+proj=longlat +a=6378376.041 +b=6356991.355140301 +no_defs "); NAD1983HARNAdjWIMarquette = ProjectionInfo.FromProj4String("+proj=longlat +a=6378375.601 +b=6356990.9151403 +no_defs "); NAD1983HARNAdjWIMenominee = ProjectionInfo.FromProj4String("+proj=longlat +a=6378406.601 +b=6357021.9151403 +no_defs "); NAD1983HARNAdjWIMilwaukee = ProjectionInfo.FromProj4String("+proj=longlat +a=6378315.7 +b=6356931.014140301 +no_defs "); NAD1983HARNAdjWIMonroe = ProjectionInfo.FromProj4String("+proj=longlat +a=6378438.991 +b=6357054.305140301 +no_defs "); NAD1983HARNAdjWIOconto = ProjectionInfo.FromProj4String("+proj=longlat +a=6378345.42 +b=6356960.7341403 +no_defs "); NAD1983HARNAdjWIOneida = ProjectionInfo.FromProj4String("+proj=longlat +a=6378593.86 +b=6357209.174140301 +no_defs "); NAD1983HARNAdjWIOutagamie = ProjectionInfo.FromProj4String("+proj=longlat +a=6378345.09 +b=6356960.4041403 +no_defs "); NAD1983HARNAdjWIOzaukee = ProjectionInfo.FromProj4String("+proj=longlat +a=6378315.7 +b=6356931.014140301 +no_defs "); NAD1983HARNAdjWIPepin = ProjectionInfo.FromProj4String("+proj=longlat +a=6378381.271 +b=6356996.5851403 +no_defs "); NAD1983HARNAdjWIPierce = ProjectionInfo.FromProj4String("+proj=longlat +a=6378381.271 +b=6356996.5851403 +no_defs "); NAD1983HARNAdjWIPolk = ProjectionInfo.FromProj4String("+proj=longlat +a=6378413.671 +b=6357028.9851403 +no_defs "); NAD1983HARNAdjWIPortage = ProjectionInfo.FromProj4String("+proj=longlat +a=6378344.377 +b=6356959.691139228 +no_defs "); NAD1983HARNAdjWIPrice = ProjectionInfo.FromProj4String("+proj=longlat +a=6378563.891 +b=6357179.2051403 +no_defs "); NAD1983HARNAdjWIRacine = ProjectionInfo.FromProj4String("+proj=longlat +a=6378315.7 +b=6356931.014140301 +no_defs "); NAD1983HARNAdjWIRichland = ProjectionInfo.FromProj4String("+proj=longlat +a=6378408.091 +b=6357023.4051403 +no_defs "); NAD1983HARNAdjWIRock = ProjectionInfo.FromProj4String("+proj=longlat +a=6378377.671 +b=6356992.9851403 +no_defs "); NAD1983HARNAdjWIRusk = ProjectionInfo.FromProj4String("+proj=longlat +a=6378472.751 +b=6357088.0651403 +no_defs "); NAD1983HARNAdjWISauk = ProjectionInfo.FromProj4String("+proj=longlat +a=6378407.281 +b=6357022.595140301 +no_defs "); NAD1983HARNAdjWISawyer = ProjectionInfo.FromProj4String("+proj=longlat +a=6378534.451 +b=6357149.765140301 +no_defs "); NAD1983HARNAdjWIShawano = ProjectionInfo.FromProj4String("+proj=longlat +a=6378406.051 +b=6357021.3651403 +no_defs "); NAD1983HARNAdjWISheboygan = ProjectionInfo.FromProj4String("+proj=longlat +a=6378285.86 +b=6356901.174140301 +no_defs "); NAD1983HARNAdjWIStCroix = ProjectionInfo.FromProj4String("+proj=longlat +a=6378412.511 +b=6357027.8251403 +no_defs "); NAD1983HARNAdjWITaylor = ProjectionInfo.FromProj4String("+proj=longlat +a=6378532.921 +b=6357148.2351403 +no_defs "); NAD1983HARNAdjWITrempealeau = ProjectionInfo.FromProj4String("+proj=longlat +a=6378380.091 +b=6356995.4051403 +no_defs "); NAD1983HARNAdjWIVernon = ProjectionInfo.FromProj4String("+proj=longlat +a=6378408.941 +b=6357024.2551403 +no_defs "); NAD1983HARNAdjWIVilas = ProjectionInfo.FromProj4String("+proj=longlat +a=6378624.171 +b=6357239.4851403 +no_defs "); NAD1983HARNAdjWIWalworth = ProjectionInfo.FromProj4String("+proj=longlat +a=6378377.411 +b=6356992.725140301 +no_defs "); NAD1983HARNAdjWIWashburn = ProjectionInfo.FromProj4String("+proj=longlat +a=6378474.591 +b=6357089.9051403 +no_defs "); NAD1983HARNAdjWIWashington = ProjectionInfo.FromProj4String("+proj=longlat +a=6378407.141 +b=6357022.4551403 +no_defs "); NAD1983HARNAdjWIWaukesha = ProjectionInfo.FromProj4String("+proj=longlat +a=6378376.871 +b=6356992.185140301 +no_defs "); NAD1983HARNAdjWIWaupaca = ProjectionInfo.FromProj4String("+proj=longlat +a=6378375.251 +b=6356990.5651403 +no_defs "); NAD1983HARNAdjWIWaushara = ProjectionInfo.FromProj4String("+proj=longlat +a=6378405.971 +b=6357021.2851403 +no_defs "); NAD1983HARNAdjWIWinnebago = ProjectionInfo.FromProj4String("+proj=longlat +a=6378345.09 +b=6356960.4041403 +no_defs "); NAD1983HARNAdjWIWood = ProjectionInfo.FromProj4String("+proj=longlat +a=6378437.651 +b=6357052.9651403 +no_defs "); NAD1983HARNAdjMNAnoka.Name = "GCS_NAD_1983_HARN_Adj_MN_Anoka"; NAD1983HARNAdjMNAnoka.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_Anoka"; NAD1983HARNAdjMNBecker.Name = "GCS_NAD_1983_HARN_Adj_MN_Becker"; NAD1983HARNAdjMNBecker.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_Becker"; NAD1983HARNAdjMNBeltramiNorth.Name = "GCS_NAD_1983_HARN_Adj_MN_Beltrami_North"; NAD1983HARNAdjMNBeltramiNorth.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_Beltrami_North"; NAD1983HARNAdjMNBeltramiSouth.Name = "GCS_NAD_1983_HARN_Adj_MN_Beltrami_South"; NAD1983HARNAdjMNBeltramiSouth.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_Beltrami_South"; NAD1983HARNAdjMNBenton.Name = "GCS_NAD_1983_HARN_Adj_MN_Benton"; NAD1983HARNAdjMNBenton.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_Benton"; NAD1983HARNAdjMNBigStone.Name = "GCS_NAD_1983_HARN_Adj_MN_Big_Stone"; NAD1983HARNAdjMNBigStone.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_Big_Stone"; NAD1983HARNAdjMNBlueEarth.Name = "GCS_NAD_1983_HARN_Adj_MN_Blue_Earth"; NAD1983HARNAdjMNBlueEarth.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_Blue_Earth"; NAD1983HARNAdjMNBrown.Name = "GCS_NAD_1983_HARN_Adj_MN_Brown"; NAD1983HARNAdjMNBrown.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_Brown"; NAD1983HARNAdjMNCarlton.Name = "GCS_NAD_1983_HARN_Adj_MN_Carlton"; NAD1983HARNAdjMNCarlton.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_Carlton"; NAD1983HARNAdjMNCarver.Name = "GCS_NAD_1983_HARN_Adj_MN_Carver"; NAD1983HARNAdjMNCarver.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_Carver"; NAD1983HARNAdjMNCassNorth.Name = "GCS_NAD_1983_HARN_Adj_MN_Cass_North"; NAD1983HARNAdjMNCassNorth.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_Cass_North"; NAD1983HARNAdjMNCassSouth.Name = "GCS_NAD_1983_HARN_Adj_MN_Cass_South"; NAD1983HARNAdjMNCassSouth.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_Cass_South"; NAD1983HARNAdjMNChippewa.Name = "GCS_NAD_1983_HARN_Adj_MN_Chippewa"; NAD1983HARNAdjMNChippewa.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_Chippewa"; NAD1983HARNAdjMNChisago.Name = "GCS_NAD_1983_HARN_Adj_MN_Chisago"; NAD1983HARNAdjMNChisago.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_Chisago"; NAD1983HARNAdjMNCookNorth.Name = "GCS_NAD_1983_HARN_Adj_MN_Cook_North"; NAD1983HARNAdjMNCookNorth.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_Cook_North"; NAD1983HARNAdjMNCookSouth.Name = "GCS_NAD_1983_HARN_Adj_MN_Cook_South"; NAD1983HARNAdjMNCookSouth.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_Cook_South"; NAD1983HARNAdjMNCottonwood.Name = "GCS_NAD_1983_HARN_Adj_MN_Cottonwood"; NAD1983HARNAdjMNCottonwood.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_Cottonwood"; NAD1983HARNAdjMNCrowWing.Name = "GCS_NAD_1983_HARN_Adj_MN_Crow_Wing"; NAD1983HARNAdjMNCrowWing.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_Crow_Wing"; NAD1983HARNAdjMNDakota.Name = "GCS_NAD_1983_HARN_Adj_MN_Dakota"; NAD1983HARNAdjMNDakota.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_Dakota"; NAD1983HARNAdjMNDodge.Name = "GCS_NAD_1983_HARN_Adj_MN_Dodge"; NAD1983HARNAdjMNDodge.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_Dodge"; NAD1983HARNAdjMNDouglas.Name = "GCS_NAD_1983_HARN_Adj_MN_Douglas"; NAD1983HARNAdjMNDouglas.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_Douglas"; NAD1983HARNAdjMNFaribault.Name = "GCS_NAD_1983_HARN_Adj_MN_Faribault"; NAD1983HARNAdjMNFaribault.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_Faribault"; NAD1983HARNAdjMNFillmore.Name = "GCS_NAD_1983_HARN_Adj_MN_Fillmore"; NAD1983HARNAdjMNFillmore.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_Fillmore"; NAD1983HARNAdjMNFreeborn.Name = "GCS_NAD_1983_HARN_Adj_MN_Freeborn"; NAD1983HARNAdjMNFreeborn.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_Freeborn"; NAD1983HARNAdjMNGoodhue.Name = "GCS_NAD_1983_HARN_Adj_MN_Goodhue"; NAD1983HARNAdjMNGoodhue.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_Goodhue"; NAD1983HARNAdjMNGrant.Name = "GCS_NAD_1983_HARN_Adj_MN_Grant"; NAD1983HARNAdjMNGrant.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_Grant"; NAD1983HARNAdjMNHennepin.Name = "GCS_NAD_1983_HARN_Adj_MN_Hennepin"; NAD1983HARNAdjMNHennepin.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_Hennepin"; NAD1983HARNAdjMNHouston.Name = "GCS_NAD_1983_HARN_Adj_MN_Houston"; NAD1983HARNAdjMNHouston.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_Houston"; NAD1983HARNAdjMNIsanti.Name = "GCS_NAD_1983_HARN_Adj_MN_Isanti"; NAD1983HARNAdjMNIsanti.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_Isanti"; NAD1983HARNAdjMNItascaNorth.Name = "GCS_NAD_1983_HARN_Adj_MN_Itasca_North"; NAD1983HARNAdjMNItascaNorth.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_Itasca_North"; NAD1983HARNAdjMNItascaSouth.Name = "GCS_NAD_1983_HARN_Adj_MN_Itasca_South"; NAD1983HARNAdjMNItascaSouth.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_Itasca_South"; NAD1983HARNAdjMNJackson.Name = "GCS_NAD_1983_HARN_Adj_MN_Jackson"; NAD1983HARNAdjMNJackson.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_Jackson"; NAD1983HARNAdjMNKanabec.Name = "GCS_NAD_1983_HARN_Adj_MN_Kanabec"; NAD1983HARNAdjMNKanabec.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_Kanabec"; NAD1983HARNAdjMNKandiyohi.Name = "GCS_NAD_1983_HARN_Adj_MN_Kandiyohi"; NAD1983HARNAdjMNKandiyohi.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_Kandiyohi"; NAD1983HARNAdjMNKittson.Name = "GCS_NAD_1983_HARN_Adj_MN_Kittson"; NAD1983HARNAdjMNKittson.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_Kittson"; NAD1983HARNAdjMNKoochiching.Name = "GCS_NAD_1983_HARN_Adj_MN_Koochiching"; NAD1983HARNAdjMNKoochiching.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_Koochiching"; NAD1983HARNAdjMNLacQuiParle.Name = "GCS_NAD_1983_HARN_Adj_MN_Lac_Qui_Parle"; NAD1983HARNAdjMNLacQuiParle.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_Lac_Qui_Parle"; NAD1983HARNAdjMNLakeoftheWoodsNorth.Name = "GCS_NAD_1983_HARN_Adj_MN_Lake_of_the_Woods_North"; NAD1983HARNAdjMNLakeoftheWoodsNorth.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_Lake_of_the_Woods_North"; NAD1983HARNAdjMNLakeoftheWoodsSouth.Name = "GCS_NAD_1983_HARN_Adj_MN_Lake_of_the_Woods_South"; NAD1983HARNAdjMNLakeoftheWoodsSouth.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_Lake_of_the_Woods_South"; NAD1983HARNAdjMNLeSueur.Name = "GCS_NAD_1983_HARN_Adj_MN_Le_Sueur"; NAD1983HARNAdjMNLeSueur.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_Le_Sueur"; NAD1983HARNAdjMNLincoln.Name = "GCS_NAD_1983_HARN_Adj_MN_Lincoln"; NAD1983HARNAdjMNLincoln.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_Lincoln"; NAD1983HARNAdjMNLyon.Name = "GCS_NAD_1983_HARN_Adj_MN_Lyon"; NAD1983HARNAdjMNLyon.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_Lyon"; NAD1983HARNAdjMNMahnomen.Name = "GCS_NAD_1983_HARN_Adj_MN_Mahnomen"; NAD1983HARNAdjMNMahnomen.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_Mahnomen"; NAD1983HARNAdjMNMarshall.Name = "GCS_NAD_1983_HARN_Adj_MN_Marshall"; NAD1983HARNAdjMNMarshall.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_Marshall"; NAD1983HARNAdjMNMartin.Name = "GCS_NAD_1983_HARN_Adj_MN_Martin"; NAD1983HARNAdjMNMartin.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_Martin"; NAD1983HARNAdjMNMcLeod.Name = "GCS_NAD_1983_HARN_Adj_MN_McLeod"; NAD1983HARNAdjMNMcLeod.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_McLeod"; NAD1983HARNAdjMNMeeker.Name = "GCS_NAD_1983_HARN_Adj_MN_Meeker"; NAD1983HARNAdjMNMeeker.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_Meeker"; NAD1983HARNAdjMNMorrison.Name = "GCS_NAD_1983_HARN_Adj_MN_Morrison"; NAD1983HARNAdjMNMorrison.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_Morrison"; NAD1983HARNAdjMNMower.Name = "GCS_NAD_1983_HARN_Adj_MN_Mower"; NAD1983HARNAdjMNMower.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_Mower"; NAD1983HARNAdjMNMurray.Name = "GCS_NAD_1983_HARN_Adj_MN_Murray"; NAD1983HARNAdjMNMurray.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_Murray"; NAD1983HARNAdjMNNicollet.Name = "GCS_NAD_1983_HARN_Adj_MN_Nicollet"; NAD1983HARNAdjMNNicollet.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_Nicollet"; NAD1983HARNAdjMNNobles.Name = "GCS_NAD_1983_HARN_Adj_MN_Nobles"; NAD1983HARNAdjMNNobles.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_Nobles"; NAD1983HARNAdjMNNorman.Name = "GCS_NAD_1983_HARN_Adj_MN_Norman"; NAD1983HARNAdjMNNorman.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_Norman"; NAD1983HARNAdjMNOlmsted.Name = "GCS_NAD_1983_HARN_Adj_MN_Olmsted"; NAD1983HARNAdjMNOlmsted.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_Olmsted"; NAD1983HARNAdjMNOttertail.Name = "GCS_NAD_1983_HARN_Adj_MN_Ottertail"; NAD1983HARNAdjMNOttertail.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_Ottertail"; NAD1983HARNAdjMNPennington.Name = "GCS_NAD_1983_HARN_Adj_MN_Pennington"; NAD1983HARNAdjMNPennington.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_Pennington"; NAD1983HARNAdjMNPine.Name = "GCS_NAD_1983_HARN_Adj_MN_Pine"; NAD1983HARNAdjMNPine.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_Pine"; NAD1983HARNAdjMNPipestone.Name = "GCS_NAD_1983_HARN_Adj_MN_Pipestone"; NAD1983HARNAdjMNPipestone.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_Pipestone"; NAD1983HARNAdjMNPolk.Name = "GCS_NAD_1983_HARN_Adj_MN_Polk"; NAD1983HARNAdjMNPolk.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_Polk"; NAD1983HARNAdjMNPope.Name = "GCS_NAD_1983_HARN_Adj_MN_Pope"; NAD1983HARNAdjMNPope.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_Pope"; NAD1983HARNAdjMNRamsey.Name = "GCS_NAD_1983_HARN_Adj_MN_Ramsey"; NAD1983HARNAdjMNRamsey.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_Ramsey"; NAD1983HARNAdjMNRedLake.Name = "GCS_NAD_1983_HARN_Adj_MN_Red_Lake"; NAD1983HARNAdjMNRedLake.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_Red_Lake"; NAD1983HARNAdjMNRedwood.Name = "GCS_NAD_1983_HARN_Adj_MN_Redwood"; NAD1983HARNAdjMNRedwood.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_Redwood"; NAD1983HARNAdjMNRenville.Name = "GCS_NAD_1983_HARN_Adj_MN_Renville"; NAD1983HARNAdjMNRenville.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_Renville"; NAD1983HARNAdjMNRice.Name = "GCS_NAD_1983_HARN_Adj_MN_Rice"; NAD1983HARNAdjMNRice.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_Rice"; NAD1983HARNAdjMNRock.Name = "GCS_NAD_1983_HARN_Adj_MN_Rock"; NAD1983HARNAdjMNRock.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_Rock"; NAD1983HARNAdjMNRoseau.Name = "GCS_NAD_1983_HARN_Adj_MN_Roseau"; NAD1983HARNAdjMNRoseau.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_Roseau"; NAD1983HARNAdjMNScott.Name = "GCS_NAD_1983_HARN_Adj_MN_Scott"; NAD1983HARNAdjMNScott.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_Scott"; NAD1983HARNAdjMNSherburne.Name = "GCS_NAD_1983_HARN_Adj_MN_Sherburne"; NAD1983HARNAdjMNSherburne.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_Sherburne"; NAD1983HARNAdjMNSibley.Name = "GCS_NAD_1983_HARN_Adj_MN_Sibley"; NAD1983HARNAdjMNSibley.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_Sibley"; NAD1983HARNAdjMNStLouisCentral.Name = "GCS_NAD_1983_HARN_Adj_MN_St_Louis_Central"; NAD1983HARNAdjMNStLouisCentral.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_St_Louis_Central"; NAD1983HARNAdjMNStLouisNorth.Name = "GCS_NAD_1983_HARN_Adj_MN_St_Louis_North"; NAD1983HARNAdjMNStLouisNorth.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_St_Louis_North"; NAD1983HARNAdjMNStLouisSouth.Name = "GCS_NAD_1983_HARN_Adj_MN_St_Louis_South"; NAD1983HARNAdjMNStLouisSouth.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_St_Louis_South"; NAD1983HARNAdjMNStearns.Name = "GCS_NAD_1983_HARN_Adj_MN_Stearns"; NAD1983HARNAdjMNStearns.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_Stearns"; NAD1983HARNAdjMNSteele.Name = "GCS_NAD_1983_HARN_Adj_MN_Steele"; NAD1983HARNAdjMNSteele.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_Steele"; NAD1983HARNAdjMNStevens.Name = "GCS_NAD_1983_HARN_Adj_MN_Stevens"; NAD1983HARNAdjMNStevens.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_Stevens"; NAD1983HARNAdjMNSwift.Name = "GCS_NAD_1983_HARN_Adj_MN_Swift"; NAD1983HARNAdjMNSwift.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_Swift"; NAD1983HARNAdjMNTodd.Name = "GCS_NAD_1983_HARN_Adj_MN_Todd"; NAD1983HARNAdjMNTodd.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_Todd"; NAD1983HARNAdjMNTraverse.Name = "GCS_NAD_1983_HARN_Adj_MN_Traverse"; NAD1983HARNAdjMNTraverse.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_Traverse"; NAD1983HARNAdjMNWabasha.Name = "GCS_NAD_1983_HARN_Adj_MN_Wabasha"; NAD1983HARNAdjMNWabasha.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_Wabasha"; NAD1983HARNAdjMNWadena.Name = "GCS_NAD_1983_HARN_Adj_MN_Wadena"; NAD1983HARNAdjMNWadena.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_Wadena"; NAD1983HARNAdjMNWaseca.Name = "GCS_NAD_1983_HARN_Adj_MN_Waseca"; NAD1983HARNAdjMNWaseca.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_Waseca"; NAD1983HARNAdjMNWatonwan.Name = "GCS_NAD_1983_HARN_Adj_MN_Watonwan"; NAD1983HARNAdjMNWatonwan.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_Watonwan"; NAD1983HARNAdjMNWinona.Name = "GCS_NAD_1983_HARN_Adj_MN_Winona"; NAD1983HARNAdjMNWinona.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_Winona"; NAD1983HARNAdjMNWright.Name = "GCS_NAD_1983_HARN_Adj_MN_Wright"; NAD1983HARNAdjMNWright.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_Wright"; NAD1983HARNAdjMNYellowMedicine.Name = "GCS_NAD_1983_HARN_Adj_MN_Yellow_Medicine"; NAD1983HARNAdjMNYellowMedicine.GeographicInfo.Name = "GCS_NAD_1983_HARN_Adj_MN_Yellow_Medicine"; NAD1983HARNAdjMNAnoka.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_Anoka"; NAD1983HARNAdjMNBecker.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_Becker"; NAD1983HARNAdjMNBeltramiNorth.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_Beltrami_North"; NAD1983HARNAdjMNBeltramiSouth.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_Beltrami_South"; NAD1983HARNAdjMNBenton.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_Benton"; NAD1983HARNAdjMNBigStone.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_Big_Stone"; NAD1983HARNAdjMNBlueEarth.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_Blue_Earth"; NAD1983HARNAdjMNBrown.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_Brown"; NAD1983HARNAdjMNCarlton.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_Carlton"; NAD1983HARNAdjMNCarver.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_Carver"; NAD1983HARNAdjMNCassNorth.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_Cass_North"; NAD1983HARNAdjMNCassSouth.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_Cass_South"; NAD1983HARNAdjMNChippewa.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_Chippewa"; NAD1983HARNAdjMNChisago.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_Chisago"; NAD1983HARNAdjMNCookNorth.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_Cook_North"; NAD1983HARNAdjMNCookSouth.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_Cook_South"; NAD1983HARNAdjMNCottonwood.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_Cottonwood"; NAD1983HARNAdjMNCrowWing.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_Crow_Wing"; NAD1983HARNAdjMNDakota.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_Dakota"; NAD1983HARNAdjMNDodge.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_Dodge"; NAD1983HARNAdjMNDouglas.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_Douglas"; NAD1983HARNAdjMNFaribault.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_Faribault"; NAD1983HARNAdjMNFillmore.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_Fillmore"; NAD1983HARNAdjMNFreeborn.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_Freeborn"; NAD1983HARNAdjMNGoodhue.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_Goodhue"; NAD1983HARNAdjMNGrant.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_Grant"; NAD1983HARNAdjMNHennepin.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_Hennepin"; NAD1983HARNAdjMNHouston.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_Houston"; NAD1983HARNAdjMNIsanti.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_Isanti"; NAD1983HARNAdjMNItascaNorth.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_Itasca_North"; NAD1983HARNAdjMNItascaSouth.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_Itasca_South"; NAD1983HARNAdjMNJackson.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_Jackson"; NAD1983HARNAdjMNKanabec.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_Kanabec"; NAD1983HARNAdjMNKandiyohi.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_Kandiyohi"; NAD1983HARNAdjMNKittson.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_Kittson"; NAD1983HARNAdjMNKoochiching.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_Koochiching"; NAD1983HARNAdjMNLacQuiParle.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_Lac_Qui_Parle"; NAD1983HARNAdjMNLakeoftheWoodsNorth.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_Lake_of_the_Woods_North"; NAD1983HARNAdjMNLakeoftheWoodsSouth.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_Lake_of_the_Woods_South"; NAD1983HARNAdjMNLeSueur.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_Le_Sueur"; NAD1983HARNAdjMNLincoln.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_Lincoln"; NAD1983HARNAdjMNLyon.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_Lyon"; NAD1983HARNAdjMNMahnomen.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_Mahnomen"; NAD1983HARNAdjMNMarshall.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_Marshall"; NAD1983HARNAdjMNMartin.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_Martin"; NAD1983HARNAdjMNMcLeod.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_McLeod"; NAD1983HARNAdjMNMeeker.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_Meeker"; NAD1983HARNAdjMNMorrison.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_Morrison"; NAD1983HARNAdjMNMower.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_Mower"; NAD1983HARNAdjMNMurray.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_Murray"; NAD1983HARNAdjMNNicollet.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_Nicollet"; NAD1983HARNAdjMNNobles.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_Nobles"; NAD1983HARNAdjMNNorman.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_Norman"; NAD1983HARNAdjMNOlmsted.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_Olmsted"; NAD1983HARNAdjMNOttertail.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_Ottertail"; NAD1983HARNAdjMNPennington.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_Pennington"; NAD1983HARNAdjMNPine.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_Pine"; NAD1983HARNAdjMNPipestone.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_Pipestone"; NAD1983HARNAdjMNPolk.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_Polk"; NAD1983HARNAdjMNPope.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_Pope"; NAD1983HARNAdjMNRamsey.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_Ramsey"; NAD1983HARNAdjMNRedLake.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_Red_Lake"; NAD1983HARNAdjMNRedwood.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_Redwood"; NAD1983HARNAdjMNRenville.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_Renville"; NAD1983HARNAdjMNRice.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_Rice"; NAD1983HARNAdjMNRock.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_Rock"; NAD1983HARNAdjMNRoseau.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_Roseau"; NAD1983HARNAdjMNScott.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_Scott"; NAD1983HARNAdjMNSherburne.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_Sherburne"; NAD1983HARNAdjMNSibley.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_Sibley"; NAD1983HARNAdjMNStLouisCentral.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_St_Louis_Central"; NAD1983HARNAdjMNStLouisNorth.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_St_Louis_North"; NAD1983HARNAdjMNStLouisSouth.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_St_Louis_South"; NAD1983HARNAdjMNStearns.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_Stearns"; NAD1983HARNAdjMNSteele.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_Steele"; NAD1983HARNAdjMNStevens.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_Stevens"; NAD1983HARNAdjMNSwift.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_Swift"; NAD1983HARNAdjMNTodd.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_Todd"; NAD1983HARNAdjMNTraverse.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_Traverse"; NAD1983HARNAdjMNWabasha.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_Wabasha"; NAD1983HARNAdjMNWadena.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_Wadena"; NAD1983HARNAdjMNWaseca.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_Waseca"; NAD1983HARNAdjMNWatonwan.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_Watonwan"; NAD1983HARNAdjMNWinona.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_Winona"; NAD1983HARNAdjMNWright.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_Wright"; NAD1983HARNAdjMNYellowMedicine.GeographicInfo.Datum.Name = "D_NAD_1983_HARN_Adj_MN_Yellow_Medicine"; } #endregion } } #pragma warning restore 1591
using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection; using log4net; using SFML.Graphics; namespace NetGore.Graphics { public class DrawingManager : IDrawingManager { // FUTURE: !! Add support for a DrawingManager that doesn't need RenderImage static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// The <see cref="Color"/> to use when clearing the GUI. This needs to have an alpha of 0 since we will /// be copying from the buffer onto the window, and if the world was drawn, we will be copying on top /// of the world. /// </summary> static readonly Color _clearGUIBufferColor = new Color(0, 0, 0, 0); readonly SFML.Graphics.Sprite _drawBufferToWindowSprite; readonly ILightManager _lightManager; readonly IRefractionManager _refractionManager; readonly ISpriteBatch _sb; readonly View _view = new View(); RenderTexture _buffer; bool _isDisposed; /// <summary> /// Contains if the last draw was to the world. This way, we can make sure to not draw the GUI twice or world twice /// in a row without clearing. True for last drawing being to World, false for GUI. /// </summary> bool _lastDrawWasToWorld; RenderWindow _rw; DrawingManagerState _state = DrawingManagerState.Idle; ICamera2D _worldCamera; /// <summary> /// Initializes a new instance of the <see cref="DrawingManager"/> class. /// </summary> public DrawingManager() : this(null) { } /// <summary> /// Initializes a new instance of the <see cref="DrawingManager"/> class. /// </summary> /// <param name="rw">The <see cref="RenderWindow"/>.</param> public DrawingManager(RenderWindow rw) { BackgroundColor = Color.Black; // Create the objects _sb = new RoundedSpriteBatch(); _lightManager = CreateLightManager(); _refractionManager = CreateRefractionManager(); // Set up the sprite used to draw the light map _drawBufferToWindowSprite = new SFML.Graphics.Sprite { Color = Color.White, Rotation = 0, Scale = Vector2.One, Origin = Vector2.Zero, Position = Vector2.Zero }; // Set the RenderWindow RenderWindow = rw; } /// <summary> /// Creates the <see cref="ILightManager"/> to use. /// </summary> /// <returns>The <see cref="ILightManager"/> to use. Cannot be null.</returns> protected virtual ILightManager CreateLightManager() { return new LightManager(); } /// <summary> /// Creates the <see cref="IRefractionManager"/> to use. /// </summary> /// <returns>The <see cref="IRefractionManager"/> to use. Cannot be null.</returns> protected virtual IRefractionManager CreateRefractionManager() { return new RefractionManager(); } /// <summary> /// Releases unmanaged and - optionally - managed resources /// </summary> /// <param name="disposeManaged"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release /// only unmanaged resources.</param> protected virtual void Dispose(bool disposeManaged) { if (!disposeManaged) return; if (_lightManager != null) _lightManager.Dispose(); if (_refractionManager != null) _refractionManager.Dispose(); if (_sb != null && !_sb.IsDisposed) _sb.Dispose(); if (_drawBufferToWindowSprite != null && !_drawBufferToWindowSprite.IsDisposed) _drawBufferToWindowSprite.Dispose(); } /// <summary> /// Draws an <see cref="Texture"/> to the screen. /// </summary> /// <param name="buffer">The <see cref="Texture"/> to draw.</param> /// <param name="blendMode">The <see cref="BlendMode"/> to use.</param> void DrawBufferToScreen(Texture buffer, BlendMode blendMode) { var size = buffer.Size; _drawBufferToWindowSprite.Texture = buffer; _drawBufferToWindowSprite.TextureRect = new IntRect(0, 0, (int)size.X, (int)size.Y); _rw.Draw(_drawBufferToWindowSprite, new RenderStates(blendMode)); } /// <summary> /// Gets if the <see cref="RenderWindow"/> is available. If it is not, we cannot draw. /// </summary> /// <returns>True if the <see cref="RenderWindow"/> is available; otherwise false.</returns> protected bool IsRenderWindowAvailable() { try { return !_rw.IsDisposed && _rw.IsOpen(); } catch (ObjectDisposedException) { return false; } catch (Exception ex) { const string errmsg = "Unexpected exception occured while trying to get the state of RenderWindow `{0}`. Exception: {1}"; if (log.IsErrorEnabled) log.ErrorFormat(errmsg, _rw, ex); Debug.Fail(string.Format(errmsg, _rw, ex)); return false; } } /// <summary> /// Allows derived classes to handle when the <see cref="RenderWindow"/> changes. /// </summary> /// <param name="newRenderWindow">The new <see cref="RenderWindow"/>.</param> protected virtual void OnRenderWindowChanged(RenderWindow newRenderWindow) { if (_sb != null) _sb.RenderTarget = newRenderWindow; if (LightManager != null) LightManager.Initialize(newRenderWindow); if (RefractionManager != null) RefractionManager.Initialize(newRenderWindow); } /// <summary> /// Ends a SpriteBatch without throwing any <see cref="Exception"/>s. /// </summary> /// <param name="sb">The <see cref="ISpriteBatch"/> to end.</param> void SafeEndSpriteBatch(ISpriteBatch sb) { try { sb.End(); } catch (Exception ex) { const string errmsg = "Exception occured while calling End() the SpriteBatch `{0}` on `{1}`. Exception: {2}"; if (log.IsWarnEnabled) log.WarnFormat(errmsg, sb, this, ex); Debug.Fail(string.Format(errmsg, sb, this, ex)); } } #region IDrawingManager Members /// <summary> /// Gets or sets the background <see cref="Color"/>. /// </summary> public Color BackgroundColor { get; set; } /// <summary> /// Gets if this <see cref="IDrawingManager"/> has been disposed. /// </summary> public bool IsDisposed { get { return _isDisposed; } } /// <summary> /// Gets the <see cref="ILightManager"/> used by this <see cref="IDrawingManager"/>. /// </summary> public ILightManager LightManager { get { return _lightManager; } } /// <summary> /// Gets the <see cref="IRefractionManager"/> used by this <see cref="IDrawingManager"/>. /// </summary> public IRefractionManager RefractionManager { get { return _refractionManager; } } /// <summary> /// Gets or sets the <see cref="RenderWindow"/> to draw to. /// </summary> public RenderWindow RenderWindow { get { return _rw; } set { if (_rw == value) return; _rw = value; _sb.RenderTarget = _rw; if (_rw != null) { LightManager.Initialize(_rw); RefractionManager.Initialize(_rw); } OnRenderWindowChanged(_rw); } } /// <summary> /// Gets the <see cref="DrawingManagerState"/> describing the current drawing state. /// </summary> public DrawingManagerState State { get { return _state; } } /// <summary> /// Begins drawing the graphical user interface, which is not affected by the camera. /// </summary> /// <param name="clearBuffer">When true, the buffer will be cleared before drawing. When false, the contents of the previous /// frame will remain in the buffer, only if the last draw was also to the GUI. When the last draw call was to the /// world, then this will have no affect. Useful for when you want to draw multiple GUI screens on top of one another.</param> /// <returns> /// The <see cref="ISpriteBatch"/> to use to draw the GUI, or null if an unexpected /// error was encountered when preparing the <see cref="ISpriteBatch"/>. When null, all drawing /// should be aborted completely instead of trying to draw with a different <see cref="ISpriteBatch"/> /// or manually recovering the error. /// </returns> /// <exception cref="InvalidOperationException"><see cref="IDrawingManager.State"/> is not equal to /// <see cref="DrawingManagerState.Idle"/>.</exception> public ISpriteBatch BeginDrawGUI(bool clearBuffer = true) { if (State != DrawingManagerState.Idle) throw new InvalidOperationException("This method cannot be called while already busy drawing."); try { // Ensure the RenderWindow is available if (!IsRenderWindowAvailable()) { if (log.IsInfoEnabled) log.Info("Skipping BeginDrawGUI() call - the RenderWindow is not available."); _state = DrawingManagerState.Idle; return null; } if (clearBuffer) { // If the last draw was also to the GUI, clear the screen if (!_lastDrawWasToWorld) _rw.Clear(BackgroundColor); } _lastDrawWasToWorld = false; // Ensure the buffer is set up _buffer = _rw.CreateBufferRenderTexture(_buffer); _sb.RenderTarget = _buffer; if (_buffer == null) return null; // Always clear the GUI with alpha = 0 since we will be copying it over the screen _buffer.Clear(_clearGUIBufferColor); // Start up the SpriteBatch _sb.Begin(BlendMode.Alpha); // Change the state _state = DrawingManagerState.DrawingGUI; } catch (AccessViolationException ex) { // More frequent and less concerning exception const string errmsg = "Failed to start drawing GUI on `{0}`. Device was probably lost. Exception: {1}"; if (log.IsInfoEnabled) log.InfoFormat(errmsg, this, ex); _state = DrawingManagerState.Idle; SafeEndSpriteBatch(_sb); return null; } catch (Exception ex) { // Unexpected exception const string errmsg = "Failed to start drawing GUI on `{0}` due to unexpected exception. Exception: {1}"; if (log.IsErrorEnabled) log.ErrorFormat(errmsg, this, ex); Debug.Fail(string.Format(errmsg, this, ex)); _state = DrawingManagerState.Idle; SafeEndSpriteBatch(_sb); return null; } return _sb; } /// <summary> /// Begins drawing of the world. /// </summary> /// <param name="camera">The camera describing the the current view of the world.</param> /// <returns> /// The <see cref="ISpriteBatch"/> to use to draw the world objects, or null if an unexpected /// error was encountered when preparing the <see cref="ISpriteBatch"/>. When null, all drawing /// should be aborted completely instead of trying to draw with a different <see cref="ISpriteBatch"/> /// or manually recovering the error. /// </returns> /// <exception cref="InvalidOperationException"><see cref="IDrawingManager.State"/> is not equal to /// <see cref="DrawingManagerState.Idle"/>.</exception> public ISpriteBatch BeginDrawWorld(ICamera2D camera) { if (State != DrawingManagerState.Idle) throw new InvalidOperationException("This method cannot be called while already busy drawing."); try { // Ensure the RenderWindow is available if (!IsRenderWindowAvailable()) { if (log.IsInfoEnabled) log.Info("Skipping BeginDrawWorld() call - the RenderWindow is not available."); _state = DrawingManagerState.Idle; return null; } _worldCamera = camera; // No matter what the last draw was, we clear the screen when drawing the world since the world drawing // always comes first or not at all (makes no sense to draw the GUI then the world) _rw.Clear(BackgroundColor); _lastDrawWasToWorld = true; // Ensure the buffer is set up _buffer = _rw.CreateBufferRenderTexture(_buffer); _sb.RenderTarget = _buffer; if (_buffer == null) return null; _buffer.Clear(BackgroundColor); // Start up the SpriteBatch _sb.Begin(BlendMode.Alpha, camera); // Change the state _state = DrawingManagerState.DrawingWorld; } catch (AccessViolationException ex) { // More frequent and less concerning exception const string errmsg = "Failed to start drawing world on `{0}`. Device was probably lost. Exception: {1}"; if (log.IsInfoEnabled) log.InfoFormat(errmsg, this, ex); _state = DrawingManagerState.Idle; SafeEndSpriteBatch(_sb); return null; } catch (Exception ex) { // Unexpected exception const string errmsg = "Failed to start drawing world on `{0}` due to unexpected exception. Exception: {1}"; if (log.IsErrorEnabled) log.ErrorFormat(errmsg, this, ex); Debug.Fail(string.Format(errmsg, this, ex)); _state = DrawingManagerState.Idle; SafeEndSpriteBatch(_sb); return null; } return _sb; } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { if (_isDisposed) return; _isDisposed = true; Dispose(true); } /// <summary> /// Ends drawing the graphical user interface. /// </summary> /// <exception cref="InvalidOperationException"><see cref="IDrawingManager.State"/> is not equal to /// <see cref="DrawingManagerState.DrawingGUI"/>.</exception> [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "BeginDrawGUI")] public void EndDrawGUI() { if (State != DrawingManagerState.DrawingGUI) throw new InvalidOperationException("This method can only be called after BeginDrawGUI."); try { _state = DrawingManagerState.Idle; // Ensure the RenderWindow is available if (!IsRenderWindowAvailable()) { if (log.IsInfoEnabled) log.Info("Skipping EndDrawGUI() call - the RenderWindow is not available."); return; } // Ensure the buffer is available if (_buffer == null || _buffer.IsDisposed) { const string errmsg = "Skipping EndDrawWorld() call - the _buffer is not available."; if (log.IsWarnEnabled) log.WarnFormat(errmsg); return; } SafeEndSpriteBatch(_sb); // Copy the GUI to the screen _buffer.Display(); DrawBufferToScreen(_buffer.Texture, BlendMode.Alpha); } catch (AccessViolationException ex) { // More frequently and less concerning exception const string errmsg = "EndDrawGUI failed on `{0}`. Device was probably lost. The GUI will have to skip being drawn this frame. Exception: {1}"; if (log.IsInfoEnabled) log.InfoFormat(errmsg, this, ex); } catch (Exception ex) { // Unexpected exception const string errmsg = "EndDrawGUI failed on `{0}` due to unexpected exception. The GUI will have to skip being drawn this frame. Exception: {1}"; if (log.IsErrorEnabled) log.ErrorFormat(errmsg, this, ex); } } /// <summary> /// Ends drawing the world. /// </summary> /// <exception cref="InvalidOperationException"><see cref="IDrawingManager.State"/> is not equal to /// <see cref="DrawingManagerState.DrawingWorld"/>.</exception> [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "BeginDrawWorld")] public void EndDrawWorld() { if (State != DrawingManagerState.DrawingWorld) throw new InvalidOperationException("This method can only be called after BeginDrawWorld."); try { _state = DrawingManagerState.Idle; // Ensure the RenderWindow is available if (!IsRenderWindowAvailable()) { if (log.IsInfoEnabled) log.Info("Skipping EndDrawWorld() call - the RenderWindow is not available."); return; } // Ensure the buffer is available if (_buffer == null || _buffer.IsDisposed) { const string errmsg = "Skipping EndDrawWorld() call - the _buffer is not available."; if (log.IsWarnEnabled) log.WarnFormat(errmsg); return; } SafeEndSpriteBatch(_sb); // Draw the lights try { if (LightManager.IsEnabled) { // Copy the lights onto the buffer LightManager.DrawToTarget(_worldCamera, _buffer); _buffer.Display(); } else { // Don't have to take any alternate drawing route since lights are just drawn on top of the screen buffer } } catch (Exception ex) { // Do not catch AccessViolationException - let that be handled by the outer block if (ex is AccessViolationException) throw; const string errmsg = "Error on `{0}` while trying to draw the LightManager `{1}`." + " Lights will have to be skipped this frame. Exception: {2}"; if (log.IsErrorEnabled) log.ErrorFormat(errmsg, this, LightManager, ex); } // Have to display the buffer since we will start referencing the texture for it _buffer.Display(); // Draw the refractions try { if (RefractionManager.IsEnabled) { // Pass the buffer to the refraction manager to draw to the screen RefractionManager.DrawToTarget(_worldCamera, _rw, _buffer.Texture); } else { // Since the RefractionManager won't be handling copying to the screen for us, we will have to draw // to the screen manually DrawBufferToScreen(_buffer.Texture, BlendMode.None); } } catch (Exception ex) { // Do not catch AccessViolationException - let that be handled by the outer block if (ex is AccessViolationException) throw; const string errmsg = "Error on `{0}` while trying to draw the RefractionManager `{1}`." + " Refractions will have to be skipped this frame. Exception: {2}"; if (log.IsErrorEnabled) log.ErrorFormat(errmsg, this, RefractionManager, ex); } _view.Reset(new FloatRect(0, 0, _rw.Size.X, _rw.Size.Y)); _rw.SetView(_view); } catch (AccessViolationException ex) { // More frequently and less concerning exception const string errmsg = "EndDrawWorld failed on `{0}`. Device was probably lost. The world will have to skip being drawn this frame. Exception: {1}"; if (log.IsInfoEnabled) log.InfoFormat(errmsg, this, ex); } catch (Exception ex) { // Unexpected exception const string errmsg = "EndDrawWorld failed on `{0}` due to unexpected exception. The world will have to skip being drawn this frame. Exception: {1}"; if (log.IsErrorEnabled) log.ErrorFormat(errmsg, this, ex); } } /// <summary> /// Updates the <see cref="IDrawingManager"/> and all components inside of it. /// </summary> /// <param name="currentTime">The current game time in milliseconds.</param> public void Update(TickCount currentTime) { LightManager.Update(currentTime); RefractionManager.Update(currentTime); } #endregion } }
using System; using System.Collections.Concurrent; using System.Reflection; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; using Orleans.CodeGeneration; using Orleans.Serialization; namespace Orleans.Runtime { /// <summary> /// This is the base class for all typed grain references. /// </summary> [Serializable] public class GrainReference : IAddressable, IEquatable<GrainReference>, ISerializable { private readonly string genericArguments; private readonly GuidId observerId; [NonSerialized] private static readonly Logger logger = LogManager.GetLogger("GrainReference", LoggerType.Runtime); [NonSerialized] private static ConcurrentDictionary<int, string> debugContexts = new ConcurrentDictionary<int, string>(); [NonSerialized] private const bool USE_DEBUG_CONTEXT = true; [NonSerialized] private const bool USE_DEBUG_CONTEXT_PARAMS = false; [NonSerialized] private readonly bool isUnordered = false; internal bool IsSystemTarget { get { return GrainId.IsSystemTarget; } } internal bool IsObserverReference { get { return GrainId.IsClient; } } internal GuidId ObserverId { get { return observerId; } } private bool HasGenericArgument { get { return !String.IsNullOrEmpty(genericArguments); } } internal GrainId GrainId { get; private set; } /// <summary> /// Called from generated code. /// </summary> protected internal readonly SiloAddress SystemTargetSilo; /// <summary> /// Whether the runtime environment for system targets has been initialized yet. /// Called from generated code. /// </summary> protected internal bool IsInitializedSystemTarget { get { return SystemTargetSilo != null; } } internal bool IsUnordered { get { return isUnordered; } } #region Constructors /// <summary>Constructs a reference to the grain with the specified Id.</summary> /// <param name="grainId">The Id of the grain to refer to.</param> /// <param name="genericArgument">Type arguments in case of a generic grain.</param> /// <param name="systemTargetSilo">Target silo in case of a system target reference.</param> /// <param name="observerId">Observer ID in case of an observer reference.</param> private GrainReference(GrainId grainId, string genericArgument, SiloAddress systemTargetSilo, GuidId observerId) { GrainId = grainId; genericArguments = genericArgument; SystemTargetSilo = systemTargetSilo; this.observerId = observerId; if (String.IsNullOrEmpty(genericArgument)) { genericArguments = null; // always keep it null instead of empty. } // SystemTarget checks if (grainId.IsSystemTarget && systemTargetSilo==null) { throw new ArgumentNullException("systemTargetSilo", String.Format("Trying to create a GrainReference for SystemTarget grain id {0}, but passing null systemTargetSilo.", grainId)); } if (grainId.IsSystemTarget && genericArguments != null) { throw new ArgumentException(String.Format("Trying to create a GrainReference for SystemTarget grain id {0}, and also passing non-null genericArguments {1}.", grainId, genericArguments), "genericArgument"); } if (grainId.IsSystemTarget && observerId != null) { throw new ArgumentException(String.Format("Trying to create a GrainReference for SystemTarget grain id {0}, and also passing non-null observerId {1}.", grainId, observerId), "genericArgument"); } if (!grainId.IsSystemTarget && systemTargetSilo != null) { throw new ArgumentException(String.Format("Trying to create a GrainReference for non-SystemTarget grain id {0}, but passing a non-null systemTargetSilo {1}.", grainId, systemTargetSilo), "systemTargetSilo"); } // ObserverId checks if (grainId.IsClient && observerId == null) { throw new ArgumentNullException("observerId", String.Format("Trying to create a GrainReference for Observer with Client grain id {0}, but passing null observerId.", grainId)); } if (grainId.IsClient && genericArguments != null) { throw new ArgumentException(String.Format("Trying to create a GrainReference for Client grain id {0}, and also passing non-null genericArguments {1}.", grainId, genericArguments), "genericArgument"); } if (grainId.IsClient && systemTargetSilo != null) { throw new ArgumentException(String.Format("Trying to create a GrainReference for Client grain id {0}, and also passing non-null systemTargetSilo {1}.", grainId, systemTargetSilo), "genericArgument"); } if (!grainId.IsClient && observerId != null) { throw new ArgumentException(String.Format("Trying to create a GrainReference with non null Observer {0}, but non Client grain id {1}.", observerId, grainId), "observerId"); } isUnordered = GetUnordered(); } /// <summary> /// Constructs a copy of a grain reference. /// </summary> /// <param name="other">The reference to copy.</param> protected GrainReference(GrainReference other) : this(other.GrainId, other.genericArguments, other.SystemTargetSilo, other.ObserverId) { } #endregion #region Instance creator factory functions /// <summary>Constructs a reference to the grain with the specified ID.</summary> /// <param name="grainId">The ID of the grain to refer to.</param> /// <param name="genericArguments">Type arguments in case of a generic grain.</param> /// <param name="systemTargetSilo">Target silo in case of a system target reference.</param> internal static GrainReference FromGrainId(GrainId grainId, string genericArguments = null, SiloAddress systemTargetSilo = null) { return new GrainReference(grainId, genericArguments, systemTargetSilo, null); } internal static GrainReference NewObserverGrainReference(GrainId grainId, GuidId observerId) { return new GrainReference(grainId, null, null, observerId); } #endregion /// <summary> /// Tests this reference for equality to another object. /// Two grain references are equal if they both refer to the same grain. /// </summary> /// <param name="obj">The object to test for equality against this reference.</param> /// <returns><c>true</c> if the object is equal to this reference.</returns> public override bool Equals(object obj) { return Equals(obj as GrainReference); } public bool Equals(GrainReference other) { if (other == null) return false; if (genericArguments != other.genericArguments) return false; if (!GrainId.Equals(other.GrainId)) { return false; } if (IsSystemTarget) { return Equals(SystemTargetSilo, other.SystemTargetSilo); } if (IsObserverReference) { return observerId.Equals(other.observerId); } return true; } /// <summary> Calculates a hash code for a grain reference. </summary> public override int GetHashCode() { int hash = GrainId.GetHashCode(); if (IsSystemTarget) { hash = hash ^ SystemTargetSilo.GetHashCode(); } if (IsObserverReference) { hash = hash ^ observerId.GetHashCode(); } return hash; } /// <summary>Get a uniform hash code for this grain reference.</summary> public uint GetUniformHashCode() { // GrainId already includes the hashed type code for generic arguments. return GrainId.GetUniformHashCode(); } /// <summary> /// Compares two references for equality. /// Two grain references are equal if they both refer to the same grain. /// </summary> /// <param name="reference1">First grain reference to compare.</param> /// <param name="reference2">Second grain reference to compare.</param> /// <returns><c>true</c> if both grain references refer to the same grain (by grain identifier).</returns> public static bool operator ==(GrainReference reference1, GrainReference reference2) { if (((object)reference1) == null) return ((object)reference2) == null; return reference1.Equals(reference2); } /// <summary> /// Compares two references for inequality. /// Two grain references are equal if they both refer to the same grain. /// </summary> /// <param name="reference1">First grain reference to compare.</param> /// <param name="reference2">Second grain reference to compare.</param> /// <returns><c>false</c> if both grain references are resolved to the same grain (by grain identifier).</returns> public static bool operator !=(GrainReference reference1, GrainReference reference2) { if (((object)reference1) == null) return ((object)reference2) != null; return !reference1.Equals(reference2); } #region Protected members /// <summary> /// Implemented by generated subclasses to return a constant /// Implemented in generated code. /// </summary> protected virtual int InterfaceId { get { throw new InvalidOperationException("Should be overridden by subclass"); } } /// <summary> /// Implemented in generated code. /// </summary> public virtual bool IsCompatible(int interfaceId) { throw new InvalidOperationException("Should be overridden by subclass"); } /// <summary> /// Return the name of the interface for this GrainReference. /// Implemented in Orleans generated code. /// </summary> public virtual string InterfaceName { get { throw new InvalidOperationException("Should be overridden by subclass"); } } /// <summary> /// Return the method name associated with the specified interfaceId and methodId values. /// </summary> /// <param name="interfaceId">Interface Id</param> /// <param name="methodId">Method Id</param> /// <returns>Method name string.</returns> protected virtual string GetMethodName(int interfaceId, int methodId) { throw new InvalidOperationException("Should be overridden by subclass"); } /// <summary> /// Called from generated code. /// </summary> protected void InvokeOneWayMethod(int methodId, object[] arguments, InvokeMethodOptions options = InvokeMethodOptions.None, SiloAddress silo = null) { Task<object> resultTask = InvokeMethodAsync<object>(methodId, arguments, options | InvokeMethodOptions.OneWay); if (!resultTask.IsCompleted && resultTask.Result != null) { throw new OrleansException("Unexpected return value: one way InvokeMethod is expected to return null."); } } /// <summary> /// Called from generated code. /// </summary> protected Task<T> InvokeMethodAsync<T>(int methodId, object[] arguments, InvokeMethodOptions options = InvokeMethodOptions.None, SiloAddress silo = null) { object[] argsDeepCopy = null; if (arguments != null) { CheckForGrainArguments(arguments); SetGrainCancellationTokensTarget(arguments, this); argsDeepCopy = (object[])SerializationManager.DeepCopy(arguments); } var request = new InvokeMethodRequest(this.InterfaceId, methodId, argsDeepCopy); if (IsUnordered) options |= InvokeMethodOptions.Unordered; Task<object> resultTask = InvokeMethod_Impl(request, null, options); if (resultTask == null) { if (typeof(T) == typeof(object)) { // optimize for most common case when using one way calls. return PublicOrleansTaskExtensions.CompletedTask as Task<T>; } return Task.FromResult(default(T)); } resultTask = OrleansTaskExtentions.ConvertTaskViaTcs(resultTask); return resultTask.Unbox<T>(); } #endregion #region Private members private Task<object> InvokeMethod_Impl(InvokeMethodRequest request, string debugContext, InvokeMethodOptions options) { if (debugContext == null && USE_DEBUG_CONTEXT) { if (USE_DEBUG_CONTEXT_PARAMS) { #pragma warning disable 162 // This is normally unreachable code, but kept for debugging purposes debugContext = GetDebugContext(this.InterfaceName, GetMethodName(this.InterfaceId, request.MethodId), request.Arguments); #pragma warning restore 162 } else { var hash = InterfaceId ^ request.MethodId; if (!debugContexts.TryGetValue(hash, out debugContext)) { debugContext = GetDebugContext(this.InterfaceName, GetMethodName(this.InterfaceId, request.MethodId), request.Arguments); debugContexts[hash] = debugContext; } } } // Call any registered client pre-call interceptor function. CallClientInvokeCallback(request); bool isOneWayCall = ((options & InvokeMethodOptions.OneWay) != 0); var resolver = isOneWayCall ? null : new TaskCompletionSource<object>(); RuntimeClient.Current.SendRequest(this, request, resolver, ResponseCallback, debugContext, options, genericArguments); return isOneWayCall ? null : resolver.Task; } private void CallClientInvokeCallback(InvokeMethodRequest request) { // Make callback to any registered client callback function, allowing opportunity for an application to set any additional RequestContext info, etc. // Should we set some kind of callback-in-progress flag to detect and prevent any inappropriate callback loops on this GrainReference? try { Action<InvokeMethodRequest, IGrain> callback = GrainClient.ClientInvokeCallback; // Take copy to avoid potential race conditions if (callback == null) return; // Call ClientInvokeCallback only for grain calls, not for system targets. if (this is IGrain) { callback(request, (IGrain) this); } } catch (Exception exc) { logger.Warn(ErrorCode.ProxyClient_ClientInvokeCallback_Error, "Error while invoking ClientInvokeCallback function " + GrainClient.ClientInvokeCallback, exc); throw; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] private static void ResponseCallback(Message message, TaskCompletionSource<object> context) { Response response; if (message.Result != Message.ResponseTypes.Rejection) { try { response = (Response)message.BodyObject; } catch (Exception exc) { // catch the Deserialize exception and break the promise with it. response = Response.ExceptionResponse(exc); } } else { Exception rejection; switch (message.RejectionType) { case Message.RejectionTypes.GatewayTooBusy: rejection = new GatewayTooBusyException(); break; case Message.RejectionTypes.DuplicateRequest: return; // Ignore duplicates default: rejection = message.BodyObject as OrleansException; if (rejection == null) { if (string.IsNullOrEmpty(message.RejectionInfo)) { message.RejectionInfo = "Unable to send request - no rejection info available"; } rejection = new OrleansException(message.RejectionInfo); } break; } response = Response.ExceptionResponse(rejection); } if (!response.ExceptionFlag) { context.TrySetResult(response.Data); } else { context.TrySetException(response.Exception); } } private bool GetUnordered() { if (RuntimeClient.Current == null) return false; return RuntimeClient.Current.GrainTypeResolver != null && RuntimeClient.Current.GrainTypeResolver.IsUnordered(GrainId.GetTypeCode()); } #endregion private static String GetDebugContext(string interfaceName, string methodName, object[] arguments) { // String concatenation is approx 35% faster than string.Format here //debugContext = String.Format("{0}:{1}()", this.InterfaceName, GetMethodName(this.InterfaceId, methodId)); var debugContext = new StringBuilder(); debugContext.Append(interfaceName); debugContext.Append(":"); debugContext.Append(methodName); if (USE_DEBUG_CONTEXT_PARAMS && arguments != null && arguments.Length > 0) { debugContext.Append("("); debugContext.Append(Utils.EnumerableToString(arguments)); debugContext.Append(")"); } else { debugContext.Append("()"); } return debugContext.ToString(); } private static void CheckForGrainArguments(object[] arguments) { foreach (var argument in arguments) if (argument is Grain) throw new ArgumentException(String.Format("Cannot pass a grain object {0} as an argument to a method. Pass this.AsReference<GrainInterface>() instead.", argument.GetType().FullName)); } /// <summary> /// Sets target grain to the found instances of type GrainCancellationToken /// </summary> /// <param name="arguments"> Grain method arguments list</param> /// <param name="target"> Target grain reference</param> private static void SetGrainCancellationTokensTarget(object[] arguments, GrainReference target) { if (arguments == null) return; foreach (var argument in arguments) { (argument as GrainCancellationToken)?.AddGrainReference(target); } } /// <summary> Serializer function for grain reference.</summary> /// <seealso cref="SerializationManager"/> [SerializerMethod] protected internal static void SerializeGrainReference(object obj, BinaryTokenStreamWriter stream, Type expected) { var input = (GrainReference)obj; stream.Write(input.GrainId); if (input.IsSystemTarget) { stream.Write((byte)1); stream.Write(input.SystemTargetSilo); } else { stream.Write((byte)0); } if (input.IsObserverReference) { input.observerId.SerializeToStream(stream); } // store as null, serialize as empty. var genericArg = String.Empty; if (input.HasGenericArgument) genericArg = input.genericArguments; stream.Write(genericArg); } /// <summary> Deserializer function for grain reference.</summary> /// <seealso cref="SerializationManager"/> [DeserializerMethod] protected internal static object DeserializeGrainReference(Type t, BinaryTokenStreamReader stream) { GrainId id = stream.ReadGrainId(); SiloAddress silo = null; GuidId observerId = null; byte siloAddressPresent = stream.ReadByte(); if (siloAddressPresent != 0) { silo = stream.ReadSiloAddress(); } bool expectObserverId = id.IsClient; if (expectObserverId) { observerId = GuidId.DeserializeFromStream(stream); } // store as null, serialize as empty. var genericArg = stream.ReadString(); if (String.IsNullOrEmpty(genericArg)) genericArg = null; if (expectObserverId) { return NewObserverGrainReference(id, observerId); } return FromGrainId(id, genericArg, silo); } /// <summary> Copier function for grain reference. </summary> /// <seealso cref="SerializationManager"/> [CopierMethod] protected internal static object CopyGrainReference(object original) { return (GrainReference)original; } private const string GRAIN_REFERENCE_STR = "GrainReference"; private const string SYSTEM_TARGET_STR = "SystemTarget"; private const string OBSERVER_ID_STR = "ObserverId"; private const string GENERIC_ARGUMENTS_STR = "GenericArguments"; /// <summary>Returns a string representation of this reference.</summary> public override string ToString() { if (IsSystemTarget) { return String.Format("{0}:{1}/{2}", SYSTEM_TARGET_STR, GrainId, SystemTargetSilo); } if (IsObserverReference) { return String.Format("{0}:{1}/{2}", OBSERVER_ID_STR, GrainId, observerId); } return String.Format("{0}:{1}{2}", GRAIN_REFERENCE_STR, GrainId, !HasGenericArgument ? String.Empty : String.Format("<{0}>", genericArguments)); } internal string ToDetailedString() { if (IsSystemTarget) { return String.Format("{0}:{1}/{2}", SYSTEM_TARGET_STR, GrainId.ToDetailedString(), SystemTargetSilo); } if (IsObserverReference) { return String.Format("{0}:{1}/{2}", OBSERVER_ID_STR, GrainId.ToDetailedString(), observerId.ToDetailedString()); } return String.Format("{0}:{1}{2}", GRAIN_REFERENCE_STR, GrainId.ToDetailedString(), !HasGenericArgument ? String.Empty : String.Format("<{0}>", genericArguments)); } /// <summary> Get the key value for this grain, as a string. </summary> public string ToKeyString() { if (IsObserverReference) { return String.Format("{0}={1} {2}={3}", GRAIN_REFERENCE_STR, GrainId.ToParsableString(), OBSERVER_ID_STR, observerId.ToParsableString()); } if (IsSystemTarget) { return String.Format("{0}={1} {2}={3}", GRAIN_REFERENCE_STR, GrainId.ToParsableString(), SYSTEM_TARGET_STR, SystemTargetSilo.ToParsableString()); } if (HasGenericArgument) { return String.Format("{0}={1} {2}={3}", GRAIN_REFERENCE_STR, GrainId.ToParsableString(), GENERIC_ARGUMENTS_STR, genericArguments); } return String.Format("{0}={1}", GRAIN_REFERENCE_STR, GrainId.ToParsableString()); } public static GrainReference FromKeyString(string key) { if (string.IsNullOrWhiteSpace(key)) throw new ArgumentNullException("key", "GrainReference.FromKeyString cannot parse null key"); string trimmed = key.Trim(); string grainIdStr; int grainIdIndex = (GRAIN_REFERENCE_STR + "=").Length; int genericIndex = trimmed.IndexOf(GENERIC_ARGUMENTS_STR + "=", StringComparison.Ordinal); int observerIndex = trimmed.IndexOf(OBSERVER_ID_STR + "=", StringComparison.Ordinal); int systemTargetIndex = trimmed.IndexOf(SYSTEM_TARGET_STR + "=", StringComparison.Ordinal); if (genericIndex >= 0) { grainIdStr = trimmed.Substring(grainIdIndex, genericIndex - grainIdIndex).Trim(); string genericStr = trimmed.Substring(genericIndex + (GENERIC_ARGUMENTS_STR + "=").Length); if (String.IsNullOrEmpty(genericStr)) { genericStr = null; } return FromGrainId(GrainId.FromParsableString(grainIdStr), genericStr); } else if (observerIndex >= 0) { grainIdStr = trimmed.Substring(grainIdIndex, observerIndex - grainIdIndex).Trim(); string observerIdStr = trimmed.Substring(observerIndex + (OBSERVER_ID_STR + "=").Length); GuidId observerId = GuidId.FromParsableString(observerIdStr); return NewObserverGrainReference(GrainId.FromParsableString(grainIdStr), observerId); } else if (systemTargetIndex >= 0) { grainIdStr = trimmed.Substring(grainIdIndex, systemTargetIndex - grainIdIndex).Trim(); string systemTargetStr = trimmed.Substring(systemTargetIndex + (SYSTEM_TARGET_STR + "=").Length); SiloAddress siloAddress = SiloAddress.FromParsableString(systemTargetStr); return FromGrainId(GrainId.FromParsableString(grainIdStr), null, siloAddress); } else { grainIdStr = trimmed.Substring(grainIdIndex); return FromGrainId(GrainId.FromParsableString(grainIdStr)); } //return FromGrainId(GrainId.FromParsableString(grainIdStr), generic); } #region ISerializable Members public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { // Use the AddValue method to specify serialized values. info.AddValue("GrainId", GrainId.ToParsableString(), typeof(string)); if (IsSystemTarget) { info.AddValue("SystemTargetSilo", SystemTargetSilo.ToParsableString(), typeof(string)); } if (IsObserverReference) { info.AddValue(OBSERVER_ID_STR, observerId.ToParsableString(), typeof(string)); } string genericArg = String.Empty; if (HasGenericArgument) genericArg = genericArguments; info.AddValue("GenericArguments", genericArg, typeof(string)); } // The special constructor is used to deserialize values. protected GrainReference(SerializationInfo info, StreamingContext context) { // Reset the property value using the GetValue method. var grainIdStr = info.GetString("GrainId"); GrainId = GrainId.FromParsableString(grainIdStr); if (IsSystemTarget) { var siloAddressStr = info.GetString("SystemTargetSilo"); SystemTargetSilo = SiloAddress.FromParsableString(siloAddressStr); } if (IsObserverReference) { var observerIdStr = info.GetString(OBSERVER_ID_STR); observerId = GuidId.FromParsableString(observerIdStr); } var genericArg = info.GetString("GenericArguments"); if (String.IsNullOrEmpty(genericArg)) genericArg = null; genericArguments = genericArg; } #endregion } }
using System; using NUnit.Framework; using NServiceKit.Common.Extensions; using NServiceKit.DataAnnotations; using NServiceKit.Logging; using NServiceKit.Text; namespace NServiceKit.Common.Tests.Models { /// <summary>A model with fields of different types as nullables.</summary> public class ModelWithFieldsOfDifferentTypesAsNullables { private static readonly ILog Log = LogManager.GetLogger(typeof(ModelWithFieldsOfDifferentTypesAsNullables)); /// <summary>Gets or sets the identifier.</summary> /// /// <value>The identifier.</value> public int? Id { get; set; } /// <summary>Gets or sets the name.</summary> /// /// <value>The name.</value> public string Name { get; set; } /// <summary>Gets or sets the identifier of the long.</summary> /// /// <value>The identifier of the long.</value> public long? LongId { get; set; } /// <summary>Gets or sets a unique identifier.</summary> /// /// <value>The identifier of the unique.</value> public Guid? Guid { get; set; } /// <summary>Gets or sets the. </summary> /// /// <value>The bool.</value> public bool? Bool { get; set; } /// <summary>Gets or sets the date time.</summary> /// /// <value>The date time.</value> public DateTime? DateTime { get; set; } /// <summary>Gets or sets the double.</summary> /// /// <value>The double.</value> public double? Double { get; set; } /// <summary>Creates a new ModelWithFieldsOfDifferentTypesAsNullables.</summary> /// /// <param name="id">The identifier.</param> /// /// <returns>The ModelWithFieldsOfDifferentTypesAsNullables.</returns> public static ModelWithFieldsOfDifferentTypesAsNullables Create(int id) { var row = new ModelWithFieldsOfDifferentTypesAsNullables { Id = id, Bool = id % 2 == 0, DateTime = System.DateTime.Now.AddDays(id), Double = 1.11d + id, Guid = System.Guid.NewGuid(), LongId = 999 + id, Name = "Name" + id }; return row; } /// <summary>Creates a constant.</summary> /// /// <param name="id">The identifier.</param> /// /// <returns>The new constant.</returns> public static ModelWithFieldsOfDifferentTypesAsNullables CreateConstant(int id) { var row = new ModelWithFieldsOfDifferentTypesAsNullables { Id = id, Bool = id % 2 == 0, DateTime = new DateTime(1979, (id % 12) + 1, (id % 28) + 1), Double = 1.11d + id, Guid = new Guid(((id % 240) + 16).ToString("X") + "726E3B-9983-40B4-A8CB-2F8ADA8C8760"), LongId = 999 + id, Name = "Name" + id }; return row; } /// <summary>Assert is equal.</summary> /// /// <param name="actual"> The actual.</param> /// <param name="expected">The expected.</param> public static void AssertIsEqual(ModelWithFieldsOfDifferentTypes actual, ModelWithFieldsOfDifferentTypesAsNullables expected) { Assert.That(actual.Id, Is.EqualTo(expected.Id.Value)); Assert.That(actual.Name, Is.EqualTo(expected.Name)); Assert.That(actual.Guid, Is.EqualTo(expected.Guid.Value)); Assert.That(actual.LongId, Is.EqualTo(expected.LongId.Value)); Assert.That(actual.Bool, Is.EqualTo(expected.Bool.Value)); try { Assert.That(actual.DateTime, Is.EqualTo(expected.DateTime.Value)); } catch (Exception ex) { Log.Error("Trouble with DateTime precisions, trying Assert again with rounding to seconds", ex); Assert.That(actual.DateTime.RoundToSecond(), Is.EqualTo(expected.DateTime.Value.RoundToSecond())); } try { Assert.That(actual.Double, Is.EqualTo(expected.Double.Value)); } catch (Exception ex) { Log.Error("Trouble with double precisions, trying Assert again with rounding to 10 decimals", ex); Assert.That(Math.Round(actual.Double, 10), Is.EqualTo(Math.Round(actual.Double, 10))); } } } /// <summary>A model with fields of different types.</summary> public class ModelWithFieldsOfDifferentTypes { private static readonly ILog Log = LogManager.GetLogger(typeof(ModelWithFieldsOfDifferentTypes)); /// <summary>Gets or sets the identifier.</summary> /// /// <value>The identifier.</value> [AutoIncrement] public int Id { get; set; } /// <summary>Gets or sets the name.</summary> /// /// <value>The name.</value> public string Name { get; set; } /// <summary>Gets or sets the identifier of the long.</summary> /// /// <value>The identifier of the long.</value> public long LongId { get; set; } /// <summary>Gets or sets a unique identifier.</summary> /// /// <value>The identifier of the unique.</value> public Guid Guid { get; set; } /// <summary>Gets or sets a value indicating whether the. </summary> /// /// <value>true if , false if not.</value> public bool Bool { get; set; } /// <summary>Gets or sets the date time.</summary> /// /// <value>The date time.</value> public DateTime DateTime { get; set; } /// <summary>Gets or sets the double.</summary> /// /// <value>The double.</value> public double Double { get; set; } /// <summary>Creates a new ModelWithFieldsOfDifferentTypes.</summary> /// /// <param name="id">The identifier.</param> /// /// <returns>The ModelWithFieldsOfDifferentTypes.</returns> public static ModelWithFieldsOfDifferentTypes Create(int id) { var row = new ModelWithFieldsOfDifferentTypes { Id = id, Bool = id % 2 == 0, DateTime = DateTime.Now.AddDays(id), Double = 1.11d + id, Guid = Guid.NewGuid(), LongId = 999 + id, Name = "Name" + id }; return row; } /// <summary>Creates a constant.</summary> /// /// <param name="id">The identifier.</param> /// /// <returns>The new constant.</returns> public static ModelWithFieldsOfDifferentTypes CreateConstant(int id) { var row = new ModelWithFieldsOfDifferentTypes { Id = id, Bool = id % 2 == 0, DateTime = new DateTime(1979, (id % 12) + 1, (id % 28) + 1), Double = 1.11d + id, Guid = new Guid(((id % 240) + 16).ToString("X") + "726E3B-9983-40B4-A8CB-2F8ADA8C8760"), LongId = 999 + id, Name = "Name" + id }; return row; } /// <summary>Determines whether the specified <see cref="T:System.Object" /> is equal to the current <see cref="T:System.Object" />.</summary> /// /// <param name="obj">The <see cref="T:System.Object" /> to compare with the current <see cref="T:System.Object" />.</param> /// /// <returns>true if the specified <see cref="T:System.Object" /> is equal to the current <see cref="T:System.Object" />; otherwise, false.</returns> public override bool Equals(object obj) { var other = obj as ModelWithFieldsOfDifferentTypes; if (other == null) return false; try { AssertIsEqual(this, other); return true; } catch (Exception) { return false; } } /// <summary>Serves as a hash function for a particular type.</summary> /// /// <returns>A hash code for the current <see cref="T:System.Object" />.</returns> public override int GetHashCode() { return (Id + Guid.ToString()).GetHashCode(); } /// <summary>Assert is equal.</summary> /// /// <param name="actual"> The actual.</param> /// <param name="expected">The expected.</param> public static void AssertIsEqual(ModelWithFieldsOfDifferentTypes actual, ModelWithFieldsOfDifferentTypes expected) { Assert.That(actual.Id, Is.EqualTo(expected.Id)); Assert.That(actual.Name, Is.EqualTo(expected.Name)); Assert.That(actual.Guid, Is.EqualTo(expected.Guid)); Assert.That(actual.LongId, Is.EqualTo(expected.LongId)); Assert.That(actual.Bool, Is.EqualTo(expected.Bool)); try { Assert.That(actual.DateTime, Is.EqualTo(expected.DateTime)); } catch (Exception ex) { Log.Error("Trouble with DateTime precisions, trying Assert again with rounding to seconds", ex); Assert.That(actual.DateTime.RoundToSecond(), Is.EqualTo(expected.DateTime.RoundToSecond())); } try { Assert.That(actual.Double, Is.EqualTo(expected.Double)); } catch (Exception ex) { Log.Error("Trouble with double precisions, trying Assert again with rounding to 10 decimals", ex); Assert.That(Math.Round(actual.Double, 10), Is.EqualTo(Math.Round(actual.Double, 10))); } } } }
// DataEditor.cs // using jQueryApi; using jQueryApi.UI.Widgets; using Slick; using System; using System.Collections.Generic; using Xrm.Sdk; namespace SparkleXrm.GridEditor { public class XrmDateEditor : GridEditorBase { public static EditorFactory CrmDateEditor; static XrmDateEditor() { CrmDateEditor = delegate(EditorArguments args) { XrmDateEditor editor = new XrmDateEditor(args); return editor; }; } public static string FormatterDateOnly(int row, int cell, object value, Column columnDef, object dataContext) { string dateFormat = (string)columnDef.Options; if (OrganizationServiceProxy.UserSettings != null) { dateFormat = OrganizationServiceProxy.UserSettings.DateFormatString; } DateTime dateValue = (DateTime)value; return DateTimeEx.FormatDateSpecific(dateValue, dateFormat); } public static string FormatterDateAndTime(int row, int cell, object value, Column columnDef, object dataContext) { string dateFormat = (string)columnDef.Options; if (OrganizationServiceProxy.UserSettings != null) { dateFormat = OrganizationServiceProxy.UserSettings.DateFormatString + " " + OrganizationServiceProxy.UserSettings.TimeFormatString; } DateTime dateValue = (DateTime)value; return DateTimeEx.FormatDateSpecific(dateValue, dateFormat); } private jQueryObject _input; private jQueryObject _container; private DateTime _defaultValue=null; private bool _calendarOpen = false; private DateTime _selectedValue = null; private string _dateFormat = "dd/mm/yy"; public XrmDateEditor(EditorArguments args) : base(args) { XrmDateEditor self = this; _container = jQuery.FromHtml("<div ><table class='inline-edit-container' cellspacing='0' cellpadding='0'><tr>" + "<td><INPUT type=text class='sparkle-input-inline' /></td>" + "<td class='lookup-button-td'><input type=button class='sparkle-imagestrip-inlineedit_calendar_icon' /></td></tr></table></div>"); _container.AppendTo(_args.Container); _input = _container.Find(".sparkle-input-inline"); _input.Bind("keydown.nav", delegate(jQueryEvent e) { if (!_calendarOpen && (e.Which == 38 || e.Which == 40) && e.CtrlKey) // Ctrl-Up/Down shows date picker { _input.Plugin<DatePickerPlugIn>().DatePicker(DatePickerMethod2.Show); e.StopImmediatePropagation(); } else if (_calendarOpen && e.Which == 13) { e.PreventDefault(); } }); jQueryObject selectButton = _container.Find(".sparkle-imagestrip-inlineedit_calendar_icon"); _input.Focus().Select(); DatePickerOptions2 options2 = new DatePickerOptions2(); options2.ShowOtherMonths = true; options2.ShowOn = ""; // Date Pickers in CRM do not show when they are focused - you click the button options2.FirstDay = OrganizationServiceProxy.OrganizationSettings != null ? OrganizationServiceProxy.OrganizationSettings.WeekStartDayCode.Value.Value : 0; options2.BeforeShow = delegate() { this._calendarOpen = true; }; options2.OnClose = delegate() { this._calendarOpen = false; _selectedValue = GetSelectedValue(); }; options2.OnSelect = delegate(string dateString, object instance) { // Select the date text field when selecting a date Focus(); }; if (OrganizationServiceProxy.UserSettings != null) { _dateFormat = OrganizationServiceProxy.UserSettings.DateFormatString; } options2.DateFormat = _dateFormat; _input.Plugin<DatePickerPlugIn>().DatePicker(options2); // Wire up the date picker button selectButton.Click(delegate(jQueryEvent e){ _input.Plugin<DatePickerPlugIn>().DatePicker(DatePickerMethod2.Show); Focus(); }); //_input.Width(_input.GetWidth() - 24); } public override void Destroy() { ((jQueryObject)Script.Literal("$.datepicker.dpDiv")).Stop(true, true); _input.Plugin<DatePickerPlugIn>().DatePicker(DatePickerMethod2.Hide); _input.Plugin<DatePickerPlugIn>().DatePicker(DatePickerMethod2.Destroy); Hide(); // Ensure the calendar is hidden when ending an edit _container.Remove(); } public override void Show() { if (_calendarOpen) { ((jQueryObject)Script.Literal("$.datepicker.dpDiv")).Stop(true, true).Show(); } } public override void Hide() { if (_calendarOpen) { ((jQueryObject)Script.Literal("$.datepicker.dpDiv")).Stop(true, true).Hide(); } } public override void Position(jQueryPosition position) { if (!_calendarOpen) { return; } ((jQueryObject)Script.Literal("$.datepicker.dpDiv")).CSS("top", (position.Top + 30).ToString()).CSS("left", position.Left.ToString()); } public override void Focus() { _input.Focus(); } public override void LoadValue(Dictionary<string, object> item) { DateTime currentValue = (DateTime)item[_args.Column.Field]; _defaultValue = currentValue!=null ? currentValue : null; string valueFormated = _defaultValue != null ? _defaultValue.ToLocaleDateString() : String.Empty; if (_args.Column.Formatter != null) { valueFormated = _args.Column.Formatter(0, 0, _defaultValue, _args.Column, null); } //_input[0].defaultValue = defaultValue; SetSelectedValue(_defaultValue); //_input.Value(valueFormated); _input.Select(); } public override object SerializeValue() { //string stringVal = _input.GetValue(); //Date dateVal = Date.Parse(stringVal); return GetSelectedValue(); } public override void ApplyValue(Dictionary<string, object> item, object state) { DateTime previousValue = (DateTime)item[_args.Column.Field]; DateTime newValue = (DateTime)state; DateTimeEx.SetTime(newValue, previousValue); item[_args.Column.Field] = newValue; this.RaiseOnChange(item); } public override bool IsValueChanged() { DateTime selectedValue = GetSelectedValue(); string selected = selectedValue == null ? "" : selectedValue.ToString(); string defaultValueString = _defaultValue == null ? "" : _defaultValue.ToString(); return (selected!=defaultValueString); } private DateTime GetSelectedValue() { DateTime selectedValue = null; if (!_calendarOpen) { selectedValue = DateTimeEx.ParseDateSpecific(_input.GetValue(), _dateFormat); } else { selectedValue = (DateTime)_input.Plugin<DatePickerObject>().DatePicker(DatePickerMethod.GetDate); } return selectedValue; } private void SetSelectedValue(DateTime date) { _input.Plugin<DatePickerObject>().DatePicker(DatePickerMethod.SetDate, date); } public static Column BindColumn(Column column, bool dateOnly) { column.Editor = CrmDateEditor; column.Formatter = FormatterDateOnly; return column; } public static Column BindReadOnlyColumn(Column column, bool dateOnly) { column.Formatter = FormatterDateOnly; return column; } } }
using UnityEngine; using UnityEngine.UI; using System; using System.Collections; using System.IO; using System.Collections.Generic; public class movement_controller : MonoBehaviour { public Material glass_mat; public Material glow_neon_mat; public Material glow_red_mat; public GameObject destructionPrefab; public GameObject polarizationPrefab; public RaycastHit hit_latest, hit_latest2; public int hit_latest_column, hit_latest_row; public int hit_latest2_column, hit_latest2_row; public AudioSource destroy_sound; public AudioSource moving_sound; private bool correct_pawn_selected = false; // Use this for initialization void Start () { } // Update is called once per frame void Update () { if(game_controller.game_started && !game_controller.game_ended && !game_controller.game_paused && !game_controller.placing_plastic ){ if (Input.GetButtonDown("Fire1")) { glowOff(); correct_pawn_selected = false; Ray ray = game_controller.activeCam.ScreenPointToRay(Input.mousePosition); if(Physics.Raycast(ray,out hit_latest,Mathf.Infinity)){ // Debug: Selection of glass in hit_latest instead of pawn // Re-RayCast using current x and z Physics.Raycast( new Vector3 (hit_latest.transform.position.x, 5f, hit_latest.transform.position.z), Vector3.down,out hit_latest,Mathf.Infinity); // Check if it is a Self Destruction Cell if(hit_latest.transform.position.x < 0.5f || hit_latest.transform.position.z < -1.5f || hit_latest.transform.position.x > 5.5f || hit_latest.transform.position.z > 3.5f){ //Debug.Log("Skipped"); goto skip_update_hit_fire1; } // Check if it is a pawn of the current team hit_latest_column = (int)(hit_latest.transform.position.x + 0.5f); hit_latest_row = (int)(hit_latest.transform.position.z + 2.5f); Debug.Log("Player" + game_controller.playerNo + " clicked on [" + hit_latest_row + ", " + hit_latest_column + "] = " + game_controller.boardMatrix[hit_latest_row,hit_latest_column]); if(game_controller.boardMatrix[hit_latest_row,hit_latest_column] >= 1 && game_controller.boardMatrix[hit_latest_row,hit_latest_column] <= 3 && game_controller.playerNo == 1 || game_controller.boardMatrix[hit_latest_row,hit_latest_column] >= 5 && game_controller.boardMatrix[hit_latest_row,hit_latest_column] <= 7 && game_controller.playerNo == 2 ){ //Debug.Log(hit_latest.transform.gameObject.name); correct_pawn_selected = true; //Debug.Log(hit_latest.transform.position); int i = (int)((hit_latest.transform.position.x - 0.5f)*6 + (hit_latest.transform.position.z + 2.5f)); if(i + 6 <= 36){ glowOn(i + 6); } if(i - 6 > 0){ glowOn(i - 6); } if(i % 6 != 0){ glowOn(i + 1); } else { redGlowOn(i); } if((i-1) % 6 != 0){ glowOn(i - 1); } else { redGlowOn(i); } if(i <= 6 || i >= 31){ redGlowOn(i); } } // check if magnet is selected and glow effected i.e. polarized irons if (GetComponent<game_controller>().polarization_rule_on) { if (game_controller.boardMatrix [hit_latest_row, hit_latest_column] == 1) { if (game_controller.boardMatrix [hit_latest_row + 1, hit_latest_column] == 2) { Vector3 tempVect = new Vector3 ((float)hit_latest_column - 0.5f, 1.15f, (float)hit_latest_row + 1f - 2.5f); GameObject pPrefab = Instantiate (polarizationPrefab, tempVect, Quaternion.identity) as GameObject; } if (game_controller.boardMatrix [hit_latest_row - 1, hit_latest_column] == 2) { Vector3 tempVect = new Vector3 ((float)hit_latest_column - 0.5f, 1.05f, (float)hit_latest_row - 1f - 2.5f); GameObject pPrefab = Instantiate (polarizationPrefab, tempVect, Quaternion.identity) as GameObject; } if (game_controller.boardMatrix [hit_latest_row, hit_latest_column + 1] == 2) { Vector3 tempVect = new Vector3 ((float)hit_latest_column + 1f - 0.5f, 1.05f, (float)hit_latest_row - 2.5f); GameObject pPrefab = Instantiate (polarizationPrefab, tempVect, Quaternion.identity) as GameObject; } if (game_controller.boardMatrix [hit_latest_row, hit_latest_column - 1] == 2) { Vector3 tempVect = new Vector3 ((float)hit_latest_column - 1f - 0.5f, 1.05f, (float)hit_latest_row - 2.5f); GameObject pPrefab = Instantiate (polarizationPrefab, tempVect, Quaternion.identity) as GameObject; } } if (game_controller.boardMatrix [hit_latest_row, hit_latest_column] == 5) { if (game_controller.boardMatrix [hit_latest_row + 1, hit_latest_column] == 6) { Vector3 tempVect = new Vector3 ((float)hit_latest_column - 0.5f, 1.15f, (float)hit_latest_row + 1f - 2.5f); GameObject pPrefab = Instantiate (polarizationPrefab, tempVect, Quaternion.identity) as GameObject; } if (game_controller.boardMatrix [hit_latest_row - 1, hit_latest_column] == 6) { Vector3 tempVect = new Vector3 ((float)hit_latest_column - 0.5f, 1.05f, (float)hit_latest_row - 1f - 2.5f); GameObject pPrefab = Instantiate (polarizationPrefab, tempVect, Quaternion.identity) as GameObject; } if (game_controller.boardMatrix [hit_latest_row, hit_latest_column + 1] == 6) { Vector3 tempVect = new Vector3 ((float)hit_latest_column + 1f - 0.5f, 1.05f, (float)hit_latest_row - 2.5f); GameObject pPrefab = Instantiate (polarizationPrefab, tempVect, Quaternion.identity) as GameObject; } if (game_controller.boardMatrix [hit_latest_row, hit_latest_column - 1] == 6) { Vector3 tempVect = new Vector3 ((float)hit_latest_column - 1f - 0.5f, 1.05f, (float)hit_latest_row - 2.5f); GameObject pPrefab = Instantiate (polarizationPrefab, tempVect, Quaternion.identity) as GameObject; } } } } } skip_update_hit_fire1: if (Input.GetButtonDown("Fire2") && !game_controller.placing_plastic) { glowOff(); Ray ray = game_controller.activeCam.ScreenPointToRay(Input.mousePosition); if(Physics.Raycast(ray,out hit_latest2,Mathf.Infinity)){ hit_latest2_column = (int)(hit_latest2.transform.position.x + 0.5f); hit_latest2_row = (int)(hit_latest2.transform.position.z + 2.5f); float distance = Mathf.Abs(hit_latest2.transform.position.x - hit_latest.transform.position.x) + Mathf.Abs(hit_latest2.transform.position.z - hit_latest.transform.position.z); int x_value = (int)(Mathf.Abs(hit_latest2.transform.position.x - hit_latest.transform.position.x)); int z_value = (int)(Mathf.Abs(hit_latest2.transform.position.z - hit_latest.transform.position.z)); if(x_value == 1){ x_value = (int)(Mathf.Abs(hit_latest2.transform.position.x - hit_latest.transform.position.x)/(hit_latest2.transform.position.x - hit_latest.transform.position.x)); } if(z_value == 1){ z_value = (int)(Mathf.Abs(hit_latest2.transform.position.z - hit_latest.transform.position.z)/(hit_latest2.transform.position.z - hit_latest.transform.position.z)); } if(distance == 1 && correct_pawn_selected && !GetComponent<game_controller>().swapping_preferred){ // change_player returns 1 if the move was successful int change_player = move_or_push_pawn (hit_latest_row, hit_latest_column, z_value, x_value); if (change_player == 1 && game_controller.boardMatrix [hit_latest_row + z_value, hit_latest_column + x_value] == 1) { Debug.Log ("Magnet1 polarization effect taking place."); if (x_value == 0) { if (game_controller.boardMatrix [hit_latest_row, hit_latest_column + 1] == 2) { move_or_push_pawn (hit_latest_row, hit_latest_column + 1, z_value, x_value); } if (game_controller.boardMatrix [hit_latest_row, hit_latest_column - 1] == 2) { move_or_push_pawn (hit_latest_row, hit_latest_column - 1, z_value, x_value); } } if (z_value == 0) { if (game_controller.boardMatrix [hit_latest_row + 1, hit_latest_column] == 2) { move_or_push_pawn (hit_latest_row + 1, hit_latest_column, z_value, x_value); } if (game_controller.boardMatrix [hit_latest_row - 1, hit_latest_column] == 2) { move_or_push_pawn (hit_latest_row - 1, hit_latest_column, z_value, x_value); } } if (game_controller.boardMatrix [hit_latest_row - z_value, hit_latest_column - x_value] == 2) { push_pawn (hit_latest_row - z_value, hit_latest_column - x_value, z_value, x_value); } } if (change_player == 1 && game_controller.boardMatrix [hit_latest_row + z_value, hit_latest_column + x_value] == 5) { Debug.Log ("Magnet2 polarization effect taking place."); if (x_value == 0) { if (game_controller.boardMatrix [hit_latest_row, hit_latest_column + 1] == 6) { move_or_push_pawn (hit_latest_row, hit_latest_column + 1, z_value, x_value); } if (game_controller.boardMatrix [hit_latest_row, hit_latest_column - 1] == 6) { move_or_push_pawn (hit_latest_row, hit_latest_column - 1, z_value, x_value); } } if (z_value == 0) { if (game_controller.boardMatrix [hit_latest_row + 1, hit_latest_column] == 6) { move_or_push_pawn (hit_latest_row + 1, hit_latest_column, z_value, x_value); } if (game_controller.boardMatrix [hit_latest_row - 1, hit_latest_column] == 6) { move_or_push_pawn (hit_latest_row - 1, hit_latest_column, z_value, x_value); } } if (game_controller.boardMatrix [hit_latest_row - z_value, hit_latest_column - x_value] == 6) { push_pawn (hit_latest_row - z_value, hit_latest_column - x_value, z_value, x_value); } } if (change_player == 1) { game_controller.changePlayer (); } } // if swapping is on if (distance == 1 && correct_pawn_selected && GetComponent<game_controller>().swapping_preferred) { // Player1 swaps if (game_controller.boardMatrix [hit_latest_row, hit_latest_column] == 1 && game_controller.boardMatrix [hit_latest2_row, hit_latest2_column] == 2) { Debug.Log ("Player1 swaps"); swap_pawn (hit_latest_row, hit_latest_column, hit_latest2_row - hit_latest_row, hit_latest2_column - hit_latest_column); move_analysis.learning_modifier ("swap", game_controller.playerNo); game_controller.changePlayer (); } // Player2 swaps else if (game_controller.boardMatrix [hit_latest_row, hit_latest_column] == 5 && game_controller.boardMatrix [hit_latest2_row, hit_latest2_column] == 6) { Debug.Log ("Player2 swaps"); swap_pawn (hit_latest_row, hit_latest_column, hit_latest2_row - hit_latest_row, hit_latest2_column - hit_latest_column); move_analysis.learning_modifier ("swap", game_controller.playerNo); game_controller.changePlayer (); } else { if(game_controller.boardMatrix [hit_latest2_row, hit_latest2_column] == 3 || game_controller.boardMatrix [hit_latest2_row, hit_latest2_column] == 7){ move_analysis.learning_modifier ("plastic_swap", game_controller.playerNo); } else { move_analysis.learning_modifier ("wrong_swap", game_controller.playerNo); } Debug.Log ("Swap not possible!"); } } } // You have to re-left-click to move again correct_pawn_selected = false; } } // If placing_plastic is on and plastic pawn is placed, but not moved yet if (Input.GetButtonDown("Fire2") && game_controller.placing_plastic && !game_controller.placed_plastic_moved) { Debug.Log("Right click move plastic " + game_controller.latest_plastic_position); Physics.Raycast( new Vector3 (game_controller.latest_plastic_position.x, 5f, game_controller.latest_plastic_position.z), Vector3.down,out hit_latest,Mathf.Infinity); hit_latest_column = (int)(game_controller.latest_plastic_position.x + 0.5f); hit_latest_row = (int)(game_controller.latest_plastic_position.z + 2.5f); Ray ray = game_controller.activeCam.ScreenPointToRay(Input.mousePosition); if(Physics.Raycast(ray,out hit_latest2,Mathf.Infinity)){ hit_latest2_column = (int)(hit_latest2.transform.position.x + 0.5f); hit_latest2_row = (int)(hit_latest2.transform.position.z + 2.5f); float distance = Mathf.Abs(hit_latest2.transform.position.x - hit_latest.transform.position.x) + Mathf.Abs(hit_latest2.transform.position.z - hit_latest.transform.position.z); int x_value = (int)(Mathf.Abs(hit_latest2.transform.position.x - hit_latest.transform.position.x)); int z_value = (int)(Mathf.Abs(hit_latest2.transform.position.z - hit_latest.transform.position.z)); if(x_value == 1){ x_value = (int)(Mathf.Abs(hit_latest2.transform.position.x - hit_latest.transform.position.x)/(hit_latest2.transform.position.x - hit_latest.transform.position.x)); } if(z_value == 1){ z_value = (int)(Mathf.Abs(hit_latest2.transform.position.z - hit_latest.transform.position.z)/(hit_latest2.transform.position.z - hit_latest.transform.position.z)); } Debug.Log("x_value " + x_value + " z_value " + z_value); if(distance == 1){ if(game_controller.boardMatrix[hit_latest2_row,hit_latest2_column] == 0){ // If selected cell is empty, move to that cell Debug.Log("boardMatrix["+hit_latest_row+","+hit_latest_column+"] = " + game_controller.boardMatrix[hit_latest_row,hit_latest_column] + " moving to empty cell " + "boardMatrix["+hit_latest2_row+","+hit_latest2_column+"] = " + game_controller.boardMatrix[hit_latest2_row,hit_latest2_column]); game_controller.boardMatrix[hit_latest2_row,hit_latest2_column] = game_controller.boardMatrix[hit_latest_row,hit_latest_column]; game_controller.boardMatrix[hit_latest_row,hit_latest_column] = 0; StartCoroutine(moveAnimStep(hit_latest.transform.gameObject, new Vector3((hit_latest2.transform.position.x - hit_latest.transform.position.x),0,(hit_latest2.transform.position.z - hit_latest.transform.position.z)), 1f)); Debug.Log(hit_latest.transform.gameObject.name + " moveAnimStep (" + (hit_latest2.transform.position.x - hit_latest.transform.position.x) + ",0," + (hit_latest2.transform.position.z - hit_latest.transform.position.z) +")"); glowOff(); game_controller.plastic_placed(); game_controller.changePlayer(); } else if(game_controller.boardMatrix[hit_latest2_row,hit_latest2_column] == -1){ // If selected cell is self destruction cell Debug.Log("boardMatrix["+hit_latest_row+","+hit_latest_column+"] = " + game_controller.boardMatrix[hit_latest_row,hit_latest_column] + " moving to self destruction cell " + "boardMatrix["+hit_latest2_row+","+hit_latest2_column+"] = " + game_controller.boardMatrix[hit_latest2_row,hit_latest2_column]); game_controller.boardMatrix[hit_latest_row,hit_latest_column] = 0; StartCoroutine(moveAnimStep(hit_latest.transform.gameObject, new Vector3((hit_latest2.transform.position.x - hit_latest.transform.position.x),0,(hit_latest2.transform.position.z - hit_latest.transform.position.z)), 1f)); Debug.Log(hit_latest.transform.gameObject.name + " moveAnimStep (" + (hit_latest2.transform.position.x - hit_latest.transform.position.x) + ",0," + (hit_latest2.transform.position.z - hit_latest.transform.position.z) +")"); StartCoroutine(destroyPawn(hit_latest.transform.gameObject, game_controller.playerNo)); glowOff(); game_controller.plastic_placed(); game_controller.changePlayer(); } else if(game_controller.boardMatrix[hit_latest2_row,hit_latest2_column] == 3 || game_controller.boardMatrix[hit_latest2_row,hit_latest2_column] == 7){ // If selected cell contains plastic if(game_controller.boardMatrix[hit_latest_row,hit_latest_column] == 3 || game_controller.boardMatrix[hit_latest_row,hit_latest_column] == 7){ Debug.Log("Plastic can not move plastic."); } else if(game_controller.boardMatrix[hit_latest2_row + z_value,hit_latest2_column + x_value] > 0){ Debug.Log("Cell next to plastic is not empty."); Debug.Log("boardMatrix[" + (hit_latest2_row + z_value) + "," + (hit_latest2_column + x_value) + "] = " + game_controller.boardMatrix[hit_latest_row + z_value,hit_latest_column + x_value]); } else { Debug.Log("Cell next to plastic is empty. Plastic gets pushed."); push_pawn(hit_latest_row + z_value, hit_latest_column + x_value, z_value, x_value); push_pawn(hit_latest_row, hit_latest_column, z_value, x_value); glowOff(); game_controller.plastic_placed(); game_controller.changePlayer(); } } else if(game_controller.boardMatrix[hit_latest2_row,hit_latest2_column] > 0f){ // If selected cell contains some pawn other than plastic bool plastic_blocks = false; Debug.Log("Move checking " + game_controller.boardMatrix[hit_latest2_row,hit_latest2_column]); int i = 1; //Debug.Log("x_value = " + x_value + " z_value = " + z_value); while(game_controller.boardMatrix[hit_latest_row + i*z_value,hit_latest_column + i*x_value] > 0){ //Debug.Log("Checking " + game_controller.boardMatrix[hit_latest_row + i*z_value,hit_latest_column + i*x_value]); // Check if plastic exists in the path if(game_controller.boardMatrix[hit_latest_row + i*z_value,hit_latest_column + i*x_value] == 3 || game_controller.boardMatrix[hit_latest_row + i*z_value,hit_latest_column + i*x_value] == 7){ plastic_blocks = true; } i += 1; } if(plastic_blocks){ Debug.Log("Plastic blocked the desired movement."); move_analysis.learning_modifier ("plastic_blocks", game_controller.playerNo); } else { for(;i>0;i--){ push_pawn(hit_latest_row + (i-1)*z_value, hit_latest_column + (i-1)*x_value, z_value, x_value); } Debug.Log("Pushing all the pawns in the path."); glowOff(); game_controller.plastic_placed(); game_controller.changePlayer(); } } } } } } // given matrix(x,y) position and direction to move, push polarized iron pawn in a specific direction using all rules int move_or_push_pawn(int row_num,int col_num,int z,int x){ RaycastHit hit_latest, hit_latest2; Physics.Raycast( new Vector3 (col_num - 0.5f, 5f, row_num - 2.5f), Vector3.down,out hit_latest,Mathf.Infinity); Physics.Raycast( new Vector3 (col_num + x - 0.5f, 5f, row_num + z - 2.5f), Vector3.down,out hit_latest2,Mathf.Infinity); int hit_latest2_row = row_num + z; int hit_latest2_column = col_num + x; int hit_latest_row = row_num; int hit_latest_column = col_num; int x_value = x; int z_value = z; int change_player = 0; if(game_controller.boardMatrix[hit_latest2_row,hit_latest2_column] == 0){ // If selected cell is empty, move to that cell Debug.Log("boardMatrix["+hit_latest_row+","+hit_latest_column+"] = " + game_controller.boardMatrix[hit_latest_row,hit_latest_column] + " moving to empty cell " + "boardMatrix["+hit_latest2_row+","+hit_latest2_column+"] = " + game_controller.boardMatrix[hit_latest2_row,hit_latest2_column]); game_controller.boardMatrix[hit_latest2_row,hit_latest2_column] = game_controller.boardMatrix[hit_latest_row,hit_latest_column]; game_controller.boardMatrix[hit_latest_row,hit_latest_column] = 0; StartCoroutine(moveAnimStep(hit_latest.transform.gameObject, new Vector3((hit_latest2.transform.position.x - hit_latest.transform.position.x),0,(hit_latest2.transform.position.z - hit_latest.transform.position.z)), 1f)); Debug.Log(hit_latest.transform.gameObject.name + " moveAnimStep (" + (hit_latest2.transform.position.x - hit_latest.transform.position.x) + ",0," + (hit_latest2.transform.position.z - hit_latest.transform.position.z) +")"); //game_controller.changePlayer(); change_player = 1; } else if(game_controller.boardMatrix[hit_latest2_row,hit_latest2_column] == -1){ // If selected cell is self destruction cell Debug.Log("boardMatrix["+hit_latest_row+","+hit_latest_column+"] = " + game_controller.boardMatrix[hit_latest_row,hit_latest_column] + " moving to self destruction cell " + "boardMatrix["+hit_latest2_row+","+hit_latest2_column+"] = " + game_controller.boardMatrix[hit_latest2_row,hit_latest2_column]); game_controller.boardMatrix[hit_latest_row,hit_latest_column] = 0; StartCoroutine(moveAnimStep(hit_latest.transform.gameObject, new Vector3((hit_latest2.transform.position.x - hit_latest.transform.position.x),0,(hit_latest2.transform.position.z - hit_latest.transform.position.z)), 1f)); Debug.Log(hit_latest.transform.gameObject.name + " moveAnimStep (" + (hit_latest2.transform.position.x - hit_latest.transform.position.x) + ",0," + (hit_latest2.transform.position.z - hit_latest.transform.position.z) +")"); StartCoroutine(destroyPawn(hit_latest.transform.gameObject, game_controller.playerNo)); //game_controller.changePlayer(); change_player = 1; } else if(game_controller.boardMatrix[hit_latest2_row,hit_latest2_column] == 3 || game_controller.boardMatrix[hit_latest2_row,hit_latest2_column] == 7){ // If selected cell contains plastic if(game_controller.boardMatrix[hit_latest_row,hit_latest_column] == 3 || game_controller.boardMatrix[hit_latest_row,hit_latest_column] == 7){ Debug.Log("Plastic can not move plastic."); } else if(game_controller.boardMatrix[hit_latest2_row + z_value,hit_latest2_column + x_value] > 0){ Debug.Log("Cell next to plastic is not empty."); Debug.Log("boardMatrix[" + (hit_latest2_row + z_value) + "," + (hit_latest2_column + x_value) + "] = " + game_controller.boardMatrix[hit_latest_row + z_value,hit_latest_column + x_value]); } else { Debug.Log("Cell next to plastic is empty. Plastic gets pushed."); push_pawn(hit_latest_row + z_value, hit_latest_column + x_value, z_value, x_value); push_pawn(hit_latest_row, hit_latest_column, z_value, x_value); //game_controller.changePlayer(); change_player = 1; } } else if(game_controller.boardMatrix[hit_latest2_row,hit_latest2_column] > 0f){ // If selected cell contains some pawn other than plastic bool plastic_blocks = false; Debug.Log("Move checking " + game_controller.boardMatrix[hit_latest2_row,hit_latest2_column]); int i = 1; //Debug.Log("x_value = " + x_value + " z_value = " + z_value); while(game_controller.boardMatrix[hit_latest_row + i*z_value,hit_latest_column + i*x_value] > 0){ //Debug.Log("Checking " + game_controller.boardMatrix[hit_latest_row + i*z_value,hit_latest_column + i*x_value]); // Check if plastic exists in the path if(game_controller.boardMatrix[hit_latest_row + i*z_value,hit_latest_column + i*x_value] == 3 || game_controller.boardMatrix[hit_latest_row + i*z_value,hit_latest_column + i*x_value] == 7){ plastic_blocks = true; } i += 1; } if(plastic_blocks){ Debug.Log("Plastic blocked the desired movement."); } else { for(;i>0;i--){ push_pawn(hit_latest_row + (i-1)*z_value, hit_latest_column + (i-1)*x_value, z_value, x_value); } Debug.Log("Pushing all the pawns in the path."); //game_controller.changePlayer(); change_player = 1; } } return change_player; } // Basic function: Pushes that (single) pawn of selected row and column using z and x as unit directions void push_pawn(int row_num,int col_num,int z,int x){ RaycastHit temp_hit; Physics.Raycast( new Vector3 (col_num - 0.5f, 5f, row_num - 2.5f), Vector3.down,out temp_hit,Mathf.Infinity); if(game_controller.boardMatrix[row_num + z, col_num + x] == 0){ game_controller.boardMatrix[row_num + z, col_num + x] = game_controller.boardMatrix[row_num, col_num]; game_controller.boardMatrix[row_num, col_num] = 0; StartCoroutine(moveAnimStep(temp_hit.transform.gameObject, new Vector3(x,0,z), 1f)); } else if(game_controller.boardMatrix[row_num + z, col_num + x] == -1){ game_controller.boardMatrix[row_num, col_num] = 0; StartCoroutine(moveAnimStep(temp_hit.transform.gameObject, new Vector3(x,0,z), 1f)); StartCoroutine(destroyPawn(temp_hit.transform.gameObject, game_controller.playerNo)); } } // Swap the pawn of selected row and column using z and x as unit directions void swap_pawn(int row_num,int col_num,int z,int x){ RaycastHit temp_hit, temp_hit2; Physics.Raycast( new Vector3 (col_num - 0.5f, 5f, row_num - 2.5f), Vector3.down,out temp_hit,Mathf.Infinity); Physics.Raycast( new Vector3 (col_num + x - 0.5f, 5f, row_num + z - 2.5f), Vector3.down,out temp_hit2,Mathf.Infinity); if(game_controller.boardMatrix[row_num + z, col_num + x] == 1){ game_controller.boardMatrix[row_num + z, col_num + x] = 2; game_controller.boardMatrix[row_num, col_num] = 1; StartCoroutine(moveAnimStep(temp_hit.transform.gameObject, new Vector3(x,0,z), 1f)); StartCoroutine(moveAnimStep(temp_hit2.transform.gameObject, new Vector3(-x,0,-z), 1f)); } else if(game_controller.boardMatrix[row_num + z, col_num + x] == 2){ game_controller.boardMatrix [row_num + z, col_num + x] = 1; game_controller.boardMatrix[row_num, col_num] = 2; StartCoroutine(moveAnimStep(temp_hit.transform.gameObject, new Vector3(x,0,z), 1f)); StartCoroutine(moveAnimStep(temp_hit2.transform.gameObject, new Vector3(-x,0,-z), 1f)); } else if(game_controller.boardMatrix[row_num + z, col_num + x] == 5){ game_controller.boardMatrix[row_num + z, col_num + x] = 6; game_controller.boardMatrix[row_num, col_num] = 5; StartCoroutine(moveAnimStep(temp_hit.transform.gameObject, new Vector3(x,0,z), 1f)); StartCoroutine(moveAnimStep(temp_hit2.transform.gameObject, new Vector3(-x,0,-z), 1f)); } else if(game_controller.boardMatrix[row_num + z, col_num + x] == 6){ game_controller.boardMatrix[row_num + z, col_num + x] = 5; game_controller.boardMatrix[row_num, col_num] = 6; StartCoroutine(moveAnimStep(temp_hit.transform.gameObject, new Vector3(x,0,z), 1f)); StartCoroutine(moveAnimStep(temp_hit2.transform.gameObject, new Vector3(-x,0,-z), 1f)); } } public void glowOn(int i){ GameObject go = GameObject.Find("GlowGlass" + i); go.GetComponent<Renderer>().material = glow_neon_mat; } // Red Glow shows positions where self destruction occurs public void redGlowOn(int i){ GameObject go = GameObject.Find("GlowGlass-" + i); go.GetComponent<Renderer>().material = glow_red_mat; if(i == 1|| i == 6 || i == 31 || i == 36){ GameObject go2 = GameObject.Find("GlowGlass-" + i + "(1)"); go2.GetComponent<Renderer>().material = glow_red_mat; } } public void glowOff(){ for(int i = 1; i <= 36; i++){ GameObject go = GameObject.Find("GlowGlass" + i); go.GetComponent<Renderer>().material = glass_mat; } for(int i = -1; i >= -6; i--){ GameObject go = GameObject.Find("GlowGlass" + i); go.GetComponent<Renderer>().material = glass_mat; } for(int i = -31; i >= -36; i--){ GameObject go = GameObject.Find("GlowGlass" + i); go.GetComponent<Renderer>().material = glass_mat; } for(int i = 1; i <= 36; i++){ if(i%6 == 0 || i%6 == 1){ GameObject go = GameObject.Find("GlowGlass-" + i); go.GetComponent<Renderer>().material = glass_mat; } if(i == 1|| i == 6 || i == 31 || i == 36){ GameObject go = GameObject.Find("GlowGlass-" + i +"(1)"); go.GetComponent<Renderer>().material = glass_mat; } } // destroy polarizationAnim s if (GetComponent<game_controller> ().polarization_rule_on) { foreach(GameObject go in GameObject.FindGameObjectsWithTag("polarizationAnimTag")){ StartCoroutine(waitNDestroy (go, 0.25f)); } } } IEnumerator moveAnimStep(GameObject gameObject, Vector3 v, float time){ float t = 0f; Vector3 vectorStart = gameObject.transform.position; moving_sound.Play(); while (t < time) { t += Time.deltaTime; // Sweeps from 0 to time in seconds gameObject.transform.position = Vector3.Lerp(vectorStart, vectorStart + v, t); yield return null; // Leave the routine and return here in the next frame } } IEnumerator waitNDestroy(GameObject gameObject, float time){ yield return new WaitForSeconds(time); Destroy(gameObject); } IEnumerator destroyPawn(GameObject gameObject, int playerNumber){ yield return new WaitForSeconds(1.05f); // this will wait > 1 seconds GameObject blastObj = Instantiate(destructionPrefab, gameObject.transform.position, Quaternion.identity) as GameObject; Destroy(gameObject); destroy_sound.Play(); Debug.Log("Player" + playerNumber + "'s " + hit_latest.transform.gameObject.name + " self destroyed."); // Check if a magnet was destroyed, then set game_ended flag + show winning animation bool magnet1_exists = false; bool iron1_exists = false; bool magnet2_exists = false; bool iron2_exists = false; for(int i=1; i<7; i++){ for(int j=1; j<7; j++){ if(game_controller.boardMatrix[i,j] == 1){ magnet1_exists = true; } if(game_controller.boardMatrix[i,j] == 2){ iron1_exists = true; } if(game_controller.boardMatrix[i,j] == 5){ magnet2_exists = true; } if(game_controller.boardMatrix[i,j] == 6){ iron2_exists = true; } } } if(!magnet2_exists){ GetComponent<game_controller>().playerWon(1, 1); game_controller.game_ended = true; } if(!magnet1_exists){ GetComponent<game_controller>().playerWon(1, 2); game_controller.game_ended = true; } if(!iron2_exists){ GetComponent<game_controller>().playerWon(2, 1); game_controller.game_ended = true; } if(!iron1_exists){ GetComponent<game_controller>().playerWon(2, 2); game_controller.game_ended = true; } // Wait 2 seconds, then destroy the Explosion Prefab yield return new WaitForSeconds(5f); Destroy(blastObj); } }
using Lucene.Net.Diagnostics; using Lucene.Net.Documents; using NUnit.Framework; using Assert = Lucene.Net.TestFramework.Assert; namespace Lucene.Net.Search { /* * 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 AtomicReaderContext = Lucene.Net.Index.AtomicReaderContext; using DefaultSimilarity = Lucene.Net.Search.Similarities.DefaultSimilarity; using Directory = Lucene.Net.Store.Directory; using Document = Documents.Document; using Field = Field; using IndexReader = Lucene.Net.Index.IndexReader; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; using RandomIndexWriter = Lucene.Net.Index.RandomIndexWriter; using Term = Lucene.Net.Index.Term; /// <summary> /// this class only tests some basic functionality in CSQ, the main parts are mostly /// tested by MultiTermQuery tests, explanations seems to be tested in TestExplanations! /// </summary> [TestFixture] public class TestConstantScoreQuery : LuceneTestCase { [Test] public virtual void TestCSQ() { Query q1 = new ConstantScoreQuery(new TermQuery(new Term("a", "b"))); Query q2 = new ConstantScoreQuery(new TermQuery(new Term("a", "c"))); Query q3 = new ConstantScoreQuery(TermRangeFilter.NewStringRange("a", "b", "c", true, true)); QueryUtils.Check(q1); QueryUtils.Check(q2); QueryUtils.CheckEqual(q1, q1); QueryUtils.CheckEqual(q2, q2); QueryUtils.CheckEqual(q3, q3); QueryUtils.CheckUnequal(q1, q2); QueryUtils.CheckUnequal(q2, q3); QueryUtils.CheckUnequal(q1, q3); QueryUtils.CheckUnequal(q1, new TermQuery(new Term("a", "b"))); } private void CheckHits(IndexSearcher searcher, Query q, float expectedScore, string scorerClassName, string innerScorerClassName) { int[] count = new int[1]; searcher.Search(q, new CollectorAnonymousClass(this, expectedScore, scorerClassName, innerScorerClassName, count)); Assert.AreEqual(1, count[0], "invalid number of results"); } private class CollectorAnonymousClass : ICollector { private readonly TestConstantScoreQuery outerInstance; private readonly float expectedScore; private readonly string scorerClassName; private readonly string innerScorerClassName; private readonly int[] count; public CollectorAnonymousClass(TestConstantScoreQuery outerInstance, float expectedScore, string scorerClassName, string innerScorerClassName, int[] count) { this.outerInstance = outerInstance; this.expectedScore = expectedScore; this.scorerClassName = scorerClassName; this.innerScorerClassName = innerScorerClassName; this.count = count; } private Scorer scorer; public virtual void SetScorer(Scorer scorer) { this.scorer = scorer; Assert.AreEqual(scorerClassName, scorer.GetType().Name, "Scorer is implemented by wrong class"); if (innerScorerClassName != null && scorer is ConstantScoreQuery.ConstantScorer) { ConstantScoreQuery.ConstantScorer innerScorer = (ConstantScoreQuery.ConstantScorer)scorer; Assert.AreEqual(innerScorerClassName, innerScorer.docIdSetIterator.GetType().Name, "inner Scorer is implemented by wrong class"); } } public virtual void Collect(int doc) { Assert.AreEqual(expectedScore, this.scorer.GetScore(), 0, "Score differs from expected"); count[0]++; } public virtual void SetNextReader(AtomicReaderContext context) { } public virtual bool AcceptsDocsOutOfOrder => true; } [Test] public virtual void TestWrapped2Times() { Directory directory = null; IndexReader reader = null; IndexSearcher searcher = null; try { directory = NewDirectory(); RandomIndexWriter writer = new RandomIndexWriter( #if FEATURE_INSTANCE_TESTDATA_INITIALIZATION this, #endif Random, directory); Document doc = new Document(); doc.Add(NewStringField("field", "term", Field.Store.NO)); writer.AddDocument(doc); reader = writer.GetReader(); writer.Dispose(); // we don't wrap with AssertingIndexSearcher in order to have the original scorer in setScorer. searcher = NewSearcher(reader, true, false); // set a similarity that does not normalize our boost away searcher.Similarity = new DefaultSimilarityAnonymousClass(this); Query csq1 = new ConstantScoreQuery(new TermQuery(new Term("field", "term"))); csq1.Boost = 2.0f; Query csq2 = new ConstantScoreQuery(csq1); csq2.Boost = 5.0f; BooleanQuery bq = new BooleanQuery(); bq.Add(csq1, Occur.SHOULD); bq.Add(csq2, Occur.SHOULD); Query csqbq = new ConstantScoreQuery(bq); csqbq.Boost = 17.0f; CheckHits(searcher, csq1, csq1.Boost, typeof(ConstantScoreQuery.ConstantScorer).Name, null); CheckHits(searcher, csq2, csq2.Boost, typeof(ConstantScoreQuery.ConstantScorer).Name, typeof(ConstantScoreQuery.ConstantScorer).Name); // for the combined BQ, the scorer should always be BooleanScorer's BucketScorer, because our scorer supports out-of order collection! string bucketScorerClass = typeof(FakeScorer).Name; CheckHits(searcher, bq, csq1.Boost + csq2.Boost, bucketScorerClass, null); CheckHits(searcher, csqbq, csqbq.Boost, typeof(ConstantScoreQuery.ConstantScorer).Name, bucketScorerClass); } finally { if (reader != null) { reader.Dispose(); } if (directory != null) { directory.Dispose(); } } } private class DefaultSimilarityAnonymousClass : DefaultSimilarity { private readonly TestConstantScoreQuery outerInstance; public DefaultSimilarityAnonymousClass(TestConstantScoreQuery outerInstance) { this.outerInstance = outerInstance; } public override float QueryNorm(float sumOfSquaredWeights) { return 1.0f; } } [Test] public virtual void TestConstantScoreQueryAndFilter() { Directory d = NewDirectory(); RandomIndexWriter w = new RandomIndexWriter( #if FEATURE_INSTANCE_TESTDATA_INITIALIZATION this, #endif Random, d); Document doc = new Document(); doc.Add(NewStringField("field", "a", Field.Store.NO)); w.AddDocument(doc); doc = new Document(); doc.Add(NewStringField("field", "b", Field.Store.NO)); w.AddDocument(doc); IndexReader r = w.GetReader(); w.Dispose(); Filter filterB = new CachingWrapperFilter(new QueryWrapperFilter(new TermQuery(new Term("field", "b")))); Query query = new ConstantScoreQuery(filterB); IndexSearcher s = NewSearcher(r); Assert.AreEqual(1, s.Search(query, filterB, 1).TotalHits); // Query for field:b, Filter field:b Filter filterA = new CachingWrapperFilter(new QueryWrapperFilter(new TermQuery(new Term("field", "a")))); query = new ConstantScoreQuery(filterA); Assert.AreEqual(0, s.Search(query, filterB, 1).TotalHits); // Query field:b, Filter field:a r.Dispose(); d.Dispose(); } // LUCENE-5307 // don't reuse the scorer of filters since they have been created with bulkScorer=false [Test] public virtual void TestQueryWrapperFilter() { Directory d = NewDirectory(); RandomIndexWriter w = new RandomIndexWriter( #if FEATURE_INSTANCE_TESTDATA_INITIALIZATION this, #endif Random, d); Document doc = new Document(); doc.Add(NewStringField("field", "a", Field.Store.NO)); w.AddDocument(doc); IndexReader r = w.GetReader(); w.Dispose(); Filter filter = new QueryWrapperFilter(AssertingQuery.Wrap(Random, new TermQuery(new Term("field", "a")))); IndexSearcher s = NewSearcher(r); if (Debugging.AssertsEnabled) Debugging.Assert(s is AssertingIndexSearcher); // this used to fail s.Search(new ConstantScoreQuery(filter), new TotalHitCountCollector()); // check the rewrite Query rewritten = (new ConstantScoreQuery(filter)).Rewrite(r); Assert.IsTrue(rewritten is ConstantScoreQuery); Assert.IsTrue(((ConstantScoreQuery)rewritten).Query is AssertingQuery); r.Dispose(); d.Dispose(); } } }
using System; using System.Collections.Generic; using System.Reflection; using System.Xml; using System.Threading; using OpenMetaverse; using OpenMetaverse.Packets; namespace OpenMetaverse.TestClient { public class LoginDetails { public string FirstName; public string LastName; public string Password; public string StartLocation; public bool GroupCommands; public string MasterName; public UUID MasterKey; public string URI; } public class StartPosition { public string sim; public int x; public int y; public int z; public StartPosition() { this.sim = null; this.x = 0; this.y = 0; this.z = 0; } } public sealed class ClientManager { const string VERSION = "1.0.0"; class Singleton { internal static readonly ClientManager Instance = new ClientManager(); } public static ClientManager Instance { get { return Singleton.Instance; } } public Dictionary<UUID, TestClient> Clients = new Dictionary<UUID, TestClient>(); public Dictionary<Simulator, Dictionary<uint, Primitive>> SimPrims = new Dictionary<Simulator, Dictionary<uint, Primitive>>(); public bool Running = true; public bool GetTextures = false; public volatile int PendingLogins = 0; public string onlyAvatar = String.Empty; ClientManager() { } public void Start(List<LoginDetails> accounts, bool getTextures) { GetTextures = getTextures; foreach (LoginDetails account in accounts) Login(account); } public TestClient Login(string[] args) { if (args.Length < 3) { Console.WriteLine("Usage: login firstname lastname password [simname] [login server url]"); return null; } LoginDetails account = new LoginDetails(); account.FirstName = args[0]; account.LastName = args[1]; account.Password = args[2]; if (args.Length > 3) { // If it looks like a full starting position was specified, parse it if (args[3].StartsWith("http")) { account.URI = args[3]; } else { if (args[3].IndexOf('/') >= 0) { char sep = '/'; string[] startbits = args[3].Split(sep); try { account.StartLocation = NetworkManager.StartLocation(startbits[0], Int32.Parse(startbits[1]), Int32.Parse(startbits[2]), Int32.Parse(startbits[3])); } catch (FormatException) { } } // Otherwise, use the center of the named region if (account.StartLocation == null) account.StartLocation = NetworkManager.StartLocation(args[3], 128, 128, 40); } } if (args.Length > 4) if (args[4].StartsWith("http")) account.URI = args[4]; if (string.IsNullOrEmpty(account.URI)) account.URI = Program.LoginURI; Logger.Log("Using login URI " + account.URI, Helpers.LogLevel.Info); return Login(account); } public TestClient Login(LoginDetails account) { // Check if this client is already logged in foreach (TestClient c in Clients.Values) { if (c.Self.FirstName == account.FirstName && c.Self.LastName == account.LastName) { Logout(c); break; } } ++PendingLogins; TestClient client = new TestClient(this); client.Network.LoginProgress += delegate(object sender, LoginProgressEventArgs e) { Logger.Log(String.Format("Login {0}: {1}", e.Status, e.Message), Helpers.LogLevel.Info, client); if (e.Status == LoginStatus.Success) { Clients[client.Self.AgentID] = client; if (client.MasterKey == UUID.Zero) { UUID query = UUID.Zero; EventHandler<DirPeopleReplyEventArgs> peopleDirCallback = delegate(object sender2, DirPeopleReplyEventArgs dpe) { if (dpe.QueryID == query) { if (dpe.MatchedPeople.Count != 1) { Logger.Log("Unable to resolve master key from " + client.MasterName, Helpers.LogLevel.Warning); } else { client.MasterKey = dpe.MatchedPeople[0].AgentID; Logger.Log("Master key resolved to " + client.MasterKey, Helpers.LogLevel.Info); } } }; client.Directory.DirPeopleReply += peopleDirCallback; query = client.Directory.StartPeopleSearch(client.MasterName, 0); } Logger.Log("Logged in " + client.ToString(), Helpers.LogLevel.Info); --PendingLogins; } else if (e.Status == LoginStatus.Failed) { Logger.Log("Failed to login " + account.FirstName + " " + account.LastName + ": " + client.Network.LoginMessage, Helpers.LogLevel.Warning); --PendingLogins; } }; // Optimize the throttle client.Throttle.Wind = 0; client.Throttle.Cloud = 0; client.Throttle.Land = 1000000; client.Throttle.Task = 1000000; client.GroupCommands = account.GroupCommands; client.MasterName = account.MasterName; client.MasterKey = account.MasterKey; client.AllowObjectMaster = client.MasterKey != UUID.Zero; // Require UUID for object master. LoginParams loginParams = client.Network.DefaultLoginParams( account.FirstName, account.LastName, account.Password, "TestClient", VERSION); if (!String.IsNullOrEmpty(account.StartLocation)) loginParams.Start = account.StartLocation; if (!String.IsNullOrEmpty(account.URI)) loginParams.URI = account.URI; client.Network.BeginLogin(loginParams); return client; } /// <summary> /// /// </summary> public void Run(bool noGUI) { if (noGUI) { while (Running) { Thread.Sleep(2 * 1000); } } else { Console.WriteLine("Type quit to exit. Type help for a command list."); while (Running) { PrintPrompt(); string input = Console.ReadLine(); DoCommandAll(input, UUID.Zero); } } foreach (GridClient client in Clients.Values) { if (client.Network.Connected) client.Network.Logout(); } } private void PrintPrompt() { int online = 0; foreach (GridClient client in Clients.Values) { if (client.Network.Connected) online++; } Console.Write(online + " avatars online> "); } /// <summary> /// /// </summary> /// <param name="cmd"></param> /// <param name="fromAgentID"></param> /// <param name="imSessionID"></param> public void DoCommandAll(string cmd, UUID fromAgentID) { string[] tokens = cmd.Trim().Split(new char[] { ' ', '\t' }); if (tokens.Length == 0) return; string firstToken = tokens[0].ToLower(); if (String.IsNullOrEmpty(firstToken)) return; // Allow for comments when cmdline begins with ';' or '#' if (firstToken[0] == ';' || firstToken[0] == '#') return; if ('@' == firstToken[0]) { onlyAvatar = String.Empty; if (tokens.Length == 3) { bool found = false; onlyAvatar = tokens[1]+" "+tokens[2]; foreach (TestClient client in Clients.Values) { if ((client.ToString() == onlyAvatar) && (client.Network.Connected)) { found = true; break; } } if (found) { Logger.Log("Commanding only "+onlyAvatar+" now", Helpers.LogLevel.Info); } else { Logger.Log("Commanding nobody now. Avatar "+onlyAvatar+" is offline", Helpers.LogLevel.Info); } } else { Logger.Log("Commanding all avatars now", Helpers.LogLevel.Info); } return; } string[] args = new string[tokens.Length - 1]; if (args.Length > 0) Array.Copy(tokens, 1, args, 0, args.Length); if (firstToken == "login") { Login(args); } else if (firstToken == "quit") { Quit(); Logger.Log("All clients logged out and program finished running.", Helpers.LogLevel.Info); } else if (firstToken == "help") { if (Clients.Count > 0) { foreach (TestClient client in Clients.Values) { Console.WriteLine(client.Commands["help"].Execute(args, UUID.Zero)); break; } } else { Console.WriteLine("You must login at least one bot to use the help command"); } } else if (firstToken == "script") { // No reason to pass this to all bots, and we also want to allow it when there are no bots ScriptCommand command = new ScriptCommand(null); Logger.Log(command.Execute(args, UUID.Zero), Helpers.LogLevel.Info); } else if (firstToken == "waitforlogin") { // Special exception to allow this to run before any bots have logged in if (ClientManager.Instance.PendingLogins > 0) { WaitForLoginCommand command = new WaitForLoginCommand(null); Logger.Log(command.Execute(args, UUID.Zero), Helpers.LogLevel.Info); } else { Logger.Log("No pending logins", Helpers.LogLevel.Info); } } else { // Make an immutable copy of the Clients dictionary to safely iterate over Dictionary<UUID, TestClient> clientsCopy = new Dictionary<UUID, TestClient>(Clients); int completed = 0; foreach (TestClient client in clientsCopy.Values) { ThreadPool.QueueUserWorkItem((WaitCallback) delegate(object state) { TestClient testClient = (TestClient)state; if ((String.Empty == onlyAvatar) || (testClient.ToString() == onlyAvatar)) { if (testClient.Commands.ContainsKey(firstToken)) { string result; try { result = testClient.Commands[firstToken].Execute(args, fromAgentID); Logger.Log(result, Helpers.LogLevel.Info, testClient); } catch(Exception e) { Logger.Log(String.Format("{0} raised exception {1}", firstToken, e), Helpers.LogLevel.Error, testClient); } } else Logger.Log("Unknown command " + firstToken, Helpers.LogLevel.Warning); } ++completed; }, client); } while (completed < clientsCopy.Count) Thread.Sleep(50); } } /// <summary> /// /// </summary> /// <param name="client"></param> public void Logout(TestClient client) { Clients.Remove(client.Self.AgentID); client.Network.Logout(); } /// <summary> /// /// </summary> public void Quit() { Running = false; // TODO: It would be really nice if we could figure out a way to abort the ReadLine here in so that Run() will exit. } } }
using System; using System.Runtime.InteropServices; using System.Collections; namespace ASCOM.NexStar { #region C# Definition of IClassFactory // // Provide a definition of theCOM IClassFactory interface. // [ ComImport, // This interface originated from COM. ComVisible(false), // Must not be exposed to COM!!! InterfaceType(ComInterfaceType.InterfaceIsIUnknown), // Indicate that this interface is not IDispatch-based. Guid("00000001-0000-0000-C000-000000000046") // This GUID is the actual GUID of IClassFactory. ] public interface IClassFactory { void CreateInstance(IntPtr pUnkOuter, ref Guid riid, out IntPtr ppvObject); void LockServer(bool fLock); } #endregion // // Universal ClassFactory. Given a type as a parameter of the // constructor, it implements IClassFactory for any interface // that the class implements. Magic!!! // public class ClassFactory : IClassFactory { #region Access to ole32.dll functions for class factories // Define two common GUID objects for public usage. public static Guid IID_IUnknown = new Guid("{00000000-0000-0000-C000-000000000046}"); public static Guid IID_IDispatch = new Guid("{00020400-0000-0000-C000-000000000046}"); [Flags] enum CLSCTX : uint { CLSCTX_INPROC_SERVER = 0x1, CLSCTX_INPROC_HANDLER = 0x2, CLSCTX_LOCAL_SERVER = 0x4, CLSCTX_INPROC_SERVER16 = 0x8, CLSCTX_REMOTE_SERVER = 0x10, CLSCTX_INPROC_HANDLER16 = 0x20, CLSCTX_RESERVED1 = 0x40, CLSCTX_RESERVED2 = 0x80, CLSCTX_RESERVED3 = 0x100, CLSCTX_RESERVED4 = 0x200, CLSCTX_NO_CODE_DOWNLOAD = 0x400, CLSCTX_RESERVED5 = 0x800, CLSCTX_NO_CUSTOM_MARSHAL = 0x1000, CLSCTX_ENABLE_CODE_DOWNLOAD = 0x2000, CLSCTX_NO_FAILURE_LOG = 0x4000, CLSCTX_DISABLE_AAA = 0x8000, CLSCTX_ENABLE_AAA = 0x10000, CLSCTX_FROM_DEFAULT_CONTEXT = 0x20000, CLSCTX_INPROC = CLSCTX_INPROC_SERVER | CLSCTX_INPROC_HANDLER, CLSCTX_SERVER = CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER | CLSCTX_REMOTE_SERVER, CLSCTX_ALL = CLSCTX_SERVER | CLSCTX_INPROC_HANDLER } [Flags] enum REGCLS : uint { REGCLS_SINGLEUSE = 0, REGCLS_MULTIPLEUSE = 1, REGCLS_MULTI_SEPARATE = 2, REGCLS_SUSPENDED = 4, REGCLS_SURROGATE = 8 } // // CoRegisterClassObject() is used to register a Class Factory // into COM's internal table of Class Factories. // [DllImport("ole32.dll")] static extern int CoRegisterClassObject( [In] ref Guid rclsid, [MarshalAs(UnmanagedType.IUnknown)] object pUnk, uint dwClsContext, uint flags, out uint lpdwRegister); // // Called by a COM EXE Server that can register multiple class objects // to inform COM about all registered classes, and permits activation // requests for those class objects. // This function causes OLE to inform the SCM about all the registered // classes, and begins letting activation requests into the server process. // [DllImport("ole32.dll")] static extern int CoResumeClassObjects(); // // Prevents any new activation requests from the SCM on all class objects // registered within the process. Even though a process may call this API, // the process still must call CoRevokeClassObject for each CLSID it has // registered, in the apartment it registered in. // [DllImport("ole32.dll")] static extern int CoSuspendClassObjects(); // // CoRevokeClassObject() is used to unregister a Class Factory // from COM's internal table of Class Factories. // [DllImport("ole32.dll")] static extern int CoRevokeClassObject(uint dwRegister); #endregion #region Constructor and Private ClassFactory Data protected Type m_ClassType; protected Guid m_ClassId; protected ArrayList m_InterfaceTypes; protected uint m_ClassContext; protected uint m_Flags; protected UInt32 m_locked = 0; protected uint m_Cookie; protected string m_progid; public ClassFactory(Type type) { if (type == null) throw new ArgumentNullException("type"); m_ClassType = type; //PWGS Get the ProgID from the MetaData m_progid = Marshal.GenerateProgIdForType(type); m_ClassId = Marshal.GenerateGuidForType(type); // Should be nailed down by [Guid(...)] m_ClassContext = (uint)CLSCTX.CLSCTX_LOCAL_SERVER; // Default m_Flags = (uint)REGCLS.REGCLS_MULTIPLEUSE | // Default (uint)REGCLS.REGCLS_SUSPENDED; m_InterfaceTypes = new ArrayList(); foreach (Type T in type.GetInterfaces()) // Save all of the implemented interfaces m_InterfaceTypes.Add(T); } #endregion #region Common ClassFactory Methods public uint ClassContext { get { return m_ClassContext; } set { m_ClassContext = value; } } public Guid ClassId { get { return m_ClassId; } set { m_ClassId = value; } } public uint Flags { get { return m_Flags; } set { m_Flags = value; } } public bool RegisterClassObject() { // Register the class factory int i = CoRegisterClassObject ( ref m_ClassId, this, m_ClassContext, m_Flags, out m_Cookie ); return (i == 0); } public bool RevokeClassObject() { int i = CoRevokeClassObject(m_Cookie); return (i == 0); } public static bool ResumeClassObjects() { int i = CoResumeClassObjects(); return (i == 0); } public static bool SuspendClassObjects() { int i = CoSuspendClassObjects(); return (i == 0); } #endregion #region IClassFactory Implementations // // Implement creation of the type and interface. // void IClassFactory.CreateInstance(IntPtr pUnkOuter, ref Guid riid, out IntPtr ppvObject) { IntPtr nullPtr = new IntPtr(0); ppvObject = nullPtr; // // Handle specific requests for implemented interfaces // foreach (Type iType in m_InterfaceTypes) { if (riid == Marshal.GenerateGuidForType(iType)) { ppvObject = Marshal.GetComInterfaceForObject(Activator.CreateInstance(m_ClassType), iType); return; } } // // Handle requests for IDispatch or IUnknown on the class // if (riid == IID_IDispatch) { ppvObject = Marshal.GetIDispatchForObject(Activator.CreateInstance(m_ClassType)); return; } else if (riid == IID_IUnknown) { ppvObject = Marshal.GetIUnknownForObject(Activator.CreateInstance(m_ClassType)); } else { // // Oops, some interface that the class doesn't implement // throw new COMException("No interface", unchecked((int)0x80004002)); } } void IClassFactory.LockServer(bool bLock) { if (bLock) Server.CountLock(); else Server.UncountLock(); // Always attempt to see if we need to shutdown this server application. Server.ExitIf(); } #endregion } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // // <OWNER>[....]</OWNER> /*============================================================ ** ** Class: SynchronizationContext ** ** ** Purpose: Capture synchronization semantics for asynchronous callbacks ** ** ===========================================================*/ namespace System.Threading { #if !MONO using Microsoft.Win32.SafeHandles; #endif using System.Security.Permissions; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; #if FEATURE_CORRUPTING_EXCEPTIONS using System.Runtime.ExceptionServices; #endif // FEATURE_CORRUPTING_EXCEPTIONS using System.Runtime; using System.Runtime.Versioning; using System.Runtime.ConstrainedExecution; using System.Reflection; using System.Security; using System.Diagnostics.Contracts; using System.Diagnostics.CodeAnalysis; #if FEATURE_SYNCHRONIZATIONCONTEXT_WAIT [Flags] enum SynchronizationContextProperties { None = 0, RequireWaitNotification = 0x1 }; #endif #if FEATURE_COMINTEROP && FEATURE_APPX // // This is implemented in System.Runtime.WindowsRuntime, allowing us to ask that assembly for a WinRT-specific SyncCtx. // I'd like this to be an interface, or at least an abstract class - but neither seems to play nice with FriendAccessAllowed. // [FriendAccessAllowed] [SecurityCritical] internal class WinRTSynchronizationContextFactoryBase { [SecurityCritical] public virtual SynchronizationContext Create(object coreDispatcher) {return null;} } #endif //FEATURE_COMINTEROP #if !FEATURE_CORECLR [SecurityPermissionAttribute(SecurityAction.InheritanceDemand, Flags =SecurityPermissionFlag.ControlPolicy|SecurityPermissionFlag.ControlEvidence)] #endif public class SynchronizationContext { #if FEATURE_SYNCHRONIZATIONCONTEXT_WAIT SynchronizationContextProperties _props = SynchronizationContextProperties.None; #endif public SynchronizationContext() { } #if FEATURE_SYNCHRONIZATIONCONTEXT_WAIT static Type s_cachedPreparedType1; static Type s_cachedPreparedType2; static Type s_cachedPreparedType3; static Type s_cachedPreparedType4; static Type s_cachedPreparedType5; // protected so that only the derived [....] context class can enable these flags [System.Security.SecuritySafeCritical] // auto-generated [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "We never dereference s_cachedPreparedType*, so ordering is unimportant")] protected void SetWaitNotificationRequired() { // // Prepare the method so that it can be called in a reliable fashion when a wait is needed. // This will obviously only make the Wait reliable if the Wait method is itself reliable. The only thing // preparing the method here does is to ensure there is no failure point before the method execution begins. // // Preparing the method in this way is quite expensive, but only needs to be done once per type, per AppDomain. // So we keep track of a few types we've already prepared in this AD. It is uncommon to have more than // a few SynchronizationContext implementations, so we only cache the first five we encounter; this lets // our cache be much faster than a more general cache might be. This is important, because this // is a *very* hot code path for many WPF and [....] apps. // Type type = this.GetType(); if (s_cachedPreparedType1 != type && s_cachedPreparedType2 != type && s_cachedPreparedType3 != type && s_cachedPreparedType4 != type && s_cachedPreparedType5 != type) { RuntimeHelpers.PrepareDelegate(new WaitDelegate(this.Wait)); if (s_cachedPreparedType1 == null) s_cachedPreparedType1 = type; else if (s_cachedPreparedType2 == null) s_cachedPreparedType2 = type; else if (s_cachedPreparedType3 == null) s_cachedPreparedType3 = type; else if (s_cachedPreparedType4 == null) s_cachedPreparedType4 = type; else if (s_cachedPreparedType5 == null) s_cachedPreparedType5 = type; } _props |= SynchronizationContextProperties.RequireWaitNotification; } public bool IsWaitNotificationRequired() { return ((_props & SynchronizationContextProperties.RequireWaitNotification) != 0); } #endif public virtual void Send(SendOrPostCallback d, Object state) { d(state); } public virtual void Post(SendOrPostCallback d, Object state) { ThreadPool.QueueUserWorkItem(new WaitCallback(d), state); } /// <summary> /// Optional override for subclasses, for responding to notification that operation is starting. /// </summary> public virtual void OperationStarted() { } /// <summary> /// Optional override for subclasses, for responding to notification that operation has completed. /// </summary> public virtual void OperationCompleted() { } #if FEATURE_SYNCHRONIZATIONCONTEXT_WAIT // Method called when the CLR does a wait operation [System.Security.SecurityCritical] // auto-generated_required [CLSCompliant(false)] [PrePrepareMethod] public virtual int Wait(IntPtr[] waitHandles, bool waitAll, int millisecondsTimeout) { if (waitHandles == null) { throw new ArgumentNullException("waitHandles"); } Contract.EndContractBlock(); return WaitHelper(waitHandles, waitAll, millisecondsTimeout); } // Static helper to which the above method can delegate to in order to get the default // COM behavior. [System.Security.SecurityCritical] // auto-generated_required [CLSCompliant(false)] [PrePrepareMethod] [ResourceExposure(ResourceScope.None)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #if MONO protected static int WaitHelper(IntPtr[] waitHandles, bool waitAll, int millisecondsTimeout) { throw new NotImplementedException (); } #else [MethodImplAttribute(MethodImplOptions.InternalCall)] protected static extern int WaitHelper(IntPtr[] waitHandles, bool waitAll, int millisecondsTimeout); #endif #endif // set SynchronizationContext on the current thread [System.Security.SecurityCritical] // auto-generated_required #if !FEATURE_CORECLR [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] #endif public static void SetSynchronizationContext(SynchronizationContext syncContext) { ExecutionContext ec = Thread.CurrentThread.GetMutableExecutionContext(); ec.SynchronizationContext = syncContext; ec.SynchronizationContextNoFlow = syncContext; } #if FEATURE_CORECLR || MOBILE_LEGACY // // This is a framework-internal method for Jolt's use. The problem is that SynchronizationContexts set inside of a reverse p/invoke // into an AppDomain are not persisted in that AppDomain; the next time the same thread calls into the same AppDomain, // the [....] context will be null. For Silverlight, this means that it's impossible to persist a [....] context on the UI thread, // since Jolt is constantly transitioning in and out of each control's AppDomain on that thread. // // So for Jolt we will track a special thread-static context, which *will* persist across calls from Jolt, and if the thread does not // have a [....] context set in its execution context we'll use the thread-static context instead. // // This will break any future work that requires SynchronizationContext.Current to be in [....] with the value // stored in a thread's ExecutionContext (wait notifications being one such example). If that becomes a problem, we will // need to rework this mechanism (which is one reason it's not being exposed publically). // [ThreadStatic] private static SynchronizationContext s_threadStaticContext; #if FEATURE_LEGACYNETCF // // NetCF had a bug where SynchronizationContext.SetThreadStaticContext would set the SyncContext for every thread in the process. // This was because they stored the value in a regular static field (NetCF has no support for ThreadStatic fields). This was fixed in // Mango, but some apps built against pre-Mango WP7 do depend on the broken behavior. So for those apps we need an AppDomain-wide static // to hold whatever context was last set on any thread. // private static SynchronizationContext s_appDomainStaticContext; #endif [System.Security.SecurityCritical] #if FEATURE_LEGACYNETCF || MOBILE_LEGACY public static void SetThreadStaticContext(SynchronizationContext syncContext) #else internal static void SetThreadStaticContext(SynchronizationContext syncContext) #endif { #if FEATURE_LEGACYNETCF // // If this is a pre-Mango Windows Phone app, we need to set the SC for *all* threads to match the old NetCF behavior. // if (CompatibilitySwitches.IsAppEarlierThanWindowsPhoneMango) s_appDomainStaticContext = syncContext; else #endif s_threadStaticContext = syncContext; } #endif // Get the current SynchronizationContext on the current thread public static SynchronizationContext Current { #if !FEATURE_CORECLR [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] #endif get { return Thread.CurrentThread.GetExecutionContextReader().SynchronizationContext ?? GetThreadLocalContext(); } } // Get the last SynchronizationContext that was set explicitly (not flowed via ExecutionContext.Capture/Run) internal static SynchronizationContext CurrentNoFlow { [FriendAccessAllowed] get { return Thread.CurrentThread.GetExecutionContextReader().SynchronizationContextNoFlow ?? GetThreadLocalContext(); } } #if !FEATURE_CORECLR [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] #endif private static SynchronizationContext GetThreadLocalContext() { SynchronizationContext context = null; #if FEATURE_CORECLR #if FEATURE_LEGACYNETCF if (CompatibilitySwitches.IsAppEarlierThanWindowsPhoneMango) context = s_appDomainStaticContext; else #endif //FEATURE_LEGACYNETCF context = s_threadStaticContext; #endif //FEATURE_CORECLR #if FEATURE_APPX if (context == null && Environment.IsWinRTSupported) context = GetWinRTContext(); #endif #if MONODROID if (context == null) context = AndroidPlatform.GetDefaultSyncContext (); #endif return context; } #if FEATURE_APPX [SecuritySafeCritical] private static SynchronizationContext GetWinRTContext() { Contract.Assert(Environment.IsWinRTSupported); // Temporary hack to avoid loading a bunch of DLLs in every managed process. // This disables this feature for non-AppX processes that happen to use CoreWindow/CoreDispatcher, // which is not what we want. if (!AppDomain.IsAppXModel()) return null; // // We call into the VM to get the dispatcher. This is because: // // a) We cannot call the WinRT APIs directly from mscorlib, because we don't have the fancy projections here. // b) We cannot call into System.Runtime.WindowsRuntime here, because we don't want to load that assembly // into processes that don't need it (for performance reasons). // // So, we check the VM to see if the current thread has a dispatcher; if it does, we pass that along to // System.Runtime.WindowsRuntime to get a corresponding SynchronizationContext. // object dispatcher = GetWinRTDispatcherForCurrentThread(); if (dispatcher != null) return GetWinRTSynchronizationContextFactory().Create(dispatcher); return null; } [SecurityCritical] static WinRTSynchronizationContextFactoryBase s_winRTContextFactory; [SecurityCritical] private static WinRTSynchronizationContextFactoryBase GetWinRTSynchronizationContextFactory() { // // Since we can't directly reference System.Runtime.WindowsRuntime from mscorlib, we have to get the factory via reflection. // It would be better if we could just implement WinRTSynchronizationContextFactory in mscorlib, but we can't, because // we can do very little with WinRT stuff in mscorlib. // WinRTSynchronizationContextFactoryBase factory = s_winRTContextFactory; if (factory == null) { Type factoryType = Type.GetType("System.Threading.WinRTSynchronizationContextFactory, " + AssemblyRef.SystemRuntimeWindowsRuntime, true); s_winRTContextFactory = factory = (WinRTSynchronizationContextFactoryBase)Activator.CreateInstance(factoryType, true); } return factory; } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SecurityCritical] [ResourceExposure(ResourceScope.None)] [SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Interface)] private static extern object GetWinRTDispatcherForCurrentThread(); #endif //FEATURE_APPX // helper to Clone this SynchronizationContext, public virtual SynchronizationContext CreateCopy() { // the CLR dummy has an empty clone function - no member data return new SynchronizationContext(); } #if FEATURE_SYNCHRONIZATIONCONTEXT_WAIT [System.Security.SecurityCritical] // auto-generated private static int InvokeWaitMethodHelper(SynchronizationContext syncContext, IntPtr[] waitHandles, bool waitAll, int millisecondsTimeout) { return syncContext.Wait(waitHandles, waitAll, millisecondsTimeout); } #endif } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Runtime.Serialization; using System.Text.RegularExpressions; using Funq; using NUnit.Framework; using NServiceKit.Common.Web; using NServiceKit.ServiceClient.Web; using NServiceKit.FluentValidation; using NServiceKit.Service; using NServiceKit.ServiceHost; using NServiceKit.ServiceInterface; using NServiceKit.ServiceInterface.ServiceModel; using NServiceKit.ServiceInterface.Validation; using NServiceKit.Text; using NServiceKit.WebHost.Endpoints; using NServiceKit.WebHost.Endpoints.Support; using NServiceKit.WebHost.Endpoints.Tests; using NServiceKit.WebHost.Endpoints.Tests.Support; using NServiceKit.WebHost.Endpoints.Tests.Support.Host; namespace NServiceKit.WebHost.IntegrationTests.Services { /// <summary>A customers.</summary> [Route("/customers")] [Route("/customers/{Id}")] public class Customers { /// <summary>Gets or sets the identifier.</summary> /// /// <value>The identifier.</value> public int Id { get; set; } /// <summary>Gets or sets the person's first name.</summary> /// /// <value>The name of the first.</value> public string FirstName { get; set; } /// <summary>Gets or sets the person's last name.</summary> /// /// <value>The name of the last.</value> public string LastName { get; set; } /// <summary>Gets or sets the company.</summary> /// /// <value>The company.</value> public string Company { get; set; } /// <summary>Gets or sets the discount.</summary> /// /// <value>The discount.</value> public decimal Discount { get; set; } /// <summary>Gets or sets the address.</summary> /// /// <value>The address.</value> public string Address { get; set; } /// <summary>Gets or sets the postcode.</summary> /// /// <value>The postcode.</value> public string Postcode { get; set; } /// <summary>Gets or sets a value indicating whether this object has discount.</summary> /// /// <value>true if this object has discount, false if not.</value> public bool HasDiscount { get; set; } } /// <summary>Interface for address validator.</summary> public interface IAddressValidator { /// <summary>Valid address.</summary> /// /// <param name="address">The address.</param> /// /// <returns>true if it succeeds, false if it fails.</returns> bool ValidAddress(string address); } /// <summary>The address validator.</summary> public class AddressValidator : IAddressValidator { /// <summary>Valid address.</summary> /// /// <param name="address">The address.</param> /// /// <returns>true if it succeeds, false if it fails.</returns> public bool ValidAddress(string address) { return address != null && address.Length >= 20 && address.Length <= 250; } } /// <summary>The customers validator.</summary> public class CustomersValidator : AbstractValidator<Customers> { /// <summary>Gets or sets the address validator.</summary> /// /// <value>The address validator.</value> public IAddressValidator AddressValidator { get; set; } /// <summary>Initializes a new instance of the NServiceKit.WebHost.IntegrationTests.Services.CustomersValidator class.</summary> public CustomersValidator() { RuleFor(x => x.Id).NotEqual(default(int)); RuleSet(ApplyTo.Post | ApplyTo.Put, () => { RuleFor(x => x.LastName).NotEmpty().WithErrorCode("ShouldNotBeEmpty"); RuleFor(x => x.FirstName).NotEmpty().WithMessage("Please specify a first name"); RuleFor(x => x.Company).NotNull(); RuleFor(x => x.Discount).NotEqual(0).When(x => x.HasDiscount); RuleFor(x => x.Address).Must(x => AddressValidator.ValidAddress(x)); RuleFor(x => x.Postcode).Must(BeAValidPostcode).WithMessage("Please specify a valid postcode"); }); } static readonly Regex UsPostCodeRegEx = new Regex(@"^\d{5}(-\d{4})?$", RegexOptions.Compiled); private bool BeAValidPostcode(string postcode) { return !string.IsNullOrEmpty(postcode) && UsPostCodeRegEx.IsMatch(postcode); } } /// <summary>The customers response.</summary> public class CustomersResponse { /// <summary>Gets or sets the result.</summary> /// /// <value>The result.</value> public Customers Result { get; set; } /// <summary>Gets or sets the response status.</summary> /// /// <value>The response status.</value> public ResponseStatus ResponseStatus { get; set; } } /// <summary>A customer service.</summary> [DefaultRequest(typeof(Customers))] public class CustomerService : ServiceInterface.Service { /// <summary>Gets the given request.</summary> /// /// <param name="request">The request to delete.</param> /// /// <returns>An object.</returns> public object Get(Customers request) { return new CustomersResponse { Result = request }; } /// <summary>Post this message.</summary> /// /// <param name="request">The request to delete.</param> /// /// <returns>An object.</returns> public object Post(Customers request) { return new CustomersResponse { Result = request }; } /// <summary>Puts the given request.</summary> /// /// <param name="request">The request to delete.</param> /// /// <returns>An object.</returns> public object Put(Customers request) { return new CustomersResponse { Result = request }; } /// <summary>Deletes the given request.</summary> /// /// <param name="request">The request to delete.</param> /// /// <returns>An object.</returns> public object Delete(Customers request) { return new CustomersResponse { Result = request }; } } /// <summary>A customer service validation tests.</summary> [TestFixture] public class CustomerServiceValidationTests { private const string ListeningOn = "http://localhost:82/"; /// <summary>A validation application host HTTP listener.</summary> public class ValidationAppHostHttpListener : AppHostHttpListenerBase { /// <summary>Initializes a new instance of the NServiceKit.WebHost.IntegrationTests.Services.CustomerServiceValidationTests.ValidationAppHostHttpListener class.</summary> public ValidationAppHostHttpListener() : base("Validation Tests", typeof(CustomerService).Assembly) { } /// <summary>Configures the given container.</summary> /// /// <param name="container">The container.</param> public override void Configure(Container container) { Plugins.Add(new ValidationFeature()); container.Register<IAddressValidator>(new AddressValidator()); container.RegisterValidators(typeof(CustomersValidator).Assembly); } } ValidationAppHostHttpListener appHost; /// <summary>Executes the test fixture set up action.</summary> [TestFixtureSetUp] public void OnTestFixtureSetUp() { appHost = new ValidationAppHostHttpListener(); appHost.Init(); appHost.Start(ListeningOn); } /// <summary>Executes the test fixture tear down action.</summary> [TestFixtureTearDown] public void OnTestFixtureTearDown() { appHost.Dispose(); EndpointHandlerBase.ServiceManager = null; } private static List<ResponseError> GetValidationFieldErrors(string httpMethod, Customers request) { var validator = (IValidator)new CustomersValidator { AddressValidator = new AddressValidator() }; var validationResult = validator.Validate( new ValidationContext(request, null, new MultiRuleSetValidatorSelector(httpMethod))); var responseStatus = validationResult.ToErrorResult().ToResponseStatus(); var errorFields = responseStatus.Errors; return errorFields ?? new List<ResponseError>(); } private string[] ExpectedPostErrorFields = new[] { "Id", "LastName", "FirstName", "Company", "Address", "Postcode", }; private string[] ExpectedPostErrorCodes = new[] { "NotEqual", "ShouldNotBeEmpty", "NotEmpty", "NotNull", "Predicate", "Predicate", }; Customers validRequest; /// <summary>Sets the up.</summary> [SetUp] public void SetUp() { validRequest = new Customers { Id = 1, FirstName = "FirstName", LastName = "LastName", Address = "12345 Address St, New York", Company = "Company", Discount = 10, HasDiscount = true, Postcode = "11215", }; } /// <summary>Validation feature add request filter once.</summary> [Test] public void ValidationFeature_add_request_filter_once() { var old = appHost.RequestFilters.Count; appHost.LoadPlugin(new ValidationFeature()); Assert.That(old, Is.EqualTo(appHost.RequestFilters.Count)); } /// <summary>Validates valid request on post.</summary> [Test] public void Validates_ValidRequest_request_on_Post() { var errorFields = GetValidationFieldErrors(HttpMethods.Post, validRequest); Assert.That(errorFields.Count, Is.EqualTo(0)); } /// <summary>Validates valid request on get.</summary> [Test] public void Validates_ValidRequest_request_on_Get() { var errorFields = GetValidationFieldErrors(HttpMethods.Get, validRequest); Assert.That(errorFields.Count, Is.EqualTo(0)); } /// <summary>Validates conditional request on post.</summary> [Test] public void Validates_Conditional_Request_request_on_Post() { validRequest.Discount = 0; validRequest.HasDiscount = true; var errorFields = GetValidationFieldErrors(HttpMethods.Post, validRequest); Assert.That(errorFields.Count, Is.EqualTo(1)); Assert.That(errorFields[0].FieldName, Is.EqualTo("Discount")); } /// <summary>Validates empty request on post.</summary> [Test] public void Validates_empty_request_on_Post() { var request = new Customers(); var errorFields = GetValidationFieldErrors(HttpMethods.Post, request); var fieldNames = errorFields.Select(x => x.FieldName).ToArray(); var fieldErrorCodes = errorFields.Select(x => x.ErrorCode).ToArray(); Assert.That(errorFields.Count, Is.EqualTo(ExpectedPostErrorFields.Length)); Assert.That(fieldNames, Is.EquivalentTo(ExpectedPostErrorFields)); Assert.That(fieldErrorCodes, Is.EquivalentTo(ExpectedPostErrorCodes)); } /// <summary>Validates empty request on put.</summary> [Test] public void Validates_empty_request_on_Put() { var request = new Customers(); var errorFields = GetValidationFieldErrors(HttpMethods.Put, request); var fieldNames = errorFields.Select(x => x.FieldName).ToArray(); var fieldErrorCodes = errorFields.Select(x => x.ErrorCode).ToArray(); Assert.That(errorFields.Count, Is.EqualTo(ExpectedPostErrorFields.Length)); Assert.That(fieldNames, Is.EquivalentTo(ExpectedPostErrorFields)); Assert.That(fieldErrorCodes, Is.EquivalentTo(ExpectedPostErrorCodes)); } /// <summary>Validates empty request on get.</summary> [Test] public void Validates_empty_request_on_Get() { var request = new Customers(); var errorFields = GetValidationFieldErrors(HttpMethods.Get, request); Assert.That(errorFields.Count, Is.EqualTo(1)); Assert.That(errorFields[0].ErrorCode, Is.EqualTo("NotEqual")); Assert.That(errorFields[0].FieldName, Is.EqualTo("Id")); } /// <summary>Validates empty request on delete.</summary> [Test] public void Validates_empty_request_on_Delete() { var request = new Customers(); var errorFields = GetValidationFieldErrors(HttpMethods.Delete, request); Assert.That(errorFields.Count, Is.EqualTo(1)); Assert.That(errorFields[0].ErrorCode, Is.EqualTo("NotEqual")); Assert.That(errorFields[0].FieldName, Is.EqualTo("Id")); } /// <summary>Unit test service client.</summary> /// /// <returns>An IServiceClient.</returns> protected static IServiceClient UnitTestServiceClient() { EndpointHandlerBase.ServiceManager = new ServiceManager(typeof(SecureService).Assembly).Init(); return new DirectServiceClient(EndpointHandlerBase.ServiceManager); } /// <summary>Gets the service clients.</summary> /// /// <value>The service clients.</value> public static IEnumerable ServiceClients { get { //Seriously retarded workaround for some devs idea who thought this should //be run for all test fixtures, not just this one. return new Func<IServiceClient>[] { () => UnitTestServiceClient(), () => new JsonServiceClient(ListeningOn), () => new JsvServiceClient(ListeningOn), () => new XmlServiceClient(ListeningOn), }; } } /// <summary>Posts an empty request throws validation exception.</summary> /// /// <exception cref="Validation">Thrown when a validation error condition occurs.</exception> /// /// <param name="factory">The factory.</param> [Test, TestCaseSource(typeof(CustomerServiceValidationTests), "ServiceClients")] public void Post_empty_request_throws_validation_exception(Func<IServiceClient> factory) { try { var client = factory(); var response = client.Send<CustomersResponse>(new Customers()); Assert.Fail("Should throw Validation Exception"); } catch (WebServiceException ex) { var response = (CustomersResponse)ex.ResponseDto; var errorFields = response.ResponseStatus.Errors; var fieldNames = errorFields.Select(x => x.FieldName).ToArray(); var fieldErrorCodes = errorFields.Select(x => x.ErrorCode).ToArray(); Assert.That(ex.StatusCode, Is.EqualTo((int)HttpStatusCode.BadRequest)); Assert.That(errorFields.Count, Is.EqualTo(ExpectedPostErrorFields.Length)); Assert.That(fieldNames, Is.EquivalentTo(ExpectedPostErrorFields)); Assert.That(fieldErrorCodes, Is.EquivalentTo(ExpectedPostErrorCodes)); } } /// <summary>Gets empty request throws validation exception.</summary> /// /// <exception cref="Validation">Thrown when a validation error condition occurs.</exception> /// /// <param name="factory">The factory.</param> [Test, TestCaseSource(typeof(CustomerServiceValidationTests), "ServiceClients")] public void Get_empty_request_throws_validation_exception(Func<IServiceClient> factory) { try { var client = (IRestClient)factory(); var response = client.Get<CustomersResponse>("Customers"); Assert.Fail("Should throw Validation Exception"); } catch (WebServiceException ex) { var response = (CustomersResponse)ex.ResponseDto; var errorFields = response.ResponseStatus.Errors; Assert.That(ex.StatusCode, Is.EqualTo((int)HttpStatusCode.BadRequest)); Assert.That(errorFields.Count, Is.EqualTo(1)); Assert.That(errorFields[0].ErrorCode, Is.EqualTo("NotEqual")); Assert.That(errorFields[0].FieldName, Is.EqualTo("Id")); } } /// <summary>Posts a valid request succeeds.</summary> /// /// <param name="factory">The factory.</param> [Test, TestCaseSource(typeof(CustomerServiceValidationTests), "ServiceClients")] public void Post_ValidRequest_succeeds(Func<IServiceClient> factory) { var client = factory(); var response = client.Send<CustomersResponse>(validRequest); Assert.That(response.ResponseStatus, Is.Null); } } }
// *********************************************************************** // Copyright (c) 2007 Charlie Poole // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using Microsoft.Win32; namespace NUnit.Engine { /// <summary> /// Enumeration identifying profile of .NET Framework /// </summary> public enum Profile { /// <summary>Profile Unspecified</summary> Unspecified, /// <summary>Client Profile</summary> Client, /// <summary>Full Profile</summary> Full } /// <summary> /// RuntimeFramework represents a particular version /// of a common language runtime implementation. /// </summary> [Serializable] public sealed class RuntimeFramework : IRuntimeFramework { #region Static and Instance Fields /// <summary> /// DefaultVersion is an empty Version, used to indicate that /// NUnit should select the CLR version to use for the test. /// </summary> public static readonly Version DefaultVersion = new Version(0, 0); private static RuntimeFramework currentFramework; private static RuntimeFramework[] availableFrameworks; #endregion #region Constructor /// <summary> /// Construct from a runtime type and version. If the version has /// two parts, it is taken as a framework version. If it has three /// or more, it is taken as a CLR version. In either case, the other /// version is deduced based on the runtime type and provided version. /// </summary> /// <param name="runtime">The runtime type of the framework</param> /// <param name="version">The version of the framework</param> public RuntimeFramework(RuntimeType runtime, Version version) : this(runtime, version, Profile.Unspecified) { } /// <summary> /// Construct from a runtime type, version and profile. If the version has /// two parts, it is taken as a framework version. If it has three /// or more, it is taken as a CLR version. In either case, the other /// version is deduced based on the runtime type and provided version. /// </summary> /// <param name="runtime">The runtime type of the framework</param> /// <param name="version">The version of the framework</param> public RuntimeFramework(RuntimeType runtime, Version version, Profile profile) { Runtime = runtime; if (version.Build < 0) InitFromFrameworkVersion(version); else InitFromClrVersion(version); Profile = profile; DisplayName = GetDefaultDisplayName(runtime, FrameworkVersion, profile); } private void InitFromFrameworkVersion(Version version) { this.FrameworkVersion = this.ClrVersion = version; if (version.Major > 0) // 0 means any version switch (Runtime) { case RuntimeType.Net: case RuntimeType.Mono: case RuntimeType.Any: switch (version.Major) { case 1: switch (version.Minor) { case 0: this.ClrVersion = Runtime == RuntimeType.Mono ? new Version(1, 1, 4322) : new Version(1, 0, 3705); break; case 1: if (Runtime == RuntimeType.Mono) this.FrameworkVersion = new Version(1, 0); this.ClrVersion = new Version(1, 1, 4322); break; default: ThrowInvalidFrameworkVersion(version); break; } break; case 2: case 3: this.ClrVersion = new Version(2, 0, 50727); break; case 4: this.ClrVersion = new Version(4, 0, 30319); break; default: ThrowInvalidFrameworkVersion(version); break; } break; case RuntimeType.Silverlight: this.ClrVersion = version.Major >= 4 ? new Version(4, 0, 60310) : new Version(2, 0, 50727); break; } } private static void ThrowInvalidFrameworkVersion(Version version) { throw new ArgumentException("Unknown framework version " + version.ToString(), "version"); } private void InitFromClrVersion(Version version) { this.FrameworkVersion = new Version(version.Major, version.Minor); this.ClrVersion = version; if (Runtime == RuntimeType.Mono && version.Major == 1) this.FrameworkVersion = new Version(1, 0); } #endregion #region IRuntimeFramework Explicit Implementation /// <summary> /// Gets the inique Id for this runtime, such as "net-4.5" /// </summary> string IRuntimeFramework.Id { get { return this.ToString(); } } /// <summary> /// Gets the display name of the framework, such as ".NET 4.5" /// </summary> string IRuntimeFramework.DisplayName { get { return this.DisplayName; } } /// <summary> /// Gets the framework version: usually contains two components, Major /// and Minor, which match the corresponding CLR components, but not always. /// </summary> Version IRuntimeFramework.FrameworkVersion { get { return this.FrameworkVersion; } } /// <summary> /// Gets the Version of the CLR for this framework /// </summary> Version IRuntimeFramework.ClrVersion { get { return this.ClrVersion; } } /// <summary> /// Gets a string representing the particular profile installed, /// or null if there is no profile. Currently. the only defined /// values are Full and Client. /// </summary> string IRuntimeFramework.Profile { get { return Profile.ToString(); } } #endregion #region Properties /// <summary> /// Static method to return a RuntimeFramework object /// for the framework that is currently in use. /// </summary> public static RuntimeFramework CurrentFramework { get { if (currentFramework == null) { Type monoRuntimeType = Type.GetType("Mono.Runtime", false); bool isMono = monoRuntimeType != null; RuntimeType runtime = isMono ? RuntimeType.Mono : Environment.OSVersion.Platform == PlatformID.WinCE ? RuntimeType.NetCF : RuntimeType.Net; int major = Environment.Version.Major; int minor = Environment.Version.Minor; if (isMono) { switch (major) { case 1: minor = 0; break; case 2: major = 3; minor = 5; break; } } else /* It's windows */ if (major == 2) { RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\.NETFramework"); if (key != null) { string installRoot = key.GetValue("InstallRoot") as string; if (installRoot != null) { if (Directory.Exists(Path.Combine(installRoot, "v3.5"))) { major = 3; minor = 5; } else if (Directory.Exists(Path.Combine(installRoot, "v3.0"))) { major = 3; minor = 0; } } } } else if (major == 4 && Type.GetType("System.Reflection.AssemblyMetadataAttribute") != null) { minor = 5; } currentFramework = new RuntimeFramework(runtime, new Version(major, minor)); currentFramework.ClrVersion = Environment.Version; if (isMono) { MethodInfo getDisplayNameMethod = monoRuntimeType.GetMethod( "GetDisplayName", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.DeclaredOnly | BindingFlags.ExactBinding); if (getDisplayNameMethod != null) currentFramework.DisplayName = (string)getDisplayNameMethod.Invoke(null, new object[0]); } } return currentFramework; } } /// <summary> /// Gets an array of all available frameworks /// </summary> // TODO: Special handling for netcf public static RuntimeFramework[] AvailableFrameworks { get { if (availableFrameworks == null) { List<RuntimeFramework> frameworks = new List<RuntimeFramework>(); AppendDotNetFrameworks(frameworks); AppendDefaultMonoFramework(frameworks); // NYI //AppendMonoFrameworks(frameworks); availableFrameworks = frameworks.ToArray(); } return availableFrameworks; } } /// <summary> /// Returns true if the current RuntimeFramework is available. /// In the current implementation, only Mono and Microsoft .NET /// are supported. /// </summary> /// <returns>True if it's available, false if not</returns> public bool IsAvailable { get { foreach (RuntimeFramework framework in AvailableFrameworks) if (framework.Supports(this)) return true; return false; } } /// <summary> /// The type of this runtime framework /// </summary> public RuntimeType Runtime { get; private set; } /// <summary> /// The framework version for this runtime framework /// </summary> public Version FrameworkVersion { get; private set; } /// <summary> /// The CLR version for this runtime framework /// </summary> public Version ClrVersion { get; private set; } /// <summary> /// The .NET Framework Profile for this framwork, where relevant /// </summary> public Profile Profile { get; private set; } /// <summary> /// Return true if any CLR version may be used in /// matching this RuntimeFramework object. /// </summary> public bool AllowAnyVersion { get { return this.ClrVersion == DefaultVersion; } } /// <summary> /// Returns the Display name for this framework /// </summary> public string DisplayName { get; private set; } #endregion #region Public Methods /// <summary> /// Parses a string representing a RuntimeFramework. /// The string may be just a RuntimeType name or just /// a Version or a hyphenated RuntimeType-Version or /// a Version prefixed by 'v'. /// </summary> /// <param name="s"></param> /// <returns></returns> public static RuntimeFramework Parse(string s) { RuntimeType runtime = RuntimeType.Any; Version version = DefaultVersion; string[] parts = s.Split(new char[] { '-' }); if (parts.Length == 2) { runtime = (RuntimeType)System.Enum.Parse(typeof(RuntimeType), parts[0], true); string vstring = parts[1]; if (vstring != "") version = new Version(vstring); } else if (char.ToLower(s[0]) == 'v') { version = new Version(s.Substring(1)); } else if (IsRuntimeTypeName(s)) { runtime = (RuntimeType)System.Enum.Parse(typeof(RuntimeType), s, true); } else { version = new Version(s); } return new RuntimeFramework(runtime, version); } /// <summary> /// Returns the best available framework that matches a target framework. /// If the target framework has a build number specified, then an exact /// match is needed. Otherwise, the matching framework with the highest /// build number is used. /// </summary> /// <param name="target"></param> /// <returns></returns> public static RuntimeFramework GetBestAvailableFramework(RuntimeFramework target) { RuntimeFramework result = target; if (target.ClrVersion.Build < 0) { foreach (RuntimeFramework framework in AvailableFrameworks) if (framework.Supports(target) && framework.ClrVersion.Build > result.ClrVersion.Build) { result = framework; } } return result; } /// <summary> /// Overridden to return the short name of the framework /// </summary> /// <returns></returns> public override string ToString() { if (this.AllowAnyVersion) { return Runtime.ToString().ToLower(); } else { string vstring = FrameworkVersion.ToString(); if (Runtime == RuntimeType.Any) return "v" + vstring; else return Runtime.ToString().ToLower() + "-" + vstring; } } /// <summary> /// Returns true if the current framework matches the /// one supplied as an argument. Two frameworks match /// if their runtime types are the same or either one /// is RuntimeType.Any and all specified version components /// are equal. Negative (i.e. unspecified) version /// components are ignored. /// </summary> /// <param name="target">The RuntimeFramework to be matched.</param> /// <returns><c>true</c> on match, otherwise <c>false</c></returns> public bool Supports(RuntimeFramework target) { if (this.Runtime != RuntimeType.Any && target.Runtime != RuntimeType.Any && this.Runtime != target.Runtime) return false; if (this.AllowAnyVersion || target.AllowAnyVersion) return true; return VersionsMatch(this.ClrVersion, target.ClrVersion) && this.FrameworkVersion.Major >= target.FrameworkVersion.Major && this.FrameworkVersion.Minor >= target.FrameworkVersion.Minor; } #endregion #region Helper Methods private static bool IsRuntimeTypeName(string name) { foreach (string item in Enum.GetNames(typeof(RuntimeType))) if (item.ToLower() == name.ToLower()) return true; return false; } private static string GetDefaultDisplayName(RuntimeType runtime, Version version, Profile profile) { string displayName; if (version == DefaultVersion) displayName = runtime.ToString(); else if (runtime == RuntimeType.Any) displayName = "v" + version.ToString(); else displayName = runtime.ToString() + " " + version.ToString(); if (profile != Profile.Unspecified && profile != Profile.Full) displayName += " - " + profile.ToString(); return displayName; } private static bool VersionsMatch(Version v1, Version v2) { return v1.Major == v2.Major && v1.Minor == v2.Minor && (v1.Build < 0 || v2.Build < 0 || v1.Build == v2.Build) && (v1.Revision < 0 || v2.Revision < 0 || v1.Revision == v2.Revision); } private static void AppendMonoFrameworks(List<RuntimeFramework> frameworks) { if (Environment.OSVersion.Platform == PlatformID.Win32NT) AppendAllMonoFrameworks(frameworks); else AppendDefaultMonoFramework(frameworks); } private static void AppendAllMonoFrameworks(List<RuntimeFramework> frameworks) { // TODO: Find multiple installed Mono versions under Linux if (Environment.OSVersion.Platform == PlatformID.Win32NT) { // Use registry to find alternate versions RegistryKey key = Registry.LocalMachine.OpenSubKey(@"Software\Novell\Mono"); if (key == null) return; foreach (string version in key.GetSubKeyNames()) { RegistryKey subKey = key.OpenSubKey(version); if (subKey == null) continue; string monoPrefix = subKey.GetValue("SdkInstallRoot") as string; AppendMonoFramework(frameworks, monoPrefix, version); } } else AppendDefaultMonoFramework(frameworks); } // This method works for Windows and Linux but currently // is only called under Linux. private static void AppendDefaultMonoFramework(List<RuntimeFramework> frameworks) { string monoPrefix = null; string version = null; if (Environment.OSVersion.Platform == PlatformID.Win32NT) { RegistryKey key = Registry.LocalMachine.OpenSubKey(@"Software\Novell\Mono"); if (key != null) { version = key.GetValue("DefaultCLR") as string; if (version != null && version != "") { key = key.OpenSubKey(version); if (key != null) monoPrefix = key.GetValue("SdkInstallRoot") as string; } } } else // Assuming we're currently running Mono - change if more runtimes are added { string libMonoDir = Path.GetDirectoryName(typeof(object).Assembly.Location); monoPrefix = Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(libMonoDir))); } AppendMonoFramework(frameworks, monoPrefix, version); } private static void AppendMonoFramework(List<RuntimeFramework> frameworks, string monoPrefix, string version) { if (monoPrefix != null) { string displayFmt = version != null ? "Mono " + version + " - {0} Profile" : "Mono {0} Profile"; if (File.Exists(Path.Combine(monoPrefix, "lib/mono/1.0/mscorlib.dll"))) { RuntimeFramework framework = new RuntimeFramework(RuntimeType.Mono, new Version(1, 1, 4322)); framework.DisplayName = string.Format(displayFmt, "1.0"); frameworks.Add(framework); } if (File.Exists(Path.Combine(monoPrefix, "lib/mono/2.0/mscorlib.dll")) || File.Exists(Path.Combine(monoPrefix, "lib/mono/2.0-api/mscorlib.dll"))) { RuntimeFramework framework = new RuntimeFramework(RuntimeType.Mono, new Version(2, 0, 50727)); framework.DisplayName = string.Format(displayFmt, "2.0"); frameworks.Add(framework); } if (Directory.Exists(Path.Combine(monoPrefix, "lib/mono/3.5")) || Directory.Exists(Path.Combine(monoPrefix, "lib/mono/3.5-api"))) { RuntimeFramework framework = new RuntimeFramework(RuntimeType.Mono, new Version(2, 0, 50727)); framework.FrameworkVersion = new Version(3,5); framework.DisplayName = string.Format(displayFmt, "3.5"); frameworks.Add(framework); } if (File.Exists(Path.Combine(monoPrefix, "lib/mono/4.0/mscorlib.dll")) || File.Exists(Path.Combine(monoPrefix, "lib/mono/4.0-api/mscorlib.dll"))) { RuntimeFramework framework = new RuntimeFramework(RuntimeType.Mono, new Version(4, 0, 30319)); framework.DisplayName = string.Format(displayFmt, "4.0"); frameworks.Add(framework); } if (File.Exists(Path.Combine(monoPrefix, "lib/mono/4.5/mscorlib.dll")) || File.Exists(Path.Combine(monoPrefix, "lib/mono/4.5-api/mscorlib.dll"))) { RuntimeFramework framework = new RuntimeFramework(RuntimeType.Mono, new Version(4, 0, 30319)); framework.FrameworkVersion = new Version(4,5); framework.DisplayName = string.Format(displayFmt, "4.5"); frameworks.Add(framework); } } } private static void AppendDotNetFrameworks(List<RuntimeFramework> frameworks) { if (Environment.OSVersion.Platform == PlatformID.Win32NT) { // Handle Version 1.0, using a different registry key AppendExtremelyOldDotNetFrameworkVersions(frameworks); RegistryKey key = Registry.LocalMachine.OpenSubKey(@"Software\Microsoft\NET Framework Setup\NDP"); if (key != null) { foreach (string name in key.GetSubKeyNames()) { if (name.StartsWith("v") && name != "v4.0") // v4.0 is a duplicate, legacy key { var versionKey = key.OpenSubKey(name); if (versionKey == null) continue; if (name.StartsWith("v4", StringComparison.Ordinal)) // Version 4 and 4.5 AppendDotNetFourFrameworkVersions(frameworks, versionKey); else // Versions 1.1 through 3.5 AppendOlderDotNetFrameworkVersion(frameworks, versionKey, new Version(name.Substring(1))); } } } } } private static void AppendExtremelyOldDotNetFrameworkVersions(List<RuntimeFramework> frameworks) { RegistryKey key = Registry.LocalMachine.OpenSubKey(@"Software\Microsoft\.NETFramework\policy\v1.0"); if (key != null) foreach (string build in key.GetValueNames()) frameworks.Add(new RuntimeFramework(RuntimeType.Net, new Version("1.0." + build))); } private static void AppendOlderDotNetFrameworkVersion(List<RuntimeFramework> frameworks, RegistryKey versionKey, Version version) { if (CheckInstallDword(versionKey)) frameworks.Add(new RuntimeFramework(RuntimeType.Net, version)); } // Note: this method cannot be generalized past V4, because (a) it has // specific code for detecting .NET 4.5 and (b) we don't know what // microsoft will do in the future private static void AppendDotNetFourFrameworkVersions(List<RuntimeFramework> frameworks, RegistryKey versionKey) { foreach (Profile profile in new Profile[] { Profile.Full, Profile.Client }) { var profileKey = versionKey.OpenSubKey(profile.ToString()); if (profileKey == null) continue; if (CheckInstallDword(profileKey)) { var framework = new RuntimeFramework(RuntimeType.Net, new Version(4, 0), profile); framework.Profile = profile; frameworks.Add(framework); var release = (int)profileKey.GetValue("Release", 0); if (release > 0) { framework = new RuntimeFramework(RuntimeType.Net, new Version(4, 5)); frameworks.Add(framework); } return; //If full profile found, return and don't check for client profile } } } private static bool CheckInstallDword(RegistryKey key) { return ((int)key.GetValue("Install", 0) == 1); } #endregion } }
#region -- License Terms -- // // MessagePack for CLI // // Copyright (C) 2010-2016 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion -- License Terms -- using System; using System.Collections.Generic; #if CORE_CLR || NETSTANDARD1_1 using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; #endif // CORE_CLR || NETSTANDARD1_1 using System.Globalization; using System.Linq; namespace MsgPack.Serialization.AbstractSerializers { /// <summary> /// Defines common interfaces and features for context objects for serializer generation. /// </summary> /// <typeparam name="TConstruct">The contextType of the code construct for serializer builder.</typeparam> internal abstract class SerializerGenerationContext<TConstruct> { /// <summary> /// Gets the code construct which represents 'context' parameter of generated methods. /// </summary> /// <value> /// The code construct which represents 'context' parameter of generated methods. /// Its type is <see cref="SerializationContext"/>, and it holds dependent serializers. /// This value will not be <c>null</c>. /// </value> public virtual TConstruct Context { get { throw new NotSupportedException(); } } /// <summary> /// Gets the serialization context which holds various serialization configuration. /// </summary> /// <value> /// The serialization context. This value will not be <c>null</c>. /// </value> public SerializationContext SerializationContext { get; private set; } /// <summary> /// Gets the code construct which represents the argument for the packer. /// </summary> /// <value> /// The code construct which represents the argument for the packer. /// This value will not be <c>null</c>. /// </value> public TConstruct Packer { get; protected set; } /// <summary> /// Gets the code construct which represents the argument for the packing target object tree root. /// </summary> /// <returns> /// The code construct which represents the argument for the packing target object tree root. /// This value will not be <c>null</c>. /// </returns> public TConstruct PackToTarget { get; protected set; } /// <summary> /// Gets the code construct which represents the argument for the single argument for null checking. /// </summary> /// <returns> /// The code construct which represents the argument for the single argument for null checking. /// This value will not be <c>null</c>. /// </returns> public TConstruct NullCheckTarget { get; protected set; } /// <summary> /// Gets the code construct which represents the argument for the unpacker. /// </summary> /// <value> /// The code construct which represents the argument for the unpacker. /// This value will not be <c>null</c>. /// </value> public TConstruct Unpacker { get; protected set; } /// <summary> /// Gets the code construct which represents the argument for the collection which will hold unpacked items. /// </summary> /// <returns> /// The code construct which represents the argument for the collection which will hold unpacked items. /// This value will not be <c>null</c>. /// </returns> public TConstruct UnpackToTarget { get; protected set; } /// <summary> /// Gets the code construct which represents the argument for the collection which will be added new unpacked item. /// </summary> /// <returns> /// The code construct which represents the argument for the collection which will be added new unpacked item. /// This value will not be <c>null</c>. /// </returns> public TConstruct CollectionToBeAdded { get; protected set; } /// <summary> /// Gets the code construct which represents the argument for the item to be added to the collection. /// </summary> /// <returns> /// The code construct which represents the argument for the item to be added to the collection. /// This value will not be <c>null</c>. /// </returns> public TConstruct ItemToAdd { get; protected set; } /// <summary> /// Gets the code construct which represents the argument for the key to be added to the dictionary. /// </summary> /// <returns> /// The code construct which represents the argument for the key to be added to the dictionary. /// This value will not be <c>null</c>. /// </returns> public TConstruct KeyToAdd { get; protected set; } /// <summary> /// Gets the code construct which represents the argument for the value to be added to the dictionary. /// </summary> /// <returns> /// The code construct which represents the argument for the key to be added to the dictionary. /// This value will not be <c>null</c>. /// </returns> public TConstruct ValueToAdd { get; protected set; } /// <summary> /// Gets the code construct which represents the argument for the initial capacity of the new collection. /// </summary> /// <returns> /// The code construct which represents the argument for the initial capacity of the new collection. /// This value will not be <c>null</c>. /// </returns> public TConstruct InitialCapacity { get; protected set; } /// <summary> /// Gets the code construct which represents the unpacking context for unpacking operations. /// </summary> /// <value> /// The code construct which represents the the unpacking context for unpacking operations. /// This value is initialized in <see cref="DefineUnpackingContext"/>. /// </value> public TConstruct UnpackingContextInUnpackValueMethods { get; private set; } /// <summary> /// Gets the code construct which represents the unpacking context for unpacking operations. /// </summary> /// <value> /// The code construct which represents the the unpacking context for unpacking operations. /// This value is initialized in <see cref="DefineUnpackingContext"/>. /// </value> public TConstruct UnpackingContextInSetValueMethods { get; private set; } /// <summary> /// Gets the code construct which represents the unpacking context for CreateObjectFromContext method. /// </summary> /// <value> /// The code construct which represents the the unpacking context for CreateObjectFromContext method. /// This value is initialized in <see cref="DefineUnpackingContext"/>. /// </value> public TConstruct UnpackingContextInCreateObjectFromContext { get; private set; } /// <summary> /// Gets the code construct which represents the index of unpacking item in the source array or map. /// </summary> /// <value> /// The code construct which represents the index of unpacking item in the source array or map. /// This value will not be <c>null</c>. /// </value> public TConstruct IndexOfItem { get; protected set; } /// <summary> /// Gets the code construct which represents the count of unpacking items in the source array or map. /// </summary> /// <value> /// The code construct which represents the count of unpacking items in the source array or map. /// This value will not be <c>null</c>. /// </value> public TConstruct ItemsCount { get; protected set; } /// <summary> /// Gets the configured nil-implication for collection items. /// </summary> /// <value> /// The configured nil-implication for collection items. /// </value> public NilImplication CollectionItemNilImplication { get; private set; } /// <summary> /// Gets the configured nil-implication for dictionary keys. /// </summary> /// <value> /// The configured nil-implication for dictionary keys. /// </value> public NilImplication DictionaryKeyNilImplication { get; private set; } // NOTE: Missing map value is MemberDefault /// <summary> /// Gets the configured nil-implication for tuple items. /// </summary> /// <value> /// The configured nil-implication for tuple items. /// </value> public NilImplication TupleItemNilImplication { get; private set; } private readonly IDictionary<string, MethodDefinition> _declaredMethods; /// <summary> /// Gets the declared method. /// </summary> /// <param name="name">The name of the method.</param> /// <returns> /// The <see cref="MethodDefinition"/>. This value will not be <c>null</c>. /// </returns> /// <exception cref="InvalidOperationException">The specified method has not been declared yet.</exception> public MethodDefinition GetDeclaredMethod( string name ) { var method = this.TryGetDeclaredMethod( name ); if ( method == null ) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "Method '{0}' is not declared yet.", name ) ); } return method; } /// <summary> /// Gets the declared method. /// </summary> /// <param name="name">The name of the method.</param> /// <returns> /// The <see cref="MethodDefinition"/>. This value will be <c>null</c> when the specified method is not declared. /// </returns> /// <exception cref="InvalidOperationException">The specified method has not been declared yet.</exception> public MethodDefinition TryGetDeclaredMethod( string name ) { MethodDefinition method; if ( !this._declaredMethods.TryGetValue( name, out method ) ) { return null; } return method; } /// <summary> /// Determines whether specified named private method is already declared or not. /// </summary> /// <param name="name">The name of the method.</param> /// <returns><c>true</c>, if specified named method is already declared; <c>fale</c>, otherwise.</returns> public bool IsDeclaredMethod( string name ) { return this._declaredMethods.ContainsKey( name ); } private readonly IDictionary<string, FieldDefinition> _declaredFields; /// <summary> /// Gets the declared field. /// </summary> /// <param name="name">The name of the field.</param> /// <returns> /// The <see cref="FieldDefinition"/>. This value will not be <c>null</c>. /// </returns> /// <exception cref="FieldDefinition">The specified field has not been declared yet.</exception> public FieldDefinition GetDeclaredField( string name ) { FieldDefinition field; if ( !this._declaredFields.TryGetValue( name, out field ) ) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "Field '{0}' is not declared yet.", name ) ); } return field; } private readonly IDictionary<string, CachedDelegateInfo> _cachedDelegateInfos; public FieldDefinition GetCachedPrivateMethodDelegate( MethodDefinition method, TypeDefinition delegateType ) { return this.GetCachedDelegateCore( method, delegateType, "this", true ); } public FieldDefinition GetCachedStaticMethodDelegate( MethodDefinition method, TypeDefinition delegateType ) { return this.GetCachedDelegateCore( method, delegateType, method.DeclaringType.TypeName, false ); } private FieldDefinition GetCachedDelegateCore( MethodDefinition method, TypeDefinition delegateType, string prefix, bool isThis ) { var key = prefix + "." + method.MethodName; CachedDelegateInfo delegateInfo; if ( !this._cachedDelegateInfos.TryGetValue( key, out delegateInfo ) ) { delegateInfo = new CachedDelegateInfo( isThis, method, this.DeclarePrivateField( key.Replace( '.', '_' ) + "Delegate", delegateType ) ); this._cachedDelegateInfos.Add( key, delegateInfo ); } return delegateInfo.BackingField; } public IEnumerable<CachedDelegateInfo> GetCachedDelegateInfos() { return this._cachedDelegateInfos.Values; } private KeyValuePair<TypeDefinition, ConstructorDefinition> _unpackingContextDefinition; /// <summary> /// Gets the type of the unpacking context. /// </summary> /// <value> /// The type of the unpacking context. This value is <c>null</c> until <see cref="DefineUnpackingContext"/> called after last <see cref="Reset"/>. /// </value> public TypeDefinition UnpackingContextType { get { return this._unpackingContextDefinition.Key; } } /// <summary> /// Gets or sets a value indicating whether an UnpackTo method call is emitted or not. /// </summary> /// <value> /// <c>true</c> if an UnpackTo method call is emitted; otherwise, <c>false</c>. /// </value> public bool IsUnpackToUsed { get; set; } #if DEBUG private KeyValuePair<string, TypeDefinition>[] _lastUnpackingContextFields; #endif // DEBUG /// <summary> /// Initializes a new instance of the <see cref="SerializerGenerationContext{TConstruct}"/> class. /// </summary> /// <param name="context">The serialization context.</param> protected SerializerGenerationContext( SerializationContext context ) { this.SerializationContext = context; this.CollectionItemNilImplication = NilImplication.Null; this.DictionaryKeyNilImplication = NilImplication.Prohibit; this.TupleItemNilImplication = NilImplication.Null; this._declaredMethods = new Dictionary<string, MethodDefinition>(); this._declaredFields = new Dictionary<string, FieldDefinition>(); this._cachedDelegateInfos = new Dictionary<string, CachedDelegateInfo>(); } /// <summary> /// Resets internal states for specified target type. /// </summary> /// <param name="targetType">Type of the serialization target.</param> /// <param name="baseClass">Type of base class of the target.</param> public void Reset( Type targetType, Type baseClass ) { this.Packer = default( TConstruct ); this.PackToTarget = default( TConstruct ); this.NullCheckTarget = default ( TConstruct ); this.Unpacker = default( TConstruct ); this.UnpackToTarget = default( TConstruct ); this.CollectionToBeAdded = default( TConstruct ); this.ItemToAdd = default( TConstruct ); this.KeyToAdd = default( TConstruct ); this.ValueToAdd = default( TConstruct ); this.InitialCapacity = default( TConstruct ); this.UnpackingContextInUnpackValueMethods = default( TConstruct ); this.UnpackingContextInSetValueMethods = default( TConstruct ); this.UnpackingContextInCreateObjectFromContext = default( TConstruct ); this.IndexOfItem = default( TConstruct ); this.ItemsCount = default( TConstruct ); this.ResetCore( targetType, baseClass ); this._declaredMethods.Clear(); this._declaredFields.Clear(); this._cachedDelegateInfos.Clear(); this._unpackingContextDefinition = default( KeyValuePair<TypeDefinition, ConstructorDefinition> ); this.IsUnpackToUsed = false; #if DEBUG this._lastUnpackingContextFields = null; #endif // DEBUG } /// <summary> /// Resets internal states for specified target type. /// </summary> /// <param name="targetType">Type of the serialization target.</param> /// <param name="baseClass">Type of base class of the target.</param> protected abstract void ResetCore( Type targetType, Type baseClass ); /// <summary> /// Gets a unique name of a local variable. /// </summary> /// <param name="prefix">The prefix of the variable.</param> /// <returns>A unique name of a local variable.</returns> public virtual string GetUniqueVariableName( string prefix ) { // Many implementations do not need local variable name, so this method is not needed to do anything. return prefix; } /// <summary> /// Begins implementing overriding method. /// </summary> /// <param name="name">The name of the method.</param> public abstract void BeginMethodOverride( string name ); /// <summary> /// Ends implementing overriding method. /// </summary> /// <param name="name">The name of the method.</param> /// <param name="body">The construct which represents whole method body.</param> /// <returns> /// The method definition of the overridden method. /// </returns> public MethodDefinition EndMethodOverride( string name, TConstruct body ) { var method = this.EndMethodOverrideCore( name, body ); this._declaredMethods[ name ] = method; return method; } /// <summary> /// Ends implementing overriding method. /// </summary> /// <param name="name">The name of the method.</param> /// <param name="body">The construct which represents whole method body.</param> /// <returns> /// The method definition of the overridden method. /// </returns> protected abstract MethodDefinition EndMethodOverrideCore( string name, TConstruct body ); /// <summary> /// Begins implementing private method. /// </summary> /// <param name="name">The name of the method.</param> /// <param name="isStatic"><c>true</c> for static method.</param> /// <param name="returnType">The type of the method return value.</param> /// <param name="parameters">The name and type pairs of the method parameters.</param> public abstract void BeginPrivateMethod( string name, bool isStatic, TypeDefinition returnType, params TConstruct[] parameters ); /// <summary> /// Ends current implementing private method. /// </summary> /// <param name="name">The name of the method.</param> /// <param name="body">The construct which represents whole method body.</param> /// <returns> /// The method definition of the private method. /// </returns> public MethodDefinition EndPrivateMethod( string name, TConstruct body ) { var method = this.EndPrivateMethodCore( name, body ); this._declaredMethods[ name ] = method; return method; } /// <summary> /// Ends current implementing private method. /// </summary> /// <param name="name">The name of the method.</param> /// <param name="body">The construct which represents whole method body.</param> /// <returns> /// The method definition of the private method. /// </returns> protected abstract MethodDefinition EndPrivateMethodCore( string name, TConstruct body ); /// <summary> /// Declares new private field. /// </summary> /// <param name="name">The name.</param> /// <param name="type">The type.</param> /// <returns></returns> public FieldDefinition DeclarePrivateField( string name, TypeDefinition type ) { var field = this.DeclarePrivateFieldCore( name, type ); this._declaredFields[ name ] = field; return field; } /// <summary> /// Declares new private field. /// </summary> /// <param name="name">The name.</param> /// <param name="type">The type.</param> /// <returns></returns> protected abstract FieldDefinition DeclarePrivateFieldCore( string name, TypeDefinition type ); /// <summary> /// Defines the unpacking context type. /// </summary> /// <param name="fields">The fields must be declared.</param> /// <param name="type"> /// The type definition of the unpacking context. /// Note that this type will be existing property bag or generated private type. /// </param> /// <param name="constructor"> /// The constructor of the context. /// </param> public void DefineUnpackingContext( KeyValuePair<string, TypeDefinition>[] fields, out TypeDefinition type, out ConstructorDefinition constructor ) { if ( this.UnpackingContextType != null ) { #if DEBUG Contract.Assert( this._lastUnpackingContextFields.Select( kv => kv.Key + ":" + kv.Value ) .SequenceEqual( fields.Select( kv => kv.Key + ":" + kv.Value ) ), "Duplicated UnpackingContext registration." ); #endif // DEBUG type = this._unpackingContextDefinition.Key; constructor = this._unpackingContextDefinition.Value; return; } #if DEBUG this._lastUnpackingContextFields = fields.ToArray(); #endif // DEBUG TConstruct parameterInUnpackValueMethods, parameterInSetValueMethods, parameterInCreateObjectFromContext; this.DefineUnpackingContextCore( fields, out type, out constructor, out parameterInUnpackValueMethods, out parameterInSetValueMethods, out parameterInCreateObjectFromContext ); this.UnpackingContextInUnpackValueMethods = parameterInUnpackValueMethods; this.UnpackingContextInSetValueMethods = parameterInSetValueMethods; this.UnpackingContextInCreateObjectFromContext = parameterInCreateObjectFromContext; this._unpackingContextDefinition = new KeyValuePair<TypeDefinition, ConstructorDefinition>( type, constructor ); } /// <summary> /// Defines the unpacking context type. /// </summary> /// <param name="fields">The fields must be declared.</param> /// <param name="type"> /// The type definition of the unpacking context. /// Note that this type will be existing property bag or generated private type. /// </param> /// <param name="constructor"> /// The constructor of the context. /// </param> /// <param name="parameterInUnpackValueMethods">The <paramref name="type"/> typed parameter for unpacking operations.</param> /// <param name="parameterInSetValueMethods">The <paramref name="type"/> typed parameter for unpacking operations.</param> /// <param name="parameterInCreateObjectFromContext">The <paramref name="type"/> typed parameter for CreateObjectFromContext method.</param> protected abstract void DefineUnpackingContextCore( IList<KeyValuePair<string, TypeDefinition>> fields, out TypeDefinition type, out ConstructorDefinition constructor, out TConstruct parameterInUnpackValueMethods, out TConstruct parameterInSetValueMethods, out TConstruct parameterInCreateObjectFromContext ); /// <summary> /// Defines the unpacking context type with result object type. /// </summary> /// <returns>The unpacking context type.</returns> public TypeDefinition DefineUnpackingContextWithResultObject() { TypeDefinition type; TConstruct parameterInUnpackValueMethods, parameterInSetValueMethods, parameterInCreateObjectFromContext; this.DefineUnpackingContextWithResultObjectCore( out type, out parameterInUnpackValueMethods, out parameterInSetValueMethods, out parameterInCreateObjectFromContext ); this.UnpackingContextInUnpackValueMethods = parameterInUnpackValueMethods; this.UnpackingContextInSetValueMethods = parameterInSetValueMethods; this.UnpackingContextInCreateObjectFromContext = parameterInCreateObjectFromContext; this._unpackingContextDefinition = new KeyValuePair<TypeDefinition, ConstructorDefinition>( type, null ); return type; } /// <summary> /// Defines the unpacking context type with result object type. /// </summary> /// <param name="type"> /// The type definition of the unpacking context. /// Note that this type will be existing property bag or generated private type. /// </param> /// <param name="parameterInUnpackValueMethods">The <paramref name="type"/> typed parameter for unpacking operations.</param> /// <param name="parameterInSetValueMethods">The <paramref name="type"/> typed parameter for unpacking operations.</param> /// <param name="parameterInCreateObjectFromContext">The <paramref name="type"/> typed parameter for CreateObjectFromContext method.</param> protected abstract void DefineUnpackingContextWithResultObjectCore( out TypeDefinition type, out TConstruct parameterInUnpackValueMethods, out TConstruct parameterInSetValueMethods, out TConstruct parameterInCreateObjectFromContext ); /// <summary> /// Defines the unpacked item parameter in set value methods. /// </summary> /// <param name="itemType">Type of the value.</param> /// <returns>The parameter construct.</returns> public abstract TConstruct DefineUnpackedItemParameterInSetValueMethods( TypeDefinition itemType ); } }
using System; using System.Collections.Generic; using NUnit.Framework; using NServiceKit.Common.Tests.Models; using NServiceKit.Redis.Generic; namespace NServiceKit.Redis.Tests.Generic { [TestFixture] public class RedisTypedTransactionTests : RedisClientTestsBase { private const string Key = "multitest"; private const string ListKey = "multitest-list"; private const string SetKey = "multitest-set"; private const string SortedSetKey = "multitest-sortedset"; readonly ShipperFactory modelFactory = new ShipperFactory(); private IRedisTypedClient<Shipper> typedClient; private Shipper model; public RedisTypedTransactionTests() { CleanMask = "multitest*"; } public override void OnBeforeEachTest() { base.OnBeforeEachTest(); typedClient = Redis.GetTypedClient<Shipper>(); model = modelFactory.CreateInstance(1); } [Test] public void Can_call_single_operation_in_transaction() { Assert.That(typedClient.GetValue(Key), Is.Null); using (var trans = typedClient.CreateTransaction()) { trans.QueueCommand(r => r.SetEntry(Key, model)); trans.Commit(); } modelFactory.AssertIsEqual(typedClient.GetValue(Key), model); } [Test] public void No_commit_of_atomic_transactions_discards_all_commands() { Assert.That(typedClient.GetValue(Key), Is.Null); using (var trans = typedClient.CreateTransaction()) { trans.QueueCommand(r => r.SetEntry(Key, model)); } Assert.That(typedClient.GetValue(Key), Is.Null); } [Test] public void Exception_in_atomic_transactions_discards_all_commands() { Assert.That(typedClient.GetValue(Key), Is.Null); try { using (var trans = typedClient.CreateTransaction()) { trans.QueueCommand(r => r.SetEntry(Key, model)); throw new NotSupportedException(); } } catch (NotSupportedException ignore) { Assert.That(typedClient.GetValue(Key), Is.Null); } } [Test] public void Can_call_single_operation_3_Times_in_transaction() { var typedList = typedClient.Lists[ListKey]; Assert.That(typedList.Count, Is.EqualTo(0)); using (var trans = typedClient.CreateTransaction()) { trans.QueueCommand(r => r.AddItemToList(typedList, modelFactory.CreateInstance(1))); trans.QueueCommand(r => r.AddItemToList(typedList, modelFactory.CreateInstance(2))); trans.QueueCommand(r => r.AddItemToList(typedList, modelFactory.CreateInstance(3))); trans.Commit(); } Assert.That(typedList.Count, Is.EqualTo(3)); } [Test] public void Can_call_single_operation_with_callback_3_Times_in_transaction() { var results = new List<int>(); var typedList = typedClient.Lists[ListKey]; Assert.That(typedList.Count, Is.EqualTo(0)); using (var trans = typedClient.CreateTransaction()) { trans.QueueCommand(r => r.AddItemToList(typedList, modelFactory.CreateInstance(1)), () => results.Add(1)); trans.QueueCommand(r => r.AddItemToList(typedList, modelFactory.CreateInstance(2)), () => results.Add(2)); trans.QueueCommand(r => r.AddItemToList(typedList, modelFactory.CreateInstance(3)), () => results.Add(3)); trans.Commit(); } Assert.That(typedList.Count, Is.EqualTo(3)); Assert.That(results, Is.EquivalentTo(new List<int> { 1, 2, 3 })); } [Test] public void Supports_different_operation_types_in_same_transaction() { var incrementResults = new List<long>(); var collectionCounts = new List<long>(); var containsItem = false; var typedList = typedClient.Lists[ListKey]; var typedSet = typedClient.Sets[SetKey]; var typedSortedSet = typedClient.SortedSets[SortedSetKey]; Assert.That(typedClient.GetValue(Key), Is.Null); using (var trans = typedClient.CreateTransaction()) { trans.QueueCommand(r => r.IncrementValue(Key), intResult => incrementResults.Add(intResult)); trans.QueueCommand(r => r.AddItemToList(typedList, modelFactory.CreateInstance(1))); trans.QueueCommand(r => r.AddItemToList(typedList, modelFactory.CreateInstance(2))); trans.QueueCommand(r => r.AddItemToSet(typedSet, modelFactory.CreateInstance(3))); trans.QueueCommand(r => r.SetContainsItem(typedSet, modelFactory.CreateInstance(3)), b => containsItem = b); trans.QueueCommand(r => r.AddItemToSortedSet(typedSortedSet, modelFactory.CreateInstance(4))); trans.QueueCommand(r => r.AddItemToSortedSet(typedSortedSet, modelFactory.CreateInstance(5))); trans.QueueCommand(r => r.AddItemToSortedSet(typedSortedSet, modelFactory.CreateInstance(6))); trans.QueueCommand(r => r.GetListCount(typedList), intResult => collectionCounts.Add(intResult)); trans.QueueCommand(r => r.GetSetCount(typedSet), intResult => collectionCounts.Add(intResult)); trans.QueueCommand(r => r.GetSortedSetCount(typedSortedSet), intResult => collectionCounts.Add(intResult)); trans.QueueCommand(r => r.IncrementValue(Key), intResult => incrementResults.Add(intResult)); trans.Commit(); } Assert.That(containsItem, Is.True); Assert.That(Redis.GetValue(Key), Is.EqualTo("2")); Assert.That(incrementResults, Is.EquivalentTo(new List<int> { 1, 2 })); Assert.That(collectionCounts, Is.EquivalentTo(new List<int> { 2, 1, 3 })); modelFactory.AssertListsAreEqual(typedList.GetAll(), new List<Shipper> { modelFactory.CreateInstance(1), modelFactory.CreateInstance(2) }); Assert.That(typedSet.GetAll(), Is.EquivalentTo(new List<Shipper> { modelFactory.CreateInstance(3) })); modelFactory.AssertListsAreEqual(typedSortedSet.GetAll(), new List<Shipper> { modelFactory.CreateInstance(4), modelFactory.CreateInstance(5), modelFactory.CreateInstance(6) }); } [Test] public void Can_call_multi_string_operations_in_transaction() { Shipper item1 = null; Shipper item4 = null; var results = new List<Shipper>(); var typedList = typedClient.Lists[ListKey]; Assert.That(typedList.Count, Is.EqualTo(0)); using (var trans = typedClient.CreateTransaction()) { trans.QueueCommand(r => r.AddItemToList(typedList, modelFactory.CreateInstance(1))); trans.QueueCommand(r => r.AddItemToList(typedList, modelFactory.CreateInstance(2))); trans.QueueCommand(r => r.AddItemToList(typedList, modelFactory.CreateInstance(3))); trans.QueueCommand(r => r.GetAllItemsFromList(typedList), x => results = x); trans.QueueCommand(r => r.GetItemFromList(typedList, 0), x => item1 = x); trans.QueueCommand(r => r.GetItemFromList(typedList, 4), x => item4 = x); trans.Commit(); } Assert.That(typedList.Count, Is.EqualTo(3)); modelFactory.AssertListsAreEqual(results, new List<Shipper> { modelFactory.CreateInstance(1), modelFactory.CreateInstance(2), modelFactory.CreateInstance(3) }); modelFactory.AssertIsEqual(item1, modelFactory.CreateInstance(1)); Assert.That(item4, Is.Null); } [Test] // Operations that are not supported in older versions will look at server info to determine what to do. // If server info is fetched each time, then it will interfer with transaction public void Can_call_operation_not_supported_on_older_servers_in_transaction() { var temp = new byte[1]; using (var trans = Redis.CreateTransaction()) { trans.QueueCommand(r => ((RedisNativeClient)r).SetEx("key", 5, temp)); trans.Commit(); } } [Test] public void Transaction_can_be_replayed() { string KeySquared = Key + Key; Assert.That(Redis.GetValue(Key), Is.Null); Assert.That(Redis.GetValue(KeySquared), Is.Null); using (var trans = Redis.CreateTransaction()) { trans.QueueCommand(r => r.IncrementValue(Key)); trans.QueueCommand(r => r.IncrementValue(KeySquared)); trans.Commit(); Assert.That(Redis.GetValue(Key), Is.EqualTo("1")); Assert.That(Redis.GetValue(KeySquared), Is.EqualTo("1")); Redis.Del(Key); Redis.Del(KeySquared); Assert.That(Redis.GetValue(Key), Is.Null); Assert.That(Redis.GetValue(KeySquared), Is.Null); trans.Replay(); trans.Dispose(); Assert.That(Redis.GetValue(Key), Is.EqualTo("1")); Assert.That(Redis.GetValue(KeySquared), Is.EqualTo("1")); } } } }
#region Copyright & License // // Copyright 2001-2005 The Apache Software Foundation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion namespace NotLogging { using System; using System.Collections; using log4net; using log4net.Appender; using log4net.Layout; using log4net.Repository; using log4net.Repository.Hierarchy; public class NotLogging { #region Init Code private static int WARM_UP_CYCLES = 10000; static readonly ILog SHORT_LOG = LogManager.GetLogger("A0123456789"); static readonly ILog MEDIUM_LOG= LogManager.GetLogger("A0123456789.B0123456789"); static readonly ILog LONG_LOG = LogManager.GetLogger("A0123456789.B0123456789.C0123456789"); static readonly ILog INEXISTENT_SHORT_LOG = LogManager.GetLogger("I0123456789"); static readonly ILog INEXISTENT_MEDIUM_LOG= LogManager.GetLogger("I0123456789.B0123456789"); static readonly ILog INEXISTENT_LONG_LOG = LogManager.GetLogger("I0123456789.B0123456789.C0123456789"); static readonly ILog[] LOG_ARRAY = new ILog[] { SHORT_LOG, MEDIUM_LOG, LONG_LOG, INEXISTENT_SHORT_LOG, INEXISTENT_MEDIUM_LOG, INEXISTENT_LONG_LOG}; static readonly TimedTest[] TIMED_TESTS = new TimedTest[] { new SimpleMessage_Bare(), new SimpleMessage_Array(), new SimpleMessage_MethodGuard_Bare(), new SimpleMessage_LocalGuard_Bare(), new ComplexMessage_Bare(), new ComplexMessage_Array(), new ComplexMessage_MethodGuard_Bare(), new ComplexMessage_MethodGuard_Array(), new ComplexMessage_MemberGuard_Bare(), new ComplexMessage_LocalGuard_Bare()}; private static void Usage() { System.Console.WriteLine( "Usage: NotLogging <true|false> <runLength>" + Environment.NewLine + "\t true indicates shipped code" + Environment.NewLine + "\t false indicates code in development" + Environment.NewLine + "\t runLength is an int representing the run length of loops" + Environment.NewLine + "\t We suggest that runLength be at least 1000000 (1 million)."); Environment.Exit(1); } /// <summary> /// Program wide initialization method /// </summary> /// <param name="args"></param> private static int ProgramInit(String[] args) { int runLength = 0; try { runLength = int.Parse(args[1]); } catch(Exception e) { System.Console.Error.WriteLine(e); Usage(); } ConsoleAppender appender = new ConsoleAppender(); appender.Layout = new SimpleLayout(); ((SimpleLayout)appender.Layout).ActivateOptions(); appender.ActivateOptions(); if("false" == args[0]) { // nothing to do } else if ("true" == args[0]) { System.Console.WriteLine("Flagging as shipped code."); ((Hierarchy)LogManager.GetRepository()).Threshold = log4net.Core.Level.Warn; } else { Usage(); } ((Logger)SHORT_LOG.Logger).Level = log4net.Core.Level.Info; ((Hierarchy)LogManager.GetRepository()).Root.Level = log4net.Core.Level.Info; ((Hierarchy)LogManager.GetRepository()).Root.AddAppender(appender); return runLength; } #endregion /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main(string[] argv) { if (System.Diagnostics.Debugger.IsAttached) { WARM_UP_CYCLES = 0; argv = new string[] { "false", "2" }; } if(argv.Length != 2) { Usage(); } int runLength = ProgramInit(argv); System.Console.WriteLine(); System.Console.Write("Warming Up..."); if (WARM_UP_CYCLES > 0) { foreach(ILog logger in LOG_ARRAY) { foreach(TimedTest timedTest in TIMED_TESTS) { timedTest.Run(logger, WARM_UP_CYCLES); } } } System.Console.WriteLine("Done"); System.Console.WriteLine(); // Calculate maximum description length int maxDescLen = 0; foreach(TimedTest timedTest in TIMED_TESTS) { maxDescLen = Math.Max(maxDescLen, timedTest.Description.Length); } string formatString = "{0,-"+(maxDescLen+1)+"} {1,9:G} ticks. Log: {2}"; double delta; ArrayList averageData = new ArrayList(); foreach(TimedTest timedTest in TIMED_TESTS) { double total = 0; foreach(ILog logger in LOG_ARRAY) { delta = timedTest.Run(logger, runLength); System.Console.WriteLine(string.Format(formatString, timedTest.Description, delta, ((Logger)logger.Logger).Name)); total += delta; } System.Console.WriteLine(); averageData.Add(new object[] { timedTest, total/((double)LOG_ARRAY.Length) }); } System.Console.WriteLine(); System.Console.WriteLine("Averages:"); System.Console.WriteLine(); foreach(object[] pair in averageData) { string avgFormatString = "{0,-"+(maxDescLen+1)+"} {1,9:G} ticks."; System.Console.WriteLine(string.Format(avgFormatString, ((TimedTest)pair[0]).Description, ((double)pair[1]))); } } } abstract class TimedTest { abstract public double Run(ILog log, long runLength); abstract public string Description {get;} } #region Tests calling Debug(string) class SimpleMessage_Bare : TimedTest { override public double Run(ILog log, long runLength) { DateTime before = DateTime.Now; for(int i = 0; i < runLength; i++) { log.Debug("msg"); } DateTime after = DateTime.Now; TimeSpan diff = after - before; return ((double)diff.Ticks)/((double)runLength); } override public string Description { get { return "log.Debug(\"msg\");"; } } } class ComplexMessage_MethodGuard_Bare : TimedTest { override public double Run(ILog log, long runLength) { DateTime before = DateTime.Now; for(int i = 0; i < runLength; i++) { if(log.IsDebugEnabled) { log.Debug("msg" + i + "msg"); } } DateTime after = DateTime.Now; TimeSpan diff = after - before; return ((double)diff.Ticks)/((double)runLength); } override public string Description { get { return "if(log.IsDebugEnabled) log.Debug(\"msg\" + i + \"msg\");"; } } } class ComplexMessage_Bare : TimedTest { override public double Run(ILog log, long runLength) { DateTime before = DateTime.Now; for(int i = 0; i < runLength; i++) { log.Debug("msg" + i + "msg"); } DateTime after = DateTime.Now; TimeSpan diff = after - before; return ((double)diff.Ticks)/((double)runLength); } override public string Description { get { return "log.Debug(\"msg\" + i + \"msg\");"; } } } #endregion #region Tests calling Debug(new object[] { ... }) class SimpleMessage_Array : TimedTest { override public double Run(ILog log, long runLength) { DateTime before = DateTime.Now; for(int i = 0; i < runLength; i++) { log.Debug(new object[] { "msg" }); } DateTime after = DateTime.Now; TimeSpan diff = after - before; return ((double)diff.Ticks)/((double)runLength); } override public string Description { get { return "log.Debug(new object[] { \"msg\" });"; } } } class ComplexMessage_MethodGuard_Array : TimedTest { override public double Run(ILog log, long runLength) { DateTime before = DateTime.Now; for(int i = 0; i < runLength; i++) { if(log.IsDebugEnabled) { log.Debug(new object[] { "msg" , i , "msg" }); } } DateTime after = DateTime.Now; TimeSpan diff = after - before; return ((double)diff.Ticks)/((double)runLength); } override public string Description { get { return "if(log.IsDebugEnabled) log.Debug(new object[] { \"msg\" , i , \"msg\" });"; } } } class ComplexMessage_Array : TimedTest { override public double Run(ILog log, long runLength) { DateTime before = DateTime.Now; for(int i = 0; i < runLength; i++) { log.Debug(new object[] { "msg" , i , "msg" }); } DateTime after = DateTime.Now; TimeSpan diff = after - before; return ((double)diff.Ticks)/((double)runLength); } override public string Description { get { return "log.Debug(new object[] { \"msg\" , i , \"msg\" });"; } } } #endregion #region Tests calling Debug(string) (using class members) class ComplexMessage_MemberGuard_Bare : TimedTest { override public double Run(ILog log, long runLength) { return (new Impl(log)).Run(runLength); } override public string Description { get { return "if(m_isEnabled) m_log.Debug(\"msg\" + i + \"msg\");"; } } class Impl { private readonly ILog m_log; private readonly bool m_isEnabled; public Impl(ILog log) { m_log = log; m_isEnabled = m_log.IsDebugEnabled; } public double Run(long runLength) { DateTime before = DateTime.Now; for(int i = 0; i < runLength; i++) { if(m_isEnabled) { m_log.Debug("msg" + i + "msg"); } } DateTime after = DateTime.Now; TimeSpan diff = after - before; return ((double)diff.Ticks)/((double)runLength); } } } class SimpleMessage_LocalGuard_Bare : TimedTest { override public double Run(ILog log, long runLength) { bool isEnabled = log.IsDebugEnabled; DateTime before = DateTime.Now; for(int i = 0; i < runLength; i++) { if (isEnabled) log.Debug("msg"); } DateTime after = DateTime.Now; TimeSpan diff = after - before; return ((double)diff.Ticks)/((double)runLength); } override public string Description { get { return "if (isEnabled) log.Debug(\"msg\");"; } } } class SimpleMessage_MethodGuard_Bare : TimedTest { override public double Run(ILog log, long runLength) { DateTime before = DateTime.Now; for(int i = 0; i < runLength; i++) { if (log.IsDebugEnabled) log.Debug("msg"); } DateTime after = DateTime.Now; TimeSpan diff = after - before; return ((double)diff.Ticks)/((double)runLength); } override public string Description { get { return "if (log.IsDebugEnabled) log.Debug(\"msg\");"; } } } class ComplexMessage_LocalGuard_Bare : TimedTest { override public double Run(ILog log, long runLength) { bool isEnabled = log.IsDebugEnabled; DateTime before = DateTime.Now; for(int i = 0; i < runLength; i++) { if(isEnabled) log.Debug("msg" + i + "msg"); } DateTime after = DateTime.Now; TimeSpan diff = after - before; return ((double)diff.Ticks)/((double)runLength); } override public string Description { get { return "if (isEnabled) log.Debug(\"msg\" + i + \"msg\");"; } } } #endregion }
// 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 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; } 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; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void XorUInt64() { var test = new SimpleBinaryOpTest__XorUInt64(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__XorUInt64 { private const int VectorSize = 32; private const int ElementCount = VectorSize / sizeof(UInt64); private static UInt64[] _data1 = new UInt64[ElementCount]; private static UInt64[] _data2 = new UInt64[ElementCount]; private static Vector256<UInt64> _clsVar1; private static Vector256<UInt64> _clsVar2; private Vector256<UInt64> _fld1; private Vector256<UInt64> _fld2; private SimpleBinaryOpTest__DataTable<UInt64> _dataTable; static SimpleBinaryOpTest__XorUInt64() { var random = new Random(); for (var i = 0; i < ElementCount; i++) { _data1[i] = (ulong)(random.Next(0, int.MaxValue)); _data2[i] = (ulong)(random.Next(0, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref _clsVar1), ref Unsafe.As<UInt64, byte>(ref _data2[0]), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref _clsVar2), ref Unsafe.As<UInt64, byte>(ref _data1[0]), VectorSize); } public SimpleBinaryOpTest__XorUInt64() { Succeeded = true; var random = new Random(); for (var i = 0; i < ElementCount; i++) { _data1[i] = (ulong)(random.Next(0, int.MaxValue)); _data2[i] = (ulong)(random.Next(0, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref _fld1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref _fld2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < ElementCount; i++) { _data1[i] = (ulong)(random.Next(0, int.MaxValue)); _data2[i] = (ulong)(random.Next(0, int.MaxValue)); } _dataTable = new SimpleBinaryOpTest__DataTable<UInt64>(_data1, _data2, new UInt64[ElementCount], VectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Avx2.Xor( Unsafe.Read<Vector256<UInt64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<UInt64>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Avx2.Xor( Avx.LoadVector256((UInt64*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((UInt64*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Avx2.Xor( Avx.LoadAlignedVector256((UInt64*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((UInt64*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Avx2).GetMethod(nameof(Avx2.Xor), new Type[] { typeof(Vector256<UInt64>), typeof(Vector256<UInt64>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<UInt64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<UInt64>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Avx2).GetMethod(nameof(Avx2.Xor), new Type[] { typeof(Vector256<UInt64>), typeof(Vector256<UInt64>) }) .Invoke(null, new object[] { Avx.LoadVector256((UInt64*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((UInt64*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Avx2).GetMethod(nameof(Avx2.Xor), new Type[] { typeof(Vector256<UInt64>), typeof(Vector256<UInt64>) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((UInt64*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((UInt64*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Avx2.Xor( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector256<UInt64>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector256<UInt64>>(_dataTable.inArray2Ptr); var result = Avx2.Xor(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var left = Avx.LoadVector256((UInt64*)(_dataTable.inArray1Ptr)); var right = Avx.LoadVector256((UInt64*)(_dataTable.inArray2Ptr)); var result = Avx2.Xor(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var left = Avx.LoadAlignedVector256((UInt64*)(_dataTable.inArray1Ptr)); var right = Avx.LoadAlignedVector256((UInt64*)(_dataTable.inArray2Ptr)); var result = Avx2.Xor(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleBinaryOpTest__XorUInt64(); var result = Avx2.Xor(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Avx2.Xor(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector256<UInt64> left, Vector256<UInt64> right, void* result, [CallerMemberName] string method = "") { UInt64[] inArray1 = new UInt64[ElementCount]; UInt64[] inArray2 = new UInt64[ElementCount]; UInt64[] outArray = new UInt64[ElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { UInt64[] inArray1 = new UInt64[ElementCount]; UInt64[] inArray2 = new UInt64[ElementCount]; UInt64[] outArray = new UInt64[ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(UInt64[] left, UInt64[] right, UInt64[] result, [CallerMemberName] string method = "") { if ((ulong)(left[0] ^ right[0]) != result[0]) { Succeeded = false; } else { for (var i = 1; i < left.Length; i++) { if ((ulong)(left[i] ^ right[i]) != result[i]) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Avx2)}.{nameof(Avx2.Xor)}<UInt64>: {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
// // PropertyDefinition.cs // // Author: // Jb Evain (jbevain@gmail.com) // // Copyright (c) 2008 - 2011 Jb Evain // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System.Text; using Mono.Collections.Generic; namespace Mono.Cecil { public sealed class PropertyDefinition : PropertyReference, IMemberDefinition, IConstantProvider { bool? has_this; ushort attributes; Collection<CustomAttribute> custom_attributes; internal MethodDefinition get_method; internal MethodDefinition set_method; internal Collection<MethodDefinition> other_methods; object constant = Mixin.NotResolved; public PropertyAttributes Attributes { get { return (PropertyAttributes) attributes; } set { attributes = (ushort) value; } } public bool HasThis { get { if (has_this.HasValue) return has_this.Value; if (GetMethod != null) return get_method.HasThis; if (SetMethod != null) return set_method.HasThis; return false; } set { has_this = value; } } public bool HasCustomAttributes { get { if (custom_attributes != null) return custom_attributes.Count > 0; return this.GetHasCustomAttributes (Module); } } public Collection<CustomAttribute> CustomAttributes { get { return custom_attributes ?? (custom_attributes = this.GetCustomAttributes (Module)); } } public MethodDefinition GetMethod { get { if (get_method != null) return get_method; InitializeMethods (); return get_method; } set { get_method = value; } } public MethodDefinition SetMethod { get { if (set_method != null) return set_method; InitializeMethods (); return set_method; } set { set_method = value; } } public bool HasOtherMethods { get { if (other_methods != null) return other_methods.Count > 0; InitializeMethods (); return !other_methods.IsNullOrEmpty (); } } public Collection<MethodDefinition> OtherMethods { get { if (other_methods != null) return other_methods; InitializeMethods (); if (other_methods != null) return other_methods; return other_methods = new Collection<MethodDefinition> (); } } public bool HasParameters { get { InitializeMethods (); if (get_method != null) return get_method.HasParameters; if (set_method != null) return set_method.HasParameters && set_method.Parameters.Count > 1; return false; } } public override Collection<ParameterDefinition> Parameters { get { InitializeMethods (); if (get_method != null) return MirrorParameters (get_method, 0); if (set_method != null) return MirrorParameters (set_method, 1); return new Collection<ParameterDefinition> (); } } static Collection<ParameterDefinition> MirrorParameters (MethodDefinition method, int bound) { var parameters = new Collection<ParameterDefinition> (); if (!method.HasParameters) return parameters; var original_parameters = method.Parameters; var end = original_parameters.Count - bound; for (int i = 0; i < end; i++) parameters.Add (original_parameters [i]); return parameters; } public bool HasConstant { get { ResolveConstant (); return constant != Mixin.NoValue; } set { if (!value) constant = Mixin.NoValue; } } public object Constant { get { return HasConstant ? constant : null; } set { constant = value; } } void ResolveConstant () { if (constant != Mixin.NotResolved) return; this.ResolveConstant (ref constant, Module); } #region PropertyAttributes public bool IsSpecialName { get { return attributes.GetAttributes ((ushort) PropertyAttributes.SpecialName); } set { attributes = attributes.SetAttributes ((ushort) PropertyAttributes.SpecialName, value); } } public bool IsRuntimeSpecialName { get { return attributes.GetAttributes ((ushort) PropertyAttributes.RTSpecialName); } set { attributes = attributes.SetAttributes ((ushort) PropertyAttributes.RTSpecialName, value); } } public bool HasDefault { get { return attributes.GetAttributes ((ushort) PropertyAttributes.HasDefault); } set { attributes = attributes.SetAttributes ((ushort) PropertyAttributes.HasDefault, value); } } #endregion public new TypeDefinition DeclaringType { get { return (TypeDefinition) base.DeclaringType; } set { base.DeclaringType = value; } } public override bool IsDefinition { get { return true; } } public override string FullName { get { var builder = new StringBuilder (); builder.Append (PropertyType.ToString ()); builder.Append (' '); builder.Append (MemberFullName ()); builder.Append ('('); if (HasParameters) { var parameters = Parameters; for (int i = 0; i < parameters.Count; i++) { if (i > 0) builder.Append (','); builder.Append (parameters [i].ParameterType.FullName); } } builder.Append (')'); return builder.ToString (); } } public PropertyDefinition (string name, PropertyAttributes attributes, TypeReference propertyType) : base (name, propertyType) { this.attributes = (ushort) attributes; this.token = new MetadataToken (TokenType.Property); } void InitializeMethods () { if (get_method != null || set_method != null) return; var module = this.Module; if (!module.HasImage ()) return; module.Read (this, (property, reader) => reader.ReadMethods (property)); } public override PropertyDefinition Resolve () { return this; } } }
#if UNITY_WINRT && !UNITY_EDITOR && !UNITY_WP8 #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 Newtonsoft.Json.Utilities; namespace Newtonsoft.Json.Serialization { /// <summary> /// Maps a JSON property to a .NET member or constructor parameter. /// </summary> public class JsonProperty { internal Required? _required; internal bool _hasExplicitDefaultValue; internal object _defaultValue; private string _propertyName; private bool _skipPropertyNameEscape; // use to cache contract during deserialization internal JsonContract PropertyContract { get; set; } /// <summary> /// Gets or sets the name of the property. /// </summary> /// <value>The name of the property.</value> public string PropertyName { get { return _propertyName; } set { _propertyName = value; CalculateSkipPropertyNameEscape(); } } private void CalculateSkipPropertyNameEscape() { if (_propertyName == null) { _skipPropertyNameEscape = false; } else { _skipPropertyNameEscape = true; foreach (char c in _propertyName) { if (!char.IsLetterOrDigit(c) && c != '_' && c != '@') { _skipPropertyNameEscape = false; break; } } } } /// <summary> /// Gets or sets the type that declared this property. /// </summary> /// <value>The type that declared this property.</value> public Type DeclaringType { get; set; } /// <summary> /// Gets or sets the order of serialization and deserialization of a member. /// </summary> /// <value>The numeric order of serialization or deserialization.</value> public int? Order { get; set; } /// <summary> /// Gets or sets the name of the underlying member or parameter. /// </summary> /// <value>The name of the underlying member or parameter.</value> public string UnderlyingName { get; set; } /// <summary> /// Gets the <see cref="IValueProvider"/> that will get and set the <see cref="JsonProperty"/> during serialization. /// </summary> /// <value>The <see cref="IValueProvider"/> that will get and set the <see cref="JsonProperty"/> during serialization.</value> public IValueProvider ValueProvider { get; set; } /// <summary> /// Gets or sets the type of the property. /// </summary> /// <value>The type of the property.</value> public Type PropertyType { get; set; } /// <summary> /// Gets or sets the <see cref="JsonConverter" /> for the property. /// If set this converter takes presidence over the contract converter for the property type. /// </summary> /// <value>The converter.</value> public JsonConverter Converter { get; set; } /// <summary> /// Gets the member converter. /// </summary> /// <value>The member converter.</value> public JsonConverter MemberConverter { get; set; } /// <summary> /// Gets a value indicating whether this <see cref="JsonProperty"/> is ignored. /// </summary> /// <value><c>true</c> if ignored; otherwise, <c>false</c>.</value> public bool Ignored { get; set; } /// <summary> /// Gets a value indicating whether this <see cref="JsonProperty"/> is readable. /// </summary> /// <value><c>true</c> if readable; otherwise, <c>false</c>.</value> public bool Readable { get; set; } /// <summary> /// Gets a value indicating whether this <see cref="JsonProperty"/> is writable. /// </summary> /// <value><c>true</c> if writable; otherwise, <c>false</c>.</value> public bool Writable { get; set; } /// <summary> /// Gets a value indicating whether this <see cref="JsonProperty"/> has a member attribute. /// </summary> /// <value><c>true</c> if has a member attribute; otherwise, <c>false</c>.</value> public bool HasMemberAttribute { get; set; } /// <summary> /// Gets the default value. /// </summary> /// <value>The default value.</value> public object DefaultValue { get { return _defaultValue; } set { _hasExplicitDefaultValue = true; _defaultValue = value; } } internal object GetResolvedDefaultValue() { if (!_hasExplicitDefaultValue && PropertyType != null) return ReflectionUtils.GetDefaultValue(PropertyType); return _defaultValue; } /// <summary> /// Gets a value indicating whether this <see cref="JsonProperty"/> is required. /// </summary> /// <value>A value indicating whether this <see cref="JsonProperty"/> is required.</value> public Required Required { get { return _required ?? Required.Default; } set { _required = value; } } /// <summary> /// Gets a value indicating whether this property preserves object references. /// </summary> /// <value> /// <c>true</c> if this instance is reference; otherwise, <c>false</c>. /// </value> public bool? IsReference { get; set; } /// <summary> /// Gets the property null value handling. /// </summary> /// <value>The null value handling.</value> public NullValueHandling? NullValueHandling { get; set; } /// <summary> /// Gets the property default value handling. /// </summary> /// <value>The default value handling.</value> public DefaultValueHandling? DefaultValueHandling { get; set; } /// <summary> /// Gets the property reference loop handling. /// </summary> /// <value>The reference loop handling.</value> public ReferenceLoopHandling? ReferenceLoopHandling { get; set; } /// <summary> /// Gets the property object creation handling. /// </summary> /// <value>The object creation handling.</value> public ObjectCreationHandling? ObjectCreationHandling { get; set; } /// <summary> /// Gets or sets the type name handling. /// </summary> /// <value>The type name handling.</value> public TypeNameHandling? TypeNameHandling { get; set; } /// <summary> /// Gets or sets a predicate used to determine whether the property should be serialize. /// </summary> /// <value>A predicate used to determine whether the property should be serialize.</value> public Predicate<object> ShouldSerialize { get; set; } /// <summary> /// Gets or sets a predicate used to determine whether the property should be serialized. /// </summary> /// <value>A predicate used to determine whether the property should be serialized.</value> public Predicate<object> GetIsSpecified { get; set; } /// <summary> /// Gets or sets an action used to set whether the property has been deserialized. /// </summary> /// <value>An action used to set whether the property has been deserialized.</value> public Action<object, object> SetIsSpecified { get; set; } /// <summary> /// Returns a <see cref="String"/> that represents this instance. /// </summary> /// <returns> /// A <see cref="String"/> that represents this instance. /// </returns> public override string ToString() { return PropertyName; } /// <summary> /// Gets or sets the converter used when serializing the property's collection items. /// </summary> /// <value>The collection's items converter.</value> public JsonConverter ItemConverter { get; set; } /// <summary> /// Gets or sets whether this property's collection items are serialized as a reference. /// </summary> /// <value>Whether this property's collection items are serialized as a reference.</value> public bool? ItemIsReference { get; set; } /// <summary> /// Gets or sets the the type name handling used when serializing the property's collection items. /// </summary> /// <value>The collection's items type name handling.</value> public TypeNameHandling? ItemTypeNameHandling { get; set; } /// <summary> /// Gets or sets the the reference loop handling used when serializing the property's collection items. /// </summary> /// <value>The collection's items reference loop handling.</value> public ReferenceLoopHandling? ItemReferenceLoopHandling { get; set; } internal void WritePropertyName(JsonWriter writer) { if (_skipPropertyNameEscape) writer.WritePropertyName(PropertyName, false); else writer.WritePropertyName(PropertyName); } } } #endif
// // Copyright (c) 2004-2017 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Layouts { using System; using System.Collections.Generic; using System.Text; using NLog.Config; /// <summary> /// A specialized layout that renders JSON-formatted events. /// </summary> [Layout("JsonLayout")] [ThreadAgnostic] [AppDomainFixedOutput] public class JsonLayout : Layout { private IJsonConverter JsonConverter { get { return _jsonConverter ?? (_jsonConverter = ConfigurationItemFactory.Default.JsonConverter); } set { _jsonConverter = value; } } private IJsonConverter _jsonConverter = null; /// <summary> /// Initializes a new instance of the <see cref="JsonLayout"/> class. /// </summary> public JsonLayout() { this.Attributes = new List<JsonAttribute>(); this.RenderEmptyObject = true; this.IncludeAllProperties = false; this.ExcludeProperties = new HashSet<string>(); } /// <summary> /// Gets the array of attributes' configurations. /// </summary> /// <docgen category='CSV Options' order='10' /> [ArrayParameter(typeof(JsonAttribute), "attribute")] public IList<JsonAttribute> Attributes { get; private set; } /// <summary> /// Gets or sets the option to suppress the extra spaces in the output json /// </summary> public bool SuppressSpaces { get; set; } /// <summary> /// Gets or sets the option to render the empty object value {} /// </summary> public bool RenderEmptyObject { get; set; } /// <summary> /// Gets or sets a value indicating whether to include contents of the <see cref="MappedDiagnosticsContext"/> dictionary. /// </summary> public bool IncludeMdc { get; set; } #if !SILVERLIGHT /// <summary> /// Gets or sets a value indicating whether to include contents of the <see cref="MappedDiagnosticsLogicalContext"/> dictionary. /// </summary> public bool IncludeMdlc { get; set; } #endif /// <summary> /// Gets or sets the option to include all properties from the log events /// </summary> public bool IncludeAllProperties { get; set; } /// <summary> /// List of property names to exclude when <see cref="IncludeAllProperties"/> is true /// </summary> #if NET3_5 public HashSet<string> ExcludeProperties { get; set; } #else public ISet<string> ExcludeProperties { get; set; } #endif /// <summary> /// Initializes the layout. /// </summary> protected override void InitializeLayout() { base.InitializeLayout(); if (IncludeMdc) { base.ThreadAgnostic = false; } #if !SILVERLIGHT if (IncludeMdlc) { base.ThreadAgnostic = false; } #endif } /// <summary> /// Closes the layout. /// </summary> protected override void CloseLayout() { JsonConverter = null; base.CloseLayout(); } /// <summary> /// Formats the log event as a JSON document for writing. /// </summary> /// <param name="logEvent">The logging event.</param> /// <param name="target"><see cref="StringBuilder"/> for the result</param> protected override void RenderFormattedMessage(LogEventInfo logEvent, StringBuilder target) { int orgLength = target.Length; RenderJsonFormattedMessage(logEvent, target); if (target.Length == orgLength && RenderEmptyObject) { target.Append(SuppressSpaces ? "{}" : "{ }"); } } /// <summary> /// Formats the log event as a JSON document for writing. /// </summary> /// <param name="logEvent">The log event to be formatted.</param> /// <returns>A JSON string representation of the log event.</returns> protected override string GetFormattedMessage(LogEventInfo logEvent) { return RenderAllocateBuilder(logEvent); } private void RenderJsonFormattedMessage(LogEventInfo logEvent, StringBuilder sb) { int orgLength = sb.Length; //Memory profiling pointed out that using a foreach-loop was allocating //an Enumerator. Switching to a for-loop avoids the memory allocation. for (int i = 0; i < this.Attributes.Count; i++) { var attrib = this.Attributes[i]; int beforeAttribLength = sb.Length; if (!RenderAppendJsonPropertyValue(attrib, logEvent, false, sb, sb.Length == orgLength)) { sb.Length = beforeAttribLength; } } if (this.IncludeMdc) { foreach (string key in MappedDiagnosticsContext.GetNames()) { if (string.IsNullOrEmpty(key)) continue; object propertyValue = MappedDiagnosticsContext.GetObject(key); AppendJsonPropertyValue(key, propertyValue, sb, sb.Length == orgLength); } } #if !SILVERLIGHT if (this.IncludeMdlc) { foreach (string key in MappedDiagnosticsLogicalContext.GetNames()) { if (string.IsNullOrEmpty(key)) continue; object propertyValue = MappedDiagnosticsLogicalContext.GetObject(key); AppendJsonPropertyValue(key, propertyValue, sb, sb.Length == orgLength); } } #endif if (this.IncludeAllProperties && logEvent.HasProperties) { foreach (var prop in logEvent.Properties) { //Determine property name string propName = Internal.XmlHelper.XmlConvertToString(prop.Key ?? string.Empty); if (string.IsNullOrEmpty(propName)) continue; //Skips properties in the ExcludeProperties list if (this.ExcludeProperties.Contains(propName)) continue; AppendJsonPropertyValue(propName, prop.Value, sb, sb.Length == orgLength); } } if (sb.Length > orgLength) CompleteJsonMessage(sb); } private void BeginJsonProperty(StringBuilder sb, string propName, bool beginJsonMessage) { if (beginJsonMessage) { sb.Append(SuppressSpaces ? "{" : "{ "); } else { sb.Append(','); if (!this.SuppressSpaces) sb.Append(' '); } sb.Append('"'); sb.Append(propName); sb.Append('"'); sb.Append(':'); if (!this.SuppressSpaces) sb.Append(' '); } private void CompleteJsonMessage(StringBuilder sb) { sb.Append(SuppressSpaces ? "}" : " }"); } private void AppendJsonPropertyValue(string propName, object propertyValue, StringBuilder sb, bool beginJsonMessage) { BeginJsonProperty(sb, propName, beginJsonMessage); JsonConverter.SerializeObject(propertyValue, sb); } private bool RenderAppendJsonPropertyValue(JsonAttribute attrib, LogEventInfo logEvent, bool renderEmptyValue, StringBuilder sb, bool beginJsonMessage) { BeginJsonProperty(sb, attrib.Name, beginJsonMessage); if (attrib.Encode) { // "\"{0}\":{1}\"{2}\"" sb.Append('"'); } int beforeValueLength = sb.Length; attrib.LayoutWrapper.RenderAppendBuilder(logEvent, sb); if (!renderEmptyValue && beforeValueLength == sb.Length) { return false; } if (attrib.Encode) { sb.Append('"'); } return true; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Threading.Tasks; using Meekys.Common.Extensions; using Meekys.OData.Expressions.TokenParsers; namespace Meekys.OData.Expressions { public static class FilterExpressionBuilder { public static Expression<Func<T, bool>> Build<T>(string filter) { using (var builder = new FilterExpressionBuilder<T>(filter)) { return builder.BuildBoolExpression(); } } } [SuppressMessage("Microsoft.StyleCop.CSharp.MaintainabilityRules", "SA1402:FileMayOnlyContainASingleClass", Justification = "Generic implementation of same class")] public class FilterExpressionBuilder<T> : IDisposable { private const string NoToken = "{No Token}"; private static readonly Dictionary<string, Func<Expression, Expression, BinaryExpression>> LogicalOrMap = new Dictionary<string, Func<Expression, Expression, BinaryExpression>>(StringComparer.OrdinalIgnoreCase) { { "or", Expression.OrElse } }; private static readonly Dictionary<string, Func<Expression, Expression, BinaryExpression>> LogicalAndMap = new Dictionary<string, Func<Expression, Expression, BinaryExpression>>(StringComparer.OrdinalIgnoreCase) { { "and", Expression.AndAlso } }; private static readonly Dictionary<string, Func<Expression, Expression, BinaryExpression>> LogicalComparisonMap = new Dictionary<string, Func<Expression, Expression, BinaryExpression>>(StringComparer.OrdinalIgnoreCase) { { "eq", Expression.Equal }, { "ne", Expression.NotEqual }, { "gt", Expression.GreaterThan }, { "ge", Expression.GreaterThanOrEqual }, { "lt", Expression.LessThan }, { "le", Expression.LessThanOrEqual } }; private static readonly Dictionary<string, Func<Expression, Expression, BinaryExpression>> AdditiveMap = new Dictionary<string, Func<Expression, Expression, BinaryExpression>>(StringComparer.OrdinalIgnoreCase) { { "add", Expression.Add }, { "sub", Expression.Subtract } }; private static readonly Dictionary<string, Func<Expression, Expression, BinaryExpression>> MultiplicativeMap = new Dictionary<string, Func<Expression, Expression, BinaryExpression>>(StringComparer.OrdinalIgnoreCase) { { "div", Expression.Divide }, { "mul", Expression.Multiply } }; private static readonly Dictionary<string, Func<Expression, UnaryExpression>> UnaryMap = new Dictionary<string, Func<Expression, UnaryExpression>>(StringComparer.OrdinalIgnoreCase) { { "not", Expression.Not } }; private static readonly Type[] CastTypes = new[] { typeof(double), typeof(float), typeof(decimal), typeof(long), typeof(int), typeof(short), typeof(byte), typeof(bool) }; private static readonly Type[] ConstantParsers = new[] { typeof(NullTokenParser), typeof(StringTokenParser), typeof(DateTimeTokenParser), //// typeof(TimeTokenParser), //// typeof(DateTimeOffsetTokenParser), typeof(BooleanTokenParser), typeof(DoubleTokenParser), typeof(FloatTokenParser), typeof(DecimalTokenParser), typeof(ByteTokenParser), //// typeof(SByteTokenParser), typeof(Int16TokenParser), typeof(Int32TokenParser), typeof(Int64TokenParser), typeof(GuidTokenParser), typeof(BinaryTokenParser) }; private readonly int _maxDepth; private BufferedEnumerator<FilterToken> _tokens; private ParameterExpression _parameter; private List<ITokenParser> _constantParsers; private bool _disposed; public int MaxDepth { get { return _maxDepth; } } public int RecursionDepth { get; set; } public FilterExpressionBuilder(string filter) { _maxDepth = 100; InitConstantParsers(); var tokenizer = new FilterTokeniser(filter); _tokens = new BufferedEnumerator<FilterToken>(tokenizer.Tokens.GetEnumerator(), 1); _parameter = Expression.Parameter(typeof(T), "item"); if (!_tokens.MoveNext()) throw new ArgumentException("Expected expression", nameof(filter)); } public Expression<Func<T, bool>> BuildBoolExpression() { var expression = BuildExpression(); if (_tokens.Current != null) throw new FilterExpressionException($"Unexpected token: {_tokens.Current}"); if (expression.Type != typeof(bool)) throw new FilterExpressionException("Expected boolean expression"); return Expression.Lambda<Func<T, bool>>(expression, _parameter); } private Expression BuildExpression() { using (RecurseIn()) { return BuildLogicalOr(); } } private bool CurrentOperator(Dictionary<string, Func<Expression, Expression, BinaryExpression>> map, out Func<Expression, Expression, BinaryExpression> op) { op = null; if (_tokens.Current == null) return false; return map.TryGetValue(_tokens.Current.Token, out op); } private bool CurrentOperator(Dictionary<string, Func<Expression, UnaryExpression>> map, out Func<Expression, UnaryExpression> op) { op = null; if (_tokens.Current == null) return false; return map.TryGetValue(_tokens.Current.Token, out op); } private bool CheckToken(string expected) { var found = _tokens.Current == expected; if (found) _tokens.MoveNext(); return found; } private void ExpectToken() { if (!_tokens.MoveNext()) throw new FilterExpressionException($"Expected token after {(_tokens.HasPrevious() ? _tokens.Previous().ToString() : NoToken)}"); } private void ExpectToken(string expected) { if (_tokens.Current != expected) { if (_tokens.Current != null) throw new FilterExpressionException($"Expected {expected} but got {_tokens.Current}"); else if (_tokens.HasPrevious()) throw new FilterExpressionException($"Expected {expected} but got {NoToken} after {_tokens.Previous()}"); else throw new FilterExpressionException($"Expected {expected} but got {NoToken}"); } _tokens.MoveNext(); } private void CastParameters(ref Expression left, ref Expression right) { var leftType = Nullable.GetUnderlyingType(left.Type) ?? left.Type; var rightType = Nullable.GetUnderlyingType(right.Type) ?? right.Type; if (!leftType.In(CastTypes) || !rightType.In(CastTypes)) return; if (TryCastParameters<double?>(ref left, ref right)) return; if (TryCastParameters<double>(ref left, ref right)) return; if (TryCastParameters<float?>(ref left, ref right)) return; if (TryCastParameters<float>(ref left, ref right)) return; if (TryCastParameters<decimal?>(ref left, ref right)) return; if (TryCastParameters<decimal>(ref left, ref right)) return; if (TryCastParameters<long?>(ref left, ref right)) return; if (TryCastParameters<long>(ref left, ref right)) return; if (TryCastParameters<int?>(ref left, ref right)) return; if (TryCastParameters<int>(ref left, ref right)) return; if (TryCastParameters<short?, int?>(ref left, ref right)) return; if (TryCastParameters<short, int>(ref left, ref right)) return; if (TryCastParameters<byte?, int?>(ref left, ref right)) return; if (TryCastParameters<byte, int>(ref left, ref right)) return; if (TryCastParameters<bool?>(ref left, ref right)) return; if (TryCastParameters<bool>(ref left, ref right)) return; } private bool TryCastParameters<TParam>(ref Expression left, ref Expression right) { return TryCastParameters<TParam, TParam>(ref left, ref right); } private bool TryCastParameters<TCastFrom, TCastTo>(ref Expression left, ref Expression right) { if (left.Type != typeof(TCastFrom) && right.Type != typeof(TCastFrom)) return false; if (right.Type != typeof(TCastTo)) right = CastExpressionBuilder.Build<TCastTo>(right); if (left.Type != typeof(TCastTo)) left = CastExpressionBuilder.Build<TCastTo>(left); return true; } private Expression BuildBinaryExpression(Func<Expression> leftOrRightFunc, Dictionary<string, Func<Expression, Expression, BinaryExpression>> operatorMap) { using (RecurseIn()) { var left = leftOrRightFunc(); Func<Expression, Expression, BinaryExpression> op; while (CurrentOperator(operatorMap, out op)) { ExpectToken(); var right = leftOrRightFunc(); CastParameters(ref left, ref right); left = op(left, right); } return left; } } private Expression BuildUnaryExpression(Func<Expression> rightFunc, Dictionary<string, Func<Expression, UnaryExpression>> operatorMap) { using (RecurseIn()) { Func<Expression, UnaryExpression> op; if (CurrentOperator(operatorMap, out op)) { ExpectToken(); var right = BuildUnaryExpression(rightFunc, operatorMap); return op(right); } return rightFunc(); } } private Expression BuildLogicalOr() { return BuildBinaryExpression(BuildLogicalAnd, LogicalOrMap); } private Expression BuildLogicalAnd() { return BuildBinaryExpression(BuildComparison, LogicalAndMap); } private Expression BuildComparison() { return BuildBinaryExpression(BuildAdditive, LogicalComparisonMap); } private Expression BuildAdditive() { return BuildBinaryExpression(BuildMultiplicative, AdditiveMap); } private Expression BuildMultiplicative() { return BuildBinaryExpression(BuildUnary, MultiplicativeMap); } private Expression BuildUnary() { return BuildUnaryExpression(BuildPrimaryExpression, UnaryMap); } private Expression BuildPrimaryExpression() { using (RecurseIn()) { return BuildParenExpression() ?? BuildFunctionExpression() ?? BuildMemberExpression() ?? BuildConstantExpression() ?? BuildUnknownToken(); } } private Expression BuildParenExpression() { if (!CheckToken(ExpressionConstants.OpenParen)) return null; var expression = BuildExpression(); ExpectToken(ExpressionConstants.CloseParen); return expression; } private Expression BuildFunctionExpression() { FilterToken peekNext; if (!_tokens.TryPeek(out peekNext) || peekNext != ExpressionConstants.OpenParen) return null; var functionName = _tokens.Current; _tokens.MoveNext(); var arguments = BuildFunctionArguments().ToArray(); ExpectToken(ExpressionConstants.CloseParen); return FunctionExpressionBuilder.Build(functionName, arguments); } private IEnumerable<Expression> BuildFunctionArguments() { ExpectToken(ExpressionConstants.OpenParen); if (_tokens.Current == ExpressionConstants.CloseParen) yield break; do { yield return BuildExpression(); } while (CheckToken(ExpressionConstants.Comma)); } private Expression BuildMemberExpression() { if (_tokens.Current == null) return null; string propertyName = _tokens.Current; var property = typeof(T).GetTypeInfo().GetProperty(propertyName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase); if (property == null) return null; _tokens.MoveNext(); return Expression.Property(_parameter, property); } private Expression BuildConstantExpression() { var expression = _constantParsers .Select(x => x.Parse(_tokens.Current)) .FirstOrDefault(x => x != null); if (expression != null) _tokens.MoveNext(); return expression; } private void InitConstantParsers() { if (_constantParsers != null) return; _constantParsers = ConstantParsers .Select(x => (ITokenParser)Activator.CreateInstance(x)) .ToList(); } private Expression BuildUnknownToken() { throw new FilterExpressionException($"Unrecognised token: {_tokens.Current}"); } private Recurse RecurseIn() { return new Recurse(this); } protected virtual void Dispose(bool disposing) { if (_disposed) return; if (disposing) { _tokens.Dispose(); } _disposed = true; } public void Dispose() { // Do not change this code. Put cleanup code in Dispose(bool disposing) above. Dispose(true); GC.SuppressFinalize(this); } private class Recurse : IDisposable { private FilterExpressionBuilder<T> _owner; public Recurse(FilterExpressionBuilder<T> owner) { _owner = owner; _owner.RecursionDepth++; if (_owner.RecursionDepth > _owner.MaxDepth) throw new InvalidOperationException("Expression depth is too deep"); } public void Dispose() { _owner.RecursionDepth--; } } } }
//--------------------------------------------------------------------- // <copyright file="DbExpressionVisitor_TResultType.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // // @owner [....] // @backupOwner [....] //--------------------------------------------------------------------- using System.Collections.Generic; using System.Data.Metadata.Edm; namespace System.Data.Common.CommandTrees { /// <summary> /// The expression visitor pattern abstract base class that should be implemented by visitors that return a result value of a specific type. /// </summary> /// <typeparam name="TResultType">The type of the result value produced by the visitor.</typeparam> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Db")] public abstract class DbExpressionVisitor<TResultType> { /// <summary> /// Called when an expression of an otherwise unrecognized type is encountered. /// </summary> /// <param name="expression">The expression.</param> public abstract TResultType Visit(DbExpression expression); /// <summary> /// Typed visitor pattern method for DbAndExpression. /// </summary> /// <param name="expression">The DbAndExpression that is being visited.</param> /// <returns>An instance of TResultType.</returns> public abstract TResultType Visit(DbAndExpression expression); /// <summary> /// Typed visitor pattern method for DbApplyExpression. /// </summary> /// <param name="expression">The DbApplyExpression that is being visited.</param> /// <returns>An instance of TResultType.</returns> public abstract TResultType Visit(DbApplyExpression expression); /// <summary> /// Typed visitor pattern method for DbArithmeticExpression. /// </summary> /// <param name="expression">The DbArithmeticExpression that is being visited.</param> /// <returns>An instance of TResultType.</returns> public abstract TResultType Visit(DbArithmeticExpression expression); /// <summary> /// Typed visitor pattern method for DbCaseExpression. /// </summary> /// <param name="expression">The DbCaseExpression that is being visited.</param> /// <returns>An instance of TResultType.</returns> public abstract TResultType Visit(DbCaseExpression expression); /// <summary> /// Typed visitor pattern method for DbCastExpression. /// </summary> /// <param name="expression">The DbCastExpression that is being visited.</param> /// <returns>An instance of TResultType.</returns> public abstract TResultType Visit(DbCastExpression expression); /// <summary> /// Typed visitor pattern method for DbComparisonExpression. /// </summary> /// <param name="expression">The DbComparisonExpression that is being visited.</param> /// <returns>An instance of TResultType.</returns> public abstract TResultType Visit(DbComparisonExpression expression); /// <summary> /// Typed visitor pattern method for DbConstantExpression. /// </summary> /// <param name="expression">The DbConstantExpression that is being visited.</param> /// <returns>An instance of TResultType.</returns> public abstract TResultType Visit(DbConstantExpression expression); /// <summary> /// Typed visitor pattern method for DbCrossJoinExpression. /// </summary> /// <param name="expression">The DbCrossJoinExpression that is being visited.</param> /// <returns>An instance of TResultType.</returns> public abstract TResultType Visit(DbCrossJoinExpression expression); /// <summary> /// Visitor pattern method for DbDerefExpression. /// </summary> /// <param name="expression">The DbDerefExpression that is being visited.</param> /// <returns>An instance of TResultType.</returns> public abstract TResultType Visit(DbDerefExpression expression); /// <summary> /// Typed visitor pattern method for DbDistinctExpression. /// </summary> /// <param name="expression">The DbDistinctExpression that is being visited.</param> /// <returns>An instance of TResultType.</returns> public abstract TResultType Visit(DbDistinctExpression expression); /// <summary> /// Typed visitor pattern method for DbElementExpression. /// </summary> /// <param name="expression">The DbElementExpression that is being visited.</param> /// <returns>An instance of TResultType.</returns> public abstract TResultType Visit(DbElementExpression expression); /// <summary> /// Typed visitor pattern method for DbExceptExpression. /// </summary> /// <param name="expression">The DbExceptExpression that is being visited.</param> /// <returns>An instance of TResultType.</returns> public abstract TResultType Visit(DbExceptExpression expression); /// <summary> /// Typed visitor pattern method for DbFilterExpression. /// </summary> /// <param name="expression">The DbFilterExpression that is being visited.</param> /// <returns>An instance of TResultType.</returns> public abstract TResultType Visit(DbFilterExpression expression); /// <summary> /// Visitor pattern method for DbFunctionExpression /// </summary> /// <param name="expression">The DbFunctionExpression that is being visited.</param> /// <returns>An instance of TResultType.</returns> public abstract TResultType Visit(DbFunctionExpression expression); /// <summary> /// Visitor pattern method for DbEntityRefExpression. /// </summary> /// <param name="expression">The DbEntityRefExpression that is being visited.</param> /// <returns>An instance of TResultType.</returns> public abstract TResultType Visit(DbEntityRefExpression expression); /// <summary> /// Visitor pattern method for DbRefKeyExpression. /// </summary> /// <param name="expression">The DbRefKeyExpression that is being visited.</param> /// <returns>An instance of TResultType.</returns> public abstract TResultType Visit(DbRefKeyExpression expression); /// <summary> /// Typed visitor pattern method for DbGroupByExpression. /// </summary> /// <param name="expression">The DbGroupByExpression that is being visited.</param> /// <returns>An instance of TResultType.</returns> public abstract TResultType Visit(DbGroupByExpression expression); /// <summary> /// Typed visitor pattern method for DbIntersectExpression. /// </summary> /// <param name="expression">The DbIntersectExpression that is being visited.</param> /// <returns>An instance of TResultType.</returns> public abstract TResultType Visit(DbIntersectExpression expression); /// <summary> /// Typed visitor pattern method for DbIsEmptyExpression. /// </summary> /// <param name="expression">The DbIsEmptyExpression that is being visited.</param> /// <returns>An instance of TResultType.</returns> public abstract TResultType Visit(DbIsEmptyExpression expression); /// <summary> /// Typed visitor pattern method for DbIsNullExpression. /// </summary> /// <param name="expression">The DbIsNullExpression that is being visited.</param> /// <returns>An instance of TResultType.</returns> public abstract TResultType Visit(DbIsNullExpression expression); /// <summary> /// Typed visitor pattern method for DbIsOfExpression. /// </summary> /// <param name="expression">The DbIsOfExpression that is being visited.</param> /// <returns>An instance of TResultType.</returns> public abstract TResultType Visit(DbIsOfExpression expression); /// <summary> /// Typed visitor pattern method for DbJoinExpression. /// </summary> /// <param name="expression">The DbJoinExpression that is being visited.</param> /// <returns>An instance of TResultType.</returns> public abstract TResultType Visit(DbJoinExpression expression); /// <summary> /// Visitor pattern method for DbLambdaExpression. /// </summary> /// <param name="expression">The DbLambdaExpression that is being visited.</param> /// <returns>An instance of TResultType.</returns> public virtual TResultType Visit(DbLambdaExpression expression) { throw EntityUtil.NotSupported(); } /// <summary> /// Visitor pattern method for DbLikeExpression. /// </summary> /// <param name="expression">The DbLikeExpression that is being visited.</param> /// <returns>An instance of TResultType.</returns> public abstract TResultType Visit(DbLikeExpression expression); /// <summary> /// Visitor pattern method for DbLimitExpression. /// </summary> /// <param name="expression">The DbLimitExpression that is being visited.</param> /// <returns>An instance of TResultType.</returns> public abstract TResultType Visit(DbLimitExpression expression); #if METHOD_EXPRESSION /// <summary> /// Typed visitor pattern method for MethodExpression. /// </summary> /// <param name="expression">The Expression that is being visited.</param> /// <returns>An instance of TResultType.</returns> public abstract TResultType Visit(MethodExpression expression); #endif /// <summary> /// Typed visitor pattern method for DbNewInstanceExpression. /// </summary> /// <param name="expression">The DbNewInstanceExpression that is being visited.</param> /// <returns>An instance of TResultType.</returns> public abstract TResultType Visit(DbNewInstanceExpression expression); /// <summary> /// Typed visitor pattern method for DbNotExpression. /// </summary> /// <param name="expression">The DbNotExpression that is being visited.</param> /// <returns>An instance of TResultType.</returns> public abstract TResultType Visit(DbNotExpression expression); /// <summary> /// Typed visitor pattern method for DbNullExpression. /// </summary> /// <param name="expression">The DbNullExpression that is being visited.</param> /// <returns>An instance of TResultType.</returns> public abstract TResultType Visit(DbNullExpression expression); /// <summary> /// Typed visitor pattern method for DbOfTypeExpression. /// </summary> /// <param name="expression">The DbOfTypeExpression that is being visited.</param> /// <returns>An instance of TResultType.</returns> public abstract TResultType Visit(DbOfTypeExpression expression); /// <summary> /// Typed visitor pattern method for DbOrExpression. /// </summary> /// <param name="expression">The DbOrExpression that is being visited.</param> /// <returns>An instance of TResultType.</returns> public abstract TResultType Visit(DbOrExpression expression); /// <summary> /// Typed visitor pattern method for DbParameterReferenceExpression. /// </summary> /// <param name="expression">The DbParameterReferenceExpression that is being visited.</param> /// <returns>An instance of TResultType.</returns> public abstract TResultType Visit(DbParameterReferenceExpression expression); /// <summary> /// Typed visitor pattern method for DbProjectExpression. /// </summary> /// <param name="expression">The DbProjectExpression that is being visited.</param> /// <returns>An instance of TResultType.</returns> public abstract TResultType Visit(DbProjectExpression expression); /// <summary> /// Typed visitor pattern method for DbPropertyExpression. /// </summary> /// <param name="expression">The DbPropertyExpression that is being visited.</param> /// <returns>An instance of TResultType.</returns> public abstract TResultType Visit(DbPropertyExpression expression); /// <summary> /// Typed visitor pattern method for DbQuantifierExpression. /// </summary> /// <param name="expression">The DbQuantifierExpression that is being visited.</param> /// <returns>An instance of TResultType.</returns> public abstract TResultType Visit(DbQuantifierExpression expression); /// <summary> /// Typed visitor pattern method for DbRefExpression. /// </summary> /// <param name="expression">The DbRefExpression that is being visited.</param> /// <returns>An instance of TResultType.</returns> public abstract TResultType Visit(DbRefExpression expression); /// <summary> /// Typed visitor pattern method for DbRelationshipNavigationExpression. /// </summary> /// <param name="expression">The DbRelationshipNavigationExpression that is being visited.</param> /// <returns>An instance of TResultType.</returns> public abstract TResultType Visit(DbRelationshipNavigationExpression expression); /// <summary> /// Typed visitor pattern method for DbScanExpression. /// </summary> /// <param name="expression">The DbScanExpression that is being visited.</param> /// <returns>An instance of TResultType.</returns> public abstract TResultType Visit(DbScanExpression expression); /// <summary> /// Typed visitor pattern method for DbSortExpression. /// </summary> /// <param name="expression">The DbSortExpression that is being visited.</param> /// <returns>An instance of TResultType.</returns> public abstract TResultType Visit(DbSortExpression expression); /// <summary> /// Typed visitor pattern method for DbSkipExpression. /// </summary> /// <param name="expression">The DbSkipExpression that is being visited.</param> /// <returns>An instance of TResultType.</returns> public abstract TResultType Visit(DbSkipExpression expression); /// <summary> /// Typed visitor pattern method for DbTreatExpression. /// </summary> /// <param name="expression">The DbTreatExpression that is being visited.</param> /// <returns>An instance of TResultType.</returns> public abstract TResultType Visit(DbTreatExpression expression); /// <summary> /// Typed visitor pattern method for DbUnionAllExpression. /// </summary> /// <param name="expression">The DbUnionAllExpression that is being visited.</param> /// <returns>An instance of TResultType.</returns> public abstract TResultType Visit(DbUnionAllExpression expression); /// <summary> /// Typed visitor pattern method for DbVariableReferenceExpression. /// </summary> /// <param name="expression">The DbVariableReferenceExpression that is being visited.</param> /// <returns>An instance of TResultType.</returns> public abstract TResultType Visit(DbVariableReferenceExpression expression); } }
using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using Telligent.Evolution.Extensibility.Api.Entities.Version1; using Telligent.Evolution.Extensibility.Caching.Version1; using Telligent.Evolution.Extensions.SharePoint.Client.Api; using Telligent.Evolution.Extensions.SharePoint.Client.Exceptions; using Telligent.Evolution.Extensions.SharePoint.Components.Data.Log; namespace Telligent.Evolution.Extensions.SharePoint.Client.InternalApi { internal interface IListDataService : ICacheable { void AddUpdate(ListBase list); ListBase Get(Guid id); ListBase Get(string applicationKey, int groupId); List<ListBase> List(int groupId); List<ListBase> List(int groupId, Guid typeId); List<ListBase> List(Guid typeId); void Delete(Guid id); PagedList<ListBase> ListsToReindex(Guid applicationTypeId, int pageSize, int pageIndex = 0); void UpdateIndexingStatus(Guid[] ids, bool isIndexed); } internal class SPListDataService : IListDataService { private readonly ICacheService cacheService; private readonly IApplicationKeyValidationService applicationKeyValidator; public SPListDataService(IApplicationKeyValidationService applicationKeyValidator, ICacheService cacheService) { this.applicationKeyValidator = applicationKeyValidator; this.cacheService = cacheService; } public SPListDataService() : this(ServiceLocator.Get<IApplicationKeyValidationService>(), ServiceLocator.Get<ICacheService>()) { } #region ICacheService private TimeSpan cacheTimeOut = TimeSpan.FromSeconds(15); public TimeSpan CacheTimeOut { get { return cacheTimeOut; } set { cacheTimeOut = value; } } #endregion public void AddUpdate(ListBase list) { list.Validate(); // Make ApplicationKey valid and unique if (!string.IsNullOrEmpty(list.ApplicationKey)) { int groupId = list.GroupId; list.ApplicationKey = applicationKeyValidator.MakeValid(list.ApplicationKey.ToLowerInvariant(), applicationKey => { // List is duplicate when there is another list with the same application key but different Id var anotherList = Get(applicationKey, groupId); return anotherList != null && anotherList.Id != Guid.Empty && anotherList.Id != list.Id; }); } try { using (var connection = DataHelpers.GetSqlConnection()) { using (var command = DataHelpers.CreateSprocCommand("[te_SharePoint_List_AddUpdate]", connection)) { command.Parameters.Add("@ApplicationId", SqlDbType.UniqueIdentifier).Value = list.Id; command.Parameters.Add("@ApplicationKey", SqlDbType.NVarChar, 256).Value = list.ApplicationKey; command.Parameters.Add("@TypeId", SqlDbType.UniqueIdentifier).Value = list.TypeId; command.Parameters.Add("@GroupId", SqlDbType.Int).Value = list.GroupId; command.Parameters.Add("@SPWebUrl", SqlDbType.NVarChar, 256).Value = list.SPWebUrl; command.Parameters.Add("@ViewId", SqlDbType.UniqueIdentifier).Value = list.ViewId; connection.Open(); command.ExecuteNonQuery(); connection.Close(); } } // Clear Cache cacheService.RemoveByTags(new[] { GetTagId(list.Id) }, CacheScope.Context | CacheScope.Process); } catch (Exception ex) { string message = string.Format("An exception of type {0} occurred in the SPListDataService.AddUpdate() method. The exception message is: {1}", ex.GetType(), ex.Message); SPLog.DataProvider(ex, message); throw new AddLibraryException(ex.Message, list.SPWebUrl, list.Id, list.GroupId); } } public ListBase Get(Guid id) { var cacheId = GetCacheId(id); var listBase = (ListBase)cacheService.Get(cacheId, CacheScope.Context | CacheScope.Process); if (listBase != null) return listBase; try { using (var connection = DataHelpers.GetSqlConnection()) { using (var command = DataHelpers.CreateSprocCommand("[te_SharePoint_List_Get]", connection)) { command.Parameters.Add("@ApplicationId", SqlDbType.UniqueIdentifier).Value = id; connection.Open(); using (var reader = command.ExecuteReader(CommandBehavior.SingleRow | CommandBehavior.CloseConnection)) { if (reader.HasRows && reader.Read()) { listBase = GetListBase(reader); PutInCache(listBase); } } } } } catch (Exception ex) { var message = string.Format("An exception of type {0} occurred in the SPListDataService.Get() method for ApplicationId: {1}. The exception message is: {2}", ex.GetType(), id, ex.Message); SPLog.DataProvider(ex, message); throw new SPDataException(ex.Message, ex.InnerException); } return listBase; } public ListBase Get(string applicationKey, int groupId) { var cacheId = GetCacheId(groupId, applicationKey); var listBase = (ListBase)cacheService.Get(cacheId, CacheScope.Context | CacheScope.Process); if (listBase != null) return listBase; try { using (var connection = DataHelpers.GetSqlConnection()) { using (var command = DataHelpers.CreateSprocCommand("[te_SharePoint_List_GetByApplicationKey]", connection)) { command.Parameters.Add("@ApplicationKey", SqlDbType.NVarChar, 256).Value = applicationKey; command.Parameters.Add("@GroupId", SqlDbType.Int).Value = groupId; connection.Open(); using (var reader = command.ExecuteReader(CommandBehavior.SingleRow | CommandBehavior.CloseConnection)) { if (reader.Read()) { listBase = GetListBase(reader); PutInCache(listBase); } } } } } catch (Exception ex) { var message = string.Format("An exception of type {0} occurred in the SPListDataService.Get() method for ApplicationKey: {1}, GroupId: {2}. The exception message is: {3}", ex.GetType(), applicationKey, groupId, ex.Message); SPLog.DataProvider(ex, message); throw new SPDataException(ex.Message, ex.InnerException); } return listBase; } public List<ListBase> List(int groupId) { var listCollection = new List<ListBase>(); try { using (var connection = DataHelpers.GetSqlConnection()) { using (var command = DataHelpers.CreateSprocCommand("[te_SharePoint_List_ListByGroupId]", connection)) { command.Parameters.Add("@GroupId", SqlDbType.Int).Value = groupId; connection.Open(); using (var reader = command.ExecuteReader()) { while (reader.Read()) { var listBase = GetListBase(reader); PutInCache(listBase); listCollection.Add(listBase); } } connection.Close(); } } } catch (Exception ex) { var message = string.Format("An exception of type {0} occurred in the SPListDataService.List() method for GroupId: {1}. The exception message is: {2}", ex.GetType(), groupId, ex.Message); SPLog.DataProvider(ex, message); throw new SPDataException(message, ex); } return listCollection; } public List<ListBase> List(int groupId, Guid typeId) { var listCollection = new List<ListBase>(); try { using (var connection = DataHelpers.GetSqlConnection()) { using (var command = DataHelpers.CreateSprocCommand("[te_SharePoint_List_ListByGroupIdTypeId]", connection)) { command.Parameters.Add("@GroupId", SqlDbType.Int).Value = groupId; command.Parameters.Add("@TypeId", SqlDbType.UniqueIdentifier).Value = typeId; connection.Open(); using (var reader = command.ExecuteReader()) { while (reader.Read()) { var listBase = GetListBase(reader); PutInCache(listBase); listCollection.Add(listBase); } } connection.Close(); } } } catch (Exception ex) { var message = string.Format("An exception of type {0} occurred in the listDataService.List() method for GroupId: {1} and ApplicationTypeId: {2}. The exception message is: {3}", ex.GetType(), groupId, typeId, ex.Message); SPLog.DataProvider(ex, message); throw new SPDataException(message, ex); } return listCollection; } public List<ListBase> List(Guid typeId) { var listCollection = new List<ListBase>(); try { using (var connection = DataHelpers.GetSqlConnection()) { using (var command = DataHelpers.CreateSprocCommand("[te_SharePoint_List_ListByTypeId]", connection)) { command.Parameters.Add("@TypeId", SqlDbType.UniqueIdentifier).Value = typeId; connection.Open(); using (var reader = command.ExecuteReader()) { while (reader.Read()) { var listBase = GetListBase(reader); PutInCache(listBase); listCollection.Add(listBase); } } connection.Close(); } } } catch (Exception ex) { var message = string.Format("An exception of type {0} occurred in the SPListDataService.List() method for ApplicationTypeId: {1}. The exception message is: {2}", ex.GetType(), typeId, ex.Message); SPLog.DataProvider(ex, message); throw new SPDataException(message, ex); } return listCollection; } public void Delete(Guid id) { try { using (var connection = DataHelpers.GetSqlConnection()) { using (var command = DataHelpers.CreateSprocCommand("[te_SharePoint_List_Delete]", connection)) { command.Parameters.Add("@ApplicationId", SqlDbType.UniqueIdentifier).Value = id; connection.Open(); command.ExecuteNonQuery(); connection.Close(); } } cacheService.RemoveByTags(new[] { GetTagId(id) }, CacheScope.Context | CacheScope.Process); } catch (Exception ex) { var message = string.Format("An exception of type {0} occurred in the SPListDataService.Delete() method for ApplicationId: {1}. The exception message is: {2}", ex.GetType(), id, ex.Message); SPLog.DataProvider(ex, message); throw new SPDataException(message, ex); } } public PagedList<ListBase> ListsToReindex(Guid applicationTypeId, int pageSize, int pageIndex = 0) { var listCollection = new List<ListBase>(); int totalCount; try { using (var connection = DataHelpers.GetSqlConnection()) { using (var command = DataHelpers.CreateSprocCommand("[te_SharePoint_List_GetToReindex]", connection)) { command.Parameters.Add("@TypeId", SqlDbType.UniqueIdentifier).Value = applicationTypeId; command.Parameters.Add("@PagingBegin", SqlDbType.Int).Value = pageIndex * pageSize; command.Parameters.Add("@PagingEnd", SqlDbType.Int).Value = (pageIndex + 1) * pageSize; command.Parameters.Add("@TotalRecords", SqlDbType.Int).Direction = ParameterDirection.Output; connection.Open(); using (var reader = command.ExecuteReader()) { while (reader.Read()) { var listBase = GetListBase(reader); PutInCache(listBase); listCollection.Add(listBase); } } connection.Close(); totalCount = (int)command.Parameters["@TotalRecords"].Value; } } } catch (Exception ex) { var message = string.Format("An exception of type {0} occurred in the SPListDataService.ListsToReindex() method for ApplicationTypeId = {1}. The exception message is: {2}", ex.GetType(), applicationTypeId, ex.Message); SPLog.DataProvider(ex, message); throw new SPDataException(message, ex); } return new PagedList<ListBase>(listCollection, pageSize, pageIndex, totalCount); } public void UpdateIndexingStatus(Guid[] ids, bool isIndexed) { if (ids == null || ids.Length <= 0) return; var applicationIds = string.Join(",", ids); try { using (var connection = DataHelpers.GetSqlConnection()) { using (var command = DataHelpers.CreateSprocCommand("[te_SharePoint_List_UpdateIsIndexed]", connection)) { connection.Open(); command.Parameters.Add("@IsIndexed", SqlDbType.Bit).Value = isIndexed ? 1 : 0; command.Parameters.Add("@ApplicationIds", SqlDbType.NVarChar).Value = applicationIds; command.ExecuteNonQuery(); connection.Close(); } } } catch (Exception ex) { var message = string.Format("An exception of type {0} occurred in the SPListDataService.ListsToReindex() method for Application Ids: {1}. The exception message is: {2}", ex.GetType(), applicationIds, ex.Message); SPLog.DataProvider(ex, message); throw new SPDataException(message, ex); } } private void PutInCache(ListBase listBase) { cacheService.Put(GetCacheId(listBase.GroupId, listBase.ApplicationKey), listBase, CacheScope.Context | CacheScope.Process, new[] { GetTagId(listBase.Id) }, CacheTimeOut); cacheService.Put(GetCacheId(listBase.Id), listBase, CacheScope.Context | CacheScope.Process, new[] { GetTagId(listBase.Id) }, CacheTimeOut); } private static string GetCacheId(Guid applicationId) { return string.Concat("ListBase:", applicationId.ToString("N")); } private static string GetCacheId(int groupId, string applicationKey) { return string.Concat("ListBase:", groupId, ":", applicationKey); } private static string GetTagId(Guid id) { return string.Concat("ListBase_Tag:", id.ToString("N")); } private static ListBase GetListBase(SqlDataReader reader) { return new ListBase(reader.GetInt("GroupId"), reader.GetGuid("ApplicationId"), reader.GetGuid("TypeId"), reader["SPWebUrl"].ToString()) { ApplicationKey = reader.GetStringOrEmpty("ApplicationKey"), ViewId = reader.GetGuid("ViewId") }; } } }
/******************************************************************** * * PropertyBag.cs * -------------- * Derived from PropertyBag.cs by Tony Allowatt * CodeProject: http://www.codeproject.com/cs/miscctrl/bending_property.asp * Last Update: 04/05/2005 * ********************************************************************/ using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Drawing.Design; using System.Reflection; using CslaGenerator.Attributes; using CslaGenerator.Metadata; namespace CslaGenerator.Util.PropertyBags { /// <summary> /// Represents a collection of custom properties that can be selected into a /// PropertyGrid to provide functionality beyond that of the simple reflection /// normally used to query an object's properties. /// </summary> public class ValuePropertyBag : ICustomTypeDescriptor, IBoundProperty { #region PropertySpecCollection class definition /// <summary> /// Encapsulates a collection of PropertySpec objects. /// </summary> [Serializable] public class PropertySpecCollection : IList { private readonly ArrayList _innerArray; /// <summary> /// Initializes a new instance of the PropertySpecCollection class. /// </summary> public PropertySpecCollection() { _innerArray = new ArrayList(); } /// <summary> /// Gets or sets the element at the specified index. /// In C#, this property is the indexer for the PropertySpecCollection class. /// </summary> /// <param name="index">The zero-based index of the element to get or set.</param> /// <value> /// The element at the specified index. /// </value> public PropertySpec this[int index] { get { return (PropertySpec)_innerArray[index]; } set { _innerArray[index] = value; } } #region IList Members /// <summary> /// Gets the number of elements in the PropertySpecCollection. /// </summary> /// <value> /// The number of elements contained in the PropertySpecCollection. /// </value> public int Count { get { return _innerArray.Count; } } /// <summary> /// Gets a value indicating whether the PropertySpecCollection has a fixed size. /// </summary> /// <value> /// true if the PropertySpecCollection has a fixed size; otherwise, false. /// </value> public bool IsFixedSize { get { return false; } } /// <summary> /// Gets a value indicating whether the PropertySpecCollection is read-only. /// </summary> public bool IsReadOnly { get { return false; } } /// <summary> /// Gets a value indicating whether access to the collection is synchronized (thread-safe). /// </summary> /// <value> /// true if access to the PropertySpecCollection is synchronized (thread-safe); otherwise, false. /// </value> public bool IsSynchronized { get { return false; } } /// <summary> /// Gets an object that can be used to synchronize access to the collection. /// </summary> /// <value> /// An object that can be used to synchronize access to the collection. /// </value> object ICollection.SyncRoot { get { return null; } } /// <summary> /// Removes all elements from the PropertySpecCollection. /// </summary> public void Clear() { _innerArray.Clear(); } /// <summary> /// Returns an enumerator that can iterate through the PropertySpecCollection. /// </summary> /// <returns>An IEnumerator for the entire PropertySpecCollection.</returns> public IEnumerator GetEnumerator() { return _innerArray.GetEnumerator(); } /// <summary> /// Removes the object at the specified index of the PropertySpecCollection. /// </summary> /// <param name="index">The zero-based index of the element to remove.</param> public void RemoveAt(int index) { _innerArray.RemoveAt(index); } #endregion /// <summary> /// Adds a PropertySpec to the end of the PropertySpecCollection. /// </summary> /// <param name="value">The PropertySpec to be added to the end of the PropertySpecCollection.</param> /// <returns>The PropertySpecCollection index at which the value has been added.</returns> public int Add(PropertySpec value) { int index = _innerArray.Add(value); return index; } /// <summary> /// Adds the elements of an array of PropertySpec objects to the end of the PropertySpecCollection. /// </summary> /// <param name="array">The PropertySpec array whose elements should be added to the end of the /// PropertySpecCollection.</param> public void AddRange(PropertySpec[] array) { _innerArray.AddRange(array); } /// <summary> /// Determines whether a PropertySpec is in the PropertySpecCollection. /// </summary> /// <param name="item">The PropertySpec to locate in the PropertySpecCollection. The element to locate /// can be a null reference (Nothing in Visual Basic).</param> /// <returns>true if item is found in the PropertySpecCollection; otherwise, false.</returns> public bool Contains(PropertySpec item) { return _innerArray.Contains(item); } /// <summary> /// Determines whether a PropertySpec with the specified name is in the PropertySpecCollection. /// </summary> /// <param name="name">The name of the PropertySpec to locate in the PropertySpecCollection.</param> /// <returns>true if item is found in the PropertySpecCollection; otherwise, false.</returns> public bool Contains(string name) { foreach (PropertySpec spec in _innerArray) if (spec.Name == name) return true; return false; } /// <summary> /// Copies the entire PropertySpecCollection to a compatible one-dimensional Array, starting at the /// beginning of the target array. /// </summary> /// <param name="array">The one-dimensional Array that is the destination of the elements copied /// from PropertySpecCollection. The Array must have zero-based indexing.</param> public void CopyTo(PropertySpec[] array) { _innerArray.CopyTo(array); } /// <summary> /// Copies the PropertySpecCollection or a portion of it to a one-dimensional array. /// </summary> /// <param name="array">The one-dimensional Array that is the destination of the elements copied /// from the collection.</param> /// <param name="index">The zero-based index in array at which copying begins.</param> public void CopyTo(PropertySpec[] array, int index) { _innerArray.CopyTo(array, index); } /// <summary> /// Searches for the specified PropertySpec and returns the zero-based index of the first /// occurrence within the entire PropertySpecCollection. /// </summary> /// <param name="value">The PropertySpec to locate in the PropertySpecCollection.</param> /// <returns>The zero-based index of the first occurrence of value within the entire PropertySpecCollection, /// if found; otherwise, -1.</returns> public int IndexOf(PropertySpec value) { return _innerArray.IndexOf(value); } /// <summary> /// Searches for the PropertySpec with the specified name and returns the zero-based index of /// the first occurrence within the entire PropertySpecCollection. /// </summary> /// <param name="name">The name of the PropertySpec to locate in the PropertySpecCollection.</param> /// <returns>The zero-based index of the first occurrence of value within the entire PropertySpecCollection, /// if found; otherwise, -1.</returns> public int IndexOf(string name) { int i = 0; foreach (PropertySpec spec in _innerArray) { //if (spec.Name == name) if (spec.TargetProperty == name) return i; i++; } return -1; } /// <summary> /// Inserts a PropertySpec object into the PropertySpecCollection at the specified index. /// </summary> /// <param name="index">The zero-based index at which value should be inserted.</param> /// <param name="value">The PropertySpec to insert.</param> public void Insert(int index, PropertySpec value) { _innerArray.Insert(index, value); } /// <summary> /// Removes the first occurrence of a specific object from the PropertySpecCollection. /// </summary> /// <param name="obj">The PropertySpec to remove from the PropertySpecCollection.</param> public void Remove(PropertySpec obj) { _innerArray.Remove(obj); } /// <summary> /// Removes the property with the specified name from the PropertySpecCollection. /// </summary> /// <param name="name">The name of the PropertySpec to remove from the PropertySpecCollection.</param> public void Remove(string name) { int index = IndexOf(name); RemoveAt(index); } /// <summary> /// Copies the elements of the PropertySpecCollection to a new PropertySpec array. /// </summary> /// <returns>A PropertySpec array containing copies of the elements of the PropertySpecCollection.</returns> public PropertySpec[] ToArray() { return (PropertySpec[])_innerArray.ToArray(typeof(PropertySpec)); } #region Explicit interface implementations for ICollection and IList /// <summary> /// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code. /// </summary> void ICollection.CopyTo(Array array, int index) { CopyTo((PropertySpec[])array, index); } /// <summary> /// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code. /// </summary> int IList.Add(object value) { return Add((PropertySpec)value); } /// <summary> /// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code. /// </summary> bool IList.Contains(object obj) { return Contains((PropertySpec)obj); } /// <summary> /// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code. /// </summary> object IList.this[int index] { get { return this[index]; } set { this[index] = (PropertySpec)value; } } /// <summary> /// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code. /// </summary> int IList.IndexOf(object obj) { return IndexOf((PropertySpec)obj); } /// <summary> /// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code. /// </summary> void IList.Insert(int index, object value) { Insert(index, (PropertySpec)value); } /// <summary> /// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code. /// </summary> void IList.Remove(object value) { Remove((PropertySpec)value); } #endregion } #endregion #region PropertySpecDescriptor class definition private class PropertySpecDescriptor : PropertyDescriptor { private readonly ValuePropertyBag _bag; private readonly PropertySpec _item; public PropertySpecDescriptor(PropertySpec item, ValuePropertyBag bag, string name, Attribute[] attrs) : base(name, attrs) { _bag = bag; _item = item; } public override Type ComponentType { get { return _item.GetType(); } } public override bool IsReadOnly { get { return (Attributes.Matches(ReadOnlyAttribute.Yes)); } } public override Type PropertyType { get { return Type.GetType(_item.TypeName); } } public override bool CanResetValue(object component) { if (_item.DefaultValue == null) return false; return !GetValue(component).Equals(_item.DefaultValue); } public override object GetValue(object component) { // Have the property bag raise an event to get the current value // of the property. var e = new PropertySpecEventArgs(_item, null); _bag.OnGetValue(e); return e.Value; } public override void ResetValue(object component) { SetValue(component, _item.DefaultValue); } public override void SetValue(object component, object value) { // Have the property bag raise an event to set the current value // of the property. var e = new PropertySpecEventArgs(_item, value); _bag.OnSetValue(e); } public override bool ShouldSerializeValue(object component) { object val = GetValue(component); if (_item.DefaultValue == null && val == null) return false; return !val.Equals(_item.DefaultValue); } } #endregion #region Properties and Events private readonly PropertySpecCollection _properties; private string _defaultProperty; private ValueProperty[] _selectedObject; /// <summary> /// Initializes a new instance of the ValuePropertyBag class. /// </summary> public ValuePropertyBag() { _defaultProperty = null; _properties = new PropertySpecCollection(); } public ValuePropertyBag(ValueProperty obj) : this(new[] { obj }) { } public ValuePropertyBag(ValueProperty[] obj) { _defaultProperty = "Name"; _properties = new PropertySpecCollection(); _selectedObject = obj; InitPropertyBag(); } /// <summary> /// Gets or sets the name of the default property in the collection. /// </summary> public string DefaultProperty { get { return _defaultProperty; } set { _defaultProperty = value; } } /// <summary> /// Gets or sets the name of the default property in the collection. /// </summary> public ValueProperty[] SelectedObject { get { return _selectedObject; } set { _selectedObject = value; InitPropertyBag(); } } /// <summary> /// Gets the collection of properties contained within this ValuePropertyBag. /// </summary> public PropertySpecCollection Properties { get { return _properties; } } /// <summary> /// Occurs when a PropertyGrid requests the value of a property. /// </summary> public event PropertySpecEventHandler GetValue; /// <summary> /// Occurs when the user changes the value of a property in a PropertyGrid. /// </summary> public event PropertySpecEventHandler SetValue; /// <summary> /// Raises the GetValue event. /// </summary> /// <param name="e">A PropertySpecEventArgs that contains the event data.</param> protected virtual void OnGetValue(PropertySpecEventArgs e) { if (e.Value != null) GetValue(this, e); e.Value = GetProperty(e.Property.TargetObject, e.Property.TargetProperty, e.Property.DefaultValue); } /// <summary> /// Raises the SetValue event. /// </summary> /// <param name="e">A PropertySpecEventArgs that contains the event data.</param> protected virtual void OnSetValue(PropertySpecEventArgs e) { if (SetValue != null) SetValue(this, e); SetProperty(e.Property.TargetObject, e.Property.TargetProperty, e.Value); } #endregion #region Initialize Propertybag private void InitPropertyBag() { PropertyInfo propertyInfo; Type t = typeof(ValueProperty);// _selectedObject.GetType(); PropertyInfo[] props = t.GetProperties(); // Display information for all properties. for (int i = 0; i < props.Length; i++) { propertyInfo = props[i]; object[] myAttributes = propertyInfo.GetCustomAttributes(true); string category = ""; string description = ""; bool isreadonly = false; bool isbrowsable = true; object defaultvalue = null; string userfriendlyname = ""; string typeconverter = ""; string designertypename = ""; string helptopic = ""; bool bindable = true; string editor = ""; for (int n = 0; n < myAttributes.Length; n++) { var a = (Attribute)myAttributes[n]; switch (a.GetType().ToString()) { case "System.ComponentModel.CategoryAttribute": category = ((CategoryAttribute)a).Category; break; case "System.ComponentModel.DescriptionAttribute": description = ((DescriptionAttribute)a).Description; break; case "System.ComponentModel.ReadOnlyAttribute": isreadonly = ((ReadOnlyAttribute)a).IsReadOnly; break; case "System.ComponentModel.BrowsableAttribute": isbrowsable = ((BrowsableAttribute)a).Browsable; break; case "System.ComponentModel.DefaultValueAttribute": defaultvalue = ((DefaultValueAttribute)a).Value; break; case "CslaGenerator.Attributes.UserFriendlyNameAttribute": userfriendlyname = ((UserFriendlyNameAttribute)a).UserFriendlyName; break; case "CslaGenerator.Attributes.HelpTopicAttribute": helptopic = ((HelpTopicAttribute)a).HelpTopic; break; case "System.ComponentModel.TypeConverterAttribute": typeconverter = ((TypeConverterAttribute)a).ConverterTypeName; break; case "System.ComponentModel.DesignerAttribute": designertypename = ((DesignerAttribute)a).DesignerTypeName; break; case "System.ComponentModel.BindableAttribute": bindable = ((BindableAttribute)a).Bindable; break; case "System.ComponentModel.EditorAttribute": editor = ((EditorAttribute)a).EditorTypeName; break; } } // Set ReadOnly properties if (SelectedObject[0].PropertyType == TypeCodeEx.CustomType) { if ((SelectedObject[0].DeclarationMode != PropertyDeclaration.ClassicPropertyWithTypeConversion && SelectedObject[0].DeclarationMode != PropertyDeclaration.ManagedWithTypeConversion && SelectedObject[0].DeclarationMode != PropertyDeclaration.UnmanagedWithTypeConversion || SelectedObject[0].BackingFieldType == TypeCodeEx.Empty || SelectedObject[0].BackingFieldType == TypeCodeEx.CustomType) && propertyInfo.Name == "IsDatabaseBound") isreadonly = true; } if (SelectedObject[0].DeclarationMode != PropertyDeclaration.ClassicPropertyWithTypeConversion && SelectedObject[0].DeclarationMode != PropertyDeclaration.ManagedWithTypeConversion && SelectedObject[0].DeclarationMode != PropertyDeclaration.UnmanagedWithTypeConversion && propertyInfo.Name == "BackingFieldType") isreadonly = true; if (SelectedObject[0].ReadOnly && propertyInfo.Name == "PropSetAccessibility") isreadonly = true; userfriendlyname = userfriendlyname.Length > 0 ? userfriendlyname : propertyInfo.Name; var types = new List<ValueProperty>(); foreach (var obj in _selectedObject) { if (!types.Contains(obj)) types.Add(obj); } // here get rid of Parent bool isValidProperty = propertyInfo.Name != "Parent"; if (isValidProperty && IsBrowsable(types.ToArray(), propertyInfo.Name)) { // CR added missing parameters //this.Properties.Add(new PropertySpec(userfriendlyname,propertyInfo.PropertyType.AssemblyQualifiedName,category,description,defaultvalue, editor, typeconverter, _selectedObject, propertyInfo.Name,helptopic)); Properties.Add(new PropertySpec(userfriendlyname, propertyInfo.PropertyType.AssemblyQualifiedName, category, description, defaultvalue, editor, typeconverter, _selectedObject, propertyInfo.Name, helptopic, isreadonly, isbrowsable, designertypename, bindable)); } } } #endregion private readonly Dictionary<string, PropertyInfo> propertyInfoCache = new Dictionary<string, PropertyInfo>(); private PropertyInfo GetPropertyInfoCache(string propertyName) { if (!propertyInfoCache.ContainsKey(propertyName)) { propertyInfoCache.Add(propertyName, typeof(ValueProperty).GetProperty(propertyName)); } return propertyInfoCache[propertyName]; } private bool IsEnumerable(PropertyInfo prop) { if (prop.PropertyType == typeof(string)) return false; Type[] interfaces = prop.PropertyType.GetInterfaces(); foreach (Type typ in interfaces) if (typ.Name.Contains("IEnumerable")) return true; return false; } #region IsBrowsable map objectType:propertyName -> true | false private bool IsBrowsable(ValueProperty[] objectType, string propertyName) { var cslaObject = (CslaObjectInfo)GeneratorController.Current.GetSelectedItem(); var isNotDbConsumer = cslaObject.IsNotDbConsumer(); try { foreach (var valueProperty in objectType) { // Don't bother extracting these out of the loop, since it only runs once, ever. if ((GeneratorController.Current.CurrentUnit.GenerationParams.GenerateAuthorization == AuthorizationLevel.None || GeneratorController.Current.CurrentUnit.GenerationParams.GenerateAuthorization == AuthorizationLevel.ObjectLevel || ((valueProperty.AuthzProvider == AuthorizationProvider.Custom) && !GeneratorController.Current.CurrentUnit.GenerationParams.UsesCslaAuthorizationProvider)) && (propertyName == "ReadRoles" || propertyName == "WriteRoles")) return false; if ((GeneratorController.Current.CurrentUnit.GenerationParams.GenerateAuthorization == AuthorizationLevel.None || GeneratorController.Current.CurrentUnit.GenerationParams.GenerateAuthorization == AuthorizationLevel.ObjectLevel || ((valueProperty.AuthzProvider == AuthorizationProvider.IsInRole || valueProperty.AuthzProvider == AuthorizationProvider.IsNotInRole) && !GeneratorController.Current.CurrentUnit.GenerationParams.UsesCslaAuthorizationProvider) || GeneratorController.Current.CurrentUnit.GenerationParams.UsesCslaAuthorizationProvider) && (propertyName == "ReadAuthzRuleType" || propertyName == "WriteAuthzRuleType")) return false; if (((GeneratorController.Current.CurrentUnit.GenerationParams.GenerateAuthorization == AuthorizationLevel.None || GeneratorController.Current.CurrentUnit.GenerationParams.GenerateAuthorization == AuthorizationLevel.ObjectLevel) || GeneratorController.Current.CurrentUnit.GenerationParams.UsesCslaAuthorizationProvider) && propertyName == "AuthzProvider") return false; if (cslaObject.IsReadOnlyObject() && propertyName == "Undoable") return false; if (cslaObject.IsNameValueList() && (propertyName == "AuthzProvider" || propertyName == "ReadRoles" || propertyName == "WriteRoles" || propertyName == "ReadAuthzRuleType" || propertyName == "WriteAuthzRuleType" || propertyName == "BusinessRules" || propertyName == "Undoable")) return false; if ((isNotDbConsumer || !valueProperty.IsDatabaseBound) && (propertyName == "DbBindColumn" || propertyName == "DataAccess" || propertyName == "PrimaryKey" || propertyName == "FKConstraint" || propertyName == "ParameterName")) return false; if (valueProperty.PropertyType != TypeCodeEx.CustomType && propertyName == "CustomPropertyType") return false; /*if (valueProperty.DeclarationMode != PropertyDeclaration.ClassicPropertyWithTypeConversion && valueProperty.DeclarationMode != PropertyDeclaration.ManagedWithTypeConversion && valueProperty.DeclarationMode != PropertyDeclaration.UnmanagedWithTypeConversion && propertyName == "BackingFieldType") return false;*/ if (_selectedObject.Length > 1 && IsEnumerable(GetPropertyInfoCache(propertyName))) return false; } return true; } catch //(Exception e) { //Debug.WriteLine(objectType + ":" + propertyName); return true; } } #endregion #region Reflection functions private object GetField(Type t, string name, object target) { object obj = null; Type tx; //FieldInfo[] fields; //fields = target.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public); //fields = target.GetType().GetFields(BindingFlags.Public); tx = target.GetType(); obj = tx.InvokeMember(name, BindingFlags.Default | BindingFlags.GetField, null, target, new object[] { }); return obj; } private object SetField(Type t, string name, object value, object target) { object obj; obj = t.InvokeMember(name, BindingFlags.Default | BindingFlags.SetField, null, target, new[] { value }); return obj; } private bool SetProperty(object obj, string propertyName, object val) { try { // get a reference to the PropertyInfo, exit if no property with that name PropertyInfo propertyInfo = typeof(ValueProperty).GetProperty(propertyName); if (propertyInfo == null) return false; // convert the value to the expected type val = Convert.ChangeType(val, propertyInfo.PropertyType); // attempt the assignment foreach (ValueProperty bo in (ValueProperty[])obj) propertyInfo.SetValue(bo, val, null); return true; } catch { return false; } } private object GetProperty(object obj, string propertyName, object defaultValue) { try { PropertyInfo propertyInfo = GetPropertyInfoCache(propertyName); if (!(propertyInfo == null)) { var objs = (ValueProperty[])obj; var valueList = new ArrayList(); foreach (ValueProperty bo in objs) { object value = propertyInfo.GetValue(bo, null); if (!valueList.Contains(value)) { valueList.Add(value); } } switch (valueList.Count) { case 1: return valueList[0]; default: return string.Empty; } } } catch (Exception ex) { Console.WriteLine(ex.Message); } // if property doesn't exist or throws return defaultValue; } #endregion #region ICustomTypeDescriptor explicit interface definitions // Most of the functions required by the ICustomTypeDescriptor are // merely pssed on to the default TypeDescriptor for this type, // which will do something appropriate. The exceptions are noted // below. AttributeCollection ICustomTypeDescriptor.GetAttributes() { return TypeDescriptor.GetAttributes(this, true); } string ICustomTypeDescriptor.GetClassName() { return TypeDescriptor.GetClassName(this, true); } string ICustomTypeDescriptor.GetComponentName() { return TypeDescriptor.GetComponentName(this, true); } TypeConverter ICustomTypeDescriptor.GetConverter() { return TypeDescriptor.GetConverter(this, true); } EventDescriptor ICustomTypeDescriptor.GetDefaultEvent() { return TypeDescriptor.GetDefaultEvent(this, true); } PropertyDescriptor ICustomTypeDescriptor.GetDefaultProperty() { // This function searches the property list for the property // with the same name as the DefaultProperty specified, and // returns a property descriptor for it. If no property is // found that matches DefaultProperty, a null reference is // returned instead. PropertySpec propertySpec = null; if (_defaultProperty != null) { int index = _properties.IndexOf(_defaultProperty); propertySpec = _properties[index]; } if (propertySpec != null) return new PropertySpecDescriptor(propertySpec, this, propertySpec.Name, null); return null; } object ICustomTypeDescriptor.GetEditor(Type editorBaseType) { return TypeDescriptor.GetEditor(this, editorBaseType, true); } EventDescriptorCollection ICustomTypeDescriptor.GetEvents() { return TypeDescriptor.GetEvents(this, true); } EventDescriptorCollection ICustomTypeDescriptor.GetEvents(Attribute[] attributes) { return TypeDescriptor.GetEvents(this, attributes, true); } PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties() { return ((ICustomTypeDescriptor)this).GetProperties(new Attribute[0]); } PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[] attributes) { // Rather than passing this function on to the default TypeDescriptor, // which would return the actual properties of ValuePropertyBag, I construct // a list here that contains property descriptors for the elements of the // Properties list in the bag. var props = new ArrayList(); foreach (PropertySpec property in _properties) { var attrs = new ArrayList(); // If a category, description, editor, or type converter are specified // in the PropertySpec, create attributes to define that relationship. if (property.Category != null) attrs.Add(new CategoryAttribute(property.Category)); if (property.Description != null) attrs.Add(new DescriptionAttribute(property.Description)); if (property.EditorTypeName != null) attrs.Add(new EditorAttribute(property.EditorTypeName, typeof(UITypeEditor))); if (property.ConverterTypeName != null) attrs.Add(new TypeConverterAttribute(property.ConverterTypeName)); // Additionally, append the custom attributes associated with the // PropertySpec, if any. if (property.Attributes != null) attrs.AddRange(property.Attributes); if (property.DefaultValue != null) attrs.Add(new DefaultValueAttribute(property.DefaultValue)); attrs.Add(new BrowsableAttribute(property.Browsable)); attrs.Add(new ReadOnlyAttribute(property.ReadOnly)); attrs.Add(new BindableAttribute(property.Bindable)); var attrArray = (Attribute[])attrs.ToArray(typeof(Attribute)); // Create a new property descriptor for the property item, and add // it to the list. var pd = new PropertySpecDescriptor(property, this, property.Name, attrArray); props.Add(pd); } // Convert the list of PropertyDescriptors to a collection that the // ICustomTypeDescriptor can use, and return it. var propArray = (PropertyDescriptor[])props.ToArray( typeof(PropertyDescriptor)); return new PropertyDescriptorCollection(propArray); } object ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor pd) { return this; } #endregion public DbBindColumn DbBindColumn { get { return _selectedObject[0].DbBindColumn; } set { _selectedObject[0].DbBindColumn = value; } } } }
using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using BTDB.KVDBLayer.BTree; namespace BTDB.KVDBLayer { class KeyValueDBTransaction : IKeyValueDBTransaction { readonly KeyValueDB _keyValueDB; IBTreeRootNode? _btreeRoot; readonly List<NodeIdxPair> _stack = new List<NodeIdxPair>(); bool _writing; readonly bool _readOnly; bool _preapprovedWriting; bool _temporaryCloseTransactionLog; long _keyIndex; long _cursorMovedCounter; public DateTime CreatedTime { get; } = DateTime.UtcNow; public KeyValueDBTransaction(KeyValueDB keyValueDB, IBTreeRootNode btreeRoot, bool writing, bool readOnly) { _preapprovedWriting = writing; _readOnly = readOnly; _keyValueDB = keyValueDB; _btreeRoot = btreeRoot; _keyIndex = -1; _cursorMovedCounter = 0; _keyValueDB.StartedUsingBTreeRoot(_btreeRoot); } ~KeyValueDBTransaction() { if (_btreeRoot != null || _writing || _preapprovedWriting) { Dispose(); _keyValueDB.Logger?.ReportTransactionLeak(this); } } internal IBTreeRootNode? BtreeRoot => _btreeRoot; public bool FindFirstKey(in ReadOnlySpan<byte> prefix) { _cursorMovedCounter++; if (_btreeRoot!.FindKey(_stack, out _keyIndex, prefix, (uint)prefix.Length) != FindResult.NotFound) return true; InvalidateCurrentKey(); return false; } public bool FindLastKey(in ReadOnlySpan<byte> prefix) { _cursorMovedCounter++; _keyIndex = _btreeRoot!.FindLastWithPrefix(prefix); if (_keyIndex == -1) return false; _btreeRoot.FillStackByIndex(_stack, _keyIndex); return true; } public bool FindPreviousKey(in ReadOnlySpan<byte> prefix) { if (_keyIndex == -1) return FindLastKey(prefix); _cursorMovedCounter++; if (_btreeRoot!.FindPreviousKey(_stack)) { if (CheckPrefixIn(prefix, GetCurrentKeyFromStack())) { _keyIndex--; return true; } } InvalidateCurrentKey(); return false; } public bool FindNextKey(in ReadOnlySpan<byte> prefix) { if (_keyIndex == -1) return FindFirstKey(prefix); _cursorMovedCounter++; if (_btreeRoot!.FindNextKey(_stack)) { if (CheckPrefixIn(prefix, GetCurrentKeyFromStack())) { _keyIndex++; return true; } } InvalidateCurrentKey(); return false; } public FindResult Find(in ReadOnlySpan<byte> key, uint prefixLen) { _cursorMovedCounter++; return _btreeRoot!.FindKey(_stack, out _keyIndex, key, prefixLen); } public bool CreateOrUpdateKeyValue(in ReadOnlySpan<byte> key, in ReadOnlySpan<byte> value) { _cursorMovedCounter++; MakeWritable(); _keyValueDB.WriteCreateOrUpdateCommand(key, value, out var valueFileId, out var valueOfs, out var valueSize); var ctx = new CreateOrUpdateCtx { Key = key, ValueFileId = valueFileId, ValueOfs = valueOfs, ValueSize = valueSize, Stack = _stack }; _btreeRoot!.CreateOrUpdate(ref ctx); _keyIndex = ctx.KeyIndex; return ctx.Created; } void MakeWritable() { if (_writing) return; if (_preapprovedWriting) { _writing = true; _preapprovedWriting = false; _keyValueDB.WriteStartTransaction(); return; } if (_readOnly) { throw new BTDBTransactionRetryException("Cannot write from readOnly transaction"); } var oldBTreeRoot = _btreeRoot; _btreeRoot = _keyValueDB.MakeWritableTransaction(this, oldBTreeRoot!); _keyValueDB.StartedUsingBTreeRoot(_btreeRoot); _keyValueDB.FinishedUsingBTreeRoot(oldBTreeRoot); _btreeRoot.DescriptionForLeaks = _descriptionForLeaks; _writing = true; InvalidateCurrentKey(); _keyValueDB.WriteStartTransaction(); } public long GetKeyValueCount() => _btreeRoot!.CalcKeyCount(); public long GetKeyIndex() => _keyIndex; public bool SetKeyIndex(long index) { _cursorMovedCounter++; if (index < 0 || index >= _btreeRoot!.CalcKeyCount()) { InvalidateCurrentKey(); return false; } _keyIndex = index; _btreeRoot!.FillStackByIndex(_stack, _keyIndex); return true; } public bool SetKeyIndex(in ReadOnlySpan<byte> prefix, long index) { _cursorMovedCounter++; if (_btreeRoot!.FindKey(_stack, out _keyIndex, prefix, (uint)prefix.Length) == FindResult.NotFound) { InvalidateCurrentKey(); return false; } index += _keyIndex; if (index < _btreeRoot!.CalcKeyCount()) { _keyIndex = index; _btreeRoot!.FillStackByIndex(_stack, _keyIndex); if (CheckPrefixIn(prefix, GetCurrentKeyFromStack())) return true; } InvalidateCurrentKey(); return false; } static bool CheckPrefixIn(in ReadOnlySpan<byte> prefix, in ReadOnlySpan<byte> key) { return BTreeRoot.KeyStartsWithPrefix(prefix, key); } ReadOnlySpan<byte> GetCurrentKeyFromStack() { var nodeIdxPair = _stack[^1]; return ((IBTreeLeafNode)nodeIdxPair.Node).GetKey(nodeIdxPair.Idx); } public void InvalidateCurrentKey() { _cursorMovedCounter++; _keyIndex = -1; _stack.Clear(); } public bool IsValidKey() { return _keyIndex >= 0; } public ReadOnlySpan<byte> GetKey() { if (!IsValidKey()) return new ReadOnlySpan<byte>(); return GetCurrentKeyFromStack(); } public byte[] GetKeyToArray() { var nodeIdxPair = _stack[^1]; return ((IBTreeLeafNode)nodeIdxPair.Node).GetKey(nodeIdxPair.Idx).ToArray(); } public ReadOnlySpan<byte> GetKey(ref byte buffer, int bufferLength) { if (!IsValidKey()) return new ReadOnlySpan<byte>(); return GetCurrentKeyFromStack(); } public ReadOnlySpan<byte> GetClonedValue(ref byte buffer, int bufferLength) { if (!IsValidKey()) return ReadOnlySpan<byte>.Empty; var nodeIdxPair = _stack[^1]; var leafMember = ((IBTreeLeafNode)nodeIdxPair.Node).GetMemberValue(nodeIdxPair.Idx); try { return _keyValueDB.ReadValue(leafMember.ValueFileId, leafMember.ValueOfs, leafMember.ValueSize, ref buffer, bufferLength); } catch (BTDBException ex) { var oldestRoot = (IBTreeRootNode)_keyValueDB.ReferenceAndGetOldestRoot(); var lastCommitted = (IBTreeRootNode)_keyValueDB.ReferenceAndGetLastCommitted(); // no need to dereference roots because we know it is managed throw new BTDBException($"GetValue failed in TrId:{_btreeRoot!.TransactionId},TRL:{_btreeRoot!.TrLogFileId},Ofs:{_btreeRoot!.TrLogOffset},ComUlong:{_btreeRoot!.CommitUlong} and LastTrId:{lastCommitted.TransactionId},ComUlong:{lastCommitted.CommitUlong} OldestTrId:{oldestRoot.TransactionId},TRL:{oldestRoot.TrLogFileId},ComUlong:{oldestRoot.CommitUlong} innerMessage:{ex.Message}", ex); } } public ReadOnlySpan<byte> GetValue() { return GetClonedValue(ref Unsafe.AsRef((byte)0), 0); } void EnsureValidKey() { if (_keyIndex < 0) { throw new InvalidOperationException("Current key is not valid"); } } public void SetValue(in ReadOnlySpan<byte> value) { EnsureValidKey(); var keyIndexBackup = _keyIndex; MakeWritable(); if (_keyIndex != keyIndexBackup) { _keyIndex = keyIndexBackup; _btreeRoot!.FillStackByIndex(_stack, _keyIndex); } var nodeIdxPair = _stack[^1]; var memberValue = ((IBTreeLeafNode)nodeIdxPair.Node).GetMemberValue(nodeIdxPair.Idx); var memberKey = ((IBTreeLeafNode)nodeIdxPair.Node).GetKey(nodeIdxPair.Idx); _keyValueDB.WriteCreateOrUpdateCommand(memberKey, value, out memberValue.ValueFileId, out memberValue.ValueOfs, out memberValue.ValueSize); ((IBTreeLeafNode)nodeIdxPair.Node).SetMemberValue(nodeIdxPair.Idx, memberValue); } public void EraseCurrent() { _cursorMovedCounter++; EnsureValidKey(); var keyIndex = _keyIndex; MakeWritable(); if (_keyIndex != keyIndex) { _keyIndex = keyIndex; _btreeRoot!.FillStackByIndex(_stack, keyIndex); } _keyValueDB.WriteEraseOneCommand(GetCurrentKeyFromStack()); InvalidateCurrentKey(); _btreeRoot!.EraseOne(keyIndex); } public bool EraseCurrent(in ReadOnlySpan<byte> exactKey) { _cursorMovedCounter++; if (_btreeRoot!.FindKey(_stack, out _keyIndex, exactKey, 0) != FindResult.Exact) { InvalidateCurrentKey(); return false; } var keyIndex = _keyIndex; MakeWritable(); _keyValueDB.WriteEraseOneCommand(exactKey); InvalidateCurrentKey(); _btreeRoot!.EraseOne(keyIndex); return true; } public bool EraseCurrent(in ReadOnlySpan<byte> exactKey, ref byte buffer, int bufferLength, out ReadOnlySpan<byte> value) { _cursorMovedCounter++; if (_btreeRoot!.FindKey(_stack, out _keyIndex, exactKey, 0) != FindResult.Exact) { InvalidateCurrentKey(); value = ReadOnlySpan<byte>.Empty; return false; } var keyIndex = _keyIndex; value = GetClonedValue(ref buffer, bufferLength); MakeWritable(); _keyValueDB.WriteEraseOneCommand(exactKey); InvalidateCurrentKey(); _btreeRoot!.EraseOne(keyIndex); return true; } public void EraseAll() { EraseRange(0, GetKeyValueCount() - 1); } public void EraseRange(long firstKeyIndex, long lastKeyIndex) { if (firstKeyIndex < 0) firstKeyIndex = 0; if (lastKeyIndex >= GetKeyValueCount()) lastKeyIndex = GetKeyValueCount() - 1; if (lastKeyIndex < firstKeyIndex) return; _cursorMovedCounter++; MakeWritable(); InvalidateCurrentKey(); _btreeRoot!.FillStackByIndex(_stack, firstKeyIndex); if (firstKeyIndex == lastKeyIndex) { _keyValueDB.WriteEraseOneCommand(GetCurrentKeyFromStack()); } else { var firstKey = GetCurrentKeyFromStack(); _btreeRoot!.FillStackByIndex(_stack, lastKeyIndex); _keyValueDB.WriteEraseRangeCommand(firstKey, GetCurrentKeyFromStack()); } _btreeRoot!.EraseRange(firstKeyIndex, lastKeyIndex); } public bool IsWriting() { return _writing || _preapprovedWriting; } public bool IsReadOnly() { return _readOnly; } public bool IsDisposed() { return BtreeRoot == null; } public ulong GetCommitUlong() { return _btreeRoot!.CommitUlong; } public void SetCommitUlong(ulong value) { if (_btreeRoot!.CommitUlong != value) { MakeWritable(); _btreeRoot!.CommitUlong = value; } } public void NextCommitTemporaryCloseTransactionLog() { MakeWritable(); _temporaryCloseTransactionLog = true; } public void Commit() { if (BtreeRoot == null) throw new BTDBException("Transaction already committed or disposed"); InvalidateCurrentKey(); var currentBtreeRoot = _btreeRoot; _keyValueDB.FinishedUsingBTreeRoot(_btreeRoot!); _btreeRoot = null; GC.SuppressFinalize(this); if (_preapprovedWriting) { _preapprovedWriting = false; _keyValueDB.RevertWritingTransaction(true); } else if (_writing) { _keyValueDB.CommitWritingTransaction(currentBtreeRoot!, _temporaryCloseTransactionLog); _writing = false; } } public void Dispose() { if (_writing || _preapprovedWriting) { _keyValueDB.RevertWritingTransaction(_preapprovedWriting); _writing = false; _preapprovedWriting = false; } if (_btreeRoot == null) return; _keyValueDB.FinishedUsingBTreeRoot(_btreeRoot); _btreeRoot = null; GC.SuppressFinalize(this); } public long GetTransactionNumber() { return _btreeRoot!.TransactionId; } public long CursorMovedCounter => _cursorMovedCounter; public KeyValuePair<uint, uint> GetStorageSizeOfCurrentKey() { if (!IsValidKey()) return new KeyValuePair<uint, uint>(); var nodeIdxPair = _stack[^1]; var leafMember = ((IBTreeLeafNode)nodeIdxPair.Node).GetMemberValue(nodeIdxPair.Idx); return new KeyValuePair<uint, uint>( (uint)((IBTreeLeafNode)nodeIdxPair.Node).GetKey(nodeIdxPair.Idx).Length, KeyValueDB.CalcValueSize(leafMember.ValueFileId, leafMember.ValueOfs, leafMember.ValueSize)); } public ulong GetUlong(uint idx) { return _btreeRoot!.GetUlong(idx); } public void SetUlong(uint idx, ulong value) { if (_btreeRoot!.GetUlong(idx) != value) { MakeWritable(); _btreeRoot!.SetUlong(idx, value); } } public uint GetUlongCount() { return _btreeRoot!.UlongsArray == null ? 0U : (uint)_btreeRoot!.UlongsArray.Length; } string? _descriptionForLeaks; public IKeyValueDB Owner => _keyValueDB; public string? DescriptionForLeaks { get => _descriptionForLeaks; set { _descriptionForLeaks = value; if (_preapprovedWriting || _writing) _btreeRoot!.DescriptionForLeaks = value; } } public bool RollbackAdvised { get; set; } } }
/* * CP869.cs - Greek (DOS) code page. * * Copyright (c) 2002 Southern Storm Software, Pty Ltd * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ // Generated from "ibm-869.ucm". namespace I18N.Rare { using System; using I18N.Common; public class CP869 : ByteEncoding { public CP869() : base(869, ToChars, "Greek (DOS)", "ibm869", "ibm869", "ibm869", false, false, false, false, 1253) {} private static readonly char[] ToChars = { '\u0000', '\u0001', '\u0002', '\u0003', '\u0004', '\u0005', '\u0006', '\u0007', '\u0008', '\u0009', '\u000A', '\u000B', '\u000C', '\u000D', '\u000E', '\u000F', '\u0010', '\u0011', '\u0012', '\u0013', '\u0014', '\u0015', '\u0016', '\u0017', '\u0018', '\u0019', '\u001C', '\u001B', '\u007F', '\u001D', '\u001E', '\u001F', '\u0020', '\u0021', '\u0022', '\u0023', '\u0024', '\u0025', '\u0026', '\u0027', '\u0028', '\u0029', '\u002A', '\u002B', '\u002C', '\u002D', '\u002E', '\u002F', '\u0030', '\u0031', '\u0032', '\u0033', '\u0034', '\u0035', '\u0036', '\u0037', '\u0038', '\u0039', '\u003A', '\u003B', '\u003C', '\u003D', '\u003E', '\u003F', '\u0040', '\u0041', '\u0042', '\u0043', '\u0044', '\u0045', '\u0046', '\u0047', '\u0048', '\u0049', '\u004A', '\u004B', '\u004C', '\u004D', '\u004E', '\u004F', '\u0050', '\u0051', '\u0052', '\u0053', '\u0054', '\u0055', '\u0056', '\u0057', '\u0058', '\u0059', '\u005A', '\u005B', '\u005C', '\u005D', '\u005E', '\u005F', '\u0060', '\u0061', '\u0062', '\u0063', '\u0064', '\u0065', '\u0066', '\u0067', '\u0068', '\u0069', '\u006A', '\u006B', '\u006C', '\u006D', '\u006E', '\u006F', '\u0070', '\u0071', '\u0072', '\u0073', '\u0074', '\u0075', '\u0076', '\u0077', '\u0078', '\u0079', '\u007A', '\u007B', '\u007C', '\u007D', '\u007E', '\u001A', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u0386', '\u003F', '\u0387', '\u00AC', '\u00A6', '\u2018', '\u2019', '\u0388', '\u2015', '\u0389', '\u038A', '\u03AA', '\u038C', '\u003F', '\u003F', '\u038E', '\u03AB', '\u00A9', '\u038F', '\u00B2', '\u00B3', '\u03AC', '\u00A3', '\u03AD', '\u03AE', '\u03AF', '\u03CA', '\u0390', '\u03CC', '\u03CD', '\u0391', '\u0392', '\u0393', '\u0394', '\u0395', '\u0396', '\u0397', '\u00BD', '\u0398', '\u0399', '\u00AB', '\u00BB', '\u2591', '\u2592', '\u2593', '\u2502', '\u2524', '\u039A', '\u039B', '\u039C', '\u039D', '\u2563', '\u2551', '\u2557', '\u255D', '\u039E', '\u039F', '\u2510', '\u2514', '\u2534', '\u252C', '\u251C', '\u2500', '\u253C', '\u03A0', '\u03A1', '\u255A', '\u2554', '\u2569', '\u2566', '\u2560', '\u2550', '\u256C', '\u03A3', '\u03A4', '\u03A5', '\u03A6', '\u03A7', '\u03A8', '\u03A9', '\u03B1', '\u03B2', '\u03B3', '\u2518', '\u250C', '\u2588', '\u2584', '\u03B4', '\u03B5', '\u2580', '\u03B6', '\u03B7', '\u03B8', '\u03B9', '\u03BA', '\u03BB', '\u03BC', '\u03BD', '\u03BE', '\u03BF', '\u03C0', '\u03C1', '\u03C3', '\u03C2', '\u03C4', '\u00B4', '\u00AD', '\u00B1', '\u03C5', '\u03C6', '\u03C7', '\u00A7', '\u03C8', '\u0385', '\u00B0', '\u00A8', '\u03C9', '\u03CB', '\u03B0', '\u03CE', '\u25A0', '\u00A0', }; protected override void ToBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { int ch; while(charCount > 0) { ch = (int)(chars[charIndex++]); if(ch >= 26) switch(ch) { case 0x001B: case 0x001D: case 0x001E: case 0x001F: case 0x0020: case 0x0021: case 0x0022: case 0x0023: case 0x0024: case 0x0025: case 0x0026: case 0x0027: case 0x0028: case 0x0029: case 0x002A: case 0x002B: case 0x002C: case 0x002D: case 0x002E: case 0x002F: case 0x0030: case 0x0031: case 0x0032: case 0x0033: case 0x0034: case 0x0035: case 0x0036: case 0x0037: case 0x0038: case 0x0039: case 0x003A: case 0x003B: case 0x003C: case 0x003D: case 0x003E: case 0x003F: case 0x0040: case 0x0041: case 0x0042: case 0x0043: case 0x0044: case 0x0045: case 0x0046: case 0x0047: case 0x0048: case 0x0049: case 0x004A: case 0x004B: case 0x004C: case 0x004D: case 0x004E: case 0x004F: case 0x0050: case 0x0051: case 0x0052: case 0x0053: case 0x0054: case 0x0055: case 0x0056: case 0x0057: case 0x0058: case 0x0059: case 0x005A: case 0x005B: case 0x005C: case 0x005D: case 0x005E: case 0x005F: case 0x0060: case 0x0061: case 0x0062: case 0x0063: case 0x0064: case 0x0065: case 0x0066: case 0x0067: case 0x0068: case 0x0069: case 0x006A: case 0x006B: case 0x006C: case 0x006D: case 0x006E: case 0x006F: case 0x0070: case 0x0071: case 0x0072: case 0x0073: case 0x0074: case 0x0075: case 0x0076: case 0x0077: case 0x0078: case 0x0079: case 0x007A: case 0x007B: case 0x007C: case 0x007D: case 0x007E: break; case 0x001A: ch = 0x7F; break; case 0x001C: ch = 0x1A; break; case 0x007F: ch = 0x1C; break; case 0x00A0: ch = 0xFF; break; case 0x00A3: ch = 0x9C; break; case 0x00A6: ch = 0x8A; break; case 0x00A7: ch = 0xF5; break; case 0x00A8: ch = 0xF9; break; case 0x00A9: ch = 0x97; break; case 0x00AB: ch = 0xAE; break; case 0x00AC: ch = 0x89; break; case 0x00AD: ch = 0xF0; break; case 0x00B0: ch = 0xF8; break; case 0x00B1: ch = 0xF1; break; case 0x00B2: ch = 0x99; break; case 0x00B3: ch = 0x9A; break; case 0x00B4: ch = 0xEF; break; case 0x00B6: ch = 0x14; break; case 0x00B7: ch = 0x88; break; case 0x00BB: ch = 0xAF; break; case 0x00BD: ch = 0xAB; break; case 0x0385: ch = 0xF7; break; case 0x0386: ch = 0x86; break; case 0x0387: ch = 0x88; break; case 0x0388: ch = 0x8D; break; case 0x0389: ch = 0x8F; break; case 0x038A: ch = 0x90; break; case 0x038C: ch = 0x92; break; case 0x038E: ch = 0x95; break; case 0x038F: ch = 0x98; break; case 0x0390: ch = 0xA1; break; case 0x0391: case 0x0392: case 0x0393: case 0x0394: case 0x0395: case 0x0396: case 0x0397: ch -= 0x02ED; break; case 0x0398: ch = 0xAC; break; case 0x0399: ch = 0xAD; break; case 0x039A: case 0x039B: case 0x039C: case 0x039D: ch -= 0x02E5; break; case 0x039E: ch = 0xBD; break; case 0x039F: ch = 0xBE; break; case 0x03A0: ch = 0xC6; break; case 0x03A1: ch = 0xC7; break; case 0x03A3: case 0x03A4: case 0x03A5: case 0x03A6: case 0x03A7: case 0x03A8: case 0x03A9: ch -= 0x02D4; break; case 0x03AA: ch = 0x91; break; case 0x03AB: ch = 0x96; break; case 0x03AC: ch = 0x9B; break; case 0x03AD: ch = 0x9D; break; case 0x03AE: ch = 0x9E; break; case 0x03AF: ch = 0x9F; break; case 0x03B0: ch = 0xFC; break; case 0x03B1: ch = 0xD6; break; case 0x03B2: ch = 0xD7; break; case 0x03B3: ch = 0xD8; break; case 0x03B4: ch = 0xDD; break; case 0x03B5: ch = 0xDE; break; case 0x03B6: case 0x03B7: case 0x03B8: case 0x03B9: case 0x03BA: case 0x03BB: case 0x03BC: case 0x03BD: case 0x03BE: case 0x03BF: case 0x03C0: case 0x03C1: ch -= 0x02D6; break; case 0x03C2: ch = 0xED; break; case 0x03C3: ch = 0xEC; break; case 0x03C4: ch = 0xEE; break; case 0x03C5: ch = 0xF2; break; case 0x03C6: ch = 0xF3; break; case 0x03C7: ch = 0xF4; break; case 0x03C8: ch = 0xF6; break; case 0x03C9: ch = 0xFA; break; case 0x03CA: ch = 0xA0; break; case 0x03CB: ch = 0xFB; break; case 0x03CC: ch = 0xA2; break; case 0x03CD: ch = 0xA3; break; case 0x03CE: ch = 0xFD; break; case 0x03D5: ch = 0xF3; break; case 0x2015: ch = 0x8E; break; case 0x2018: ch = 0x8B; break; case 0x2019: ch = 0x8C; break; case 0x2022: ch = 0x07; break; case 0x203C: ch = 0x13; break; case 0x2190: ch = 0x1B; break; case 0x2191: ch = 0x18; break; case 0x2192: ch = 0x1A; break; case 0x2193: ch = 0x19; break; case 0x2194: ch = 0x1D; break; case 0x2195: ch = 0x12; break; case 0x21A8: ch = 0x17; break; case 0x221F: ch = 0x1C; break; case 0x2302: ch = 0x7F; break; case 0x2500: ch = 0xC4; break; case 0x2502: ch = 0xB3; break; case 0x250C: ch = 0xDA; break; case 0x2510: ch = 0xBF; break; case 0x2514: ch = 0xC0; break; case 0x2518: ch = 0xD9; break; case 0x251C: ch = 0xC3; break; case 0x2524: ch = 0xB4; break; case 0x252C: ch = 0xC2; break; case 0x2534: ch = 0xC1; break; case 0x253C: ch = 0xC5; break; case 0x2550: ch = 0xCD; break; case 0x2551: ch = 0xBA; break; case 0x2554: ch = 0xC9; break; case 0x2557: ch = 0xBB; break; case 0x255A: ch = 0xC8; break; case 0x255D: ch = 0xBC; break; case 0x2560: ch = 0xCC; break; case 0x2563: ch = 0xB9; break; case 0x2566: ch = 0xCB; break; case 0x2569: ch = 0xCA; break; case 0x256C: ch = 0xCE; break; case 0x2580: ch = 0xDF; break; case 0x2584: ch = 0xDC; break; case 0x2588: ch = 0xDB; break; case 0x2591: ch = 0xB0; break; case 0x2592: ch = 0xB1; break; case 0x2593: ch = 0xB2; break; case 0x25A0: ch = 0xFE; break; case 0x25AC: ch = 0x16; break; case 0x25B2: ch = 0x1E; break; case 0x25BA: ch = 0x10; break; case 0x25BC: ch = 0x1F; break; case 0x25C4: ch = 0x11; break; case 0x25CB: ch = 0x09; break; case 0x25D8: ch = 0x08; break; case 0x25D9: ch = 0x0A; break; case 0x263A: ch = 0x01; break; case 0x263B: ch = 0x02; break; case 0x263C: ch = 0x0F; break; case 0x2640: ch = 0x0C; break; case 0x2642: ch = 0x0B; break; case 0x2660: ch = 0x06; break; case 0x2663: ch = 0x05; break; case 0x2665: ch = 0x03; break; case 0x2666: ch = 0x04; break; case 0x266A: ch = 0x0D; break; case 0x266B: ch = 0x0E; break; case 0xFFE8: ch = 0xB3; break; case 0xFFE9: ch = 0x1B; break; case 0xFFEA: ch = 0x18; break; case 0xFFEB: ch = 0x1A; break; case 0xFFEC: ch = 0x19; break; case 0xFFED: ch = 0xFE; break; case 0xFFEE: ch = 0x09; break; default: { if(ch >= 0xFF01 && ch <= 0xFF5E) ch -= 0xFEE0; else ch = 0x3F; } break; } bytes[byteIndex++] = (byte)ch; --charCount; } } protected override void ToBytes(String s, int charIndex, int charCount, byte[] bytes, int byteIndex) { int ch; while(charCount > 0) { ch = (int)(s[charIndex++]); if(ch >= 26) switch(ch) { case 0x001B: case 0x001D: case 0x001E: case 0x001F: case 0x0020: case 0x0021: case 0x0022: case 0x0023: case 0x0024: case 0x0025: case 0x0026: case 0x0027: case 0x0028: case 0x0029: case 0x002A: case 0x002B: case 0x002C: case 0x002D: case 0x002E: case 0x002F: case 0x0030: case 0x0031: case 0x0032: case 0x0033: case 0x0034: case 0x0035: case 0x0036: case 0x0037: case 0x0038: case 0x0039: case 0x003A: case 0x003B: case 0x003C: case 0x003D: case 0x003E: case 0x003F: case 0x0040: case 0x0041: case 0x0042: case 0x0043: case 0x0044: case 0x0045: case 0x0046: case 0x0047: case 0x0048: case 0x0049: case 0x004A: case 0x004B: case 0x004C: case 0x004D: case 0x004E: case 0x004F: case 0x0050: case 0x0051: case 0x0052: case 0x0053: case 0x0054: case 0x0055: case 0x0056: case 0x0057: case 0x0058: case 0x0059: case 0x005A: case 0x005B: case 0x005C: case 0x005D: case 0x005E: case 0x005F: case 0x0060: case 0x0061: case 0x0062: case 0x0063: case 0x0064: case 0x0065: case 0x0066: case 0x0067: case 0x0068: case 0x0069: case 0x006A: case 0x006B: case 0x006C: case 0x006D: case 0x006E: case 0x006F: case 0x0070: case 0x0071: case 0x0072: case 0x0073: case 0x0074: case 0x0075: case 0x0076: case 0x0077: case 0x0078: case 0x0079: case 0x007A: case 0x007B: case 0x007C: case 0x007D: case 0x007E: break; case 0x001A: ch = 0x7F; break; case 0x001C: ch = 0x1A; break; case 0x007F: ch = 0x1C; break; case 0x00A0: ch = 0xFF; break; case 0x00A3: ch = 0x9C; break; case 0x00A6: ch = 0x8A; break; case 0x00A7: ch = 0xF5; break; case 0x00A8: ch = 0xF9; break; case 0x00A9: ch = 0x97; break; case 0x00AB: ch = 0xAE; break; case 0x00AC: ch = 0x89; break; case 0x00AD: ch = 0xF0; break; case 0x00B0: ch = 0xF8; break; case 0x00B1: ch = 0xF1; break; case 0x00B2: ch = 0x99; break; case 0x00B3: ch = 0x9A; break; case 0x00B4: ch = 0xEF; break; case 0x00B6: ch = 0x14; break; case 0x00B7: ch = 0x88; break; case 0x00BB: ch = 0xAF; break; case 0x00BD: ch = 0xAB; break; case 0x0385: ch = 0xF7; break; case 0x0386: ch = 0x86; break; case 0x0387: ch = 0x88; break; case 0x0388: ch = 0x8D; break; case 0x0389: ch = 0x8F; break; case 0x038A: ch = 0x90; break; case 0x038C: ch = 0x92; break; case 0x038E: ch = 0x95; break; case 0x038F: ch = 0x98; break; case 0x0390: ch = 0xA1; break; case 0x0391: case 0x0392: case 0x0393: case 0x0394: case 0x0395: case 0x0396: case 0x0397: ch -= 0x02ED; break; case 0x0398: ch = 0xAC; break; case 0x0399: ch = 0xAD; break; case 0x039A: case 0x039B: case 0x039C: case 0x039D: ch -= 0x02E5; break; case 0x039E: ch = 0xBD; break; case 0x039F: ch = 0xBE; break; case 0x03A0: ch = 0xC6; break; case 0x03A1: ch = 0xC7; break; case 0x03A3: case 0x03A4: case 0x03A5: case 0x03A6: case 0x03A7: case 0x03A8: case 0x03A9: ch -= 0x02D4; break; case 0x03AA: ch = 0x91; break; case 0x03AB: ch = 0x96; break; case 0x03AC: ch = 0x9B; break; case 0x03AD: ch = 0x9D; break; case 0x03AE: ch = 0x9E; break; case 0x03AF: ch = 0x9F; break; case 0x03B0: ch = 0xFC; break; case 0x03B1: ch = 0xD6; break; case 0x03B2: ch = 0xD7; break; case 0x03B3: ch = 0xD8; break; case 0x03B4: ch = 0xDD; break; case 0x03B5: ch = 0xDE; break; case 0x03B6: case 0x03B7: case 0x03B8: case 0x03B9: case 0x03BA: case 0x03BB: case 0x03BC: case 0x03BD: case 0x03BE: case 0x03BF: case 0x03C0: case 0x03C1: ch -= 0x02D6; break; case 0x03C2: ch = 0xED; break; case 0x03C3: ch = 0xEC; break; case 0x03C4: ch = 0xEE; break; case 0x03C5: ch = 0xF2; break; case 0x03C6: ch = 0xF3; break; case 0x03C7: ch = 0xF4; break; case 0x03C8: ch = 0xF6; break; case 0x03C9: ch = 0xFA; break; case 0x03CA: ch = 0xA0; break; case 0x03CB: ch = 0xFB; break; case 0x03CC: ch = 0xA2; break; case 0x03CD: ch = 0xA3; break; case 0x03CE: ch = 0xFD; break; case 0x03D5: ch = 0xF3; break; case 0x2015: ch = 0x8E; break; case 0x2018: ch = 0x8B; break; case 0x2019: ch = 0x8C; break; case 0x2022: ch = 0x07; break; case 0x203C: ch = 0x13; break; case 0x2190: ch = 0x1B; break; case 0x2191: ch = 0x18; break; case 0x2192: ch = 0x1A; break; case 0x2193: ch = 0x19; break; case 0x2194: ch = 0x1D; break; case 0x2195: ch = 0x12; break; case 0x21A8: ch = 0x17; break; case 0x221F: ch = 0x1C; break; case 0x2302: ch = 0x7F; break; case 0x2500: ch = 0xC4; break; case 0x2502: ch = 0xB3; break; case 0x250C: ch = 0xDA; break; case 0x2510: ch = 0xBF; break; case 0x2514: ch = 0xC0; break; case 0x2518: ch = 0xD9; break; case 0x251C: ch = 0xC3; break; case 0x2524: ch = 0xB4; break; case 0x252C: ch = 0xC2; break; case 0x2534: ch = 0xC1; break; case 0x253C: ch = 0xC5; break; case 0x2550: ch = 0xCD; break; case 0x2551: ch = 0xBA; break; case 0x2554: ch = 0xC9; break; case 0x2557: ch = 0xBB; break; case 0x255A: ch = 0xC8; break; case 0x255D: ch = 0xBC; break; case 0x2560: ch = 0xCC; break; case 0x2563: ch = 0xB9; break; case 0x2566: ch = 0xCB; break; case 0x2569: ch = 0xCA; break; case 0x256C: ch = 0xCE; break; case 0x2580: ch = 0xDF; break; case 0x2584: ch = 0xDC; break; case 0x2588: ch = 0xDB; break; case 0x2591: ch = 0xB0; break; case 0x2592: ch = 0xB1; break; case 0x2593: ch = 0xB2; break; case 0x25A0: ch = 0xFE; break; case 0x25AC: ch = 0x16; break; case 0x25B2: ch = 0x1E; break; case 0x25BA: ch = 0x10; break; case 0x25BC: ch = 0x1F; break; case 0x25C4: ch = 0x11; break; case 0x25CB: ch = 0x09; break; case 0x25D8: ch = 0x08; break; case 0x25D9: ch = 0x0A; break; case 0x263A: ch = 0x01; break; case 0x263B: ch = 0x02; break; case 0x263C: ch = 0x0F; break; case 0x2640: ch = 0x0C; break; case 0x2642: ch = 0x0B; break; case 0x2660: ch = 0x06; break; case 0x2663: ch = 0x05; break; case 0x2665: ch = 0x03; break; case 0x2666: ch = 0x04; break; case 0x266A: ch = 0x0D; break; case 0x266B: ch = 0x0E; break; case 0xFFE8: ch = 0xB3; break; case 0xFFE9: ch = 0x1B; break; case 0xFFEA: ch = 0x18; break; case 0xFFEB: ch = 0x1A; break; case 0xFFEC: ch = 0x19; break; case 0xFFED: ch = 0xFE; break; case 0xFFEE: ch = 0x09; break; default: { if(ch >= 0xFF01 && ch <= 0xFF5E) ch -= 0xFEE0; else ch = 0x3F; } break; } bytes[byteIndex++] = (byte)ch; --charCount; } } }; // class CP869 public class ENCibm869 : CP869 { public ENCibm869() : base() {} }; // class ENCibm869 }; // namespace I18N.Rare
// 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. using System; using System.Collections.Generic; using System.Linq; using System.Text; using RoslynToCCICodeModel; using System.Diagnostics.Contracts; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis; using System.Threading; using Microsoft.CodeAnalysis.Text; namespace ClousotExtension { [ContractVerification(true)] public static class ISymbolExtensions { public static bool TryGetType(this ISymbol symbol, out ITypeSymbol type) { Contract.Requires(symbol != null); Contract.Ensures(!Contract.Result<bool>() || Contract.ValueAtReturn(out type) != null); var asLocal = symbol as ILocalSymbol; if (asLocal != null) { type = asLocal.Type; Contract.Assume(type != null, "Missing contract on Roslyn API"); return true; } var asParam = symbol as IParameterSymbol; if (asParam != null) { type = asParam.Type; Contract.Assume(type != null, "Missing contract on Roslyn API"); return true; } var asField = symbol as IFieldSymbol; if (asField != null) { type = asField.Type; Contract.Assume(type != null, "Missing contract on Roslyn API"); return true; } type = null; return false; } } public static class StatementSyntaxExtensions { static public bool IsPrecondition(this StatementSyntax statementSyntax) { var exprStmt = statementSyntax as ExpressionStatementSyntax; if (exprStmt == null) return false; var expr = exprStmt.Expression as InvocationExpressionSyntax; if (expr == null) return false; var method = expr.Expression as MemberAccessExpressionSyntax; if (method == null) return false; return (method.Name.Identifier.ValueText.Equals("Requires")); } static public bool IsPostcondition(this StatementSyntax statementSyntax) { var exprStmt = statementSyntax as ExpressionStatementSyntax; if (exprStmt == null) return false; var expr = exprStmt.Expression as InvocationExpressionSyntax; if (expr == null) return false; var method = expr.Expression as MemberAccessExpressionSyntax; if (method == null) return false; return (method.Name.Identifier.ValueText.Equals("Ensures")); } } public static class MethodDeclarationSyntaxExtensions { static public TMethodDeclarationSyntax InsertStatements<TMethodDeclarationSyntax>(this TMethodDeclarationSyntax method, StatementSyntax statement, ContractKind kind, bool avoidDuplicates = true) where TMethodDeclarationSyntax : BaseMethodDeclarationSyntax { Contract.Requires(statement != null); if (method.Body == null) return null; var oldStatements = method.Body.Statements; var newStatements = new List<StatementSyntax>(); var conditionText = statement.GetText(); var n = oldStatements.Count; var i = 0; // Take a prefix of the oldStatments before inserting "statement". if (kind == ContractKind.Precondition) { // prefix = "precondition" ==> all existing preconditions while (i < n) { if (!oldStatements[i].IsPrecondition()) break; if (avoidDuplicates && oldStatements[i].GetText() == conditionText) return method; newStatements.Add(oldStatements[i]); i++; } newStatements.Add(statement); while (i < n) { newStatements.Add(oldStatements[i]); i++; } } else if (kind == ContractKind.Postcondition) { // prefix = "postcondition" ==> all existing contracts while (i < n && (oldStatements[i].IsPostcondition() || oldStatements[i].IsPrecondition())) { if (avoidDuplicates && oldStatements[i].IsPostcondition() && oldStatements[i].GetText() == conditionText) return method; newStatements.Add(oldStatements[i]); i++; } while (i < n) { if (!oldStatements[i].IsPostcondition()) break; if (avoidDuplicates && oldStatements[i].GetText() == conditionText) return method; newStatements.Add(oldStatements[i]); i++; } newStatements.Add(statement); while (i < n) { newStatements.Add(oldStatements[i]); i++; } } else { newStatements.Add(statement); newStatements.AddRange(oldStatements); } var x = SyntaxFactory.List<StatementSyntax>(newStatements); if (method is ConstructorDeclarationSyntax) { var methodConstructor = method as ConstructorDeclarationSyntax; return SyntaxFactory.ConstructorDeclaration( attributeLists: methodConstructor.AttributeLists, modifiers: methodConstructor.Modifiers, identifier: methodConstructor.Identifier, parameterList: method.ParameterList, initializer: null, body: SyntaxFactory.Block(statements: x) ) as TMethodDeclarationSyntax; } if (method is ConversionOperatorDeclarationSyntax) { throw new NotImplementedException(); } if (method is DestructorDeclarationSyntax) { throw new NotImplementedException(); } if (method is MethodDeclarationSyntax) { var methodMethod = method as MethodDeclarationSyntax; return SyntaxFactory.MethodDeclaration( attributeLists: methodMethod.AttributeLists, modifiers: methodMethod.Modifiers, returnType: methodMethod.ReturnType, explicitInterfaceSpecifier: methodMethod.ExplicitInterfaceSpecifier, identifier: methodMethod.Identifier, typeParameterList: methodMethod.TypeParameterList, parameterList: method.ParameterList, constraintClauses: methodMethod.ConstraintClauses, body: SyntaxFactory.Block(statements: x) ) as TMethodDeclarationSyntax; } if (method is OperatorDeclarationSyntax) { throw new NotImplementedException(); } throw new NotSupportedException(); } static public bool ContainsSuggestion(this BaseMethodDeclarationSyntax method, string suggestion) { if (method == null || method.Body == null) { return false; } // Smarter way is to look up to the end of contracts foreach (var statement in method.Body.Statements) { if (statement.ToString() == suggestion) return true; } return false; } } public static class StringExtensions { public static string AddParentheses(this string s, char open = '(', char close = ')') { if (s == null) { return s; } return string.Format("{0} {1} {2}", open, s, close); } public static ContractKind ToContractKind(this string s) { s = s.ToLower(); switch (s) { case "assume": return ContractKind.Assume; case "code fix": return ContractKind.CodeFix; case "requires": return ContractKind.Precondition; case "ensures": return ContractKind.Postcondition; case "invariant": return ContractKind.ObjectInvariant; } if (s.Contains("assume")) return ContractKind.Assume; if (s.Contains("code fix")) return ContractKind.CodeFix; if(s.Contains("precondition")) return ContractKind.Precondition; if(s.Contains("postcondition")) return ContractKind.Postcondition; if(s.Contains("invariant")) return ContractKind.ObjectInvariant; if (s.Contains("abstract state")) return ContractKind.AbstractState; throw new InvalidOperationException(); } public static bool TryParseSuggestion(this string s, out ContractKind kind, out string condition) { if (s == null || !s.ToLower().Contains("suggestion")) { kind = default(ContractKind); condition = null; return false; } var where = s.LastIndexOf(':')+1; if (where > 0) { condition = s.Substring(where); if (s.Contains("Requires")) { kind = ContractKind.Precondition; return true; } else if (s.Contains("Ensures")) { kind = ContractKind.Postcondition; return true; } else if (s.Contains("Invariant")) { kind = ContractKind.ObjectInvariant; return true; } else { kind = default(ContractKind); condition = null; return false; } } kind = default(ContractKind); condition = null; return false; } } public static class DocumentExtensions { public static SyntaxNode GetSyntaxRoot(this Document d, CancellationToken token) { return d.GetSyntaxRootAsync(token).Result; } public static SyntaxNode GetSyntaxRoot(this Document d) { return d.GetSyntaxRootAsync().Result; } public static SyntaxTree GetSyntaxTree(this Document d, CancellationToken token) { return d.GetSyntaxTreeAsync(token).Result; } public static SemanticModel GetSemanticModel(this Document d, CancellationToken token) { return d.GetSemanticModelAsync(token).Result; } public static SourceText GetText(this Document d) { return d.GetTextAsync().Result; } } }
using System; using System.Collections; using System.Collections.Generic; using Server; using Server.Mobiles; using Server.Commands; namespace Server.Regions { public class SpawnEntry : ISpawner { public static readonly TimeSpan DefaultMinSpawnTime = TimeSpan.FromMinutes( 2.0 ); public static readonly TimeSpan DefaultMaxSpawnTime = TimeSpan.FromMinutes( 5.0 ); private static Hashtable m_Table = new Hashtable(); public static Hashtable Table{ get{ return m_Table; } } // When a creature's AI is deactivated (PlayerRangeSensitive optimization) does it return home? public bool ReturnOnDeactivate{ get{ return true; } } // Are creatures unlinked on taming (true) or should they also go out of the region (false)? public bool UnlinkOnTaming{ get{ return false; } } // Are unlinked and untamed creatures removed after 20 hours? public bool RemoveIfUntamed{ get{ return true; } } public static readonly Direction InvalidDirection = Direction.Running; private int m_ID; private BaseRegion m_Region; private Point3D m_Home; private int m_Range; private Direction m_Direction; private SpawnDefinition m_Definition; private List<ISpawnable> m_SpawnedObjects; private int m_Max; private TimeSpan m_MinSpawnTime; private TimeSpan m_MaxSpawnTime; private bool m_Running; private DateTime m_NextSpawn; private Timer m_SpawnTimer; public int ID{ get{ return m_ID; } } public BaseRegion Region{ get{ return m_Region; } } public Point3D HomeLocation{ get{ return m_Home; } } public int HomeRange{ get{ return m_Range; } } public Direction Direction{ get{ return m_Direction; } } public SpawnDefinition Definition{ get{ return m_Definition; } } public List<ISpawnable> SpawnedObjects{ get{ return m_SpawnedObjects; } } public int Max{ get{ return m_Max; } } public TimeSpan MinSpawnTime{ get{ return m_MinSpawnTime; } } public TimeSpan MaxSpawnTime{ get{ return m_MaxSpawnTime; } } public bool Running{ get{ return m_Running; } } public bool Complete{ get{ return m_SpawnedObjects.Count >= m_Max; } } public bool Spawning{ get{ return m_Running && !this.Complete; } } public SpawnEntry( int id, BaseRegion region, Point3D home, int range, Direction direction, SpawnDefinition definition, int max, TimeSpan minSpawnTime, TimeSpan maxSpawnTime ) { m_ID = id; m_Region = region; m_Home = home; m_Range = range; m_Direction = direction; m_Definition = definition; m_SpawnedObjects = new List<ISpawnable>(); m_Max = max; m_MinSpawnTime = minSpawnTime; m_MaxSpawnTime = maxSpawnTime; m_Running = false; if ( m_Table.Contains( id ) ) Console.WriteLine( "Warning: double SpawnEntry ID '{0}'", id ); else m_Table[id] = this; } public Point3D RandomSpawnLocation( int spawnHeight, bool land, bool water ) { return m_Region.RandomSpawnLocation( spawnHeight, land, water, m_Home, m_Range ); } public void Start() { if ( m_Running ) return; m_Running = true; CheckTimer(); } public void Stop() { if ( !m_Running ) return; m_Running = false; CheckTimer(); } private void Spawn() { ISpawnable spawn = m_Definition.Spawn(this); if ( spawn != null ) Add( spawn ); } private void Add( ISpawnable spawn ) { m_SpawnedObjects.Add( spawn ); spawn.Spawner = this; if ( spawn is BaseCreature ) ((BaseCreature)spawn).RemoveIfUntamed = this.RemoveIfUntamed; } void ISpawner.Remove( ISpawnable spawn ) { m_SpawnedObjects.Remove( spawn ); CheckTimer(); } private TimeSpan RandomTime() { int min = (int) m_MinSpawnTime.TotalSeconds; int max = (int) m_MaxSpawnTime.TotalSeconds; int rand = Utility.RandomMinMax( min, max ); return TimeSpan.FromSeconds( rand ); } private void CheckTimer() { if ( this.Spawning ) { if ( m_SpawnTimer == null ) { TimeSpan time = RandomTime(); m_SpawnTimer = Timer.DelayCall( time, new TimerCallback( TimerCallback ) ); m_NextSpawn = DateTime.Now + time; } } else if ( m_SpawnTimer != null ) { m_SpawnTimer.Stop(); m_SpawnTimer = null; } } private void TimerCallback() { int amount = Math.Max( (m_Max - m_SpawnedObjects.Count) / 3, 1 ); for ( int i = 0; i < amount; i++ ) Spawn(); m_SpawnTimer = null; CheckTimer(); } public void DeleteSpawnedObjects() { InternalDeleteSpawnedObjects(); m_Running = false; CheckTimer(); } private void InternalDeleteSpawnedObjects() { foreach ( ISpawnable spawnable in m_SpawnedObjects ) { spawnable.Spawner = null; bool uncontrolled = !(spawnable is BaseCreature) || !((BaseCreature)spawnable).Controlled; if( uncontrolled ) spawnable.Delete(); } m_SpawnedObjects.Clear(); } public void Respawn() { InternalDeleteSpawnedObjects(); for ( int i = 0; !this.Complete && i < m_Max; i++ ) Spawn(); m_Running = true; CheckTimer(); } public void Delete() { m_Max = 0; InternalDeleteSpawnedObjects(); if ( m_SpawnTimer != null ) { m_SpawnTimer.Stop(); m_SpawnTimer = null; } if ( m_Table[m_ID] == this ) m_Table.Remove( m_ID ); } public void Serialize( GenericWriter writer ) { writer.Write( (int) m_SpawnedObjects.Count ); for ( int i = 0; i < m_SpawnedObjects.Count; i++ ) { ISpawnable spawn = m_SpawnedObjects[i]; int serial = spawn.Serial; writer.Write( (int) serial ); } writer.Write( (bool) m_Running ); if ( m_SpawnTimer != null ) { writer.Write( true ); writer.WriteDeltaTime( (DateTime) m_NextSpawn ); } else { writer.Write( false ); } } public void Deserialize( GenericReader reader, int version ) { int count = reader.ReadInt(); for ( int i = 0; i < count; i++ ) { int serial = reader.ReadInt(); ISpawnable spawnableEntity = World.FindEntity( serial ) as ISpawnable; if (spawnableEntity != null) Add(spawnableEntity); } m_Running = reader.ReadBool(); if ( reader.ReadBool() ) { m_NextSpawn = reader.ReadDeltaTime(); if ( this.Spawning ) { if ( m_SpawnTimer != null ) m_SpawnTimer.Stop(); TimeSpan delay = m_NextSpawn - DateTime.Now; m_SpawnTimer = Timer.DelayCall( delay > TimeSpan.Zero ? delay : TimeSpan.Zero, new TimerCallback( TimerCallback ) ); } } CheckTimer(); } private static List<IEntity> m_RemoveList; public static void Remove( GenericReader reader, int version ) { int count = reader.ReadInt(); for ( int i = 0; i < count; i++ ) { int serial = reader.ReadInt(); IEntity entity = World.FindEntity( serial ); if ( entity != null ) { if ( m_RemoveList == null ) m_RemoveList = new List<IEntity>(); m_RemoveList.Add( entity ); } } reader.ReadBool(); // m_Running if ( reader.ReadBool() ) reader.ReadDeltaTime(); // m_NextSpawn } public static void Initialize() { if ( m_RemoveList != null ) { foreach ( IEntity ent in m_RemoveList ) { ent.Delete(); } m_RemoveList = null; } SpawnPersistence.EnsureExistence(); CommandSystem.Register( "RespawnAllRegions", AccessLevel.Administrator, new CommandEventHandler( RespawnAllRegions_OnCommand ) ); CommandSystem.Register( "RespawnRegion", AccessLevel.GameMaster, new CommandEventHandler( RespawnRegion_OnCommand ) ); CommandSystem.Register( "DelAllRegionSpawns", AccessLevel.Administrator, new CommandEventHandler( DelAllRegionSpawns_OnCommand ) ); CommandSystem.Register( "DelRegionSpawns", AccessLevel.GameMaster, new CommandEventHandler( DelRegionSpawns_OnCommand ) ); CommandSystem.Register( "StartAllRegionSpawns", AccessLevel.Administrator, new CommandEventHandler( StartAllRegionSpawns_OnCommand ) ); CommandSystem.Register( "StartRegionSpawns", AccessLevel.GameMaster, new CommandEventHandler( StartRegionSpawns_OnCommand ) ); CommandSystem.Register( "StopAllRegionSpawns", AccessLevel.Administrator, new CommandEventHandler( StopAllRegionSpawns_OnCommand ) ); CommandSystem.Register( "StopRegionSpawns", AccessLevel.GameMaster, new CommandEventHandler( StopRegionSpawns_OnCommand ) ); } private static BaseRegion GetCommandData( CommandEventArgs args ) { Mobile from = args.Mobile; Region reg; if ( args.Length == 0 ) { reg = from.Region; } else { string name = args.GetString( 0 ); //reg = (Region) from.Map.Regions[name]; if ( !from.Map.Regions.TryGetValue( name, out reg ) ) { from.SendMessage( "Could not find region '{0}'.", name ); return null; } } BaseRegion br = reg as BaseRegion; if ( br == null || br.Spawns == null ) { from.SendMessage( "There are no spawners in region '{0}'.", reg ); return null; } return br; } [Usage( "RespawnAllRegions" )] [Description( "Respawns all regions and sets the spawners as running." )] private static void RespawnAllRegions_OnCommand( CommandEventArgs args ) { foreach ( SpawnEntry entry in m_Table.Values ) { entry.Respawn(); } args.Mobile.SendMessage( "All regions have respawned." ); } [Usage( "RespawnRegion [<region name>]" )] [Description( "Respawns the region in which you are (or that you provided) and sets the spawners as running." )] private static void RespawnRegion_OnCommand( CommandEventArgs args ) { BaseRegion region = GetCommandData( args ); if ( region == null ) return; for ( int i = 0; i < region.Spawns.Length; i++ ) region.Spawns[i].Respawn(); args.Mobile.SendMessage( "Region '{0}' has respawned.", region ); } [Usage( "DelAllRegionSpawns" )] [Description( "Deletes all spawned objects of every regions and sets the spawners as not running." )] private static void DelAllRegionSpawns_OnCommand( CommandEventArgs args ) { foreach ( SpawnEntry entry in m_Table.Values ) { entry.DeleteSpawnedObjects(); } args.Mobile.SendMessage( "All region spawned objects have been deleted." ); } [Usage( "DelRegionSpawns [<region name>]" )] [Description( "Deletes all spawned objects of the region in which you are (or that you provided) and sets the spawners as not running." )] private static void DelRegionSpawns_OnCommand( CommandEventArgs args ) { BaseRegion region = GetCommandData( args ); if ( region == null ) return; for ( int i = 0; i < region.Spawns.Length; i++ ) region.Spawns[i].DeleteSpawnedObjects(); args.Mobile.SendMessage( "Spawned objects of region '{0}' have been deleted.", region ); } [Usage( "StartAllRegionSpawns" )] [Description( "Sets the region spawners of all regions as running." )] private static void StartAllRegionSpawns_OnCommand( CommandEventArgs args ) { foreach ( SpawnEntry entry in m_Table.Values ) { entry.Start(); } args.Mobile.SendMessage( "All region spawners have started." ); } [Usage( "StartRegionSpawns [<region name>]" )] [Description( "Sets the region spawners of the region in which you are (or that you provided) as running." )] private static void StartRegionSpawns_OnCommand( CommandEventArgs args ) { BaseRegion region = GetCommandData( args ); if ( region == null ) return; for ( int i = 0; i < region.Spawns.Length; i++ ) region.Spawns[i].Start(); args.Mobile.SendMessage( "Spawners of region '{0}' have started.", region ); } [Usage( "StopAllRegionSpawns" )] [Description( "Sets the region spawners of all regions as not running." )] private static void StopAllRegionSpawns_OnCommand( CommandEventArgs args ) { foreach ( SpawnEntry entry in m_Table.Values ) { entry.Stop(); } args.Mobile.SendMessage( "All region spawners have stopped." ); } [Usage( "StopRegionSpawns [<region name>]" )] [Description( "Sets the region spawners of the region in which you are (or that you provided) as not running." )] private static void StopRegionSpawns_OnCommand( CommandEventArgs args ) { BaseRegion region = GetCommandData( args ); if ( region == null ) return; for ( int i = 0; i < region.Spawns.Length; i++ ) region.Spawns[i].Stop(); args.Mobile.SendMessage( "Spawners of region '{0}' have stopped.", region ); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.Azure.AcceptanceTestsAzureReport { using Azure; using Microsoft.Rest; using Microsoft.Rest.Azure; using Microsoft.Rest.Serialization; 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> /// Test Infrastructure for AutoRest /// </summary> public partial class AutoRestReportServiceForAzureClient : ServiceClient<AutoRestReportServiceForAzureClient>, IAutoRestReportServiceForAzureClient, IAzureClient { /// <summary> /// The base URI of the service. /// </summary> public System.Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> public JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// Credentials needed for the client to connect to Azure. /// </summary> public ServiceClientCredentials Credentials { get; private set; } /// <summary> /// Gets or sets the preferred language for the response. /// </summary> public string AcceptLanguage { get; set; } /// <summary> /// Gets or sets the retry timeout in seconds for Long Running Operations. /// Default value is 30. /// </summary> public int? LongRunningOperationRetryTimeout { get; set; } /// <summary> /// When set to true a unique x-ms-client-request-id value is generated and /// included in each request. Default is true. /// </summary> public bool? GenerateClientRequestId { get; set; } /// <summary> /// Initializes a new instance of the AutoRestReportServiceForAzureClient class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected AutoRestReportServiceForAzureClient(params System.Net.Http.DelegatingHandler[] handlers) : base(handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the AutoRestReportServiceForAzureClient class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected AutoRestReportServiceForAzureClient(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : base(rootHandler, handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the AutoRestReportServiceForAzureClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected AutoRestReportServiceForAzureClient(System.Uri baseUri, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the AutoRestReportServiceForAzureClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected AutoRestReportServiceForAzureClient(System.Uri baseUri, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the AutoRestReportServiceForAzureClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AutoRestReportServiceForAzureClient(ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the AutoRestReportServiceForAzureClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AutoRestReportServiceForAzureClient(ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the AutoRestReportServiceForAzureClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AutoRestReportServiceForAzureClient(System.Uri baseUri, ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } BaseUri = baseUri; Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the AutoRestReportServiceForAzureClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AutoRestReportServiceForAzureClient(System.Uri baseUri, ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } BaseUri = baseUri; Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// An optional partial-method to perform custom initialization. /// </summary> partial void CustomInitialize(); /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { BaseUri = new System.Uri("http://localhost"); AcceptLanguage = "en-US"; LongRunningOperationRetryTimeout = 30; GenerateClientRequestId = true; SerializationSettings = new JsonSerializerSettings { Formatting = Formatting.Indented, DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Utc, NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; DeserializationSettings = new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Utc, NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; CustomInitialize(); DeserializationSettings.Converters.Add(new CloudErrorJsonConverter()); } /// <summary> /// Get test coverage report /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IDictionary<string, int?>>> GetReportWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetReport", tracingParameters); } // Construct URL var _baseUrl = BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "report/azure").ToString(); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (GenerateClientRequestId != null && GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", 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 (Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await 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 ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IDictionary<string, int?>>(); _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 = SafeJsonConvert.DeserializeObject<IDictionary<string, int?>>(_responseContent, 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; } } }
// 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.Text; using System.Reflection; using System.Diagnostics; using System.Globalization; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.CompilerServices; using System.Reflection.Runtime.TypeInfos; using System.Reflection.Runtime.Assemblies; using System.Reflection.Runtime.MethodInfos; using Internal.LowLevelLinq; using Internal.Runtime.Augments; using Internal.Reflection.Core.Execution; using Internal.Reflection.Core.NonPortable; using Internal.Reflection.Extensions.NonPortable; namespace System.Reflection.Runtime.General { internal static partial class Helpers { // This helper helps reduce the temptation to write "h == default(RuntimeTypeHandle)" which causes boxing. public static bool IsNull(this RuntimeTypeHandle h) { return h.Equals(default(RuntimeTypeHandle)); } // Clones a Type[] array for the purpose of returning it from an api. public static Type[] CloneTypeArray(this Type[] types) { int count = types.Length; if (count == 0) return Array.Empty<Type>(); // Ok not to clone empty arrays - those are immutable. Type[] clonedTypes = new Type[count]; for (int i = 0; i < count; i++) { clonedTypes[i] = types[i]; } return clonedTypes; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Type[] GetGenericTypeParameters(this Type type) { Debug.Assert(type.IsGenericTypeDefinition); return type.GetGenericArguments(); } public static RuntimeTypeInfo[] ToRuntimeTypeInfoArray(this Type[] types) { int count = types.Length; RuntimeTypeInfo[] typeInfos = new RuntimeTypeInfo[count]; for (int i = 0; i < count; i++) { typeInfos[i] = types[i].CastToRuntimeTypeInfo(); } return typeInfos; } public static string LastResortString(this RuntimeTypeHandle typeHandle) { return ReflectionCoreExecution.ExecutionEnvironment.GetLastResortString(typeHandle); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static RuntimeNamedTypeInfo CastToRuntimeNamedTypeInfo(this Type type) { Debug.Assert(type is RuntimeNamedTypeInfo); return (RuntimeNamedTypeInfo)type; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static RuntimeTypeInfo CastToRuntimeTypeInfo(this Type type) { Debug.Assert(type == null || type is RuntimeTypeInfo); return (RuntimeTypeInfo)type; } public static ReadOnlyCollection<T> ToReadOnlyCollection<T>(this IEnumerable<T> enumeration) { return new ReadOnlyCollection<T>(enumeration.ToArray()); } public static MethodInfo FilterAccessor(this MethodInfo accessor, bool nonPublic) { if (nonPublic) return accessor; if (accessor.IsPublic) return accessor; return null; } public static Type GetTypeCore(this Assembly assembly, string name, bool ignoreCase) { if (assembly is RuntimeAssembly runtimeAssembly) { // Not a recursion - this one goes to the actual instance method on RuntimeAssembly. return runtimeAssembly.GetTypeCore(name, ignoreCase: ignoreCase); } else { // This is a third-party Assembly object. We can emulate GetTypeCore() by calling the public GetType() // method. This is wasteful because it'll probably reparse a type string that we've already parsed // but it can't be helped. string escapedName = name.EscapeTypeNameIdentifier(); return assembly.GetType(escapedName, throwOnError: false, ignoreCase: ignoreCase); } } public static TypeLoadException CreateTypeLoadException(string typeName, Assembly assemblyIfAny) { if (assemblyIfAny == null) throw new TypeLoadException(SR.Format(SR.TypeLoad_TypeNotFound, typeName)); else throw Helpers.CreateTypeLoadException(typeName, assemblyIfAny.FullName); } public static TypeLoadException CreateTypeLoadException(string typeName, string assemblyName) { string message = SR.Format(SR.TypeLoad_TypeNotFoundInAssembly, typeName, assemblyName); return ReflectionCoreNonPortable.CreateTypeLoadException(message, typeName); } // Escape identifiers as described in "Specifying Fully Qualified Type Names" on msdn. // Current link is http://msdn.microsoft.com/en-us/library/yfsftwz6(v=vs.110).aspx public static string EscapeTypeNameIdentifier(this string identifier) { // Some characters in a type name need to be escaped if (identifier != null && identifier.IndexOfAny(s_charsToEscape) != -1) { StringBuilder sbEscapedName = new StringBuilder(identifier.Length); foreach (char c in identifier) { if (c.NeedsEscapingInTypeName()) sbEscapedName.Append('\\'); sbEscapedName.Append(c); } identifier = sbEscapedName.ToString(); } return identifier; } public static bool NeedsEscapingInTypeName(this char c) { return Array.IndexOf(s_charsToEscape, c) >= 0; } private static readonly char[] s_charsToEscape = new char[] { '\\', '[', ']', '+', '*', '&', ',' }; public static RuntimeMethodInfo GetInvokeMethod(this RuntimeTypeInfo delegateType) { Debug.Assert(delegateType.IsDelegate); MethodInfo invokeMethod = delegateType.GetMethod("Invoke", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly); if (invokeMethod == null) { // No Invoke method found. Since delegate types are compiler constructed, the most likely cause is missing metadata rather than // a missing Invoke method. // We're deliberating calling FullName rather than ToString() because if it's the type that's missing metadata, // the FullName property constructs a more informative MissingMetadataException than we can. string fullName = delegateType.FullName; throw new MissingMetadataException(SR.Format(SR.Arg_InvokeMethodMissingMetadata, fullName)); // No invoke method found. } return (RuntimeMethodInfo)invokeMethod; } public static BinderBundle ToBinderBundle(this Binder binder, BindingFlags invokeAttr, CultureInfo cultureInfo) { if (binder == null || binder is DefaultBinder || ((invokeAttr & BindingFlags.ExactBinding) != 0)) return null; return new BinderBundle(binder, cultureInfo); } // Helper for ICustomAttributeProvider.GetCustomAttributes(). The result of this helper is returned directly to apps // so it must always return a newly allocated array. Unlike most of the newer custom attribute apis, the attribute type // need not derive from System.Attribute. (In particular, it can be an interface or System.Object.) public static object[] InstantiateAsArray(this IEnumerable<CustomAttributeData> cads, Type actualElementType) { LowLevelList<object> attributes = new LowLevelList<object>(); foreach (CustomAttributeData cad in cads) { object instantiatedAttribute = cad.Instantiate(); attributes.Add(instantiatedAttribute); } int count = attributes.Count; object[] result = (object[])Array.CreateInstance(actualElementType, count); attributes.CopyTo(result, 0); return result; } public static bool GetCustomAttributeDefaultValueIfAny(IEnumerable<CustomAttributeData> customAttributes, bool raw, out object defaultValue) { // Legacy: If there are multiple default value attribute, the desktop picks one at random (and so do we...) foreach (CustomAttributeData cad in customAttributes) { Type attributeType = cad.AttributeType; if (attributeType.IsSubclassOf(typeof(CustomConstantAttribute))) { if (raw) { foreach (CustomAttributeNamedArgument namedArgument in cad.NamedArguments) { if (namedArgument.MemberInfo.Name.Equals("Value")) { defaultValue = namedArgument.TypedValue.Value; return true; } } defaultValue = null; return false; } else { CustomConstantAttribute customConstantAttribute = (CustomConstantAttribute)(cad.Instantiate()); defaultValue = customConstantAttribute.Value; return true; } } if (attributeType.Equals(typeof(DecimalConstantAttribute))) { // We should really do a non-instanting check if "raw == false" but given that we don't support // reflection-only loads, there isn't an observable difference. DecimalConstantAttribute decimalConstantAttribute = (DecimalConstantAttribute)(cad.Instantiate()); defaultValue = decimalConstantAttribute.Value; return true; } } defaultValue = null; return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using Microsoft.CSharp.RuntimeBinder.Errors; using Microsoft.CSharp.RuntimeBinder.Syntax; namespace Microsoft.CSharp.RuntimeBinder.Semantics { internal enum ACCESSERROR { ACCESSERROR_NOACCESS, ACCESSERROR_NOACCESSTHRU, ACCESSERROR_NOERROR }; // // Semantic check methods on SymbolLoader // internal abstract class CSemanticChecker { // Generate an error if CType is static. public bool CheckForStaticClass(Symbol symCtx, CType CType, ErrorCode err) { if (!CType.isStaticClass()) return false; ReportStaticClassError(symCtx, CType, err); return true; } public virtual ACCESSERROR CheckAccess2(Symbol symCheck, AggregateType atsCheck, Symbol symWhere, CType typeThru) { Debug.Assert(symCheck != null); Debug.Assert(atsCheck == null || symCheck.parent == atsCheck.getAggregate()); Debug.Assert(typeThru == null || typeThru.IsAggregateType() || typeThru.IsTypeParameterType() || typeThru.IsArrayType() || typeThru.IsNullableType() || typeThru.IsErrorType()); #if DEBUG switch (symCheck.getKind()) { default: break; case SYMKIND.SK_MethodSymbol: case SYMKIND.SK_PropertySymbol: case SYMKIND.SK_FieldSymbol: case SYMKIND.SK_EventSymbol: Debug.Assert(atsCheck != null); break; } #endif // DEBUG ACCESSERROR error = CheckAccessCore(symCheck, atsCheck, symWhere, typeThru); if (ACCESSERROR.ACCESSERROR_NOERROR != error) { return error; } // Check the accessibility of the return CType. CType CType = symCheck.getType(); if (CType == null) { return ACCESSERROR.ACCESSERROR_NOERROR; } // For members of AGGSYMs, atsCheck should always be specified! Debug.Assert(atsCheck != null); // Substitute on the CType. if (atsCheck.GetTypeArgsAll().Count > 0) { CType = SymbolLoader.GetTypeManager().SubstType(CType, atsCheck); } return CheckTypeAccess(CType, symWhere) ? ACCESSERROR.ACCESSERROR_NOERROR : ACCESSERROR.ACCESSERROR_NOACCESS; } public virtual bool CheckTypeAccess(CType type, Symbol symWhere) { Debug.Assert(type != null); // Array, Ptr, Nub, etc don't matter. type = type.GetNakedType(true); if (!type.IsAggregateType()) { Debug.Assert(type.IsVoidType() || type.IsErrorType() || type.IsTypeParameterType()); return true; } for (AggregateType ats = type.AsAggregateType(); ats != null; ats = ats.outerType) { if (ACCESSERROR.ACCESSERROR_NOERROR != CheckAccessCore(ats.GetOwningAggregate(), ats.outerType, symWhere, null)) { return false; } } TypeArray typeArgs = type.AsAggregateType().GetTypeArgsAll(); for (int i = 0; i < typeArgs.Count; i++) { if (!CheckTypeAccess(typeArgs[i], symWhere)) return false; } return true; } // Generates an error for static classes public void ReportStaticClassError(Symbol symCtx, CType CType, ErrorCode err) { if (symCtx != null) ErrorContext.Error(err, CType, new ErrArgRef(symCtx)); else ErrorContext.Error(err, CType); } public abstract SymbolLoader SymbolLoader { get; } public abstract SymbolLoader GetSymbolLoader(); ///////////////////////////////////////////////////////////////////////////////// // SymbolLoader forwarders (begin) // private ErrorHandling ErrorContext { get { return SymbolLoader.ErrorContext; } } public ErrorHandling GetErrorContext() { return ErrorContext; } public NameManager GetNameManager() { return SymbolLoader.GetNameManager(); } public TypeManager GetTypeManager() { return SymbolLoader.GetTypeManager(); } public BSYMMGR getBSymmgr() { return SymbolLoader.getBSymmgr(); } public SymFactory GetGlobalSymbolFactory() { return SymbolLoader.GetGlobalSymbolFactory(); } public MiscSymFactory GetGlobalMiscSymFactory() { return SymbolLoader.GetGlobalMiscSymFactory(); } //protected CompilerPhase GetCompPhase() { return SymbolLoader.CompPhase(); } //protected void SetCompPhase(CompilerPhase compPhase) { SymbolLoader.compPhase = compPhase; } public PredefinedTypes getPredefTypes() { return SymbolLoader.getPredefTypes(); } // // SymbolLoader forwarders (end) ///////////////////////////////////////////////////////////////////////////////// // // Utility methods // private ACCESSERROR CheckAccessCore(Symbol symCheck, AggregateType atsCheck, Symbol symWhere, CType typeThru) { Debug.Assert(symCheck != null); Debug.Assert(atsCheck == null || symCheck.parent == atsCheck.getAggregate()); Debug.Assert(typeThru == null || typeThru.IsAggregateType() || typeThru.IsTypeParameterType() || typeThru.IsArrayType() || typeThru.IsNullableType() || typeThru.IsErrorType()); switch (symCheck.GetAccess()) { default: throw Error.InternalCompilerError(); //return ACCESSERROR.ACCESSERROR_NOACCESS; case ACCESS.ACC_UNKNOWN: return ACCESSERROR.ACCESSERROR_NOACCESS; case ACCESS.ACC_PUBLIC: return ACCESSERROR.ACCESSERROR_NOERROR; case ACCESS.ACC_PRIVATE: case ACCESS.ACC_PROTECTED: if (symWhere == null) { return ACCESSERROR.ACCESSERROR_NOACCESS; } break; case ACCESS.ACC_INTERNAL: case ACCESS.ACC_INTERNALPROTECTED: // Check internal, then protected. if (symWhere == null) { return ACCESSERROR.ACCESSERROR_NOACCESS; } if (symWhere.SameAssemOrFriend(symCheck)) { return ACCESSERROR.ACCESSERROR_NOERROR; } if (symCheck.GetAccess() == ACCESS.ACC_INTERNAL) { return ACCESSERROR.ACCESSERROR_NOACCESS; } break; } // Should always have atsCheck for private and protected access check. // We currently don't need it since access doesn't respect instantiation. // We just use symWhere.parent.AsAggregateSymbol() instead. AggregateSymbol aggCheck = symCheck.parent.AsAggregateSymbol(); // Find the inner-most enclosing AggregateSymbol. AggregateSymbol aggWhere = null; for (Symbol symT = symWhere; symT != null; symT = symT.parent) { if (symT.IsAggregateSymbol()) { aggWhere = symT.AsAggregateSymbol(); break; } if (symT.IsAggregateDeclaration()) { aggWhere = symT.AsAggregateDeclaration().Agg(); break; } } if (aggWhere == null) { return ACCESSERROR.ACCESSERROR_NOACCESS; } // First check for private access. for (AggregateSymbol agg = aggWhere; agg != null; agg = agg.GetOuterAgg()) { if (agg == aggCheck) { return ACCESSERROR.ACCESSERROR_NOERROR; } } if (symCheck.GetAccess() == ACCESS.ACC_PRIVATE) { return ACCESSERROR.ACCESSERROR_NOACCESS; } // Handle the protected case - which is the only real complicated one. Debug.Assert(symCheck.GetAccess() == ACCESS.ACC_PROTECTED || symCheck.GetAccess() == ACCESS.ACC_INTERNALPROTECTED); // Check if symCheck is in aggWhere or a base of aggWhere, // or in an outer agg of aggWhere or a base of an outer agg of aggWhere. AggregateType atsThru = null; if (typeThru != null && !symCheck.isStatic) { atsThru = SymbolLoader.GetAggTypeSym(typeThru); } // Look for aggCheck among the base classes of aggWhere and outer aggs. bool found = false; for (AggregateSymbol agg = aggWhere; agg != null; agg = agg.GetOuterAgg()) { Debug.Assert(agg != aggCheck); // We checked for this above. // Look for aggCheck among the base classes of agg. if (agg.FindBaseAgg(aggCheck)) { found = true; // aggCheck is a base class of agg. Check atsThru. // For non-static protected access to be legal, atsThru must be an instantiation of // agg or a CType derived from an instantiation of agg. In this case // all that matters is that agg is in the base AggregateSymbol chain of atsThru. The // actual AGGTYPESYMs involved don't matter. if (atsThru == null || atsThru.getAggregate().FindBaseAgg(agg)) { return ACCESSERROR.ACCESSERROR_NOERROR; } } } // the CType in which the method is being called has no relationship with the // CType on which the method is defined surely this is NOACCESS and not NOACCESSTHRU if (found == false) return ACCESSERROR.ACCESSERROR_NOACCESS; return (atsThru == null) ? ACCESSERROR.ACCESSERROR_NOACCESS : ACCESSERROR.ACCESSERROR_NOACCESSTHRU; } public bool CheckBogus(Symbol sym) { if (sym == null) { return false; } if (!sym.hasBogus()) { bool fBogus = sym.computeCurrentBogusState(); if (fBogus) { // Only set this if everything is declared or // at least 1 declared thing is bogus sym.setBogus(fBogus); } } return sym.hasBogus() && sym.checkBogus(); } public bool CheckBogus(CType pType) { if (pType == null) { return false; } if (!pType.hasBogus()) { bool fBogus = pType.computeCurrentBogusState(); if (fBogus) { // Only set this if everything is declared or // at least 1 declared thing is bogus pType.setBogus(fBogus); } } return pType.hasBogus() && pType.checkBogus(); } public void ReportAccessError(SymWithType swtBad, Symbol symWhere, CType typeQual) { Debug.Assert(!CheckAccess(swtBad.Sym, swtBad.GetType(), symWhere, typeQual) || !CheckTypeAccess(swtBad.GetType(), symWhere)); if (CheckAccess2(swtBad.Sym, swtBad.GetType(), symWhere, typeQual) == ACCESSERROR.ACCESSERROR_NOACCESSTHRU) { ErrorContext.Error(ErrorCode.ERR_BadProtectedAccess, swtBad, typeQual, symWhere); } else { ErrorContext.ErrorRef(ErrorCode.ERR_BadAccess, swtBad); } } public bool CheckAccess(Symbol symCheck, AggregateType atsCheck, Symbol symWhere, CType typeThru) { return CheckAccess2(symCheck, atsCheck, symWhere, typeThru) == ACCESSERROR.ACCESSERROR_NOERROR; } } }
#region BSD License /* Copyright (c) 2004-2005 Matthew Holmes (matthew@wildfiregames.com), Dan Moorehead (dan05a@gmail.com) 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. * The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 #region CVS Information /* * $Source$ * $Author: jendave $ * $Date: 2006-01-27 16:49:58 -0800 (Fri, 27 Jan 2006) $ * $Revision: 71 $ */ #endregion using System; using System.IO; namespace Prebuild.Core.Utilities { /// <summary> /// /// </summary> public enum LogType { /// <summary> /// /// </summary> None, /// <summary> /// /// </summary> Info, /// <summary> /// /// </summary> Warning, /// <summary> /// /// </summary> Error } /// <summary> /// /// </summary> [Flags] public enum LogTargets { /// <summary> /// /// </summary> None = 0, /// <summary> /// /// </summary> Null = 1, /// <summary> /// /// </summary> File = 2, /// <summary> /// /// </summary> Console = 4 } /// <summary> /// Summary description for Log. /// </summary> public class Log : IDisposable { #region Fields private StreamWriter m_Writer; private LogTargets m_Target = LogTargets.Null; bool disposed; #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="Log"/> class. /// </summary> /// <param name="target">The target.</param> /// <param name="fileName">Name of the file.</param> public Log(LogTargets target, string fileName) { m_Target = target; if((m_Target & LogTargets.File) != 0) { m_Writer = new StreamWriter(fileName, false); } } #endregion #region Public Methods /// <summary> /// Writes this instance. /// </summary> public void Write() { Write(string.Empty); } /// <summary> /// Writes the specified MSG. /// </summary> /// <param name="msg">The MSG.</param> public void Write(string msg) { if((m_Target & LogTargets.Null) != 0) { return; } if((m_Target & LogTargets.Console) != 0) { Console.WriteLine(msg); } if((m_Target & LogTargets.File) != 0 && m_Writer != null) { m_Writer.WriteLine(msg); } } /// <summary> /// Writes the specified format. /// </summary> /// <param name="format">The format.</param> /// <param name="args">The args.</param> public void Write(string format, params object[] args) { Write(string.Format(format,args)); } /// <summary> /// Writes the specified type. /// </summary> /// <param name="type">The type.</param> /// <param name="format">The format.</param> /// <param name="args">The args.</param> public void Write(LogType type, string format, params object[] args) { if((m_Target & LogTargets.Null) != 0) { return; } string str = ""; switch(type) { case LogType.Info: str = "[I] "; break; case LogType.Warning: str = "[!] "; break; case LogType.Error: str = "[X] "; break; } Write(str + format,args); } /// <summary> /// Writes the exception. /// </summary> /// <param name="type">The type.</param> /// <param name="ex">The ex.</param> public void WriteException(LogType type, Exception ex) { if(ex != null) { Write(type, ex.Message); //#if DEBUG m_Writer.WriteLine("Exception @{0} stack trace [[", ex.TargetSite.Name); m_Writer.WriteLine(ex.StackTrace); m_Writer.WriteLine("]]"); //#endif } } /// <summary> /// Flushes this instance. /// </summary> public void Flush() { if(m_Writer != null) { m_Writer.Flush(); } } #endregion #region IDisposable Members /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or /// resetting unmanaged resources. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Dispose objects /// </summary> /// <param name="disposing"> /// If true, it will dispose close the handle /// </param> /// <remarks> /// Will dispose managed and unmanaged resources. /// </remarks> protected virtual void Dispose(bool disposing) { if (!this.disposed) { if (disposing) { if (m_Writer != null) { m_Writer.Close(); m_Writer = null; } } } this.disposed = true; } /// <summary> /// /// </summary> ~Log() { this.Dispose(false); } /// <summary> /// Closes and destroys this object /// </summary> /// <remarks> /// Same as Dispose(true) /// </remarks> public void Close() { Dispose(); } #endregion } }
// Copyright (c) Umbraco. // See LICENSE for more details. using System; using System.Collections.Generic; using Umbraco.Cms.Core.Models; using Umbraco.Cms.Tests.Common.Builders.Extensions; using Umbraco.Cms.Tests.Common.Builders.Interfaces; using Umbraco.Cms.Tests.Common.Extensions; using Constants = Umbraco.Cms.Core.Constants; namespace Umbraco.Cms.Tests.Common.Builders { public class MediaBuilder : BuilderBase<Media>, IBuildContentTypes, IWithIdBuilder, IWithKeyBuilder, IWithParentIdBuilder, IWithCreatorIdBuilder, IWithCreateDateBuilder, IWithUpdateDateBuilder, IWithNameBuilder, IWithTrashedBuilder, IWithLevelBuilder, IWithPathBuilder, IWithSortOrderBuilder, IWithPropertyValues { private MediaTypeBuilder _mediaTypeBuilder; private GenericDictionaryBuilder<MediaBuilder, string, object> _propertyDataBuilder; private int? _id; private Guid? _key; private DateTime? _createDate; private DateTime? _updateDate; private int? _parentId; private string _name; private int? _creatorId; private int? _level; private string _path; private int? _sortOrder; private bool? _trashed; private IMediaType _mediaType; private object _propertyValues; private string _propertyValuesCulture; private string _propertyValuesSegment; public MediaTypeBuilder AddMediaType() { _mediaType = null; var builder = new MediaTypeBuilder(this); _mediaTypeBuilder = builder; return builder; } public MediaBuilder WithMediaType(IMediaType mediaType) { _mediaTypeBuilder = null; _mediaType = mediaType; return this; } public GenericDictionaryBuilder<MediaBuilder, string, object> AddPropertyData() { var builder = new GenericDictionaryBuilder<MediaBuilder, string, object>(this); _propertyDataBuilder = builder; return builder; } public override Media Build() { var id = _id ?? 0; Guid key = _key ?? Guid.NewGuid(); var parentId = _parentId ?? -1; DateTime createDate = _createDate ?? DateTime.Now; DateTime updateDate = _updateDate ?? DateTime.Now; var name = _name ?? Guid.NewGuid().ToString(); var creatorId = _creatorId ?? 0; var level = _level ?? 1; var path = _path ?? $"-1,{id}"; var sortOrder = _sortOrder ?? 0; var trashed = _trashed ?? false; var propertyValues = _propertyValues ?? null; var propertyValuesCulture = _propertyValuesCulture ?? null; var propertyValuesSegment = _propertyValuesSegment ?? null; if (_mediaTypeBuilder is null && _mediaType is null) { throw new InvalidOperationException("A media item cannot be constructed without providing a media type. Use AddMediaType() or WithMediaType()."); } IMediaType mediaType = _mediaType ?? _mediaTypeBuilder.Build(); var media = new Media(name, parentId, mediaType) { Id = id, Key = key, CreateDate = createDate, UpdateDate = updateDate, CreatorId = creatorId, Level = level, Path = path, SortOrder = sortOrder, Trashed = trashed, }; if (_propertyDataBuilder != null || propertyValues != null) { if (_propertyDataBuilder != null) { IDictionary<string, object> propertyData = _propertyDataBuilder.Build(); foreach (KeyValuePair<string, object> keyValuePair in propertyData) { media.SetValue(keyValuePair.Key, keyValuePair.Value); } } else { media.PropertyValues(propertyValues, propertyValuesCulture, propertyValuesSegment); } media.ResetDirtyProperties(false); } return media; } public static Media CreateSimpleMedia(IMediaType mediaType, string name, int parentId, int id = 0) => new MediaBuilder() .WithId(id) .WithName(name) .WithMediaType(mediaType) .WithParentId(parentId) .WithPropertyValues(new { title = name + " Subpage", bodyText = "This is a subpage", author = "John Doe" }) .Build(); public static Media CreateMediaImage(IMediaType mediaType, int parentId) => CreateMediaImage(mediaType, parentId, "/media/test-image.png"); public static Media CreateMediaImageWithCrop(IMediaType mediaType, int parentId) => CreateMediaImage(mediaType, parentId, "{src: '/media/test-image.png', crops: []}"); private static Media CreateMediaImage(IMediaType mediaType, int parentId, string fileValue) => new MediaBuilder() .WithMediaType(mediaType) .WithName("Test Image") .WithParentId(parentId) .AddPropertyData() .WithKeyValue(Constants.Conventions.Media.File, fileValue) .WithKeyValue(Constants.Conventions.Media.Width, "200") .WithKeyValue(Constants.Conventions.Media.Height, "200") .WithKeyValue(Constants.Conventions.Media.Bytes, "100") .WithKeyValue(Constants.Conventions.Media.Extension, "png") .Done() .Build(); public static Media CreateMediaFolder(IMediaType mediaType, int parentId) => new MediaBuilder() .WithMediaType(mediaType) .WithName("Test Folder") .WithParentId(parentId) .Build(); public static Media CreateMediaFile(IMediaType mediaType, int parentId) => new MediaBuilder() .WithMediaType(mediaType) .WithName("Test File") .WithParentId(parentId) .AddPropertyData() .WithKeyValue(Constants.Conventions.Media.File, "/media/test-file.txt") .WithKeyValue(Constants.Conventions.Media.Bytes, "100") .WithKeyValue(Constants.Conventions.Media.Extension, "png") .Done() .Build(); int? IWithIdBuilder.Id { get => _id; set => _id = value; } Guid? IWithKeyBuilder.Key { get => _key; set => _key = value; } int? IWithCreatorIdBuilder.CreatorId { get => _creatorId; set => _creatorId = value; } DateTime? IWithCreateDateBuilder.CreateDate { get => _createDate; set => _createDate = value; } DateTime? IWithUpdateDateBuilder.UpdateDate { get => _updateDate; set => _updateDate = value; } string IWithNameBuilder.Name { get => _name; set => _name = value; } bool? IWithTrashedBuilder.Trashed { get => _trashed; set => _trashed = value; } int? IWithLevelBuilder.Level { get => _level; set => _level = value; } string IWithPathBuilder.Path { get => _path; set => _path = value; } int? IWithSortOrderBuilder.SortOrder { get => _sortOrder; set => _sortOrder = value; } int? IWithParentIdBuilder.ParentId { get => _parentId; set => _parentId = value; } object IWithPropertyValues.PropertyValues { get => _propertyValues; set => _propertyValues = value; } string IWithPropertyValues.PropertyValuesCulture { get => _propertyValuesCulture; set => _propertyValuesCulture = value; } string IWithPropertyValues.PropertyValuesSegment { get => _propertyValuesSegment; set => _propertyValuesSegment = value; } } }
/* * 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.Linq; using System.Reflection; using log4net; using Nini.Config; using OpenMetaverse; using OpenMetaverse.StructuredData; using OpenSim.Framework; using OpenSim.Framework.Capabilities; using OpenSim.Region.Framework.Interfaces; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Services.Interfaces; using Caps = OpenSim.Framework.Capabilities.Caps; namespace OpenSim.Capabilities.Handlers { public class FetchInvDescHandler { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private IInventoryService m_InventoryService; private ILibraryService m_LibraryService; private IScene m_Scene; // private object m_fetchLock = new Object(); public FetchInvDescHandler(IInventoryService invService, ILibraryService libService, IScene s) { m_InventoryService = invService; m_LibraryService = libService; m_Scene = s; } public string FetchInventoryDescendentsRequest(string request, string path, string param, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { //m_log.DebugFormat("[XXX]: FetchInventoryDescendentsRequest in {0}, {1}", (m_Scene == null) ? "none" : m_Scene.Name, request); // nasty temporary hack here, the linden client falsely // identifies the uuid 00000000-0000-0000-0000-000000000000 // as a string which breaks us // // correctly mark it as a uuid // request = request.Replace("<string>00000000-0000-0000-0000-000000000000</string>", "<uuid>00000000-0000-0000-0000-000000000000</uuid>"); // another hack <integer>1</integer> results in a // System.ArgumentException: Object type System.Int32 cannot // be converted to target type: System.Boolean // request = request.Replace("<key>fetch_folders</key><integer>0</integer>", "<key>fetch_folders</key><boolean>0</boolean>"); request = request.Replace("<key>fetch_folders</key><integer>1</integer>", "<key>fetch_folders</key><boolean>1</boolean>"); Hashtable hash = new Hashtable(); try { hash = (Hashtable)LLSD.LLSDDeserialize(Utils.StringToBytes(request)); } catch (LLSD.LLSDParseException e) { m_log.ErrorFormat("[WEB FETCH INV DESC HANDLER]: Fetch error: {0}{1}" + e.Message, e.StackTrace); m_log.Error("Request: " + request); } ArrayList foldersrequested = (ArrayList)hash["folders"]; string response = ""; string bad_folders_response = ""; List<LLSDFetchInventoryDescendents> folders = new List<LLSDFetchInventoryDescendents>(); for (int i = 0; i < foldersrequested.Count; i++) { Hashtable inventoryhash = (Hashtable)foldersrequested[i]; LLSDFetchInventoryDescendents llsdRequest = new LLSDFetchInventoryDescendents(); try { LLSDHelpers.DeserialiseOSDMap(inventoryhash, llsdRequest); } catch (Exception e) { m_log.Debug("[WEB FETCH INV DESC HANDLER]: caught exception doing OSD deserialize" + e); continue; } // Filter duplicate folder ids that bad viewers may send if (folders.Find(f => f.folder_id == llsdRequest.folder_id) == null) folders.Add(llsdRequest); } if (folders.Count > 0) { List<UUID> bad_folders = new List<UUID>(); List<InventoryCollectionWithDescendents> invcollSet = Fetch(folders, bad_folders); //m_log.DebugFormat("[XXX]: Got {0} folders from a request of {1}", invcollSet.Count, folders.Count); if (invcollSet == null) { m_log.DebugFormat("[WEB FETCH INV DESC HANDLER]: Multiple folder fetch failed. Trying old protocol."); return FetchInventoryDescendentsRequest(foldersrequested, httpRequest, httpResponse); } string inventoryitemstr = string.Empty; foreach (InventoryCollectionWithDescendents icoll in invcollSet) { LLSDInventoryDescendents reply = ToLLSD(icoll.Collection, icoll.Descendents); inventoryitemstr = LLSDHelpers.SerialiseLLSDReply(reply); inventoryitemstr = inventoryitemstr.Replace("<llsd><map><key>folders</key><array>", ""); inventoryitemstr = inventoryitemstr.Replace("</array></map></llsd>", ""); response += inventoryitemstr; } //m_log.DebugFormat("[WEB FETCH INV DESC HANDLER]: Bad folders {0}", string.Join(", ", bad_folders)); foreach (UUID bad in bad_folders) bad_folders_response += "<uuid>" + bad + "</uuid>"; } if (response.Length == 0) { /* Viewers expect a bad_folders array when not available */ if (bad_folders_response.Length != 0) { response = "<llsd><map><key>bad_folders</key><array>" + bad_folders_response + "</array></map></llsd>"; } else { response = "<llsd><map><key>folders</key><array /></map></llsd>"; } } else { if (bad_folders_response.Length != 0) { response = "<llsd><map><key>folders</key><array>" + response + "</array><key>bad_folders</key><array>" + bad_folders_response + "</array></map></llsd>"; } else { response = "<llsd><map><key>folders</key><array>" + response + "</array></map></llsd>"; } } //m_log.DebugFormat("[WEB FETCH INV DESC HANDLER]: Replying to CAPS fetch inventory request for {0} folders. Item count {1}", folders.Count, item_count); //m_log.Debug("[WEB FETCH INV DESC HANDLER] " + response); return response; } /// <summary> /// Construct an LLSD reply packet to a CAPS inventory request /// </summary> /// <param name="invFetch"></param> /// <returns></returns> private LLSDInventoryDescendents FetchInventoryReply(LLSDFetchInventoryDescendents invFetch) { LLSDInventoryDescendents reply = new LLSDInventoryDescendents(); LLSDInventoryFolderContents contents = new LLSDInventoryFolderContents(); contents.agent_id = invFetch.owner_id; contents.owner_id = invFetch.owner_id; contents.folder_id = invFetch.folder_id; reply.folders.Array.Add(contents); InventoryCollection inv = new InventoryCollection(); inv.Folders = new List<InventoryFolderBase>(); inv.Items = new List<InventoryItemBase>(); int version = 0; int descendents = 0; inv = Fetch( invFetch.owner_id, invFetch.folder_id, invFetch.owner_id, invFetch.fetch_folders, invFetch.fetch_items, invFetch.sort_order, out version, out descendents); if (inv != null && inv.Folders != null) { foreach (InventoryFolderBase invFolder in inv.Folders) { contents.categories.Array.Add(ConvertInventoryFolder(invFolder)); } descendents += inv.Folders.Count; } if (inv != null && inv.Items != null) { foreach (InventoryItemBase invItem in inv.Items) { contents.items.Array.Add(ConvertInventoryItem(invItem)); } } contents.descendents = descendents; contents.version = version; //m_log.DebugFormat( // "[WEB FETCH INV DESC HANDLER]: Replying to request for folder {0} (fetch items {1}, fetch folders {2}) with {3} items and {4} folders for agent {5}", // invFetch.folder_id, // invFetch.fetch_items, // invFetch.fetch_folders, // contents.items.Array.Count, // contents.categories.Array.Count, // invFetch.owner_id); return reply; } private LLSDInventoryDescendents ToLLSD(InventoryCollection inv, int descendents) { LLSDInventoryDescendents reply = new LLSDInventoryDescendents(); LLSDInventoryFolderContents contents = new LLSDInventoryFolderContents(); contents.agent_id = inv.OwnerID; contents.owner_id = inv.OwnerID; contents.folder_id = inv.FolderID; reply.folders.Array.Add(contents); if (inv.Folders != null) { foreach (InventoryFolderBase invFolder in inv.Folders) { contents.categories.Array.Add(ConvertInventoryFolder(invFolder)); } descendents += inv.Folders.Count; } if (inv.Items != null) { foreach (InventoryItemBase invItem in inv.Items) { contents.items.Array.Add(ConvertInventoryItem(invItem)); } } contents.descendents = descendents; contents.version = inv.Version; return reply; } /// <summary> /// Old style. Soon to be deprecated. /// </summary> /// <param name="request"></param> /// <param name="httpRequest"></param> /// <param name="httpResponse"></param> /// <returns></returns> [Obsolete] private string FetchInventoryDescendentsRequest(ArrayList foldersrequested, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { //m_log.DebugFormat("[WEB FETCH INV DESC HANDLER]: Received request for {0} folders", foldersrequested.Count); string response = ""; string bad_folders_response = ""; for (int i = 0; i < foldersrequested.Count; i++) { string inventoryitemstr = ""; Hashtable inventoryhash = (Hashtable)foldersrequested[i]; LLSDFetchInventoryDescendents llsdRequest = new LLSDFetchInventoryDescendents(); try { LLSDHelpers.DeserialiseOSDMap(inventoryhash, llsdRequest); } catch (Exception e) { m_log.Debug("[WEB FETCH INV DESC HANDLER]: caught exception doing OSD deserialize" + e); } LLSDInventoryDescendents reply = FetchInventoryReply(llsdRequest); if (null == reply) { bad_folders_response += "<uuid>" + llsdRequest.folder_id.ToString() + "</uuid>"; } else { inventoryitemstr = LLSDHelpers.SerialiseLLSDReply(reply); inventoryitemstr = inventoryitemstr.Replace("<llsd><map><key>folders</key><array>", ""); inventoryitemstr = inventoryitemstr.Replace("</array></map></llsd>", ""); } response += inventoryitemstr; } if (response.Length == 0) { /* Viewers expect a bad_folders array when not available */ if (bad_folders_response.Length != 0) { response = "<llsd><map><key>bad_folders</key><array>" + bad_folders_response + "</array></map></llsd>"; } else { response = "<llsd><map><key>folders</key><array /></map></llsd>"; } } else { if (bad_folders_response.Length != 0) { response = "<llsd><map><key>folders</key><array>" + response + "</array><key>bad_folders</key><array>" + bad_folders_response + "</array></map></llsd>"; } else { response = "<llsd><map><key>folders</key><array>" + response + "</array></map></llsd>"; } } // m_log.DebugFormat("[WEB FETCH INV DESC HANDLER]: Replying to CAPS fetch inventory request"); //m_log.Debug("[WEB FETCH INV DESC HANDLER] "+response); return response; // } } /// <summary> /// Handle the caps inventory descendents fetch. /// </summary> /// <param name="agentID"></param> /// <param name="folderID"></param> /// <param name="ownerID"></param> /// <param name="fetchFolders"></param> /// <param name="fetchItems"></param> /// <param name="sortOrder"></param> /// <param name="version"></param> /// <returns>An empty InventoryCollection if the inventory look up failed</returns> [Obsolete] private InventoryCollection Fetch( UUID agentID, UUID folderID, UUID ownerID, bool fetchFolders, bool fetchItems, int sortOrder, out int version, out int descendents) { //m_log.DebugFormat( // "[WEB FETCH INV DESC HANDLER]: Fetching folders ({0}), items ({1}) from {2} for agent {3}", // fetchFolders, fetchItems, folderID, agentID); // FIXME MAYBE: We're not handling sortOrder! version = 0; descendents = 0; InventoryFolderImpl fold; if (m_LibraryService != null && m_LibraryService.LibraryRootFolder != null && agentID == m_LibraryService.LibraryRootFolder.Owner) { if ((fold = m_LibraryService.LibraryRootFolder.FindFolder(folderID)) != null) { InventoryCollection ret = new InventoryCollection(); ret.Folders = new List<InventoryFolderBase>(); ret.Items = fold.RequestListOfItems(); descendents = ret.Folders.Count + ret.Items.Count; return ret; } } InventoryCollection contents = new InventoryCollection(); if (folderID != UUID.Zero) { InventoryCollection fetchedContents = m_InventoryService.GetFolderContent(agentID, folderID); if (fetchedContents == null) { m_log.WarnFormat("[WEB FETCH INV DESC HANDLER]: Could not get contents of folder {0} for user {1}", folderID, agentID); return contents; } contents = fetchedContents; InventoryFolderBase containingFolder = new InventoryFolderBase(); containingFolder.ID = folderID; containingFolder.Owner = agentID; containingFolder = m_InventoryService.GetFolder(containingFolder); if (containingFolder != null) { //m_log.DebugFormat( // "[WEB FETCH INV DESC HANDLER]: Retrieved folder {0} {1} for agent id {2}", // containingFolder.Name, containingFolder.ID, agentID); version = containingFolder.Version; if (fetchItems) { List<InventoryItemBase> itemsToReturn = contents.Items; List<InventoryItemBase> originalItems = new List<InventoryItemBase>(itemsToReturn); // descendents must only include the links, not the linked items we add descendents = originalItems.Count; // Add target items for links in this folder before the links themselves. foreach (InventoryItemBase item in originalItems) { if (item.AssetType == (int)AssetType.Link) { InventoryItemBase linkedItem = m_InventoryService.GetItem(new InventoryItemBase(item.AssetID)); // Take care of genuinely broken links where the target doesn't exist // HACK: Also, don't follow up links that just point to other links. In theory this is legitimate, // but no viewer has been observed to set these up and this is the lazy way of avoiding cycles // rather than having to keep track of every folder requested in the recursion. if (linkedItem != null && linkedItem.AssetType != (int)AssetType.Link) itemsToReturn.Insert(0, linkedItem); } } // Now scan for folder links and insert the items they target and those links at the head of the return data foreach (InventoryItemBase item in originalItems) { if (item.AssetType == (int)AssetType.LinkFolder) { InventoryCollection linkedFolderContents = m_InventoryService.GetFolderContent(ownerID, item.AssetID); List<InventoryItemBase> links = linkedFolderContents.Items; itemsToReturn.InsertRange(0, links); foreach (InventoryItemBase link in linkedFolderContents.Items) { // Take care of genuinely broken links where the target doesn't exist // HACK: Also, don't follow up links that just point to other links. In theory this is legitimate, // but no viewer has been observed to set these up and this is the lazy way of avoiding cycles // rather than having to keep track of every folder requested in the recursion. if (link != null) { // m_log.DebugFormat( // "[WEB FETCH INV DESC HANDLER]: Adding item {0} {1} from folder {2} linked from {3}", // link.Name, (AssetType)link.AssetType, item.AssetID, containingFolder.Name); InventoryItemBase linkedItem = m_InventoryService.GetItem(new InventoryItemBase(link.AssetID)); if (linkedItem != null) itemsToReturn.Insert(0, linkedItem); } } } } } // foreach (InventoryItemBase item in contents.Items) // { // m_log.DebugFormat( // "[WEB FETCH INV DESC HANDLER]: Returning item {0}, type {1}, parent {2} in {3} {4}", // item.Name, (AssetType)item.AssetType, item.Folder, containingFolder.Name, containingFolder.ID); // } // ===== // // foreach (InventoryItemBase linkedItem in linkedItemsToAdd) // { // m_log.DebugFormat( // "[WEB FETCH INV DESC HANDLER]: Inserted linked item {0} for link in folder {1} for agent {2}", // linkedItem.Name, folderID, agentID); // // contents.Items.Add(linkedItem); // } // // // If the folder requested contains links, then we need to send those folders first, otherwise the links // // will be broken in the viewer. // HashSet<UUID> linkedItemFolderIdsToSend = new HashSet<UUID>(); // foreach (InventoryItemBase item in contents.Items) // { // if (item.AssetType == (int)AssetType.Link) // { // InventoryItemBase linkedItem = m_InventoryService.GetItem(new InventoryItemBase(item.AssetID)); // // // Take care of genuinely broken links where the target doesn't exist // // HACK: Also, don't follow up links that just point to other links. In theory this is legitimate, // // but no viewer has been observed to set these up and this is the lazy way of avoiding cycles // // rather than having to keep track of every folder requested in the recursion. // if (linkedItem != null && linkedItem.AssetType != (int)AssetType.Link) // { // // We don't need to send the folder if source and destination of the link are in the same // // folder. // if (linkedItem.Folder != containingFolder.ID) // linkedItemFolderIdsToSend.Add(linkedItem.Folder); // } // } // } // // foreach (UUID linkedItemFolderId in linkedItemFolderIdsToSend) // { // m_log.DebugFormat( // "[WEB FETCH INV DESC HANDLER]: Recursively fetching folder {0} linked by item in folder {1} for agent {2}", // linkedItemFolderId, folderID, agentID); // // int dummyVersion; // InventoryCollection linkedCollection // = Fetch( // agentID, linkedItemFolderId, ownerID, fetchFolders, fetchItems, sortOrder, out dummyVersion); // // InventoryFolderBase linkedFolder = new InventoryFolderBase(linkedItemFolderId); // linkedFolder.Owner = agentID; // linkedFolder = m_InventoryService.GetFolder(linkedFolder); // //// contents.Folders.AddRange(linkedCollection.Folders); // // contents.Folders.Add(linkedFolder); // contents.Items.AddRange(linkedCollection.Items); // } // } } } else { // Lost items don't really need a version version = 1; } return contents; } private void AddLibraryFolders(List<LLSDFetchInventoryDescendents> fetchFolders, List<InventoryCollectionWithDescendents> result) { InventoryFolderImpl fold; if (m_LibraryService != null && m_LibraryService.LibraryRootFolder != null) { List<LLSDFetchInventoryDescendents> libfolders = fetchFolders.FindAll(f => f.owner_id == m_LibraryService.LibraryRootFolder.Owner); fetchFolders.RemoveAll(f => libfolders.Contains(f)); //m_log.DebugFormat("[XXX]: Found {0} library folders in request", libfolders.Count); foreach (LLSDFetchInventoryDescendents f in libfolders) { if ((fold = m_LibraryService.LibraryRootFolder.FindFolder(f.folder_id)) != null) { InventoryCollectionWithDescendents ret = new InventoryCollectionWithDescendents(); ret.Collection = new InventoryCollection(); ret.Collection.Folders = new List<InventoryFolderBase>(); ret.Collection.Items = fold.RequestListOfItems(); ret.Collection.OwnerID = m_LibraryService.LibraryRootFolder.Owner; ret.Collection.FolderID = f.folder_id; ret.Collection.Version = fold.Version; ret.Descendents = ret.Collection.Items.Count; result.Add(ret); //m_log.DebugFormat("[XXX]: Added libfolder {0} ({1}) {2}", ret.Collection.FolderID, ret.Collection.OwnerID); } } } } private List<InventoryCollectionWithDescendents> Fetch(List<LLSDFetchInventoryDescendents> fetchFolders, List<UUID> bad_folders) { //m_log.DebugFormat( // "[WEB FETCH INV DESC HANDLER]: Fetching {0} folders for owner {1}", fetchFolders.Count, fetchFolders[0].owner_id); // FIXME MAYBE: We're not handling sortOrder! List<InventoryCollectionWithDescendents> result = new List<InventoryCollectionWithDescendents>(); AddLibraryFolders(fetchFolders, result); // Filter folder Zero right here. Some viewers (Firestorm) send request for folder Zero, which doesn't make sense // and can kill the sim (all root folders have parent_id Zero) LLSDFetchInventoryDescendents zero = fetchFolders.Find(f => f.folder_id == UUID.Zero); if (zero != null) { fetchFolders.Remove(zero); BadFolder(zero, null, bad_folders); } if (fetchFolders.Count > 0) { UUID[] fids = new UUID[fetchFolders.Count]; int i = 0; foreach (LLSDFetchInventoryDescendents f in fetchFolders) fids[i++] = f.folder_id; //m_log.DebugFormat("[XXX]: {0}", string.Join(",", fids)); InventoryCollection[] fetchedContents = m_InventoryService.GetMultipleFoldersContent(fetchFolders[0].owner_id, fids); if (fetchedContents == null || (fetchedContents != null && fetchedContents.Length == 0)) { m_log.WarnFormat("[WEB FETCH INV DESC HANDLER]: Could not get contents of multiple folders for user {0}", fetchFolders[0].owner_id); foreach (LLSDFetchInventoryDescendents freq in fetchFolders) BadFolder(freq, null, bad_folders); return null; } i = 0; // Do some post-processing. May need to fetch more from inv server for links foreach (InventoryCollection contents in fetchedContents) { // Find the original request LLSDFetchInventoryDescendents freq = fetchFolders[i++]; InventoryCollectionWithDescendents coll = new InventoryCollectionWithDescendents(); coll.Collection = contents; if (BadFolder(freq, contents, bad_folders)) continue; // Next: link management ProcessLinks(freq, coll); result.Add(coll); } } return result; } private bool BadFolder(LLSDFetchInventoryDescendents freq, InventoryCollection contents, List<UUID> bad_folders) { bool bad = false; if (contents == null) { bad_folders.Add(freq.folder_id); bad = true; } // The inventory server isn't sending FolderID in the collection... // Must fetch it individually else if (contents.FolderID == UUID.Zero) { InventoryFolderBase containingFolder = new InventoryFolderBase(); containingFolder.ID = freq.folder_id; containingFolder.Owner = freq.owner_id; containingFolder = m_InventoryService.GetFolder(containingFolder); if (containingFolder != null) { contents.FolderID = containingFolder.ID; contents.OwnerID = containingFolder.Owner; contents.Version = containingFolder.Version; } else { // Was it really a request for folder Zero? // This is an overkill, but Firestorm really asks for folder Zero. // I'm leaving the code here for the time being, but commented. if (freq.folder_id == UUID.Zero) { //coll.Collection.OwnerID = freq.owner_id; //coll.Collection.FolderID = contents.FolderID; //containingFolder = m_InventoryService.GetRootFolder(freq.owner_id); //if (containingFolder != null) //{ // m_log.WarnFormat("[WEB FETCH INV DESC HANDLER]: Request for parent of folder {0}", containingFolder.ID); // coll.Collection.Folders.Clear(); // coll.Collection.Folders.Add(containingFolder); // if (m_LibraryService != null && m_LibraryService.LibraryRootFolder != null) // { // InventoryFolderBase lib = new InventoryFolderBase(m_LibraryService.LibraryRootFolder.ID, m_LibraryService.LibraryRootFolder.Owner); // lib.Name = m_LibraryService.LibraryRootFolder.Name; // lib.Type = m_LibraryService.LibraryRootFolder.Type; // lib.Version = m_LibraryService.LibraryRootFolder.Version; // coll.Collection.Folders.Add(lib); // } // coll.Collection.Items.Clear(); //} } else { m_log.WarnFormat("[WEB FETCH INV DESC HANDLER]: Unable to fetch folder {0}", freq.folder_id); bad_folders.Add(freq.folder_id); } bad = true; } } return bad; } private void ProcessLinks(LLSDFetchInventoryDescendents freq, InventoryCollectionWithDescendents coll) { InventoryCollection contents = coll.Collection; if (freq.fetch_items && contents.Items != null) { List<InventoryItemBase> itemsToReturn = contents.Items; // descendents must only include the links, not the linked items we add coll.Descendents = itemsToReturn.Count; // Add target items for links in this folder before the links themselves. List<UUID> itemIDs = new List<UUID>(); List<UUID> folderIDs = new List<UUID>(); foreach (InventoryItemBase item in itemsToReturn) { //m_log.DebugFormat("[XXX]: {0} {1}", item.Name, item.AssetType); if (item.AssetType == (int)AssetType.Link) itemIDs.Add(item.AssetID); else if (item.AssetType == (int)AssetType.LinkFolder) folderIDs.Add(item.AssetID); } //m_log.DebugFormat("[XXX]: folder {0} has {1} links and {2} linkfolders", contents.FolderID, itemIDs.Count, folderIDs.Count); // Scan for folder links and insert the items they target and those links at the head of the return data if (folderIDs.Count > 0) { InventoryCollection[] linkedFolders = m_InventoryService.GetMultipleFoldersContent(coll.Collection.OwnerID, folderIDs.ToArray()); foreach (InventoryCollection linkedFolderContents in linkedFolders) { if (linkedFolderContents == null) continue; List<InventoryItemBase> links = linkedFolderContents.Items; itemsToReturn.InsertRange(0, links); } } if (itemIDs.Count > 0) { InventoryItemBase[] linked = m_InventoryService.GetMultipleItems(freq.owner_id, itemIDs.ToArray()); if (linked == null) { // OMG!!! One by one!!! This is fallback code, in case the backend isn't updated m_log.WarnFormat("[WEB FETCH INV DESC HANDLER]: GetMultipleItems failed. Falling back to fetching inventory items one by one."); linked = new InventoryItemBase[itemIDs.Count]; int i = 0; InventoryItemBase item = new InventoryItemBase(); item.Owner = freq.owner_id; foreach (UUID id in itemIDs) { item.ID = id; linked[i++] = m_InventoryService.GetItem(item); } } //m_log.DebugFormat("[WEB FETCH INV DESC HANDLER]: Processing folder {0}. Existing items:", freq.folder_id); //foreach (InventoryItemBase item in itemsToReturn) // m_log.DebugFormat("[XXX]: {0} {1} {2}", item.Name, item.AssetType, item.Folder); if (linked != null) { foreach (InventoryItemBase linkedItem in linked) { // Take care of genuinely broken links where the target doesn't exist // HACK: Also, don't follow up links that just point to other links. In theory this is legitimate, // but no viewer has been observed to set these up and this is the lazy way of avoiding cycles // rather than having to keep track of every folder requested in the recursion. if (linkedItem != null && linkedItem.AssetType != (int)AssetType.Link) { itemsToReturn.Insert(0, linkedItem); //m_log.DebugFormat("[WEB FETCH INV DESC HANDLER]: Added {0} {1} {2}", linkedItem.Name, linkedItem.AssetType, linkedItem.Folder); } } } } } } /// <summary> /// Convert an internal inventory folder object into an LLSD object. /// </summary> /// <param name="invFolder"></param> /// <returns></returns> private LLSDInventoryFolder ConvertInventoryFolder(InventoryFolderBase invFolder) { LLSDInventoryFolder llsdFolder = new LLSDInventoryFolder(); llsdFolder.folder_id = invFolder.ID; llsdFolder.parent_id = invFolder.ParentID; llsdFolder.name = invFolder.Name; llsdFolder.type = invFolder.Type; llsdFolder.preferred_type = -1; return llsdFolder; } /// <summary> /// Convert an internal inventory item object into an LLSD object. /// </summary> /// <param name="invItem"></param> /// <returns></returns> private LLSDInventoryItem ConvertInventoryItem(InventoryItemBase invItem) { LLSDInventoryItem llsdItem = new LLSDInventoryItem(); llsdItem.asset_id = invItem.AssetID; llsdItem.created_at = invItem.CreationDate; llsdItem.desc = invItem.Description; llsdItem.flags = (int)invItem.Flags; llsdItem.item_id = invItem.ID; llsdItem.name = invItem.Name; llsdItem.parent_id = invItem.Folder; llsdItem.type = invItem.AssetType; llsdItem.inv_type = invItem.InvType; llsdItem.permissions = new LLSDPermissions(); llsdItem.permissions.creator_id = invItem.CreatorIdAsUuid; llsdItem.permissions.base_mask = (int)invItem.CurrentPermissions; llsdItem.permissions.everyone_mask = (int)invItem.EveryOnePermissions; llsdItem.permissions.group_id = invItem.GroupID; llsdItem.permissions.group_mask = (int)invItem.GroupPermissions; llsdItem.permissions.is_owner_group = invItem.GroupOwned; llsdItem.permissions.next_owner_mask = (int)invItem.NextPermissions; llsdItem.permissions.owner_id = invItem.Owner; llsdItem.permissions.owner_mask = (int)invItem.CurrentPermissions; llsdItem.sale_info = new LLSDSaleInfo(); llsdItem.sale_info.sale_price = invItem.SalePrice; llsdItem.sale_info.sale_type = invItem.SaleType; return llsdItem; } } class InventoryCollectionWithDescendents { public InventoryCollection Collection; public int Descendents; } }
// // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. // using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Xml; using UnityEditor; using UnityEngine; namespace HoloToolkit.Unity { /// <summary> /// Class containing various utility methods to build a WSA solution from a Unity project. /// </summary> public static class BuildSLNUtilities { public class CopyDirectoryInfo { public string Source { get; set; } public string Destination { get; set; } public string Filter { get; set; } public bool Recursive { get; set; } public CopyDirectoryInfo() { Source = null; Destination = null; Filter = "*"; Recursive = false; } } public class BuildInfo { public string OutputDirectory { get; set; } public IEnumerable<string> Scenes { get; set; } public IEnumerable<CopyDirectoryInfo> CopyDirectories { get; set; } public Action<BuildInfo> PreBuildAction { get; set; } public Action<BuildInfo, string> PostBuildAction { get; set; } public BuildOptions BuildOptions { get; set; } // EditorUserBuildSettings public BuildTarget BuildTarget { get; set; } public WSASDK? WSASdk { get; set; } public WSAUWPBuildType? WSAUWPBuildType { get; set; } public Boolean? WSAGenerateReferenceProjects { get; set; } public ColorSpace? ColorSpace { get; set; } public bool IsCommandLine { get; set; } public string BuildSymbols { get; private set; } public BuildInfo() { BuildSymbols = string.Empty; } public void AppendSymbols(params string[] symbol) { AppendSymbols((IEnumerable<string>)symbol); } public void AppendSymbols(IEnumerable<string> symbols) { string[] toAdd = symbols.Except(BuildSymbols.Split(';')) .Where(sym => !string.IsNullOrEmpty(sym)).ToArray(); if (!toAdd.Any()) { return; } if (!String.IsNullOrEmpty(BuildSymbols)) { BuildSymbols += ";"; } BuildSymbols += String.Join(";", toAdd); } public bool HasAnySymbols(params string[] symbols) { return BuildSymbols.Split(';').Intersect(symbols).Any(); } public bool HasConfigurationSymbol() { return HasAnySymbols( BuildSymbolDebug, BuildSymbolRelease, BuildSymbolMaster); } public static IEnumerable<string> RemoveConfigurationSymbols(string symbolstring) { return symbolstring.Split(';').Except(new[] { BuildSymbolDebug, BuildSymbolRelease, BuildSymbolMaster }); } public bool HasAnySymbols(IEnumerable<string> symbols) { return BuildSymbols.Split(';').Intersect(symbols).Any(); } } // Build configurations. Exactly one of these should be defined for any given build. public const string BuildSymbolDebug = "DEBUG"; public const string BuildSymbolRelease = "RELEASE"; public const string BuildSymbolMaster = "MASTER"; /// <summary> /// Event triggered when a build starts. /// </summary> public static event Action<BuildInfo> BuildStarted; /// <summary> /// Event triggered when a build completes. /// </summary> public static event Action<BuildInfo, string> BuildCompleted; public static void PerformBuild(BuildInfo buildInfo) { BuildTargetGroup buildTargetGroup = GetGroup(buildInfo.BuildTarget); string oldBuildSymbols = PlayerSettings.GetScriptingDefineSymbolsForGroup(buildTargetGroup); if (!string.IsNullOrEmpty(oldBuildSymbols)) { if (buildInfo.HasConfigurationSymbol()) { buildInfo.AppendSymbols(BuildInfo.RemoveConfigurationSymbols(oldBuildSymbols)); } else { buildInfo.AppendSymbols(oldBuildSymbols.Split(';')); } } if ((buildInfo.BuildOptions & BuildOptions.Development) == BuildOptions.Development) { if (!buildInfo.HasConfigurationSymbol()) { buildInfo.AppendSymbols(BuildSymbolDebug); } } if (buildInfo.HasAnySymbols(BuildSymbolDebug)) { buildInfo.BuildOptions |= BuildOptions.Development | BuildOptions.AllowDebugging; } if (buildInfo.HasAnySymbols(BuildSymbolRelease)) { //Unity automatically adds the DEBUG symbol if the BuildOptions.Development flag is //specified. In order to have debug symbols and the RELEASE symbole we have to //inject the symbol Unity relies on to enable the /debug+ flag of csc.exe which is "DEVELOPMENT_BUILD" buildInfo.AppendSymbols("DEVELOPMENT_BUILD"); } BuildTarget oldBuildTarget = EditorUserBuildSettings.activeBuildTarget; BuildTargetGroup oldBuildTargetGroup = GetGroup(oldBuildTarget); EditorUserBuildSettings.SwitchActiveBuildTarget(buildTargetGroup, buildInfo.BuildTarget); var oldWSASDK = EditorUserBuildSettings.wsaSDK; if (buildInfo.WSASdk.HasValue) { EditorUserBuildSettings.wsaSDK = buildInfo.WSASdk.Value; } WSAUWPBuildType? oldWSAUWPBuildType = null; if (EditorUserBuildSettings.wsaSDK == WSASDK.UWP) { oldWSAUWPBuildType = EditorUserBuildSettings.wsaUWPBuildType; if (buildInfo.WSAUWPBuildType.HasValue) { EditorUserBuildSettings.wsaUWPBuildType = buildInfo.WSAUWPBuildType.Value; } } var oldWSAGenerateReferenceProjects = EditorUserBuildSettings.wsaGenerateReferenceProjects; if (buildInfo.WSAGenerateReferenceProjects.HasValue) { EditorUserBuildSettings.wsaGenerateReferenceProjects = buildInfo.WSAGenerateReferenceProjects.Value; } var oldColorSpace = PlayerSettings.colorSpace; if (buildInfo.ColorSpace.HasValue) { PlayerSettings.colorSpace = buildInfo.ColorSpace.Value; } if (buildInfo.BuildSymbols != null) { PlayerSettings.SetScriptingDefineSymbolsForGroup(buildTargetGroup, buildInfo.BuildSymbols); } string buildError = "Error"; try { // For the WSA player, Unity builds into a target directory. // For other players, the OutputPath parameter indicates the // path to the target executable to build. if (buildInfo.BuildTarget == BuildTarget.WSAPlayer) { Directory.CreateDirectory(buildInfo.OutputDirectory); } OnPreProcessBuild(buildInfo); buildError = BuildPipeline.BuildPlayer( buildInfo.Scenes.ToArray(), buildInfo.OutputDirectory, buildInfo.BuildTarget, buildInfo.BuildOptions); if (buildError.StartsWith("Error")) { throw new Exception(buildError); } } finally { OnPostProcessBuild(buildInfo, buildError); PlayerSettings.colorSpace = oldColorSpace; PlayerSettings.SetScriptingDefineSymbolsForGroup(buildTargetGroup, oldBuildSymbols); EditorUserBuildSettings.wsaSDK = oldWSASDK; if (oldWSAUWPBuildType.HasValue) { EditorUserBuildSettings.wsaUWPBuildType = oldWSAUWPBuildType.Value; } EditorUserBuildSettings.wsaGenerateReferenceProjects = oldWSAGenerateReferenceProjects; EditorUserBuildSettings.SwitchActiveBuildTarget(oldBuildTargetGroup, oldBuildTarget); } } public static void ParseBuildCommandLine(ref BuildInfo buildInfo) { string[] arguments = Environment.GetCommandLineArgs(); buildInfo.IsCommandLine = true; for (int i = 0; i < arguments.Length; ++i) { // Can't use -buildTarget which is something Unity already takes as an argument for something. if (string.Equals(arguments[i], "-duskBuildTarget", StringComparison.InvariantCultureIgnoreCase)) { buildInfo.BuildTarget = (BuildTarget)Enum.Parse(typeof(BuildTarget), arguments[++i]); } else if (string.Equals(arguments[i], "-wsaSDK", StringComparison.InvariantCultureIgnoreCase)) { string wsaSdkArg = arguments[++i]; buildInfo.WSASdk = (WSASDK)Enum.Parse(typeof(WSASDK), wsaSdkArg); } else if (string.Equals(arguments[i], "-wsaUWPBuildType", StringComparison.InvariantCultureIgnoreCase)) { buildInfo.WSAUWPBuildType = (WSAUWPBuildType)Enum.Parse(typeof(WSAUWPBuildType), arguments[++i]); } else if (string.Equals(arguments[i], "-wsaGenerateReferenceProjects", StringComparison.InvariantCultureIgnoreCase)) { buildInfo.WSAGenerateReferenceProjects = Boolean.Parse(arguments[++i]); } else if (string.Equals(arguments[i], "-buildOutput", StringComparison.InvariantCultureIgnoreCase)) { buildInfo.OutputDirectory = arguments[++i]; } else if (string.Equals(arguments[i], "-buildDesc", StringComparison.InvariantCultureIgnoreCase)) { ParseBuildDescriptionFile(arguments[++i], ref buildInfo); } else if (string.Equals(arguments[i], "-unityBuildSymbols", StringComparison.InvariantCultureIgnoreCase)) { string newBuildSymbols = arguments[++i]; buildInfo.AppendSymbols(newBuildSymbols.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)); } } } public static void PerformBuild_CommandLine() { BuildInfo buildInfo = new BuildInfo { // Use scenes from the editor build settings. Scenes = EditorBuildSettings.scenes.Where(scene => scene.enabled).Select(scene => scene.path) }; ParseBuildCommandLine(ref buildInfo); PerformBuild(buildInfo); } public static void ParseBuildDescriptionFile(string filename, ref BuildInfo buildInfo) { Debug.Log(string.Format(CultureInfo.InvariantCulture, "Build: Using \"{0}\" as build description", filename)); // Parse the XML file XmlTextReader reader = new XmlTextReader(filename); while (reader.Read()) { switch (reader.NodeType) { case XmlNodeType.Element: if (string.Equals(reader.Name, "SceneList", StringComparison.InvariantCultureIgnoreCase)) { // Set the scenes we want to build buildInfo.Scenes = ReadSceneList(reader); } else if (string.Equals(reader.Name, "CopyList", StringComparison.InvariantCultureIgnoreCase)) { // Set the directories we want to copy buildInfo.CopyDirectories = ReadCopyList(reader); } break; } } } private static BuildTargetGroup GetGroup(BuildTarget buildTarget) { switch (buildTarget) { case BuildTarget.WSAPlayer: return BuildTargetGroup.WSA; case BuildTarget.StandaloneWindows: case BuildTarget.StandaloneWindows64: return BuildTargetGroup.Standalone; default: return BuildTargetGroup.Unknown; } } private static IEnumerable<string> ReadSceneList(XmlTextReader reader) { List<string> result = new List<string>(); while (reader.Read()) { switch (reader.NodeType) { case XmlNodeType.Element: if (string.Equals(reader.Name, "Scene", StringComparison.InvariantCultureIgnoreCase)) { while (reader.MoveToNextAttribute()) { if (string.Equals(reader.Name, "Name", StringComparison.InvariantCultureIgnoreCase)) { result.Add(reader.Value); Debug.Log(string.Format(CultureInfo.InvariantCulture, "Build: Adding scene \"{0}\"", reader.Value)); } } } break; case XmlNodeType.EndElement: if (string.Equals(reader.Name, "SceneList", StringComparison.InvariantCultureIgnoreCase)) return result; break; } } return result; } private static IEnumerable<CopyDirectoryInfo> ReadCopyList(XmlTextReader reader) { List<CopyDirectoryInfo> result = new List<CopyDirectoryInfo>(); while (reader.Read()) { switch (reader.NodeType) { case XmlNodeType.Element: if (string.Equals(reader.Name, "Copy", StringComparison.InvariantCultureIgnoreCase)) { string source = null; string dest = null; string filter = null; bool recursive = false; while (reader.MoveToNextAttribute()) { if (string.Equals(reader.Name, "Source", StringComparison.InvariantCultureIgnoreCase)) { source = reader.Value; } else if (string.Equals(reader.Name, "Destination", StringComparison.InvariantCultureIgnoreCase)) { dest = reader.Value; } else if (string.Equals(reader.Name, "Recursive", StringComparison.InvariantCultureIgnoreCase)) { recursive = Convert.ToBoolean(reader.Value); } else if (string.Equals(reader.Name, "Filter", StringComparison.InvariantCultureIgnoreCase)) { filter = reader.Value; } } if (source != null) { // Either the file specifies the Destination as well, or else CopyDirectory will use Source for Destination CopyDirectoryInfo info = new CopyDirectoryInfo(); info.Source = source; if (dest != null) { info.Destination = dest; } if (filter != null) { info.Filter = filter; } info.Recursive = recursive; Debug.Log(string.Format(CultureInfo.InvariantCulture, @"Build: Adding {0}copy ""{1}\{2}"" => ""{3}""", info.Recursive ? "Recursive " : "", info.Source, info.Filter, info.Destination ?? info.Source)); result.Add(info); } } break; case XmlNodeType.EndElement: if (string.Equals(reader.Name, "CopyList", StringComparison.InvariantCultureIgnoreCase)) return result; break; } } return result; } public static void CopyDirectory(string sourceDirectoryPath, string destinationDirectoryPath, CopyDirectoryInfo directoryInfo) { sourceDirectoryPath = Path.Combine(sourceDirectoryPath, directoryInfo.Source); destinationDirectoryPath = Path.Combine(destinationDirectoryPath, directoryInfo.Destination ?? directoryInfo.Source); Debug.Log(string.Format(CultureInfo.InvariantCulture, @"{0} ""{1}\{2}"" to ""{3}""", directoryInfo.Recursive ? "Recursively copying" : "Copying", sourceDirectoryPath, directoryInfo.Filter, destinationDirectoryPath)); foreach (string sourceFilePath in Directory.GetFiles(sourceDirectoryPath, directoryInfo.Filter, directoryInfo.Recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly)) { string destinationFilePath = sourceFilePath.Replace(sourceDirectoryPath, destinationDirectoryPath); try { Directory.CreateDirectory(Path.GetDirectoryName(destinationFilePath)); if (File.Exists(destinationFilePath)) { File.SetAttributes(destinationFilePath, FileAttributes.Normal); } File.Copy(sourceFilePath, destinationFilePath, true); File.SetAttributes(destinationFilePath, FileAttributes.Normal); } catch (Exception exception) { Debug.LogError(string.Format(CultureInfo.InvariantCulture, "Failed to copy \"{0}\" to \"{1}\" with \"{2}\"", sourceFilePath, destinationFilePath, exception)); } } } private static void OnPreProcessBuild(BuildInfo buildInfo) { // Raise the global event for listeners BuildStarted.RaiseEvent(buildInfo); // Call the pre-build action, if any if (buildInfo.PreBuildAction != null) { buildInfo.PreBuildAction(buildInfo); } } private static void OnPostProcessBuild(BuildInfo buildInfo, string buildError) { if (string.IsNullOrEmpty(buildError)) { if (buildInfo.CopyDirectories != null) { string inputProjectDirectoryPath = GetProjectPath(); string outputProjectDirectoryPath = Path.Combine(GetProjectPath(), buildInfo.OutputDirectory); foreach (var directory in buildInfo.CopyDirectories) { CopyDirectory(inputProjectDirectoryPath, outputProjectDirectoryPath, directory); } } } // Raise the global event for listeners BuildCompleted.RaiseEvent(buildInfo, buildError); // Call the post-build action, if any if (buildInfo.PostBuildAction != null) { buildInfo.PostBuildAction(buildInfo, buildError); } } private static string GetProjectPath() { return Path.GetDirectoryName(Path.GetFullPath(Application.dataPath)); } } }
// Copyright 2014, 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. // Author: api.anash@gmail.com (Anash P. Oommen) using Google.Api.Ads.Dfp.Lib; using Google.Api.Ads.Dfp.Util.v201411; using Google.Api.Ads.Dfp.v201411; using NUnit.Framework; using System; using System.Collections.Generic; using System.IO; using System.Xml; using System.Threading; namespace Google.Api.Ads.Dfp.Tests.v201411 { /// <summary> /// UnitTests for <see cref="LineItemService"/> class. /// </summary> [TestFixture] public class LineItemServiceTests : BaseTests { /// <summary> /// UnitTests for <see cref="LineItemService"/> class. /// </summary> private LineItemService lineItemService; /// <summary> /// Advertiser company id for running tests. /// </summary> private long advertiserId; /// <summary> /// Salesperson user id for running tests. /// </summary> private long salespersonId; /// <summary> /// Trafficker user id for running tests. /// </summary> private long traffickerId; /// <summary> /// Ad unit id for running tests. /// </summary> private string adUnitId; /// <summary> /// Placement id for running tests. /// </summary> private long placementId; /// <summary> /// Order id for running tests. /// </summary> private long orderId; /// <summary> /// Line item 1 for running tests. /// </summary> private LineItem lineItem1; /// <summary> /// Line item 2 for running tests. /// </summary> private LineItem lineItem2; /// <summary> /// Default public constructor. /// </summary> public LineItemServiceTests() : base() { } /// <summary> /// Initialize the test case. /// </summary> [SetUp] public void Init() { TestUtils utils = new TestUtils(); lineItemService = (LineItemService)user.GetService(DfpService.v201411.LineItemService); advertiserId = utils.CreateCompany(user, CompanyType.ADVERTISER).id; salespersonId = utils.GetSalesperson(user).id; traffickerId = utils.GetTrafficker(user).id; orderId = utils.CreateOrder(user, advertiserId, salespersonId, traffickerId).id; adUnitId = utils.CreateAdUnit(user).id; placementId = utils.CreatePlacement(user, new string[] {adUnitId}).id; lineItem1 = utils.CreateLineItem(user, orderId, adUnitId); lineItem2 = utils.CreateLineItem(user, orderId, adUnitId); } /// <summary> /// Test whether we can create a list of line items. /// </summary> [Test] public void TestCreateLineItems() { // Create inventory targeting. InventoryTargeting inventoryTargeting = new InventoryTargeting(); inventoryTargeting.targetedPlacementIds = new long[] {placementId}; // Create geographical targeting. GeoTargeting geoTargeting = new GeoTargeting(); // Include the US and Quebec, Canada. Location countryLocation = new Location(); countryLocation.id = 2840L; Location regionLocation = new Location(); regionLocation.id = 20123L; geoTargeting.targetedLocations = new Location[] {countryLocation, regionLocation}; // Exclude Chicago and the New York metro area. Location cityLocation = new Location(); cityLocation.id = 1016367L; Location metroLocation = new Location(); metroLocation.id = 200501L; geoTargeting.excludedLocations = new Location[] {cityLocation, metroLocation}; // Exclude domains that are not under the network's control. UserDomainTargeting userDomainTargeting = new UserDomainTargeting(); userDomainTargeting.domains = new String[] {"usa.gov"}; userDomainTargeting.targeted = false; // Create day-part targeting. DayPartTargeting dayPartTargeting = new DayPartTargeting(); dayPartTargeting.timeZone = DeliveryTimeZone.BROWSER; // Target only the weekend in the browser's timezone. DayPart saturdayDayPart = new DayPart(); saturdayDayPart.dayOfWeek = Google.Api.Ads.Dfp.v201411.DayOfWeek.SATURDAY; saturdayDayPart.startTime = new TimeOfDay(); saturdayDayPart.startTime.hour = 0; saturdayDayPart.startTime.minute = MinuteOfHour.ZERO; saturdayDayPart.endTime = new TimeOfDay(); saturdayDayPart.endTime.hour = 24; saturdayDayPart.endTime.minute = MinuteOfHour.ZERO; DayPart sundayDayPart = new DayPart(); sundayDayPart.dayOfWeek = Google.Api.Ads.Dfp.v201411.DayOfWeek.SUNDAY; sundayDayPart.startTime = new TimeOfDay(); sundayDayPart.startTime.hour = 0; sundayDayPart.startTime.minute = MinuteOfHour.ZERO; sundayDayPart.endTime = new TimeOfDay(); sundayDayPart.endTime.hour = 24; sundayDayPart.endTime.minute = MinuteOfHour.ZERO; dayPartTargeting.dayParts = new DayPart[] {saturdayDayPart, sundayDayPart}; // Create technology targeting. TechnologyTargeting technologyTargeting = new TechnologyTargeting(); // Create browser targeting. BrowserTargeting browserTargeting = new BrowserTargeting(); browserTargeting.isTargeted = true; // Target just the Chrome browser. Technology browserTechnology = new Technology(); browserTechnology.id = 500072L; browserTargeting.browsers = new Technology[] {browserTechnology}; technologyTargeting.browserTargeting = browserTargeting; // Create an array to store local line item objects. LineItem[] lineItems = new LineItem[2]; for (int i = 0; i < lineItems.Length; i++) { LineItem lineItem = new LineItem(); lineItem.name = "Line item #" + new TestUtils().GetTimeStamp(); lineItem.orderId = orderId; lineItem.targeting = new Targeting(); lineItem.targeting.inventoryTargeting = inventoryTargeting; lineItem.targeting.geoTargeting = geoTargeting; lineItem.targeting.userDomainTargeting = userDomainTargeting; lineItem.targeting.dayPartTargeting = dayPartTargeting; lineItem.targeting.technologyTargeting = technologyTargeting; lineItem.lineItemType = LineItemType.STANDARD; lineItem.allowOverbook = true; // Set the creative rotation type to even. lineItem.creativeRotationType = CreativeRotationType.EVEN; // Set the size of creatives that can be associated with this line item. Size size = new Size(); size.width = 300; size.height = 250; size.isAspectRatio = false; // Create the creative placeholder. CreativePlaceholder creativePlaceholder = new CreativePlaceholder(); creativePlaceholder.size = size; lineItem.creativePlaceholders = new CreativePlaceholder[] {creativePlaceholder}; // Set the length of the line item to run. //lineItem.startDateTimeType = StartDateTimeType.IMMEDIATELY; lineItem.startDateTimeType = StartDateTimeType.IMMEDIATELY; lineItem.endDateTime = DateTimeUtilities.FromDateTime(System.DateTime.Today.AddMonths(1)); // Set the cost per unit to $2. lineItem.costType = CostType.CPM; lineItem.costPerUnit = new Money(); lineItem.costPerUnit.currencyCode = "USD"; lineItem.costPerUnit.microAmount = 2000000L; // Set the number of units bought to 500,000 so that the budget is // $1,000. Goal goal = new Goal(); goal.units = 500000L; goal.unitType = UnitType.IMPRESSIONS; lineItem.primaryGoal = goal; lineItems[i] = lineItem; } LineItem[] localLineItems = null; Assert.DoesNotThrow(delegate() { localLineItems = lineItemService.createLineItems(lineItems); }); Assert.NotNull(localLineItems); Assert.AreEqual(localLineItems.Length, 2); Assert.AreEqual(localLineItems[0].name, lineItems[0].name); Assert.AreEqual(localLineItems[0].orderId, lineItems[0].orderId); Assert.AreEqual(localLineItems[1].name, lineItems[1].name); Assert.AreEqual(localLineItems[1].orderId, lineItems[1].orderId); } /// <summary> /// Test whether we can fetch a list of existing line items that match given /// statement. /// </summary> [Test] public void TestGetLineItemsByStatement() { Statement statement = new Statement(); statement.query = string.Format("WHERE id = '{0}' LIMIT 1", lineItem1.id); LineItemPage page = null; Assert.DoesNotThrow(delegate() { page = lineItemService.getLineItemsByStatement(statement); }); Assert.NotNull(page); Assert.AreEqual(page.totalResultSetSize, 1); Assert.NotNull(page.results); Assert.AreEqual(page.results[0].id, lineItem1.id); Assert.AreEqual(page.results[0].name, lineItem1.name); Assert.AreEqual(page.results[0].orderId, lineItem1.orderId); } /// <summary> /// Test whether we can activate a line item. /// </summary> [Test] public void TestPerformLineItemAction() { Statement statement = new Statement(); statement.query = string.Format("WHERE orderId = '{0}' and status = '{1}'", orderId, ComputedStatus.INACTIVE); ActivateLineItems action = new ActivateLineItems(); UpdateResult result = null; Assert.DoesNotThrow(delegate() { result = lineItemService.performLineItemAction(action, statement); }); Assert.NotNull(result); } /// <summary> /// Test whether we can update a list of line items. /// </summary> [Test] public void TestUpdateLineItems() { lineItem1.costPerUnit.microAmount = 3500000; lineItem2.costPerUnit.microAmount = 3500000; LineItem[] localLineItems = null; Assert.DoesNotThrow(delegate() { localLineItems = lineItemService.updateLineItems(new LineItem[] {lineItem1, lineItem2}); }); Assert.NotNull(localLineItems); Assert.AreEqual(localLineItems.Length, 2); Assert.AreEqual(localLineItems[0].id, lineItem1.id); Assert.AreEqual(localLineItems[0].name, lineItem1.name); Assert.AreEqual(localLineItems[0].orderId, lineItem1.orderId); Assert.AreEqual(localLineItems[0].costPerUnit.microAmount, lineItem1.costPerUnit.microAmount); Assert.AreEqual(localLineItems[1].id, lineItem2.id); Assert.AreEqual(localLineItems[1].name, lineItem2.name); Assert.AreEqual(localLineItems[1].orderId, lineItem2.orderId); Assert.AreEqual(localLineItems[1].costPerUnit.microAmount, lineItem2.costPerUnit.microAmount); } } }