context stringlengths 2.52k 185k | gt stringclasses 1 value |
|---|---|
#region File Description
//-----------------------------------------------------------------------------
// MaterialsAndLights.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
#endregion
namespace MultipassLightingSample
{
/// <summary>
/// The central class for the sample Game.
/// </summary>
public class MultipassLighting : Microsoft.Xna.Framework.Game
{
#region Sample Fields
private GraphicsDeviceManager graphics;
private SampleArcBallCamera camera;
private Vector2 safeBounds;
private Vector2 debugTextHeight;
private SpriteBatch spriteBatch;
private SpriteFont debugTextFont;
private GamePadState lastGpState;
private KeyboardState lastKbState;
private Effect pointLightMeshEffect;
private string shaderVersionString = string.Empty;
private Matrix projection;
private Random random = new Random();
private bool forcePSTwo = false;
private float totalTime;
private float numFrames;
private float fps;
#endregion
#region Scene Fields
private Matrix meshRotation;
private Matrix[] meshWorlds;
private Material[] materials;
private Material floorMaterial;
private Matrix floorWorld;
private int materialRotation = 0;
private PointLight[] lights;
private Model[] sampleMeshes;
private Model pointLightMesh;
private int numLights;
private int maxLights;
private int numLightsPerPass;
private int maxLightsPerPass;
private Matrix lightMeshWorld;
#endregion
#region Shared Effect Fields
private Effect lightingEffect;
private EffectParameter viewParameter;
private EffectParameter projectionParameter;
private EffectParameter cameraPositionParameter;
#endregion
#region Initialization and Cleanup
public MultipassLighting()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
// enable default sample behaviors.
graphics.PreferredBackBufferWidth = 853;
graphics.PreferredBackBufferHeight = 480;
graphics.MinimumVertexShaderProfile = ShaderProfile.VS_2_0;
graphics.MinimumPixelShaderProfile = ShaderProfile.PS_2_0;
graphics.SynchronizeWithVerticalRetrace = false;
IsFixedTimeStep = false;
}
/// <summary>
/// Initialize the sample.
/// </summary>
protected override void Initialize()
{
// create a default world and matrix
meshRotation = Matrix.Identity;
// create the mesh array
sampleMeshes = new Model[5];
// set up the sample camera
camera = new SampleArcBallCamera(SampleArcBallCameraMode.RollConstrained);
camera.Distance = 12;
// orbit the camera so we're looking down the z=-1 axis,
// at the "front" of the object
camera.OrbitRight(MathHelper.Pi);
// orbit up a bit for perspective
camera.OrbitUp(.2f);
//set up a ring of meshes
meshWorlds = new Matrix[8];
for (int i = 0; i < 8; i++)
{
float theta = MathHelper.TwoPi * ((float)i / 8f);
meshWorlds[i] = Matrix.CreateTranslation(
5f * (float)Math.Sin(theta), 0, 5f * (float)Math.Cos(theta));
}
// set the initial material assignments to the geometry
materialRotation = 2;
// stretch the cube out to represent a "floor"
// that will help visualize the light radii
floorWorld = Matrix.CreateScale(30f, 1f, 30f) *
Matrix.CreateTranslation(0, -2.2f, 0);
lightMeshWorld = Matrix.CreateScale(.2f);
base.Initialize();
}
/// <summary>
/// Load the graphics content.
/// </summary>
protected override void LoadContent()
{
// create the spritebatch for debug text
spriteBatch = new SpriteBatch(graphics.GraphicsDevice);
// load meshes
sampleMeshes[0] = Content.Load<Model>("Meshes\\Cube");
sampleMeshes[1] = Content.Load<Model>("Meshes\\SphereHighPoly");
sampleMeshes[2] = Content.Load<Model>("Meshes\\Cylinder");
sampleMeshes[3] = Content.Load<Model>("Meshes\\Cone");
pointLightMesh = Content.Load<Model>("Meshes\\SphereLowPoly");
// load the sprite font for debug text
debugTextFont = Content.Load<SpriteFont>("DebugText");
debugTextHeight = new Vector2(0, debugTextFont.LineSpacing + 5);
//load the effects
pointLightMeshEffect = Content.Load<Effect>("Effects\\PointLightMesh");
//////////////////////////////////////////////////////////////
// Example 1.1: Maximum Lights //
// //
// In this sample, there's an arbitrary fixed bound on the //
// number of lights used, this will generally be bounded by //
// pixel fill rates at the highest numbers. //
//////////////////////////////////////////////////////////////
maxLights = 300;
lights = new PointLight[maxLights];
//Select a pixel shader version based on device caps
if ((graphics.GraphicsDevice.GraphicsDeviceCapabilities.
PixelShaderVersion.Major >= 3) && !forcePSTwo)
{
lightingEffect = Content.Load<Effect>("Effects\\MaterialShader30");
numLights = 30;
maxLightsPerPass = 12;
numLightsPerPass = 8;
shaderVersionString = "Using Shader Model 3.0";
}
else
{
lightingEffect = Content.Load<Effect>("Effects\\MaterialShader20");
numLights = 30;
maxLightsPerPass = 1;
numLightsPerPass = 1;
shaderVersionString = "Using Shader Model 2.0";
}
// generate random light paramters
GenerateRandomLights();
// cache the effect parameters
viewParameter = lightingEffect.Parameters["view"];
projectionParameter = lightingEffect.Parameters["projection"];
cameraPositionParameter = lightingEffect.Parameters["cameraPosition"];
// create the materials
materials = new Material[8];
for (int i = 0; i < materials.Length; i++)
{
materials[i] = new Material(Content, graphics.GraphicsDevice,
lightingEffect);
}
floorMaterial = new Material(Content, graphics.GraphicsDevice,
lightingEffect);
//////////////////////////////////////////////////////////////
// Example 1.2: Material Properties //
// //
// Each material will have a unique set of properties. For //
// the purposes of this sample, the materials are assigned //
// at runtime. Often, these kinds of material properties //
// are specific to the Model being used, and can be //
// imported through the Content Pipeline using custom //
// processors and/or importers. Very little of //
// this code has to change when rendering multiple passes. //
//////////////////////////////////////////////////////////////
materials[0].SetBasicProperties(Color.Purple, .5f, 1.2f);
materials[1].SetBasicProperties(Color.Orange, 8f, 2f);
materials[2].SetBasicProperties(Color.Green, 2f, 3f);
materials[3].SetBasicProperties(Color.White, 256f, 16f);
materials[4].SetTexturedMaterial(Color.CornflowerBlue, 64f, 4f, null,
"Scratches", .5f, .5f);
materials[5].SetTexturedMaterial(Color.LemonChiffon, 32f, 4f, "Marble",
"Scratches", 1f, 1f);
materials[6].SetTexturedMaterial(Color.White, 32f, 16f, "Wood", null,
3f, 3f);
materials[7].SetTexturedMaterial(Color.White, 64f, 64f, "Hexes",
"HexesSpecular", 4f, 2f);
floorMaterial.SetTexturedMaterial(Color.White, 16f, .8f, "Grid",
"Grid", 15f, 15f);
//////////////////////////////////////////////////////////////
// Example 1.3: Shared Parameters //
// //
// It is interesting to note that shared parameters like //
// the following offfer little in the way of improved //
// batching performance as of the development of this //
// sample. They are most used for convenience and //
// readability. //
//////////////////////////////////////////////////////////////
lightingEffect.Parameters["ambientLightColor"].SetValue(
new Vector4(.10f, .10f, .10f, 1.0f));
lightingEffect.Parameters["numLightsPerPass"].SetValue(numLightsPerPass);
// Recalculate the projection properties on every LoadGraphicsContent call.
// That way, if the window gets resized, then the perspective matrix will
// be updated accordingly
float aspectRatio = (float)graphics.GraphicsDevice.Viewport.Width /
(float)graphics.GraphicsDevice.Viewport.Height;
float fieldOfView = aspectRatio * MathHelper.PiOver4 * 3f / 4f;
projection = Matrix.CreatePerspectiveFieldOfView(
fieldOfView, aspectRatio, .1f, 1000f);
projectionParameter.SetValue(projection);
// calculate the safe left and top edges of the screen
safeBounds = new Vector2(
(float)graphics.GraphicsDevice.Viewport.X +
(float)graphics.GraphicsDevice.Viewport.Width * 0.1f,
(float)graphics.GraphicsDevice.Viewport.Y +
(float)graphics.GraphicsDevice.Viewport.Height * 0.1f
);
}
#endregion
#region Update and Render
/// <summary>
/// This function populates the lights list with semi-random
/// light properties.
/// </summary>
public void GenerateRandomLights()
{
for (int i = 0; i < lights.Length; i++)
{
//generate a "circle" of lights
float theta = MathHelper.TwoPi * ((float)(i / 2) / (float)lights.Length)
+ (MathHelper.Pi * i);
Vector4 position = new Vector4(
9f * (float)Math.Sin(theta), 4, 9f * (float)Math.Cos(theta), 1.0f);
//initialize the lights
lights[i] = new PointLight(position);
//randomize the color, range, and power of the lights
lights[i].Range = 4f + ((float)random.NextDouble() * 24f);
lights[i].Falloff = 2f + ((float)random.NextDouble() * 4f);
lights[i].Color = new Color(new Vector3((float)random.NextDouble(),
(float)random.NextDouble(), (float)random.NextDouble()));
//rotate all of the lights to give them a more
//interesting distribution
Matrix rotation = Matrix.CreateRotationX(
(float)(random.NextDouble() * Math.PI * 2.0));
lights[i].Position = Vector4.Transform(lights[i].Position, rotation);
rotation = Matrix.CreateRotationZ(
(float)(random.NextDouble() * Math.PI * 2.0));
lights[i].Position = Vector4.Transform(lights[i].Position, rotation);
}
//always set light 0 to pure white as a reference point
//and make it bright enough to be obvious
lights[0].Color = Color.White;
lights[0].Falloff = 2f;
lights[0].Range = 30f;
}
/// <summary>
/// Update the game world.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
GamePadState gpState = GamePad.GetState(PlayerIndex.One);
KeyboardState kbState = Keyboard.GetState();
// Check for exit
if ((gpState.Buttons.Back == ButtonState.Pressed) ||
kbState.IsKeyDown(Keys.Escape))
{
Exit();
}
// handle inputs for the sample camera
camera.HandleDefaultGamepadControls(gpState, gameTime);
camera.HandleDefaultKeyboardControls(kbState, gameTime);
// handle inputs specific to this sample
HandleInput(gameTime, gpState, kbState);
// The camera position should also be updated for the
// Phong specular component to be meaningful.
cameraPositionParameter.SetValue(camera.Position);
// replace the "last" gamepad and keyboard states
lastGpState = gpState;
lastKbState = kbState;
//This section adds a rotation to put the array of lights into motion
Matrix rotation = Matrix.CreateRotationX(
(float)(gameTime.ElapsedGameTime.TotalSeconds));
for (int i = 0; i < (maxLights / 2); i++)
{
// rotate all of the lights by transforming their positions
lights[i].Position = Vector4.Transform(lights[i].Position, rotation);
}
rotation = Matrix.CreateRotationZ(
(float)(gameTime.ElapsedGameTime.TotalSeconds * .5f));
for (int i = (maxLights / 2); i < maxLights; i++)
{
// rotate all of the lights by transforming their positions
lights[i].Position = Vector4.Transform(lights[i].Position, rotation);
}
base.Update(gameTime);
}
private void HandleInput(GameTime gameTime, GamePadState gpState,
KeyboardState kbState)
{
float elapsedTime = (float)gameTime.ElapsedGameTime.TotalSeconds;
// handle input for rotating the materials
if (((gpState.Buttons.X == ButtonState.Pressed) &&
(lastGpState.Buttons.X == ButtonState.Released)) ||
(kbState.IsKeyDown(Keys.Tab) && lastKbState.IsKeyUp(Keys.Tab)))
{
// switch the active mesh
materialRotation = (materialRotation + 1) % materials.Length;
}
// handle input for adding lights to the scene
if (((gpState.Buttons.RightShoulder == ButtonState.Pressed) &&
(lastGpState.Buttons.RightShoulder == ButtonState.Released)) ||
(kbState.IsKeyDown(Keys.Add) && lastKbState.IsKeyUp(Keys.Add)))
{
numLights = ((numLights) % (maxLights)) + 1;
}
// handle input for removing lights from the scene
if (((gpState.Buttons.LeftShoulder == ButtonState.Pressed) &&
(lastGpState.Buttons.LeftShoulder == ButtonState.Released)) ||
(kbState.IsKeyDown(Keys.Subtract) &&
lastKbState.IsKeyUp(Keys.Subtract)))
{
numLights = (numLights - 1);
if (numLights < 1) numLights = maxLights;
}
// handle input for adding lights to the scene
if (((gpState.DPad.Up == ButtonState.Pressed) &&
(lastGpState.DPad.Up == ButtonState.Released)) ||
(kbState.IsKeyDown(Keys.P) && lastKbState.IsKeyUp(Keys.P)))
{
numLightsPerPass = ((numLightsPerPass) % (maxLightsPerPass)) + 1;
lightingEffect.Parameters["numLightsPerPass"].SetValue(numLightsPerPass);
}
// handle input for generating new values for the lights
if (((gpState.Buttons.Y == ButtonState.Pressed) &&
(lastGpState.Buttons.Y == ButtonState.Released)) ||
(kbState.IsKeyDown(Keys.Space) && lastKbState.IsKeyUp(Keys.Space)))
{
GenerateRandomLights();
}
// handle mesh rotation inputs
float dx =
SampleArcBallCamera.ReadKeyboardAxis(kbState, Keys.Left, Keys.Right) +
gpState.ThumbSticks.Left.X;
float dy =
SampleArcBallCamera.ReadKeyboardAxis(kbState, Keys.Down, Keys.Up) +
gpState.ThumbSticks.Left.Y;
// apply mesh rotation from inputs
if (dx != 0)
{
meshRotation *= Matrix.CreateFromAxisAngle(camera.Up,
elapsedTime * dx);
}
if (dy != 0)
{
meshRotation *= Matrix.CreateFromAxisAngle(camera.Right,
elapsedTime * -dy);
}
// handle the light rotation inputs
float lightRotation =
SampleArcBallCamera.ReadKeyboardAxis(kbState, Keys.PageUp,
Keys.PageDown) + gpState.Triggers.Right - gpState.Triggers.Left;
if (lightRotation != 0)
{
Matrix rotation = Matrix.CreateRotationY(lightRotation * elapsedTime);
foreach (PointLight light in lights)
{
// rotate all of the lights by transforming their positions
light.Position = Vector4.Transform(light.Position, rotation);
}
}
}
/// <summary>
/// Draw the current scene.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
graphics.GraphicsDevice.Clear(Color.Black);
// always set the shared effects parameters
viewParameter.SetValue(camera.ViewMatrix);
cameraPositionParameter.SetValue(camera.Position);
//////////////////////////////////////////////////////////////
// Example 1.4: Render States //
// //
// Rendering lights in multiple passes is accomplished by //
// using an additive color blend on each subsequent //
// lighting pass. The following renderstates cause each //
// pass to add the effect of each light or group of lights //
// to the back buffer. This requires careful use of the //
// depth buffer compare function so that lights are not //
// discarded. //
//////////////////////////////////////////////////////////////
graphics.GraphicsDevice.RenderState.BlendFunction =
BlendFunction.Add;
graphics.GraphicsDevice.RenderState.DestinationBlend = Blend.One;
graphics.GraphicsDevice.RenderState.SourceBlend = Blend.One;
graphics.GraphicsDevice.RenderState.DepthBufferFunction =
CompareFunction.LessEqual;
graphics.GraphicsDevice.RenderState.DepthBufferEnable = true;
//The outer loop progresses through each material
for (int i = 0; i < materials.Length; i++)
{
Matrix world = meshRotation * meshWorlds[i];
lightingEffect.Parameters["numLightsPerPass"].SetValue(numLightsPerPass);
int materialIndex = (i + materialRotation) % 8;
//A material batch is started.
materials[materialIndex].BeginBatch(
sampleMeshes[i % 4], ref world);
//////////////////////////////////////////////////////////////
// Example 1.5: Multi-Pass Geometry Render Loop //
// //
// Each light or group of lights is drawn in a pass. //
// Light parameters are set before each draw, and //
// CommitChanges() is called on the effect by the material //
// DrawModel() function. //
//////////////////////////////////////////////////////////////
for (int pass = 0; pass < (((numLights - 1) / numLightsPerPass) + 1);
pass++)
{
//Here the light effect parameters are updated based on
//the number of lights in each pass.
for (int l = 0; l < numLightsPerPass; l++)
{
//loop through parameters and update them for the current pass
int lightIndex = (pass * numLightsPerPass) + l;
if (lightIndex < numLights)
lights[lightIndex].UpdateLight(
materials[materialIndex].LightsParameter.Elements[l]);
else
{
lightingEffect.Parameters["numLightsPerPass"].SetValue(l);
break;
}
}
materials[materialIndex].DrawModel();
}
materials[materialIndex].EndBatch();
}
//The final set of lighting passes applies only to the floor model.
lightingEffect.Parameters["numLightsPerPass"].SetValue(numLightsPerPass);
floorMaterial.BeginBatch(sampleMeshes[0], ref floorWorld);
for (int pass = 0; pass < (((numLights-1) / numLightsPerPass)+1); pass++)
{
for (int l = 0; l < numLightsPerPass; l++)
{
int lightIndex = (pass * numLightsPerPass) + l;
if (lightIndex < numLights)
lights[lightIndex].UpdateLight(
floorMaterial.LightsParameter.Elements[l]);
else
{
lightingEffect.Parameters["numLightsPerPass"].SetValue(l);
break;
}
}
floorMaterial.DrawModel();
}
floorMaterial.EndBatch();
// draw a representation of the point lights in the scene
DrawLights();
totalTime += (float) gameTime.ElapsedGameTime.TotalSeconds;
numFrames++;
if (totalTime > 1.0f)
{
fps = numFrames / totalTime;
totalTime = 0f;
numFrames = 0f;
}
DrawDebugText();
base.Draw(gameTime);
}
/// <summary>
/// Draws debug information about the sample scene
/// </summary>
protected void DrawDebugText()
{
//draw the text description of the scene
spriteBatch.Begin();
//align text to pixels to avoid text artifacts
Vector2 fontPosition = new Vector2((float) Math.Floor(safeBounds.X),
(float) Math.Floor(safeBounds.Y));
spriteBatch.DrawString(debugTextFont,
shaderVersionString,
fontPosition, Color.White);
fontPosition = new Vector2(
(float) Math.Floor(safeBounds.X + (1 * debugTextHeight.X)),
(float) Math.Floor(safeBounds.Y + (1 * debugTextHeight.Y)));
spriteBatch.DrawString(debugTextFont,
"Number of lights: " + numLights + " out of " + maxLights,
fontPosition, Color.White);
fontPosition = new Vector2(
(float)Math.Floor(safeBounds.X + (2 * debugTextHeight.X)),
(float)Math.Floor(safeBounds.Y + (2 * debugTextHeight.Y)));
spriteBatch.DrawString(debugTextFont,
"Lights Per Draw: " + numLightsPerPass + " out of " + maxLightsPerPass,
fontPosition, Color.White);
fontPosition = new Vector2(
(float)Math.Floor(safeBounds.X + (3 * debugTextHeight.X)),
(float)Math.Floor(safeBounds.Y + (3 * debugTextHeight.Y)));
spriteBatch.DrawString(debugTextFont,
"FPS: " + fps,
fontPosition, Color.White);
spriteBatch.End();
}
/// <summary>
/// This simple draw function is used to draw the on-screen
/// representation of the lights affecting the meshes in the scene.
/// </summary>
protected void DrawLights()
{
ModelMesh mesh = pointLightMesh.Meshes[0];
ModelMeshPart meshPart = mesh.MeshParts[0];
graphics.GraphicsDevice.Vertices[0].SetSource(
mesh.VertexBuffer, meshPart.StreamOffset, meshPart.VertexStride);
graphics.GraphicsDevice.VertexDeclaration = meshPart.VertexDeclaration;
graphics.GraphicsDevice.Indices = mesh.IndexBuffer;
pointLightMeshEffect.Begin(SaveStateMode.None);
pointLightMeshEffect.CurrentTechnique.Passes[0].Begin();
//loop through the lights and draw a flat-colored sphere
//to represent their positions
for (int i = 0; i < numLights; i++)
{
lightMeshWorld.M41 = lights[i].Position.X;
lightMeshWorld.M42 = lights[i].Position.Y;
lightMeshWorld.M43 = lights[i].Position.Z;
pointLightMeshEffect.Parameters["world"].SetValue(lightMeshWorld);
pointLightMeshEffect.Parameters["lightColor"].SetValue(
lights[i].Color.ToVector4());
pointLightMeshEffect.CommitChanges();
graphics.GraphicsDevice.DrawIndexedPrimitives(
PrimitiveType.TriangleList, meshPart.BaseVertex, 0,
meshPart.NumVertices, meshPart.StartIndex, meshPart.PrimitiveCount);
}
pointLightMeshEffect.CurrentTechnique.Passes[0].End();
pointLightMeshEffect.End();
}
#endregion
#region Entry Point
/// <summary>
/// The main entry point for the application.
/// </summary>
public static void Main()
{
using (MultipassLighting game = new MultipassLighting())
{
game.Run();
}
}
#endregion
}
}
| |
using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using Telegram.Bot.Converters;
using Telegram.Bot.Types.Enums;
namespace Telegram.Bot.Types
{
/// <summary>
/// This object contains information about one member of the chat.
/// </summary>
[JsonObject(MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))]
[JsonConverter(typeof(ChatMemberConverter))]
public abstract class ChatMember
{
/// <summary>
/// The member's status in the chat.
/// </summary>
[JsonProperty]
public abstract ChatMemberStatus Status { get; }
/// <summary>
/// Information about the user
/// </summary>
[JsonProperty(Required = Required.Always)]
public User User { get; set; } = default!;
}
/// <summary>
/// Represents a <see cref="ChatMember"/> that owns the chat and has all administrator privileges
/// </summary>
[JsonObject(MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))]
public class ChatMemberOwner : ChatMember
{
/// <inheritdoc />
public override ChatMemberStatus Status => ChatMemberStatus.Creator;
/// <summary>
/// Custom title for this user
/// </summary>
[JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)]
public string? CustomTitle { get; set; }
/// <summary>
/// True, if the user's presence in the chat is hidden
/// </summary>
[JsonProperty(Required = Required.Always)]
public bool IsAnonymous { get; set; }
}
/// <summary>
/// Represents a <see cref="ChatMember"/> that has some additional privileges
/// </summary>
[JsonObject(MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))]
public class ChatMemberAdministrator : ChatMember
{
/// <inheritdoc />
public override ChatMemberStatus Status => ChatMemberStatus.Administrator;
/// <summary>
/// <c>true</c>, if the bot is allowed to edit administrator privileges of that user
/// </summary>
[JsonProperty(Required = Required.Always)]
public bool CanBeEdited { get; set; }
/// <summary>
/// Custom title for this user
/// </summary>
[JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)]
public string? CustomTitle { get; set; }
/// <summary>
/// <c>true</c>, if the user's presence in the chat is hidden
/// </summary>
[JsonProperty(Required = Required.Always)]
public bool IsAnonymous { get; set; }
/// <summary>
/// <c>true</c>, if the administrator can access the chat event log, chat statistics, message statistics
/// in channels, see channel members, see anonymous administrators in supergroups and ignore slow mode.
/// Implied by any other administrator privilege
/// </summary>
[JsonProperty(Required = Required.Always)]
public bool CanManageChat { get; set; }
/// <summary>
/// <c>true</c>, if the administrator can post in the channel, channels only
/// </summary>
[JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)]
public bool? CanPostMessages { get; set; }
/// <summary>
/// <c>true</c>, if the administrator can edit messages of other users, channels only
/// </summary>
[JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)]
public bool? CanEditMessages { get; set; }
/// <summary>
/// <c>true</c>, if the administrator can delete messages of other users
/// </summary>
[JsonProperty(Required = Required.Always)]
public bool CanDeleteMessages { get; set; }
/// <summary>
/// <c>true</c>, if the administrator can manage voice chats
/// </summary>
[JsonProperty(Required = Required.Always)]
public bool CanManageVoiceChats { get; set; }
/// <summary>
/// <c>true</c>, if the administrator can restrict, ban or unban chat members
/// </summary>
[JsonProperty(Required = Required.Always)]
public bool CanRestrictMembers { get; set; }
/// <summary>
/// <c>true</c>, if the administrator can add new administrators with a subset of his own privileges or
/// demote administrators that he has promoted, directly or indirectly (promoted by administrators that
/// were appointed by the user)
/// </summary>
[JsonProperty(Required = Required.Always)]
public bool CanPromoteMembers { get; set; }
/// <summary>
/// <c>true</c>, if the administrator can change the chat title, photo and other settings
/// </summary>
[JsonProperty(Required = Required.Always)]
public bool CanChangeInfo { get; set; }
/// <summary>
/// <c>true</c>, if the administrator can invite new users to the chat
/// </summary>
[JsonProperty(Required = Required.Always)]
public bool CanInviteUsers { get; set; }
/// <summary>
/// <c>true</c>, if the administrator can pin messages, supergroups only
/// </summary>
[JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)]
public bool? CanPinMessages { get; set; }
}
/// <summary>
/// Represents a <see cref="ChatMember"/> that has no additional privileges or restrictions.
/// </summary>
[JsonObject(MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))]
public class ChatMemberMember : ChatMember
{
/// <inheritdoc />
public override ChatMemberStatus Status => ChatMemberStatus.Member;
}
/// <summary>
/// Represents a <see cref="ChatMember"/> that is under certain restrictions in the chat. Supergroups only.
/// </summary>
[JsonObject(MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))]
public class ChatMemberRestricted : ChatMember
{
/// <inheritdoc />
public override ChatMemberStatus Status => ChatMemberStatus.Restricted;
/// <summary>
/// <c>true</c>, if the user is a member of the chat at the moment of the request
/// </summary>
[JsonProperty(Required = Required.Always)]
public bool IsMember { get; set; }
/// <summary>
/// <c>true</c>, if the user can change the chat title, photo and other settings
/// </summary>
[JsonProperty(Required = Required.Always)]
public bool CanChangeInfo { get; set; }
/// <summary>
/// <c>true</c>, if the user can invite new users to the chat
/// </summary>
[JsonProperty(Required = Required.Always)]
public bool CanInviteUsers { get; set; }
/// <summary>
/// <c>true</c>, if the user can pin messages, supergroups only
/// </summary>
[JsonProperty(Required = Required.Always)]
public bool CanPinMessages { get; set; }
/// <summary>
/// <c>true</c>, if the user can send text messages, contacts, locations and venues
/// </summary>
[JsonProperty(Required = Required.Always)]
public bool CanSendMessages { get; set; }
/// <summary>
/// <c>true</c>, if the user can send audios, documents, photos, videos, video notes and voice notes,
/// implies <see cref="CanSendMessages"/>
/// </summary>
[JsonProperty(Required = Required.Always)]
public bool CanSendMediaMessages { get; set; }
/// <summary>
/// <c>true</c>, if the user is allowed to send polls
/// </summary>
[JsonProperty(Required = Required.Always)]
public bool CanSendPolls { get; set; }
/// <summary>
/// <c>true</c>, if the user can send animations, games, stickers and use inline bots,
/// implies <see cref="CanSendMediaMessages"/>
/// </summary>
[JsonProperty(Required = Required.Always)]
public bool CanSendOtherMessages { get; set; }
/// <summary>
/// <c>true</c>, if user may add web page previews to his messages,
/// implies <see cref="CanSendMediaMessages"/>
/// </summary>
[JsonProperty(Required = Required.Always)]
public bool CanAddWebPagePreviews { get; set; }
/// <summary>
/// Date when restrictions will be lifted for this user, UTC time
/// </summary>
[JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)]
[JsonConverter(typeof(BanTimeUnixDateTimeConverter))]
public DateTime? UntilDate { get; set; }
}
/// <summary>
/// Represents a <see cref="ChatMember"/> that isn't currently a member of the chat, but may join it themselves
/// </summary>
[JsonObject(MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))]
public class ChatMemberLeft : ChatMember
{
/// <inheritdoc />
public override ChatMemberStatus Status => ChatMemberStatus.Left;
}
/// <summary>
/// Represents a <see cref="ChatMember"/> that was banned in the chat and can't return to the chat
/// or view chat messages
/// </summary>
[JsonObject(MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))]
public class ChatMemberBanned : ChatMember
{
/// <inheritdoc />
public override ChatMemberStatus Status => ChatMemberStatus.Kicked;
/// <summary>
/// Date when restrictions will be lifted for this user, UTC time
/// </summary>
[JsonConverter(typeof(BanTimeUnixDateTimeConverter))]
[JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)]
public DateTime? UntilDate { get; set; }
}
}
| |
/*
* UltraCart Rest API V2
*
* UltraCart REST API Version 2
*
* OpenAPI spec version: 2.0.0
* Contact: support@ultracart.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using SwaggerDateConverter = com.ultracart.admin.v2.Client.SwaggerDateConverter;
namespace com.ultracart.admin.v2.Model
{
/// <summary>
/// CustomerReviewer
/// </summary>
[DataContract]
public partial class CustomerReviewer : IEquatable<CustomerReviewer>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="CustomerReviewer" /> class.
/// </summary>
/// <param name="autoApprove">True if reviewes from this customer profile should automatically be approved.</param>
/// <param name="averageOverallRating">Average overall rating of items reviewed.</param>
/// <param name="expert">True if the customer is an expert.</param>
/// <param name="firstReview">First review.</param>
/// <param name="lastReview">Last review.</param>
/// <param name="location">Location of the reviewer.</param>
/// <param name="nickname">Nickname of the reviewer.</param>
/// <param name="numberHelpfulReviewVotes">Number of helpful review votes.</param>
/// <param name="rank">Rank of this reviewer.</param>
/// <param name="reviewsContributed">Number of reviews contributed.</param>
public CustomerReviewer(bool? autoApprove = default(bool?), decimal? averageOverallRating = default(decimal?), bool? expert = default(bool?), string firstReview = default(string), string lastReview = default(string), string location = default(string), string nickname = default(string), int? numberHelpfulReviewVotes = default(int?), int? rank = default(int?), int? reviewsContributed = default(int?))
{
this.AutoApprove = autoApprove;
this.AverageOverallRating = averageOverallRating;
this.Expert = expert;
this.FirstReview = firstReview;
this.LastReview = lastReview;
this.Location = location;
this.Nickname = nickname;
this.NumberHelpfulReviewVotes = numberHelpfulReviewVotes;
this.Rank = rank;
this.ReviewsContributed = reviewsContributed;
}
/// <summary>
/// True if reviewes from this customer profile should automatically be approved
/// </summary>
/// <value>True if reviewes from this customer profile should automatically be approved</value>
[DataMember(Name="auto_approve", EmitDefaultValue=false)]
public bool? AutoApprove { get; set; }
/// <summary>
/// Average overall rating of items reviewed
/// </summary>
/// <value>Average overall rating of items reviewed</value>
[DataMember(Name="average_overall_rating", EmitDefaultValue=false)]
public decimal? AverageOverallRating { get; set; }
/// <summary>
/// True if the customer is an expert
/// </summary>
/// <value>True if the customer is an expert</value>
[DataMember(Name="expert", EmitDefaultValue=false)]
public bool? Expert { get; set; }
/// <summary>
/// First review
/// </summary>
/// <value>First review</value>
[DataMember(Name="first_review", EmitDefaultValue=false)]
public string FirstReview { get; set; }
/// <summary>
/// Last review
/// </summary>
/// <value>Last review</value>
[DataMember(Name="last_review", EmitDefaultValue=false)]
public string LastReview { get; set; }
/// <summary>
/// Location of the reviewer
/// </summary>
/// <value>Location of the reviewer</value>
[DataMember(Name="location", EmitDefaultValue=false)]
public string Location { get; set; }
/// <summary>
/// Nickname of the reviewer
/// </summary>
/// <value>Nickname of the reviewer</value>
[DataMember(Name="nickname", EmitDefaultValue=false)]
public string Nickname { get; set; }
/// <summary>
/// Number of helpful review votes
/// </summary>
/// <value>Number of helpful review votes</value>
[DataMember(Name="number_helpful_review_votes", EmitDefaultValue=false)]
public int? NumberHelpfulReviewVotes { get; set; }
/// <summary>
/// Rank of this reviewer
/// </summary>
/// <value>Rank of this reviewer</value>
[DataMember(Name="rank", EmitDefaultValue=false)]
public int? Rank { get; set; }
/// <summary>
/// Number of reviews contributed
/// </summary>
/// <value>Number of reviews contributed</value>
[DataMember(Name="reviews_contributed", EmitDefaultValue=false)]
public int? ReviewsContributed { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class CustomerReviewer {\n");
sb.Append(" AutoApprove: ").Append(AutoApprove).Append("\n");
sb.Append(" AverageOverallRating: ").Append(AverageOverallRating).Append("\n");
sb.Append(" Expert: ").Append(Expert).Append("\n");
sb.Append(" FirstReview: ").Append(FirstReview).Append("\n");
sb.Append(" LastReview: ").Append(LastReview).Append("\n");
sb.Append(" Location: ").Append(Location).Append("\n");
sb.Append(" Nickname: ").Append(Nickname).Append("\n");
sb.Append(" NumberHelpfulReviewVotes: ").Append(NumberHelpfulReviewVotes).Append("\n");
sb.Append(" Rank: ").Append(Rank).Append("\n");
sb.Append(" ReviewsContributed: ").Append(ReviewsContributed).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public virtual string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as CustomerReviewer);
}
/// <summary>
/// Returns true if CustomerReviewer instances are equal
/// </summary>
/// <param name="input">Instance of CustomerReviewer to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(CustomerReviewer input)
{
if (input == null)
return false;
return
(
this.AutoApprove == input.AutoApprove ||
(this.AutoApprove != null &&
this.AutoApprove.Equals(input.AutoApprove))
) &&
(
this.AverageOverallRating == input.AverageOverallRating ||
(this.AverageOverallRating != null &&
this.AverageOverallRating.Equals(input.AverageOverallRating))
) &&
(
this.Expert == input.Expert ||
(this.Expert != null &&
this.Expert.Equals(input.Expert))
) &&
(
this.FirstReview == input.FirstReview ||
(this.FirstReview != null &&
this.FirstReview.Equals(input.FirstReview))
) &&
(
this.LastReview == input.LastReview ||
(this.LastReview != null &&
this.LastReview.Equals(input.LastReview))
) &&
(
this.Location == input.Location ||
(this.Location != null &&
this.Location.Equals(input.Location))
) &&
(
this.Nickname == input.Nickname ||
(this.Nickname != null &&
this.Nickname.Equals(input.Nickname))
) &&
(
this.NumberHelpfulReviewVotes == input.NumberHelpfulReviewVotes ||
(this.NumberHelpfulReviewVotes != null &&
this.NumberHelpfulReviewVotes.Equals(input.NumberHelpfulReviewVotes))
) &&
(
this.Rank == input.Rank ||
(this.Rank != null &&
this.Rank.Equals(input.Rank))
) &&
(
this.ReviewsContributed == input.ReviewsContributed ||
(this.ReviewsContributed != null &&
this.ReviewsContributed.Equals(input.ReviewsContributed))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.AutoApprove != null)
hashCode = hashCode * 59 + this.AutoApprove.GetHashCode();
if (this.AverageOverallRating != null)
hashCode = hashCode * 59 + this.AverageOverallRating.GetHashCode();
if (this.Expert != null)
hashCode = hashCode * 59 + this.Expert.GetHashCode();
if (this.FirstReview != null)
hashCode = hashCode * 59 + this.FirstReview.GetHashCode();
if (this.LastReview != null)
hashCode = hashCode * 59 + this.LastReview.GetHashCode();
if (this.Location != null)
hashCode = hashCode * 59 + this.Location.GetHashCode();
if (this.Nickname != null)
hashCode = hashCode * 59 + this.Nickname.GetHashCode();
if (this.NumberHelpfulReviewVotes != null)
hashCode = hashCode * 59 + this.NumberHelpfulReviewVotes.GetHashCode();
if (this.Rank != null)
hashCode = hashCode * 59 + this.Rank.GetHashCode();
if (this.ReviewsContributed != null)
hashCode = hashCode * 59 + this.ReviewsContributed.GetHashCode();
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
namespace Finsternis
{
using System.Collections.Generic;
#region using Unity
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;
using UnityEngine.EventSystems;
#endregion
using UnityQuery;
using System.Collections;
using System;
[RequireComponent(typeof(InputRouter))]
[DisallowMultipleComponent]
public class InGameMenuController : MenuController
{
[SerializeField]
private ConfirmationDialogController confirmationDialog;
private GameObject optionsContainer;
private List<GameObject> options;
private Circle menuBounds;
private MenuEyeController eyeController;
private bool transitioning;
private float targetPercentage;
private GameObject lastSelected;
private UnityAction showNewGameDialog;
private UnityAction showExitGameDialog;
protected override void Awake()
{
base.Awake();
this.optionsContainer = transform.FindChild("OptionsContainer").gameObject;
this.menuBounds = new Circle(GetComponent<RectTransform>().sizeDelta.Min() / 2, GetComponent<RectTransform>().anchoredPosition);
this.options = new List<GameObject>();
this.eyeController = GetComponentInChildren<MenuEyeController>(true);
OnOpen.AddListener(menu =>
{
if (!lastSelected)
lastSelected = options[0];
if (EventSystem.currentSelectedGameObject != lastSelected)
EventSystem.SetSelectedGameObject(lastSelected);
else
eyeController.LookAt(lastSelected);
});
LoadOptions(optionsContainer);
showNewGameDialog = new UnityAction(() =>
this.confirmationDialog.Show("Start a new game?\n(current progress will be lost)", GameManager.Instance.NewGame, BeginOpening)
);
showExitGameDialog = new UnityAction(() =>
this.confirmationDialog.Show("Exit game?", GameManager.Instance.Exit, BeginOpening)
);
}
public void LoadOptions(GameObject optionsContainer)
{
foreach (Transform t in optionsContainer.transform)
this.options.Add(t.gameObject);
#if LOG_INFO || LOG_WARN
if (this.options.Count <= 0)
Log.W(this, "Not a single option found on the menu.");
else
#endif
if (this.options.Count > 1)
{
InitOptions();
}
}
private void InitOptions()
{
var options = this.optionsContainer.GetComponentsInChildren<Button>();
for (int i = 0; i < this.options.Count; i++)
{
int leftOption = i - 1;
int rightOption = i + 1;
if (leftOption < 0)
leftOption = this.options.Count - 1;
if (rightOption >= this.options.Count)
rightOption = 0;
Navigation n = new Navigation();
n.mode = Navigation.Mode.Explicit;
n.selectOnRight = options[rightOption];
n.selectOnLeft = options[leftOption];
options[i].navigation = n;
}
}
/// <summary>
/// Sets up everything in order for the menu to open (animations, effects, callbacks)
/// </summary>
public override void BeginOpening()
{
this.targetPercentage = 1;
base.BeginOpening();
onFinishedToggling.AddListener(Open);
StartCoroutine(_ToggleMenu());
}
/// <summary>
/// Sets up everything in order for the menu to close (animations, effects, callbacks)
/// </summary>
public override void BeginClosing()
{
this.targetPercentage = 0;
this.eyeController.Reset();
onFinishedToggling.AddListener(Close);
base.BeginClosing();
StartCoroutine(_ToggleMenu());
}
/// <summary>
/// Animates the menu, interpolating it's current and target state (eg. from Closed to Opened)
/// </summary>
protected IEnumerator _ToggleMenu()
{
if (!transitioning)
{
transitioning = true;
float currentPercentage = 1 - this.targetPercentage;
do
{
PositionButtons(currentPercentage);
currentPercentage = Mathf.Lerp(currentPercentage, targetPercentage, 0.2f);
yield return null;
}
while (Mathf.Abs(currentPercentage - targetPercentage) > 0.2f);
PositionButtons(targetPercentage); //call once more to avoid precision errors
onFinishedToggling.Invoke();
onFinishedToggling.RemoveAllListeners();
transitioning = false;
}
}
/// <summary>
/// Position every button within the menu in a circular fashion.
/// </summary>
/// <param name="percentage">How far from the center should the buttons be? (0 = centered, 1 = the menu radius. </param>
private void PositionButtons(float percentage = 1)
{
float angleBetweenOptions = -360 / options.Count;
Vector2 optionPosition = this.menuBounds.center + Vector2.up * this.menuBounds.radius * percentage;
for (int index = 0; index < options.Count; index++)
{
this.options[index].GetComponent<RectTransform>().anchoredPosition = optionPosition;
var dir = optionPosition - menuBounds.center;
dir = dir.Rotate(angleBetweenOptions);
optionPosition = dir.normalized * this.menuBounds.radius * percentage;
}
}
public void NewGame(bool immediately = true)
{
if (immediately)
{
GameManager.Instance.NewGame();
}
else
{
SkipCloseEvent = true;
BeginClosing();
onFinishedToggling.AddListener(showNewGameDialog);
}
}
public void Exit(bool immediately = false)
{
if (immediately)
{
GameManager.Instance.Exit();
}
else
{
SkipCloseEvent = true;
BeginClosing();
onFinishedToggling.AddListener(showExitGameDialog);
}
}
public override void Close()
{
this.lastSelected = EventSystem.currentSelectedGameObject;
base.Close();
}
public void CloseAndThenOpen(MenuController menu)
{
BeginClosing();
onFinishedToggling.AddListener(() => menu.BeginOpening());
}
}
}
| |
// 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.11.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsHttp
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Models;
/// <summary>
/// HttpRedirects operations.
/// </summary>
public partial interface IHttpRedirects
{
/// <summary>
/// Return 300 status code and redirect to /http/success/200
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> Head300WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Return 300 status code and redirect to /http/success/200
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<IList<string>>> Get300WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Return 301 status code and redirect to /http/success/200
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> Head301WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Return 301 status code and redirect to /http/success/200
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> Get301WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Put true Boolean value in request returns 301. This request
/// should not be automatically redirected, but should return the
/// received 301 to the caller for evaluation
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> Put301WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Return 302 status code and redirect to /http/success/200
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> Head302WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Return 302 status code and redirect to /http/success/200
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> Get302WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Patch true Boolean value in request returns 302. This request
/// should not be automatically redirected, but should return the
/// received 302 to the caller for evaluation
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> Patch302WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Post true Boolean value in request returns 303. This request
/// should be automatically redirected usign a get, ultimately
/// returning a 200 status code
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> Post303WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Redirect with 307, resulting in a 200 success
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> Head307WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Redirect get with 307, resulting in a 200 success
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> Get307WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Put redirected with 307, resulting in a 200 after redirect
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> Put307WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Patch redirected with 307, resulting in a 200 after redirect
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> Patch307WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Post redirected with 307, resulting in a 200 after redirect
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> Post307WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Delete redirected with 307, resulting in a 200 after redirect
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> Delete307WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
//
// Author: Nate Kohari <nate@enkari.com>
// Copyright (c) 2007-2010, Enkari, Ltd.
//
// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL).
// See the file LICENSE.txt for details.
//
namespace Telerik.JustMock.AutoMock.Ninject
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Telerik.JustMock.AutoMock.Ninject.Activation;
using Telerik.JustMock.AutoMock.Ninject.Activation.Blocks;
using Telerik.JustMock.AutoMock.Ninject.Activation.Caching;
using Telerik.JustMock.AutoMock.Ninject.Components;
using Telerik.JustMock.AutoMock.Ninject.Infrastructure;
using Telerik.JustMock.AutoMock.Ninject.Infrastructure.Introspection;
using Telerik.JustMock.AutoMock.Ninject.Infrastructure.Language;
using Telerik.JustMock.AutoMock.Ninject.Modules;
using Telerik.JustMock.AutoMock.Ninject.Parameters;
using Telerik.JustMock.AutoMock.Ninject.Planning;
using Telerik.JustMock.AutoMock.Ninject.Planning.Bindings;
using Telerik.JustMock.AutoMock.Ninject.Planning.Bindings.Resolvers;
using Telerik.JustMock.AutoMock.Ninject.Syntax;
/// <summary>
/// The base implementation of an <see cref="IKernel"/>.
/// </summary>
public abstract class KernelBase : BindingRoot, IKernel
{
/// <summary>
/// Lock used when adding missing bindings.
/// </summary>
protected readonly object HandleMissingBindingLockObject = new object();
private readonly Multimap<Type, IBinding> bindings = new Multimap<Type, IBinding>();
private readonly Multimap<Type, IBinding> bindingCache = new Multimap<Type, IBinding>();
private readonly Dictionary<string, INinjectModule> modules = new Dictionary<string, INinjectModule>();
/// <summary>
/// Initializes a new instance of the <see cref="KernelBase"/> class.
/// </summary>
protected KernelBase()
: this(new ComponentContainer(), new NinjectSettings(), new INinjectModule[0])
{
}
/// <summary>
/// Initializes a new instance of the <see cref="KernelBase"/> class.
/// </summary>
/// <param name="modules">The modules to load into the kernel.</param>
protected KernelBase(params INinjectModule[] modules)
: this(new ComponentContainer(), new NinjectSettings(), modules)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="KernelBase"/> class.
/// </summary>
/// <param name="settings">The configuration to use.</param>
/// <param name="modules">The modules to load into the kernel.</param>
protected KernelBase(INinjectSettings settings, params INinjectModule[] modules)
: this(new ComponentContainer(), settings, modules)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="KernelBase"/> class.
/// </summary>
/// <param name="components">The component container to use.</param>
/// <param name="settings">The configuration to use.</param>
/// <param name="modules">The modules to load into the kernel.</param>
protected KernelBase(IComponentContainer components, INinjectSettings settings, params INinjectModule[] modules)
{
Ensure.ArgumentNotNull(components, "components");
Ensure.ArgumentNotNull(settings, "settings");
Ensure.ArgumentNotNull(modules, "modules");
this.Settings = settings;
this.Components = components;
components.Kernel = this;
this.AddComponents();
this.Bind<IKernel>().ToConstant(this).InTransientScope();
this.Bind<IResolutionRoot>().ToConstant(this).InTransientScope();
#if !NO_ASSEMBLY_SCANNING
if (this.Settings.LoadExtensions)
{
this.Load(this.Settings.ExtensionSearchPatterns);
}
#endif
this.Load(modules);
}
/// <summary>
/// Gets the kernel settings.
/// </summary>
public INinjectSettings Settings { get; private set; }
/// <summary>
/// Gets the component container, which holds components that contribute to Ninject.
/// </summary>
public IComponentContainer Components { get; private set; }
/// <summary>
/// Releases resources held by the object.
/// </summary>
public override void Dispose(bool disposing)
{
if (disposing && !IsDisposed)
{
if (this.Components != null)
{
// Deactivate all cached instances before shutting down the kernel.
var cache = this.Components.Get<ICache>();
cache.Clear();
this.Components.Dispose();
}
}
base.Dispose(disposing);
}
/// <summary>
/// Unregisters all bindings for the specified service.
/// </summary>
/// <param name="service">The service to unbind.</param>
public override void Unbind(Type service)
{
Ensure.ArgumentNotNull(service, "service");
this.bindings.RemoveAll(service);
lock (this.bindingCache)
{
this.bindingCache.Clear();
}
}
/// <summary>
/// Registers the specified binding.
/// </summary>
/// <param name="binding">The binding to add.</param>
public override void AddBinding(IBinding binding)
{
Ensure.ArgumentNotNull(binding, "binding");
this.AddBindings(new[] { binding });
}
/// <summary>
/// Unregisters the specified binding.
/// </summary>
/// <param name="binding">The binding to remove.</param>
public override void RemoveBinding(IBinding binding)
{
Ensure.ArgumentNotNull(binding, "binding");
this.bindings.Remove(binding.Service, binding);
lock (this.bindingCache)
this.bindingCache.Clear();
}
/// <summary>
/// Determines whether a module with the specified name has been loaded in the kernel.
/// </summary>
/// <param name="name">The name of the module.</param>
/// <returns><c>True</c> if the specified module has been loaded; otherwise, <c>false</c>.</returns>
public bool HasModule(string name)
{
Ensure.ArgumentNotNullOrEmpty(name, "name");
return this.modules.ContainsKey(name);
}
/// <summary>
/// Gets the modules that have been loaded into the kernel.
/// </summary>
/// <returns>A series of loaded modules.</returns>
public IEnumerable<INinjectModule> GetModules()
{
return this.modules.Values.ToArray();
}
/// <summary>
/// Loads the module(s) into the kernel.
/// </summary>
/// <param name="m">The modules to load.</param>
public void Load(IEnumerable<INinjectModule> m)
{
Ensure.ArgumentNotNull(m, "modules");
m = m.ToList();
foreach (INinjectModule module in m)
{
if (string.IsNullOrEmpty(module.Name))
{
throw new NotSupportedException(ExceptionFormatter.ModulesWithNullOrEmptyNamesAreNotSupported());
}
INinjectModule existingModule;
if (this.modules.TryGetValue(module.Name, out existingModule))
{
throw new NotSupportedException(ExceptionFormatter.ModuleWithSameNameIsAlreadyLoaded(module, existingModule));
}
module.OnLoad(this);
this.modules.Add(module.Name, module);
}
foreach (INinjectModule module in m)
{
module.OnVerifyRequiredModules();
}
}
#if !NO_ASSEMBLY_SCANNING
/// <summary>
/// Loads modules from the files that match the specified pattern(s).
/// </summary>
/// <param name="filePatterns">The file patterns (i.e. "*.dll", "modules/*.rb") to match.</param>
public void Load(IEnumerable<string> filePatterns)
{
var moduleLoader = this.Components.Get<IModuleLoader>();
moduleLoader.LoadModules(filePatterns);
}
/// <summary>
/// Loads modules defined in the specified assemblies.
/// </summary>
/// <param name="assemblies">The assemblies to search.</param>
public void Load(IEnumerable<Assembly> assemblies)
{
this.Load(assemblies.SelectMany(asm => asm.GetNinjectModules()));
}
#endif //!NO_ASSEMBLY_SCANNING
/// <summary>
/// Unloads the plugin with the specified name.
/// </summary>
/// <param name="name">The plugin's name.</param>
public void Unload(string name)
{
Ensure.ArgumentNotNullOrEmpty(name, "name");
INinjectModule module;
if (!this.modules.TryGetValue(name, out module))
{
throw new NotSupportedException(ExceptionFormatter.NoModuleLoadedWithTheSpecifiedName(name));
}
module.OnUnload(this);
this.modules.Remove(name);
}
/// <summary>
/// Injects the specified existing instance, without managing its lifecycle.
/// </summary>
/// <param name="instance">The instance to inject.</param>
/// <param name="parameters">The parameters to pass to the request.</param>
public virtual void Inject(object instance, params IParameter[] parameters)
{
Ensure.ArgumentNotNull(instance, "instance");
Ensure.ArgumentNotNull(parameters, "parameters");
Type service = instance.GetType();
var planner = this.Components.Get<IPlanner>();
var pipeline = this.Components.Get<IPipeline>();
var binding = new Binding(service);
var request = this.CreateRequest(service, null, parameters, false, false);
var context = this.CreateContext(request, binding);
context.Plan = planner.GetPlan(service);
var reference = new InstanceReference { Instance = instance };
pipeline.Activate(context, reference);
}
/// <summary>
/// Deactivates and releases the specified instance if it is currently managed by Ninject.
/// </summary>
/// <param name="instance">The instance to release.</param>
/// <returns><see langword="True"/> if the instance was found and released; otherwise <see langword="false"/>.</returns>
public virtual bool Release(object instance)
{
Ensure.ArgumentNotNull(instance, "instance");
var cache = this.Components.Get<ICache>();
return cache.Release(instance);
}
/// <summary>
/// Determines whether the specified request can be resolved.
/// </summary>
/// <param name="request">The request.</param>
/// <returns><c>True</c> if the request can be resolved; otherwise, <c>false</c>.</returns>
public virtual bool CanResolve(IRequest request)
{
Ensure.ArgumentNotNull(request, "request");
return this.GetBindings(request.Service).Any(this.SatifiesRequest(request));
}
/// <summary>
/// Determines whether the specified request can be resolved.
/// </summary>
/// <param name="request">The request.</param>
/// <param name="ignoreImplicitBindings">if set to <c>true</c> implicit bindings are ignored.</param>
/// <returns>
/// <c>True</c> if the request can be resolved; otherwise, <c>false</c>.
/// </returns>
public virtual bool CanResolve(IRequest request, bool ignoreImplicitBindings)
{
Ensure.ArgumentNotNull(request, "request");
return this.GetBindings(request.Service)
.Any(binding => (!ignoreImplicitBindings || !binding.IsImplicit) && this.SatifiesRequest(request)(binding));
}
/// <summary>
/// Resolves instances for the specified request. The instances are not actually resolved
/// until a consumer iterates over the enumerator.
/// </summary>
/// <param name="request">The request to resolve.</param>
/// <returns>An enumerator of instances that match the request.</returns>
public virtual IEnumerable<object> Resolve(IRequest request)
{
Ensure.ArgumentNotNull(request, "request");
var bindingPrecedenceComparer = this.GetBindingPrecedenceComparer();
var resolveBindings = Enumerable.Empty<IBinding>();
if (this.CanResolve(request) || this.HandleMissingBinding(request))
{
resolveBindings = this.GetBindings(request.Service)
.Where(this.SatifiesRequest(request));
}
if (!resolveBindings.Any())
{
if (request.IsOptional)
{
return Enumerable.Empty<object>();
}
throw new ActivationException(ExceptionFormatter.CouldNotResolveBinding(request));
}
if (request.IsUnique)
{
resolveBindings = resolveBindings.OrderByDescending(b => b, bindingPrecedenceComparer).ToList();
var model = resolveBindings.First(); // the type (conditonal, implicit, etc) of binding we'll return
resolveBindings =
resolveBindings.TakeWhile(binding => bindingPrecedenceComparer.Compare(binding, model) == 0);
if (resolveBindings.Count() > 1)
{
if (request.IsOptional)
{
return Enumerable.Empty<object>();
}
var formattedBindings =
from binding in resolveBindings
let context = this.CreateContext(request, binding)
select binding.Format(context);
throw new ActivationException(ExceptionFormatter.CouldNotUniquelyResolveBinding(request, formattedBindings.ToArray()));
}
}
if(resolveBindings.Any(binding => !binding.IsImplicit))
{
resolveBindings = resolveBindings.Where(binding => !binding.IsImplicit);
}
return resolveBindings
.Select(binding => this.CreateContext(request, binding).Resolve());
}
/// <summary>
/// Creates a request for the specified service.
/// </summary>
/// <param name="service">The service that is being requested.</param>
/// <param name="constraint">The constraint to apply to the bindings to determine if they match the request.</param>
/// <param name="parameters">The parameters to pass to the resolution.</param>
/// <param name="isOptional"><c>True</c> if the request is optional; otherwise, <c>false</c>.</param>
/// <param name="isUnique"><c>True</c> if the request should return a unique result; otherwise, <c>false</c>.</param>
/// <returns>The created request.</returns>
public virtual IRequest CreateRequest(Type service, Func<IBindingMetadata, bool> constraint, IEnumerable<IParameter> parameters, bool isOptional, bool isUnique)
{
Ensure.ArgumentNotNull(service, "service");
Ensure.ArgumentNotNull(parameters, "parameters");
return new Request(service, constraint, parameters, null, isOptional, isUnique);
}
/// <summary>
/// Begins a new activation block, which can be used to deterministically dispose resolved instances.
/// </summary>
/// <returns>The new activation block.</returns>
public virtual IActivationBlock BeginBlock()
{
return new ActivationBlock(this);
}
/// <summary>
/// Gets the bindings registered for the specified service.
/// </summary>
/// <param name="service">The service in question.</param>
/// <returns>A series of bindings that are registered for the service.</returns>
public virtual IEnumerable<IBinding> GetBindings(Type service)
{
Ensure.ArgumentNotNull(service, "service");
lock (this.bindingCache)
{
if (!this.bindingCache.ContainsKey(service))
{
var resolvers = this.Components.GetAll<IBindingResolver>();
resolvers
.SelectMany(resolver => resolver.Resolve(this.bindings, service))
.Map(binding => this.bindingCache.Add(service, binding));
}
return this.bindingCache[service];
}
}
/// <summary>
/// Returns an IComparer that is used to determine resolution precedence.
/// </summary>
/// <returns>An IComparer that is used to determine resolution precedence.</returns>
protected virtual IComparer<IBinding> GetBindingPrecedenceComparer()
{
return new BindingPrecedenceComparer();
}
/// <summary>
/// Returns a predicate that can determine if a given IBinding matches the request.
/// </summary>
/// <param name="request">The request/</param>
/// <returns>A predicate that can determine if a given IBinding matches the request.</returns>
protected virtual Func<IBinding, bool> SatifiesRequest(IRequest request)
{
return binding => binding.Matches(request) && request.Matches(binding);
}
/// <summary>
/// Adds components to the kernel during startup.
/// </summary>
protected abstract void AddComponents();
/// <summary>
/// Attempts to handle a missing binding for a service.
/// </summary>
/// <param name="service">The service.</param>
/// <returns><c>True</c> if the missing binding can be handled; otherwise <c>false</c>.</returns>
[Obsolete]
protected virtual bool HandleMissingBinding(Type service)
{
return false;
}
/// <summary>
/// Attempts to handle a missing binding for a request.
/// </summary>
/// <param name="request">The request.</param>
/// <returns><c>True</c> if the missing binding can be handled; otherwise <c>false</c>.</returns>
protected virtual bool HandleMissingBinding(IRequest request)
{
Ensure.ArgumentNotNull(request, "request");
#pragma warning disable 612,618
if (this.HandleMissingBinding(request.Service))
{
return true;
}
#pragma warning restore 612,618
var components = this.Components.GetAll<IMissingBindingResolver>();
// Take the first set of bindings that resolve.
var bindings = components
.Select(c => c.Resolve(this.bindings, request).ToList())
.FirstOrDefault(b => b.Any());
if (bindings == null)
{
return false;
}
lock (this.HandleMissingBindingLockObject)
{
if (!this.CanResolve(request))
{
bindings.Map(binding => binding.IsImplicit = true);
this.AddBindings(bindings);
}
}
return true;
}
/// <summary>
/// Returns a value indicating whether the specified service is self-bindable.
/// </summary>
/// <param name="service">The service.</param>
/// <returns><see langword="True"/> if the type is self-bindable; otherwise <see langword="false"/>.</returns>
[Obsolete]
protected virtual bool TypeIsSelfBindable(Type service)
{
return !service.IsInterface
&& !service.IsAbstract
&& !service.IsValueType
&& service != typeof(string)
&& !service.ContainsGenericParameters;
}
/// <summary>
/// Creates a context for the specified request and binding.
/// </summary>
/// <param name="request">The request.</param>
/// <param name="binding">The binding.</param>
/// <returns>The created context.</returns>
protected virtual IContext CreateContext(IRequest request, IBinding binding)
{
Ensure.ArgumentNotNull(request, "request");
Ensure.ArgumentNotNull(binding, "binding");
return new Context(this, request, binding, this.Components.Get<ICache>(), this.Components.Get<IPlanner>(), this.Components.Get<IPipeline>());
}
private void AddBindings(IEnumerable<IBinding> bindings)
{
bindings.Map(binding => this.bindings.Add(binding.Service, binding));
lock (this.bindingCache)
this.bindingCache.Clear();
}
object IServiceProvider.GetService(Type service)
{
return this.Get(service);
}
private class BindingPrecedenceComparer : IComparer<IBinding>
{
public int Compare(IBinding x, IBinding y)
{
if (x == y)
{
return 0;
}
// Each function represents a level of precedence.
var funcs = new List<Func<IBinding, bool>>
{
b => b != null, // null bindings should never happen, but just in case
b => b.IsConditional, // conditional bindings > unconditional
b => !b.Service.ContainsGenericParameters, // closed generics > open generics
b => !b.IsImplicit, // explicit bindings > implicit
};
var q = from func in funcs
let xVal = func(x)
where xVal != func(y)
select xVal ? 1 : -1;
// returns the value of the first function that represents a difference
// between the bindings, or else returns 0 (equal)
return q.FirstOrDefault();
}
}
}
}
| |
#region License
/*
* All content copyright Marko Lahma, unless otherwise indicated. 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.
*
*/
#endregion
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Quartz.Core;
using Quartz.Impl.AdoJobStore;
using Quartz.Impl.AdoJobStore.Common;
using Quartz.Impl.Matchers;
using Quartz.Logging;
using Quartz.Simpl;
using Quartz.Spi;
using Quartz.Util;
namespace Quartz.Impl
{
/// <summary>
/// An implementation of <see cref="ISchedulerFactory" /> that
/// does all of it's work of creating a <see cref="QuartzScheduler" /> instance
/// based on the contents of a properties file.
/// </summary>
/// <remarks>
/// <para>
/// By default a properties are loaded from App.config's quartz section.
/// If that fails, then the file is loaded "quartz.config". If file does not exist,
/// default configuration located (as a embedded resource) in Quartz.dll is loaded. If you
/// wish to use a file other than these defaults, you must define the system
/// property 'quartz.properties' to point to the file you want.
/// </para>
/// <para>
/// See the sample properties that are distributed with Quartz for
/// information about the various settings available within the file.
/// </para>
/// <para>
/// Alternatively, you can explicitly Initialize the factory by calling one of
/// the <see cref="Initialize()" /> methods before calling <see cref="GetScheduler(CancellationToken)" />.
/// </para>
/// <para>
/// Instances of the specified <see cref="IJobStore" />,
/// <see cref="IThreadPool" />, classes will be created
/// by name, and then any additional properties specified for them in the config
/// file will be set on the instance by calling an equivalent 'set' method. For
/// example if the properties file contains the property 'quartz.jobStore.
/// myProp = 10' then after the JobStore class has been instantiated, the property
/// 'MyProp' will be set with the value. Type conversion to primitive CLR types
/// (int, long, float, double, boolean, enum and string) are performed before calling
/// the property's setter method.
/// </para>
/// </remarks>
/// <author>James House</author>
/// <author>Anthony Eden</author>
/// <author>Mohammad Rezaei</author>
/// <author>Marko Lahma (.NET)</author>
public class StdSchedulerFactory : ISchedulerFactory
{
private const string ConfigurationKeyPrefix = "quartz.";
private const string ConfigurationKeyPrefixServer = "quartz.server";
public const string ConfigurationSectionName = "quartz";
public const string PropertiesFile = "quartz.config";
public const string PropertySchedulerInstanceName = "quartz.scheduler.instanceName";
public const string PropertySchedulerInstanceId = "quartz.scheduler.instanceId";
public const string PropertySchedulerInstanceIdGeneratorPrefix = "quartz.scheduler.instanceIdGenerator";
public const string PropertySchedulerInstanceIdGeneratorType = PropertySchedulerInstanceIdGeneratorPrefix + ".type";
public const string PropertySchedulerThreadName = "quartz.scheduler.threadName";
public const string PropertySchedulerBatchTimeWindow = "quartz.scheduler.batchTriggerAcquisitionFireAheadTimeWindow";
public const string PropertySchedulerMaxBatchSize = "quartz.scheduler.batchTriggerAcquisitionMaxCount";
public const string PropertySchedulerExporterPrefix = "quartz.scheduler.exporter";
public const string PropertySchedulerExporterType = PropertySchedulerExporterPrefix + ".type";
public const string PropertySchedulerProxy = "quartz.scheduler.proxy";
public const string PropertySchedulerProxyType = "quartz.scheduler.proxy.type";
public const string PropertySchedulerIdleWaitTime = "quartz.scheduler.idleWaitTime";
public const string PropertySchedulerDbFailureRetryInterval = "quartz.scheduler.dbFailureRetryInterval";
public const string PropertySchedulerMakeSchedulerThreadDaemon = "quartz.scheduler.makeSchedulerThreadDaemon";
public const string PropertySchedulerTypeLoadHelperType = "quartz.scheduler.typeLoadHelper.type";
public const string PropertySchedulerJobFactoryType = "quartz.scheduler.jobFactory.type";
public const string PropertySchedulerJobFactoryPrefix = "quartz.scheduler.jobFactory";
public const string PropertySchedulerInterruptJobsOnShutdown = "quartz.scheduler.interruptJobsOnShutdown";
public const string PropertySchedulerInterruptJobsOnShutdownWithWait = "quartz.scheduler.interruptJobsOnShutdownWithWait";
public const string PropertySchedulerContextPrefix = "quartz.context.key";
public const string PropertyThreadPoolPrefix = "quartz.threadPool";
public const string PropertyThreadPoolType = "quartz.threadPool.type";
public const string PropertyJobStorePrefix = "quartz.jobStore";
public const string PropertyJobStoreLockHandlerPrefix = PropertyJobStorePrefix + ".lockHandler";
public const string PropertyJobStoreLockHandlerType = PropertyJobStoreLockHandlerPrefix + ".type";
public const string PropertyTablePrefix = "tablePrefix";
public const string PropertySchedulerName = "schedName";
public const string PropertyJobStoreType = "quartz.jobStore.type";
public const string PropertyDataSourcePrefix = "quartz.dataSource";
public const string PropertyDbProvider = "quartz.dbprovider";
public const string PropertyDbProviderType = "connectionProvider.type";
public const string PropertyDataSourceProvider = "provider";
public const string PropertyDataSourceConnectionString = "connectionString";
public const string PropertyDataSourceConnectionStringName = "connectionStringName";
public const string PropertyPluginPrefix = "quartz.plugin";
public const string PropertyPluginType = "type";
public const string PropertyJobListenerPrefix = "quartz.jobListener";
public const string PropertyTriggerListenerPrefix = "quartz.triggerListener";
public const string PropertyListenerType = "type";
public const string DefaultInstanceId = "NON_CLUSTERED";
public const string PropertyCheckConfiguration = "quartz.checkConfiguration";
public const string AutoGenerateInstanceId = "AUTO";
public const string PropertyThreadExecutor = "quartz.threadExecutor";
public const string PropertyThreadExecutorType = "quartz.threadExecutor.type";
public const string PropertyObjectSerializer = "quartz.serializer";
public const string SystemPropertyAsInstanceId = "SYS_PROP";
private SchedulerException? initException;
private PropertiesParser cfg = null!;
private ILog log = null!;
private string SchedulerName
{
// ReSharper disable once ArrangeAccessorOwnerBody
get { return cfg.GetStringProperty(PropertySchedulerInstanceName, "QuartzScheduler")!; }
}
/// <summary>
/// Returns a handle to the default Scheduler, creating it if it does not
/// yet exist.
/// </summary>
/// <seealso cref="Initialize()">
/// </seealso>
public static Task<IScheduler> GetDefaultScheduler(
CancellationToken cancellationToken = default)
{
StdSchedulerFactory fact = new StdSchedulerFactory();
return fact.GetScheduler(cancellationToken);
}
/// <summary> <para>
/// Returns a handle to all known Schedulers (made by any
/// StdSchedulerFactory instance.).
/// </para>
/// </summary>
public virtual Task<IReadOnlyList<IScheduler>> GetAllSchedulers(
CancellationToken cancellationToken = default)
{
return SchedulerRepository.Instance.LookupAll(cancellationToken);
}
/// <summary>
/// Initializes a new instance of the <see cref="StdSchedulerFactory"/> class.
/// </summary>
public StdSchedulerFactory()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="StdSchedulerFactory"/> class.
/// </summary>
/// <param name="props">The props.</param>
public StdSchedulerFactory(NameValueCollection props)
{
Initialize(props);
}
/// <summary>
/// Initialize the <see cref="ISchedulerFactory" />.
/// </summary>
/// <remarks>
/// By default a properties file named "quartz.config" is loaded from
/// the 'current working directory'. If that fails, then the
/// "quartz.config" file located (as an embedded resource) in the Quartz.NET
/// assembly is loaded. If you wish to use a file other than these defaults,
/// you must define the system property 'quartz.properties' to point to
/// the file you want.
/// </remarks>
public virtual void Initialize()
{
// short-circuit if already initialized
if (cfg != null)
{
return;
}
if (initException != null)
{
throw initException;
}
log ??= LogProvider.GetLogger(typeof(StdSchedulerFactory));
var props = InitializeProperties(log, throwOnProblem: true);
Initialize(OverrideWithSysProps(props ?? new NameValueCollection()));
}
internal static NameValueCollection? InitializeProperties(ILog logger, bool throwOnProblem)
{
var props = Util.Configuration.GetSection(ConfigurationSectionName);
var requestedFile = QuartzEnvironment.GetEnvironmentVariable(PropertiesFile);
string propFileName = !string.IsNullOrWhiteSpace(requestedFile) ? requestedFile : "~/quartz.config";
// check for specials
propFileName = FileUtil.ResolveFile(propFileName) ?? "quartz.config";
if (props == null && File.Exists(propFileName))
{
// file system
try
{
PropertiesParser pp = PropertiesParser.ReadFromFileResource(propFileName!);
props = pp.UnderlyingProperties;
logger?.Info($"Quartz.NET properties loaded from configuration file '{propFileName}'");
}
catch (Exception ex)
{
logger?.ErrorException("Could not load properties for Quartz from file {0}: {1}".FormatInvariant(propFileName!, ex.Message), ex);
}
}
if (props == null)
{
// read from assembly
try
{
PropertiesParser pp = PropertiesParser.ReadFromEmbeddedAssemblyResource("Quartz.quartz.config");
props = pp.UnderlyingProperties;
logger?.Info("Default Quartz.NET properties loaded from embedded resource file");
}
catch (Exception ex)
{
logger?.ErrorException("Could not load default properties for Quartz from Quartz assembly: {0}".FormatInvariant(ex.Message), ex);
}
}
if (props == null && throwOnProblem)
{
throw new SchedulerConfigException(
@"Could not find <quartz> configuration section from your application config or load default configuration from assembly.
Please add configuration to your application config file to correctly initialize Quartz.");
}
return props;
}
/// <summary>
/// Creates a new name value collection and overrides its values
/// with system values (environment variables).
/// </summary>
/// <param name="props">The base properties to override.</param>
/// <returns>A new NameValueCollection instance.</returns>
private static NameValueCollection OverrideWithSysProps(NameValueCollection props)
{
NameValueCollection retValue = new NameValueCollection(props);
var vars = QuartzEnvironment.GetEnvironmentVariables();
foreach (string key in vars.Keys)
{
retValue.Set(key, vars[key]);
}
return retValue;
}
/// <summary>
/// Initialize the <see cref="ISchedulerFactory" /> with
/// the contents of the given key value collection object.
/// </summary>
public virtual void Initialize(NameValueCollection props)
{
cfg = new PropertiesParser(props);
ValidateConfiguration();
}
protected virtual void ValidateConfiguration()
{
if (!cfg.GetBooleanProperty(PropertyCheckConfiguration, true))
{
// should not validate
return;
}
// determine currently supported configuration keys via reflection
List<string> supportedKeys = new List<string>();
List<FieldInfo> fields = new List<FieldInfo>(GetType().GetFields(BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy));
// choose constant string fields
fields = fields.FindAll(field => field.FieldType == typeof(string));
// read value from each field
foreach (FieldInfo field in fields)
{
var value = (string?) field.GetValue(null);
if (value != null && value.StartsWith(ConfigurationKeyPrefix) && value != ConfigurationKeyPrefix)
{
supportedKeys.Add(value);
}
}
// now check against allowed
foreach (var configurationKey in cfg.UnderlyingProperties.AllKeys)
{
if (configurationKey is null
|| !configurationKey.StartsWith(ConfigurationKeyPrefix)
|| configurationKey.StartsWith(ConfigurationKeyPrefixServer))
{
// don't bother if truly unknown property
continue;
}
var isMatch = false;
foreach (var supportedKey in supportedKeys)
{
if (CultureInfo.InvariantCulture.CompareInfo.IsPrefix(configurationKey, supportedKey, CompareOptions.None))
{
isMatch = true;
break;
}
}
if (!isMatch)
{
throw new SchedulerConfigException("Unknown configuration property '" + configurationKey + "'");
}
}
}
/// <summary> </summary>
private async Task<IScheduler> Instantiate()
{
if (cfg == null)
{
Initialize();
}
if (initException != null)
{
throw initException;
}
log ??= LogProvider.GetLogger(typeof(StdSchedulerFactory));
ISchedulerExporter? exporter = null;
IJobStore js;
IThreadPool tp;
QuartzScheduler? qs = null;
IDbConnectionManager? dbMgr = null;
Type? instanceIdGeneratorType = null;
NameValueCollection tProps;
bool autoId = false;
TimeSpan idleWaitTime = TimeSpan.Zero;
TimeSpan dbFailureRetry = TimeSpan.FromSeconds(15);
SchedulerRepository schedRep = SchedulerRepository.Instance;
// Get Scheduler Properties
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
string schedName = cfg!.GetStringProperty(PropertySchedulerInstanceName, "QuartzScheduler")!;
string threadName = cfg.GetStringProperty(PropertySchedulerThreadName, "{0}_QuartzSchedulerThread".FormatInvariant(schedName))!;
var schedInstId = cfg.GetStringProperty(PropertySchedulerInstanceId, DefaultInstanceId)!;
if (schedInstId.Equals(AutoGenerateInstanceId))
{
autoId = true;
instanceIdGeneratorType = LoadType(cfg.GetStringProperty(PropertySchedulerInstanceIdGeneratorType)) ?? typeof(SimpleInstanceIdGenerator);
}
else if (schedInstId.Equals(SystemPropertyAsInstanceId))
{
autoId = true;
instanceIdGeneratorType = typeof(SystemPropertyInstanceIdGenerator);
}
Type? typeLoadHelperType = LoadType(cfg.GetStringProperty(PropertySchedulerTypeLoadHelperType));
idleWaitTime = cfg.GetTimeSpanProperty(PropertySchedulerIdleWaitTime, idleWaitTime);
if (idleWaitTime > TimeSpan.Zero && idleWaitTime < TimeSpan.FromMilliseconds(1000))
{
throw new SchedulerException("quartz.scheduler.idleWaitTime of less than 1000ms is not legal.");
}
dbFailureRetry = cfg.GetTimeSpanProperty(PropertySchedulerDbFailureRetryInterval, dbFailureRetry);
if (dbFailureRetry < TimeSpan.Zero)
{
throw new SchedulerException(PropertySchedulerDbFailureRetryInterval + " of less than 0 ms is not legal.");
}
bool makeSchedulerThreadDaemon = cfg.GetBooleanProperty(PropertySchedulerMakeSchedulerThreadDaemon);
long batchTimeWindow = cfg.GetLongProperty(PropertySchedulerBatchTimeWindow, 0L);
int maxBatchSize = cfg.GetIntProperty(PropertySchedulerMaxBatchSize, 1);
bool interruptJobsOnShutdown = cfg.GetBooleanProperty(PropertySchedulerInterruptJobsOnShutdown, false);
bool interruptJobsOnShutdownWithWait = cfg.GetBooleanProperty(PropertySchedulerInterruptJobsOnShutdownWithWait, false);
var schedCtxtProps = cfg.GetPropertyGroup(PropertySchedulerContextPrefix, true);
var proxyScheduler = cfg.GetBooleanProperty(PropertySchedulerProxy, false);
// Create type load helper
ITypeLoadHelper loadHelper;
try
{
loadHelper = InstantiateType<ITypeLoadHelper>(typeLoadHelperType ?? typeof(SimpleTypeLoadHelper));
}
catch (Exception e)
{
throw new SchedulerConfigException("Unable to instantiate type load helper: {0}".FormatInvariant(e.Message), e);
}
loadHelper.Initialize();
// If Proxying to remote scheduler, short-circuit here...
// ~~~~~~~~~~~~~~~~~~
if (proxyScheduler)
{
if (autoId)
{
schedInstId = DefaultInstanceId;
}
var proxyType = loadHelper.LoadType(cfg.GetStringProperty(PropertySchedulerProxyType)) ?? typeof(RemotingSchedulerProxyFactory);
IRemotableSchedulerProxyFactory factory;
try
{
factory = InstantiateType<IRemotableSchedulerProxyFactory>(proxyType);
ObjectUtils.SetObjectProperties(factory, cfg.GetPropertyGroup(PropertySchedulerProxy, true));
}
catch (Exception e)
{
initException = new SchedulerException("Remotable proxy factory '{0}' could not be instantiated.".FormatInvariant(proxyType), e);
throw initException;
}
string uid = QuartzSchedulerResources.GetUniqueIdentifier(schedName, schedInstId);
RemoteScheduler remoteScheduler = new RemoteScheduler(uid, factory);
schedRep.Bind(remoteScheduler);
return remoteScheduler;
}
Type? jobFactoryType = LoadType(cfg.GetStringProperty(PropertySchedulerJobFactoryType));
IJobFactory? jobFactory = null;
if (jobFactoryType != null)
{
try
{
jobFactory = InstantiateType<IJobFactory>(jobFactoryType);
}
catch (Exception e)
{
throw new SchedulerConfigException("Unable to Instantiate JobFactory: {0}".FormatInvariant(e.Message), e);
}
tProps = cfg.GetPropertyGroup(PropertySchedulerJobFactoryPrefix, true);
try
{
ObjectUtils.SetObjectProperties(jobFactory, tProps);
}
catch (Exception e)
{
initException = new SchedulerException("JobFactory of type '{0}' props could not be configured.".FormatInvariant(jobFactoryType), e);
throw initException;
}
}
IInstanceIdGenerator? instanceIdGenerator = null;
if (instanceIdGeneratorType != null)
{
try
{
instanceIdGenerator = InstantiateType<IInstanceIdGenerator>(instanceIdGeneratorType);
}
catch (Exception e)
{
throw new SchedulerConfigException("Unable to Instantiate InstanceIdGenerator: {0}".FormatInvariant(e.Message), e);
}
tProps = cfg.GetPropertyGroup(PropertySchedulerInstanceIdGeneratorPrefix, true);
try
{
ObjectUtils.SetObjectProperties(instanceIdGenerator, tProps);
}
catch (Exception e)
{
initException = new SchedulerException("InstanceIdGenerator of type '{0}' props could not be configured.".FormatInvariant(instanceIdGeneratorType), e);
throw initException;
}
}
// Get ThreadPool Properties
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
var threadPoolTypeString = cfg.GetStringProperty(PropertyThreadPoolType).NullSafeTrim();
if (threadPoolTypeString != null
&& threadPoolTypeString.StartsWith("Quartz.Simpl.SimpleThreadPool", StringComparison.OrdinalIgnoreCase))
{
// default to use as synonym for now
threadPoolTypeString = typeof(DefaultThreadPool).AssemblyQualifiedNameWithoutVersion();
}
Type tpType = loadHelper.LoadType(threadPoolTypeString) ?? typeof(DefaultThreadPool);
try
{
tp = InstantiateType<IThreadPool>(tpType);
}
catch (Exception e)
{
initException = new SchedulerException("ThreadPool type '{0}' could not be instantiated.".FormatInvariant(tpType), e);
throw initException;
}
tProps = cfg.GetPropertyGroup(PropertyThreadPoolPrefix, true);
try
{
ObjectUtils.SetObjectProperties(tp, tProps);
}
catch (Exception e)
{
initException = new SchedulerException("ThreadPool type '{0}' props could not be configured.".FormatInvariant(tpType), e);
throw initException;
}
// Set up any DataSources
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
var dsNames = cfg.GetPropertyGroups(PropertyDataSourcePrefix);
foreach (string dataSourceName in dsNames)
{
string datasourceKey = "{0}.{1}".FormatInvariant(PropertyDataSourcePrefix, dataSourceName);
NameValueCollection propertyGroup = cfg.GetPropertyGroup(datasourceKey, true);
PropertiesParser pp = new PropertiesParser(propertyGroup);
Type? cpType = loadHelper.LoadType(pp.GetStringProperty(PropertyDbProviderType, null));
// custom connectionProvider...
if (cpType != null)
{
IDbProvider cp;
try
{
cp = InstantiateType<IDbProvider>(cpType);
}
catch (Exception e)
{
initException = new SchedulerException("ConnectionProvider of type '{0}' could not be instantiated.".FormatInvariant(cpType), e);
throw initException;
}
try
{
// remove the type name, so it isn't attempted to be set
pp.UnderlyingProperties.Remove(PropertyDbProviderType);
ObjectUtils.SetObjectProperties(cp, pp.UnderlyingProperties);
cp.Initialize();
}
catch (Exception e)
{
initException = new SchedulerException("ConnectionProvider type '{0}' props could not be configured.".FormatInvariant(cpType), e);
throw initException;
}
dbMgr = DBConnectionManager.Instance;
dbMgr.AddConnectionProvider(dataSourceName, cp);
}
else
{
var dsProvider = pp.GetStringProperty(PropertyDataSourceProvider, null);
var dsConnectionString = pp.GetStringProperty(PropertyDataSourceConnectionString, null);
var dsConnectionStringName = pp.GetStringProperty(PropertyDataSourceConnectionStringName, null);
if (dsConnectionString == null && !string.IsNullOrEmpty(dsConnectionStringName))
{
var connectionStringSettings = ConfigurationManager.ConnectionStrings[dsConnectionStringName];
if (connectionStringSettings == null)
{
initException = new SchedulerException("Named connection string '{0}' not found for DataSource: {1}".FormatInvariant(dsConnectionStringName, dataSourceName));
throw initException;
}
dsConnectionString = connectionStringSettings.ConnectionString;
}
if (dsProvider == null)
{
initException = new SchedulerException("Provider not specified for DataSource: {0}".FormatInvariant(dataSourceName));
throw initException;
}
if (dsConnectionString == null)
{
initException = new SchedulerException("Connection string not specified for DataSource: {0}".FormatInvariant(dataSourceName));
throw initException;
}
try
{
DbProvider dbp = new DbProvider(dsProvider, dsConnectionString);
dbp.Initialize();
dbMgr = DBConnectionManager.Instance;
dbMgr.AddConnectionProvider(dataSourceName, dbp);
}
catch (Exception exception)
{
initException = new SchedulerException("Could not Initialize DataSource: {0}".FormatInvariant(dataSourceName), exception);
throw initException;
}
}
}
// Get JobStore Properties
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Type? jsType = loadHelper.LoadType(cfg.GetStringProperty(PropertyJobStoreType));
try
{
js = InstantiateType<IJobStore>(jsType ?? typeof(RAMJobStore));
}
catch (Exception e)
{
initException = new SchedulerException("JobStore of type '{0}' could not be instantiated.".FormatInvariant(jsType), e);
throw initException;
}
// Get object serializer properties
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
IObjectSerializer? objectSerializer = null;
string serializerTypeKey = "quartz.serializer.type";
string? objectSerializerType = cfg.GetStringProperty(serializerTypeKey);
if (objectSerializerType != null)
{
// some aliases
if (objectSerializerType.Equals("json", StringComparison.OrdinalIgnoreCase))
{
objectSerializerType = "Quartz.Simpl.JsonObjectSerializer, Quartz.Serialization.Json";
}
if (objectSerializerType.Equals("binary", StringComparison.OrdinalIgnoreCase))
{
objectSerializerType = typeof(BinaryObjectSerializer).AssemblyQualifiedNameWithoutVersion();
}
tProps = cfg.GetPropertyGroup(PropertyObjectSerializer, true);
try
{
objectSerializer = InstantiateType<IObjectSerializer>(loadHelper.LoadType(objectSerializerType));
log.Info("Using object serializer: " + objectSerializerType);
ObjectUtils.SetObjectProperties(objectSerializer, tProps);
objectSerializer.Initialize();
}
catch (Exception e)
{
initException = new SchedulerException("Object serializer type '" + objectSerializerType + "' could not be instantiated.", e);
throw initException;
}
}
else if (js.GetType() != typeof(RAMJobStore))
{
// when we know for sure that job store does not need serialization we can be a bit more relaxed
// otherwise it's an error to not define the serialization strategy
initException = new SchedulerException($"You must define object serializer using configuration key '{serializerTypeKey}' when using other than RAMJobStore. " +
"Out of the box supported values are 'json' and 'binary'. JSON doesn't suffer from versioning as much as binary serialization but you cannot use it if you already have binary serialized data.");
throw initException;
}
SchedulerDetailsSetter.SetDetails(js, schedName, schedInstId);
tProps = cfg.GetPropertyGroup(PropertyJobStorePrefix, true, new[] {PropertyJobStoreLockHandlerPrefix});
try
{
ObjectUtils.SetObjectProperties(js, tProps);
}
catch (Exception e)
{
initException = new SchedulerException("JobStore type '{0}' props could not be configured.".FormatInvariant(jsType), e);
throw initException;
}
if (js is JobStoreSupport jobStoreSupport)
{
// Install custom lock handler (Semaphore)
var lockHandlerType = loadHelper.LoadType(cfg.GetStringProperty(PropertyJobStoreLockHandlerType));
if (lockHandlerType != null)
{
try
{
ISemaphore lockHandler;
var cWithDbProvider = lockHandlerType.GetConstructor(new[] {typeof(DbProvider)});
if (cWithDbProvider != null)
{
// takes db provider
IDbProvider dbProvider = DBConnectionManager.Instance.GetDbProvider(jobStoreSupport.DataSource);
lockHandler = (ISemaphore) cWithDbProvider.Invoke(new object[] {dbProvider});
}
else
{
lockHandler = InstantiateType<ISemaphore>(lockHandlerType);
}
tProps = cfg.GetPropertyGroup(PropertyJobStoreLockHandlerPrefix, true);
// If this lock handler requires the table prefix, add it to its properties.
if (lockHandler is ITablePrefixAware)
{
tProps[PropertyTablePrefix] = jobStoreSupport.TablePrefix;
tProps[PropertySchedulerName] = schedName;
}
try
{
ObjectUtils.SetObjectProperties(lockHandler, tProps);
}
catch (Exception e)
{
initException = new SchedulerException("JobStore LockHandler type '{0}' props could not be configured.".FormatInvariant(lockHandlerType), e);
throw initException;
}
jobStoreSupport.LockHandler = lockHandler;
log.Info("Using custom data access locking (synchronization): " + lockHandlerType);
}
catch (Exception e)
{
initException = new SchedulerException("JobStore LockHandler type '{0}' could not be instantiated.".FormatInvariant(lockHandlerType), e);
throw initException;
}
}
}
// Set up any SchedulerPlugins
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
var pluginNames = cfg.GetPropertyGroups(PropertyPluginPrefix);
ISchedulerPlugin[] plugins = new ISchedulerPlugin[pluginNames.Count];
for (int i = 0; i < pluginNames.Count; i++)
{
var pp = cfg.GetPropertyGroup("{0}.{1}".FormatInvariant(PropertyPluginPrefix, pluginNames[i]), true);
var plugInType = pp[PropertyPluginType];
if (plugInType == null)
{
initException = new SchedulerException("SchedulerPlugin type not specified for plugin '{0}'".FormatInvariant(pluginNames[i]));
throw initException;
}
ISchedulerPlugin plugin;
try
{
plugin = InstantiateType<ISchedulerPlugin>(LoadType(plugInType));
}
catch (Exception e)
{
initException = new SchedulerException("SchedulerPlugin of type '{0}' could not be instantiated.".FormatInvariant(plugInType), e);
throw initException;
}
try
{
ObjectUtils.SetObjectProperties(plugin, pp);
}
catch (Exception e)
{
initException = new SchedulerException("JobStore SchedulerPlugin '{0}' props could not be configured.".FormatInvariant(plugInType), e);
throw initException;
}
plugins[i] = plugin;
}
// Set up any JobListeners
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
var jobListenerNames = cfg.GetPropertyGroups(PropertyJobListenerPrefix);
IJobListener[] jobListeners = new IJobListener[jobListenerNames.Count];
for (int i = 0; i < jobListenerNames.Count; i++)
{
var lp = cfg.GetPropertyGroup("{0}.{1}".FormatInvariant(PropertyJobListenerPrefix, jobListenerNames[i]), true);
var listenerType = lp[PropertyListenerType];
if (listenerType == null)
{
initException = new SchedulerException("JobListener type not specified for listener '{0}'".FormatInvariant(jobListenerNames[i]));
throw initException;
}
IJobListener listener;
try
{
listener = InstantiateType<IJobListener>(loadHelper.LoadType(listenerType));
}
catch (Exception e)
{
initException = new SchedulerException("JobListener of type '{0}' could not be instantiated.".FormatInvariant(listenerType), e);
throw initException;
}
try
{
var nameProperty = listener.GetType().GetProperty("Name", BindingFlags.Public | BindingFlags.Instance);
if (nameProperty != null && nameProperty.CanWrite)
{
nameProperty.GetSetMethod()!.Invoke(listener, new object[] {jobListenerNames[i]});
}
ObjectUtils.SetObjectProperties(listener, lp);
}
catch (Exception e)
{
initException = new SchedulerException("JobListener '{0}' props could not be configured.".FormatInvariant(listenerType), e);
throw initException;
}
jobListeners[i] = listener;
}
// Set up any TriggerListeners
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
var triggerListenerNames = cfg.GetPropertyGroups(PropertyTriggerListenerPrefix);
ITriggerListener[] triggerListeners = new ITriggerListener[triggerListenerNames.Count];
for (int i = 0; i < triggerListenerNames.Count; i++)
{
var lp = cfg.GetPropertyGroup("{0}.{1}".FormatInvariant(PropertyTriggerListenerPrefix, triggerListenerNames[i]), true);
var listenerType = lp[PropertyListenerType];
if (listenerType == null)
{
initException = new SchedulerException("TriggerListener type not specified for listener '{0}'".FormatInvariant(triggerListenerNames[i]));
throw initException;
}
ITriggerListener listener;
try
{
listener = InstantiateType<ITriggerListener>(loadHelper.LoadType(listenerType));
}
catch (Exception e)
{
initException = new SchedulerException("TriggerListener of type '{0}' could not be instantiated.".FormatInvariant(listenerType), e);
throw initException;
}
try
{
var nameProperty = listener.GetType().GetProperty("Name", BindingFlags.Public | BindingFlags.Instance);
if (nameProperty != null && nameProperty.CanWrite)
{
nameProperty.GetSetMethod()!.Invoke(listener, new object[] {triggerListenerNames[i]});
}
ObjectUtils.SetObjectProperties(listener, lp);
}
catch (Exception e)
{
initException = new SchedulerException("TriggerListener '{0}' props could not be configured.".FormatInvariant(listenerType), e);
throw initException;
}
triggerListeners[i] = listener;
}
// Get exporter
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
var exporterType = cfg.GetStringProperty(PropertySchedulerExporterType, null);
#if !REMOTING
if (exporterType != null && exporterType.StartsWith("Quartz.Simpl.RemotingSchedulerExporter"))
{
log.Warn("RemotingSchedulerExporter configuration was ignored as Remoting is not supported");
exporterType = null;
}
#endif
if (exporterType != null)
{
try
{
exporter = InstantiateType<ISchedulerExporter>(loadHelper.LoadType(exporterType));
}
catch (Exception e)
{
initException = new SchedulerException("Scheduler exporter of type '{0}' could not be instantiated.".FormatInvariant(exporterType), e);
throw initException;
}
tProps = cfg.GetPropertyGroup(PropertySchedulerExporterPrefix, true);
try
{
ObjectUtils.SetObjectProperties(exporter, tProps);
}
catch (Exception e)
{
initException = new SchedulerException("Scheduler exporter type '{0}' props could not be configured.".FormatInvariant(exporterType), e);
throw initException;
}
}
bool tpInited = false;
bool qsInited = false;
// Fire everything up
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
try
{
IJobRunShellFactory jrsf = new StdJobRunShellFactory();
if (autoId)
{
try
{
schedInstId = DefaultInstanceId;
if (js.Clustered)
{
schedInstId = (await instanceIdGenerator!.GenerateInstanceId().ConfigureAwait(false))!;
}
}
catch (Exception e)
{
log.ErrorException("Couldn't generate instance Id!", e);
throw new InvalidOperationException("Cannot run without an instance id.");
}
}
if (js is JobStoreSupport js2)
{
js2.DbRetryInterval = dbFailureRetry;
js2.ObjectSerializer = objectSerializer;
}
QuartzSchedulerResources rsrcs = new QuartzSchedulerResources();
rsrcs.Name = schedName;
rsrcs.ThreadName = threadName;
rsrcs.InstanceId = schedInstId!;
rsrcs.JobRunShellFactory = jrsf;
rsrcs.MakeSchedulerThreadDaemon = makeSchedulerThreadDaemon;
rsrcs.BatchTimeWindow = TimeSpan.FromMilliseconds(batchTimeWindow);
rsrcs.MaxBatchSize = maxBatchSize;
rsrcs.InterruptJobsOnShutdown = interruptJobsOnShutdown;
rsrcs.InterruptJobsOnShutdownWithWait = interruptJobsOnShutdownWithWait;
rsrcs.SchedulerExporter = exporter;
SchedulerDetailsSetter.SetDetails(tp, schedName, schedInstId!);
rsrcs.ThreadPool = tp;
tp.Initialize();
tpInited = true;
rsrcs.JobStore = js;
// add plugins
foreach (ISchedulerPlugin plugin in plugins)
{
rsrcs.AddSchedulerPlugin(plugin);
}
qs = new QuartzScheduler(rsrcs, idleWaitTime);
qsInited = true;
// Create Scheduler ref...
IScheduler sched = Instantiate(rsrcs, qs);
// set job factory if specified
if (jobFactory != null)
{
qs.JobFactory = jobFactory;
}
// Initialize plugins now that we have a Scheduler instance.
for (int i = 0; i < plugins.Length; i++)
{
await plugins[i].Initialize(pluginNames[i], sched).ConfigureAwait(false);
}
// add listeners
foreach (IJobListener listener in jobListeners)
{
qs.ListenerManager.AddJobListener(listener, EverythingMatcher<JobKey>.AllJobs());
}
foreach (ITriggerListener listener in triggerListeners)
{
qs.ListenerManager.AddTriggerListener(listener, EverythingMatcher<TriggerKey>.AllTriggers());
}
// set scheduler context data...
foreach (var key in schedCtxtProps)
{
var val = schedCtxtProps.Get((string) key!);
sched.Context.Put((string) key!, val);
}
// fire up job store, and runshell factory
js.InstanceId = schedInstId!;
js.InstanceName = schedName;
js.ThreadPoolSize = tp.PoolSize;
await js.Initialize(loadHelper, qs.SchedulerSignaler).ConfigureAwait(false);
jrsf.Initialize(sched);
qs.Initialize();
log.Info("Quartz scheduler '{0}' initialized".FormatInvariant(sched.SchedulerName));
log.Info("Quartz scheduler version: {0}".FormatInvariant(qs.Version));
// prevents the repository from being garbage collected
qs.AddNoGCObject(schedRep);
// prevents the db manager from being garbage collected
if (dbMgr != null)
{
qs.AddNoGCObject(dbMgr);
}
schedRep.Bind(sched);
return sched;
}
catch (SchedulerException)
{
await ShutdownFromInstantiateException(tp, qs, tpInited, qsInited).ConfigureAwait(false);
throw;
}
catch
{
await ShutdownFromInstantiateException(tp, qs, tpInited, qsInited).ConfigureAwait(false);
throw;
}
}
protected virtual T InstantiateType<T>(Type? implementationType)
{
return ObjectUtils.InstantiateType<T>(implementationType);
}
private async Task ShutdownFromInstantiateException(IThreadPool? tp, QuartzScheduler? qs, bool tpInited, bool qsInited)
{
try
{
if (qsInited)
{
await qs!.Shutdown(false).ConfigureAwait(false);
}
else if (tpInited)
{
tp!.Shutdown(false);
}
}
catch (Exception e)
{
log.ErrorException("Got another exception while shutting down after instantiation exception", e);
}
}
protected virtual IScheduler Instantiate(QuartzSchedulerResources rsrcs, QuartzScheduler qs)
{
IScheduler sched = new StdScheduler(qs);
return sched;
}
/// <summary>
/// Needed while loadhelper is not constructed.
/// </summary>
/// <param name="typeName"></param>
/// <returns></returns>
protected virtual Type? LoadType(string? typeName)
{
if (string.IsNullOrEmpty(typeName))
{
return null;
}
return Type.GetType(typeName, true);
}
/// <summary>
/// Returns a handle to the Scheduler produced by this factory.
/// </summary>
/// <remarks>
/// If one of the <see cref="Initialize()" /> methods has not be previously
/// called, then the default (no-arg) <see cref="Initialize()" /> method
/// will be called by this method.
/// </remarks>
public virtual async Task<IScheduler> GetScheduler(CancellationToken cancellationToken = default)
{
if (cfg == null)
{
Initialize();
}
SchedulerRepository schedRep = SchedulerRepository.Instance;
IScheduler? sched = await schedRep.Lookup(SchedulerName, cancellationToken).ConfigureAwait(false);
if (sched != null)
{
if (sched.IsShutdown)
{
schedRep.Remove(SchedulerName);
}
else
{
return sched;
}
}
sched = await Instantiate().ConfigureAwait(false);
return sched!;
}
/// <summary> <para>
/// Returns a handle to the Scheduler with the given name, if it exists (if
/// it has already been instantiated).
/// </para>
/// </summary>
public virtual Task<IScheduler?> GetScheduler(string schedName,
CancellationToken cancellationToken = default)
{
return SchedulerRepository.Instance.Lookup(schedName, cancellationToken);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using ProtocolFamily = System.Net.Internals.ProtocolFamily;
namespace System.Net
{
internal static class NameResolutionPal
{
//
// used by GetHostName() to preallocate a buffer for the call to gethostname.
//
private const int HostNameBufferLength = 256;
private static bool s_initialized;
private static readonly object s_initializedLock = new object();
/*++
Routine Description:
Takes a native pointer (expressed as an int) to a hostent structure,
and converts the information in their to an IPHostEntry class. This
involves walking through an array of native pointers, and a temporary
ArrayList object is used in doing this.
Arguments:
nativePointer - Native pointer to hostent structure.
Return Value:
An IPHostEntry structure.
--*/
private static IPHostEntry NativeToHostEntry(IntPtr nativePointer)
{
//
// marshal pointer to struct
//
hostent Host = Marshal.PtrToStructure<hostent>(nativePointer);
IPHostEntry HostEntry = new IPHostEntry();
if (Host.h_name != IntPtr.Zero)
{
HostEntry.HostName = Marshal.PtrToStringAnsi(Host.h_name);
if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"HostEntry.HostName: {HostEntry.HostName}");
}
// decode h_addr_list to ArrayList of IP addresses.
// The h_addr_list field is really a pointer to an array of pointers
// to IP addresses. Loop through the array, and while the pointer
// isn't NULL read the IP address, convert it to an IPAddress class,
// and add it to the list.
var TempIPAddressList = new List<IPAddress>();
int IPAddressToAdd;
string AliasToAdd;
IntPtr currentArrayElement;
//
// get the first pointer in the array
//
currentArrayElement = Host.h_addr_list;
nativePointer = Marshal.ReadIntPtr(currentArrayElement);
while (nativePointer != IntPtr.Zero)
{
//
// if it's not null it points to an IPAddress,
// read it...
//
IPAddressToAdd = Marshal.ReadInt32(nativePointer);
#if BIGENDIAN
// IP addresses from native code are always a byte array
// converted to int. We need to convert the address into
// a uniform integer value.
IPAddressToAdd = (int)(((uint)IPAddressToAdd << 24) |
(((uint)IPAddressToAdd & 0x0000FF00) << 8) |
(((uint)IPAddressToAdd >> 8) & 0x0000FF00) |
((uint)IPAddressToAdd >> 24));
#endif
if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"currentArrayElement:{currentArrayElement} nativePointer:{nativePointer} IPAddressToAdd:{IPAddressToAdd}");
//
// ...and add it to the list
//
TempIPAddressList.Add(new IPAddress((long)IPAddressToAdd & 0x0FFFFFFFF));
//
// now get the next pointer in the array and start over
//
currentArrayElement = IntPtrHelper.Add(currentArrayElement, IntPtr.Size);
nativePointer = Marshal.ReadIntPtr(currentArrayElement);
}
HostEntry.AddressList = TempIPAddressList.ToArray();
//
// Now do the same thing for the aliases.
//
var TempAliasList = new List<string>();
currentArrayElement = Host.h_aliases;
nativePointer = Marshal.ReadIntPtr(currentArrayElement);
while (nativePointer != IntPtr.Zero)
{
if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"currentArrayElement:{currentArrayElement} nativePointer:{nativePointer}");
//
// if it's not null it points to an Alias,
// read it...
//
AliasToAdd = Marshal.PtrToStringAnsi(nativePointer);
//
// ...and add it to the list
//
TempAliasList.Add(AliasToAdd);
//
// now get the next pointer in the array and start over
//
currentArrayElement = IntPtrHelper.Add(currentArrayElement, IntPtr.Size);
nativePointer = Marshal.ReadIntPtr(currentArrayElement);
}
HostEntry.Aliases = TempAliasList.ToArray();
return HostEntry;
} // NativeToHostEntry
public static IPHostEntry GetHostByName(string hostName)
{
//
// IPv6 disabled: use gethostbyname() to obtain DNS information.
//
IntPtr nativePointer =
Interop.Winsock.gethostbyname(
hostName);
if (nativePointer == IntPtr.Zero)
{
// Need to do this first since if we wait the last error code might be overwritten.
SocketException socketException = new SocketException();
IPAddress address;
if (IPAddress.TryParse(hostName, out address))
{
IPHostEntry ipHostEntry = NameResolutionUtilities.GetUnresolvedAnswer(address);
if (NetEventSource.IsEnabled) NetEventSource.Exit(null, ipHostEntry);
return ipHostEntry;
}
throw socketException;
}
return NativeToHostEntry(nativePointer);
}
public static IPHostEntry GetHostByAddr(IPAddress address)
{
// TODO #2891: Optimize this (or decide if this legacy code can be removed):
int addressAsInt = unchecked((int)address.GetAddress());
#if BIGENDIAN
// TODO #2891: above code needs testing for BIGENDIAN.
addressAsInt = (int)(((uint)addressAsInt << 24) | (((uint)addressAsInt & 0x0000FF00) << 8) |
(((uint)addressAsInt >> 8) & 0x0000FF00) | ((uint)addressAsInt >> 24));
#endif
IntPtr nativePointer =
Interop.Winsock.gethostbyaddr(
ref addressAsInt,
sizeof(int),
ProtocolFamily.InterNetwork);
if (nativePointer != IntPtr.Zero)
{
return NativeToHostEntry(nativePointer);
}
throw new SocketException();
}
public static unsafe SocketError TryGetAddrInfo(string name, out IPHostEntry hostinfo, out int nativeErrorCode)
{
//
// Use SocketException here to show operation not supported
// if, by some nefarious means, this method is called on an
// unsupported platform.
//
SafeFreeAddrInfo root = null;
var addresses = new List<IPAddress>();
string canonicalname = null;
AddressInfo hints = new AddressInfo();
hints.ai_flags = AddressInfoHints.AI_CANONNAME;
hints.ai_family = AddressFamily.Unspecified; // gets all address families
nativeErrorCode = 0;
//
// Use try / finally so we always get a shot at freeaddrinfo
//
try
{
SocketError errorCode = (SocketError)SafeFreeAddrInfo.GetAddrInfo(name, null, ref hints, out root);
if (errorCode != SocketError.Success)
{ // Should not throw, return mostly blank hostentry
hostinfo = NameResolutionUtilities.GetUnresolvedAnswer(name);
return errorCode;
}
AddressInfo* pAddressInfo = (AddressInfo*)root.DangerousGetHandle();
//
// Process the results
//
while (pAddressInfo != null)
{
SocketAddress sockaddr;
//
// Retrieve the canonical name for the host - only appears in the first AddressInfo
// entry in the returned array.
//
if (canonicalname == null && pAddressInfo->ai_canonname != null)
{
canonicalname = Marshal.PtrToStringUni((IntPtr)pAddressInfo->ai_canonname);
}
//
// Only process IPv4 or IPv6 Addresses. Note that it's unlikely that we'll
// ever get any other address families, but better to be safe than sorry.
// We also filter based on whether IPv6 is supported on the current
// platform / machine.
//
if ((pAddressInfo->ai_family == AddressFamily.InterNetwork) || // Never filter v4
(pAddressInfo->ai_family == AddressFamily.InterNetworkV6 && SocketProtocolSupportPal.OSSupportsIPv6))
{
sockaddr = new SocketAddress(pAddressInfo->ai_family, pAddressInfo->ai_addrlen);
//
// Push address data into the socket address buffer
//
for (int d = 0; d < pAddressInfo->ai_addrlen; d++)
{
sockaddr[d] = *(pAddressInfo->ai_addr + d);
}
//
// NOTE: We need an IPAddress now, the only way to create it from a
// SocketAddress is via IPEndPoint. This ought to be simpler.
//
if (pAddressInfo->ai_family == AddressFamily.InterNetwork)
{
addresses.Add(((IPEndPoint)IPEndPointStatics.Any.Create(sockaddr)).Address);
}
else
{
addresses.Add(((IPEndPoint)IPEndPointStatics.IPv6Any.Create(sockaddr)).Address);
}
}
//
// Next addressinfo entry
//
pAddressInfo = pAddressInfo->ai_next;
}
}
finally
{
if (root != null)
{
root.Dispose();
}
}
//
// Finally, put together the IPHostEntry
//
hostinfo = new IPHostEntry();
hostinfo.HostName = canonicalname != null ? canonicalname : name;
hostinfo.Aliases = Array.Empty<string>();
hostinfo.AddressList = addresses.ToArray();
return SocketError.Success;
}
public static string TryGetNameInfo(IPAddress addr, out SocketError errorCode, out int nativeErrorCode)
{
//
// Use SocketException here to show operation not supported
// if, by some nefarious means, this method is called on an
// unsupported platform.
//
SocketAddress address = (new IPEndPoint(addr, 0)).Serialize();
StringBuilder hostname = new StringBuilder(1025); // NI_MAXHOST
int flags = (int)Interop.Winsock.NameInfoFlags.NI_NAMEREQD;
nativeErrorCode = 0;
// TODO #2891: Remove the copying step to improve performance. This requires a change in the contracts.
byte[] addressBuffer = new byte[address.Size];
for (int i = 0; i < address.Size; i++)
{
addressBuffer[i] = address[i];
}
errorCode =
Interop.Winsock.GetNameInfoW(
addressBuffer,
address.Size,
hostname,
hostname.Capacity,
null, // We don't want a service name
0, // so no need for buffer or length
flags);
if (errorCode != SocketError.Success)
{
return null;
}
return hostname.ToString();
}
public static string GetHostName()
{
//
// note that we could cache the result ourselves since you
// wouldn't expect the hostname of the machine to change during
// execution, but this might still happen and we would want to
// react to that change.
//
StringBuilder sb = new StringBuilder(HostNameBufferLength);
SocketError errorCode =
Interop.Winsock.gethostname(
sb,
HostNameBufferLength);
//
// if the call failed throw a SocketException()
//
if (errorCode != SocketError.Success)
{
throw new SocketException();
}
return sb.ToString();
}
public static void EnsureSocketsAreInitialized()
{
if (!Volatile.Read(ref s_initialized))
{
lock (s_initializedLock)
{
if (!s_initialized)
{
Interop.Winsock.WSAData wsaData = new Interop.Winsock.WSAData();
SocketError errorCode =
Interop.Winsock.WSAStartup(
(short)0x0202, // we need 2.2
out wsaData);
if (errorCode != SocketError.Success)
{
//
// failed to initialize, throw
//
// WSAStartup does not set LastWin32Error
throw new SocketException((int)errorCode);
}
Volatile.Write(ref s_initialized, true);
}
}
}
}
}
}
| |
using UnityEditor;
using UnityEngine;
using System.Collections.Generic;
using System.IO;
[InitializeOnLoad]
public static class tk2dEditorUtility
{
public static double version = 2.5;
public static int releaseId = -2; // < -10001 = alpha 1, other negative = beta release, 0 = final, positive = final hotfix
static tk2dEditorUtility() {
#if UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2
System.Reflection.FieldInfo undoCallback = typeof(EditorApplication).GetField("undoRedoPerformed", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static);
if (undoCallback != null) {
undoCallback.SetValue(null, (EditorApplication.CallbackFunction)OnUndoRedo);
}
else {
Debug.LogError("tk2d Undo/Redo callback failed. Undo/Redo not supported in this version of Unity.");
}
#else
Undo.undoRedoPerformed += OnUndoRedo;
#endif
}
static void OnUndoRedo() {
foreach (GameObject go in Selection.gameObjects) {
tk2dSpriteFromTexture sft = go.GetComponent<tk2dSpriteFromTexture>();
tk2dBaseSprite spr = go.GetComponent<tk2dBaseSprite>();
tk2dTextMesh tm = go.GetComponent<tk2dTextMesh>();
if (sft != null) {
sft.ForceBuild();
}
else if (spr != null) {
spr.ForceBuild();
}
else if (tm != null) {
tm.ForceBuild();
}
}
}
public static string ReleaseStringIdentifier(double _version, int _releaseId)
{
string id = _version.ToString("0.0");
if (_releaseId == 0) id += ".0";
else if (_releaseId > 0) id += "." + _releaseId.ToString();
else if (_releaseId < -10000) id += " alpha " + (-_releaseId - 10000).ToString();
else if (_releaseId < 0) id += " beta " + (-_releaseId).ToString();
return id;
}
/// <summary>
/// Release filename for the current version
/// </summary>
public static string CurrentReleaseFileName(string product, double _version, int _releaseId)
{
string id = product + _version.ToString("0.0");
if (_releaseId == 0) id += ".0";
else if (_releaseId > 0) id += "." + _releaseId.ToString();
else if (_releaseId < -10000) id += "alpha" + (-_releaseId - 10000).ToString();
else if (_releaseId < 0) id += "beta" + (-_releaseId).ToString();
return id;
}
[MenuItem(tk2dMenu.root + "About", false, 10300)]
public static void About2DToolkit()
{
EditorUtility.DisplayDialog("About 2D Toolkit",
"2D Toolkit Version " + ReleaseStringIdentifier(version, releaseId) + "\n" +
"Copyright (c) Unikron Software Ltd",
"Ok");
}
[MenuItem(tk2dMenu.root + "Documentation", false, 10098)]
public static void LaunchDocumentation()
{
Application.OpenURL(string.Format("http://www.2dtoolkit.com/docs/{0:0.0}", version));
}
[MenuItem(tk2dMenu.root + "Support/Forum", false, 10103)]
public static void LaunchForum()
{
Application.OpenURL("http://www.2dtoolkit.com/forum");
}
[MenuItem(tk2dMenu.root + "Support/Email", false, 10103)]
public static void LaunchEmail()
{
Application.OpenURL(string.Format("mailto:support@unikronsoftware.com?subject=2D%20Toolkit%20{0:0.0}{1}%20Support", version, (releaseId!=0)?releaseId.ToString():"" ));
}
[MenuItem(tk2dMenu.root + "Rebuild Index", false, 1)]
public static void RebuildIndex()
{
AssetDatabase.DeleteAsset(indexPath);
AssetDatabase.Refresh();
CreateIndex();
// Now rebuild system object
tk2dSystemUtility.RebuildResources();
}
[MenuItem(tk2dMenu.root + "Preferences...", false, 1)]
public static void ShowPreferences()
{
EditorWindow.GetWindow( typeof(tk2dPreferencesEditor), true, "2D Toolkit Preferences" );
}
public static string CreateNewPrefab(string name) // name is the filename of the prefab EXCLUDING .prefab
{
Object obj = Selection.activeObject;
string assetPath = AssetDatabase.GetAssetPath(obj);
if (assetPath.Length == 0)
{
assetPath = tk2dGuiUtility.SaveFileInProject("Create...", "Assets/", name, "prefab");
}
else
{
// is a directory
string path = System.IO.Directory.Exists(assetPath) ? assetPath : System.IO.Path.GetDirectoryName(assetPath);
assetPath = AssetDatabase.GenerateUniqueAssetPath(path + "/" + name + ".prefab");
}
return assetPath;
}
const string indexPath = "Assets/-tk2d.asset";
static tk2dIndex index = null;
public static tk2dIndex GetExistingIndex()
{
if (index == null)
{
index = AssetDatabase.LoadAssetAtPath(indexPath, typeof(tk2dIndex)) as tk2dIndex;
}
return index;
}
public static tk2dIndex ForceCreateIndex()
{
CreateIndex();
return GetExistingIndex();
}
public static tk2dIndex GetOrCreateIndex()
{
tk2dIndex thisIndex = GetExistingIndex();
if (thisIndex == null || thisIndex.version != tk2dIndex.CURRENT_VERSION)
{
CreateIndex();
thisIndex = GetExistingIndex();
}
return thisIndex;
}
public static void CommitIndex()
{
if (index)
{
EditorUtility.SetDirty(index);
tk2dSpriteGuiUtility.ResetCache();
}
}
static void CreateIndex()
{
tk2dIndex newIndex = ScriptableObject.CreateInstance<tk2dIndex>();
newIndex.version = tk2dIndex.CURRENT_VERSION;
newIndex.hideFlags = HideFlags.DontSave; // get this to not be destroyed in Unity 4.1
List<string> rebuildSpriteCollectionPaths = new List<string>();
// check all prefabs to see if we can find any objects we are interested in
List<string> allPrefabPaths = new List<string>();
Stack<string> paths = new Stack<string>();
paths.Push(Application.dataPath);
while (paths.Count != 0)
{
string path = paths.Pop();
string[] files = Directory.GetFiles(path, "*.prefab");
foreach (var file in files)
{
allPrefabPaths.Add(file.Substring(Application.dataPath.Length - 6));
}
foreach (string subdirs in Directory.GetDirectories(path))
paths.Push(subdirs);
}
// Check all prefabs
int currPrefabCount = 1;
foreach (string prefabPath in allPrefabPaths)
{
EditorUtility.DisplayProgressBar("Rebuilding Index", "Scanning project folder...", (float)currPrefabCount / (float)(allPrefabPaths.Count));
GameObject iterGo = AssetDatabase.LoadAssetAtPath( prefabPath, typeof(GameObject) ) as GameObject;
if (!iterGo) continue;
tk2dSpriteCollection spriteCollection = iterGo.GetComponent<tk2dSpriteCollection>();
tk2dSpriteCollectionData spriteCollectionData = iterGo.GetComponent<tk2dSpriteCollectionData>();
tk2dFont font = iterGo.GetComponent<tk2dFont>();
tk2dSpriteAnimation anim = iterGo.GetComponent<tk2dSpriteAnimation>();
if (spriteCollection)
{
tk2dSpriteCollectionData thisSpriteCollectionData = spriteCollection.spriteCollection;
if (thisSpriteCollectionData)
{
if (thisSpriteCollectionData.version < 1)
{
rebuildSpriteCollectionPaths.Add( AssetDatabase.GetAssetPath(spriteCollection ));
}
newIndex.AddSpriteCollectionData( thisSpriteCollectionData );
}
}
else if (spriteCollectionData)
{
string guid = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(spriteCollectionData));
bool present = false;
foreach (var v in newIndex.GetSpriteCollectionIndex())
{
if (v.spriteCollectionDataGUID == guid)
{
present = true;
break;
}
}
if (!present && guid != "")
newIndex.AddSpriteCollectionData(spriteCollectionData);
}
else if (font)
{
newIndex.AddOrUpdateFont(font); // unfortunate but necessary
}
else if (anim)
{
newIndex.AddSpriteAnimation(anim);
}
else
{
iterGo = null;
System.GC.Collect();
}
tk2dEditorUtility.UnloadUnusedAssets();
++currPrefabCount;
}
EditorUtility.ClearProgressBar();
// Create index
newIndex.hideFlags = 0; // to save it
AssetDatabase.CreateAsset(newIndex, indexPath);
AssetDatabase.SaveAssets();
// unload all unused assets
tk2dEditorUtility.UnloadUnusedAssets();
// Rebuild invalid sprite collections
if (rebuildSpriteCollectionPaths.Count > 0)
{
EditorUtility.DisplayDialog("Upgrade required",
"Please wait while your sprite collection is upgraded.",
"Ok");
int count = 1;
foreach (var scPath in rebuildSpriteCollectionPaths)
{
tk2dSpriteCollection sc = AssetDatabase.LoadAssetAtPath(scPath, typeof(tk2dSpriteCollection)) as tk2dSpriteCollection;
EditorUtility.DisplayProgressBar("Rebuilding Sprite Collections", "Rebuilding Sprite Collection: " + sc.name, (float)count / (float)(rebuildSpriteCollectionPaths.Count));
tk2dSpriteCollectionBuilder.Rebuild(sc);
sc = null;
tk2dEditorUtility.UnloadUnusedAssets();
++count;
}
EditorUtility.ClearProgressBar();
}
index = newIndex;
tk2dSpriteGuiUtility.ResetCache();
}
[System.ObsoleteAttribute]
static T[] FindPrefabsInProjectWithComponent<T>() where T : Component
// returns null if nothing is found
{
List<T> allGens = new List<T>();
Stack<string> paths = new Stack<string>();
paths.Push(Application.dataPath);
while (paths.Count != 0)
{
string path = paths.Pop();
string[] files = Directory.GetFiles(path, "*.prefab");
foreach (var file in files)
{
GameObject go = AssetDatabase.LoadAssetAtPath( file.Substring(Application.dataPath.Length - 6), typeof(GameObject) ) as GameObject;
if (!go) continue;
T gen = go.GetComponent<T>();
if (gen)
{
allGens.Add(gen);
}
}
foreach (string subdirs in Directory.GetDirectories(path))
paths.Push(subdirs);
}
if (allGens.Count == 0) return null;
T[] allGensArray = new T[allGens.Count];
for (int i = 0; i < allGens.Count; ++i)
allGensArray[i] = allGens[i];
return allGensArray;
}
public static GameObject CreateGameObjectInScene(string name)
{
string realName = name;
int counter = 0;
while (GameObject.Find(realName) != null)
{
realName = name + counter++;
}
GameObject go = new GameObject(realName);
if (Selection.activeGameObject != null)
{
string assetPath = AssetDatabase.GetAssetPath(Selection.activeGameObject);
if (assetPath.Length == 0) {
go.transform.parent = Selection.activeGameObject.transform;
go.layer = Selection.activeGameObject.layer;
}
}
go.transform.localPosition = Vector3.zero;
go.transform.localRotation = Quaternion.identity;
go.transform.localScale = Vector3.one;
return go;
}
public static void DrawMeshBounds(Mesh mesh, Transform transform, Color c)
{
var e = mesh.bounds.extents;
Vector3[] boundPoints = new Vector3[] {
mesh.bounds.center + new Vector3(-e.x, e.y, 0.0f),
mesh.bounds.center + new Vector3( e.x, e.y, 0.0f),
mesh.bounds.center + new Vector3( e.x,-e.y, 0.0f),
mesh.bounds.center + new Vector3(-e.x,-e.y, 0.0f),
mesh.bounds.center + new Vector3(-e.x, e.y, 0.0f) };
for (int i = 0; i < boundPoints.Length; ++i)
boundPoints[i] = transform.TransformPoint(boundPoints[i]);
Handles.color = c;
Handles.DrawPolyLine(boundPoints);
}
public static void UnloadUnusedAssets()
{
Object[] previousSelectedObjects = Selection.objects;
Selection.objects = new Object[0];
System.GC.Collect();
#if (UNITY_3_5 || UNITY_4_0 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7 || UNITY_4_8 || UNITY_4_9)
EditorUtility.UnloadUnusedAssets();
#else
EditorUtility.UnloadUnusedAssetsImmediate();
#endif
index = null;
Selection.objects = previousSelectedObjects;
}
public static void CollectAndUnloadUnusedAssets()
{
System.GC.Collect();
System.GC.WaitForPendingFinalizers();
#if (UNITY_3_5 || UNITY_4_0 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7 || UNITY_4_8 || UNITY_4_9)
EditorUtility.UnloadUnusedAssets();
#else
EditorUtility.UnloadUnusedAssetsImmediate();
#endif
}
public static void DeleteAsset(UnityEngine.Object obj)
{
if (obj == null) return;
UnityEditor.AssetDatabase.DeleteAsset(UnityEditor.AssetDatabase.GetAssetPath(obj));
}
public static bool IsPrefab(Object obj)
{
return (PrefabUtility.GetPrefabType(obj) == PrefabType.Prefab);
}
public static bool IsEditable(UnityEngine.Object obj) {
MonoBehaviour mb = obj as MonoBehaviour;
return (mb && (mb.gameObject.hideFlags & HideFlags.NotEditable) == 0);
}
public static void SetGameObjectActive(GameObject go, bool active)
{
#if UNITY_3_5
go.SetActiveRecursively(active);
#else
go.SetActive(active);
#endif
}
public static bool IsGameObjectActive(GameObject go)
{
#if UNITY_3_5
return go.active;
#else
return go.activeSelf;
#endif
}
#if !(UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2)
private static System.Reflection.PropertyInfo sortingLayerNamesPropInfo = null;
private static bool sortingLayerNamesChecked = false;
private static string[] GetSortingLayerNames() {
if (sortingLayerNamesPropInfo == null && !sortingLayerNamesChecked) {
sortingLayerNamesChecked = true;
try {
System.Type IEU = System.Type.GetType("UnityEditorInternal.InternalEditorUtility,UnityEditor");
if (IEU != null) {
sortingLayerNamesPropInfo = IEU.GetProperty("sortingLayerNames", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public);
}
}
catch { }
if (sortingLayerNamesPropInfo == null) {
Debug.Log("tk2dEditorUtility - Unable to get sorting layer names.");
}
}
if (sortingLayerNamesPropInfo != null) {
return sortingLayerNamesPropInfo.GetValue(null, null) as string[];
}
else {
return new string[0];
}
}
public static string SortingLayerNamePopup( string label, string value ) {
if (value == "") {
value = "Default";
}
string[] names = GetSortingLayerNames();
if (names.Length == 0) {
return EditorGUILayout.TextField(label, value);
}
else {
int sel = 0;
for (int i = 0; i < names.Length; ++i) {
if (names[i] == value) {
sel = i;
break;
}
}
sel = EditorGUILayout.Popup(label, sel, names);
return names[sel];
}
}
#endif
[MenuItem(tk2dMenu.createBase + "Empty GameObject", false, 55000)]
static void DoCreateEmptyGameObject()
{
GameObject go = tk2dEditorUtility.CreateGameObjectInScene("GameObject");
Selection.activeGameObject = go;
Undo.RegisterCreatedObjectUndo(go, "Create Empty GameObject");
}
}
| |
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel
//
// 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 SharpDX.Mathematics;
namespace SharpDX.Toolkit.Graphics
{
/// <summary>
/// A parameter of an effect.
/// </summary>
/// <remarks>
/// A parameter can be a value type that will be set to a constant buffer, or a resource type (SRV, UAV, SamplerState).
/// </remarks>
public sealed class EffectParameter : ComponentBase
{
internal readonly EffectData.Parameter ParameterDescription;
internal readonly EffectConstantBuffer buffer;
private readonly EffectResourceLinker resourceLinker;
private readonly GetMatrixDelegate GetMatrixImpl;
private readonly CopyMatrixDelegate CopyMatrix;
private readonly int matrixSize;
private int offset;
/// <summary>
/// Initializes a new instance of the <see cref="EffectParameter"/> class.
/// </summary>
internal EffectParameter(EffectData.ValueTypeParameter parameterDescription, EffectConstantBuffer buffer)
: base(parameterDescription.Name)
{
this.ParameterDescription = parameterDescription;
this.buffer = buffer;
ResourceType = EffectResourceType.None;
IsValueType = true;
ParameterClass = parameterDescription.Class;
ParameterType = parameterDescription.Type;
RowCount = parameterDescription.RowCount;
ColumnCount = parameterDescription.ColumnCount;
ElementCount = parameterDescription.Count;
Offset = parameterDescription.Offset;
Size = parameterDescription.Size;
// If the expecting Matrix is column_major or the expected size is != from Matrix, than we need to remap SharpDX.Matrix to it.
if (ParameterClass == EffectParameterClass.MatrixRows || ParameterClass == EffectParameterClass.MatrixColumns)
{
var isMatrixToMap = RowCount != 4 || ColumnCount != 4 || ParameterClass == EffectParameterClass.MatrixColumns;
matrixSize = (ParameterClass == EffectParameterClass.MatrixColumns ? ColumnCount : RowCount) * 4 * sizeof(float);
// Use the correct function for this parameter
CopyMatrix = isMatrixToMap ? (ParameterClass == EffectParameterClass.MatrixRows) ? new CopyMatrixDelegate(CopyMatrixRowMajor) : CopyMatrixColumnMajor : CopyMatrixDirect;
GetMatrixImpl = isMatrixToMap ? (ParameterClass == EffectParameterClass.MatrixRows) ? new GetMatrixDelegate(GetMatrixRowMajorFrom) : GetMatrixColumnMajorFrom : GetMatrixDirectFrom;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="EffectParameter"/> class.
/// </summary>
internal EffectParameter(EffectData.ResourceParameter parameterDescription, EffectResourceType resourceType, int offset, EffectResourceLinker resourceLinker)
: base(parameterDescription.Name)
{
this.ParameterDescription = parameterDescription;
this.resourceLinker = resourceLinker;
ResourceType = resourceType;
IsValueType = false;
ParameterClass = parameterDescription.Class;
ParameterType = parameterDescription.Type;
RowCount = ColumnCount = 0;
ElementCount = parameterDescription.Count;
Offset = offset;
}
/// <summary>
/// A unique index of this parameter instance inside the <see cref="EffectParameterCollection"/> of an effect. See remarks.
/// </summary>
/// <remarks>
/// This unique index can be used between different instance of the effect with different deferred <see cref="GraphicsDevice"/>.
/// </remarks>
public int Index { get; internal set; }
/// <summary>
/// Gets the parameter class.
/// </summary>
/// <value>The parameter class.</value>
public readonly EffectParameterClass ParameterClass;
/// <summary>
/// Gets the resource type.
/// </summary>
public readonly EffectResourceType ResourceType;
/// <summary>
/// Gets the type of the parameter.
/// </summary>
/// <value>The type of the parameter.</value>
public readonly EffectParameterType ParameterType;
/// <summary>
/// Gets a boolean indicating if this parameter is a value type (true) or a resource type (false).
/// </summary>
public readonly bool IsValueType;
/// <summary>
/// Number of rows in a matrix. Otherwise a numeric type returns 1, any other type returns 0.
/// </summary>
/// <unmanaged>int Rows</unmanaged>
public readonly int RowCount;
/// <summary>
/// Number of columns in a matrix. Otherwise a numeric type returns 1, any other type returns 0.
/// </summary>
/// <unmanaged>int Columns</unmanaged>
public readonly int ColumnCount;
/// <summary>
/// Gets the collection of effect parameters.
/// </summary>
public readonly int ElementCount;
/// <summary>
/// Size in bytes of the element, only valid for value types.
/// </summary>
public readonly int Size;
/// <summary>
/// Offset of this parameter.
/// </summary>
/// <remarks>
/// For a value type, this offset is the offset in bytes inside the constant buffer.
/// For a resource type, this offset is an index to the resource linker.
/// </remarks>
public int Offset
{
get
{
return offset;
}
internal set
{
offset = value;
}
}
/// <summary>
/// Gets a single value to the associated parameter in the constant buffer.
/// </summary>
/// <typeparam name="T">The type of the value to read from the buffer.</typeparam>
/// <returns>The value of this parameter.</returns>
public T GetValue<T>() where T : struct
{
return buffer.BackingBuffer.Get<T>(offset);
}
/// <summary>
/// Gets a single value to the associated parameter in the constant buffer.
/// </summary>
/// <typeparam name="T">The type of the value to read from the buffer.</typeparam>
/// <param name="index">The index of the value (for value array).</param>
/// <returns>The value of this parameter.</returns>
public T GetValue<T>(int index) where T : struct
{
int size;
AlignedToFloat4<T>(out size);
return buffer.BackingBuffer.Get<T>(offset + index * size);
}
/// <summary>
/// Gets an array of values to the associated parameter in the constant buffer.
/// </summary>
/// <typeparam name = "T">The type of the value to read from the buffer.</typeparam>
/// <returns>The value of this parameter.</returns>
public T[] GetValueArray<T>(int count) where T : struct
{
int size;
if (AlignedToFloat4<T>(out size))
{
var values = new T[count];
int localOffset = offset;
for (int i = 0; i < values.Length; i++, localOffset += size)
{
buffer.BackingBuffer.Get(localOffset, out values[i]);
}
return values;
}
return buffer.BackingBuffer.GetRange<T>(offset, count);
}
/// <summary>
/// Gets a single value to the associated parameter in the constant buffer.
/// </summary>
/// <returns>The value of this parameter.</returns>
public Matrix GetMatrix()
{
return GetMatrixImpl(offset);
}
/// <summary>
/// Gets a single value to the associated parameter in the constant buffer.
/// </summary>
/// <returns>The value of this parameter.</returns>
public Matrix GetMatrix(int startIndex)
{
return GetMatrixImpl(offset + (startIndex * matrixSize));
}
/// <summary>
/// Gets an array of matrices to the associated parameter in the constant buffer.
/// </summary>
/// <param name="count">The count.</param>
/// <returns>Matrix[][].</returns>
/// <returns>The value of this parameter.</returns>
public Matrix[] GetMatrixArray(int count)
{
return GetMatrixArray(0, count);
}
/// <summary>
/// Gets an array of matrices to the associated parameter in the constant buffer.
/// </summary>
/// <returns>The value of this parameter.</returns>
public unsafe Matrix[] GetMatrixArray(int startIndex, int count)
{
var result = new Matrix[count];
var localOffset = offset + (startIndex * matrixSize);
// Fix the whole buffer
fixed (Matrix* pMatrix = result)
{
for (int i = 0; i < result.Length; i++, localOffset += matrixSize)
pMatrix[i] = GetMatrixImpl(localOffset);
}
buffer.IsDirty = true;
return result;
}
/// <summary>
/// Sets a single value to the associated parameter in the constant buffer.
/// </summary>
/// <typeparam name = "T">The type of the value to be written to the buffer.</typeparam>
/// <param name = "value">The value to write to the buffer.</param>
public void SetValue<T>(ref T value) where T : struct
{
buffer.BackingBuffer.Set(offset, ref value);
buffer.IsDirty = true;
}
/// <summary>
/// Sets a single value to the associated parameter in the constant buffer.
/// </summary>
/// <typeparam name = "T">The type of the value to be written to the buffer.</typeparam>
/// <param name = "value">The value to write to the buffer.</param>
public void SetValue<T>(T value) where T : struct
{
buffer.BackingBuffer.Set(offset, value);
buffer.IsDirty = true;
}
/// <summary>
/// Sets a single matrix value to the associated parameter in the constant buffer.
/// </summary>
/// <param name = "value">The matrix to write to the buffer.</param>
public void SetValue(ref Matrix value)
{
CopyMatrix(ref value, offset);
buffer.IsDirty = true;
}
/// <summary>
/// Sets a single matrix value to the associated parameter in the constant buffer.
/// </summary>
/// <param name = "value">The matrix to write to the buffer.</param>
public void SetValue(Matrix value)
{
CopyMatrix(ref value, offset);
buffer.IsDirty = true;
}
/// <summary>
/// Sets an array of matrices to the associated parameter in the constant buffer.
/// </summary>
/// <param name = "values">An array of matrices to be written to the current buffer.</param>
public unsafe void SetValue(Matrix[] values)
{
var localOffset = offset;
// Fix the whole buffer
fixed (Matrix* pMatrix = values)
{
for (int i = 0; i < values.Length; i++, localOffset += matrixSize)
CopyMatrix(ref pMatrix[i], localOffset);
}
buffer.IsDirty = true;
}
/// <summary>
/// Sets a single matrix at the specified index for the associated parameter in the constant buffer.
/// </summary>
/// <param name="index">Index of the matrix to write in element count.</param>
/// <param name = "value">The matrix to write to the buffer.</param>
public void SetValue(int index, Matrix value)
{
CopyMatrix(ref value, offset + index * matrixSize);
buffer.IsDirty = true;
}
/// <summary>
/// Sets an array of matrices to at the specified index for the associated parameter in the constant buffer.
/// </summary>
/// <param name="index">Index of the matrix to write in element count.</param>
/// <param name = "values">An array of matrices to be written to the current buffer.</param>
public unsafe void SetValue(int index, Matrix[] values)
{
var localOffset = this.offset + (index * matrixSize);
// Fix the whole buffer
fixed (Matrix* pMatrix = values)
{
for (int i = 0; i < values.Length; i++, localOffset += matrixSize)
CopyMatrix(ref pMatrix[i], localOffset);
}
buffer.IsDirty = true;
}
/// <summary>
/// Sets an array of raw values to the associated parameter in the constant buffer.
/// </summary>
/// <param name = "values">An array of values to be written to the current buffer.</param>
public void SetRawValue(byte[] values)
{
buffer.BackingBuffer.Set(offset, values);
buffer.IsDirty = true;
}
/// <summary>
/// Sets an array of values to the associated parameter in the constant buffer.
/// </summary>
/// <typeparam name = "T">The type of the value to be written to the buffer.</typeparam>
/// <param name = "values">An array of values to be written to the current buffer.</param>
public void SetValue<T>(T[] values) where T : struct
{
int size;
if (AlignedToFloat4<T>(out size))
{
int localOffset = offset;
for (int i = 0; i < values.Length; i++, localOffset += size)
{
buffer.BackingBuffer.Set(localOffset, ref values[i]);
}
}
else
{
buffer.BackingBuffer.Set(offset, values);
}
buffer.IsDirty = true;
}
/// <summary>
/// Sets a single value at the specified index for the associated parameter in the constant buffer.
/// </summary>
/// <typeparam name = "T">The type of the value to be written to the buffer.</typeparam>
/// <param name="index">Index of the value to write in typeof(T) element count.</param>
/// <param name = "value">The value to write to the buffer.</param>
public void SetValue<T>(int index, ref T value) where T : struct
{
int size;
AlignedToFloat4<T>(out size);
buffer.BackingBuffer.Set(offset + size * index, ref value);
buffer.IsDirty = true;
}
/// <summary>
/// Sets a single value at the specified index for the associated parameter in the constant buffer.
/// </summary>
/// <typeparam name = "T">The type of the value to be written to the buffer.</typeparam>
/// <param name="index">Index of the value to write in typeof(T) element count.</param>
/// <param name = "value">The value to write to the buffer.</param>
public void SetValue<T>(int index, T value) where T : struct
{
int size;
AlignedToFloat4<T>(out size);
buffer.BackingBuffer.Set(offset + size * index, ref value);
buffer.IsDirty = true;
}
/// <summary>
/// Sets an array of values to at the specified index for the associated parameter in the constant buffer.
/// </summary>
/// <typeparam name = "T">The type of the value to be written to the buffer.</typeparam>
/// <param name="index">Index of the value to write in typeof(T) element count.</param>
/// <param name = "values">An array of values to be written to the current buffer.</param>
public void SetValue<T>(int index, T[] values) where T : struct
{
int size;
if (AlignedToFloat4<T>(out size))
{
int localOffset = offset + size * index;
for (int i = 0; i < values.Length; i++, localOffset += size)
{
buffer.BackingBuffer.Set(localOffset, ref values[i]);
}
}
else
{
buffer.BackingBuffer.Set(offset + size * index, values);
}
buffer.IsDirty = true;
}
/// <summary>
/// Gets the resource view set for this parameter.
/// </summary>
/// <typeparam name = "T">The type of the resource view.</typeparam>
/// <returns>The resource view.</returns>
public T GetResource<T>() where T : class
{
return resourceLinker.GetResource<T>(offset);
}
/// <summary>
/// Sets a shader resource for the associated parameter.
/// </summary>
/// <typeparam name = "T">The type of the resource view.</typeparam>
/// <param name="resourceView">The resource view.</param>
public void SetResource<T>(T resourceView) where T : class
{
resourceLinker.SetResource(offset, ResourceType, resourceView);
}
/// <summary>
/// Sets a shader resource for the associated parameter.
/// </summary>
/// <param name="resourceView">The resource.</param>
/// <param name="initialUAVCount">The initial count for the UAV (-1) to keep it</param>
public void SetResource(Direct3D11.UnorderedAccessView resourceView, int initialUAVCount)
{
resourceLinker.SetResource(offset, ResourceType, resourceView, initialUAVCount);
}
/// <summary>
/// Direct access to the resource pointer in order to
/// </summary>
/// <param name="resourcePointer"></param>
internal void SetResourcePointer(IntPtr resourcePointer)
{
resourceLinker.SetResourcePointer(offset, ResourceType, resourcePointer);
}
/// <summary>
/// Sets a an array of shader resource views for the associated parameter.
/// </summary>
/// <typeparam name = "T">The type of the resource view.</typeparam>
/// <param name="resourceViewArray">The resource view array.</param>
public void SetResource<T>(params T[] resourceViewArray) where T : class
{
resourceLinker.SetResource(offset, ResourceType, resourceViewArray);
}
/// <summary>
/// Sets a an array of shader resource views for the associated parameter.
/// </summary>
/// <param name="resourceViewArray">The resource view array.</param>
/// <param name="uavCounts">Sets the initial uavCount</param>
public void SetResource(Direct3D11.UnorderedAccessView[] resourceViewArray, int[] uavCounts)
{
resourceLinker.SetResource(offset, ResourceType, resourceViewArray, uavCounts);
}
/// <summary>
/// Sets a shader resource at the specified index for the associated parameter.
/// </summary>
/// <typeparam name = "T">The type of the resource view.</typeparam>
/// <param name="index">Index to start to set the resource views</param>
/// <param name="resourceView">The resource view.</param>
public void SetResource<T>(int index, T resourceView) where T : class
{
resourceLinker.SetResource(offset + index, ResourceType, resourceView);
}
/// <summary>
/// Sets a an array of shader resource views at the specified index for the associated parameter.
/// </summary>
/// <typeparam name = "T">The type of the resource view.</typeparam>
/// <param name="index">Index to start to set the resource views</param>
/// <param name="resourceViewArray">The resource view array.</param>
public void SetResource<T>(int index, params T[] resourceViewArray) where T : class
{
resourceLinker.SetResource(offset + index, ResourceType, resourceViewArray);
}
/// <summary>
/// Sets a an array of shader resource views at the specified index for the associated parameter.
/// </summary>
/// <param name="index">Index to start to set the resource views</param>
/// <param name="resourceViewArray">The resource view array.</param>
/// <param name="uavCount">Sets the initial uavCount</param>
public void SetResource(int index, Direct3D11.UnorderedAccessView[] resourceViewArray, int[] uavCount)
{
resourceLinker.SetResource(offset + index, ResourceType, resourceViewArray, uavCount);
}
internal void SetDefaultValue()
{
if (IsValueType)
{
var defaultValue = ((EffectData.ValueTypeParameter) ParameterDescription).DefaultValue;
if (defaultValue != null)
{
SetRawValue(defaultValue);
}
}
}
public override string ToString()
{
return string.Format("[{0}] {1} Class: {2}, Resource: {3}, Type: {4}, IsValue: {5}, RowCount: {6}, ColumnCount: {7}, ElementCount: {8} Offset: {9}", Index, Name, ParameterClass, ResourceType, ParameterType, IsValueType, RowCount, ColumnCount, ElementCount, Offset);
}
/// <summary>
/// CopyMatrix delegate used to reorder matrix when copying from <see cref="Matrix"/>.
/// </summary>
/// <param name="matrix">The source matrix.</param>
/// <param name="offset">The offset in bytes to write to</param>
private delegate void CopyMatrixDelegate(ref Matrix matrix, int offset);
/// <summary>
/// Copy matrix in row major order.
/// </summary>
/// <param name="matrix">The source matrix.</param>
/// <param name="offset">The offset in bytes to write to</param>
private unsafe void CopyMatrixRowMajor(ref Matrix matrix, int offset)
{
var pDest = (float*)((byte*)buffer.BackingBuffer.DataPointer + offset);
fixed (void* pMatrix = &matrix)
{
var pSrc = (float*)pMatrix;
// If Matrix is row_major but expecting less columns/rows
// then copy only necessary columns/rows.
for (int i = 0; i < RowCount; i++, pSrc +=4, pDest += 4)
{
for (int j = 0; j < ColumnCount; j++)
pDest[j] = pSrc[j];
}
}
}
/// <summary>
/// Copy matrix in column major order.
/// </summary>
/// <param name="matrix">The source matrix.</param>
/// <param name="offset">The offset in bytes to write to</param>
private unsafe void CopyMatrixColumnMajor(ref Matrix matrix, int offset)
{
var pDest = (float*)((byte*)buffer.BackingBuffer.DataPointer + offset);
fixed (void* pMatrix = &matrix)
{
var pSrc = (float*)pMatrix;
// If Matrix is column_major, then we need to transpose it
for (int i = 0; i < ColumnCount; i++, pSrc++, pDest += 4)
{
for (int j = 0; j < RowCount; j++)
pDest[j] = pSrc[j * 4];
}
}
}
private static bool AlignedToFloat4<T>(out int size) where T : struct
{
size = Utilities.SizeOf<T>();
var requireAlign = (size & 0xF) != 0;
if (requireAlign) size = ((size >> 4) + 1) << 4;
return requireAlign;
}
/// <summary>
/// Straight Matrix copy, no conversion.
/// </summary>
/// <param name="matrix">The source matrix.</param>
/// <param name="offset">The offset in bytes to write to</param>
private void CopyMatrixDirect(ref Matrix matrix, int offset)
{
buffer.BackingBuffer.Set(offset, matrix);
}
/// <summary>
/// CopyMatrix delegate used to reorder matrix when copying from <see cref="Matrix"/>.
/// </summary>
/// <param name="offset">The offset in bytes to write to</param>
private delegate Matrix GetMatrixDelegate(int offset);
/// <summary>
/// Copy matrix in row major order.
/// </summary>
/// <param name="offset">The offset in bytes to write to</param>
private unsafe Matrix GetMatrixRowMajorFrom(int offset)
{
var result = default(Matrix);
var pSrc = (float*)((byte*)buffer.BackingBuffer.DataPointer + offset);
var pDest = (float*)&result;
// If Matrix is row_major but expecting less columns/rows
// then copy only necessary columns/rows.
for (int i = 0; i < RowCount; i++, pSrc += 4, pDest += 4)
{
for (int j = 0; j < ColumnCount; j++)
pDest[j] = pSrc[j];
}
return result;
}
/// <summary>
/// Copy matrix in column major order.
/// </summary>
/// <param name="offset">The offset in bytes to write to</param>
private unsafe Matrix GetMatrixColumnMajorFrom(int offset)
{
var result = default(Matrix);
var pSrc = (float*)((byte*)buffer.BackingBuffer.DataPointer + offset);
var pDest = (float*)&result;
// If Matrix is column_major, then we need to transpose it
for (int i = 0; i < ColumnCount; i++, pSrc +=4, pDest++)
{
for (int j = 0; j < RowCount; j++)
pDest[j * 4] = pSrc[j];
}
return result;
}
/// <summary>
/// Straight Matrix copy, no conversion.
/// </summary>
/// <param name="offset">The offset in bytes to write to</param>
private Matrix GetMatrixDirectFrom(int offset)
{
return buffer.BackingBuffer.Get<Matrix>(offset);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Caching;
using System.Threading;
using System.Web;
using Umbraco.Core.Models.EntityBase;
namespace Umbraco.Core.Persistence.Caching
{
/// <summary>
/// The Runtime Cache provider looks up objects in the Runtime cache for fast retrival
/// </summary>
/// <remarks>
///
/// If a web session is detected then the HttpRuntime.Cache will be used for the runtime cache, otherwise a custom
/// MemoryCache instance will be used. It is important to use the HttpRuntime.Cache when a web session is detected so
/// that the memory management of cache in IIS can be handled appopriately.
///
/// When a web sessions is detected we will pre-fix all HttpRuntime.Cache entries so that when we clear it we are only
/// clearing items that have been inserted by this provider.
///
/// NOTE: These changes are all temporary until we finalize the ApplicationCache implementation which will support static cache, runtime cache
/// and request based cache which will all live in one central location so it is easily managed.
///
/// Also note that we don't always keep checking if HttpContext.Current == null and instead check for _memoryCache != null. This is because
/// when there are async requests being made even in the context of a web request, the HttpContext.Current will be null but the HttpRuntime.Cache will
/// always be available.
///
/// TODO: Each item that get's added to this cache will be a clone of the original with it's dirty properties reset, and every item that is resolved from the cache
/// is a clone of the item that is in there, otherwise we end up with thread safety issues since multiple thread would be working on the exact same entity at the same time.
///
/// </remarks>
internal sealed class RuntimeCacheProvider : IRepositoryCacheProvider
{
#region Singleton
private static readonly Lazy<RuntimeCacheProvider> lazy = new Lazy<RuntimeCacheProvider>(() => new RuntimeCacheProvider());
public static RuntimeCacheProvider Current { get { return lazy.Value; } }
//internal for testing! - though I'm not a huge fan of these being singletons!
internal RuntimeCacheProvider()
{
if (HttpContext.Current == null)
{
_memoryCache = new MemoryCache("in-memory");
}
}
#endregion
//TODO Save this in cache as well, so its not limited to a single server usage
private readonly ConcurrentHashSet<string> _keyTracker = new ConcurrentHashSet<string>();
private ObjectCache _memoryCache;
private static readonly ReaderWriterLockSlim ClearLock = new ReaderWriterLockSlim();
public IEntity GetById(Type type, Guid id)
{
var key = GetCompositeId(type, id);
var item = _memoryCache != null
? _memoryCache.Get(key)
: HttpRuntime.Cache.Get(key);
var result = item as IEntity;
if (result == null)
{
//ensure the key doesn't exist anymore in the tracker
_keyTracker.Remove(key);
return null;
}
//IMPORTANT: we must clone to resolve, see: http://issues.umbraco.org/issue/U4-4259
return (IEntity)result.DeepClone();
}
public IEnumerable<IEntity> GetByIds(Type type, List<Guid> ids)
{
var collection = new List<IEntity>();
foreach (var guid in ids)
{
var key = GetCompositeId(type, guid);
var item = _memoryCache != null
? _memoryCache.Get(key)
: HttpRuntime.Cache.Get(key);
var result = item as IEntity;
if (result == null)
{
//ensure the key doesn't exist anymore in the tracker
_keyTracker.Remove(key);
}
else
{
//IMPORTANT: we must clone to resolve, see: http://issues.umbraco.org/issue/U4-4259
collection.Add((IEntity)result.DeepClone());
}
}
return collection;
}
public IEnumerable<IEntity> GetAllByType(Type type)
{
var collection = new List<IEntity>();
foreach (var key in _keyTracker)
{
if (key.StartsWith(string.Format("{0}{1}-", CacheItemPrefix, type.Name)))
{
var item = _memoryCache != null
? _memoryCache.Get(key)
: HttpRuntime.Cache.Get(key);
var result = item as IEntity;
if (result == null)
{
//ensure the key doesn't exist anymore in the tracker
_keyTracker.Remove(key);
}
else
{
//IMPORTANT: we must clone to resolve, see: http://issues.umbraco.org/issue/U4-4259
collection.Add((IEntity)result.DeepClone());
}
}
}
return collection;
}
public void Save(Type type, IEntity entity)
{
//IMPORTANT: we must clone to store, see: http://issues.umbraco.org/issue/U4-4259
var clone = (IEntity)entity.DeepClone();
var key = GetCompositeId(type, clone.Id);
_keyTracker.TryAdd(key);
//NOTE: Before we were checking if it already exists but the MemoryCache.Set handles this implicitly and does
// an add or update, same goes for HttpRuntime.Cache.Insert.
if (_memoryCache != null)
{
_memoryCache.Set(key, clone, new CacheItemPolicy { SlidingExpiration = TimeSpan.FromMinutes(5) });
}
else
{
HttpRuntime.Cache.Insert(key, clone, null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(5));
}
}
public void Delete(Type type, IEntity entity)
{
var key = GetCompositeId(type, entity.Id);
if (_memoryCache != null)
{
_memoryCache.Remove(key);
}
else
{
HttpRuntime.Cache.Remove(key);
}
_keyTracker.Remove(key);
}
public void Delete(Type type, int entityId)
{
var key = GetCompositeId(type, entityId);
if (_memoryCache != null)
{
_memoryCache.Remove(key);
}
else
{
HttpRuntime.Cache.Remove(key);
}
_keyTracker.Remove(key);
}
/// <summary>
/// Clear cache by type
/// </summary>
/// <param name="type"></param>
public void Clear(Type type)
{
using (new WriteLock(ClearLock))
{
var keys = new string[_keyTracker.Count];
_keyTracker.CopyTo(keys, 0);
var keysToRemove = new List<string>();
foreach (var key in keys.Where(x => x.StartsWith(string.Format("{0}{1}-", CacheItemPrefix, type.Name))))
{
_keyTracker.Remove(key);
keysToRemove.Add(key);
}
foreach (var key in keysToRemove)
{
if (_memoryCache != null)
{
_memoryCache.Remove(key);
}
else
{
HttpRuntime.Cache.Remove(key);
}
}
}
}
public void Clear()
{
using (new WriteLock(ClearLock))
{
_keyTracker.Clear();
ClearDataCache();
}
}
//DO not call this unless it's for testing since it clears the data cached but not the keys
internal void ClearDataCache()
{
if (_memoryCache != null)
{
_memoryCache.DisposeIfDisposable();
_memoryCache = new MemoryCache("in-memory");
}
else
{
foreach (DictionaryEntry c in HttpRuntime.Cache)
{
if (c.Key is string && ((string)c.Key).InvariantStartsWith(CacheItemPrefix))
{
if (HttpRuntime.Cache[(string)c.Key] == null) return;
HttpRuntime.Cache.Remove((string)c.Key);
}
}
}
}
/// <summary>
/// We prefix all cache keys with this so that we know which ones this class has created when
/// using the HttpRuntime cache so that when we clear it we don't clear other entries we didn't create.
/// </summary>
private const string CacheItemPrefix = "umbrtmche_";
private string GetCompositeId(Type type, Guid id)
{
return string.Format("{0}{1}-{2}", CacheItemPrefix, type.Name, id);
}
private string GetCompositeId(Type type, int id)
{
return string.Format("{0}{1}-{2}", CacheItemPrefix, type.Name, id.ToGuid());
}
}
}
| |
using Signum.Entities;
using Signum.Entities.Authorization;
using Signum.Entities.Basics;
using Signum.Entities.DynamicQuery;
using Signum.Entities.UserAssets;
using Signum.Utilities;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Xml.Linq;
namespace Signum.Entities.UserQueries
{
[Serializable, EntityKind(EntityKind.Main, EntityData.Master)]
public class UserQueryEntity : Entity, IUserAssetEntity
{
public UserQueryEntity() { }
public UserQueryEntity(object queryName)
{
this.queryName = queryName;
}
[Ignore]
internal object queryName;
public QueryEntity Query { get; set; }
public bool GroupResults { get; set; }
public Lite<TypeEntity>? EntityType { get; set; }
public bool HideQuickLink { get; set; }
public bool? IncludeDefaultFilters { get; set; }
public Lite<Entity>? Owner { get; set; }
[StringLengthValidator(Min = 1, Max = 200)]
public string DisplayName { get; set; }
public bool AppendFilters { get; set; }
public RefreshMode RefreshMode { get; set; } = RefreshMode.Auto;
[PreserveOrder]
public MList<QueryFilterEmbedded> Filters { get; set; } = new MList<QueryFilterEmbedded>();
[PreserveOrder]
public MList<QueryOrderEmbedded> Orders { get; set; } = new MList<QueryOrderEmbedded>();
public ColumnOptionsMode ColumnsMode { get; set; }
[PreserveOrder]
public MList<QueryColumnEmbedded> Columns { get; set; } = new MList<QueryColumnEmbedded>();
public PaginationMode? PaginationMode { get; set; }
[NumberIsValidator(ComparisonType.GreaterThanOrEqualTo, 1)]
public int? ElementsPerPage { get; set; }
[UniqueIndex]
public Guid Guid { get; set; } = Guid.NewGuid();
[AutoExpressionField]
public override string ToString() => As.Expression(() => DisplayName);
protected override string? PropertyValidation(PropertyInfo pi)
{
if (pi.Name == nameof(ElementsPerPage))
{
return (pi, ElementsPerPage).IsSetOnlyWhen(PaginationMode == DynamicQuery.PaginationMode.Firsts || PaginationMode == DynamicQuery.PaginationMode.Paginate);
}
return base.PropertyValidation(pi);
}
[HiddenProperty]
public bool ShouldHaveElements
{
get
{
return PaginationMode == Signum.Entities.DynamicQuery.PaginationMode.Firsts ||
PaginationMode == Signum.Entities.DynamicQuery.PaginationMode.Paginate;
}
}
internal void ParseData(QueryDescription description)
{
var canAggregate = this.GroupResults ? SubTokensOptions.CanAggregate : 0;
foreach (var f in Filters)
f.ParseData(this, description, SubTokensOptions.CanAnyAll | SubTokensOptions.CanElement | canAggregate);
foreach (var c in Columns)
c.ParseData(this, description, SubTokensOptions.CanElement | canAggregate);
foreach (var o in Orders)
o.ParseData(this, description, SubTokensOptions.CanElement | canAggregate);
}
public XElement ToXml(IToXmlContext ctx)
{
return new XElement("UserQuery",
new XAttribute("Guid", Guid),
new XAttribute("DisplayName", DisplayName),
new XAttribute("Query", Query.Key),
EntityType == null ? null! : new XAttribute("EntityType", ctx.TypeToName(EntityType)),
Owner == null ? null! : new XAttribute("Owner", Owner.Key()),
!HideQuickLink ? null! : new XAttribute("HideQuickLink", HideQuickLink),
IncludeDefaultFilters == null ? null! : new XAttribute("IncludeDefaultFilters", IncludeDefaultFilters.Value),
!AppendFilters ? null! : new XAttribute("AppendFilters", AppendFilters),
RefreshMode == RefreshMode.Auto ? null! : new XAttribute("RefreshMode", RefreshMode.ToString()),
!GroupResults ? null! : new XAttribute("GroupResults", GroupResults),
ElementsPerPage == null ? null! : new XAttribute("ElementsPerPage", ElementsPerPage),
PaginationMode == null ? null! : new XAttribute("PaginationMode", PaginationMode),
new XAttribute("ColumnsMode", ColumnsMode),
Filters.IsNullOrEmpty() ? null! : new XElement("Filters", Filters.Select(f => f.ToXml(ctx)).ToList()),
Columns.IsNullOrEmpty() ? null! : new XElement("Columns", Columns.Select(c => c.ToXml(ctx)).ToList()),
Orders.IsNullOrEmpty() ? null! : new XElement("Orders", Orders.Select(o => o.ToXml(ctx)).ToList()));
}
public void FromXml(XElement element, IFromXmlContext ctx)
{
Query = ctx.GetQuery(element.Attribute("Query")!.Value);
DisplayName = element.Attribute("DisplayName")!.Value;
EntityType = element.Attribute("EntityType")?.Let(a => ctx.GetType(a.Value).ToLite());
Owner = element.Attribute("Owner")?.Let(a => Lite.Parse(a.Value))!;
HideQuickLink = element.Attribute("HideQuickLink")?.Let(a => bool.Parse(a.Value)) ?? false;
IncludeDefaultFilters = element.Attribute("IncludeDefaultFilters")?.Let(a => bool.Parse(a.Value));
AppendFilters = element.Attribute("AppendFilters")?.Let(a => bool.Parse(a.Value)) ?? false;
RefreshMode = element.Attribute("RefreshMode")?.Let(a => a.Value.ToEnum<RefreshMode>()) ?? RefreshMode.Auto;
GroupResults = element.Attribute("GroupResults")?.Let(a => bool.Parse(a.Value)) ?? false;
ElementsPerPage = element.Attribute("ElementsPerPage")?.Let(a => int.Parse(a.Value));
PaginationMode = element.Attribute("PaginationMode")?.Let(a => a.Value.ToEnum<PaginationMode>());
ColumnsMode = element.Attribute("ColumnsMode")!.Value.ToEnum<ColumnOptionsMode>();
Filters.Synchronize(element.Element("Filters")?.Elements().ToList(), (f, x) => f.FromXml(x, ctx));
Columns.Synchronize(element.Element("Columns")?.Elements().ToList(), (c, x) => c.FromXml(x, ctx));
Orders.Synchronize(element.Element("Orders")?.Elements().ToList(), (o, x) => o.FromXml(x, ctx));
ParseData(ctx.GetQueryDescription(Query));
}
public Pagination? GetPagination()
{
switch (PaginationMode)
{
case Signum.Entities.DynamicQuery.PaginationMode.All: return new Pagination.All();
case Signum.Entities.DynamicQuery.PaginationMode.Firsts: return new Pagination.Firsts(ElementsPerPage!.Value);
case Signum.Entities.DynamicQuery.PaginationMode.Paginate: return new Pagination.Paginate(ElementsPerPage!.Value, 1);
default: return null;
}
}
}
[AutoInit]
public static class UserQueryPermission
{
public static PermissionSymbol ViewUserQuery;
}
[AutoInit]
public static class UserQueryOperation
{
public static ExecuteSymbol<UserQueryEntity> Save;
public static DeleteSymbol<UserQueryEntity> Delete;
}
[Serializable]
public class QueryOrderEmbedded : EmbeddedEntity
{
public QueryTokenEmbedded Token { get; set; }
public OrderType OrderType { get; set; }
public XElement ToXml(IToXmlContext ctx)
{
return new XElement("Orden",
new XAttribute("Token", Token.Token.FullKey()),
new XAttribute("OrderType", OrderType));
}
internal void FromXml(XElement element, IFromXmlContext ctx)
{
Token = new QueryTokenEmbedded(element.Attribute("Token")!.Value);
OrderType = element.Attribute("OrderType")!.Value.ToEnum<OrderType>();
}
public void ParseData(Entity context, QueryDescription description, SubTokensOptions options)
{
Token.ParseData(context, description, options & ~SubTokensOptions.CanAnyAll);
}
protected override string? PropertyValidation(PropertyInfo pi)
{
if (pi.Name == nameof(Token) && Token != null && Token.ParseException == null)
{
return QueryUtils.CanOrder(Token.Token);
}
return base.PropertyValidation(pi);
}
public override string ToString()
{
return "{0} {1}".FormatWith(Token, OrderType);
}
}
[Serializable]
public class QueryColumnEmbedded : EmbeddedEntity
{
public QueryTokenEmbedded Token { get; set; }
string? displayName;
public string? DisplayName
{
get { return displayName.DefaultToNull(); }
set { Set(ref displayName, value); }
}
public QueryTokenEmbedded? SummaryToken { get; set; }
public bool HiddenColumn { get; set; }
public XElement ToXml(IToXmlContext ctx)
{
return new XElement("Column",
new XAttribute("Token", Token.Token.FullKey()),
SummaryToken != null ? new XAttribute("SummaryToken", SummaryToken.Token.FullKey()) : null!,
DisplayName.HasText() ? new XAttribute("DisplayName", DisplayName) : null!,
HiddenColumn ? new XAttribute("HiddenColumn", HiddenColumn) : null!);
}
internal void FromXml(XElement element, IFromXmlContext ctx)
{
Token = new QueryTokenEmbedded(element.Attribute("Token")!.Value);
SummaryToken = element.Attribute("SummaryToken")?.Value.Let(val => new QueryTokenEmbedded(val));
DisplayName = element.Attribute("DisplayName")?.Value;
HiddenColumn = element.Attribute("HiddenColumn")?.Value.ToBool() == false;
}
public void ParseData(Entity context, QueryDescription description, SubTokensOptions options)
{
Token.ParseData(context, description, options);
SummaryToken?.ParseData(context, description, options | SubTokensOptions.CanAggregate);
}
protected override string? PropertyValidation(PropertyInfo pi)
{
if (pi.Name == nameof(Token) && Token != null && Token.ParseException == null)
{
return QueryUtils.CanColumn(Token.Token);
}
if (pi.Name == nameof(SummaryToken) && SummaryToken != null && SummaryToken.ParseException == null)
{
return QueryUtils.CanColumn(SummaryToken.Token) ??
(SummaryToken.Token is not AggregateToken ? SearchMessage.SummaryHeaderMustBeAnAggregate.NiceToString() : null);
}
return base.PropertyValidation(pi);
}
public override string ToString()
{
return "{0} {1}".FormatWith(Token, displayName);
}
}
[Serializable]
public class QueryFilterEmbedded : EmbeddedEntity
{
public QueryFilterEmbedded() { }
QueryTokenEmbedded? token;
public QueryTokenEmbedded? Token
{
get { return token; }
set
{
if (Set(ref token, value))
{
Notify(() => Operation);
Notify(() => ValueString);
}
}
}
public bool IsGroup { get; set; }
public FilterGroupOperation? GroupOperation { get; set; }
public FilterOperation? Operation { get; set; }
[StringLengthValidator(Max = 300)]
public string? ValueString { get; set; }
public PinnedQueryFilterEmbedded? Pinned { get; set; }
[NumberIsValidator(ComparisonType.GreaterThanOrEqualTo, 0)]
public int Indentation { get; set; }
public void ParseData(ModifiableEntity context, QueryDescription description, SubTokensOptions options)
{
token?.ParseData(context, description, options);
}
protected override string? PropertyValidation(PropertyInfo pi)
{
if (IsGroup)
{
if (pi.Name == nameof(GroupOperation) && GroupOperation == null)
return ValidationMessage._0IsNotSet.NiceToString(pi.NiceName());
if(token != null && token.ParseException == null)
{
if (pi.Name == nameof(Token))
{
return QueryUtils.CanFilter(token.Token);
}
}
}
else
{
if (pi.Name == nameof(Operation) && Operation == null)
return ValidationMessage._0IsNotSet.NiceToString(pi.NiceName());
if (pi.Name == nameof(Token) && Token == null)
return ValidationMessage._0IsNotSet.NiceToString(pi.NiceName());
if (token != null && token.ParseException == null)
{
if (pi.Name == nameof(Token))
{
return QueryUtils.CanFilter(token.Token);
}
if (pi.Name == nameof(Operation) && Operation != null)
{
FilterType? filterType = QueryUtils.TryGetFilterType(Token!.Token.Type);
if (filterType == null)
return UserQueryMessage._0IsNotFilterable.NiceToString().FormatWith(token);
if (!QueryUtils.GetFilterOperations(filterType.Value).Contains(Operation.Value))
return UserQueryMessage.TheFilterOperation0isNotCompatibleWith1.NiceToString().FormatWith(Operation, filterType);
}
if (pi.Name == nameof(ValueString))
{
var result = FilterValueConverter.TryParse(ValueString, Token!.Token.Type, Operation!.Value.IsList());
return result is Result<object>.Error e ? e.ErrorText : null;
}
}
}
return null;
}
public XElement ToXml(IToXmlContext ctx)
{
if (this.GroupOperation.HasValue)
{
return new XElement("Filter",
new XAttribute("Indentation", Indentation),
new XAttribute("GroupOperation", GroupOperation),
Token == null ? null! : new XAttribute("Token", Token.Token.FullKey()),
Pinned?.ToXml(ctx)!);
}
else
{
return new XElement("Filter",
new XAttribute("Indentation", Indentation),
new XAttribute("Token", Token!.Token.FullKey()),
new XAttribute("Operation", Operation!),
ValueString == null ? null! : new XAttribute("Value", ValueString),
Pinned?.ToXml(ctx)!);
}
}
public void FromXml(XElement element, IFromXmlContext ctx)
{
IsGroup = element.Attribute("GroupOperation") != null;
Indentation = element.Attribute("Indentation")?.Value.ToInt() ?? 0;
GroupOperation = element.Attribute("GroupOperation")?.Value.ToEnum<FilterGroupOperation>();
Operation = element.Attribute("Operation")?.Value.ToEnum<FilterOperation>();
Token = element.Attribute("Token")?.Let(t => new QueryTokenEmbedded(t.Value));
ValueString = element.Attribute("Value")?.Value;
Pinned = element.Element("Pinned")?.Let(p => (this.Pinned ?? new PinnedQueryFilterEmbedded()).FromXml(p, ctx));
}
public override string ToString()
{
return "{0} {1} {2}".FormatWith(token, Operation, ValueString);
}
public QueryFilterEmbedded Clone() => new QueryFilterEmbedded
{
Indentation = Indentation,
GroupOperation = GroupOperation,
IsGroup = IsGroup,
Pinned = Pinned?.Clone(),
Token = Token?.Clone(),
Operation = Operation,
ValueString = ValueString,
};
}
[Serializable]
public class PinnedQueryFilterEmbedded : EmbeddedEntity
{
[StringLengthValidator(Max = 100)]
public string? Label { get; set; }
public int? Column { get; set; }
public int? Row { get; set; }
public PinnedFilterActive Active { get; set; }
public bool SplitText { get; set; }
internal PinnedQueryFilterEmbedded Clone() => new PinnedQueryFilterEmbedded
{
Label = Label,
Column = Column,
Row = Row,
Active = Active,
SplitText = SplitText,
};
internal PinnedQueryFilterEmbedded FromXml(XElement p, IFromXmlContext ctx)
{
Label = p.Attribute("Label")?.Value;
Column = p.Attribute("Column")?.Value.ToInt();
Row = p.Attribute("Row")?.Value.ToInt();
Active = p.Attribute("Active")?.Value.ToEnum<PinnedFilterActive>() ?? (p.Attribute("DisableOnNull")?.Value.ToBool() == true ? PinnedFilterActive.WhenHasValue : PinnedFilterActive.Always);
SplitText = p.Attribute("SplitText")?.Value.ToBool() ?? false;
return this;
}
internal XElement ToXml(IToXmlContext ctx)
{
return new XElement("Pinned",
Label.DefaultToNull()?.Let(l => new XAttribute("Label", l))!,
Column?.Let(l => new XAttribute("Column", l))!,
Row?.Let(l => new XAttribute("Row", l))!,
Active == PinnedFilterActive.Always ? null! : new XAttribute("Active", Active.ToString())!,
SplitText == false ? null! : new XAttribute("SplitText", SplitText)
);
}
}
public static class UserQueryUtils
{
public static List<Filter> ToFilterList(this IEnumerable<QueryFilterEmbedded> filters, int indent = 0)
{
return filters.GroupWhen(filter => filter.Indentation == indent).Select(gr =>
{
if (!gr.Key.IsGroup)
{
if (gr.Count() != 0)
throw new InvalidOperationException("Unexpected childrens of condition");
var filter = gr.Key;
var value = FilterValueConverter.Parse(filter.ValueString, filter.Token!.Token.Type, filter.Operation!.Value.IsList());
return (Filter)new FilterCondition(filter.Token.Token, filter.Operation.Value, value);
}
else
{
var group = gr.Key;
return (Filter)new FilterGroup(group.GroupOperation!.Value, group.Token?.Token, gr.ToFilterList(indent + 1).ToList());
}
}).ToList();
}
}
public enum UserQueryMessage
{
Edit,
[Description("Create")]
CreateNew,
[Description("Back to Default")]
BackToDefault,
[Description("Apply changes")]
ApplyChanges,
[Description("The Filter Operation {0} is not compatible with {1}")]
TheFilterOperation0isNotCompatibleWith1,
[Description("{0} is not filterable")]
_0IsNotFilterable,
[Description("Use {0} to filter current entity")]
Use0ToFilterCurrentEntity,
Preview,
[Description("Makes the user query available in the contextual menu when grouping {0}")]
MakesTheUserQueryAvailableInContextualMenuWhenGrouping0,
[Description("Makes the user query available as quick link of {0}")]
MakesTheUserQueryAvailableAsAQuickLinkOf0,
[Description("the selected {0}")]
TheSelected0,
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Microsoft.Azure;
using Microsoft.Azure.Management.Resources;
using Microsoft.Azure.Management.Resources.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.Resources
{
/// <summary>
/// Operations for managing tags.
/// </summary>
internal partial class TagOperations : IServiceOperations<ResourceManagementClient>, ITagOperations
{
/// <summary>
/// Initializes a new instance of the TagOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal TagOperations(ResourceManagementClient client)
{
this._client = client;
}
private ResourceManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.Resources.ResourceManagementClient.
/// </summary>
public ResourceManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Create a subscription resource tag.
/// </summary>
/// <param name='tagName'>
/// Required. The name of the tag.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Tag information.
/// </returns>
public async Task<TagCreateResult> CreateOrUpdateAsync(string tagName, CancellationToken cancellationToken)
{
// Validate
if (tagName == null)
{
throw new ArgumentNullException("tagName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("tagName", tagName);
TracingAdapter.Enter(invocationId, this, "CreateOrUpdateAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/tagNames/";
url = url + Uri.EscapeDataString(tagName);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-04-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
TagCreateResult result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new TagCreateResult();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
TagDetails tagInstance = new TagDetails();
result.Tag = tagInstance;
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
tagInstance.Id = idInstance;
}
JToken tagNameValue = responseDoc["tagName"];
if (tagNameValue != null && tagNameValue.Type != JTokenType.Null)
{
string tagNameInstance = ((string)tagNameValue);
tagInstance.Name = tagNameInstance;
}
JToken countValue = responseDoc["count"];
if (countValue != null && countValue.Type != JTokenType.Null)
{
TagCount countInstance = new TagCount();
tagInstance.Count = countInstance;
JToken typeValue = countValue["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
countInstance.Type = typeInstance;
}
JToken valueValue = countValue["value"];
if (valueValue != null && valueValue.Type != JTokenType.Null)
{
string valueInstance = ((string)valueValue);
countInstance.Value = valueInstance;
}
}
JToken valuesArray = responseDoc["values"];
if (valuesArray != null && valuesArray.Type != JTokenType.Null)
{
foreach (JToken valuesValue in ((JArray)valuesArray))
{
TagValue tagValueInstance = new TagValue();
tagInstance.Values.Add(tagValueInstance);
JToken idValue2 = valuesValue["id"];
if (idValue2 != null && idValue2.Type != JTokenType.Null)
{
string idInstance2 = ((string)idValue2);
tagValueInstance.Id = idInstance2;
}
JToken tagValueValue = valuesValue["tagValue"];
if (tagValueValue != null && tagValueValue.Type != JTokenType.Null)
{
string tagValueInstance2 = ((string)tagValueValue);
tagValueInstance.Value = tagValueInstance2;
}
JToken countValue2 = valuesValue["count"];
if (countValue2 != null && countValue2.Type != JTokenType.Null)
{
TagCount countInstance2 = new TagCount();
tagValueInstance.Count = countInstance2;
JToken typeValue2 = countValue2["type"];
if (typeValue2 != null && typeValue2.Type != JTokenType.Null)
{
string typeInstance2 = ((string)typeValue2);
countInstance2.Type = typeInstance2;
}
JToken valueValue2 = countValue2["value"];
if (valueValue2 != null && valueValue2.Type != JTokenType.Null)
{
string valueInstance2 = ((string)valueValue2);
countInstance2.Value = valueInstance2;
}
}
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Create a subscription resource tag value.
/// </summary>
/// <param name='tagName'>
/// Required. The name of the tag.
/// </param>
/// <param name='tagValue'>
/// Required. The value of the tag.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Tag information.
/// </returns>
public async Task<TagCreateValueResult> CreateOrUpdateValueAsync(string tagName, string tagValue, CancellationToken cancellationToken)
{
// Validate
if (tagName == null)
{
throw new ArgumentNullException("tagName");
}
if (tagValue == null)
{
throw new ArgumentNullException("tagValue");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("tagName", tagName);
tracingParameters.Add("tagValue", tagValue);
TracingAdapter.Enter(invocationId, this, "CreateOrUpdateValueAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/tagNames/";
url = url + Uri.EscapeDataString(tagName);
url = url + "/tagValues/";
url = url + Uri.EscapeDataString(tagValue);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-04-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
TagCreateValueResult result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new TagCreateValueResult();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
TagValue valueInstance = new TagValue();
result.Value = valueInstance;
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
valueInstance.Id = idInstance;
}
JToken tagValueValue = responseDoc["tagValue"];
if (tagValueValue != null && tagValueValue.Type != JTokenType.Null)
{
string tagValueInstance = ((string)tagValueValue);
valueInstance.Value = tagValueInstance;
}
JToken countValue = responseDoc["count"];
if (countValue != null && countValue.Type != JTokenType.Null)
{
TagCount countInstance = new TagCount();
valueInstance.Count = countInstance;
JToken typeValue = countValue["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
countInstance.Type = typeInstance;
}
JToken valueValue = countValue["value"];
if (valueValue != null && valueValue.Type != JTokenType.Null)
{
string valueInstance2 = ((string)valueValue);
countInstance.Value = valueInstance2;
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Delete a subscription resource tag.
/// </summary>
/// <param name='tagName'>
/// Required. The name of the tag.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> DeleteAsync(string tagName, CancellationToken cancellationToken)
{
// Validate
if (tagName == null)
{
throw new ArgumentNullException("tagName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("tagName", tagName);
TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/tagNames/";
url = url + Uri.EscapeDataString(tagName);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-04-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Delete;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.NoContent)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Delete a subscription resource tag value.
/// </summary>
/// <param name='tagName'>
/// Required. The name of the tag.
/// </param>
/// <param name='tagValue'>
/// Required. The value of the tag.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> DeleteValueAsync(string tagName, string tagValue, CancellationToken cancellationToken)
{
// Validate
if (tagName == null)
{
throw new ArgumentNullException("tagName");
}
if (tagValue == null)
{
throw new ArgumentNullException("tagValue");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("tagName", tagName);
tracingParameters.Add("tagValue", tagValue);
TracingAdapter.Enter(invocationId, this, "DeleteValueAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/tagNames/";
url = url + Uri.EscapeDataString(tagName);
url = url + "/tagValues/";
url = url + Uri.EscapeDataString(tagValue);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-04-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Delete;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.NoContent)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Get a list of subscription resource tags.
/// </summary>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// List of subscription tags.
/// </returns>
public async Task<TagsListResult> ListAsync(CancellationToken cancellationToken)
{
// Validate
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/tagNames";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-04-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
TagsListResult result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new TagsListResult();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
TagDetails tagDetailsInstance = new TagDetails();
result.Tags.Add(tagDetailsInstance);
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
tagDetailsInstance.Id = idInstance;
}
JToken tagNameValue = valueValue["tagName"];
if (tagNameValue != null && tagNameValue.Type != JTokenType.Null)
{
string tagNameInstance = ((string)tagNameValue);
tagDetailsInstance.Name = tagNameInstance;
}
JToken countValue = valueValue["count"];
if (countValue != null && countValue.Type != JTokenType.Null)
{
TagCount countInstance = new TagCount();
tagDetailsInstance.Count = countInstance;
JToken typeValue = countValue["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
countInstance.Type = typeInstance;
}
JToken valueValue2 = countValue["value"];
if (valueValue2 != null && valueValue2.Type != JTokenType.Null)
{
string valueInstance = ((string)valueValue2);
countInstance.Value = valueInstance;
}
}
JToken valuesArray = valueValue["values"];
if (valuesArray != null && valuesArray.Type != JTokenType.Null)
{
foreach (JToken valuesValue in ((JArray)valuesArray))
{
TagValue tagValueInstance = new TagValue();
tagDetailsInstance.Values.Add(tagValueInstance);
JToken idValue2 = valuesValue["id"];
if (idValue2 != null && idValue2.Type != JTokenType.Null)
{
string idInstance2 = ((string)idValue2);
tagValueInstance.Id = idInstance2;
}
JToken tagValueValue = valuesValue["tagValue"];
if (tagValueValue != null && tagValueValue.Type != JTokenType.Null)
{
string tagValueInstance2 = ((string)tagValueValue);
tagValueInstance.Value = tagValueInstance2;
}
JToken countValue2 = valuesValue["count"];
if (countValue2 != null && countValue2.Type != JTokenType.Null)
{
TagCount countInstance2 = new TagCount();
tagValueInstance.Count = countInstance2;
JToken typeValue2 = countValue2["type"];
if (typeValue2 != null && typeValue2.Type != JTokenType.Null)
{
string typeInstance2 = ((string)typeValue2);
countInstance2.Type = typeInstance2;
}
JToken valueValue3 = countValue2["value"];
if (valueValue3 != null && valueValue3.Type != JTokenType.Null)
{
string valueInstance2 = ((string)valueValue3);
countInstance2.Value = valueInstance2;
}
}
}
}
}
}
JToken odatanextLinkValue = responseDoc["@odata.nextLink"];
if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null)
{
string odatanextLinkInstance = ((string)odatanextLinkValue);
result.NextLink = odatanextLinkInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Get a list of tags under a subscription.
/// </summary>
/// <param name='nextLink'>
/// Required. NextLink from the previous successful call to List
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// List of subscription tags.
/// </returns>
public async Task<TagsListResult> ListNextAsync(string nextLink, CancellationToken cancellationToken)
{
// Validate
if (nextLink == null)
{
throw new ArgumentNullException("nextLink");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextLink", nextLink);
TracingAdapter.Enter(invocationId, this, "ListNextAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + nextLink;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
TagsListResult result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new TagsListResult();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
TagDetails tagDetailsInstance = new TagDetails();
result.Tags.Add(tagDetailsInstance);
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
tagDetailsInstance.Id = idInstance;
}
JToken tagNameValue = valueValue["tagName"];
if (tagNameValue != null && tagNameValue.Type != JTokenType.Null)
{
string tagNameInstance = ((string)tagNameValue);
tagDetailsInstance.Name = tagNameInstance;
}
JToken countValue = valueValue["count"];
if (countValue != null && countValue.Type != JTokenType.Null)
{
TagCount countInstance = new TagCount();
tagDetailsInstance.Count = countInstance;
JToken typeValue = countValue["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
countInstance.Type = typeInstance;
}
JToken valueValue2 = countValue["value"];
if (valueValue2 != null && valueValue2.Type != JTokenType.Null)
{
string valueInstance = ((string)valueValue2);
countInstance.Value = valueInstance;
}
}
JToken valuesArray = valueValue["values"];
if (valuesArray != null && valuesArray.Type != JTokenType.Null)
{
foreach (JToken valuesValue in ((JArray)valuesArray))
{
TagValue tagValueInstance = new TagValue();
tagDetailsInstance.Values.Add(tagValueInstance);
JToken idValue2 = valuesValue["id"];
if (idValue2 != null && idValue2.Type != JTokenType.Null)
{
string idInstance2 = ((string)idValue2);
tagValueInstance.Id = idInstance2;
}
JToken tagValueValue = valuesValue["tagValue"];
if (tagValueValue != null && tagValueValue.Type != JTokenType.Null)
{
string tagValueInstance2 = ((string)tagValueValue);
tagValueInstance.Value = tagValueInstance2;
}
JToken countValue2 = valuesValue["count"];
if (countValue2 != null && countValue2.Type != JTokenType.Null)
{
TagCount countInstance2 = new TagCount();
tagValueInstance.Count = countInstance2;
JToken typeValue2 = countValue2["type"];
if (typeValue2 != null && typeValue2.Type != JTokenType.Null)
{
string typeInstance2 = ((string)typeValue2);
countInstance2.Type = typeInstance2;
}
JToken valueValue3 = countValue2["value"];
if (valueValue3 != null && valueValue3.Type != JTokenType.Null)
{
string valueInstance2 = ((string)valueValue3);
countInstance2.Value = valueInstance2;
}
}
}
}
}
}
JToken odatanextLinkValue = responseDoc["@odata.nextLink"];
if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null)
{
string odatanextLinkInstance = ((string)odatanextLinkValue);
result.NextLink = odatanextLinkInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
// HtmlAgilityPack V1.0 - Simon Mourier <simon underscore mourier at hotmail dot com>
using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.XPath;
#pragma warning disable 0649
namespace HtmlAgilityPack
{
/// <summary>
/// Represents an HTML navigator on an HTML document seen as a data store.
/// </summary>
public class HtmlNodeNavigator : XPathNavigator
{
#region Fields
private int _attindex;
private HtmlNode _currentnode;
private readonly HtmlDocument _doc = new HtmlDocument();
private readonly HtmlNameTable _nametable = new HtmlNameTable();
internal bool Trace;
#endregion
#region Constructors
internal HtmlNodeNavigator()
{
Reset();
}
internal HtmlNodeNavigator(HtmlDocument doc, HtmlNode currentNode)
{
if (currentNode == null)
{
throw new ArgumentNullException("currentNode");
}
if (currentNode.OwnerDocument != doc)
{
throw new ArgumentException(HtmlDocument.HtmlExceptionRefNotChild);
}
InternalTrace(null);
_doc = doc;
Reset();
_currentnode = currentNode;
}
private HtmlNodeNavigator(HtmlNodeNavigator nav)
{
if (nav == null)
{
throw new ArgumentNullException("nav");
}
InternalTrace(null);
_doc = nav._doc;
_currentnode = nav._currentnode;
_attindex = nav._attindex;
_nametable = nav._nametable; // REVIEW: should we do this?
}
/// <summary>
/// Initializes a new instance of the HtmlNavigator and loads an HTML document from a stream.
/// </summary>
/// <param name="stream">The input stream.</param>
public HtmlNodeNavigator(Stream stream)
{
_doc.Load(stream);
Reset();
}
/// <summary>
/// Initializes a new instance of the HtmlNavigator and loads an HTML document from a stream.
/// </summary>
/// <param name="stream">The input stream.</param>
/// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the stream.</param>
public HtmlNodeNavigator(Stream stream, bool detectEncodingFromByteOrderMarks)
{
_doc.Load(stream, detectEncodingFromByteOrderMarks);
Reset();
}
/// <summary>
/// Initializes a new instance of the HtmlNavigator and loads an HTML document from a stream.
/// </summary>
/// <param name="stream">The input stream.</param>
/// <param name="encoding">The character encoding to use.</param>
public HtmlNodeNavigator(Stream stream, Encoding encoding)
{
_doc.Load(stream, encoding);
Reset();
}
/// <summary>
/// Initializes a new instance of the HtmlNavigator and loads an HTML document from a stream.
/// </summary>
/// <param name="stream">The input stream.</param>
/// <param name="encoding">The character encoding to use.</param>
/// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the stream.</param>
public HtmlNodeNavigator(Stream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks)
{
_doc.Load(stream, encoding, detectEncodingFromByteOrderMarks);
Reset();
}
/// <summary>
/// Initializes a new instance of the HtmlNavigator and loads an HTML document from a stream.
/// </summary>
/// <param name="stream">The input stream.</param>
/// <param name="encoding">The character encoding to use.</param>
/// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the stream.</param>
/// <param name="buffersize">The minimum buffer size.</param>
public HtmlNodeNavigator(Stream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks, int buffersize)
{
_doc.Load(stream, encoding, detectEncodingFromByteOrderMarks, buffersize);
Reset();
}
/// <summary>
/// Initializes a new instance of the HtmlNavigator and loads an HTML document from a TextReader.
/// </summary>
/// <param name="reader">The TextReader used to feed the HTML data into the document.</param>
public HtmlNodeNavigator(TextReader reader)
{
_doc.Load(reader);
Reset();
}
/// <summary>
/// Initializes a new instance of the HtmlNavigator and loads an HTML document from a file.
/// </summary>
/// <param name="path">The complete file path to be read.</param>
public HtmlNodeNavigator(string path)
{
_doc.Load(path);
Reset();
}
/// <summary>
/// Initializes a new instance of the HtmlNavigator and loads an HTML document from a file.
/// </summary>
/// <param name="path">The complete file path to be read.</param>
/// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the file.</param>
public HtmlNodeNavigator(string path, bool detectEncodingFromByteOrderMarks)
{
_doc.Load(path, detectEncodingFromByteOrderMarks);
Reset();
}
/// <summary>
/// Initializes a new instance of the HtmlNavigator and loads an HTML document from a file.
/// </summary>
/// <param name="path">The complete file path to be read.</param>
/// <param name="encoding">The character encoding to use.</param>
public HtmlNodeNavigator(string path, Encoding encoding)
{
_doc.Load(path, encoding);
Reset();
}
/// <summary>
/// Initializes a new instance of the HtmlNavigator and loads an HTML document from a file.
/// </summary>
/// <param name="path">The complete file path to be read.</param>
/// <param name="encoding">The character encoding to use.</param>
/// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the file.</param>
public HtmlNodeNavigator(string path, Encoding encoding, bool detectEncodingFromByteOrderMarks)
{
_doc.Load(path, encoding, detectEncodingFromByteOrderMarks);
Reset();
}
/// <summary>
/// Initializes a new instance of the HtmlNavigator and loads an HTML document from a file.
/// </summary>
/// <param name="path">The complete file path to be read.</param>
/// <param name="encoding">The character encoding to use.</param>
/// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the file.</param>
/// <param name="buffersize">The minimum buffer size.</param>
public HtmlNodeNavigator(string path, Encoding encoding, bool detectEncodingFromByteOrderMarks, int buffersize)
{
_doc.Load(path, encoding, detectEncodingFromByteOrderMarks, buffersize);
Reset();
}
#endregion
#region Properties
/// <summary>
/// Gets the base URI for the current node.
/// Always returns string.Empty in the case of HtmlNavigator implementation.
/// </summary>
public override string BaseURI
{
get
{
InternalTrace(">");
return _nametable.GetOrAdd(string.Empty);
}
}
/// <summary>
/// Gets the current HTML document.
/// </summary>
public HtmlDocument CurrentDocument
{
get { return _doc; }
}
/// <summary>
/// Gets the current HTML node.
/// </summary>
public HtmlNode CurrentNode
{
get { return _currentnode; }
}
/// <summary>
/// Gets a value indicating whether the current node has child nodes.
/// </summary>
public override bool HasAttributes
{
get
{
InternalTrace(">" + (_currentnode.Attributes.Count > 0));
return (_currentnode.Attributes.Count > 0);
}
}
/// <summary>
/// Gets a value indicating whether the current node has child nodes.
/// </summary>
public override bool HasChildren
{
get
{
InternalTrace(">" + (_currentnode.ChildNodes.Count > 0));
return (_currentnode.ChildNodes.Count > 0);
}
}
/// <summary>
/// Gets a value indicating whether the current node is an empty element.
/// </summary>
public override bool IsEmptyElement
{
get
{
InternalTrace(">" + !HasChildren);
// REVIEW: is this ok?
return !HasChildren;
}
}
/// <summary>
/// Gets the name of the current HTML node without the namespace prefix.
/// </summary>
public override string LocalName
{
get
{
if (_attindex != -1)
{
InternalTrace("att>" + _currentnode.Attributes[_attindex].Name);
return _nametable.GetOrAdd(_currentnode.Attributes[_attindex].Name);
}
InternalTrace("node>" + _currentnode.Name);
return _nametable.GetOrAdd(_currentnode.Name);
}
}
/// <summary>
/// Gets the qualified name of the current node.
/// </summary>
public override string Name
{
get
{
InternalTrace(">" + _currentnode.Name);
return _nametable.GetOrAdd(_currentnode.Name);
}
}
/// <summary>
/// Gets the namespace URI (as defined in the W3C Namespace Specification) of the current node.
/// Always returns string.Empty in the case of HtmlNavigator implementation.
/// </summary>
public override string NamespaceURI
{
get
{
InternalTrace(">");
return _nametable.GetOrAdd(string.Empty);
}
}
/// <summary>
/// Gets the <see cref="XmlNameTable"/> associated with this implementation.
/// </summary>
public override XmlNameTable NameTable
{
get
{
InternalTrace(null);
return _nametable;
}
}
/// <summary>
/// Gets the type of the current node.
/// </summary>
public override XPathNodeType NodeType
{
get
{
switch (_currentnode.NodeType)
{
case HtmlNodeType.Comment:
InternalTrace(">" + XPathNodeType.Comment);
return XPathNodeType.Comment;
case HtmlNodeType.Document:
InternalTrace(">" + XPathNodeType.Root);
return XPathNodeType.Root;
case HtmlNodeType.Text:
InternalTrace(">" + XPathNodeType.Text);
return XPathNodeType.Text;
case HtmlNodeType.Element:
{
if (_attindex != -1)
{
InternalTrace(">" + XPathNodeType.Attribute);
return XPathNodeType.Attribute;
}
InternalTrace(">" + XPathNodeType.Element);
return XPathNodeType.Element;
}
default:
throw new NotImplementedException("Internal error: Unhandled HtmlNodeType: " +
_currentnode.NodeType);
}
}
}
/// <summary>
/// Gets the prefix associated with the current node.
/// Always returns string.Empty in the case of HtmlNavigator implementation.
/// </summary>
public override string Prefix
{
get
{
InternalTrace(null);
return _nametable.GetOrAdd(string.Empty);
}
}
/// <summary>
/// Gets the text value of the current node.
/// </summary>
public override string Value
{
get
{
InternalTrace("nt=" + _currentnode.NodeType);
switch (_currentnode.NodeType)
{
case HtmlNodeType.Comment:
InternalTrace(">" + ((HtmlCommentNode) _currentnode).Comment);
return ((HtmlCommentNode) _currentnode).Comment;
case HtmlNodeType.Document:
InternalTrace(">");
return "";
case HtmlNodeType.Text:
InternalTrace(">" + ((HtmlTextNode) _currentnode).Text);
return ((HtmlTextNode) _currentnode).Text;
case HtmlNodeType.Element:
{
if (_attindex != -1)
{
InternalTrace(">" + _currentnode.Attributes[_attindex].Value);
return _currentnode.Attributes[_attindex].Value;
}
return _currentnode.InnerText;
}
default:
throw new NotImplementedException("Internal error: Unhandled HtmlNodeType: " +
_currentnode.NodeType);
}
}
}
/// <summary>
/// Gets the xml:lang scope for the current node.
/// Always returns string.Empty in the case of HtmlNavigator implementation.
/// </summary>
public override string XmlLang
{
get
{
InternalTrace(null);
return _nametable.GetOrAdd(string.Empty);
}
}
#endregion
#region Public Methods
/// <summary>
/// Creates a new HtmlNavigator positioned at the same node as this HtmlNavigator.
/// </summary>
/// <returns>A new HtmlNavigator object positioned at the same node as the original HtmlNavigator.</returns>
public override XPathNavigator Clone()
{
InternalTrace(null);
return new HtmlNodeNavigator(this);
}
/// <summary>
/// Gets the value of the HTML attribute with the specified LocalName and NamespaceURI.
/// </summary>
/// <param name="localName">The local name of the HTML attribute.</param>
/// <param name="namespaceURI">The namespace URI of the attribute. Unsupported with the HtmlNavigator implementation.</param>
/// <returns>The value of the specified HTML attribute. String.Empty or null if a matching attribute is not found or if the navigator is not positioned on an element node.</returns>
public override string GetAttribute(string localName, string namespaceURI)
{
InternalTrace("localName=" + localName + ", namespaceURI=" + namespaceURI);
HtmlAttribute att = _currentnode.Attributes[localName];
if (att == null)
{
InternalTrace(">null");
return null;
}
InternalTrace(">" + att.Value);
return att.Value;
}
/// <summary>
/// Returns the value of the namespace node corresponding to the specified local name.
/// Always returns string.Empty for the HtmlNavigator implementation.
/// </summary>
/// <param name="name">The local name of the namespace node.</param>
/// <returns>Always returns string.Empty for the HtmlNavigator implementation.</returns>
public override string GetNamespace(string name)
{
InternalTrace("name=" + name);
return string.Empty;
}
/// <summary>
/// Determines whether the current HtmlNavigator is at the same position as the specified HtmlNavigator.
/// </summary>
/// <param name="other">The HtmlNavigator that you want to compare against.</param>
/// <returns>true if the two navigators have the same position, otherwise, false.</returns>
public override bool IsSamePosition(XPathNavigator other)
{
HtmlNodeNavigator nav = other as HtmlNodeNavigator;
if (nav == null)
{
InternalTrace(">false");
return false;
}
InternalTrace(">" + (nav._currentnode == _currentnode));
return (nav._currentnode == _currentnode);
}
/// <summary>
/// Moves to the same position as the specified HtmlNavigator.
/// </summary>
/// <param name="other">The HtmlNavigator positioned on the node that you want to move to.</param>
/// <returns>true if successful, otherwise false. If false, the position of the navigator is unchanged.</returns>
public override bool MoveTo(XPathNavigator other)
{
HtmlNodeNavigator nav = other as HtmlNodeNavigator;
if (nav == null)
{
InternalTrace(">false (nav is not an HtmlNodeNavigator)");
return false;
}
InternalTrace("moveto oid=" + nav.GetHashCode()
+ ", n:" + nav._currentnode.Name
+ ", a:" + nav._attindex);
if (nav._doc == _doc)
{
_currentnode = nav._currentnode;
_attindex = nav._attindex;
InternalTrace(">true");
return true;
}
// we don't know how to handle that
InternalTrace(">false (???)");
return false;
}
/// <summary>
/// Moves to the HTML attribute with matching LocalName and NamespaceURI.
/// </summary>
/// <param name="localName">The local name of the HTML attribute.</param>
/// <param name="namespaceURI">The namespace URI of the attribute. Unsupported with the HtmlNavigator implementation.</param>
/// <returns>true if the HTML attribute is found, otherwise, false. If false, the position of the navigator does not change.</returns>
public override bool MoveToAttribute(string localName, string namespaceURI)
{
InternalTrace("localName=" + localName + ", namespaceURI=" + namespaceURI);
int index = _currentnode.Attributes.GetAttributeIndex(localName);
if (index == -1)
{
InternalTrace(">false");
return false;
}
_attindex = index;
InternalTrace(">true");
return true;
}
/// <summary>
/// Moves to the first sibling of the current node.
/// </summary>
/// <returns>true if the navigator is successful moving to the first sibling node, false if there is no first sibling or if the navigator is currently positioned on an attribute node.</returns>
public override bool MoveToFirst()
{
if (_currentnode.ParentNode == null)
{
InternalTrace(">false");
return false;
}
if (_currentnode.ParentNode.FirstChild == null)
{
InternalTrace(">false");
return false;
}
_currentnode = _currentnode.ParentNode.FirstChild;
InternalTrace(">true");
return true;
}
/// <summary>
/// Moves to the first HTML attribute.
/// </summary>
/// <returns>true if the navigator is successful moving to the first HTML attribute, otherwise, false.</returns>
public override bool MoveToFirstAttribute()
{
if (!HasAttributes)
{
InternalTrace(">false");
return false;
}
_attindex = 0;
InternalTrace(">true");
return true;
}
/// <summary>
/// Moves to the first child of the current node.
/// </summary>
/// <returns>true if there is a first child node, otherwise false.</returns>
public override bool MoveToFirstChild()
{
if (!_currentnode.HasChildNodes)
{
InternalTrace(">false");
return false;
}
_currentnode = _currentnode.ChildNodes[0];
InternalTrace(">true");
return true;
}
/// <summary>
/// Moves the XPathNavigator to the first namespace node of the current element.
/// Always returns false for the HtmlNavigator implementation.
/// </summary>
/// <param name="scope">An XPathNamespaceScope value describing the namespace scope.</param>
/// <returns>Always returns false for the HtmlNavigator implementation.</returns>
public override bool MoveToFirstNamespace(XPathNamespaceScope scope)
{
InternalTrace(null);
return false;
}
/// <summary>
/// Moves to the node that has an attribute of type ID whose value matches the specified string.
/// </summary>
/// <param name="id">A string representing the ID value of the node to which you want to move. This argument does not need to be atomized.</param>
/// <returns>true if the move was successful, otherwise false. If false, the position of the navigator is unchanged.</returns>
public override bool MoveToId(string id)
{
InternalTrace("id=" + id);
HtmlNode node = _doc.GetElementbyId(id);
if (node == null)
{
InternalTrace(">false");
return false;
}
_currentnode = node;
InternalTrace(">true");
return true;
}
/// <summary>
/// Moves the XPathNavigator to the namespace node with the specified local name.
/// Always returns false for the HtmlNavigator implementation.
/// </summary>
/// <param name="name">The local name of the namespace node.</param>
/// <returns>Always returns false for the HtmlNavigator implementation.</returns>
public override bool MoveToNamespace(string name)
{
InternalTrace("name=" + name);
return false;
}
/// <summary>
/// Moves to the next sibling of the current node.
/// </summary>
/// <returns>true if the navigator is successful moving to the next sibling node, false if there are no more siblings or if the navigator is currently positioned on an attribute node. If false, the position of the navigator is unchanged.</returns>
public override bool MoveToNext()
{
if (_currentnode.NextSibling == null)
{
InternalTrace(">false");
return false;
}
InternalTrace("_c=" + _currentnode.CloneNode(false).OuterHtml);
InternalTrace("_n=" + _currentnode.NextSibling.CloneNode(false).OuterHtml);
_currentnode = _currentnode.NextSibling;
InternalTrace(">true");
return true;
}
/// <summary>
/// Moves to the next HTML attribute.
/// </summary>
/// <returns></returns>
public override bool MoveToNextAttribute()
{
InternalTrace(null);
if (_attindex >= (_currentnode.Attributes.Count - 1))
{
InternalTrace(">false");
return false;
}
_attindex++;
InternalTrace(">true");
return true;
}
/// <summary>
/// Moves the XPathNavigator to the next namespace node.
/// Always returns falsefor the HtmlNavigator implementation.
/// </summary>
/// <param name="scope">An XPathNamespaceScope value describing the namespace scope.</param>
/// <returns>Always returns false for the HtmlNavigator implementation.</returns>
public override bool MoveToNextNamespace(XPathNamespaceScope scope)
{
InternalTrace(null);
return false;
}
/// <summary>
/// Moves to the parent of the current node.
/// </summary>
/// <returns>true if there is a parent node, otherwise false.</returns>
public override bool MoveToParent()
{
if (_currentnode.ParentNode == null)
{
InternalTrace(">false");
return false;
}
_currentnode = _currentnode.ParentNode;
InternalTrace(">true");
return true;
}
/// <summary>
/// Moves to the previous sibling of the current node.
/// </summary>
/// <returns>true if the navigator is successful moving to the previous sibling node, false if there is no previous sibling or if the navigator is currently positioned on an attribute node.</returns>
public override bool MoveToPrevious()
{
if (_currentnode.PreviousSibling == null)
{
InternalTrace(">false");
return false;
}
_currentnode = _currentnode.PreviousSibling;
InternalTrace(">true");
return true;
}
/// <summary>
/// Moves to the root node to which the current node belongs.
/// </summary>
public override void MoveToRoot()
{
_currentnode = _doc.DocumentNode;
InternalTrace(null);
}
#endregion
#region Internal Methods
[Conditional("TRACE")]
internal void InternalTrace(object traceValue)
{
if (!Trace)
{
return;
}
StackFrame sf = new StackFrame(1, true);
string name = sf.GetMethod().Name;
string nodename = _currentnode == null ? "(null)" : _currentnode.Name;
string nodevalue;
if (_currentnode == null)
{
nodevalue = "(null)";
}
else
{
switch (_currentnode.NodeType)
{
case HtmlNodeType.Comment:
nodevalue = ((HtmlCommentNode) _currentnode).Comment;
break;
case HtmlNodeType.Document:
nodevalue = "";
break;
case HtmlNodeType.Text:
nodevalue = ((HtmlTextNode) _currentnode).Text;
break;
default:
nodevalue = _currentnode.CloneNode(false).OuterHtml;
break;
}
}
HtmlAgilityPack.Trace.WriteLine(string.Format("oid={0},n={1},a={2},v={3},{4}", GetHashCode(), nodename, _attindex, nodevalue, traceValue), "N!" + name);
}
#endregion
#region Private Methods
private void Reset()
{
InternalTrace(null);
_currentnode = _doc.DocumentNode;
_attindex = -1;
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
/// <summary>
/// Convert.ToChar(Int64)
/// Converts the value of the specified 64-bit signed integer to its equivalent Unicode character.
/// </summary>
public class ConvertTochar
{
public static int Main()
{
ConvertTochar testObj = new ConvertTochar();
TestLibrary.TestFramework.BeginTestCase("for method: Convert.ToChar(Int64)");
if(testObj.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
return retVal;
}
#region Positive tests
public bool PosTest1()
{
bool retVal = true;
string errorDesc;
Int64 i;
char expectedValue;
char actualValue;
i = TestLibrary.Generator.GetInt64(-55) % (UInt16.MaxValue + 1);
TestLibrary.TestFramework.BeginScenario("PosTest1: Int64 value between 0 and UInt16.MaxValue.");
try
{
actualValue = Convert.ToChar(i);
expectedValue = (char)i;
if (actualValue != expectedValue)
{
errorDesc = string.Format(
"The character corresponding to Int64 value {0} is not \\u{1:x} as expected: actual(\\u{2:x})",
i, (int)expectedValue, (int)actualValue);
TestLibrary.TestFramework.LogError("001", errorDesc);
retVal = false;
}
}
catch (Exception e)
{
errorDesc = "Unexpect exception:" + e;
errorDesc += "\nThe Int64 value is " + i;
TestLibrary.TestFramework.LogError("002", errorDesc);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
string errorDesc;
Int64 i;
char expectedValue;
char actualValue;
i = UInt16.MaxValue;
TestLibrary.TestFramework.BeginScenario("PosTest2: Int64 value is UInt16.MaxValue.");
try
{
actualValue = Convert.ToChar(i);
expectedValue = (char)i;
if (actualValue != expectedValue)
{
errorDesc = string.Format(
"The character corresponding to Int64 value {0} is not \\u{1:x} as expected: actual(\\u{2:x})",
i, (int)expectedValue, (int)actualValue);
TestLibrary.TestFramework.LogError("003", errorDesc);
retVal = false;
}
}
catch (Exception e)
{
errorDesc = "Unexpect exception:" + e;
errorDesc += "\nThe Int64 value is " + i;
TestLibrary.TestFramework.LogError("004", errorDesc);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
string errorDesc;
Int64 i;
char expectedValue;
char actualValue;
i = 0;
TestLibrary.TestFramework.BeginScenario("PosTest3: Int64 value is zero.");
try
{
actualValue = Convert.ToChar(i);
expectedValue = (char)i;
if (actualValue != expectedValue)
{
errorDesc = string.Format(
"The character corresponding to Int64 value {0} is not \\u{1:x} as expected: actual(\\u{2:x})",
i, (int)expectedValue, (int)actualValue);
TestLibrary.TestFramework.LogError("005", errorDesc);
retVal = false;
}
}
catch (Exception e)
{
errorDesc = "Unexpect exception:" + e;
errorDesc += "\nThe Int64 value is " + i;
TestLibrary.TestFramework.LogError("006", errorDesc);
retVal = false;
}
return retVal;
}
#endregion
#region Negative tests
//OverflowException
public bool NegTest1()
{
bool retVal = true;
const string c_TEST_ID = "N001";
const string c_TEST_DESC = "NegTest1: Int64 value is a negative integer between Int64.MinValue and -1.";
string errorDesc;
Int64 i = (Int64)(-1 * TestLibrary.Generator.GetInt64(-55) - 1);
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
Convert.ToChar(i);
errorDesc = "OverflowException is not thrown as expected.";
errorDesc += string.Format("\nThe Int64 value is {0}", i);
TestLibrary.TestFramework.LogError("007" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
catch (OverflowException)
{ }
catch (Exception e)
{
errorDesc = "Unexpected exception: " + e;
errorDesc += string.Format("\nThe Int64 value is {0}", i);
TestLibrary.TestFramework.LogError("008" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
const string c_TEST_ID = "N002";
const string c_TEST_DESC = "NegTest2: Int64 value is a integer between UInt16.MaxValue and Int64.MaxValue.";
string errorDesc;
Int64 i = TestLibrary.Generator.GetInt64(-55) % (Int64.MaxValue - UInt16.MaxValue) +
UInt16.MaxValue + 1;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
Convert.ToChar(i);
errorDesc = "OverflowException is not thrown as expected.";
errorDesc += string.Format("\nThe Int64 value is {0}", i);
TestLibrary.TestFramework.LogError("009" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
catch (OverflowException)
{ }
catch (Exception e)
{
errorDesc = "Unexpected exception: " + e;
errorDesc += string.Format("\nThe Int64 value is {0}", i);
TestLibrary.TestFramework.LogError("010" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
return retVal;
}
#endregion
}
| |
//
// Copyright (C) DataStax Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Cassandra.Connections;
using Cassandra.Requests;
using Cassandra.Responses;
using Cassandra.Serialization;
using Cassandra.SessionManagement;
using Cassandra.Tests.Connections.TestHelpers;
using Moq;
using NUnit.Framework;
namespace Cassandra.Tests.Requests
{
[TestFixture]
public class PrepareHandlerTests
{
private readonly ISerializer _serializer = new SerializerManager(ProtocolVersion.V3).GetCurrentSerializer();
[Test]
public async Task Should_NotSendRequestToSecondHost_When_SecondHostDoesntHavePool()
{
var lbpCluster = new FakeLoadBalancingPolicy();
var mockResult = BuildPrepareHandler(
builder =>
{
builder.QueryOptions =
new QueryOptions()
.SetConsistencyLevel(ConsistencyLevel.LocalOne)
.SetSerialConsistencyLevel(ConsistencyLevel.LocalSerial);
builder.SocketOptions =
new SocketOptions().SetReadTimeoutMillis(10);
builder.Policies = new Cassandra.Policies(
lbpCluster,
new ConstantReconnectionPolicy(5),
new DefaultRetryPolicy(),
NoSpeculativeExecutionPolicy.Instance,
new AtomicMonotonicTimestampGenerator());
});
// mock connection send
mockResult.ConnectionFactory.OnCreate += connection =>
{
Mock.Get(connection)
.Setup(c => c.Send(It.IsAny<IRequest>()))
.Returns<IRequest>(async req =>
{
mockResult.SendResults.Enqueue(new ConnectionSendResult { Connection = connection, Request = req });
await Task.Delay(1).ConfigureAwait(false);
return new ProxyResultResponse(
ResultResponse.ResultResponseKind.Void,
new OutputPrepared(
new byte[0], new RowSetMetadata { Columns = new CqlColumn[0] }, new RowSetMetadata { Columns = new CqlColumn[0] }));
});
};
var queryPlan = mockResult.Session.InternalCluster
.GetResolvedEndpoints()
.Select(x => new Host(x.Value.First().GetHostIpEndPointWithFallback(), contactPoint: null))
.ToList();
await mockResult.Session.GetOrCreateConnectionPool(queryPlan[0], HostDistance.Local).Warmup().ConfigureAwait(false);
await mockResult.Session.GetOrCreateConnectionPool(queryPlan[2], HostDistance.Local).Warmup().ConfigureAwait(false);
var pools = mockResult.Session.GetPools().ToList();
Assert.AreEqual(2, pools.Count);
var distanceCount = Interlocked.Read(ref lbpCluster.DistanceCount);
var request = new PrepareRequest(_serializer, "TEST", null, null);
await mockResult.PrepareHandler.Prepare(
request,
mockResult.Session,
queryPlan.GetEnumerator()).ConfigureAwait(false);
var results = mockResult.SendResults.ToArray();
pools = mockResult.Session.GetPools().ToList();
Assert.AreEqual(2, pools.Count);
Assert.AreEqual(2, results.Length);
Assert.AreEqual(distanceCount + 1, Interlocked.Read(ref lbpCluster.DistanceCount), 1);
Assert.AreEqual(Interlocked.Read(ref lbpCluster.NewQueryPlanCount), 0);
Assert.AreEqual(2, mockResult.ConnectionFactory.CreatedConnections.Count);
Assert.LessOrEqual(1, mockResult.ConnectionFactory.CreatedConnections[queryPlan[0].Address].Count);
Assert.LessOrEqual(1, mockResult.ConnectionFactory.CreatedConnections[queryPlan[2].Address].Count);
// Assert that each pool contains only one connection that was called send
var poolConnections = pools.Select(p => p.Value.ConnectionsSnapshot.Intersect(results.Select(r => r.Connection))).ToList();
Assert.AreEqual(2, poolConnections.Count);
foreach (var pool in poolConnections)
{
Mock.Get(pool.Single()).Verify(c => c.Send(request), Times.Once);
}
}
[Test]
public async Task Should_NotSendRequestToSecondHost_When_SecondHostPoolDoesNotHaveConnections()
{
var lbpCluster = new FakeLoadBalancingPolicy();
var mockResult = BuildPrepareHandler(
builder =>
{
builder.QueryOptions =
new QueryOptions()
.SetConsistencyLevel(ConsistencyLevel.LocalOne)
.SetSerialConsistencyLevel(ConsistencyLevel.LocalSerial);
builder.SocketOptions =
new SocketOptions().SetReadTimeoutMillis(10);
builder.Policies = new Cassandra.Policies(
lbpCluster,
new ConstantReconnectionPolicy(5),
new DefaultRetryPolicy(),
NoSpeculativeExecutionPolicy.Instance,
new AtomicMonotonicTimestampGenerator());
});
// mock connection send
mockResult.ConnectionFactory.OnCreate += connection =>
{
Mock.Get(connection)
.Setup(c => c.Send(It.IsAny<IRequest>()))
.Returns<IRequest>(async req =>
{
mockResult.SendResults.Enqueue(new ConnectionSendResult { Connection = connection, Request = req });
await Task.Delay(1).ConfigureAwait(false);
return new ProxyResultResponse(
ResultResponse.ResultResponseKind.Void,
new OutputPrepared(
new byte[0], new RowSetMetadata { Columns = new CqlColumn[0] }, new RowSetMetadata { Columns = new CqlColumn[0] }));
});
};
var queryPlan = mockResult.Session.InternalCluster
.GetResolvedEndpoints()
.Select(x => new Host(x.Value.First().GetHostIpEndPointWithFallback(), contactPoint: null))
.ToList();
await mockResult.Session.GetOrCreateConnectionPool(queryPlan[0], HostDistance.Local).Warmup().ConfigureAwait(false);
mockResult.Session.GetOrCreateConnectionPool(queryPlan[1], HostDistance.Local);
await mockResult.Session.GetOrCreateConnectionPool(queryPlan[2], HostDistance.Local).Warmup().ConfigureAwait(false);
var pools = mockResult.Session.GetPools().ToList();
Assert.AreEqual(3, pools.Count);
var distanceCount = Interlocked.Read(ref lbpCluster.DistanceCount);
var request = new PrepareRequest(_serializer, "TEST", null, null);
await mockResult.PrepareHandler.Prepare(
request,
mockResult.Session,
queryPlan.GetEnumerator()).ConfigureAwait(false);
var results = mockResult.SendResults.ToArray();
pools = mockResult.Session.GetPools().ToList();
Assert.AreEqual(3, pools.Count);
Assert.AreEqual(2, results.Length);
Assert.AreEqual(distanceCount + 1, Interlocked.Read(ref lbpCluster.DistanceCount), 1);
Assert.AreEqual(Interlocked.Read(ref lbpCluster.NewQueryPlanCount), 0);
Assert.AreEqual(2, mockResult.ConnectionFactory.CreatedConnections.Count);
Assert.LessOrEqual(1, mockResult.ConnectionFactory.CreatedConnections[queryPlan[0].Address].Count);
Assert.LessOrEqual(1, mockResult.ConnectionFactory.CreatedConnections[queryPlan[2].Address].Count);
// Assert that each pool that contains connections contains only one connection that was called send
var poolConnections = pools.Select(p => p.Value.ConnectionsSnapshot.Intersect(results.Select(r => r.Connection))).Where(p => p.Any()).ToList();
Assert.AreEqual(2, poolConnections.Count);
foreach (var pool in poolConnections)
{
Mock.Get(pool.Single()).Verify(c => c.Send(request), Times.Once);
}
}
[Test]
public async Task Should_SendRequestToAllHosts_When_AllHostsHaveConnections()
{
var lbpCluster = new FakeLoadBalancingPolicy();
var mockResult = BuildPrepareHandler(
builder =>
{
builder.QueryOptions =
new QueryOptions()
.SetConsistencyLevel(ConsistencyLevel.LocalOne)
.SetSerialConsistencyLevel(ConsistencyLevel.LocalSerial);
builder.SocketOptions =
new SocketOptions().SetReadTimeoutMillis(10);
builder.Policies = new Cassandra.Policies(
lbpCluster,
new ConstantReconnectionPolicy(5),
new DefaultRetryPolicy(),
NoSpeculativeExecutionPolicy.Instance,
new AtomicMonotonicTimestampGenerator());
});
// mock connection send
mockResult.ConnectionFactory.OnCreate += connection =>
{
Mock.Get(connection)
.Setup(c => c.Send(It.IsAny<IRequest>()))
.Returns<IRequest>(async req =>
{
mockResult.SendResults.Enqueue(new ConnectionSendResult { Connection = connection, Request = req });
await Task.Delay(1).ConfigureAwait(false);
return new ProxyResultResponse(
ResultResponse.ResultResponseKind.Void,
new OutputPrepared(
new byte[0], new RowSetMetadata { Columns = new CqlColumn[0] }, new RowSetMetadata { Columns = new CqlColumn[0] }));
});
};
var queryPlan = mockResult.Session.InternalCluster
.GetResolvedEndpoints()
.Select(x => new Host(x.Value.First().GetHostIpEndPointWithFallback(), contactPoint: null))
.ToList();
await mockResult.Session.GetOrCreateConnectionPool(queryPlan[0], HostDistance.Local).Warmup().ConfigureAwait(false);
await mockResult.Session.GetOrCreateConnectionPool(queryPlan[1], HostDistance.Local).Warmup().ConfigureAwait(false);
await mockResult.Session.GetOrCreateConnectionPool(queryPlan[2], HostDistance.Local).Warmup().ConfigureAwait(false);
var pools = mockResult.Session.GetPools().ToList();
Assert.AreEqual(3, pools.Count);
var distanceCount = Interlocked.Read(ref lbpCluster.DistanceCount);
var request = new PrepareRequest(_serializer, "TEST", null, null);
await mockResult.PrepareHandler.Prepare(
request,
mockResult.Session,
queryPlan.GetEnumerator()).ConfigureAwait(false);
var results = mockResult.SendResults.ToArray();
pools = mockResult.Session.GetPools().ToList();
Assert.AreEqual(3, pools.Count);
Assert.AreEqual(3, results.Length);
Assert.AreEqual(distanceCount + 1, Interlocked.Read(ref lbpCluster.DistanceCount), 1);
Assert.AreEqual(Interlocked.Read(ref lbpCluster.NewQueryPlanCount), 0);
Assert.AreEqual(3, mockResult.ConnectionFactory.CreatedConnections.Count);
Assert.LessOrEqual(1, mockResult.ConnectionFactory.CreatedConnections[queryPlan[0].Address].Count);
Assert.LessOrEqual(1, mockResult.ConnectionFactory.CreatedConnections[queryPlan[1].Address].Count);
Assert.LessOrEqual(1, mockResult.ConnectionFactory.CreatedConnections[queryPlan[2].Address].Count);
// Assert that each pool contains only one connection that was called send
var poolConnections = pools.Select(p => p.Value.ConnectionsSnapshot.Intersect(results.Select(r => r.Connection))).ToList();
Assert.AreEqual(3, poolConnections.Count);
foreach (var pool in poolConnections)
{
Mock.Get(pool.Single()).Verify(c => c.Send(request), Times.Once);
}
}
[Test]
public async Task Should_SendRequestToAllHosts_When_AllHostsHaveConnectionsButFirstHostDoesntHavePool()
{
var lbpCluster = new FakeLoadBalancingPolicy();
var mockResult = BuildPrepareHandler(
builder =>
{
builder.QueryOptions =
new QueryOptions()
.SetConsistencyLevel(ConsistencyLevel.LocalOne)
.SetSerialConsistencyLevel(ConsistencyLevel.LocalSerial);
builder.SocketOptions =
new SocketOptions().SetReadTimeoutMillis(10);
builder.Policies = new Cassandra.Policies(
lbpCluster,
new ConstantReconnectionPolicy(5),
new DefaultRetryPolicy(),
NoSpeculativeExecutionPolicy.Instance,
new AtomicMonotonicTimestampGenerator());
});
// mock connection send
mockResult.ConnectionFactory.OnCreate += connection =>
{
Mock.Get(connection)
.Setup(c => c.Send(It.IsAny<IRequest>()))
.Returns<IRequest>(async req =>
{
mockResult.SendResults.Enqueue(new ConnectionSendResult { Connection = connection, Request = req });
await Task.Delay(1).ConfigureAwait(false);
return new ProxyResultResponse(
ResultResponse.ResultResponseKind.Void,
new OutputPrepared(
new byte[0], new RowSetMetadata { Columns = new CqlColumn[0] }, new RowSetMetadata { Columns = new CqlColumn[0] }));
});
};
var queryPlan = mockResult.Session.InternalCluster
.GetResolvedEndpoints()
.Select(x => new Host(x.Value.First().GetHostIpEndPointWithFallback(), contactPoint: null))
.ToList();
await mockResult.Session.GetOrCreateConnectionPool(queryPlan[1], HostDistance.Local).Warmup().ConfigureAwait(false);
await mockResult.Session.GetOrCreateConnectionPool(queryPlan[2], HostDistance.Local).Warmup().ConfigureAwait(false);
var pools = mockResult.Session.GetPools().ToList();
Assert.AreEqual(2, pools.Count);
var distanceCount = Interlocked.Read(ref lbpCluster.DistanceCount);
var request = new PrepareRequest(_serializer, "TEST", null, null);
await mockResult.PrepareHandler.Prepare(
request,
mockResult.Session,
queryPlan.GetEnumerator()).ConfigureAwait(false);
var results = mockResult.SendResults.ToArray();
pools = mockResult.Session.GetPools().ToList();
Assert.AreEqual(3, pools.Count);
Assert.AreEqual(3, results.Length);
Assert.AreEqual(distanceCount + 1, Interlocked.Read(ref lbpCluster.DistanceCount), 1);
Assert.AreEqual(Interlocked.Read(ref lbpCluster.NewQueryPlanCount), 0);
Assert.AreEqual(3, mockResult.ConnectionFactory.CreatedConnections.Count);
Assert.LessOrEqual(1, mockResult.ConnectionFactory.CreatedConnections[queryPlan[0].Address].Count);
Assert.LessOrEqual(1, mockResult.ConnectionFactory.CreatedConnections[queryPlan[1].Address].Count);
Assert.LessOrEqual(1, mockResult.ConnectionFactory.CreatedConnections[queryPlan[2].Address].Count);
// Assert that each pool contains only one connection that was called send
var poolConnections = pools.Select(p => p.Value.ConnectionsSnapshot.Intersect(results.Select(r => r.Connection))).ToList();
Assert.AreEqual(3, poolConnections.Count);
foreach (var pool in poolConnections)
{
Mock.Get(pool.Single()).Verify(c => c.Send(request), Times.Once);
}
}
[Test]
public async Task Should_SendRequestToAllHosts_When_AllHostsHaveConnectionsButFirstHostPoolDoesntHaveConnections()
{
var lbpCluster = new FakeLoadBalancingPolicy();
var mockResult = BuildPrepareHandler(
builder =>
{
builder.QueryOptions =
new QueryOptions()
.SetConsistencyLevel(ConsistencyLevel.LocalOne)
.SetSerialConsistencyLevel(ConsistencyLevel.LocalSerial);
builder.SocketOptions =
new SocketOptions().SetReadTimeoutMillis(10);
builder.Policies = new Cassandra.Policies(
lbpCluster,
new ConstantReconnectionPolicy(5),
new DefaultRetryPolicy(),
NoSpeculativeExecutionPolicy.Instance,
new AtomicMonotonicTimestampGenerator());
});
// mock connection send
mockResult.ConnectionFactory.OnCreate += connection =>
{
Mock.Get(connection)
.Setup(c => c.Send(It.IsAny<IRequest>()))
.Returns<IRequest>(async req =>
{
mockResult.SendResults.Enqueue(new ConnectionSendResult { Connection = connection, Request = req });
await Task.Delay(1).ConfigureAwait(false);
return new ProxyResultResponse(
ResultResponse.ResultResponseKind.Void,
new OutputPrepared(
new byte[0], new RowSetMetadata { Columns = new CqlColumn[0] }, new RowSetMetadata { Columns = new CqlColumn[0] }));
});
};
var queryPlan = mockResult.Session.InternalCluster
.GetResolvedEndpoints()
.Select(x => new Host(x.Value.First().GetHostIpEndPointWithFallback(), contactPoint: null))
.ToList();
await mockResult.Session.GetOrCreateConnectionPool(queryPlan[1], HostDistance.Local).Warmup().ConfigureAwait(false);
await mockResult.Session.GetOrCreateConnectionPool(queryPlan[2], HostDistance.Local).Warmup().ConfigureAwait(false);
var pools = mockResult.Session.GetPools().ToList();
Assert.AreEqual(2, pools.Count);
var distanceCount = Interlocked.Read(ref lbpCluster.DistanceCount);
var request = new PrepareRequest(_serializer, "TEST", null, null);
await mockResult.PrepareHandler.Prepare(
request,
mockResult.Session,
queryPlan.GetEnumerator()).ConfigureAwait(false);
var results = mockResult.SendResults.ToArray();
pools = mockResult.Session.GetPools().ToList();
Assert.AreEqual(3, pools.Count);
Assert.AreEqual(3, results.Length);
Assert.AreEqual(distanceCount + 1, Interlocked.Read(ref lbpCluster.DistanceCount), 1);
Assert.AreEqual(Interlocked.Read(ref lbpCluster.NewQueryPlanCount), 0);
Assert.AreEqual(3, mockResult.ConnectionFactory.CreatedConnections.Count);
Assert.LessOrEqual(1, mockResult.ConnectionFactory.CreatedConnections[queryPlan[0].Address].Count);
Assert.LessOrEqual(1, mockResult.ConnectionFactory.CreatedConnections[queryPlan[1].Address].Count);
Assert.LessOrEqual(1, mockResult.ConnectionFactory.CreatedConnections[queryPlan[2].Address].Count);
// Assert that each pool contains only one connection that was called send
var poolConnections = pools.Select(p => p.Value.ConnectionsSnapshot.Intersect(results.Select(r => r.Connection))).ToList();
Assert.AreEqual(3, poolConnections.Count);
foreach (var pool in poolConnections)
{
Mock.Get(pool.Single()).Verify(c => c.Send(request), Times.Once);
}
}
[Test]
public async Task Should_SendRequestToFirstHostOnly_When_PrepareOnAllHostsIsFalseAndAllHostsHaveConnectionsButFirstHostPoolDoesntHaveConnections()
{
var lbpCluster = new FakeLoadBalancingPolicy();
var mockResult = BuildPrepareHandler(
builder =>
{
builder.QueryOptions =
new QueryOptions()
.SetConsistencyLevel(ConsistencyLevel.LocalOne)
.SetSerialConsistencyLevel(ConsistencyLevel.LocalSerial)
.SetPrepareOnAllHosts(false);
builder.SocketOptions =
new SocketOptions().SetReadTimeoutMillis(10);
builder.Policies = new Cassandra.Policies(
lbpCluster,
new ConstantReconnectionPolicy(5),
new DefaultRetryPolicy(),
NoSpeculativeExecutionPolicy.Instance,
new AtomicMonotonicTimestampGenerator());
});
// mock connection send
mockResult.ConnectionFactory.OnCreate += connection =>
{
Mock.Get(connection)
.Setup(c => c.Send(It.IsAny<IRequest>()))
.Returns<IRequest>(async req =>
{
mockResult.SendResults.Enqueue(new ConnectionSendResult { Connection = connection, Request = req });
await Task.Delay(1).ConfigureAwait(false);
return new ProxyResultResponse(
ResultResponse.ResultResponseKind.Void,
new OutputPrepared(
new byte[0], new RowSetMetadata { Columns = new CqlColumn[0] }, new RowSetMetadata { Columns = new CqlColumn[0] }));
});
};
var queryPlan = mockResult.Session.InternalCluster
.GetResolvedEndpoints()
.Select(x => new Host(x.Value.First().GetHostIpEndPointWithFallback(), contactPoint: null))
.ToList();
await mockResult.Session.GetOrCreateConnectionPool(queryPlan[1], HostDistance.Local).Warmup().ConfigureAwait(false);
await mockResult.Session.GetOrCreateConnectionPool(queryPlan[2], HostDistance.Local).Warmup().ConfigureAwait(false);
var pools = mockResult.Session.GetPools().ToList();
Assert.AreEqual(2, pools.Count);
var distanceCount = Interlocked.Read(ref lbpCluster.DistanceCount);
var request = new PrepareRequest(_serializer, "TEST", null, null);
await mockResult.PrepareHandler.Prepare(
request,
mockResult.Session,
queryPlan.GetEnumerator()).ConfigureAwait(false);
var results = mockResult.SendResults.ToArray();
pools = mockResult.Session.GetPools().ToList();
Assert.AreEqual(3, pools.Count);
Assert.AreEqual(1, results.Length);
Assert.AreEqual(distanceCount + 1, Interlocked.Read(ref lbpCluster.DistanceCount), 1);
Assert.AreEqual(Interlocked.Read(ref lbpCluster.NewQueryPlanCount), 0);
Assert.AreEqual(3, mockResult.ConnectionFactory.CreatedConnections.Count);
Assert.LessOrEqual(1, mockResult.ConnectionFactory.CreatedConnections[queryPlan[0].Address].Count);
Assert.LessOrEqual(1, mockResult.ConnectionFactory.CreatedConnections[queryPlan[1].Address].Count);
Assert.LessOrEqual(1, mockResult.ConnectionFactory.CreatedConnections[queryPlan[2].Address].Count);
// Assert that pool of first host contains only one connection that was called send
var poolConnections =
pools
.Select(p => p.Value.ConnectionsSnapshot.Intersect(results.Select(r => r.Connection)))
.Where(p => mockResult.ConnectionFactory.CreatedConnections[queryPlan[0].Address].Contains(p.SingleOrDefault()))
.ToList();
Assert.AreEqual(1, poolConnections.Count);
foreach (var pool in poolConnections)
{
Mock.Get(pool.Single()).Verify(c => c.Send(request), Times.Once);
}
}
private PrepareHandlerMockResult BuildPrepareHandler(Action<TestConfigurationBuilder> configBuilderAct)
{
var factory = new FakeConnectionFactory(MockConnection);
// create config
var configBuilder = new TestConfigurationBuilder
{
ControlConnectionFactory = new FakeControlConnectionFactory(),
ConnectionFactory = factory,
Policies = new Cassandra.Policies(new RoundRobinPolicy(), new ConstantReconnectionPolicy(100), new DefaultRetryPolicy())
};
configBuilderAct(configBuilder);
var config = configBuilder.Build();
var initializerMock = Mock.Of<IInitializer>();
Mock.Get(initializerMock).Setup(i => i.ContactPoints).Returns(new List<IPEndPoint>
{
new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9042),
new IPEndPoint(IPAddress.Parse("127.0.0.2"), 9042),
new IPEndPoint(IPAddress.Parse("127.0.0.3"), 9042)
});
Mock.Get(initializerMock).Setup(i => i.GetConfiguration()).Returns(config);
// create cluster
var cluster = Cluster.BuildFrom(initializerMock, new List<string>());
cluster.Connect();
factory.CreatedConnections.Clear();
// create session
var session = new Session(cluster, config, null, SerializerManager.Default, null);
// create prepare handler
var prepareHandler = new PrepareHandler(new SerializerManager(ProtocolVersion.V3), cluster, new ReprepareHandler());
// create mock result object
var mockResult = new PrepareHandlerMockResult(prepareHandler, session, factory);
return mockResult;
}
private IConnection MockConnection(IPEndPoint endpoint)
{
var connection = Mock.Of<IConnection>();
Mock.Get(connection)
.SetupGet(c => c.EndPoint)
.Returns(new ConnectionEndPoint(endpoint, new ServerNameResolver(new ProtocolOptions()), null));
return connection;
}
private class ConnectionSendResult
{
public IRequest Request { get; set; }
public IConnection Connection { get; set; }
}
private class PrepareHandlerMockResult
{
public PrepareHandlerMockResult(PrepareHandler prepareHandler, IInternalSession session, FakeConnectionFactory factory)
{
PrepareHandler = prepareHandler;
Session = session;
ConnectionFactory = factory;
}
public PrepareHandler PrepareHandler { get; }
public ConcurrentQueue<ConnectionSendResult> SendResults { get; } = new ConcurrentQueue<ConnectionSendResult>();
public IInternalSession Session { get; }
public FakeConnectionFactory ConnectionFactory { get; }
}
private class FakeLoadBalancingPolicy : ILoadBalancingPolicy
{
public long DistanceCount;
public long NewQueryPlanCount;
public void Initialize(ICluster cluster)
{
}
public HostDistance Distance(Host host)
{
Interlocked.Increment(ref DistanceCount);
return HostDistance.Local;
}
public IEnumerable<Host> NewQueryPlan(string keyspace, IStatement query)
{
Interlocked.Increment(ref NewQueryPlanCount);
throw new NotImplementedException();
}
}
}
}
| |
// 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.Threading.Tasks;
using Xunit;
namespace System.IO.Compression.Tests
{
public class GZipStreamTests
{
static String gzTestFile(String fileName) { return Path.Combine("GZTestData", fileName); }
[Fact]
public void BaseStream1()
{
var writeStream = new MemoryStream();
var zip = new GZipStream(writeStream, CompressionMode.Compress);
Assert.Same(zip.BaseStream, writeStream);
writeStream.Dispose();
}
[Fact]
public void BaseStream2()
{
var ms = new MemoryStream();
var zip = new GZipStream(ms, CompressionMode.Decompress);
Assert.Same(zip.BaseStream, ms);
ms.Dispose();
}
[Fact]
public async Task ModifyBaseStream()
{
var ms = await LocalMemoryStream.readAppFileAsync(gzTestFile("GZTestDocument.txt.gz"));
var zip = new GZipStream(ms, CompressionMode.Decompress);
int size = 1024;
Byte[] bytes = new Byte[size];
zip.BaseStream.Read(bytes, 0, size); // This will throw if the underlying stream is not writeable as expected
}
[Fact]
public void DecompressCanRead()
{
var ms = new MemoryStream();
var zip = new GZipStream(ms, CompressionMode.Decompress);
Assert.True(zip.CanRead, "GZipStream not CanRead in Decompress");
zip.Dispose();
Assert.False(zip.CanRead, "GZipStream CanRead after dispose in Decompress");
}
[Fact]
public void CompressCanWrite()
{
var ms = new MemoryStream();
var zip = new GZipStream(ms, CompressionMode.Compress);
Assert.True(zip.CanWrite, "GZipStream not CanWrite with CompressionMode.Compress");
zip.Dispose();
Assert.False(zip.CanWrite, "GZipStream CanWrite after dispose");
}
[Fact]
public void CanDisposeBaseStream()
{
var ms = new MemoryStream();
var zip = new GZipStream(ms, CompressionMode.Compress);
ms.Dispose(); // This would throw if this was invalid
}
[Fact]
public void CanDisposeGZipStream()
{
var ms = new MemoryStream();
var zip = new GZipStream(ms, CompressionMode.Compress);
zip.Dispose();
Assert.Null(zip.BaseStream);
zip.Dispose(); // Should be a no-op
}
[Fact]
public async Task CanReadBaseStreamAfterDispose()
{
var ms = await LocalMemoryStream.readAppFileAsync(gzTestFile("GZTestDocument.txt.gz"));
var zip = new GZipStream(ms, CompressionMode.Decompress, true);
var baseStream = zip.BaseStream;
zip.Dispose();
int size = 1024;
Byte[] bytes = new Byte[size];
baseStream.Read(bytes, 0, size); // This will throw if the underlying stream is not writeable as expected
}
[Fact]
public async Task DecompressWorks()
{
var compareStream = await LocalMemoryStream.readAppFileAsync(gzTestFile("GZTestDocument.txt"));
var gzStream = await LocalMemoryStream.readAppFileAsync(gzTestFile("GZTestDocument.txt.gz"));
await DecompressAsync(compareStream, gzStream);
}
[Fact]
public async Task DecompressWorksWithDoc()
{
var compareStream = await LocalMemoryStream.readAppFileAsync(gzTestFile("GZTestDocument.doc"));
var gzStream = await LocalMemoryStream.readAppFileAsync(gzTestFile("GZTestDocument.doc.gz"));
await DecompressAsync(compareStream, gzStream);
}
[Fact]
public async Task DecompressWorksWithDocx()
{
var compareStream = await LocalMemoryStream.readAppFileAsync(gzTestFile("GZTestDocument.docx"));
var gzStream = await LocalMemoryStream.readAppFileAsync(gzTestFile("GZTestDocument.docx.gz"));
await DecompressAsync(compareStream, gzStream);
}
[Fact]
public async Task DecompressWorksWithPdf()
{
var compareStream = await LocalMemoryStream.readAppFileAsync(gzTestFile("GZTestDocument.pdf"));
var gzStream = await LocalMemoryStream.readAppFileAsync(gzTestFile("GZTestDocument.pdf.gz"));
await DecompressAsync(compareStream, gzStream);
}
// Making this async since regular read/write are tested below
private static async Task DecompressAsync(MemoryStream compareStream, MemoryStream gzStream)
{
var ms = new MemoryStream();
var zip = new GZipStream(gzStream, CompressionMode.Decompress);
var GZipStream = new MemoryStream();
await zip.CopyToAsync(GZipStream);
GZipStream.Position = 0;
compareStream.Position = 0;
byte[] compareArray = compareStream.ToArray();
byte[] writtenArray = GZipStream.ToArray();
Assert.Equal(compareArray.Length, writtenArray.Length);
for (int i = 0; i < compareArray.Length; i++)
{
Assert.Equal(compareArray[i], writtenArray[i]);
}
}
[Fact]
public void NullBaseStreamThrows()
{
Assert.Throws<ArgumentNullException>(() =>
{
var deflate = new GZipStream(null, CompressionMode.Decompress);
});
Assert.Throws<ArgumentNullException>(() =>
{
var deflate = new GZipStream(null, CompressionMode.Compress);
});
}
[Fact]
public void DisposedBaseStreamThrows()
{
var ms = new MemoryStream();
ms.Dispose();
Assert.Throws<ArgumentException>(() =>
{
var deflate = new GZipStream(ms, CompressionMode.Decompress);
});
Assert.Throws<ArgumentException>(() =>
{
var deflate = new GZipStream(ms, CompressionMode.Compress);
});
}
[Fact]
public void ReadOnlyStreamThrowsOnCompress()
{
var ms = new LocalMemoryStream();
ms.SetCanWrite(false);
Assert.Throws<ArgumentException>(() =>
{
var gzip = new GZipStream(ms, CompressionMode.Compress);
});
}
[Fact]
public void WriteOnlyStreamThrowsOnDecompress()
{
var ms = new LocalMemoryStream();
ms.SetCanRead(false);
Assert.Throws<ArgumentException>(() =>
{
var gzip = new GZipStream(ms, CompressionMode.Decompress);
});
}
[Fact]
public void CopyToAsyncArgumentValidation()
{
using (GZipStream gs = new GZipStream(new MemoryStream(), CompressionMode.Decompress))
{
Assert.Throws<ArgumentNullException>("destination", () => { gs.CopyToAsync(null); });
Assert.Throws<ArgumentOutOfRangeException>("bufferSize", () => { gs.CopyToAsync(new MemoryStream(), 0); });
Assert.Throws<NotSupportedException>(() => { gs.CopyToAsync(new MemoryStream(new byte[1], writable: false)); });
gs.Dispose();
Assert.Throws<ObjectDisposedException>(() => { gs.CopyToAsync(new MemoryStream()); });
}
using (GZipStream gs = new GZipStream(new MemoryStream(), CompressionMode.Compress))
{
Assert.Throws<NotSupportedException>(() => { gs.CopyToAsync(new MemoryStream()); });
}
}
[Fact]
public void TestCtors()
{
CompressionLevel[] legalValues = new CompressionLevel[] { CompressionLevel.Optimal, CompressionLevel.Fastest, CompressionLevel.NoCompression };
foreach (CompressionLevel level in legalValues)
{
bool[] boolValues = new bool[] { true, false };
foreach (bool remainsOpen in boolValues)
{
TestCtor(level, remainsOpen);
}
}
}
[Fact]
public void TestLevelOptimial()
{
TestCtor(CompressionLevel.Optimal);
}
[Fact]
public void TestLevelNoCompression()
{
TestCtor(CompressionLevel.NoCompression);
}
[Fact]
public void TestLevelFastest()
{
TestCtor(CompressionLevel.Fastest);
}
private static void TestCtor(CompressionLevel level, bool? leaveOpen = null)
{
//Create the GZipStream
int _bufferSize = 1024;
var bytes = new Byte[_bufferSize];
var baseStream = new MemoryStream(bytes, true);
GZipStream ds;
if (leaveOpen == null)
{
ds = new GZipStream(baseStream, level);
}
else
{
ds = new GZipStream(baseStream, level, leaveOpen ?? false);
}
//Write some data and Close the stream
String strData = "Test Data";
var encoding = Encoding.UTF8;
Byte[] data = encoding.GetBytes(strData);
ds.Write(data, 0, data.Length);
ds.Flush();
ds.Dispose();
if (leaveOpen != true)
{
//Check that Close has really closed the underlying stream
Assert.Throws<ObjectDisposedException>(() => { baseStream.Write(bytes, 0, bytes.Length); });
}
//Read the data
Byte[] data2 = new Byte[_bufferSize];
baseStream = new MemoryStream(bytes, false);
ds = new GZipStream(baseStream, CompressionMode.Decompress);
int size = ds.Read(data2, 0, _bufferSize - 5);
//Verify the data roundtripped
for (int i = 0; i < size + 5; i++)
{
if (i < data.Length)
{
Assert.Equal(data[i], data2[i]);
}
else
{
Assert.Equal(data2[i], (byte)0);
}
}
}
[Fact]
public async Task Flush()
{
var ms = new MemoryStream();
var ds = new GZipStream(ms, CompressionMode.Compress);
ds.Flush();
await ds.FlushAsync();
// Just ensuring Flush doesn't throw
}
[Fact]
public void FlushFailsAfterDispose()
{
var ms = new MemoryStream();
var ds = new GZipStream(ms, CompressionMode.Compress);
ds.Dispose();
Assert.Throws<ObjectDisposedException>(() => { ds.Flush(); });
}
[Fact]
public async Task FlushAsyncFailsAfterDispose()
{
var ms = new MemoryStream();
var ds = new GZipStream(ms, CompressionMode.Compress);
ds.Dispose();
await Assert.ThrowsAsync<ObjectDisposedException>(async () =>
{
await ds.FlushAsync();
});
}
[Fact]
public void TestSeekMethodsDecompress()
{
var ms = new MemoryStream();
var zip = new GZipStream(ms, CompressionMode.Decompress);
Assert.False(zip.CanSeek);
Assert.Throws<NotSupportedException>(delegate { long value = zip.Length; });
Assert.Throws<NotSupportedException>(delegate { long value = zip.Position; });
Assert.Throws<NotSupportedException>(delegate { zip.Position = 100L; });
Assert.Throws<NotSupportedException>(delegate { zip.SetLength(100L); });
Assert.Throws<NotSupportedException>(delegate { zip.Seek(100L, SeekOrigin.Begin); });
zip.Dispose();
Assert.False(zip.CanSeek);
}
[Fact]
public void TestSeekMethodsCompress()
{
var ms = new MemoryStream();
var zip = new GZipStream(ms, CompressionMode.Compress);
Assert.False(zip.CanSeek);
Assert.Throws<NotSupportedException>(delegate { long value = zip.Length; });
Assert.Throws<NotSupportedException>(delegate { long value = zip.Position; });
Assert.Throws<NotSupportedException>(delegate { zip.Position = 100L; });
Assert.Throws<NotSupportedException>(delegate { zip.SetLength(100L); });
Assert.Throws<NotSupportedException>(delegate { zip.Seek(100L, SeekOrigin.Begin); });
zip.Dispose();
Assert.False(zip.CanSeek);
}
}
}
| |
using System;
using System.Collections;
using Server.Network;
using Server.Mobiles;
using Server.Items;
using Server.Gumps;
namespace Server.Items.Crops
{
public class FlaxSeed : BaseCrop
{
// return true to allow planting on Dirt Item (ItemID 0x32C9)
// See CropHelper.cs for other overriddable types
public override bool CanGrowGarden { get { return true; } }
[Constructable]
public FlaxSeed()
: this(1)
{
}
[Constructable]
public FlaxSeed(int amount)
: base(0xF27)
{
Stackable = true;
Weight = .5;
Hue = 0x5E2;
Movable = true;
Amount = amount;
Name = AgriTxt.Seed + " de Lin";
}
public override void OnDoubleClick(Mobile from)
{
if (from.Mounted && !CropHelper.CanWorkMounted)
{
from.SendMessage(AgriTxt.CannotWorkMounted);
return;
}
Point3D m_pnt = from.Location;
Map m_map = from.Map;
if (!IsChildOf(from.Backpack))
{
from.SendLocalizedMessage(1042010); //You must have the object in your backpack to use it.
return;
}
else if (!CropHelper.CheckCanGrow(this, m_map, m_pnt.X, m_pnt.Y))
{
from.SendMessage(AgriTxt.CannotGrowHere);
return;
}
//check for BaseCrop on this tile
ArrayList cropshere = CropHelper.CheckCrop(m_pnt, m_map, 0);
if (cropshere.Count > 0)
{
from.SendMessage(AgriTxt.AlreadyCrop);
return;
}
//check for over planting prohibt if 4 maybe 3 neighboring crops
ArrayList cropsnear = CropHelper.CheckCrop(m_pnt, m_map, 1);
if ((cropsnear.Count > 3) || ((cropsnear.Count == 3) && Utility.RandomBool()))
{
from.SendMessage(AgriTxt.TooMuchCrops);
return;
}
if (this.BumpZ) ++m_pnt.Z;
if (!from.Mounted)
from.Animate(32, 5, 1, true, false, 0); // Bow
from.SendMessage(AgriTxt.CropPlanted);
this.Consume();
Item item = new FlaxSeedling(from);
item.Location = m_pnt;
item.Map = m_map;
}
public FlaxSeed(Serial serial)
: base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0);
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
public class FlaxSeedling : BaseCrop
{
private static Mobile m_sower;
public Timer thisTimer;
[CommandProperty(AccessLevel.GameMaster)]
public Mobile Sower { get { return m_sower; } set { m_sower = value; } }
[Constructable]
public FlaxSeedling(Mobile sower)
: base(0x1A99)
{
Movable = false;
Name = AgriTxt.Seedling + " de lin";
m_sower = sower;
init(this);
}
public static void init(FlaxSeedling plant)
{
plant.thisTimer = new CropHelper.GrowTimer(plant, typeof(FlaxCrop), plant.Sower);
plant.thisTimer.Start();
}
public override void OnDoubleClick(Mobile from)
{
if (from.Mounted && !CropHelper.CanWorkMounted)
{
from.SendMessage(AgriTxt.CannotWorkMounted);
return;
}
if ((Utility.RandomDouble() <= .25) && !(m_sower.AccessLevel > AccessLevel.Counselor))
{ //25% Chance
from.SendMessage(AgriTxt.PickCrop);
thisTimer.Stop();
this.Delete();
}
else from.SendMessage(AgriTxt.TooYoungCrop);
}
public FlaxSeedling(Serial serial)
: base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0);
writer.Write(m_sower);
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
m_sower = reader.ReadMobile();
init(this);
}
}
public class FlaxCrop : BaseCrop
{
private const int max = 10;
private int fullGraphic;
private int pickedGraphic;
private DateTime lastpicked;
private Mobile m_sower;
private int m_yield;
public Timer regrowTimer;
private DateTime m_lastvisit;
[CommandProperty(AccessLevel.GameMaster)]
public DateTime LastSowerVisit { get { return m_lastvisit; } }
[CommandProperty(AccessLevel.GameMaster)] // debuging
public bool Growing { get { return regrowTimer.Running; } }
[CommandProperty(AccessLevel.GameMaster)]
public Mobile Sower { get { return m_sower; } set { m_sower = value; } }
[CommandProperty(AccessLevel.GameMaster)]
public int Yield { get { return m_yield; } set { m_yield = value; } }
public int Capacity { get { return max; } }
public int FullGraphic { get { return fullGraphic; } set { fullGraphic = value; } }
public int PickGraphic { get { return pickedGraphic; } set { pickedGraphic = value; } }
public DateTime LastPick { get { return lastpicked; } set { lastpicked = value; } }
[Constructable]
public FlaxCrop(Mobile sower)
: base(0x1A9A)
{
Movable = false;
Name = "Fleurs de Lin";
m_sower = sower;
m_lastvisit = DateTime.Now;
init(this, false);
}
public static void init(FlaxCrop plant, bool full)
{
plant.PickGraphic = (0x1A9A);
plant.FullGraphic = (0x1A9B);
plant.LastPick = DateTime.Now;
plant.regrowTimer = new CropTimer(plant);
if (full)
{
plant.Yield = plant.Capacity;
((Item)plant).ItemID = plant.FullGraphic;
}
else
{
plant.Yield = 0;
((Item)plant).ItemID = plant.PickGraphic;
plant.regrowTimer.Start();
}
}
public void UpRoot(Mobile from)
{
from.SendMessage(AgriTxt.WitherCrop);
if (regrowTimer.Running)
regrowTimer.Stop();
this.Delete();
}
public override void OnDoubleClick(Mobile from)
{
if (m_sower == null || m_sower.Deleted)
m_sower = from;
if (from.Mounted && !CropHelper.CanWorkMounted)
{
from.SendMessage(AgriTxt.CannotWorkMounted);
return;
}
if (DateTime.Now > lastpicked.AddSeconds(3)) // 3 seconds between picking
{
lastpicked = DateTime.Now;
int lumberValue = (int)from.Skills[SkillName.Lumberjacking].Value / 5;
if (lumberValue < 2)
{
from.SendMessage(AgriTxt.DunnoHowTo);
return;
}
if (from.InRange(this.GetWorldLocation(), 2))
{
if (m_yield < 1)
{
from.SendMessage(AgriTxt.NoCrop);
if (PlayerCanDestroy && !(m_sower.AccessLevel > AccessLevel.Counselor))
{
UpRootGump g = new UpRootGump(from, this);
from.SendGump(g);
}
}
else //check skill and sower
{
from.Direction = from.GetDirectionTo(this);
from.Animate(from.Mounted ? 29 : 32, 5, 1, true, false, 0);
if (from == m_sower)
{
lumberValue *= 2;
m_lastvisit = DateTime.Now;
}
if (lumberValue > m_yield)
lumberValue = m_yield + 1;
int pick = Utility.Random(lumberValue);
if (pick == 0)
{
from.SendMessage(AgriTxt.ZeroPicked);
return;
}
m_yield -= pick;
from.SendMessage(AgriTxt.YouPick + " {0} fleur{1} de lin!", pick, (pick == 1 ? "" : "s"));
//PublicOverheadMessage( MessageType.Regular, 0x3BD, false, string.Format( "{0}", m_yield ));
((Item)this).ItemID = pickedGraphic;
Flax crop = new Flax(pick);
from.AddToBackpack(crop);
if (SowerPickTime != TimeSpan.Zero && m_lastvisit + SowerPickTime < DateTime.Now && !(m_sower.AccessLevel > AccessLevel.Counselor))
{
this.UpRoot(from);
return;
}
if (!regrowTimer.Running)
{
regrowTimer.Start();
}
}
}
else
{
from.SendMessage(AgriTxt.TooFar);
}
}
}
private class CropTimer : Timer
{
private FlaxCrop i_plant;
public CropTimer(FlaxCrop plant)
: base(TimeSpan.FromSeconds(600), TimeSpan.FromSeconds(15))
{
Priority = TimerPriority.OneSecond;
i_plant = plant;
}
protected override void OnTick()
{
if ((i_plant != null) && (!i_plant.Deleted))
{
int current = i_plant.Yield;
if (++current >= i_plant.Capacity)
{
current = i_plant.Capacity;
((Item)i_plant).ItemID = i_plant.FullGraphic;
Stop();
}
else if (current <= 0)
current = 1;
i_plant.Yield = current;
//i_plant.PublicOverheadMessage( MessageType.Regular, 0x22, false, string.Format( "{0}", current ));
}
else Stop();
}
}
public FlaxCrop(Serial serial)
: base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)1);
writer.Write(m_lastvisit);
writer.Write(m_sower);
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
switch (version)
{
case 1:
{
m_lastvisit = reader.ReadDateTime();
goto case 0;
}
case 0:
{
m_sower = reader.ReadMobile();
break;
}
}
if (version == 0)
m_lastvisit = DateTime.Now;
init(this, true);
}
}
}
| |
// <copyright file="TFQMR.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
//
// Copyright (c) 2009-2013 Math.NET
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
using System;
using MathNet.Numerics.LinearAlgebra.Solvers;
using MathNet.Numerics.Properties;
namespace MathNet.Numerics.LinearAlgebra.Complex.Solvers
{
#if NOSYSNUMERICS
using Complex = Numerics.Complex;
#else
using Complex = System.Numerics.Complex;
#endif
/// <summary>
/// A Transpose Free Quasi-Minimal Residual (TFQMR) iterative matrix solver.
/// </summary>
/// <remarks>
/// <para>
/// The TFQMR algorithm was taken from: <br/>
/// Iterative methods for sparse linear systems.
/// <br/>
/// Yousef Saad
/// <br/>
/// Algorithm is described in Chapter 7, section 7.4.3, page 219
/// </para>
/// <para>
/// The example code below provides an indication of the possible use of the
/// solver.
/// </para>
/// </remarks>
public sealed class TFQMR : IIterativeSolver<Complex>
{
/// <summary>
/// Calculates the <c>true</c> residual of the matrix equation Ax = b according to: residual = b - Ax
/// </summary>
/// <param name="matrix">Instance of the <see cref="Matrix"/> A.</param>
/// <param name="residual">Residual values in <see cref="Vector"/>.</param>
/// <param name="x">Instance of the <see cref="Vector"/> x.</param>
/// <param name="b">Instance of the <see cref="Vector"/> b.</param>
static void CalculateTrueResidual(Matrix<Complex> matrix, Vector<Complex> residual, Vector<Complex> x, Vector<Complex> b)
{
// -Ax = residual
matrix.Multiply(x, residual);
residual.Multiply(-1, residual);
// residual + b
residual.Add(b, residual);
}
/// <summary>
/// Is <paramref name="number"/> even?
/// </summary>
/// <param name="number">Number to check</param>
/// <returns><c>true</c> if <paramref name="number"/> even, otherwise <c>false</c></returns>
static bool IsEven(int number)
{
return number % 2 == 0;
}
/// <summary>
/// Solves the matrix equation Ax = b, where A is the coefficient matrix, b is the
/// solution vector and x is the unknown vector.
/// </summary>
/// <param name="matrix">The coefficient matrix, <c>A</c>.</param>
/// <param name="input">The solution vector, <c>b</c></param>
/// <param name="result">The result vector, <c>x</c></param>
/// <param name="iterator">The iterator to use to control when to stop iterating.</param>
/// <param name="preconditioner">The preconditioner to use for approximations.</param>
public void Solve(Matrix<Complex> matrix, Vector<Complex> input, Vector<Complex> result, Iterator<Complex> iterator, IPreconditioner<Complex> preconditioner)
{
if (matrix.RowCount != matrix.ColumnCount)
{
throw new ArgumentException(Resources.ArgumentMatrixSquare, "matrix");
}
if (input.Count != matrix.RowCount || result.Count != input.Count)
{
throw Matrix.DimensionsDontMatch<ArgumentException>(matrix, input, result);
}
if (iterator == null)
{
iterator = new Iterator<Complex>();
}
if (preconditioner == null)
{
preconditioner = new UnitPreconditioner<Complex>();
}
preconditioner.Initialize(matrix);
var d = new DenseVector(input.Count);
var r = DenseVector.OfVector(input);
var uodd = new DenseVector(input.Count);
var ueven = new DenseVector(input.Count);
var v = new DenseVector(input.Count);
var pseudoResiduals = DenseVector.OfVector(input);
var x = new DenseVector(input.Count);
var yodd = new DenseVector(input.Count);
var yeven = DenseVector.OfVector(input);
// Temp vectors
var temp = new DenseVector(input.Count);
var temp1 = new DenseVector(input.Count);
var temp2 = new DenseVector(input.Count);
// Define the scalars
Complex alpha = 0;
Complex eta = 0;
double theta = 0;
// Initialize
var tau = input.L2Norm();
Complex rho = tau*tau;
// Calculate the initial values for v
// M temp = yEven
preconditioner.Approximate(yeven, temp);
// v = A temp
matrix.Multiply(temp, v);
// Set uOdd
v.CopyTo(ueven);
// Start the iteration
var iterationNumber = 0;
while (iterator.DetermineStatus(iterationNumber, result, input, pseudoResiduals) == IterationStatus.Continue)
{
// First part of the step, the even bit
if (IsEven(iterationNumber))
{
// sigma = (v, r)
var sigma = r.ConjugateDotProduct(v);
if (sigma.Real.AlmostEqualNumbersBetween(0, 1) && sigma.Imaginary.AlmostEqualNumbersBetween(0, 1))
{
// FAIL HERE
iterator.Cancel();
break;
}
// alpha = rho / sigma
alpha = rho/sigma;
// yOdd = yEven - alpha * v
v.Multiply(-alpha, temp1);
yeven.Add(temp1, yodd);
// Solve M temp = yOdd
preconditioner.Approximate(yodd, temp);
// uOdd = A temp
matrix.Multiply(temp, uodd);
}
// The intermediate step which is equal for both even and
// odd iteration steps.
// Select the correct vector
var uinternal = IsEven(iterationNumber) ? ueven : uodd;
var yinternal = IsEven(iterationNumber) ? yeven : yodd;
// pseudoResiduals = pseudoResiduals - alpha * uOdd
uinternal.Multiply(-alpha, temp1);
pseudoResiduals.Add(temp1, temp2);
temp2.CopyTo(pseudoResiduals);
// d = yOdd + theta * theta * eta / alpha * d
d.Multiply(theta*theta*eta/alpha, temp);
yinternal.Add(temp, d);
// theta = ||pseudoResiduals||_2 / tau
theta = pseudoResiduals.L2Norm()/tau;
var c = 1/Math.Sqrt(1 + (theta*theta));
// tau = tau * theta * c
tau *= theta*c;
// eta = c^2 * alpha
eta = c*c*alpha;
// x = x + eta * d
d.Multiply(eta, temp1);
x.Add(temp1, temp2);
temp2.CopyTo(x);
// Check convergence and see if we can bail
if (iterator.DetermineStatus(iterationNumber, result, input, pseudoResiduals) != IterationStatus.Continue)
{
// Calculate the real values
preconditioner.Approximate(x, result);
// Calculate the true residual. Use the temp vector for that
// so that we don't pollute the pseudoResidual vector for no
// good reason.
CalculateTrueResidual(matrix, temp, result, input);
// Now recheck the convergence
if (iterator.DetermineStatus(iterationNumber, result, input, temp) != IterationStatus.Continue)
{
// We're all good now.
return;
}
}
// The odd step
if (!IsEven(iterationNumber))
{
if (rho.Real.AlmostEqualNumbersBetween(0, 1) && rho.Imaginary.AlmostEqualNumbersBetween(0, 1))
{
// FAIL HERE
iterator.Cancel();
break;
}
var rhoNew = r.ConjugateDotProduct(pseudoResiduals);
var beta = rhoNew/rho;
// Update rho for the next loop
rho = rhoNew;
// yOdd = pseudoResiduals + beta * yOdd
yodd.Multiply(beta, temp1);
pseudoResiduals.Add(temp1, yeven);
// Solve M temp = yOdd
preconditioner.Approximate(yeven, temp);
// uOdd = A temp
matrix.Multiply(temp, ueven);
// v = uEven + beta * (uOdd + beta * v)
v.Multiply(beta, temp1);
uodd.Add(temp1, temp);
temp.Multiply(beta, temp1);
ueven.Add(temp1, v);
}
// Calculate the real values
preconditioner.Approximate(x, result);
iterationNumber++;
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using Xunit;
namespace System.Linq.Tests
{
public class CastTests
{
[Fact]
public void CastIntToLongThrows()
{
var q = from x in new[] { 9999, 0, 888, -1, 66, -777, 1, 2, -12345 }
where x > Int32.MinValue
select x;
var rst = q.Cast<long>();
Assert.Throws<InvalidCastException>(() => { foreach (var t in rst) ; });
}
[Fact]
public void CastByteToUShortThrows()
{
var q = from x in new byte[] { 0, 255, 127, 128, 1, 33, 99 }
select x;
var rst = q.Cast<ushort>();
Assert.Throws<InvalidCastException>(() => { foreach (var t in rst) ; });
}
[Fact]
public void EmptySource()
{
object[] source = { };
int[] expected = { };
Assert.Equal(expected, source.Cast<int>());
}
[Fact]
public void NullableIntFromAppropriateObjects()
{
int? i = 10;
object[] source = { -4, 1, 2, 3, 9, i };
int?[] expected = { -4, 1, 2, 3, 9, i };
Assert.Equal(expected, source.Cast<int?>());
}
[Fact]
public void LongFromNullableIntInObjectsThrows()
{
int? i = 10;
object[] source = { -4, 1, 2, 3, 9, i };
IEnumerable<long> cast = source.Cast<long>();
Assert.Throws<InvalidCastException>(() => cast.ToList());
}
[Fact]
public void LongFromNullableIntInObjectsIncludingNullThrows()
{
int? i = 10;
object[] source = { -4, 1, 2, 3, 9, null, i };
IEnumerable<long?> cast = source.Cast<long?>();
Assert.Throws<InvalidCastException>(() => cast.ToList());
}
[Fact]
public void NullableIntFromAppropriateObjectsIncludingNull()
{
int? i = 10;
object[] source = { -4, 1, 2, 3, 9, null, i };
int?[] expected = { -4, 1, 2, 3, 9, null, i };
Assert.Equal(expected, source.Cast<int?>());
}
[Fact]
public void ThrowOnUncastableItem()
{
object[] source = { -4, 1, 2, 3, 9, "45" };
int[] expectedBeginning = { -4, 1, 2, 3, 9 };
IEnumerable<int> cast = source.Cast<int>();
Assert.Throws<InvalidCastException>(() => cast.ToList());
Assert.Equal(expectedBeginning, cast.Take(5));
Assert.Throws<InvalidCastException>(() => cast.ElementAt(5));
}
[Fact]
public void ThrowCastingIntToDouble()
{
int[] source = new int[] { -4, 1, 2, 9 };
IEnumerable<double> cast = source.Cast<double>();
Assert.Throws<InvalidCastException>(() => cast.ToList());
}
private static void TestCastThrow<T>(object o)
{
byte? i = 10;
object[] source = { -1, 0, o, i };
IEnumerable<T> cast = source.Cast<T>();
Assert.Throws<InvalidCastException>(() => cast.ToList());
}
[Fact]
public void ThrowOnHeterogenousSource()
{
TestCastThrow<long?>(null);
TestCastThrow<long>(9L);
}
[Fact]
public void CastToString()
{
object[] source = { "Test1", "4.5", null, "Test2" };
string[] expected = { "Test1", "4.5", null, "Test2" };
Assert.Equal(expected, source.Cast<string>());
}
[Fact]
public void ArrayConversionThrows()
{
Assert.Throws<InvalidCastException>(() => new[] { -4 }.Cast<long>().ToList());
}
[Fact]
public void FirstElementInvalidForCast()
{
object[] source = { "Test", 3, 5, 10 };
IEnumerable<int> cast = source.Cast<int>();
Assert.Throws<InvalidCastException>(() => cast.ToList());
}
[Fact]
public void LastElementInvalidForCast()
{
object[] source = { -5, 9, 0, 5, 9, "Test" };
IEnumerable<int> cast = source.Cast<int>();
Assert.Throws<InvalidCastException>(() => cast.ToList());
}
[Fact]
public void NullableIntFromNullsAndInts()
{
object[] source = { 3, null, 5, -4, 0, null, 9 };
int?[] expected = { 3, null, 5, -4, 0, null, 9 };
Assert.Equal(expected, source.Cast<int?>());
}
[Fact]
public void ThrowCastingIntToLong()
{
int[] source = new int[] { -4, 1, 2, 3, 9 };
IEnumerable<long> cast = source.Cast<long>();
Assert.Throws<InvalidCastException>(() => cast.ToList());
}
[Fact]
public void ThrowCastingIntToNullableLong()
{
int[] source = new int[] { -4, 1, 2, 3, 9 };
IEnumerable<long?> cast = source.Cast<long?>();
Assert.Throws<InvalidCastException>(() => cast.ToList());
}
[Fact]
public void ThrowCastingNullableIntToLong()
{
int?[] source = new int?[] { -4, 1, 2, 3, 9 };
IEnumerable<long> cast = source.Cast<long>();
Assert.Throws<InvalidCastException>(() => cast.ToList());
}
[Fact]
public void ThrowCastingNullableIntToNullableLong()
{
int?[] source = new int?[] { -4, 1, 2, 3, 9, null };
IEnumerable<long?> cast = source.Cast<long?>();
Assert.Throws<InvalidCastException>(() => cast.ToList());
}
[Fact]
public void CastingNullToNonnullableIsNullReferenceException()
{
int?[] source = new int?[] { -4, 1, null, 3 };
IEnumerable<int> cast = source.Cast<int>();
Assert.Throws<NullReferenceException>(() => cast.ToList());
}
}
}
| |
using UnityEngine;
using System;
namespace UnityStandardAssets.CinematicEffects
{
//Improvement ideas:
// Use rgba8 buffer in ldr / in some pass in hdr (in correlation to previous point and remapping coc from -1/0/1 to 0/0.5/1)
// Use temporal stabilisation.
// Add a mode to do bokeh texture in quarter res as well
// Support different near and far blur for the bokeh texture
// Try distance field for the bokeh texture.
// Try to separate the output of the blur pass to two rendertarget near+far, see the gain in quality vs loss in performance.
// Try swirl effect on the samples of the circle blur.
//References :
// This DOF implementation use ideas from public sources, a big thank to them :
// http://www.iryoku.com/next-generation-post-processing-in-call-of-duty-advanced-warfare
// http://www.crytek.com/download/Sousa_Graphics_Gems_CryENGINE3.pdf
// http://graphics.cs.williams.edu/papers/MedianShaderX6/
// http://http.developer.nvidia.com/GPUGems/gpugems_ch24.html
// http://vec3.ca/bicubic-filtering-in-fewer-taps/
[ExecuteInEditMode]
[AddComponentMenu("Image Effects/Cinematic/Depth Of Field")]
[RequireComponent(typeof(Camera))]
public class DepthOfField : MonoBehaviour
{
private const float kMaxBlur = 35.0f;
#region Render passes
private enum Passes
{
BlurAlphaWeighted = 0 ,
BoxBlur = 1 ,
DilateFgCocFromColor = 2 ,
DilateFgCoc = 3 ,
CaptureCoc = 4 ,
CaptureCocExplicit = 5 ,
VisualizeCoc = 6 ,
VisualizeCocExplicit = 7 ,
CocPrefilter = 8 ,
CircleBlur = 9 ,
CircleBlurWithDilatedFg = 10,
CircleBlurLowQuality = 11,
CircleBlowLowQualityWithDilatedFg = 12,
Merge = 13,
MergeExplicit = 14,
MergeBicubic = 15,
MergeExplicitBicubic = 16,
ShapeLowQuality = 17,
ShapeLowQualityDilateFg = 18,
ShapeLowQualityMerge = 19,
ShapeLowQualityMergeDilateFg = 20,
ShapeMediumQuality = 21,
ShapeMediumQualityDilateFg = 22,
ShapeMediumQualityMerge = 23,
ShapeMediumQualityMergeDilateFg = 24,
ShapeHighQuality = 25,
ShapeHighQualityDilateFg = 26,
ShapeHighQualityMerge = 27,
ShapeHighQualityMergeDilateFg = 28
}
private enum MedianPasses
{
Median3 = 0,
Median3X3 = 1
}
private enum BokehTexturesPasses
{
Apply = 0,
Collect = 1
}
#endregion
public enum TweakMode
{
Basic,
Advanced,
Explicit
}
public enum ApertureShape
{
Circular,
Hexagonal,
Octogonal
}
public enum QualityPreset
{
Simple,
Low,
Medium,
High,
VeryHigh,
Ultra,
Custom
}
public enum FilterQuality
{
None,
Normal,
High
}
#region Attributes
[AttributeUsage(AttributeTargets.Field)]
public class TopLevelSettings : Attribute
{}
[AttributeUsage(AttributeTargets.Field)]
public class SettingsGroup : Attribute
{}
[AttributeUsage(AttributeTargets.Field)]
public class AllTweakModes : Attribute
{}
[AttributeUsage(AttributeTargets.Field)]
public class Basic : Attribute
{}
[AttributeUsage(AttributeTargets.Field)]
public class Advanced : Attribute
{}
[AttributeUsage(AttributeTargets.Field)]
public class Explicit : Attribute
{}
#endregion
#region Settings
[Serializable]
public struct GlobalSettings
{
[Tooltip("Allows to view where the blur will be applied. Yellow for near blur, blue for far blur.")]
public bool visualizeBluriness;
[Tooltip("Setup mode. Use \"Advanced\" if you need more control on blur settings and/or want to use a bokeh texture. \"Explicit\" is the same as \"Advanced\" but makes use of \"Near Plane\" and \"Far Plane\" values instead of \"F-Stop\".")]
public TweakMode tweakMode;
[Tooltip("Quality presets. Use \"Custom\" for more advanced settings.")]
public QualityPreset quality;
[Space, Tooltip("\"Circular\" is the fastest, followed by \"Hexagonal\" and \"Octogonal\".")]
public ApertureShape apertureShape;
[Range(0f, 179f), Tooltip("Rotates the aperture when working with \"Hexagonal\" and \"Ortogonal\".")]
public float apertureOrientation;
public static GlobalSettings defaultSettings
{
get
{
return new GlobalSettings
{
visualizeBluriness = false,
tweakMode = TweakMode.Basic,
quality = QualityPreset.High,
apertureShape = ApertureShape.Circular,
apertureOrientation = 0f
};
}
}
}
[Serializable]
public struct QualitySettings
{
[Tooltip("Enable this to get smooth bokeh.")]
public bool prefilterBlur;
[Tooltip("Applies a median filter for even smoother bokeh.")]
public FilterQuality medianFilter;
[Tooltip("Dilates near blur over in focus area.")]
public bool dilateNearBlur;
[Tooltip("Uses high quality upsampling.")]
public bool highQualityUpsampling;
[Tooltip("Prevent haloing from bright in focus region over dark out of focus region.")]
public bool preventHaloing;
public static QualitySettings[] presetQualitySettings =
{
// Simple
new QualitySettings
{
prefilterBlur = false,
medianFilter = FilterQuality.None,
dilateNearBlur = false,
highQualityUpsampling = false,
preventHaloing = false
},
// Low
new QualitySettings
{
prefilterBlur = true,
medianFilter = FilterQuality.None,
dilateNearBlur = false,
highQualityUpsampling = false,
preventHaloing = false
},
// Medium
new QualitySettings
{
prefilterBlur = true,
medianFilter = FilterQuality.Normal,
dilateNearBlur = false,
highQualityUpsampling = false,
preventHaloing = false
},
// High
new QualitySettings
{
prefilterBlur = true,
medianFilter = FilterQuality.Normal,
dilateNearBlur = true,
highQualityUpsampling = false,
preventHaloing = false
},
// Very high
new QualitySettings
{
prefilterBlur = true,
medianFilter = FilterQuality.High,
dilateNearBlur = true,
highQualityUpsampling = false,
preventHaloing = true
},
// Ultra
new QualitySettings
{
prefilterBlur = true,
medianFilter = FilterQuality.High,
dilateNearBlur = true,
highQualityUpsampling = true,
preventHaloing = true
}
};
}
[Serializable]
public struct FocusSettings
{
[Basic, Advanced, Explicit, Tooltip("Auto-focus on a selected transform.")]
public Transform transform;
[Basic, Advanced, Explicit, Range(0f, 1f), Tooltip("Focus distance.")]
public float plane;
[Explicit, Range(0f, 1f), Tooltip("Near focus distance.")]
public float nearPlane;
[Explicit, Range(0f, 1f), Tooltip("Far focus distance.")]
public float farPlane;
[Basic, Advanced, Range(0f, 32f), Tooltip("Simulates focal ratio. Lower values will result in a narrow depth of field.")]
public float fStops;
[Basic, Advanced, Explicit, Range(0f, 1f), Tooltip("Focus range/spread. Use this to fine-tune the F-Stop range.")]
public float rangeAdjustment;
public static FocusSettings defaultSettings
{
get
{
return new FocusSettings
{
transform = null,
plane = 0.225f,
nearPlane = 0f,
farPlane = 1f,
fStops = 5f,
rangeAdjustment = 0.9f
};
}
}
}
[Serializable]
public struct BokehTextureSettings
{
[Advanced, Explicit, Tooltip("Adding a texture to this field will enable the use of \"Bokeh Textures\". Use with care. This feature is only available on Shader Model 5 compatible-hardware and performance scale with the amount of bokeh.")]
public Texture2D texture;
[Advanced, Explicit, Range(0.01f, 5f), Tooltip("Maximum size of bokeh textures on screen.")]
public float scale;
[Advanced, Explicit, Range(0.01f, 100f), Tooltip("Bokeh brightness.")]
public float intensity;
[Advanced, Explicit, Range(0.01f, 50f), Tooltip("Controls the amount of bokeh textures. Lower values mean more bokeh splats.")]
public float threshold;
[Advanced, Explicit, Range(0.01f, 1f), Tooltip("Controls the spawn conditions. Lower values mean more visible bokeh.")]
public float spawnHeuristic;
public static BokehTextureSettings defaultSettings
{
get
{
return new BokehTextureSettings
{
texture = null,
scale = 1f,
intensity = 50f,
threshold = 2f,
spawnHeuristic = 0.15f
};
}
}
}
[Serializable]
public struct BlurSettings
{
[Basic, Advanced, Explicit, Range(0f, kMaxBlur), Tooltip("Maximum blur radius for the near plane.")]
public float nearRadius;
[Basic, Advanced, Explicit, Range(0f, kMaxBlur), Tooltip("Maximum blur radius for the far plane.")]
public float farRadius;
[Advanced, Explicit, Range(0.5f, 4f), Tooltip("Blur luminosity booster threshold for the near and far boost amounts.")]
public float boostPoint;
[Advanced, Explicit, Range(0f, 1f), Tooltip("Boosts luminosity in the near blur.")]
public float nearBoostAmount;
[Advanced, Explicit, Range(0f, 1f), Tooltip("Boosts luminosity in the far blur.")]
public float farBoostAmount;
public static BlurSettings defaultSettings
{
get
{
return new BlurSettings
{
nearRadius = 20f,
farRadius = 20f,
boostPoint = 0.75f,
nearBoostAmount = 0f,
farBoostAmount = 0f,
};
}
}
}
#endregion
[TopLevelSettings]
public GlobalSettings settings = GlobalSettings.defaultSettings;
[SettingsGroup, AllTweakModes]
public QualitySettings quality = QualitySettings.presetQualitySettings[3];
[SettingsGroup]
public FocusSettings focus = FocusSettings.defaultSettings;
[SettingsGroup]
public BokehTextureSettings bokehTexture = BokehTextureSettings.defaultSettings;
[SettingsGroup]
public BlurSettings blur = BlurSettings.defaultSettings;
[SerializeField]
private Shader m_FilmicDepthOfFieldShader;
public Shader filmicDepthOfFieldShader
{
get
{
if (m_FilmicDepthOfFieldShader == null)
m_FilmicDepthOfFieldShader = Shader.Find("Hidden/DepthOfField/DepthOfField");
return m_FilmicDepthOfFieldShader;
}
}
[SerializeField]
private Shader m_MedianFilterShader;
public Shader medianFilterShader
{
get
{
if (m_MedianFilterShader == null)
m_MedianFilterShader = Shader.Find("Hidden/DepthOfField/MedianFilter");
return m_MedianFilterShader;
}
}
[SerializeField]
private Shader m_TextureBokehShader;
public Shader textureBokehShader
{
get
{
if (m_TextureBokehShader == null)
m_TextureBokehShader = Shader.Find("Hidden/DepthOfField/BokehSplatting");
return m_TextureBokehShader;
}
}
private RenderTextureUtility m_RTU = new RenderTextureUtility();
private Material m_FilmicDepthOfFieldMaterial;
public Material filmicDepthOfFieldMaterial
{
get
{
if (m_FilmicDepthOfFieldMaterial == null)
m_FilmicDepthOfFieldMaterial = ImageEffectHelper.CheckShaderAndCreateMaterial(filmicDepthOfFieldShader);
return m_FilmicDepthOfFieldMaterial;
}
}
private Material m_MedianFilterMaterial;
public Material medianFilterMaterial
{
get
{
if (m_MedianFilterMaterial == null)
m_MedianFilterMaterial = ImageEffectHelper.CheckShaderAndCreateMaterial(medianFilterShader);
return m_MedianFilterMaterial;
}
}
private Material m_TextureBokehMaterial;
public Material textureBokehMaterial
{
get
{
if (m_TextureBokehMaterial == null)
m_TextureBokehMaterial = ImageEffectHelper.CheckShaderAndCreateMaterial(textureBokehShader);
return m_TextureBokehMaterial;
}
}
private ComputeBuffer m_ComputeBufferDrawArgs;
public ComputeBuffer computeBufferDrawArgs
{
get
{
if (m_ComputeBufferDrawArgs == null)
{
#if (UNITY_5_0 || UNITY_5_1 || UNITY_5_2 || UNITY_5_3)
m_ComputeBufferDrawArgs = new ComputeBuffer(1, 16, ComputeBufferType.DrawIndirect);
#else
m_ComputeBufferDrawArgs = new ComputeBuffer(1, 16, ComputeBufferType.IndirectArguments);
#endif
m_ComputeBufferDrawArgs.SetData(new[] {0, 1, 0, 0});
}
return m_ComputeBufferDrawArgs;
}
}
private ComputeBuffer m_ComputeBufferPoints;
public ComputeBuffer computeBufferPoints
{
get
{
if (m_ComputeBufferPoints == null)
m_ComputeBufferPoints = new ComputeBuffer(90000, 12 + 16, ComputeBufferType.Append);
return m_ComputeBufferPoints;
}
}
private QualitySettings m_CurrentQualitySettings;
private float m_LastApertureOrientation;
private Vector4 m_OctogonalBokehDirection1;
private Vector4 m_OctogonalBokehDirection2;
private Vector4 m_OctogonalBokehDirection3;
private Vector4 m_OctogonalBokehDirection4;
private Vector4 m_HexagonalBokehDirection1;
private Vector4 m_HexagonalBokehDirection2;
private Vector4 m_HexagonalBokehDirection3;
private void OnEnable()
{
if (!ImageEffectHelper.IsSupported(filmicDepthOfFieldShader, true, true, this) || !ImageEffectHelper.IsSupported(medianFilterShader, true, true, this))
{
enabled = false;
return;
}
if (ImageEffectHelper.supportsDX11 && !ImageEffectHelper.IsSupported(textureBokehShader, true, true, this))
{
enabled = false;
return;
}
ComputeBlurDirections(true);
GetComponent<Camera>().depthTextureMode |= DepthTextureMode.Depth;
}
private void OnDisable()
{
ReleaseComputeResources();
if (m_FilmicDepthOfFieldMaterial != null)
DestroyImmediate(m_FilmicDepthOfFieldMaterial);
if (m_TextureBokehMaterial != null)
DestroyImmediate(m_TextureBokehMaterial);
if (m_MedianFilterMaterial != null)
DestroyImmediate(m_MedianFilterMaterial);
m_FilmicDepthOfFieldMaterial = null;
m_TextureBokehMaterial = null;
m_MedianFilterMaterial = null;
m_RTU.ReleaseAllTemporaryRenderTextures();
}
//-------------------------------------------------------------------//
// Main entry point //
//-------------------------------------------------------------------//
private void OnRenderImage(RenderTexture source, RenderTexture destination)
{
if (medianFilterMaterial == null || filmicDepthOfFieldMaterial == null)
{
Graphics.Blit(source, destination);
return;
}
if (settings.visualizeBluriness)
{
Vector4 blurrinessParam;
Vector4 blurrinessCoe;
ComputeCocParameters(out blurrinessParam, out blurrinessCoe);
filmicDepthOfFieldMaterial.SetVector("_BlurParams", blurrinessParam);
filmicDepthOfFieldMaterial.SetVector("_BlurCoe", blurrinessCoe);
Graphics.Blit(null, destination, filmicDepthOfFieldMaterial, (settings.tweakMode == TweakMode.Explicit) ? (int)Passes.VisualizeCocExplicit : (int)Passes.VisualizeCoc);
}
else
{
DoDepthOfField(source, destination);
}
m_RTU.ReleaseAllTemporaryRenderTextures();
}
private void DoDepthOfField(RenderTexture source, RenderTexture destination)
{
m_CurrentQualitySettings = quality;
if (settings.quality != QualityPreset.Custom)
m_CurrentQualitySettings = QualitySettings.presetQualitySettings[(int)settings.quality];
float radiusAdjustement = source.height / 720.0f;
float textureBokehScale = radiusAdjustement;
float textureBokehMaxRadius = Mathf.Max(blur.nearRadius, blur.farRadius) * textureBokehScale * 0.75f;
float nearBlurRadius = blur.nearRadius * radiusAdjustement;
float farBlurRadius = blur.farRadius * radiusAdjustement;
float maxBlurRadius = Mathf.Max(nearBlurRadius, farBlurRadius);
switch (settings.apertureShape)
{
case ApertureShape.Hexagonal:
maxBlurRadius *= 1.2f;
break;
case ApertureShape.Octogonal:
maxBlurRadius *= 1.15f;
break;
}
if (maxBlurRadius < 0.5f)
{
Graphics.Blit(source, destination);
return;
}
// Quarter resolution
int rtW = source.width / 2;
int rtH = source.height / 2;
Vector4 blurrinessCoe = new Vector4(nearBlurRadius * 0.5f, farBlurRadius * 0.5f, 0.0f, 0.0f);
RenderTexture colorAndCoc = m_RTU.GetTemporaryRenderTexture(rtW, rtH);
RenderTexture colorAndCoc2 = m_RTU.GetTemporaryRenderTexture(rtW, rtH);
if (m_CurrentQualitySettings.preventHaloing)
filmicDepthOfFieldMaterial.EnableKeyword("USE_SPECIAL_FETCH_FOR_COC");
else
filmicDepthOfFieldMaterial.DisableKeyword("USE_SPECIAL_FETCH_FOR_COC");
// Downsample to Color + COC buffer and apply boost
Vector4 cocParam;
Vector4 cocCoe;
ComputeCocParameters(out cocParam, out cocCoe);
filmicDepthOfFieldMaterial.SetVector("_BlurParams", cocParam);
filmicDepthOfFieldMaterial.SetVector("_BlurCoe", cocCoe);
filmicDepthOfFieldMaterial.SetVector("_BoostParams", new Vector4(nearBlurRadius * blur.nearBoostAmount * -0.5f, farBlurRadius * blur.farBoostAmount * 0.5f, blur.boostPoint, 0.0f));
Graphics.Blit(source, colorAndCoc2, filmicDepthOfFieldMaterial, (settings.tweakMode == TweakMode.Explicit) ? (int)Passes.CaptureCocExplicit : (int)Passes.CaptureCoc);
RenderTexture src = colorAndCoc2;
RenderTexture dst = colorAndCoc;
// Collect texture bokeh candidates and replace with a darker pixel
if (shouldPerformBokeh)
{
// Blur a bit so we can do a frequency check
RenderTexture blurred = m_RTU.GetTemporaryRenderTexture(rtW, rtH);
Graphics.Blit(src, blurred, filmicDepthOfFieldMaterial, (int)Passes.BoxBlur);
filmicDepthOfFieldMaterial.SetVector("_Offsets", new Vector4(0.0f, 1.5f, 0.0f, 1.5f));
Graphics.Blit(blurred, dst, filmicDepthOfFieldMaterial, (int)Passes.BlurAlphaWeighted);
filmicDepthOfFieldMaterial.SetVector("_Offsets", new Vector4(1.5f, 0.0f, 0.0f, 1.5f));
Graphics.Blit(dst, blurred, filmicDepthOfFieldMaterial, (int)Passes.BlurAlphaWeighted);
// Collect texture bokeh candidates and replace with a darker pixel
textureBokehMaterial.SetTexture("_BlurredColor", blurred);
textureBokehMaterial.SetFloat("_SpawnHeuristic", bokehTexture.spawnHeuristic);
textureBokehMaterial.SetVector("_BokehParams", new Vector4(bokehTexture.scale * textureBokehScale, bokehTexture.intensity, bokehTexture.threshold, textureBokehMaxRadius));
Graphics.SetRandomWriteTarget(1, computeBufferPoints);
Graphics.Blit(src, dst, textureBokehMaterial, (int)BokehTexturesPasses.Collect);
Graphics.ClearRandomWriteTargets();
SwapRenderTexture(ref src, ref dst);
m_RTU.ReleaseTemporaryRenderTexture(blurred);
}
filmicDepthOfFieldMaterial.SetVector("_BlurParams", cocParam);
filmicDepthOfFieldMaterial.SetVector("_BlurCoe", blurrinessCoe);
filmicDepthOfFieldMaterial.SetVector("_BoostParams", new Vector4(nearBlurRadius * blur.nearBoostAmount * -0.5f, farBlurRadius * blur.farBoostAmount * 0.5f, blur.boostPoint, 0.0f));
// Dilate near blur factor
RenderTexture blurredFgCoc = null;
if (m_CurrentQualitySettings.dilateNearBlur)
{
RenderTexture blurredFgCoc2 = m_RTU.GetTemporaryRenderTexture(rtW, rtH, 0, RenderTextureFormat.RGHalf);
blurredFgCoc = m_RTU.GetTemporaryRenderTexture(rtW, rtH, 0, RenderTextureFormat.RGHalf);
filmicDepthOfFieldMaterial.SetVector("_Offsets", new Vector4(0.0f, nearBlurRadius * 0.75f, 0.0f, 0.0f));
Graphics.Blit(src, blurredFgCoc2, filmicDepthOfFieldMaterial, (int)Passes.DilateFgCocFromColor);
filmicDepthOfFieldMaterial.SetVector("_Offsets", new Vector4(nearBlurRadius * 0.75f, 0.0f, 0.0f, 0.0f));
Graphics.Blit(blurredFgCoc2, blurredFgCoc, filmicDepthOfFieldMaterial, (int)Passes.DilateFgCoc);
m_RTU.ReleaseTemporaryRenderTexture(blurredFgCoc2);
blurredFgCoc.filterMode = FilterMode.Point;
}
// Blur downsampled color to fill the gap between samples
if (m_CurrentQualitySettings.prefilterBlur)
{
Graphics.Blit(src, dst, filmicDepthOfFieldMaterial, (int)Passes.CocPrefilter);
SwapRenderTexture(ref src, ref dst);
}
// Apply blur : Circle / Hexagonal or Octagonal (blur will create bokeh if bright pixel where not removed by "m_UseBokehTexture")
switch (settings.apertureShape)
{
case ApertureShape.Circular:
DoCircularBlur(blurredFgCoc, ref src, ref dst, maxBlurRadius);
break;
case ApertureShape.Hexagonal:
DoHexagonalBlur(blurredFgCoc, ref src, ref dst, maxBlurRadius);
break;
case ApertureShape.Octogonal:
DoOctogonalBlur(blurredFgCoc, ref src, ref dst, maxBlurRadius);
break;
}
// Smooth result
switch (m_CurrentQualitySettings.medianFilter)
{
case FilterQuality.Normal:
{
medianFilterMaterial.SetVector("_Offsets", new Vector4(1.0f, 0.0f, 0.0f, 0.0f));
Graphics.Blit(src, dst, medianFilterMaterial, (int)MedianPasses.Median3);
SwapRenderTexture(ref src, ref dst);
medianFilterMaterial.SetVector("_Offsets", new Vector4(0.0f, 1.0f, 0.0f, 0.0f));
Graphics.Blit(src, dst, medianFilterMaterial, (int)MedianPasses.Median3);
SwapRenderTexture(ref src, ref dst);
break;
}
case FilterQuality.High:
{
Graphics.Blit(src, dst, medianFilterMaterial, (int)MedianPasses.Median3X3);
SwapRenderTexture(ref src, ref dst);
break;
}
}
// Merge to full resolution (with boost) + upsampling (linear or bicubic)
filmicDepthOfFieldMaterial.SetVector("_BlurCoe", blurrinessCoe);
filmicDepthOfFieldMaterial.SetVector("_Convolved_TexelSize", new Vector4(src.width, src.height, 1.0f / src.width, 1.0f / src.height));
filmicDepthOfFieldMaterial.SetTexture("_SecondTex", src);
int mergePass = (settings.tweakMode == TweakMode.Explicit) ? (int)Passes.MergeExplicit : (int)Passes.Merge;
if (m_CurrentQualitySettings.highQualityUpsampling)
mergePass = (settings.tweakMode == TweakMode.Explicit) ? (int)Passes.MergeExplicitBicubic : (int)Passes.MergeBicubic;
// Apply texture bokeh
if (shouldPerformBokeh)
{
RenderTexture tmp = m_RTU.GetTemporaryRenderTexture(source.height, source.width, 0, source.format);
Graphics.Blit(source, tmp, filmicDepthOfFieldMaterial, mergePass);
Graphics.SetRenderTarget(tmp);
ComputeBuffer.CopyCount(computeBufferPoints, computeBufferDrawArgs, 0);
textureBokehMaterial.SetBuffer("pointBuffer", computeBufferPoints);
textureBokehMaterial.SetTexture("_MainTex", bokehTexture.texture);
textureBokehMaterial.SetVector("_Screen", new Vector3(1.0f / (1.0f * source.width), 1.0f / (1.0f * source.height), textureBokehMaxRadius));
textureBokehMaterial.SetPass((int)BokehTexturesPasses.Apply);
Graphics.DrawProceduralIndirect(MeshTopology.Points, computeBufferDrawArgs, 0);
Graphics.Blit(tmp, destination); // hackaround for DX11 flipfun (OPTIMIZEME)
}
else
{
Graphics.Blit(source, destination, filmicDepthOfFieldMaterial, mergePass);
}
}
//-------------------------------------------------------------------//
// Blurs //
//-------------------------------------------------------------------//
private void DoHexagonalBlur(RenderTexture blurredFgCoc, ref RenderTexture src, ref RenderTexture dst, float maxRadius)
{
ComputeBlurDirections(false);
int blurPass;
int blurPassMerge;
GetDirectionalBlurPassesFromRadius(blurredFgCoc, maxRadius, out blurPass, out blurPassMerge);
filmicDepthOfFieldMaterial.SetTexture("_SecondTex", blurredFgCoc);
RenderTexture tmp = m_RTU.GetTemporaryRenderTexture(src.width, src.height, 0, src.format);
filmicDepthOfFieldMaterial.SetVector("_Offsets", m_HexagonalBokehDirection1);
Graphics.Blit(src, tmp, filmicDepthOfFieldMaterial, blurPass);
filmicDepthOfFieldMaterial.SetVector("_Offsets", m_HexagonalBokehDirection2);
Graphics.Blit(tmp, src, filmicDepthOfFieldMaterial, blurPass);
filmicDepthOfFieldMaterial.SetVector("_Offsets", m_HexagonalBokehDirection3);
filmicDepthOfFieldMaterial.SetTexture("_ThirdTex", src);
Graphics.Blit(tmp, dst, filmicDepthOfFieldMaterial, blurPassMerge);
m_RTU.ReleaseTemporaryRenderTexture(tmp);
SwapRenderTexture(ref src, ref dst);
}
private void DoOctogonalBlur(RenderTexture blurredFgCoc, ref RenderTexture src, ref RenderTexture dst, float maxRadius)
{
ComputeBlurDirections(false);
int blurPass;
int blurPassMerge;
GetDirectionalBlurPassesFromRadius(blurredFgCoc, maxRadius, out blurPass, out blurPassMerge);
filmicDepthOfFieldMaterial.SetTexture("_SecondTex", blurredFgCoc);
RenderTexture tmp = m_RTU.GetTemporaryRenderTexture(src.width, src.height, 0, src.format);
filmicDepthOfFieldMaterial.SetVector("_Offsets", m_OctogonalBokehDirection1);
Graphics.Blit(src, tmp, filmicDepthOfFieldMaterial, blurPass);
filmicDepthOfFieldMaterial.SetVector("_Offsets", m_OctogonalBokehDirection2);
Graphics.Blit(tmp, dst, filmicDepthOfFieldMaterial, blurPass);
filmicDepthOfFieldMaterial.SetVector("_Offsets", m_OctogonalBokehDirection3);
Graphics.Blit(src, tmp, filmicDepthOfFieldMaterial, blurPass);
filmicDepthOfFieldMaterial.SetVector("_Offsets", m_OctogonalBokehDirection4);
filmicDepthOfFieldMaterial.SetTexture("_ThirdTex", dst);
Graphics.Blit(tmp, src, filmicDepthOfFieldMaterial, blurPassMerge);
m_RTU.ReleaseTemporaryRenderTexture(tmp);
}
private void DoCircularBlur(RenderTexture blurredFgCoc, ref RenderTexture src, ref RenderTexture dst, float maxRadius)
{
int bokehPass;
if (blurredFgCoc != null)
{
filmicDepthOfFieldMaterial.SetTexture("_SecondTex", blurredFgCoc);
bokehPass = (maxRadius > 10.0f) ? (int)Passes.CircleBlurWithDilatedFg : (int)Passes.CircleBlowLowQualityWithDilatedFg;
}
else
{
bokehPass = (maxRadius > 10.0f) ? (int)Passes.CircleBlur : (int)Passes.CircleBlurLowQuality;
}
Graphics.Blit(src, dst, filmicDepthOfFieldMaterial, bokehPass);
SwapRenderTexture(ref src, ref dst);
}
//-------------------------------------------------------------------//
// Helpers //
//-------------------------------------------------------------------//
private void ComputeCocParameters(out Vector4 blurParams, out Vector4 blurCoe)
{
Camera sceneCamera = GetComponent<Camera>();
float focusDistance01 = focus.transform
? (sceneCamera.WorldToViewportPoint(focus.transform.position)).z / (sceneCamera.farClipPlane)
: (focus.plane * focus.plane * focus.plane * focus.plane);
if (settings.tweakMode == TweakMode.Basic || settings.tweakMode == TweakMode.Advanced)
{
float focusRange01 = focus.rangeAdjustment * focus.rangeAdjustment * focus.rangeAdjustment * focus.rangeAdjustment;
float focalLength = 4.0f / Mathf.Tan(0.5f * sceneCamera.fieldOfView * Mathf.Deg2Rad);
float aperture = focalLength / focus.fStops;
blurCoe = new Vector4(0.0f, 0.0f, 1.0f, 1.0f);
blurParams = new Vector4(aperture, focalLength, focusDistance01, focusRange01);
}
else
{
float nearDistance01 = focus.nearPlane * focus.nearPlane * focus.nearPlane * focus.nearPlane;
float farDistance01 = focus.farPlane * focus.farPlane * focus.farPlane * focus.farPlane;
float nearFocusRange01 = focus.rangeAdjustment * focus.rangeAdjustment * focus.rangeAdjustment * focus.rangeAdjustment;
float farFocusRange01 = nearFocusRange01;
if (focusDistance01 <= nearDistance01)
focusDistance01 = nearDistance01 + 0.0000001f;
if (focusDistance01 >= farDistance01)
focusDistance01 = farDistance01 - 0.0000001f;
if ((focusDistance01 - nearFocusRange01) <= nearDistance01)
nearFocusRange01 = (focusDistance01 - nearDistance01 - 0.0000001f);
if ((focusDistance01 + farFocusRange01) >= farDistance01)
farFocusRange01 = (farDistance01 - focusDistance01 - 0.0000001f);
float a1 = 1.0f / (nearDistance01 - focusDistance01 + nearFocusRange01);
float a2 = 1.0f / (farDistance01 - focusDistance01 - farFocusRange01);
float b1 = (1.0f - a1 * nearDistance01), b2 = (1.0f - a2 * farDistance01);
const float c1 = -1.0f;
const float c2 = 1.0f;
blurParams = new Vector4(c1 * a1, c1 * b1, c2 * a2, c2 * b2);
blurCoe = new Vector4(0.0f, 0.0f, (b2 - b1) / (a1 - a2), 0.0f);
}
}
private void ReleaseComputeResources()
{
if (m_ComputeBufferDrawArgs != null)
m_ComputeBufferDrawArgs.Release();
if (m_ComputeBufferPoints != null)
m_ComputeBufferPoints.Release();
m_ComputeBufferDrawArgs = null;
m_ComputeBufferPoints = null;
}
private void ComputeBlurDirections(bool force)
{
if (!force && Math.Abs(m_LastApertureOrientation - settings.apertureOrientation) < float.Epsilon)
return;
m_LastApertureOrientation = settings.apertureOrientation;
float rotationRadian = settings.apertureOrientation * Mathf.Deg2Rad;
float cosinus = Mathf.Cos(rotationRadian);
float sinus = Mathf.Sin(rotationRadian);
m_OctogonalBokehDirection1 = new Vector4(0.5f, 0.0f, 0.0f, 0.0f);
m_OctogonalBokehDirection2 = new Vector4(0.0f, 0.5f, 1.0f, 0.0f);
m_OctogonalBokehDirection3 = new Vector4(-0.353553f, 0.353553f, 1.0f, 0.0f);
m_OctogonalBokehDirection4 = new Vector4(0.353553f, 0.353553f, 1.0f, 0.0f);
m_HexagonalBokehDirection1 = new Vector4(0.5f, 0.0f, 0.0f, 0.0f);
m_HexagonalBokehDirection2 = new Vector4(0.25f, 0.433013f, 1.0f, 0.0f);
m_HexagonalBokehDirection3 = new Vector4(0.25f, -0.433013f, 1.0f, 0.0f);
if (rotationRadian > float.Epsilon)
{
Rotate2D(ref m_OctogonalBokehDirection1, cosinus, sinus);
Rotate2D(ref m_OctogonalBokehDirection2, cosinus, sinus);
Rotate2D(ref m_OctogonalBokehDirection3, cosinus, sinus);
Rotate2D(ref m_OctogonalBokehDirection4, cosinus, sinus);
Rotate2D(ref m_HexagonalBokehDirection1, cosinus, sinus);
Rotate2D(ref m_HexagonalBokehDirection2, cosinus, sinus);
Rotate2D(ref m_HexagonalBokehDirection3, cosinus, sinus);
}
}
private bool shouldPerformBokeh
{
get { return ImageEffectHelper.supportsDX11 && bokehTexture.texture != null && textureBokehMaterial && settings.tweakMode != TweakMode.Basic; }
}
private static void Rotate2D(ref Vector4 direction, float cosinus, float sinus)
{
Vector4 source = direction;
direction.x = source.x * cosinus - source.y * sinus;
direction.y = source.x * sinus + source.y * cosinus;
}
private static void SwapRenderTexture(ref RenderTexture src, ref RenderTexture dst)
{
RenderTexture tmp = dst;
dst = src;
src = tmp;
}
private static void GetDirectionalBlurPassesFromRadius(RenderTexture blurredFgCoc, float maxRadius, out int blurPass, out int blurAndMergePass)
{
if (blurredFgCoc == null)
{
if (maxRadius > 10.0f)
{
blurPass = (int)Passes.ShapeHighQuality;
blurAndMergePass = (int)Passes.ShapeHighQualityMerge;
}
else if (maxRadius > 5.0f)
{
blurPass = (int)Passes.ShapeMediumQuality;
blurAndMergePass = (int)Passes.ShapeMediumQualityMerge;
}
else
{
blurPass = (int)Passes.ShapeLowQuality;
blurAndMergePass = (int)Passes.ShapeLowQualityMerge;
}
}
else
{
if (maxRadius > 10.0f)
{
blurPass = (int)Passes.ShapeHighQualityDilateFg;
blurAndMergePass = (int)Passes.ShapeHighQualityMergeDilateFg;
}
else if (maxRadius > 5.0f)
{
blurPass = (int)Passes.ShapeMediumQualityDilateFg;
blurAndMergePass = (int)Passes.ShapeMediumQualityMergeDilateFg;
}
else
{
blurPass = (int)Passes.ShapeLowQualityDilateFg;
blurAndMergePass = (int)Passes.ShapeLowQualityMergeDilateFg;
}
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Msagl.Core.DataStructures;
using Microsoft.Msagl.Core.Geometry;
using Microsoft.Msagl.Core.Geometry.Curves;
using Microsoft.Msagl.Layout.LargeGraphLayout;
#if TEST_MSAGL
using Microsoft.Msagl.DebugHelpers;
using System.Diagnostics;
#endif
namespace Microsoft.Msagl.Core.Layout {
/// <summary>
/// This class keeps the graph nodes, edges, and clusters, together with their geometries
/// </summary>
#if TEST_MSAGL
[Serializable]
#endif
public class GeometryGraph : GeometryObject {
IList<Node> nodes;
EdgeCollection edges;
#if TEST_MSAGL
[NonSerialized]
#endif
Cluster rootCluster;
/// <summary>
/// Creates a new GeometryGraph.
/// </summary>
public GeometryGraph()
{
this.nodes = new NodeCollection(this);
this.edges = new EdgeCollection(this);
this.rootCluster = new Cluster();
}
/// <summary>
/// The root cluster for this graph. Will never be null.
/// </summary>
public Cluster RootCluster
{
get
{
return this.rootCluster;
}
set
{
ValidateArg.IsNotNull(value, "value");
this.rootCluster = value;
}
}
internal Rectangle boundingBox;
/// <summary>
/// Bounding box of the graph
/// </summary>
public override Rectangle BoundingBox {
get { return boundingBox; }
set { boundingBox = value; }
}
double margins;
#if DEBUG && TEST_MSAGL
/// <summary>
/// curves to show debug stuff
/// </summary>
public DebugCurve[] DebugCurves;
#endif
/// <summary>
/// margins width are equal from the left and from the right; they are given in percents
/// </summary>
public double Margins
{
get { return margins; }
set { margins = value; }
}
/// <summary>
/// Width of the graph
/// </summary>
public double Width {
get { return BoundingBox.RightBottom.X - BoundingBox.LeftTop.X; }
}
/// <summary>
/// Height of the graph
/// </summary>
public double Height {
get { return BoundingBox.Height; }
}
/// <summary>
/// Left bound of the graph
/// </summary>
public double Left {
get { return BoundingBox.Left; }
}
/// <summary>
/// Right bound of the graph
/// </summary>
public double Right {
get { return BoundingBox.Right; }
}
/// <summary>
/// Left bottom corner of the graph
/// </summary>
internal Point LeftBottom {
get { return new Point(BoundingBox.Left, BoundingBox.Bottom); }
}
/// <summary>
/// Right top corner of the graph
/// </summary>
internal Point RightTop {
get { return new Point(Right, Top); }
}
/// <summary>
/// Bottom bound of the graph
/// </summary>
public double Bottom {
get { return BoundingBox.Bottom; }
}
/// <summary>
/// Top bound of the graph
/// </summary>
public double Top {
get { return BoundingBox.Bottom + BoundingBox.Height; }
}
/// <summary>
/// The nodes in the graph.
/// </summary>
public IList<Node> Nodes {
get { return nodes; }
set { nodes = value; }
}
/// <summary>
/// Edges of the graph
/// </summary>
public EdgeCollection Edges {
get { return edges; }
set { edges =value; }
}
/// <summary>
/// Returns a collection of all the labels in the graph.
/// </summary>
/// <returns></returns>
public ICollection<Label> CollectAllLabels()
{
return Edges.SelectMany(e => e.Labels).ToList();
}
/// <summary>
/// transforms the graph by the given matrix
/// </summary>
/// <param name="matrix">the matrix</param>
public void Transform(PlaneTransformation matrix) {
foreach (var node in Nodes)
node.Transform(matrix);
foreach (var edge in Edges)
edge.Transform(matrix);
#if DEBUG && TEST_MSAGL
if (DebugCurves != null)
foreach (var dc in DebugCurves)
dc.Curve = dc.Curve.Transform(matrix);
#endif
UpdateBoundingBox();
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public Rectangle PumpTheBoxToTheGraphWithMargins() {
var b = Rectangle.CreateAnEmptyBox();
PumpTheBoxToTheGraph(ref b);
var del=new Point(Margins, -Margins);
b.RightBottom += del;
b.LeftTop -= del;
b.Width = Math.Max(b.Width, MinimalWidth);
b.Height = Math.Max(b.Height, MinimalHeight);
return b;
}
///<summary>
///the minimal width of the graph
///</summary>
public double MinimalWidth { get; set; }
///<summary>
///the minimal height of the graph
///</summary>
public double MinimalHeight { get; set; }
/// <summary>
/// enlarge the rectangle to contain the graph
/// </summary>
/// <param name="b"></param>
void PumpTheBoxToTheGraph(ref Rectangle b) {
foreach (Edge e in Edges) {
if (e.UnderCollapsedCluster()) continue;
if (e.Curve != null) {
var cb = e.Curve.BoundingBox;
cb.Pad(e.LineWidth);
b.Add(cb);
}
foreach (var l in e.Labels.Where(lbl => lbl != null))
b.Add(l.BoundingBox);
}
foreach (Node n in Nodes) {
if (n.UnderCollapsedCluster()) continue;
b.Add(n.BoundingBox);
}
foreach (var c in RootCluster.Clusters) {
if (c.BoundaryCurve == null) {
if (c.RectangularBoundary != null)
c.BoundaryCurve = c.RectangularBoundary.RectangularHull();
}
if (c.BoundaryCurve != null)
b.Add(c.BoundaryCurve.BoundingBox);
}
#if DEBUG && TEST_MSAGL
if(DebugCurves!=null)
foreach (var debugCurve in DebugCurves.Where(d => d.Curve != null))
b.Add(debugCurve.Curve.BoundingBox);
#endif
}
/// <summary>
/// Translates the graph by delta.
/// Assumes bounding box is already up to date.
/// </summary>
public void Translate(Point delta)
{
var nodeSet = new Set<Node>(Nodes);
foreach (var v in Nodes)
v.Center += delta;
foreach (var cluster in RootCluster.AllClustersDepthFirstExcludingSelf()) {
foreach (var node in cluster.Nodes.Where(n => !nodeSet.Contains(n)))
node.Center += delta;
cluster.Center += delta;
cluster.RectangularBoundary.TranslateRectangle(delta);
}
foreach (var e in edges)
e.Translate(delta);
BoundingBox = new Rectangle(BoundingBox.Left + delta.X, BoundingBox.Bottom + delta.Y, new Point(BoundingBox.Width, BoundingBox.Height));
}
/// <summary>
/// Updates the bounding box to fit the contents.
/// </summary>
public void UpdateBoundingBox() {
this.BoundingBox = PumpTheBoxToTheGraphWithMargins();
}
/// <summary>
/// Flatten the list of nodes and clusters
/// </summary>
/// <returns></returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
public IEnumerable<Node> GetFlattenedNodesAndClusters()
{
foreach (Node v in Nodes)
{
yield return v;
}
foreach(Cluster cluster in this.RootCluster.AllClustersDepthFirst())
{
if (cluster != this.RootCluster)
{
yield return cluster;
}
}
}
/// <summary>
/// Finds the first node with the corresponding user data.
/// </summary>
/// <returns>The first node with the given user data. Null if no such node exists.</returns>
public Node FindNodeByUserData(object userData)
{
return this.Nodes.FirstOrDefault(n => n.UserData.Equals(userData));
}
#if TEST_MSAGL
///<summary>
///</summary>
public void SetDebugIds()
{
int id = 0;
foreach (var node in RootCluster.AllClustersDepthFirst())
node.DebugId = id++;
foreach (var node in Nodes)
if (node.DebugId == null)
node.DebugId = id++;
}
internal void CheckClusterConsistency() {
foreach (var cluster in RootCluster.AllClustersDepthFirst())
CheckClusterConsistency(cluster);
}
static void CheckClusterConsistency(Cluster cluster) {
if (cluster.BoundaryCurve == null)
return;
foreach (var child in cluster.Clusters.Concat(cluster.Nodes)) {
var inside=Curve.CurveIsInsideOther(child.BoundaryCurve, cluster.BoundaryCurve);
#if TEST_MSAGL && DEBUG
// if (!inside)
// LayoutAlgorithmSettings.ShowDebugCurves(new DebugCurve("green", cluster.BoundaryCurve), new DebugCurve("red", child.BoundaryCurve));
#endif
Debug.Assert(inside,
"A child of a cluster has to have the BoundaryCurve inside of the BoundaryCurve of the cluster");
}
}
#endif
/// <summary>
/// info of layers for large graph browsing
/// </summary>
public LgData LgData { get; set; }
}
}
| |
// Copyright (c) DotSpatial Team. All rights reserved.
// Licensed under the MIT license. See License.txt file in the project root for full license information.
using System;
using System.Collections.Generic;
using DotSpatial.Data;
using DotSpatial.Serialization;
namespace DotSpatial.Symbology
{
/// <summary>
/// Layer used for labeling features.
/// </summary>
public class LabelLayer : Layer, ILabelLayer
{
#region Fields
private IFeatureLayer _featureLayer;
[Serialize("Symbology")]
private ILabelScheme _symbology;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="LabelLayer"/> class.
/// </summary>
public LabelLayer()
{
Configure();
}
/// <summary>
/// Initializes a new instance of the <see cref="LabelLayer"/> class.
/// </summary>
/// <param name="inFeatureSet">FeatureSet whose features get labeled by this label layer.</param>
public LabelLayer(IFeatureSet inFeatureSet)
{
FeatureSet = inFeatureSet;
Configure();
}
/// <summary>
/// Initializes a new instance of the <see cref="LabelLayer"/> class.
/// </summary>
/// <param name="inFeatureLayer">Layer whose features get labeled by this label layer.</param>
public LabelLayer(IFeatureLayer inFeatureLayer)
{
FeatureSet = inFeatureLayer.DataSet;
_featureLayer = inFeatureLayer;
Configure();
}
#endregion
#region Events
/// <summary>
/// Occurs after the selection has been cleared
/// </summary>
public event EventHandler<FeatureChangeArgs> SelectionCleared;
/// <summary>
/// Occurs after the selection is updated by the addition of new members
/// </summary>
public event EventHandler<FeatureChangeEnvelopeArgs> SelectionExtended;
#endregion
#region Properties
/// <summary>
/// Gets or sets the dictionary that quickly identifies the category for
/// each label.
/// </summary>
[ShallowCopy]
public Dictionary<IFeature, LabelDrawState> DrawnStates { get; set; }
/// <summary>
/// Gets or sets the indexed collection of drawn states.
/// </summary>
public FastLabelDrawnState[] FastDrawnStates { get; set; }
/// <summary>
/// Gets or sets an optional layer to link this layer to. If this is specified, then drawing will
/// be associated with this layer. This also updates the FeatureSet property.
/// </summary>
[ShallowCopy]
public IFeatureLayer FeatureLayer
{
get
{
return _featureLayer;
}
set
{
_featureLayer = value;
FeatureSet = _featureLayer.DataSet;
}
}
/// <summary>
/// Gets or sets the featureSet that defines the text for the labels on this layer.
/// </summary>
[ShallowCopy]
public IFeatureSet FeatureSet { get; set; }
/// <summary>
/// Gets or sets the selection symbolizer from the first TextSymbol group.
/// </summary>
[ShallowCopy]
public ILabelSymbolizer SelectionSymbolizer
{
get
{
if (_symbology?.Categories == null || _symbology.Categories.Count == 0) return null;
return _symbology.Categories[0].SelectionSymbolizer;
}
set
{
if (_symbology == null) _symbology = new LabelScheme();
if (_symbology.Categories == null) _symbology.Categories = new BaseList<ILabelCategory>();
if (_symbology.Categories.Count == 0) _symbology.Categories.Add(new LabelCategory());
_symbology.Categories[0].SelectionSymbolizer = value;
}
}
/// <summary>
/// Gets or sets the regular symbolizer from the first TextSymbol group.
/// </summary>
[ShallowCopy]
public ILabelSymbolizer Symbolizer
{
get
{
if (_symbology?.Categories == null || _symbology.Categories.Count == 0) return null;
return _symbology.Categories[0].Symbolizer;
}
set
{
if (_symbology == null) _symbology = new LabelScheme();
if (_symbology.Categories == null) _symbology.Categories = new BaseList<ILabelCategory>();
if (_symbology.Categories.Count == 0) _symbology.Categories.Add(new LabelCategory());
_symbology.Categories[0].Symbolizer = value;
}
}
/// <summary>
/// Gets or sets the labeling scheme as a collection of categories.
/// </summary>
public ILabelScheme Symbology
{
get
{
return _symbology;
}
set
{
_symbology = value;
CreateLabels(); // update the drawn state with the new categories
}
}
#endregion
#region Methods
/// <summary>
/// Clears the current selection, reverting the geometries back to their normal colors.
/// </summary>
public void ClearSelection()
{
}
/// <summary>
/// This builds the _drawnStates based on the current label scheme.
/// </summary>
public virtual void CreateLabels()
{
if (FeatureSet != null && FeatureSet.IndexMode)
{
CreateIndexedLabels();
return;
}
DrawnStates = new Dictionary<IFeature, LabelDrawState>();
if (FeatureSet == null || Symbology == null) return;
foreach (ILabelCategory category in Symbology.Categories)
{
List<IFeature> features = !string.IsNullOrWhiteSpace(category.FilterExpression) ? FeatureSet.SelectByAttribute(category.FilterExpression) : FeatureSet.Features.ToList();
foreach (IFeature feature in features)
{
if (DrawnStates.ContainsKey(feature)) DrawnStates[feature] = new LabelDrawState(category);
else DrawnStates.Add(feature, new LabelDrawState(category));
}
}
}
/// <summary>
/// Highlights the values from a specified region. This will not unselect any members,
/// so if you want to select a new region instead of an old one, first use ClearSelection.
/// This is the default selection that only tests the anchor point, not the entire label.
/// </summary>
/// <param name="region">An Envelope showing a 3D selection box for intersection testing.</param>
/// <returns>True if any members were added to the current selection.</returns>
public bool Select(Extent region)
{
List<IFeature> features = FeatureSet.Select(region);
if (features.Count == 0) return false;
foreach (IFeature feature in features)
{
DrawnStates[feature].Selected = true;
}
return true;
}
/// <summary>
/// Removes the features in the given region.
/// </summary>
/// <param name="region">the geographic region to remove the feature from the selection on this layer.</param>
/// <returns>Boolean true if any features were removed from the selection.</returns>
public bool UnSelect(Extent region)
{
List<IFeature> features = FeatureSet.Select(region);
if (features.Count == 0) return false;
foreach (IFeature feature in features)
{
DrawnStates[feature].Selected = false;
}
return true;
}
/// <summary>
/// This builds the _drawnStates based on the current label scheme.
/// </summary>
protected void CreateIndexedLabels()
{
if (FeatureSet == null) return;
FastDrawnStates = new FastLabelDrawnState[FeatureSet.ShapeIndices.Count];
// DataTable dt = _featureSet.DataTable; // if working correctly, this should auto-populate
if (Symbology == null) return;
foreach (ILabelCategory category in Symbology.Categories)
{
if (category.FilterExpression != null)
{
List<int> features = FeatureSet.SelectIndexByAttribute(category.FilterExpression);
foreach (int feature in features)
{
FastDrawnStates[feature] = new FastLabelDrawnState(category);
}
}
else
{
for (int i = 0; i < FastDrawnStates.Length; i++)
{
FastDrawnStates[i] = new FastLabelDrawnState(category);
}
}
}
}
/// <summary>
/// Fires the selection cleared event.
/// </summary>
/// <param name="args">The arguments.</param>
protected virtual void OnSelectionCleared(FeatureChangeArgs args)
{
SelectionCleared?.Invoke(this, args);
}
/// <summary>
/// Fires the selection extended event.
/// </summary>
/// <param name="args">The arguments.</param>
protected virtual void OnSelectionExtended(FeatureChangeEnvelopeArgs args)
{
SelectionExtended?.Invoke(this, args);
}
private void Configure()
{
if (FeatureSet != null) MyExtent = FeatureSet.Extent.Copy();
_symbology = new LabelScheme();
}
#endregion
}
}
| |
using System;
using System.Globalization;
using System.Net;
using Microsoft.Extensions.DependencyInjection;
using Orleans;
using Orleans.Runtime;
using TestExtensions;
using Xunit;
using Xunit.Abstractions;
namespace UnitTests.General
{
[Collection(TestEnvironmentFixture.DefaultCollection)]
public class IdentifierTests
{
private readonly ITestOutputHelper output;
private readonly TestEnvironmentFixture environment;
private static readonly Random random = new Random();
class A { }
class B : A { }
public IdentifierTests(ITestOutputHelper output, TestEnvironmentFixture fixture)
{
this.output = output;
this.environment = fixture;
}
[Fact]
public void GrainIdUniformHashCodeIsStable()
{
var id = GrainId.Create("type", "key");
var hashCode = id.GetUniformHashCode();
Assert.Equal((uint)2618661990, hashCode);
}
[Fact, TestCategory("BVT"), TestCategory("Identifiers")]
public void UniqueKeyKeyExtGrainCategoryDisallowsNullKeyExtension()
{
Assert.Throws<ArgumentNullException>(() =>
UniqueKey.NewKey(Guid.NewGuid(), category: UniqueKey.Category.KeyExtGrain, keyExt: null));
}
[Fact, TestCategory("BVT"), TestCategory("Identifiers")]
public void UniqueKeyKeyExtGrainCategoryDisallowsEmptyKeyExtension()
{
Assert.Throws<ArgumentException>(() =>
UniqueKey.NewKey(Guid.NewGuid(), category: UniqueKey.Category.KeyExtGrain, keyExt: ""));
}
[Fact, TestCategory("BVT"), TestCategory("Identifiers")]
public void UniqueKeyKeyExtGrainCategoryDisallowsWhiteSpaceKeyExtension()
{
Assert.Throws<ArgumentException>(() =>
UniqueKey.NewKey(Guid.NewGuid(), category: UniqueKey.Category.KeyExtGrain, keyExt: " \t\n\r"));
}
[Fact, TestCategory("BVT"), TestCategory("Identifiers")]
public void ParsingUniqueKeyStringificationShouldReproduceAnIdenticalObject()
{
UniqueKey expected1 = UniqueKey.NewKey(Guid.NewGuid());
string str1 = expected1.ToHexString();
UniqueKey actual1 = UniqueKey.Parse(str1.AsSpan());
Assert.Equal(expected1, actual1); // UniqueKey.ToString() and UniqueKey.Parse() failed to reproduce an identical object (case 1).
string kx3 = "case 3";
UniqueKey expected3 = UniqueKey.NewKey(Guid.NewGuid(), category: UniqueKey.Category.KeyExtGrain, keyExt: kx3);
string str3 = expected3.ToHexString();
UniqueKey actual3 = UniqueKey.Parse(str3.AsSpan());
Assert.Equal(expected3, actual3); // UniqueKey.ToString() and UniqueKey.Parse() failed to reproduce an identical object (case 3).
long pk = random.Next();
UniqueKey expected4 = UniqueKey.NewKey(pk);
string str4 = expected4.ToHexString();
UniqueKey actual4 = UniqueKey.Parse(str4.AsSpan());
Assert.Equal(expected4, actual4); // UniqueKey.ToString() and UniqueKey.Parse() failed to reproduce an identical object (case 4).
pk = random.Next();
string kx5 = "case 5";
UniqueKey expected5 = UniqueKey.NewKey(pk, category: UniqueKey.Category.KeyExtGrain, keyExt: kx5);
string str5 = expected5.ToHexString();
UniqueKey actual5 = UniqueKey.Parse(str5.AsSpan());
Assert.Equal(expected5, actual5); // UniqueKey.ToString() and UniqueKey.Parse() failed to reproduce an identical object (case 5).
}
[Fact, TestCategory("BVT"), TestCategory("Identifiers")]
public void GrainIdShouldEncodeAndDecodePrimaryKeyGuidCorrectly()
{
const int repeat = 100;
for (int i = 0; i < repeat; ++i)
{
Guid expected = Guid.NewGuid();
GrainId grainId = GrainId.Create(GrainType.Create("foo"), GrainIdKeyExtensions.CreateGuidKey(expected));
Guid actual = grainId.GetGuidKey();
Assert.Equal(expected, actual); // Failed to encode and decode grain id
}
}
[Fact, TestCategory("SlowBVT"), TestCategory("Functional"), TestCategory("Identifiers")]
public void GrainId_ToFromPrintableString()
{
Guid guid = Guid.NewGuid();
GrainId grainId = GrainId.Create(GrainType.Create("test"), GrainIdKeyExtensions.CreateGuidKey(guid));
GrainId roundTripped = RoundTripGrainIdToParsable(grainId);
Assert.Equal(grainId, roundTripped); // GrainId.ToPrintableString -- Guid key
string extKey = "Guid-ExtKey-1";
guid = Guid.NewGuid();
grainId = GrainId.Create(GrainType.Create("test"), GrainIdKeyExtensions.CreateGuidKey(guid, extKey));
roundTripped = RoundTripGrainIdToParsable(grainId);
Assert.Equal(grainId, roundTripped); // GrainId.ToPrintableString -- Guid key + Extended Key
grainId = GrainId.Create(GrainType.Create("test"), GrainIdKeyExtensions.CreateGuidKey(guid, null));
roundTripped = RoundTripGrainIdToParsable(grainId);
Assert.Equal(grainId, roundTripped); // GrainId.ToPrintableString -- Guid key + null Extended Key
long key = random.Next();
grainId = GrainId.Create(GrainType.Create("test"), GrainIdKeyExtensions.CreateIntegerKey(key));
roundTripped = RoundTripGrainIdToParsable(grainId);
Assert.Equal(grainId, roundTripped); // GrainId.ToPrintableString -- Int64 key
extKey = "Long-ExtKey-2";
key = random.Next();
grainId = GrainId.Create(GrainType.Create("test"), GrainIdKeyExtensions.CreateIntegerKey(key, extKey));
roundTripped = RoundTripGrainIdToParsable(grainId);
Assert.Equal(grainId, roundTripped); // GrainId.ToPrintableString -- Int64 key + Extended Key
key = UniqueKey.NewKey(key).PrimaryKeyToLong();
grainId = GrainId.Create(GrainType.Create("test"), GrainIdKeyExtensions.CreateIntegerKey(key, extKey));
roundTripped = RoundTripGrainIdToParsable(grainId);
Assert.Equal(grainId, roundTripped); // GrainId.ToPrintableString -- Int64 key + null Extended Key
}
private GrainId RoundTripGrainIdToParsable(GrainId input)
{
string str = input.ToString();
return GrainId.Parse(str);
}
[Fact, TestCategory("BVT"), TestCategory("Identifiers")]
public void UniqueTypeCodeDataShouldStore32BitsOfInformation()
{
const int expected = unchecked((int)0xfabccbaf);
var uk = UniqueKey.NewKey(0, UniqueKey.Category.None, expected);
var actual = uk.BaseTypeCode;
Assert.Equal(expected, actual);
}
[Fact, TestCategory("BVT"), TestCategory("Identifiers")]
public void UniqueKeysShouldPreserveTheirPrimaryKeyValueIfItIsGuid()
{
const int all32Bits = unchecked((int)0xffffffff);
var expectedKey1 = Guid.NewGuid();
const string expectedKeyExt1 = "1";
var uk1 = UniqueKey.NewKey(expectedKey1, UniqueKey.Category.KeyExtGrain, all32Bits, expectedKeyExt1);
string actualKeyExt1;
var actualKey1 = uk1.PrimaryKeyToGuid(out actualKeyExt1);
Assert.Equal(expectedKey1, actualKey1); //"UniqueKey objects should preserve the value of their primary key (Guid case #1).");
Assert.Equal(expectedKeyExt1, actualKeyExt1); //"UniqueKey objects should preserve the value of their key extension (Guid case #1).");
var expectedKey2 = Guid.NewGuid();
const string expectedKeyExt2 = "2";
var uk2 = UniqueKey.NewKey(expectedKey2, UniqueKey.Category.KeyExtGrain, all32Bits, expectedKeyExt2);
string actualKeyExt2;
var actualKey2 = uk2.PrimaryKeyToGuid(out actualKeyExt2);
Assert.Equal(expectedKey2, actualKey2); // "UniqueKey objects should preserve the value of their primary key (Guid case #2).");
Assert.Equal(expectedKeyExt2, actualKeyExt2); // "UniqueKey objects should preserve the value of their key extension (Guid case #2).");
}
[Fact, TestCategory("BVT"), TestCategory("Identifiers")]
public void UniqueKeysShouldPreserveTheirPrimaryKeyValueIfItIsLong()
{
const int all32Bits = unchecked((int)0xffffffff);
var n1 = random.Next();
var n2 = random.Next();
const string expectedKeyExt = "1";
var expectedKey = unchecked((long)((((ulong)((uint)n1)) << 32) | ((uint)n2)));
var uk = UniqueKey.NewKey(expectedKey, UniqueKey.Category.KeyExtGrain, all32Bits, expectedKeyExt);
string actualKeyExt;
var actualKey = uk.PrimaryKeyToLong(out actualKeyExt);
Assert.Equal(expectedKey, actualKey); // "UniqueKey objects should preserve the value of their primary key (long case).");
Assert.Equal(expectedKeyExt, actualKeyExt); // "UniqueKey objects should preserve the value of their key extension (long case).");
}
[Fact, TestCategory("BVT"), TestCategory("Identifiers")]
public void ID_HashCorrectness()
{
// This tests that our optimized Jenkins hash computes the same value as the reference implementation
int testCount = 1000;
for (int i = 0; i < testCount; i++)
{
byte[] byteData = new byte[24];
random.NextBytes(byteData);
ulong u1 = BitConverter.ToUInt64(byteData, 0);
ulong u2 = BitConverter.ToUInt64(byteData, 8);
ulong u3 = BitConverter.ToUInt64(byteData, 16);
var referenceHash = JenkinsHash.ComputeHash(byteData);
var optimizedHash = JenkinsHash.ComputeHash(u1, u2, u3);
Assert.Equal(referenceHash, optimizedHash); // "Optimized hash value doesn't match the reference value for inputs {0}, {1}, {2}", u1, u2, u3
}
}
[Fact, TestCategory("BVT"), TestCategory("Identifiers")]
public void ID_Interning_GrainID()
{
Guid guid = new Guid();
GrainId gid1 = LegacyGrainId.FromParsableString(guid.ToString("B"));
GrainId gid2 = LegacyGrainId.FromParsableString(guid.ToString("N"));
Assert.Equal(gid1, gid2); // Should be equal GrainId's
// Round-trip through Serializer
GrainId gid3 = this.environment.Serializer.Deserialize<GrainId>(environment.Serializer.SerializeToArray(gid1));
Assert.Equal(gid1, gid3); // Should be equal GrainId's
Assert.Equal(gid2, gid3); // Should be equal GrainId's
}
[Fact, TestCategory("BVT"), TestCategory("Identifiers")]
public void ID_Interning_string_equals()
{
using var interner = new Interner<string, string>();
const string str = "1";
string r1 = interner.FindOrCreate("1", _ => str);
string r2 = interner.FindOrCreate("1", _ => null); // Should always be found
Assert.Equal(r1, r2); // 1: Objects should be equal
Assert.Same(r1, r2); // 2: Objects should be same / intern'ed
// Round-trip through Serializer
string r3 = this.environment.Serializer.Deserialize<string>(environment.Serializer.SerializeToArray(r1));
Assert.Equal(r1, r3); // 3: Should be equal
Assert.Equal(r2, r3); // 4: Should be equal
}
[Fact, TestCategory("BVT"), TestCategory("Identifiers")]
public void ID_Intern_FindOrCreate_derived_class()
{
using var interner = new Interner<int, A>();
var obj1 = new A();
var obj2 = new B();
var obj3 = new B();
var r1 = interner.FindOrCreate(1, _ => obj1);
Assert.Equal(obj1, r1); // Objects should be equal
Assert.Same(obj1, r1); // Objects should be same / intern'ed
var r2 = interner.FindOrCreate(2, _ => obj2);
Assert.Equal(obj2, r2); // Objects should be equal
Assert.Same(obj2, r2); // Objects should be same / intern'ed
// FindOrCreate should not replace instances of same class
var r3 = interner.FindOrCreate(2, _ => obj3);
Assert.Same(obj2, r3); // FindOrCreate should return previous object
Assert.NotSame(obj3, r3); // FindOrCreate should not replace previous object of same class
// FindOrCreate should not replace cached instances with instances of most derived class
var r4 = interner.FindOrCreate(1, _ => obj2);
Assert.Same(obj1, r4); // FindOrCreate return previously cached object
Assert.NotSame(obj2, r4); // FindOrCreate should not replace previously cached object
// FindOrCreate should not replace cached instances with instances of less derived class
var r5 = interner.FindOrCreate(2, _ => obj1);
Assert.NotSame(obj1, r5); // FindOrCreate should not replace previously cached object
Assert.Same(obj2, r5); // FindOrCreate return previously cached object
}
[Fact, TestCategory("BVT"), TestCategory("Identifiers")]
public void Interning_SiloAddress()
{
//string addrStr1 = "1.2.3.4@11111@1";
SiloAddress a1 = SiloAddress.New(new IPEndPoint(IPAddress.Loopback, 1111), 12345);
SiloAddress a2 = SiloAddress.New(new IPEndPoint(IPAddress.Loopback, 1111), 12345);
Assert.Equal(a1, a2); // Should be equal SiloAddress's
Assert.Same(a1, a2); // Should be same / intern'ed SiloAddress object
// Round-trip through Serializer
SiloAddress a3 = this.environment.Serializer.Deserialize<SiloAddress>(environment.Serializer.SerializeToArray(a1));
Assert.Equal(a1, a3); // Should be equal SiloAddress's
Assert.Equal(a2, a3); // Should be equal SiloAddress's
Assert.Same(a1, a3); // Should be same / intern'ed SiloAddress object
Assert.Same(a2, a3); // Should be same / intern'ed SiloAddress object
}
[Fact, TestCategory("BVT"), TestCategory("Identifiers")]
public void Interning_SiloAddress2()
{
SiloAddress a1 = SiloAddress.New(new IPEndPoint(IPAddress.Loopback, 1111), 12345);
SiloAddress a2 = SiloAddress.New(new IPEndPoint(IPAddress.Loopback, 2222), 12345);
Assert.NotEqual(a1, a2); // Should not be equal SiloAddress's
Assert.NotSame(a1, a2); // Should not be same / intern'ed SiloAddress object
}
[Fact, TestCategory("BVT"), TestCategory("Identifiers")]
public void Interning_SiloAddress_Serialization()
{
SiloAddress a1 = SiloAddress.New(new IPEndPoint(IPAddress.Loopback, 1111), 12345);
// Round-trip through Serializer
SiloAddress a3 = this.environment.Serializer.Deserialize<SiloAddress>(environment.Serializer.SerializeToArray(a1));
Assert.Equal(a1, a3); // Should be equal SiloAddress's
Assert.Same(a1, a3); // Should be same / intern'ed SiloAddress object
}
[Fact, TestCategory("BVT"), TestCategory("Identifiers")]
public void SiloAddress_ToFrom_ParsableString()
{
SiloAddress address1 = SiloAddressUtils.NewLocalSiloAddress(12345);
string addressStr1 = address1.ToParsableString();
SiloAddress addressObj1 = SiloAddress.FromParsableString(addressStr1);
output.WriteLine("Convert -- From: {0} Got result string: '{1}' object: {2}",
address1, addressStr1, addressObj1);
Assert.Equal(address1, addressObj1); // SiloAddress equal after To-From-ParsableString
//const string addressStr2 = "127.0.0.1-11111-144611139";
const string addressStr2 = "127.0.0.1:11111@144611139";
SiloAddress addressObj2 = SiloAddress.FromParsableString(addressStr2);
string addressStr2Out = addressObj2.ToParsableString();
output.WriteLine("Convert -- From: {0} Got result string: '{1}' object: {2}",
addressStr2, addressStr2Out, addressObj2);
Assert.Equal(addressStr2, addressStr2Out); // SiloAddress equal after From-To-ParsableString
}
[Fact, TestCategory("BVT"), TestCategory("Identifiers"), TestCategory("GrainReference")]
public void GrainReference_Test1()
{
Guid guid = Guid.NewGuid();
GrainId regularGrainId = LegacyGrainId.GetGrainIdForTesting(guid);
GrainReference grainRef = (GrainReference)this.environment.InternalGrainFactory.GetGrain(regularGrainId);
TestGrainReference(grainRef);
grainRef = (GrainReference)this.environment.InternalGrainFactory.GetGrain(regularGrainId);
TestGrainReference(grainRef);
}
private void TestGrainReference(GrainReference grainRef)
{
GrainReference roundTripped = RoundTripGrainReferenceToKey(grainRef);
Assert.Equal(grainRef, roundTripped); // GrainReference.ToKeyString
roundTripped = this.environment.Serializer.Deserialize<GrainReference>(environment.Serializer.SerializeToArray(grainRef));
Assert.Equal(grainRef, roundTripped); // GrainReference.OrleansSerializer
}
private GrainReference RoundTripGrainReferenceToKey(GrainReference input)
{
string str = input.ToKeyString();
GrainReference output = this.environment.Services.GetRequiredService<GrainReferenceKeyStringConverter>().FromKeyString(str);
return output;
}
}
}
| |
using UnityEngine;
using System.Collections.Generic;
[AddComponentMenu("Strategy/Trade Route")]
public class TradeRoute : MonoBehaviour
{
[System.Serializable]
public class Item
{
public int id = 0; // Resource's ID
public Town town = null; // Town that owns this resource
}
static public List<TradeRoute> list = new List<TradeRoute>();
static public float globalAlpha = 1f;
// The two connected towns
public Town town0 = null;
public Town town1 = null;
// Controls whether this trade route is visible
public float targetAlpha = 1.0f;
// Texture used to draw the path
public Texture2D texture = null;
// Shared material
private static Material mMat = null;
// Spline created with the points above
private SplineV mOriginal = new SplineV();
private SplineV mNormalized = new SplineV();
private bool mRebuild = false;
private Mesh mMesh = null;
private MeshFilter mFilter = null;
private MeshRenderer mRen = null;
private float mAlpha = 0f;
private float mLength = 0f;
private Vector3 mTooltipPos;
/// <summary>
/// List of traded items
/// </summary>
public List<Item> items = new List<Item>();
/// <summary>
/// List of all ships assigned to this trade route
/// </summary>
public List<AvailableShips.Owned> ships = new List<AvailableShips.Owned>();
/// <summary>
/// Read-only access to connected towns
/// </summary>
public SplineV path { get { return mOriginal; } }
/// <summary>
/// Gets the normalized spline path.
/// </summary>
public SplineV normalizedPath { get { return mNormalized; } }
/// <summary>
/// Gets a value indicating whether this <see cref="TradeRoute"/> is valid.
/// </summary>
public bool isValid { get { return (town0 != null) && (town1 != null); } }
/// <summary>
/// Gets the length of the trade route.
/// </summary>
public float length { get { return isValid ? mLength : 0f; } }
/// <summary>
/// Sample the trade route spline at the specified time.
/// </summary>
public Vector3 Sample (float time) { return mOriginal.Sample(time, SplineV.SampleType.Spline); }
/// <summary>
/// Connect the specified town.
/// </summary>
public bool Connect (Town town)
{
if (town0 == null)
{
town0 = town;
Add(town.anchor);
}
else if (town1 == null && town0 != town)
{
Add(town.anchor);
town1 = town;
}
return (town1 != null);
}
/// <summary>
/// Adds a new point to the trade route.
/// </summary>
public void Add (Vector3 v)
{
if (town0 != null && town1 == null)
{
v.y = 0.05f;
if (mOriginal.isValid)
{
mOriginal.AddKey(mOriginal.endTime + (v - mOriginal.end).magnitude, v);
}
else
{
mOriginal.AddKey(0.0f, v);
}
mRebuild = true;
}
}
/// <summary>
/// Removes the last added trade route point.
/// </summary>
public bool UndoAdd()
{
if (mOriginal.isValid)
{
mOriginal.list.RemoveAt(mOriginal.list.Count - 1);
mRebuild = true;
return true;
}
return false;
}
/// <summary>
/// Copies the trade route path from the specified trade route.
/// </summary>
public void CopyPath (SplineV sp)
{
mRebuild = true;
mOriginal.Clear();
foreach (SplineV.CtrlPoint cp in sp.list) mOriginal.AddKey(cp.mTime, cp.mVal);
}
/// <summary>
/// Returns the town connected to the specified town if it's in this trade route.
/// </summary>
public Town GetConnectedTown (Town town)
{
if (town0 == town) return town1;
if (town1 == town) return town0;
return null;
}
/// <summary>
/// Gets the traded resource's owner, or null if it's not being traded.
/// </summary>
public Town GetExportedResourceOwner (int id)
{
foreach (Item item in items)
{
if (item.id == id)
{
return item.town;
}
}
return null;
}
/// <summary>
/// Sets the specified town's resource as being traded via the trade route.
/// </summary>
public void SetExportedResource (Town owner, int id)
{
foreach (Item item in items)
{
if (item.id == id)
{
if (owner == null)
{
items.Remove(item);
item.town.resources[id].beingTraded = false;
}
else item.town = owner;
return;
}
}
if (owner != null)
{
Item item = new Item();
item.town = owner;
item.id = id;
items.Add(item);
owner.resources[id].beingTraded = true;
}
}
/// <summary>
/// Assigns the specified ship to this trade route.
/// </summary>
public void AssignShip (AvailableShips.Owned ship)
{
if (ship.tradeRoute != this)
{
if (ship.tradeRoute != null) ship.tradeRoute.UnassignShip(ship);
ship.tradeRoute = this;
ships.Add(ship);
if (ship.prefab != null)
{
Vector3 start = mOriginal.Sample(0f, SplineV.SampleType.Linear);
Vector3 next = mOriginal.Sample(1f, SplineV.SampleType.Linear);
GameObject go = Instantiate(ship.prefab.prefab, start, Quaternion.LookRotation(next - start)) as GameObject;
if (go != null)
{
// Replace the possible multiple colliders with a single one residing at root
Collider[] cols = go.GetComponentsInChildren<Collider>();
if (cols.Length > 1)
{
foreach (Collider col in cols) Destroy(col);
go.AddComponent<BoxCollider>();
}
ship.asset = go;
go.AddComponent<Highlightable>();
TradeShip script = go.AddComponent<TradeShip>();
script.tradeRoute = this;
script.prefab = ship.prefab;
script.speed = ship.prefab.speed;
}
}
}
}
/// <summary>
/// Unassigns the specified ship from this trade route.
/// </summary>
public void UnassignShip (AvailableShips.Owned ship)
{
if (ship.tradeRoute == this)
{
ships.Remove(ship);
ship.tradeRoute = null;
if (ship.asset != null)
{
Object.Destroy(ship.asset);
ship.asset = null;
}
}
}
/// <summary>
/// Adds this trade route to the list.
/// </summary>
void OnEnable()
{
list.Add(this);
name = "Trade Route " + GetInstanceID();
}
/// <summary>
/// Removes this trade route from the list.
/// </summary>
void OnDisable()
{
list.Remove(this);
if (mFilter != null)
{
Object.Destroy(mFilter);
mFilter = null;
}
if (mMesh != null)
{
Object.Destroy(mMesh);
mMesh = null;
}
mRebuild = true;
if (Config.Instance != null) Config.Instance.onGUI.Remove(DrawGUI);
}
/// <summary>
/// Start this instance.
/// </summary>
void Start()
{
Config.Instance.onGUI.Add(DrawGUI);
}
/// <summary>
/// Draw the trade route's name.
/// </summary>
void DrawGUI()
{
if (town0 != null && town1 != null && mAlpha > 0.001f)
{
Vector3 pos = UI.GetScreenPos(mTooltipPos);
if (UI.IsVisible(pos) && pos.z < 100f)
{
Rect rect = new Rect(pos.x - 150f, pos.y - 20f, 300f, 40f);
bool hover = rect.Contains(UI.GetMousePos());
targetAlpha = hover ? 1f : 0.5f;
UI.SetAlpha(mAlpha);
UI.DrawTitle(new Rect(pos.x - 150f, pos.y - 20f, 300f, 20f),
town0.name + " - " + town1.name, Config.Instance.infoStyle);
//UI.DrawTitle(new Rect(pos.x - 150f, pos.y, 300f, 20f),
// Mathf.RoundToInt(mLength) + " miles, " + (GetIncomePerTurn() * 6) + " gold/day",
// Config.Instance.infoStyle);
UI.RestoreAlpha();
}
}
}
/// <summary>
/// Update this instance.
/// </summary>
void Update()
{
bool wasVisible = mAlpha > 0.001f;
float factor = Mathf.Min(1f, Time.deltaTime * 5f);
mAlpha = Mathf.Lerp(mAlpha, targetAlpha * globalAlpha, factor);
if (mAlpha > 0.001f)
{
if (mRebuild)
{
if (mOriginal.isValid)
{
mRebuild = false;
if (mMesh == null)
{
mMesh = new Mesh();
mMesh.name = "Trade Route " + GetInstanceID();
}
if (mFilter == null)
{
mFilter = gameObject.AddComponent<MeshFilter>();
mFilter.mesh = mMesh;
}
if (mMat == null)
{
Shader shader = Shader.Find("Transparent/Diffuse");
mMat = new Material(shader);
mMat.name = "Trade Route";
mMat.mainTexture = texture;
}
if (mRen == null)
{
mRen = gameObject.AddComponent<MeshRenderer>();
mRen.material = mMat;
mRen.castShadows = false;
mRen.receiveShadows = false;
}
// Find the center of the spline
Vector3 center = Vector3.zero;
foreach (SplineV.CtrlPoint cp in mOriginal.list) center += cp.mVal;
center *= 1.0f / mOriginal.list.Count;
// Reposition the trade route
transform.position = center;
// Re-create the mesh
mLength = mOriginal.GetMagnitude();
int subdivisions = Mathf.RoundToInt(mLength);
CreateMesh(mOriginal, -center, 0.15f, subdivisions);
// Create the normalized path that will be used for sampling
mNormalized = SplineV.Normalize(mOriginal, subdivisions);
mLength = mNormalized.GetMagnitude();
}
else if (mMesh != null)
{
mMesh.Clear();
if (mRen != null) mRen.enabled = false;
}
}
// Update the material color
if (mRen != null)
{
mRen.enabled = true;
mRen.material.color = isValid ? new Color(1f, 1f, 1f, mAlpha * 0.5f) : new Color(1f, 1f, 1f, mAlpha * 0.25f);
}
}
else if (wasVisible)
{
mAlpha = 0f;
mRen.enabled = false;
}
}
/// <summary>
/// Creates a trade route mesh.
/// </summary>
void CreateMesh (SplineV initial, Vector3 offset, float width, int subdivisions)
{
mMesh.Clear();
if (initial.list.Count < 2) return;
SplineV spline = SplineV.Normalize(initial, subdivisions * 4);
float start = spline.startTime;
float length = spline.endTime - start;
// We will need the spline's center for tooltip purposes
mTooltipPos = spline.Sample(start + length * 0.5f, SplineV.SampleType.Spline);
List<Vector3> v = new List<Vector3>();
List<Vector3> n = new List<Vector3>();
List<Vector2> uv = new List<Vector2>();
List<int> faces = new List<int>();
++subdivisions;
for (int i = 0; i < subdivisions; ++i)
{
float f0 = (float)(i - 1) / subdivisions;
float f1 = (float)(i ) / subdivisions;
float f2 = (float)(i + 1) / subdivisions;
float f3 = (float)(i + 2) / subdivisions;
Vector3 s0 = spline.Sample(start + f0 * length, SplineV.SampleType.Linear);
Vector3 s1 = spline.Sample(start + f1 * length, SplineV.SampleType.Linear);
Vector3 s2 = spline.Sample(start + f2 * length, SplineV.SampleType.Linear);
Vector3 s3 = spline.Sample(start + f3 * length, SplineV.SampleType.Linear);
Vector3 dir0 = (s2 - s0).normalized;
Vector3 dir1 = (s3 - s1).normalized;
// Cross(dir, up)
Vector3 tan0 = new Vector3(-dir0.z, 0f, dir0.x);
Vector3 tan1 = new Vector3(-dir1.z, 0f, dir1.x);
tan0 *= width;
tan1 *= width;
Vector3 v0 = s1 - tan0;
Vector3 v1 = s2 - tan1;
Vector3 v2 = s2 + tan1;
Vector3 v3 = s1 + tan0;
v.Add(offset + v1);
n.Add(Vector3.up);
uv.Add(new Vector2(1.0f, f2));
v.Add(offset + v0);
n.Add(Vector3.up);
uv.Add(new Vector2(1.0f, f1));
v.Add(offset + v3);
n.Add(Vector3.up);
uv.Add(new Vector2(0.0f, f1));
v.Add(offset + v2);
n.Add(Vector3.up);
uv.Add(new Vector2(0.0f, f2));
}
for (int i = 0; i < v.Count; i += 4)
{
faces.Add(i);
faces.Add(i+1);
faces.Add(i+2);
faces.Add(i+2);
faces.Add(i+3);
faces.Add(i);
}
// Assign the mesh data
mMesh.vertices = v.ToArray();
mMesh.normals = n.ToArray();
mMesh.uv = uv.ToArray();
mMesh.triangles = faces.ToArray();
}
/// <summary>
/// Finds the next trade route connected to the specified town.
/// </summary>
static public TradeRoute FindNext (TradeRoute tradeRoute, Town town, bool reverse)
{
bool found = false;
TradeRoute first = null;
TradeRoute last = null;
foreach (TradeRoute tr in TradeRoute.list)
{
if (tr == tradeRoute)
{
// Now that we've found the current node, if we're going in reverse, we can use the last node
if (reverse && last != null) return last;
// Remember that we've found the current node
found = true;
}
else if (tr.GetConnectedTown(town) != null)
{
// If the current node has already been found and we're going in order, we're done
if (found && !reverse) return tr;
// Remember this node
if (first == null) first = tr;
last = tr;
}
}
// If we were going in reverse, just return the last available node
if (reverse) return (last == null) ? tradeRoute : last;
// Going in order? Just return the first node.
return (first == null) ? tradeRoute : first;
}
}
| |
using System.Runtime.Serialization;
namespace GoogleApi.Entities.Common.Enums
{
/// <summary>
/// Place Location Types
/// https://developers.google.com/places/supported_types#table1
/// https://developers.google.com/places/supported_types#table2
/// </summary>
public enum PlaceLocationType
{
/// <summary>
/// Unknown is set when unmapped place location types is returned.
/// </summary>
[EnumMember(Value = "unknown")]
Uknown,
/// <summary>
/// Geocode instructs the Place Autocomplete service to return only geocoding results,
/// rather than business results. Generally, you use this request to disambiguate results where the location specified may be indeterminate.
/// </summary>
[EnumMember(Value = "geocode")]
Geocode,
/// <summary>
/// Indicates a precise street address.
/// </summary>
[EnumMember(Value = "street_address")]
Street_Address,
/// <summary>
/// Indicates a named route (such as "US 101").
/// </summary>
[EnumMember(Value = "route")]
Route,
/// <summary>
/// Indicates a major intersection, usually of two major roads.
/// </summary>
[EnumMember(Value = "intersection")]
Intersection,
/// <summary>
/// Indicates a political entity. Usually, this type indicates a polygon of some civil administration.
/// </summary>
[EnumMember(Value = "political")]
Political,
/// <summary>
/// Indicates the national political entity, and is typically the highest order type returned by the Geocoder.
/// </summary>
[EnumMember(Value = "country")]
Country,
/// <summary>
/// Indicates a first-order civil entity below the country level. Within the United States,
/// these administrative levels are states. Not all nations exhibit these administrative levels.
/// </summary>
[EnumMember(Value = "administrative_area_level_1")]
Administrative_Area_Level_1,
/// <summary>
/// Indicates a second-order civil entity below the country level. Within the United States,
/// these administrative levels are counties. Not all nations exhibit these administrative levels.
/// </summary>
[EnumMember(Value = "administrative_area_level_2")]
Administrative_Area_Level_2,
/// <summary>
/// Indicates a third-order civil entity below the country level. This type indicates a minor civil division.
/// Not all nations exhibit these administrative levels.
/// </summary>
[EnumMember(Value = "administrative_area_level_3")]
Administrative_Area_Level_3,
/// <summary>
/// Indicates a fourth-order civil entity below the country level. This type indicates a minor civil division.
/// Not all nations exhibit these administrative levels.
/// </summary>
[EnumMember(Value = "administrative_area_level_4")]
Administrative_Area_Level_4,
/// <summary>
/// Indicates a fifth-order civil entity below the country level. This type indicates a minor civil division.
/// Not all nations exhibit these administrative levels.
/// </summary>
[EnumMember(Value = "administrative_area_level_5")]
Administrative_Area_Level_5,
/// <summary>
/// Indicates a commonly-used alternative name for the entity.
/// </summary>
[EnumMember(Value = "colloquial_area")]
Colloquial_Area,
/// <summary>
/// Indicates an incorporated city or town political entity.
/// </summary>
[EnumMember(Value = "locality")]
Locality,
/// <summary>
/// locality.
/// </summary>
[EnumMember(Value = "sublocality")]
Sublocality,
/// <summary>
/// indicates an first-order civil entity below a locality.
/// </summary>
[EnumMember(Value = "sublocality_level_1")]
Sublocality_Level_1,
/// <summary>
/// indicates an second-order civil entity below a locality.
/// </summary>
[EnumMember(Value = "sublocality_level_2")]
Sublocality_Level_2,
/// <summary>
/// indicates an third-order civil entity below a locality.
/// </summary>
[EnumMember(Value = "sublocality_level_3")]
Sublocality_Level_3,
/// <summary>
/// indicates an first-order civil entity below a locality.
/// </summary>
[EnumMember(Value = "sublocality_level_4")]
Sublocality_Level_4,
/// <summary>
/// indicates an first-order civil entity below a locality.
/// </summary>
[EnumMember(Value = "sublocality_level_5")]
Sublocality_Level_5,
/// <summary>
/// Indicates a named neighborhood
/// </summary>
[EnumMember(Value = "neighborhood")]
Neighborhood,
/// <summary>
/// Indicates a named location, usually a building or collection of buildings with a common name.
/// </summary>
[EnumMember(Value = "premise")]
Premise,
/// <summary>
/// Indicates a first-order entity below a named location, usually a singular building within a collection of buildings with a common name.
/// </summary>
[EnumMember(Value = "subpremise")]
Subpremise,
/// <summary>
/// Indicates a postal code as used to address postal mail within the country.
/// </summary>
[EnumMember(Value = "postal_code")]
Postal_Code,
/// <summary>
/// Indicates a postal code prefix.
/// </summary>
[EnumMember(Value = "postal_code_prefix")]
Postal_Code_Prefix,
/// <summary>
/// Indicates a postal code suffix.
/// </summary>
[EnumMember(Value = "postal_code_suffix")]
Postal_Code_Suffix,
/// <summary>
/// Indicates a prominent natural feature.
/// </summary>
[EnumMember(Value = "natural_feature")]
Natural_Feature,
/// <summary>
/// Indicates a named point of interest. Typically, these "POI"s are prominent local entities that don't easily fit in another category such as "Empire State Building" or "Statue of Liberty."
/// </summary>
[EnumMember(Value = "point_of_interest")]
Point_Of_Interest,
/// <summary>
/// Indicates the floor of a building address.
/// </summary>
[EnumMember(Value = "floor")]
Floor,
/// <summary>
/// post_box indicates a specific postal box.
/// </summary>
[EnumMember(Value = "post_box")]
Post_Box,
/// <summary>
/// postal_town indicates a grouping of geographic areas, such as locality and sublocality, used for mailing addresses in some countries.
/// </summary>
[EnumMember(Value = "postal_town")]
Postal_Town,
/// <summary>
/// room indicates the room of a building address.
/// </summary>
[EnumMember(Value = "room")]
Room,
/// <summary>
/// street_number indicates the precise street number.
/// </summary>
[EnumMember(Value = "street_number")]
Street_Number,
/// <summary>
/// Indicate the location of a public transit stop.
/// </summary>
[EnumMember(Value = "transit_station")]
Transit_Station,
/// <summary>
/// Accounting.
/// </summary>
[EnumMember(Value = "accounting")]
Accounting,
/// <summary>
/// Airport.
/// </summary>
[EnumMember(Value = "airport")]
Airport,
/// <summary>
/// Amusement Park.
/// </summary>
[EnumMember(Value = "amusement_park")]
Amusement_Park,
/// <summary>
/// Aquarium.
/// </summary>
[EnumMember(Value = "aquarium")]
Aquarium,
/// <summary>
/// Art Gallery.
/// </summary>
[EnumMember(Value = "art_gallery")]
Art_Gallery,
/// <summary>
/// Atm.
/// </summary>
[EnumMember(Value = "atm")]
Atm,
/// <summary>
/// Bakery.
/// </summary>
[EnumMember(Value = "bakery")]
Bakery,
/// <summary>
/// Bank.
/// </summary>
[EnumMember(Value = "bank")]
Bank,
/// <summary>
/// Bar.
/// </summary>
[EnumMember(Value = "bar")]
Bar,
/// <summary>
/// Beauty Salon.
/// </summary>
[EnumMember(Value = "beauty_salon")]
Beauty_Salon,
/// <summary>
/// Bicycle Store.
/// </summary>
[EnumMember(Value = "bicycle_store")]
Bicycle_Store,
/// <summary>
/// Book Store.
/// </summary>
[EnumMember(Value = "book_store")]
Book_Store,
/// <summary>
/// Bowling Alley.
/// </summary>
[EnumMember(Value = "bowling_alley")]
Bowling_Alley,
/// <summary>
/// Bus Station.
/// </summary>
[EnumMember(Value = "bus_station")]
Bus_Station,
/// <summary>
/// Cafe.
/// </summary>
[EnumMember(Value = "cafe")]
Cafe,
/// <summary>
/// Campground.
/// </summary>
[EnumMember(Value = "campground")]
Campground,
/// <summary>
/// Car Dealer.
/// </summary>
[EnumMember(Value = "car_dealer")]
Car_Dealer,
/// <summary>
/// Car Rental.
/// </summary>
[EnumMember(Value = "car_rental")]
Car_Rental,
/// <summary>
/// Car Repair.
/// </summary>
[EnumMember(Value = "car_repair")]
Car_Repair,
/// <summary>
/// Car Wash.
/// </summary>
[EnumMember(Value = "car_wash")]
Car_Wash,
/// <summary>
/// Casino.
/// </summary>
[EnumMember(Value = "casino")]
Casino,
/// <summary>
/// Cemetery.
/// </summary>
[EnumMember(Value = "cemetery")]
Cemetery,
/// <summary>
/// Church.
/// </summary>
[EnumMember(Value = "church")]
Church,
/// <summary>
/// City Hall.
/// </summary>
[EnumMember(Value = "city_hall")]
City_Hall,
/// <summary>
/// Clothing Store.
/// </summary>
[EnumMember(Value = "clothing_store")]
Clothing_Store,
/// <summary>
/// Convenience Store.
/// </summary>
[EnumMember(Value = "convenience_store")]
Convenience_Store,
/// <summary>
/// Courthouse.
/// </summary>
[EnumMember(Value = "courthouse")]
Courthouse,
/// <summary>
/// Dentist.
/// </summary>
[EnumMember(Value = "dentist")]
Dentist,
/// <summary>
/// Department Store.
/// </summary>
[EnumMember(Value = "department_store")]
Department_Store,
/// <summary>
/// Doctor.
/// </summary>
[EnumMember(Value = "doctor")]
Doctor,
/// <summary>
/// Electrician.
/// </summary>
[EnumMember(Value = "electrician")]
Electrician,
/// <summary>
/// Electronics Store.
/// </summary>
[EnumMember(Value = "electronics_store")]
Electronics_Store,
/// <summary>
/// Embassy.
/// </summary>
[EnumMember(Value = "embassy")]
Embassy,
/// <summary>
/// Establishment.
/// </summary>
[EnumMember(Value = "establishment")]
Establishment,
/// <summary>
/// Finance.
/// </summary>
[EnumMember(Value = "finance")]
Finance,
/// <summary>
/// Fire Station.
/// </summary>
[EnumMember(Value = "fire_station")]
Fire_Station,
/// <summary>
/// Florist.
/// </summary>
[EnumMember(Value = "florist")]
Florist,
/// <summary>
/// Food.
/// </summary>
[EnumMember(Value = "food")]
Food,
/// <summary>
/// Funeral Home.
/// </summary>
[EnumMember(Value = "funeral_home")]
Funeral_Home,
/// <summary>
/// Furniture Store.
/// </summary>
[EnumMember(Value = "furniture_store")]
Furniture_Store,
/// <summary>
/// Gas Station.
/// </summary>
[EnumMember(Value = "gas_station")]
Gas_Station,
/// <summary>
/// General Contractor.
/// </summary>
[EnumMember(Value = "general_contractor")]
General_Contractor,
/// <summary>
/// Supermarket.
/// </summary>
[EnumMember(Value = "supermarket")]
Supermarket,
/// <summary>
/// Grocery Or Supermarket.
/// </summary>
[EnumMember(Value = "grocery_or_supermarket")]
Grocery_Or_Supermarket,
/// <summary>
/// Gym.
/// </summary>
[EnumMember(Value = "gym")]
Gym,
/// <summary>
/// Hair Care.
/// </summary>
[EnumMember(Value = "hair_care")]
Hair_Care,
/// <summary>
/// Hardware Store.
/// </summary>
[EnumMember(Value = "hardware_store")]
Hardware_Store,
/// <summary>
/// Health.
/// </summary>
[EnumMember(Value = "health")]
Health,
/// <summary>
/// Hindu Temple.
/// </summary>
[EnumMember(Value = "hindu_temple")]
Hindu_Temple,
/// <summary>
/// Home Goods Store.
/// </summary>
[EnumMember(Value = "home_goods_store")]
Home_Goods_Store,
/// <summary>
/// Hospital.
/// </summary>
[EnumMember(Value = "hospital")]
Hospital,
/// <summary>
/// Insurance Agency.
/// </summary>
[EnumMember(Value = "insurance_agency")]
Insurance_Agency,
/// <summary>
/// Jewelry Store.
/// </summary>
[EnumMember(Value = "jewelry_store")]
Jewelry_Store,
/// <summary>
/// Laundry.
/// </summary>
[EnumMember(Value = "laundry")]
Laundry,
/// <summary>
/// Lawyer.
/// </summary>
[EnumMember(Value = "lawyer")]
Lawyer,
/// <summary>
/// Library.
/// </summary>
[EnumMember(Value = "library")]
Library,
/// <summary>
/// Liquor Store.
/// </summary>
[EnumMember(Value = "liquor_store")]
Liquor_Store,
/// <summary>
/// Local Government Office.
/// </summary>
[EnumMember(Value = "local_government_office")]
Local_Government_Office,
/// <summary>
/// Locksmith.
/// </summary>
[EnumMember(Value = "locksmith")]
Locksmith,
/// <summary>
/// Lodging.
/// </summary>
[EnumMember(Value = "lodging")]
Lodging,
/// <summary>
/// Meal Delivery.
/// </summary>
[EnumMember(Value = "meal_delivery")]
Meal_Delivery,
/// <summary>
///
/// </summary>
[EnumMember(Value = "meal_takeaway")]
Meal_Takeaway,
/// <summary>
/// Mosque.
/// </summary>
[EnumMember(Value = "mosque")]
Mosque,
/// <summary>
/// Movie Rental.
/// </summary>
[EnumMember(Value = "movie_rental")]
Movie_Rental,
/// <summary>
/// Movie Theater.
/// </summary>
[EnumMember(Value = "movie_theater")]
Movie_Theater,
/// <summary>
/// Moving Company.
/// </summary>
[EnumMember(Value = "moving_company")]
Moving_Company,
/// <summary>
/// Museum.
/// </summary>
[EnumMember(Value = "museum")]
Museum,
/// <summary>
/// Night Club.
/// </summary>
[EnumMember(Value = "night_club")]
Night_Club,
/// <summary>
/// Painter.
/// </summary>
[EnumMember(Value = "painter")]
Painter,
/// <summary>
/// Park.
/// </summary>
[EnumMember(Value = "park")]
Park,
/// <summary>
/// Parking.
/// </summary>
[EnumMember(Value = "parking")]
Parking,
/// <summary>
/// Pet Store.
/// </summary>
[EnumMember(Value = "pet_store")]
Pet_Store,
/// <summary>
/// Pharmacy.
/// </summary>
[EnumMember(Value = "pharmacy")]
Pharmacy,
/// <summary>
/// Physiotherapist.
/// </summary>
[EnumMember(Value = "physiotherapist")]
Physiotherapist,
/// <summary>
/// Place Of Worship.
/// </summary>
[EnumMember(Value = "place_of_worship")]
Place_Of_Worship,
/// <summary>
/// Plumber.
/// </summary>
[EnumMember(Value = "plumber")]
Plumber,
/// <summary>
/// Police.
/// </summary>
[EnumMember(Value = "police")]
Police,
/// <summary>
/// Post Office.
/// </summary>
[EnumMember(Value = "post_office")]
PostOffice,
/// <summary>
/// Real Estate Agency.
/// </summary>
[EnumMember(Value = "real_estate_agency")]
Real_Estate_Agency,
/// <summary>
/// Restaurant.
/// </summary>
[EnumMember(Value = "restaurant")]
Restaurant,
/// <summary>
/// Roofing Contractor.
/// </summary>
[EnumMember(Value = "roofing_contractor")]
Roofing_Contractor,
/// <summary>
/// Rv Park.
/// </summary>
[EnumMember(Value = "rv_park")]
Rv_Park,
/// <summary>
/// School.
/// </summary>
[EnumMember(Value = "school")]
School,
/// <summary>
///
/// </summary>
[EnumMember(Value = "shoe_store")]
Shoe_Store,
/// <summary>
/// Shopping Mall.
/// </summary>
[EnumMember(Value = "shopping_mall")]
Shopping_Mall,
/// <summary>
/// Spa.
/// </summary>
[EnumMember(Value = "spa")]
Spa,
/// <summary>
/// Stadium.
/// </summary>
[EnumMember(Value = "stadium")]
Stadium,
/// <summary>
/// Storage.
/// </summary>
[EnumMember(Value = "storage")]
Storage,
/// <summary>
/// Store-
/// </summary>
[EnumMember(Value = "store")]
Store,
/// <summary>
/// Subway Station.
/// </summary>
[EnumMember(Value = "subway_station")]
Subway_Station,
/// <summary>
/// Synagogue.
/// </summary>
[EnumMember(Value = "synagogue")]
Synagogue,
/// <summary>
/// Tourist Attracton.
/// </summary>
[EnumMember(Value = "tourist_attraction")]
Tourist_Attracton,
/// <summary>
/// Taxi Stand.
/// </summary>
[EnumMember(Value = "taxi_stand")]
Taxi_Stand,
/// <summary>
/// Train Station.
/// </summary>
[EnumMember(Value = "train_station")]
Train_Station,
/// <summary>
/// Travel Agency.
/// </summary>
[EnumMember(Value = "travel_agency")]
Travel_Agency,
/// <summary>
/// University.
/// </summary>
[EnumMember(Value = "university")]
University,
/// <summary>
/// VeterinaryCare.
/// </summary>
[EnumMember(Value = "veterinary_care")]
Veterinary_Care,
/// <summary>
/// Zoo.
/// </summary>
[EnumMember(Value = "zoo")]
Zoo
}
}
| |
// Copyright (c) 1995-2009 held by the author(s). 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 names of the Naval Postgraduate School (NPS)
// Modeling Virtual Environments and Simulation (MOVES) Institute
// (http://www.nps.edu and http://www.MovesInstitute.org)
// 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.
//
// Copyright (c) 2008, MOVES Institute, Naval Postgraduate School. All
// rights reserved. This work is licensed under the BSD open source license,
// available at https://www.movesinstitute.org/licenses/bsd.html
//
// Author: DMcG
// Modified for use with C#:
// - Peter Smith (Naval Air Warfare Center - Training Systems Division)
// - Zvonko Bostjancic (Blubit d.o.o. - zvonko.bostjancic@blubit.si)
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Text;
using System.Xml.Serialization;
using OpenDis.Core;
namespace OpenDis.Dis1998
{
/// <summary>
/// Section 5.2.15. Specifies the character set used inthe first byte, followed by 11 characters of text data.
/// </summary>
[Serializable]
[XmlRoot]
public partial class Marking
{
/// <summary>
/// The character set
/// </summary>
private byte _characterSet;
/// <summary>
/// The characters
/// </summary>
private byte[] _characters = new byte[11];
/// <summary>
/// Initializes a new instance of the <see cref="Marking"/> class.
/// </summary>
public Marking()
{
}
/// <summary>
/// Implements the operator !=.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>
/// <c>true</c> if operands are not equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator !=(Marking left, Marking right)
{
return !(left == right);
}
/// <summary>
/// Implements the operator ==.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>
/// <c>true</c> if both operands are equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator ==(Marking left, Marking right)
{
if (object.ReferenceEquals(left, right))
{
return true;
}
if (((object)left == null) || ((object)right == null))
{
return false;
}
return left.Equals(right);
}
public virtual int GetMarshalledSize()
{
int marshalSize = 0;
marshalSize += 1; // this._characterSet
marshalSize += 11 * 1; // _characters
return marshalSize;
}
/// <summary>
/// Gets or sets the The character set
/// </summary>
[XmlElement(Type = typeof(byte), ElementName = "characterSet")]
public byte CharacterSet
{
get
{
return this._characterSet;
}
set
{
this._characterSet = value;
}
}
/// <summary>
/// Gets or sets the The characters
/// </summary>
[XmlArray(ElementName = "characters")]
public byte[] Characters
{
get
{
return this._characters;
}
set
{
this._characters = value;
}
}
/// <summary>
/// Occurs when exception when processing PDU is caught.
/// </summary>
public event EventHandler<PduExceptionEventArgs> ExceptionOccured;
/// <summary>
/// Called when exception occurs (raises the <see cref="Exception"/> event).
/// </summary>
/// <param name="e">The exception.</param>
protected void RaiseExceptionOccured(Exception e)
{
if (Pdu.FireExceptionEvents && this.ExceptionOccured != null)
{
this.ExceptionOccured(this, new PduExceptionEventArgs(e));
}
}
/// <summary>
/// Marshal the data to the DataOutputStream. Note: Length needs to be set before calling this method
/// </summary>
/// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public virtual void Marshal(DataOutputStream dos)
{
if (dos != null)
{
try
{
dos.WriteUnsignedByte((byte)this._characterSet);
for (int idx = 0; idx < this._characters.Length; idx++)
{
dos.WriteByte(this._characters[idx]);
}
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public virtual void Unmarshal(DataInputStream dis)
{
if (dis != null)
{
try
{
this._characterSet = dis.ReadUnsignedByte();
for (int idx = 0; idx < this._characters.Length; idx++)
{
this._characters[idx] = dis.ReadByte();
}
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
}
/// <summary>
/// This allows for a quick display of PDU data. The current format is unacceptable and only used for debugging.
/// This will be modified in the future to provide a better display. Usage:
/// pdu.GetType().InvokeMember("Reflection", System.Reflection.BindingFlags.InvokeMethod, null, pdu, new object[] { sb });
/// where pdu is an object representing a single pdu and sb is a StringBuilder.
/// Note: The supplied Utilities folder contains a method called 'DecodePDU' in the PDUProcessor Class that provides this functionality
/// </summary>
/// <param name="sb">The StringBuilder instance to which the PDU is written to.</param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public virtual void Reflection(StringBuilder sb)
{
sb.AppendLine("<Marking>");
try
{
sb.AppendLine("<characterSet type=\"byte\">" + this._characterSet.ToString(CultureInfo.InvariantCulture) + "</characterSet>");
for (int idx = 0; idx < this._characters.Length; idx++)
{
sb.AppendLine("<characters" + idx.ToString(CultureInfo.InvariantCulture) + " type=\"byte\">" + this._characters[idx] + "</characters" + idx.ToString(CultureInfo.InvariantCulture) + ">");
}
sb.AppendLine("</Marking>");
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
/// <summary>
/// Determines whether the specified <see cref="System.Object"/> is equal to this instance.
/// </summary>
/// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object obj)
{
return this == obj as Marking;
}
/// <summary>
/// Compares for reference AND value equality.
/// </summary>
/// <param name="obj">The object to compare with this instance.</param>
/// <returns>
/// <c>true</c> if both operands are equal; otherwise, <c>false</c>.
/// </returns>
public bool Equals(Marking obj)
{
bool ivarsEqual = true;
if (obj.GetType() != this.GetType())
{
return false;
}
if (this._characterSet != obj._characterSet)
{
ivarsEqual = false;
}
if (obj._characters.Length != 11)
{
ivarsEqual = false;
}
if (ivarsEqual)
{
for (int idx = 0; idx < 11; idx++)
{
if (this._characters[idx] != obj._characters[idx])
{
ivarsEqual = false;
}
}
}
return ivarsEqual;
}
/// <summary>
/// HashCode Helper
/// </summary>
/// <param name="hash">The hash value.</param>
/// <returns>The new hash value.</returns>
private static int GenerateHash(int hash)
{
hash = hash << (5 + hash);
return hash;
}
/// <summary>
/// Gets the hash code.
/// </summary>
/// <returns>The hash code.</returns>
public override int GetHashCode()
{
int result = 0;
result = GenerateHash(result) ^ this._characterSet.GetHashCode();
for (int idx = 0; idx < 11; idx++)
{
result = GenerateHash(result) ^ this._characters[idx].GetHashCode();
}
return result;
}
}
}
| |
using System;
using System.Runtime.InteropServices;
using CXIdxClientFile = System.IntPtr; // void*
using CXIdxClientEntity = System.IntPtr; // void*
using CXIdxClientContainer = System.IntPtr; // void*
using CXIdxClientASTFile = System.IntPtr; // void*
using CXIndexAction = System.IntPtr; // void*
using CXIdxObjCContainerDeclInfoPtr = System.IntPtr; // CXIdxObjCContainerDeclInfo *
using CXIdxObjCInterfaceDeclInfoPtr = System.IntPtr; // CXIdxObjCInterfaceDeclInfo *
using CXIdxObjCCategoryDeclInfoPtr = System.IntPtr; // CXIdxObjCCategoryDeclInfo *
using CXIdxObjCProtocolRefListInfoPtr = System.IntPtr; // CXIdxObjCProtocolRefListInfo *
using CXIdxObjCPropertyDeclInfoPtr = System.IntPtr; // const CXIdxObjCPropertyDeclInfo *
using CXIdxIBOutletCollectionAttrInfoPtr = System.IntPtr; // const CXIdxIBOutletCollectionAttrInfo *
using CXIdxCXXClassDeclInfoPtr = System.IntPtr; // const CXIdxCXXClassDeclInfo *
using CXIndex = System.IntPtr; // void*
using CXFile = System.IntPtr;
using CXModule = System.IntPtr; // void*
using CXClientData = System.IntPtr; // void*
using CXDiagnosticSet = System.IntPtr; // void*
using CXTranslationUnit = System.IntPtr; // CXTranslationUnitImpl*
namespace NClang.Natives
{
[UnmanagedFunctionPointer(LibClang.LibraryCallingConvention)]
delegate VisitorResult CXVisitorResultVisitor (IntPtr context, CXCursor _, CXSourceRange __);
[StructLayout (LayoutKind.Sequential)]
struct CXCursorAndRangeVisitor
{
internal CXCursorAndRangeVisitor (CXVisitorResultVisitor visit)
{
Context = IntPtr.Zero;
Visit = visit;
}
public readonly IntPtr Context;
public readonly CXVisitorResultVisitor Visit;
}
[StructLayout (LayoutKind.Sequential)]
struct CXIdxLoc
{
public IntPtr PtrData1;
public IntPtr PtrData2;
public uint IntData;
}
[StructLayout (LayoutKind.Sequential)]
struct CXIdxIncludedFileInfo
{
public CXIdxLoc HashLoc;
public string Filename;
public CXFile File;
public int IsImport;
public int IsAngled;
public int IsModuleImport;
}
[StructLayout (LayoutKind.Sequential)]
struct CXIdxImportedASTFileInfo
{
public CXIdxImportedASTFileInfo (CXIdxClientFile file, CXIdxClientFile module, CXIdxLoc loc, int isImplicit)
{
this.File = file;
this.Module = module;
this.Loc = loc;
this.IsImplicit = isImplicit;
}
public readonly CXFile File;
public readonly CXModule Module;
public readonly CXIdxLoc Loc;
public readonly int IsImplicit;
}
[StructLayout (LayoutKind.Sequential)]
struct CXIdxAttrInfo
{
public IndexAttributeKind Kind;
public CXCursor Cursor;
public CXIdxLoc Loc;
}
[StructLayout (LayoutKind.Sequential)]
struct CXIdxEntityInfo
{
public IndexEntityKind Kind;
public IndexEntityCxxTemplateKind CxxTemplateKind;
public IndexEntityLanguage Lang;
public string Name;
public string USR;
public CXCursor Cursor;
public IntPtr Attributes; // const CXIdxAttrInfo *const *
public uint NumAttributes;
}
[StructLayout (LayoutKind.Sequential)]
struct CXIdxContainerInfo
{
public CXCursor Cursor;
}
[StructLayout (LayoutKind.Sequential)]
struct CXIdxIBOutletCollectionAttrInfo
{
public IntPtr AttrInfo; // const CXIdxAttrInfo *
public IntPtr ObjcClass; // const CXIdxEntityInfo *
public CXCursor ClassCursor;
public CXIdxLoc ClassLoc;
}
[StructLayout (LayoutKind.Sequential)]
struct CXIdxDeclInfo
{
public IntPtr EntityInfo; // const CXIdxEntityInfo *
public CXCursor Cursor;
public CXIdxLoc Loc;
public IntPtr SemanticContainer; // const CXIdxContainerInfo *
public IntPtr LexicalContainer; // const CXIdxContainerInfo *
public int IsRedeclaration;
public int IsDefinition;
public int IsContainer;
public IntPtr DeclAsContainer; // const CXIdxContainerInfo *
public int IsImplicit;
public IntPtr Attributes; // const CXIdxAttrInfo *const *
public uint NumAttributes;
public IndexDeclInfoFlags Flags;
}
[StructLayout (LayoutKind.Sequential)]
struct CXIdxObjCContainerDeclInfo
{
public IntPtr DeclInfo; // const CXIdxDeclInfo *
public IndexObjCContainerKind Kind;
}
[StructLayout (LayoutKind.Sequential)]
struct CXIdxBaseClassInfo
{
public IntPtr Base; //const CXIdxEntityInfo *
public CXCursor Cursor;
public CXIdxLoc Loc;
}
[StructLayout (LayoutKind.Sequential)]
struct CXIdxObjCProtocolRefInfo
{
public IntPtr Protocol; //const CXIdxEntityInfo *
public CXCursor Cursor;
public CXIdxLoc Loc;
}
[StructLayout (LayoutKind.Sequential)]
struct CXIdxObjCProtocolRefListInfo
{
public IntPtr Protocols; // const CXIdxObjCProtocolRefInfo *const *
public uint NumProtocols;
}
[StructLayout (LayoutKind.Sequential)]
struct CXIdxObjCInterfaceDeclInfo
{
public CXIdxObjCContainerDeclInfoPtr ContainerInfo;
public IntPtr SuperInfo; // const CXIdxBaseClassInfo *
public CXIdxObjCProtocolRefListInfoPtr Protocols;
}
[StructLayout (LayoutKind.Sequential)]
struct CXIdxObjCCategoryDeclInfo
{
public CXIdxObjCContainerDeclInfoPtr ContainerInfo;
public IntPtr ObjcClass; // const CXIdxEntityInfo *
public CXCursor ClassCursor;
public CXIdxLoc ClassLoc;
public CXIdxObjCProtocolRefListInfoPtr Protocols;
}
[StructLayout (LayoutKind.Sequential)]
struct CXIdxObjCPropertyDeclInfo
{
public IntPtr DeclInfo; // const CXIdxDeclInfo *
public IntPtr Getter; // const CXIdxEntityInfo *
public IntPtr Setter; // const CXIdxEntityInfo *
}
[StructLayout (LayoutKind.Sequential)]
struct CXIdxCXXClassDeclInfo
{
public IntPtr DeclInfo; // const CXIdxDeclInfo *
public IntPtr Bases; // const CXIdxBaseClassInfo *const *
public uint NumBases;
}
[StructLayout (LayoutKind.Sequential)]
struct CXIdxEntityRefInfo
{
public IndexEntityRefKind Kind;
public CXCursor Cursor;
public CXIdxLoc Loc;
public IntPtr ReferencedEntity; // const CXIdxEntityInfo *
public IntPtr ParentEntity; // const CXIdxEntityInfo *
public IntPtr Container; // const CXIdxContainerInfo *
}
[UnmanagedFunctionPointer (LibClang.LibraryCallingConvention)]
delegate int AbortQueryHandler (CXClientData client_data, IntPtr reserved);
[UnmanagedFunctionPointer (LibClang.LibraryCallingConvention)]
delegate void DiagnosticHandler (CXClientData client_data,CXDiagnosticSet _,IntPtr reserved);
[UnmanagedFunctionPointer (LibClang.LibraryCallingConvention)]
delegate CXIdxClientFile EnteredMainFileHandler (CXClientData client_data,CXFile mainFile,IntPtr reserved);
[UnmanagedFunctionPointer (LibClang.LibraryCallingConvention)]
delegate CXIdxClientFile PpIncludedFileHandler (CXClientData client_data, IntPtr _); // CXIdxIncludedFileInfo*
[UnmanagedFunctionPointer (LibClang.LibraryCallingConvention)]
delegate CXIdxClientASTFile ImportedASTFileHandler (CXClientData client_data, IntPtr _); // CXIdxImportedASTFileInfo*
[UnmanagedFunctionPointer (LibClang.LibraryCallingConvention)]
delegate CXIdxClientContainer StartedTranslationUnitHandler (CXClientData client_data,IntPtr reserved);
[UnmanagedFunctionPointer (LibClang.LibraryCallingConvention)]
delegate void IndexDeclarationHandler (CXClientData client_data, IntPtr _); // CXIdxDeclInfo*
[UnmanagedFunctionPointer (LibClang.LibraryCallingConvention)]
delegate void IndexEntityReferenceHandler (CXClientData client_data, IntPtr _); // CXIdxEntityRefInfo*
[StructLayout (LayoutKind.Sequential)]
struct IndexerCallbacks
{
[MarshalAs (UnmanagedType.FunctionPtr)]
public AbortQueryHandler AbortQuery;
[MarshalAs (UnmanagedType.FunctionPtr)]
public DiagnosticHandler Diagnostic;
[MarshalAs (UnmanagedType.FunctionPtr)]
public EnteredMainFileHandler EnteredMainFile;
[MarshalAs (UnmanagedType.FunctionPtr)]
public PpIncludedFileHandler PpIncludedFile;
[MarshalAs (UnmanagedType.FunctionPtr)]
public ImportedASTFileHandler ImportedASTFile;
[MarshalAs (UnmanagedType.FunctionPtr)]
public StartedTranslationUnitHandler StartedTranslationUnit;
[MarshalAs (UnmanagedType.FunctionPtr)]
public IndexDeclarationHandler IndexDeclaration;
[MarshalAs (UnmanagedType.FunctionPtr)]
public IndexEntityReferenceHandler IndexEntityReference;
}
delegate VisitorResult FieldVisitor (CXCursor C, CXClientData client_data);
// done
static partial class LibClang
{
[DllImport (LibraryName, CallingConvention = LibraryCallingConvention)]
internal static extern FindResult clang_findReferencesInFile (CXCursor cursor, CXFile file, CXCursorAndRangeVisitor visitor);
[DllImport (LibraryName, CallingConvention = LibraryCallingConvention)]
internal static extern FindResult clang_findIncludesInFile (CXTranslationUnit TU, CXFile file, CXCursorAndRangeVisitor visitor);
[DllImport (LibraryName, CallingConvention = LibraryCallingConvention)]
internal static extern int clang_index_isEntityObjCContainerKind (IndexEntityKind _);
[DllImport (LibraryName, CallingConvention = LibraryCallingConvention)]
internal static extern CXIdxObjCContainerDeclInfoPtr clang_index_getObjCContainerDeclInfo (IntPtr _); // const CXIdxDeclInfo *
[DllImport (LibraryName, CallingConvention = LibraryCallingConvention)]
internal static extern CXIdxObjCInterfaceDeclInfoPtr clang_index_getObjCInterfaceDeclInfo (IntPtr _); // const CXIdxDeclInfo *
[DllImport (LibraryName, CallingConvention = LibraryCallingConvention)]
internal static extern CXIdxObjCCategoryDeclInfoPtr clang_index_getObjCCategoryDeclInfo (IntPtr _); // const CXIdxDeclInfo *
[DllImport (LibraryName, CallingConvention = LibraryCallingConvention)]
internal static extern CXIdxObjCProtocolRefListInfoPtr clang_index_getObjCProtocolRefListInfo (IntPtr _); // const CXIdxDeclInfo *
[DllImport (LibraryName, CallingConvention = LibraryCallingConvention)]
internal static extern CXIdxObjCPropertyDeclInfoPtr clang_index_getObjCPropertyDeclInfo (IntPtr _); // const CXIdxDeclInfo *
[DllImport (LibraryName, CallingConvention = LibraryCallingConvention)]
internal static extern CXIdxIBOutletCollectionAttrInfoPtr clang_index_getIBOutletCollectionAttrInfo (IntPtr _); // const CXIdxAttrInfo *
[DllImport (LibraryName, CallingConvention = LibraryCallingConvention)]
internal static extern CXIdxCXXClassDeclInfoPtr clang_index_getCXXClassDeclInfo (IntPtr _); // const CXIdxDeclInfo *
[DllImport (LibraryName, CallingConvention = LibraryCallingConvention)]
internal static extern CXIdxClientContainer clang_index_getClientContainer (IntPtr _); // const CXIdxContainerInfo *
[DllImport (LibraryName, CallingConvention = LibraryCallingConvention)]
internal static extern void clang_index_setClientContainer (IntPtr _, CXIdxClientContainer __); // const CXIdxContainerInfo *
[DllImport (LibraryName, CallingConvention = LibraryCallingConvention)]
internal static extern CXIdxClientEntity clang_index_getClientEntity (IntPtr _); // const CXIdxEntityInfo *
[DllImport (LibraryName, CallingConvention = LibraryCallingConvention)]
internal static extern void clang_index_setClientEntity (IntPtr _, CXIdxClientEntity __); // const CXIdxEntityInfo *
[DllImport (LibraryName, CallingConvention = LibraryCallingConvention)]
internal static extern CXIndexAction clang_IndexAction_create (CXIndex CIdx);
[DllImport (LibraryName, CallingConvention = LibraryCallingConvention)]
internal static extern void clang_IndexAction_dispose (CXIndexAction _);
[DllImport (LibraryName, CallingConvention = LibraryCallingConvention)]
internal static extern ErrorCode clang_indexSourceFile (CXIndexAction _, CXClientData client_data,
[MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 3)] IndexerCallbacks [] index_callbacks,
uint index_callbacks_size,
IndexOptionFlags index_options,
string source_filename,
[MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 7)] string [] command_line_args, // const char *const *
int num_command_line_args,
[MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 9)] CXUnsavedFile[] unsaved_files,
uint num_unsaved_files,
out CXTranslationUnit out_TU, TranslationUnitFlags TU_options);
[DllImport (LibraryName, CallingConvention = LibraryCallingConvention)]
internal static extern ErrorCode clang_indexSourceFileFullArgv (CXIndexAction _, CXClientData client_data,
[MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 3)] IndexerCallbacks [] index_callbacks,
uint index_callbacks_size,
IndexOptionFlags index_options,
string source_filename,
[MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 7)] string [] command_line_args, // const char *const *
int num_command_line_args,
[MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 9)] CXUnsavedFile [] unsaved_files,
uint num_unsaved_files,
out CXTranslationUnit out_TU, TranslationUnitFlags TU_options);
[DllImport (LibraryName, CallingConvention = LibraryCallingConvention)]
internal static extern ErrorCode clang_indexTranslationUnit (CXIndexAction _, CXClientData client_data,
[MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 3)] IndexerCallbacks [] index_callbacks, uint index_callbacks_size,
IndexOptionFlags index_options, CXTranslationUnit __);
[DllImport (LibraryName, CallingConvention = LibraryCallingConvention)]
internal static extern void clang_indexLoc_getFileLocation (CXIdxLoc loc, out IntPtr indexFile, out IntPtr file, // CXIdxClientFile*, CXIdxClientFile
out uint line, out uint column, out uint offset);
[DllImport (LibraryName, CallingConvention = LibraryCallingConvention)]
internal static extern CXSourceLocation clang_indexLoc_getCXSourceLocation (CXIdxLoc loc);
[DllImport (LibraryName, CallingConvention = LibraryCallingConvention)]
internal static extern uint clang_Type_visitFields (CXType T, FieldVisitor visitor, CXClientData client_data);
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.CodeDom.Compiler
{
using System;
using System.Collections;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.Win32;
using System.Security;
using System.ComponentModel;
using System.Globalization;
using System.Runtime.Versioning;
/// <devdoc>
/// <para>Represents a collection of temporary file names that are all based on a
/// single base filename located in a temporary directory.</para>
/// </devdoc>
internal class TempFileCollection : ICollection, IDisposable
{
private string _tempDir;
private bool _keepFiles;
private Hashtable _files;
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public TempFileCollection() : this(null, false)
{
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public TempFileCollection(string tempDir) : this(tempDir, false)
{
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public TempFileCollection(string tempDir, bool keepFiles)
{
_keepFiles = keepFiles;
_tempDir = tempDir;
#if !FEATURE_CASE_SENSITIVE_FILESYSTEM
_files = new Hashtable(StringComparer.OrdinalIgnoreCase);
#else
files = new Hashtable();
#endif
}
/// <internalonly/>
/// <devdoc>
/// <para> To allow it's stuff to be cleaned up</para>
/// </devdoc>
void IDisposable.Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
// It is safe to call Delete from here even if Dispose is called from Finalizer
// because the graph of objects is guaranteed to be there and
// neither Hashtable nor String have a finalizer of their own that could
// be called before TempFileCollection Finalizer
Delete();
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
~TempFileCollection()
{
Dispose(false);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void AddFile(string fileName, bool keepFile)
{
if (fileName == null || fileName.Length == 0)
throw new ArgumentException(string.Format(SR.InvalidNullEmptyArgument, "fileName"), "fileName"); // fileName not specified
if (_files[fileName] != null)
throw new ArgumentException(string.Format(SR.DuplicateFileName, fileName), "fileName"); // duplicate fileName
_files.Add(fileName, (object)keepFile);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public IEnumerator GetEnumerator()
{
return _files.Keys.GetEnumerator();
}
/// <internalonly/>
IEnumerator IEnumerable.GetEnumerator()
{
return _files.Keys.GetEnumerator();
}
/// <internalonly/>
void ICollection.CopyTo(Array array, int start)
{
_files.Keys.CopyTo(array, start);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void CopyTo(string[] fileNames, int start)
{
_files.Keys.CopyTo(fileNames, start);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public int Count
{
get
{
return _files.Count;
}
}
/// <internalonly/>
int ICollection.Count
{
get { return _files.Count; }
}
/// <internalonly/>
object ICollection.SyncRoot
{
get { return null; }
}
/// <internalonly/>
bool ICollection.IsSynchronized
{
get { return false; }
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public string TempDir
{
get { return _tempDir == null ? string.Empty : _tempDir; }
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public bool KeepFiles
{
get { return _keepFiles; }
set { _keepFiles = value; }
}
private bool KeepFile(string fileName)
{
object keep = _files[fileName];
if (keep == null) return false;
return (bool)keep;
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void Delete()
{
if (_files != null && _files.Count > 0)
{
string[] fileNames = new string[_files.Count];
_files.Keys.CopyTo(fileNames, 0);
foreach (string fileName in fileNames)
{
if (!KeepFile(fileName))
{
Delete(fileName);
_files.Remove(fileName);
}
}
}
}
private void Delete(string fileName)
{
try
{
File.Delete(fileName);
}
catch
{
// Ignore all exceptions
}
}
}
}
| |
// 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.Diagnostics.Tracing
{
[System.FlagsAttribute]
public enum EventActivityOptions
{
Detachable = 8,
Disable = 2,
None = 0,
Recursive = 4,
}
[System.AttributeUsageAttribute((System.AttributeTargets)(64))]
public sealed partial class EventAttribute : System.Attribute
{
public EventAttribute(int eventId) { }
public System.Diagnostics.Tracing.EventActivityOptions ActivityOptions { get { throw null; } set { } }
public System.Diagnostics.Tracing.EventChannel Channel { get { throw null; } set { } }
public int EventId { get { throw null; } }
public System.Diagnostics.Tracing.EventKeywords Keywords { get { throw null; } set { } }
public System.Diagnostics.Tracing.EventLevel Level { get { throw null; } set { } }
public string Message { get { throw null; } set { } }
public System.Diagnostics.Tracing.EventOpcode Opcode { get { throw null; } set { } }
public System.Diagnostics.Tracing.EventTags Tags { get { throw null; } set { } }
public System.Diagnostics.Tracing.EventTask Task { get { throw null; } set { } }
public byte Version { get { throw null; } set { } }
}
public enum EventChannel : byte
{
Admin = (byte)16,
Analytic = (byte)18,
Debug = (byte)19,
None = (byte)0,
Operational = (byte)17,
}
public enum EventCommand
{
Disable = -3,
Enable = -2,
SendManifest = -1,
Update = 0,
}
public partial class EventCommandEventArgs : System.EventArgs
{
internal EventCommandEventArgs() { }
public System.Collections.Generic.IDictionary<string, string> Arguments { get { throw null; } }
public System.Diagnostics.Tracing.EventCommand Command { get { throw null; } }
public bool DisableEvent(int eventId) { throw null; }
public bool EnableEvent(int eventId) { throw null; }
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public class EventCounter
{
public EventCounter(string name, System.Diagnostics.Tracing.EventSource eventSource) { }
public void WriteMetric(float value) { }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(12), Inherited=false)]
public partial class EventDataAttribute : System.Attribute
{
public EventDataAttribute() { }
public string Name { get { throw null; } set { } }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(128))]
public partial class EventFieldAttribute : System.Attribute
{
public EventFieldAttribute() { }
public System.Diagnostics.Tracing.EventFieldFormat Format { get { throw null; } set { } }
public System.Diagnostics.Tracing.EventFieldTags Tags { get { throw null; } set { } }
}
public enum EventFieldFormat
{
Boolean = 3,
Default = 0,
Hexadecimal = 4,
HResult = 15,
Json = 12,
String = 2,
Xml = 11,
}
[System.FlagsAttribute]
public enum EventFieldTags
{
None = 0,
}
[System.AttributeUsageAttribute((System.AttributeTargets)(128))]
public partial class EventIgnoreAttribute : System.Attribute
{
public EventIgnoreAttribute() { }
}
[System.FlagsAttribute]
public enum EventKeywords : long
{
All = (long)-1,
AuditFailure = (long)4503599627370496,
AuditSuccess = (long)9007199254740992,
CorrelationHint = (long)4503599627370496,
EventLogClassic = (long)36028797018963968,
MicrosoftTelemetry = (long)562949953421312,
None = (long)0,
Sqm = (long)2251799813685248,
WdiContext = (long)562949953421312,
WdiDiagnostic = (long)1125899906842624,
}
public enum EventLevel
{
Critical = 1,
Error = 2,
Informational = 4,
LogAlways = 0,
Verbose = 5,
Warning = 3,
}
public abstract partial class EventListener : System.IDisposable
{
protected EventListener() { }
public void DisableEvents(System.Diagnostics.Tracing.EventSource eventSource) { }
public virtual void Dispose() { }
public void EnableEvents(System.Diagnostics.Tracing.EventSource eventSource, System.Diagnostics.Tracing.EventLevel level) { }
public void EnableEvents(System.Diagnostics.Tracing.EventSource eventSource, System.Diagnostics.Tracing.EventLevel level, System.Diagnostics.Tracing.EventKeywords matchAnyKeyword) { }
public void EnableEvents(System.Diagnostics.Tracing.EventSource eventSource, System.Diagnostics.Tracing.EventLevel level, System.Diagnostics.Tracing.EventKeywords matchAnyKeyword, System.Collections.Generic.IDictionary<string, string> arguments) { }
protected static int EventSourceIndex(System.Diagnostics.Tracing.EventSource eventSource) { throw null; }
protected internal virtual void OnEventSourceCreated(System.Diagnostics.Tracing.EventSource eventSource) { }
protected internal abstract void OnEventWritten(System.Diagnostics.Tracing.EventWrittenEventArgs eventData);
}
[System.FlagsAttribute]
public enum EventManifestOptions
{
AllCultures = 2,
AllowEventSourceOverride = 8,
None = 0,
OnlyIfNeededForRegistration = 4,
Strict = 1,
}
public enum EventOpcode
{
DataCollectionStart = 3,
DataCollectionStop = 4,
Extension = 5,
Info = 0,
Receive = 240,
Reply = 6,
Resume = 7,
Send = 9,
Start = 1,
Stop = 2,
Suspend = 8,
}
public partial class EventSource : System.IDisposable
{
protected EventSource() { }
protected EventSource(bool throwOnEventWriteErrors) { }
protected EventSource(System.Diagnostics.Tracing.EventSourceSettings settings) { }
protected EventSource(System.Diagnostics.Tracing.EventSourceSettings settings, params string[] traits) { }
public EventSource(string eventSourceName) { }
public EventSource(string eventSourceName, System.Diagnostics.Tracing.EventSourceSettings config) { }
public EventSource(string eventSourceName, System.Diagnostics.Tracing.EventSourceSettings config, params string[] traits) { }
public System.Exception ConstructionException { get { throw null; } }
public static System.Guid CurrentThreadActivityId { get { throw null; } }
public System.Guid Guid { get { throw null; } }
public string Name { get { throw null; } }
public System.Diagnostics.Tracing.EventSourceSettings Settings { get { throw null; } }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public event System.EventHandler<System.Diagnostics.Tracing.EventCommandEventArgs> EventCommandExecuted { add { } remove { } }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
~EventSource() { }
public static string GenerateManifest(System.Type eventSourceType, string assemblyPathToIncludeInManifest) { throw null; }
public static string GenerateManifest(System.Type eventSourceType, string assemblyPathToIncludeInManifest, System.Diagnostics.Tracing.EventManifestOptions flags) { throw null; }
public static System.Guid GetGuid(System.Type eventSourceType) { throw null; }
public static string GetName(System.Type eventSourceType) { throw null; }
public static System.Collections.Generic.IEnumerable<System.Diagnostics.Tracing.EventSource> GetSources() { throw null; }
public string GetTrait(string key) { throw null; }
public bool IsEnabled() { throw null; }
public bool IsEnabled(System.Diagnostics.Tracing.EventLevel level, System.Diagnostics.Tracing.EventKeywords keywords) { throw null; }
public bool IsEnabled(System.Diagnostics.Tracing.EventLevel level, System.Diagnostics.Tracing.EventKeywords keywords, System.Diagnostics.Tracing.EventChannel channel) { throw null; }
protected virtual void OnEventCommand(System.Diagnostics.Tracing.EventCommandEventArgs command) { }
public static void SendCommand(System.Diagnostics.Tracing.EventSource eventSource, System.Diagnostics.Tracing.EventCommand command, System.Collections.Generic.IDictionary<string, string> commandArguments) { }
public static void SetCurrentThreadActivityId(System.Guid activityId) { }
public static void SetCurrentThreadActivityId(System.Guid activityId, out System.Guid oldActivityThatWillContinue) { oldActivityThatWillContinue = default(System.Guid); }
public override string ToString() { throw null; }
public void Write(string eventName) { }
public void Write(string eventName, System.Diagnostics.Tracing.EventSourceOptions options) { }
public void Write<T>(string eventName, T data) { }
public void Write<T>(string eventName, System.Diagnostics.Tracing.EventSourceOptions options, T data) { }
public void Write<T>(string eventName, ref System.Diagnostics.Tracing.EventSourceOptions options, ref T data) { }
public void Write<T>(string eventName, ref System.Diagnostics.Tracing.EventSourceOptions options, ref System.Guid activityId, ref System.Guid relatedActivityId, ref T data) { }
protected void WriteEvent(int eventId) { }
protected void WriteEvent(int eventId, byte[] arg1) { }
protected void WriteEvent(int eventId, int arg1) { }
protected void WriteEvent(int eventId, int arg1, int arg2) { }
protected void WriteEvent(int eventId, int arg1, int arg2, int arg3) { }
protected void WriteEvent(int eventId, int arg1, string arg2) { }
protected void WriteEvent(int eventId, long arg1) { }
protected void WriteEvent(int eventId, long arg1, byte[] arg2) { }
protected void WriteEvent(int eventId, long arg1, long arg2) { }
protected void WriteEvent(int eventId, long arg1, long arg2, long arg3) { }
protected void WriteEvent(int eventId, long arg1, string arg2) { }
protected void WriteEvent(int eventId, params object[] args) { }
protected void WriteEvent(int eventId, string arg1) { }
protected void WriteEvent(int eventId, string arg1, int arg2) { }
protected void WriteEvent(int eventId, string arg1, int arg2, int arg3) { }
protected void WriteEvent(int eventId, string arg1, long arg2) { }
protected void WriteEvent(int eventId, string arg1, string arg2) { }
protected void WriteEvent(int eventId, string arg1, string arg2, string arg3) { }
[System.CLSCompliantAttribute(false)]
protected unsafe void WriteEventCore(int eventId, int eventDataCount, System.Diagnostics.Tracing.EventSource.EventData* data) { }
protected void WriteEventWithRelatedActivityId(int eventId, System.Guid relatedActivityId, params object[] args) { }
[System.CLSCompliantAttribute(false)]
protected unsafe void WriteEventWithRelatedActivityIdCore(int eventId, System.Guid* relatedActivityId, int eventDataCount, System.Diagnostics.Tracing.EventSource.EventData* data) { }
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
protected internal partial struct EventData
{
public System.IntPtr DataPointer { get { throw null; } set { } }
public int Size { get { throw null; } set { } }
}
}
[System.AttributeUsageAttribute((System.AttributeTargets)(4))]
public sealed partial class EventSourceAttribute : System.Attribute
{
public EventSourceAttribute() { }
public string Guid { get { throw null; } set { } }
public string LocalizationResources { get { throw null; } set { } }
public string Name { get { throw null; } set { } }
}
public partial class EventSourceException : System.Exception
{
public EventSourceException() { }
protected EventSourceException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
public EventSourceException(string message) { }
public EventSourceException(string message, System.Exception innerException) { }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public partial struct EventSourceOptions
{
public System.Diagnostics.Tracing.EventActivityOptions ActivityOptions { get { throw null; } set { } }
public System.Diagnostics.Tracing.EventKeywords Keywords { get { throw null; } set { } }
public System.Diagnostics.Tracing.EventLevel Level { get { throw null; } set { } }
public System.Diagnostics.Tracing.EventOpcode Opcode { get { throw null; } set { } }
public System.Diagnostics.Tracing.EventTags Tags { get { throw null; } set { } }
}
[System.FlagsAttribute]
public enum EventSourceSettings
{
Default = 0,
EtwManifestEventFormat = 4,
EtwSelfDescribingEventFormat = 8,
ThrowOnEventWriteErrors = 1,
}
[System.FlagsAttribute]
public enum EventTags
{
None = 0,
}
public enum EventTask
{
None = 0,
}
public partial class EventWrittenEventArgs : System.EventArgs
{
internal EventWrittenEventArgs() { }
public System.Guid ActivityId { get { throw null; } }
public System.Diagnostics.Tracing.EventChannel Channel { get { throw null; } }
public int EventId { get { throw null; } }
public string EventName { get { throw null; } }
public System.Diagnostics.Tracing.EventSource EventSource { get { throw null; } }
public System.Diagnostics.Tracing.EventKeywords Keywords { get { throw null; } }
public System.Diagnostics.Tracing.EventLevel Level { get { throw null; } }
public string Message { get { throw null; } }
public System.Diagnostics.Tracing.EventOpcode Opcode { get { throw null; } }
public System.Collections.ObjectModel.ReadOnlyCollection<object> Payload { get { throw null; } }
public System.Collections.ObjectModel.ReadOnlyCollection<string> PayloadNames { get { throw null; } }
public System.Guid RelatedActivityId { get { throw null; } }
public System.Diagnostics.Tracing.EventTags Tags { get { throw null; } }
public System.Diagnostics.Tracing.EventTask Task { get { throw null; } }
public byte Version { get { throw null; } }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(64))]
public sealed partial class NonEventAttribute : System.Attribute
{
public NonEventAttribute() { }
}
}
| |
//
// LayerActions.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 Gdk;
using Gtk;
using Mono.Unix;
using System.IO;
namespace Pinta.Core
{
public class LayerActions
{
public Gtk.Action AddNewLayer { get; private set; }
public Gtk.Action DeleteLayer { get; private set; }
public Gtk.Action DuplicateLayer { get; private set; }
public Gtk.Action MergeLayerDown { get; private set; }
public Gtk.Action ImportFromFile { get; private set; }
public Gtk.Action FlipHorizontal { get; private set; }
public Gtk.Action FlipVertical { get; private set; }
public Gtk.Action RotateZoom { get; private set; }
public Gtk.Action MoveLayerUp { get; private set; }
public Gtk.Action MoveLayerDown { get; private set; }
public Gtk.Action Properties { get; private set; }
public LayerActions ()
{
Gtk.IconFactory fact = new Gtk.IconFactory ();
fact.Add ("Menu.Layers.AddNewLayer.png", new Gtk.IconSet (PintaCore.Resources.GetIcon ("Menu.Layers.AddNewLayer.png")));
fact.Add ("Menu.Layers.DeleteLayer.png", new Gtk.IconSet (PintaCore.Resources.GetIcon ("Menu.Layers.DeleteLayer.png")));
fact.Add ("Menu.Layers.DuplicateLayer.png", new Gtk.IconSet (PintaCore.Resources.GetIcon ("Menu.Layers.DuplicateLayer.png")));
fact.Add ("Menu.Layers.MergeLayerDown.png", new Gtk.IconSet (PintaCore.Resources.GetIcon ("Menu.Layers.MergeLayerDown.png")));
fact.Add ("Menu.Layers.MoveLayerDown.png", new Gtk.IconSet (PintaCore.Resources.GetIcon ("Menu.Layers.MoveLayerDown.png")));
fact.Add ("Menu.Layers.MoveLayerUp.png", new Gtk.IconSet (PintaCore.Resources.GetIcon ("Menu.Layers.MoveLayerUp.png")));
fact.Add ("Menu.Layers.FlipHorizontal.png", new Gtk.IconSet (PintaCore.Resources.GetIcon ("Menu.Layers.FlipHorizontal.png")));
fact.Add ("Menu.Layers.FlipVertical.png", new Gtk.IconSet (PintaCore.Resources.GetIcon ("Menu.Layers.FlipVertical.png")));
fact.Add ("Menu.Layers.ImportFromFile.png", new Gtk.IconSet (PintaCore.Resources.GetIcon ("Menu.Layers.ImportFromFile.png")));
fact.Add ("Menu.Layers.LayerProperties.png", new Gtk.IconSet (PintaCore.Resources.GetIcon ("Menu.Layers.LayerProperties.png")));
fact.Add ("Menu.Layers.RotateZoom.png", new Gtk.IconSet (PintaCore.Resources.GetIcon ("Menu.Layers.RotateZoom.png")));
fact.AddDefault ();
AddNewLayer = new Gtk.Action ("AddNewLayer", Catalog.GetString ("Add New Layer"), null, "Menu.Layers.AddNewLayer.png");
DeleteLayer = new Gtk.Action ("DeleteLayer", Catalog.GetString ("Delete Layer"), null, "Menu.Layers.DeleteLayer.png");
DuplicateLayer = new Gtk.Action ("DuplicateLayer", Catalog.GetString ("Duplicate Layer"), null, "Menu.Layers.DuplicateLayer.png");
MergeLayerDown = new Gtk.Action ("MergeLayerDown", Catalog.GetString ("Merge Layer Down"), null, "Menu.Layers.MergeLayerDown.png");
ImportFromFile = new Gtk.Action ("ImportFromFile", Catalog.GetString ("Import from File..."), null, "Menu.Layers.ImportFromFile.png");
FlipHorizontal = new Gtk.Action ("FlipHorizontal", Catalog.GetString ("Flip Horizontal"), null, "Menu.Layers.FlipHorizontal.png");
FlipVertical = new Gtk.Action ("FlipVertical", Catalog.GetString ("Flip Vertical"), null, "Menu.Layers.FlipVertical.png");
RotateZoom = new Gtk.Action ("RotateZoom", Catalog.GetString ("Rotate / Zoom Layer..."), null, "Menu.Layers.RotateZoom.png");
MoveLayerUp = new Gtk.Action ("MoveLayerUp", Catalog.GetString ("Move Layer Up"), null, "Menu.Layers.MoveLayerUp.png");
MoveLayerDown = new Gtk.Action ("MoveLayerDown", Catalog.GetString ("Move Layer Down"), null, "Menu.Layers.MoveLayerDown.png");
Properties = new Gtk.Action ("Properties", Catalog.GetString ("Layer Properties..."), null, "Menu.Layers.LayerProperties.png");
RotateZoom.Sensitive = false;
}
#region Initialization
public void CreateMainMenu (Gtk.Menu menu)
{
menu.Append (AddNewLayer.CreateAcceleratedMenuItem (Gdk.Key.N, Gdk.ModifierType.ControlMask | Gdk.ModifierType.ShiftMask));
menu.Append (DeleteLayer.CreateAcceleratedMenuItem (Gdk.Key.Delete, Gdk.ModifierType.ControlMask | Gdk.ModifierType.ShiftMask));
menu.Append (DuplicateLayer.CreateAcceleratedMenuItem (Gdk.Key.D, Gdk.ModifierType.ControlMask | Gdk.ModifierType.ShiftMask));
menu.Append (MergeLayerDown.CreateAcceleratedMenuItem (Gdk.Key.M, Gdk.ModifierType.ControlMask));
menu.Append (ImportFromFile.CreateMenuItem ());
menu.AppendSeparator ();
menu.Append (FlipHorizontal.CreateMenuItem ());
menu.Append (FlipVertical.CreateMenuItem ());
menu.Append (RotateZoom.CreateMenuItem ());
menu.AppendSeparator ();
menu.Append (Properties.CreateAcceleratedMenuItem (Gdk.Key.F4, Gdk.ModifierType.None));
}
public void CreateLayerWindowToolBar (Gtk.Toolbar toolbar)
{
toolbar.AppendItem (AddNewLayer.CreateToolBarItem ());
toolbar.AppendItem (DeleteLayer.CreateToolBarItem ());
toolbar.AppendItem (DuplicateLayer.CreateToolBarItem ());
toolbar.AppendItem (MergeLayerDown.CreateToolBarItem ());
toolbar.AppendItem (MoveLayerUp.CreateToolBarItem ());
toolbar.AppendItem (MoveLayerDown.CreateToolBarItem ());
toolbar.AppendItem (Properties.CreateToolBarItem ());
}
public void RegisterHandlers ()
{
AddNewLayer.Activated += HandlePintaCoreActionsLayersAddNewLayerActivated;
DeleteLayer.Activated += HandlePintaCoreActionsLayersDeleteLayerActivated;
DuplicateLayer.Activated += HandlePintaCoreActionsLayersDuplicateLayerActivated;
MergeLayerDown.Activated += HandlePintaCoreActionsLayersMergeLayerDownActivated;
MoveLayerDown.Activated += HandlePintaCoreActionsLayersMoveLayerDownActivated;
MoveLayerUp.Activated += HandlePintaCoreActionsLayersMoveLayerUpActivated;
FlipHorizontal.Activated += HandlePintaCoreActionsLayersFlipHorizontalActivated;
FlipVertical.Activated += HandlePintaCoreActionsLayersFlipVerticalActivated;
ImportFromFile.Activated += HandlePintaCoreActionsLayersImportFromFileActivated;
PintaCore.Layers.LayerAdded += EnableOrDisableLayerActions;
PintaCore.Layers.LayerRemoved += EnableOrDisableLayerActions;
PintaCore.Layers.SelectedLayerChanged += EnableOrDisableLayerActions;
EnableOrDisableLayerActions (null, EventArgs.Empty);
}
#endregion
#region Action Handlers
private void EnableOrDisableLayerActions (object sender, EventArgs e)
{
if (PintaCore.Workspace.HasOpenDocuments && PintaCore.Workspace.ActiveDocument.UserLayers.Count > 1) {
PintaCore.Actions.Layers.DeleteLayer.Sensitive = true;
PintaCore.Actions.Image.Flatten.Sensitive = true;
} else {
PintaCore.Actions.Layers.DeleteLayer.Sensitive = false;
PintaCore.Actions.Image.Flatten.Sensitive = false;
}
if (PintaCore.Workspace.HasOpenDocuments && PintaCore.Workspace.ActiveDocument.CurrentUserLayerIndex > 0) {
PintaCore.Actions.Layers.MergeLayerDown.Sensitive = true;
PintaCore.Actions.Layers.MoveLayerDown.Sensitive = true;
} else {
PintaCore.Actions.Layers.MergeLayerDown.Sensitive = false;
PintaCore.Actions.Layers.MoveLayerDown.Sensitive = false;
}
if (PintaCore.Workspace.HasOpenDocuments && PintaCore.Workspace.ActiveDocument.CurrentUserLayerIndex < PintaCore.Workspace.ActiveDocument.UserLayers.Count - 1)
PintaCore.Actions.Layers.MoveLayerUp.Sensitive = true;
else
PintaCore.Actions.Layers.MoveLayerUp.Sensitive = false;
}
private void HandlePintaCoreActionsLayersImportFromFileActivated (object sender, EventArgs e)
{
Document doc = PintaCore.Workspace.ActiveDocument;
PintaCore.Tools.Commit ();
var fcd = new Gtk.FileChooserDialog (Catalog.GetString ("Open Image File"),PintaCore.Chrome.MainWindow,
FileChooserAction.Open, Stock.Cancel, ResponseType.Cancel,
Stock.Open, ResponseType.Ok);
fcd.SetCurrentFolder (PintaCore.System.GetDialogDirectory ());
fcd.AlternativeButtonOrder = new int[] { (int) ResponseType.Ok, (int) ResponseType.Cancel };
fcd.AddImagePreview ();
int response = fcd.Run ();
if (response == (int)Gtk.ResponseType.Ok) {
string file = fcd.Filename;
PintaCore.System.LastDialogDirectory = fcd.CurrentFolder;
// Open the image and add it to the layers
UserLayer layer = doc.AddNewLayer(System.IO.Path.GetFileName(file));
using (var fs = new FileStream (file, FileMode.Open))
using (Pixbuf bg = new Pixbuf (fs))
using (Cairo.Context g = new Cairo.Context (layer.Surface)) {
CairoHelper.SetSourcePixbuf (g, bg, 0, 0);
g.Paint ();
}
doc.SetCurrentUserLayer (layer);
AddLayerHistoryItem hist = new AddLayerHistoryItem ("Menu.Layers.ImportFromFile.png", Catalog.GetString ("Import From File"), doc.UserLayers.IndexOf (layer));
doc.History.PushNewItem (hist);
doc.Workspace.Invalidate ();
}
fcd.Destroy ();
}
private void HandlePintaCoreActionsLayersFlipVerticalActivated (object sender, EventArgs e)
{
Document doc = PintaCore.Workspace.ActiveDocument;
PintaCore.Tools.Commit ();
doc.CurrentUserLayer.FlipVertical ();
doc.Workspace.Invalidate ();
doc.History.PushNewItem (new InvertHistoryItem (InvertType.FlipLayerVertical, doc.CurrentUserLayerIndex));
}
private void HandlePintaCoreActionsLayersFlipHorizontalActivated (object sender, EventArgs e)
{
Document doc = PintaCore.Workspace.ActiveDocument;
PintaCore.Tools.Commit ();
doc.CurrentUserLayer.FlipHorizontal ();
doc.Workspace.Invalidate ();
doc.History.PushNewItem (new InvertHistoryItem (InvertType.FlipLayerHorizontal, doc.CurrentUserLayerIndex));
}
private void HandlePintaCoreActionsLayersMoveLayerUpActivated (object sender, EventArgs e)
{
Document doc = PintaCore.Workspace.ActiveDocument;
PintaCore.Tools.Commit ();
SwapLayersHistoryItem hist = new SwapLayersHistoryItem ("Menu.Layers.MoveLayerUp.png", Catalog.GetString ("Move Layer Up"), doc.CurrentUserLayerIndex, doc.CurrentUserLayerIndex + 1);
doc.MoveCurrentLayerUp ();
doc.History.PushNewItem (hist);
}
private void HandlePintaCoreActionsLayersMoveLayerDownActivated (object sender, EventArgs e)
{
Document doc = PintaCore.Workspace.ActiveDocument;
PintaCore.Tools.Commit ();
SwapLayersHistoryItem hist = new SwapLayersHistoryItem ("Menu.Layers.MoveLayerDown.png", Catalog.GetString ("Move Layer Down"), doc.CurrentUserLayerIndex, doc.CurrentUserLayerIndex - 1);
doc.MoveCurrentLayerDown ();
doc.History.PushNewItem (hist);
}
private void HandlePintaCoreActionsLayersMergeLayerDownActivated (object sender, EventArgs e)
{
Document doc = PintaCore.Workspace.ActiveDocument;
PintaCore.Tools.Commit ();
int bottomLayerIndex = doc.CurrentUserLayerIndex - 1;
var oldBottomSurface = doc.UserLayers[bottomLayerIndex].Surface.Clone ();
CompoundHistoryItem hist = new CompoundHistoryItem ("Menu.Layers.MergeLayerDown.png", Catalog.GetString ("Merge Layer Down"));
DeleteLayerHistoryItem h1 = new DeleteLayerHistoryItem (string.Empty, string.Empty, doc.CurrentUserLayer, doc.CurrentUserLayerIndex);
doc.MergeCurrentLayerDown ();
SimpleHistoryItem h2 = new SimpleHistoryItem (string.Empty, string.Empty, oldBottomSurface, bottomLayerIndex);
hist.Push (h1);
hist.Push (h2);
doc.History.PushNewItem (hist);
}
private void HandlePintaCoreActionsLayersDuplicateLayerActivated (object sender, EventArgs e)
{
Document doc = PintaCore.Workspace.ActiveDocument;
PintaCore.Tools.Commit ();
UserLayer l = doc.DuplicateCurrentLayer();
// Make new layer the current layer
doc.SetCurrentUserLayer (l);
AddLayerHistoryItem hist = new AddLayerHistoryItem ("Menu.Layers.DuplicateLayer.png", Catalog.GetString ("Duplicate Layer"), doc.UserLayers.IndexOf (l));
doc.History.PushNewItem (hist);
}
private void HandlePintaCoreActionsLayersDeleteLayerActivated (object sender, EventArgs e)
{
Document doc = PintaCore.Workspace.ActiveDocument;
PintaCore.Tools.Commit ();
DeleteLayerHistoryItem hist = new DeleteLayerHistoryItem ("Menu.Layers.DeleteLayer.png", Catalog.GetString ("Delete Layer"), doc.CurrentUserLayer, doc.CurrentUserLayerIndex);
doc.DeleteLayer (doc.CurrentUserLayerIndex, false);
doc.History.PushNewItem (hist);
}
private void HandlePintaCoreActionsLayersAddNewLayerActivated (object sender, EventArgs e)
{
Document doc = PintaCore.Workspace.ActiveDocument;
PintaCore.Tools.Commit ();
UserLayer l = doc.AddNewLayer(string.Empty);
// Make new layer the current layer
doc.SetCurrentUserLayer (l);
AddLayerHistoryItem hist = new AddLayerHistoryItem ("Menu.Layers.AddNewLayer.png", Catalog.GetString ("Add New Layer"), doc.UserLayers.IndexOf (l));
doc.History.PushNewItem (hist);
}
#endregion
}
}
| |
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Formatting;
namespace RefactoringEssentials.CSharp.Diagnostics
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class ReplaceWithOfTypeAnyAnalyzer : DiagnosticAnalyzer
{
static readonly DiagnosticDescriptor descriptor = new DiagnosticDescriptor(
CSharpDiagnosticIDs.ReplaceWithOfTypeAnyAnalyzerID,
GettextCatalog.GetString("Replace with call to OfType<T>().Any()"),
GettextCatalog.GetString("Replace with 'OfType<T>().Any()'"),
DiagnosticAnalyzerCategories.PracticesAndImprovements,
DiagnosticSeverity.Warning,
isEnabledByDefault: true,
helpLinkUri: HelpLink.CreateFor(CSharpDiagnosticIDs.ReplaceWithOfTypeAnyAnalyzerID)
);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(descriptor);
public override void Initialize(AnalysisContext context)
{
context.EnableConcurrentExecution();
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
context.RegisterSyntaxNodeAction(
(nodeContext) =>
{
Diagnostic diagnostic;
if (TryGetDiagnostic(nodeContext, out diagnostic))
nodeContext.ReportDiagnostic(diagnostic);
},
SyntaxKind.InvocationExpression
);
}
static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
{
diagnostic = default(Diagnostic);
var anyInvoke = nodeContext.Node as InvocationExpressionSyntax;
var info = nodeContext.SemanticModel.GetSymbolInfo(anyInvoke);
IMethodSymbol anyResolve = info.Symbol as IMethodSymbol;
if (anyResolve == null)
{
anyResolve = info.CandidateSymbols.OfType<IMethodSymbol>().FirstOrDefault(candidate => HasPredicateVersion(candidate));
}
if (anyResolve == null || !HasPredicateVersion(anyResolve))
return false;
ExpressionSyntax target, followUp;
TypeSyntax type;
ParameterSyntax param;
if (MatchSelect(anyInvoke, out target, out type, out param, out followUp))
{
// if (member == "Where" && followUp == null) return;
diagnostic = Diagnostic.Create(
descriptor,
anyInvoke.GetLocation()
);
return true;
}
return false;
}
static bool CompareNames(ParameterSyntax param, IdentifierNameSyntax expr)
{
if (param == null || expr == null)
return false;
return param.Identifier.ValueText == expr.Identifier.ValueText;
}
// static readonly AstNode selectPattern =
// new InvocationExpression(
// new MemberReferenceExpression(
// new InvocationExpression(
// new MemberReferenceExpression(new AnyNode("targetExpr"), "Select"),
// new LambdaExpression {
// Parameters = { PatternHelper.NamedParameter ("param1", PatternHelper.AnyType ("paramType", true), Pattern.AnyString) },
// Body = PatternHelper.OptionalParentheses (new AsExpression(new AnyNode("expr1"), PatternHelper.AnyType("type")))
// }
// ),
// Pattern.AnyString
// ),
// new LambdaExpression {
// Parameters = { PatternHelper.NamedParameter ("param2", PatternHelper.AnyType ("paramType", true), Pattern.AnyString) },
// Body = PatternHelper.CommutativeOperatorWithOptionalParentheses(new AnyNode("expr2"), BinaryOperatorType.InEquality, new NullReferenceExpression())
// }
// );
//
// static readonly AstNode selectPatternWithFollowUp =
// new InvocationExpression(
// new MemberReferenceExpression(
// new InvocationExpression(
// new MemberReferenceExpression(new AnyNode("targetExpr"), "Select"),
// new LambdaExpression {
// Parameters = { PatternHelper.NamedParameter ("param1", PatternHelper.AnyType ("paramType", true), Pattern.AnyString) },
// Body = PatternHelper.OptionalParentheses (new AsExpression(new AnyNode("expr1"), PatternHelper.AnyType("type")))
// }
// ),
// Pattern.AnyString
// ),
// new NamedNode("lambda",
// new LambdaExpression {
// Parameters = { PatternHelper.NamedParameter ("param2", PatternHelper.AnyType ("paramType", true), Pattern.AnyString) },
// Body = new BinaryOperatorExpression(
// PatternHelper.CommutativeOperatorWithOptionalParentheses(new AnyNode("expr2"), BinaryOperatorType.InEquality, new NullReferenceExpression()),
// BinaryOperatorType.ConditionalAnd,
// new AnyNode("followUpExpr")
// )
// }
// )
// );
internal static bool MatchSelect(InvocationExpressionSyntax anyInvoke, out ExpressionSyntax target, out TypeSyntax type, out ParameterSyntax lambdaParam, out ExpressionSyntax followUpExpression)
{
target = null;
type = null;
lambdaParam = null;
followUpExpression = null;
if (anyInvoke.ArgumentList.Arguments.Count != 1)
return false;
var anyInvokeBase = anyInvoke.Expression as MemberAccessExpressionSyntax;
if (anyInvokeBase == null)
return false;
var selectInvoc = anyInvokeBase.Expression as InvocationExpressionSyntax;
if (selectInvoc == null || selectInvoc.ArgumentList.Arguments.Count != 1)
return false;
var baseMember = selectInvoc.Expression as MemberAccessExpressionSyntax;
if (baseMember == null || baseMember.Name.Identifier.Text != "Select")
return false;
target = baseMember.Expression;
ParameterSyntax param1, param2;
BinaryExpressionSyntax expr1, expr2;
if (!ExtractLambda(selectInvoc.ArgumentList.Arguments[0], out param1, out expr1))
return false;
if (!ExtractLambda(anyInvoke.ArgumentList.Arguments[0], out param2, out expr2))
return false;
lambdaParam = param2;
if (!CompareNames(param1, expr1.Left as IdentifierNameSyntax))
return false;
if (expr2.IsKind(SyntaxKind.LogicalAndExpression))
{
if (CheckNotEqualsNullExpr(expr2.Left as BinaryExpressionSyntax, param2))
followUpExpression = expr2.Right;
else if (CheckNotEqualsNullExpr(expr2.Right as BinaryExpressionSyntax, param2))
followUpExpression = expr2.Left;
else
return false;
}
else if (!CheckNotEqualsNullExpr(expr2, param2))
return false;
if (expr1.IsKind(SyntaxKind.AsExpression))
type = expr1.Right as TypeSyntax;
return target != null && type != null;
}
static bool CheckNotEqualsNullExpr(BinaryExpressionSyntax expr, ParameterSyntax param)
{
if (expr == null)
return false;
if (!expr.IsKind(SyntaxKind.NotEqualsExpression))
return false;
if (expr.Right.IsKind(SyntaxKind.NullLiteralExpression) && CompareNames(param, expr.Left as IdentifierNameSyntax))
return true;
if (expr.Left.IsKind(SyntaxKind.NullLiteralExpression) && CompareNames(param, expr.Right as IdentifierNameSyntax))
return true;
return false;
}
static bool ExtractLambda(ArgumentSyntax argument, out ParameterSyntax parameter, out BinaryExpressionSyntax body)
{
if (argument.Expression is SimpleLambdaExpressionSyntax)
{
var simple = (SimpleLambdaExpressionSyntax)argument.Expression;
parameter = simple.Parameter;
body = simple.Body as BinaryExpressionSyntax;
if (body == null)
{
return false;
}
body = body.SkipParens() as BinaryExpressionSyntax;
return true;
}
parameter = null;
body = null;
return false;
}
internal static InvocationExpressionSyntax MakeOfTypeCall(InvocationExpressionSyntax anyInvoke)
{
var member = ((MemberAccessExpressionSyntax)anyInvoke.Expression).Name;
ExpressionSyntax target, followUp;
TypeSyntax type;
ParameterSyntax param;
if (MatchSelect(anyInvoke, out target, out type, out param, out followUp))
{
var ofTypeIdentifier = ((SimpleNameSyntax)SyntaxFactory.ParseName("OfType")).Identifier;
var typeParams = SyntaxFactory.SeparatedList(new[] { type });
var ofTypeName = SyntaxFactory.GenericName(ofTypeIdentifier, SyntaxFactory.TypeArgumentList(typeParams));
InvocationExpressionSyntax ofTypeCall = SyntaxFactory.InvocationExpression(SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, target, ofTypeName));
var callerExpr = SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, ofTypeCall, member).WithAdditionalAnnotations(Formatter.Annotation);
if (followUp == null)
return SyntaxFactory.InvocationExpression(callerExpr);
var lambdaExpr = SyntaxFactory.SimpleLambdaExpression(param, followUp);
var argument = SyntaxFactory.Argument(lambdaExpr).WithAdditionalAnnotations(Formatter.Annotation);
return SyntaxFactory.InvocationExpression(callerExpr, SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList(new[] { argument })));
}
return null;
}
internal static bool IsQueryExtensionClass(INamedTypeSymbol typeDef)
{
if (typeDef == null || typeDef.ContainingNamespace == null || typeDef.ContainingNamespace.GetFullName() != "System.Linq")
return false;
switch (typeDef.Name)
{
case "Enumerable":
case "ParallelEnumerable":
case "Queryable":
return true;
default:
return false;
}
}
static bool HasPredicateVersion(IMethodSymbol member)
{
if (!IsQueryExtensionClass(member.ContainingType))
return false;
return member.Name == "Any";
}
}
}
| |
// 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;
/// <summary>
/// String.Remove(Int32, Int32)
/// Deletes a specified number of characters from this instance
/// beginning at a specified position.
/// </summary>
public class StringRemove2
{
private const int c_MIN_STRING_LEN = 8;
private const int c_MAX_STRING_LEN = 256;
private const int c_MAX_SHORT_STR_LEN = 31;//short string (<32 chars)
private const int c_MIN_LONG_STR_LEN = 257;//long string ( >256 chars)
private const int c_MAX_LONG_STR_LEN = 65535;
public static int Main()
{
StringRemove2 sr = new StringRemove2();
TestLibrary.TestFramework.BeginTestCase("for method: System.String.Remove(Int32, Int32)");
if(sr.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
retVal = NegTest4() && retVal;
retVal = NegTest5() && retVal;
return retVal;
}
#region Positive test scenarios
public bool PosTest1()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest1: Valid start index between 0, source string's length minus 1";
const string c_TEST_ID = "P001";
string strSrc;
int startIndex, count;
bool expectedValue = true;
bool actualValue = false;
strSrc = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
startIndex = GetInt32(0, strSrc.Length - 1);
count = GetInt32(1, strSrc.Length - startIndex);
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
string strReserved = strSrc.Remove(startIndex, count);
actualValue = (0 == string.CompareOrdinal(strReserved, strSrc.Substring(0, startIndex) + strSrc.Substring(startIndex + count)));
if (actualValue != expectedValue)
{
string errorDesc = "Value is not " + expectedValue + " as expected: Actual(" + actualValue + ")";
errorDesc += GetDataString(strSrc, startIndex, count);
TestLibrary.TestFramework.LogError("001" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(strSrc, startIndex, count));
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest2: Start index is zero, count equals whole string length";
const string c_TEST_ID = "P002";
string strSrc;
int startIndex, count;
bool expectedValue = true;
bool actualValue = false;
strSrc = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
startIndex = 0;
count = strSrc.Length;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
string strReserved = strSrc.Remove(startIndex, count);
actualValue = (0 == string.CompareOrdinal(strReserved, String.Empty));
if (actualValue != expectedValue)
{
string errorDesc = "Value is not " + expectedValue + " as expected: Actual(" + actualValue + ")";
errorDesc += GetDataString(strSrc, startIndex, count);
TestLibrary.TestFramework.LogError("003" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(strSrc, startIndex, count));
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest3: Count is zero, valid start index";
const string c_TEST_ID = "P003";
string strSrc;
int startIndex, count;
bool expectedValue = true;
bool actualValue = false;
strSrc = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
startIndex = GetInt32(0, strSrc.Length - 1);
count = 0;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
string strReserved = strSrc.Remove(startIndex, count);
actualValue = (0 == string.CompareOrdinal(strReserved, strSrc));
if (actualValue != expectedValue)
{
string errorDesc = "Value is not " + expectedValue + " as expected: Actual(" + actualValue + ")";
errorDesc += GetDataString(strSrc, startIndex, count);
TestLibrary.TestFramework.LogError("005" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(strSrc, startIndex, count));
retVal = false;
}
return retVal;
}
#endregion
#region Negative test Scenarios
//ArgumentOutOfRangeException
public bool NegTest1()
{
bool retVal = true;
const string c_TEST_DESC = "NegTest1: Start index is too greater than source string's length";
const string c_TEST_ID = "N001";
string strSrc;
int startIndex, count;
strSrc = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
startIndex = GetInt32(strSrc.Length, Int32.MaxValue);
count = GetInt32(0, strSrc.Length);
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
strSrc.Remove(startIndex, count);
TestLibrary.TestFramework.LogError("007" + " TestId-" + c_TEST_ID, "ArgumentOutOfRangeException is not thrown as expected." + GetDataString(strSrc, startIndex, count));
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch(Exception e)
{
TestLibrary.TestFramework.LogError("008" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(strSrc, startIndex, count));
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
const string c_TEST_DESC = "NegTest2: Valid start index plus count is greater than string length";
const string c_TEST_ID = "N002";
string strSrc;
int startIndex, count;
strSrc = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
startIndex = GetInt32(0, strSrc.Length - 1);
count = GetInt32(strSrc.Length - startIndex + 1, Int32.MaxValue);
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
strSrc.Remove(startIndex, count);
TestLibrary.TestFramework.LogError("009" + " TestId-" + c_TEST_ID, "ArgumentOutOfRangeException is not thrown as expected." + GetDataString(strSrc, startIndex, count));
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("010" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(strSrc, startIndex, count));
retVal = false;
}
return retVal;
}
public bool NegTest3()
{
bool retVal = true;
const string c_TEST_DESC = "NegTest3: Valid count plus start index is greater than string length";
const string c_TEST_ID = "N003";
string strSrc;
int startIndex, count;
strSrc = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
count = GetInt32(0, strSrc.Length);
startIndex = GetInt32(strSrc.Length - count + 1, Int32.MaxValue);
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
strSrc.Remove(startIndex, count);
TestLibrary.TestFramework.LogError("011" + " TestId-" + c_TEST_ID, "ArgumentOutOfRangeException is not thrown as expected." + GetDataString(strSrc, startIndex, count));
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("012" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(strSrc, startIndex, count));
retVal = false;
}
return retVal;
}
public bool NegTest4()
{
bool retVal = true;
const string c_TEST_DESC = "NegTest4: Start index is negative, valid number of characters to delete";
const string c_TEST_ID = "N004";
string strSrc;
int startIndex, count;
strSrc = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
startIndex = -1 * TestLibrary.Generator.GetInt32(-55) - 1;
count = GetInt32(0, strSrc.Length);
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
strSrc.Remove(startIndex, count);
TestLibrary.TestFramework.LogError("013" + " TestId-" + c_TEST_ID, "ArgumentOutOfRangeException is not thrown as expected." + GetDataString(strSrc, startIndex, count));
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("014" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(strSrc, startIndex, count));
retVal = false;
}
return retVal;
}
public bool NegTest5()
{
bool retVal = true;
const string c_TEST_DESC = "NegTest5: Valid start index, negative count of characters to delete";
const string c_TEST_ID = "N005";
string strSrc;
int startIndex, count;
strSrc = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
startIndex = GetInt32(0, strSrc.Length - 1);
count = -1 * TestLibrary.Generator.GetInt32(-55) - 1;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
strSrc.Remove(startIndex, count);
TestLibrary.TestFramework.LogError("015" + " TestId-" + c_TEST_ID, "ArgumentOutOfRangeException is not thrown as expected." + GetDataString(strSrc, startIndex, count));
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("016" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(strSrc, startIndex, count));
retVal = false;
}
return retVal;
}
#endregion
#region helper methods for generating test data
private bool GetBoolean()
{
Int32 i = this.GetInt32(1, 2);
return (i == 1) ? true : false;
}
//Get a non-negative integer between minValue and maxValue
private Int32 GetInt32(Int32 minValue, Int32 maxValue)
{
try
{
if (minValue == maxValue)
{
return minValue;
}
if (minValue < maxValue)
{
return minValue + TestLibrary.Generator.GetInt32(-55) % (maxValue - minValue);
}
}
catch
{
throw;
}
return minValue;
}
private Int32 Min(Int32 i1, Int32 i2)
{
return (i1 <= i2) ? i1 : i2;
}
private Int32 Max(Int32 i1, Int32 i2)
{
return (i1 >= i2) ? i1 : i2;
}
#endregion
private string GetDataString(string strSrc, int startIndex, int count)
{
string str1, str;
int len1;
if (null == strSrc)
{
str1 = "null";
len1 = 0;
}
else
{
str1 = strSrc;
len1 = strSrc.Length;
}
str = string.Format("\n[Source string value]\n \"{0}\"", str1);
str += string.Format("\n[Length of source string]\n {0}", len1);
str += string.Format("\n[Start index]\n{0}", startIndex);
str += string.Format("\n[Start index]\n{0}", count);
return str;
}
}
| |
using System.Resources;
#region Copyright (c) 2003, newtelligence AG. All rights reserved.
/*
// Copyright (c) 2003, newtelligence AG. (http://www.newtelligence.com)
// Original BlogX Source Code: Copyright (c) 2003, Chris Anderson (http://simplegeek.com)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted
// provided that the following conditions are met:
//
// (1) Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
// (2) Redistributions in binary form must reproduce the above copyright notice, this list of
// conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
// (3) Neither the name of the newtelligence AG 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.
// -------------------------------------------------------------------------
//
// Original BlogX source code (c) 2003 by Chris Anderson (http://simplegeek.com)
//
// newtelligence is a registered trademark of newtelligence Aktiengesellschaft.
//
// For portions of this software, the some additional copyright notices may apply
// which can either be found in the license.txt file included in the source distribution
// or following this notice.
//
*/
#endregion
namespace newtelligence.DasBlog.Web
{
using System;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using newtelligence.DasBlog.Runtime;
using newtelligence.DasBlog.Web.Core;
/// <summary>
/// Summary description for EntryView.
/// </summary>
public partial class SingleCommentView : System.Web.UI.UserControl
{
Comment comment;
bool obfuscateEmail = true;
public bool ObfuscateEmail { get { return obfuscateEmail; } set { obfuscateEmail = value; } }
public Comment Comment
{
get
{
return comment;
}
set
{
comment = value;
}
}
private string FixUrl(string url)
{
if (string.IsNullOrEmpty(url))
{
return url;
}
if (url.StartsWith("http://", StringComparison.OrdinalIgnoreCase) || url.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
{
return url;
}
else
{
return "http://" + url;
}
}
protected void Page_PreRender(object sender, System.EventArgs e)
{
SharedBasePage requestPage = Page as SharedBasePage;
Control root = this;
HtmlGenericControl entry = new HtmlGenericControl("div");
if (SiteSecurity.GetUserByEmail(comment.AuthorEmail) == null)
{
entry.Attributes["class"] = "commentBoxStyle";
}
else
{
entry.Attributes["class"] = "commentBoxStyle commentBoxAuthorStyle";
}
root.Controls.Add(entry);
HtmlGenericControl entryTitle = new HtmlGenericControl("div");
entryTitle.Attributes["class"] = "commentDateStyle";
//Add the unique anchor for each comment
HtmlAnchor anchor = new HtmlAnchor();
anchor.Name = comment.EntryId;
entryTitle.Controls.Add(anchor);
if (requestPage.SiteConfig.AdjustDisplayTimeZone)
{
entryTitle.Controls.Add(new LiteralControl(requestPage.SiteConfig.GetConfiguredTimeZone().FormatAdjustedUniversalTime(comment.CreatedUtc)));
}
else
{
entryTitle.Controls.Add(new LiteralControl(comment.CreatedUtc.ToString("U") + " UTC"));
}
entry.Controls.Add(entryTitle);
HtmlGenericControl entryBody = new HtmlGenericControl("div");
if (SiteSecurity.GetUserByEmail(comment.AuthorEmail) == null)
{
entryBody.Attributes["class"] = "commentBodyStyle";
}
else
{
entryBody.Attributes["class"] = "commentBodyStyle commentBodyAuthorStyle";
}
if (comment.Content != null)
{
entryBody.Controls.Add(new LiteralControl(Regex.Replace(comment.Content, "\n", "<br />")));
}
if (!requestPage.HideAdminTools && SiteSecurity.IsInRole("admin"))
{
HtmlGenericControl spamStatus = new HtmlGenericControl("div");
spamStatus.Attributes["class"] = "commentSpamStateStyle";
spamStatus.InnerText = ApplicationResourceTable.GetSpamStateDescription(comment.SpamState);
entryBody.Controls.Add(spamStatus);
}
entry.Controls.Add(entryBody);
HtmlGenericControl footer = new HtmlGenericControl("div");
footer.Attributes["class"] = "commentBoxFooterStyle";
entry.Controls.Add(footer);
if (requestPage.SiteConfig.CommentsAllowGravatar && String.IsNullOrEmpty(comment.AuthorEmail) == false)
{
string hash = "";
byte[] data, enc;
data = Encoding.Default.GetBytes(comment.AuthorEmail.ToLowerInvariant());
using (MD5 md5 = new MD5CryptoServiceProvider())
{
enc = md5.TransformFinalBlock(data, 0, data.Length);
foreach (byte b in md5.Hash)
{
hash += Convert.ToString(b, 16).ToLower().PadLeft(2, '0');
}
md5.Clear();
}
string nogravpath = "";
if (requestPage.SiteConfig.CommentsGravatarNoImgPath != null)
{
if (requestPage.SiteConfig.CommentsGravatarNoImgPath != "")
{
if (requestPage.SiteConfig.CommentsGravatarNoImgPath.Substring(0, 4) == "http")
{
nogravpath = "&default=" + Server.UrlEncode(requestPage.SiteConfig.CommentsGravatarNoImgPath);
}
else
{
nogravpath = "&default=" + Server.UrlEncode(requestPage.SiteConfig.Root + requestPage.SiteConfig.CommentsGravatarNoImgPath);
}
}
}
if (String.IsNullOrEmpty(requestPage.SiteConfig.CommentsGravatarNoImgPath) == false)
{
if (requestPage.SiteConfig.CommentsGravatarNoImgPath == "identicon" ||
requestPage.SiteConfig.CommentsGravatarNoImgPath == "wavatar" ||
requestPage.SiteConfig.CommentsGravatarNoImgPath == "monsterid" ||
requestPage.SiteConfig.CommentsGravatarNoImgPath.Substring(0, 4) == "http")
{
nogravpath = "&default=" + Server.UrlEncode(requestPage.SiteConfig.CommentsGravatarNoImgPath);
}
else
{
nogravpath = "&default=" + Server.UrlEncode(requestPage.SiteConfig.Root + requestPage.SiteConfig.CommentsGravatarNoImgPath);
}
}
string gravborder = "";
if (requestPage.SiteConfig.CommentsGravatarBorder != null)
{
if (requestPage.SiteConfig.CommentsGravatarBorder != "")
{
gravborder = "&border=" + requestPage.SiteConfig.CommentsGravatarBorder;
}
}
string gravsize = "";
if (requestPage.SiteConfig.CommentsGravatarSize != null)
{
if (requestPage.SiteConfig.CommentsGravatarSize != "")
{
gravsize = "&size=" + requestPage.SiteConfig.CommentsGravatarSize;
}
}
string gravrating = "";
if (requestPage.SiteConfig.CommentsGravatarRating != null)
{
if (requestPage.SiteConfig.CommentsGravatarRating != "")
{
gravrating = "&rating=" + requestPage.SiteConfig.CommentsGravatarRating;
}
}
HtmlGenericControl entryGRAVATAR = new HtmlGenericControl("span");
entryGRAVATAR.Attributes["class"] = "commentGravatarBlock";
entryGRAVATAR.InnerHtml = "<img class=\"commentGravatar\" src=\"//www.gravatar.com/avatar.php?gravatar_id=" + hash + gravrating + gravsize + nogravpath + gravborder + "\"/>";
footer.Controls.Add(entryGRAVATAR);
}
string authorLink = null;
if (comment.AuthorHomepage != null && comment.AuthorHomepage.Length > 0)
{
authorLink = FixUrl(comment.AuthorHomepage);
}
else if (comment.AuthorEmail != null && comment.AuthorEmail.Length > 0)
{
if (!requestPage.SiteConfig.SupressEmailAddressDisplay)
{
authorLink = "mailto:" + SiteUtilities.SpamBlocker(comment.AuthorEmail);
}
}
if (authorLink != null)
{
HyperLink link = new HyperLink();
link.Attributes["class"] = "commentPermalinkStyle";
link.NavigateUrl = authorLink;
link.Text = comment.Author;
link.Attributes.Add("rel", "nofollow");
footer.Controls.Add(link);
if (comment.OpenId)
{
System.Web.UI.WebControls.Image i = new System.Web.UI.WebControls.Image();
i.ImageUrl = "~/images/openid-icon-small.gif";
i.CssClass = "commentOpenId";
link.Controls.Add(i);
Literal l = new Literal();
l.Text = comment.Author;
link.Controls.Add(l);
}
}
else
{
Label l = new Label();
l.Attributes["class"] = "commentPermalinkStyle";
l.Text = comment.Author;
footer.Controls.Add(l);
}
if (!requestPage.SiteConfig.SupressEmailAddressDisplay)
{
if (comment.AuthorEmail != null && comment.AuthorEmail.Length > 0)
{
footer.Controls.Add(new LiteralControl(" | "));
HtmlGenericControl mailto = new HtmlGenericControl("span");
footer.Controls.Add(mailto);
HyperLink link = new HyperLink();
link.CssClass = "commentMailToStyle";
link.NavigateUrl = "mailto:" + SiteUtilities.SpamBlocker(comment.AuthorEmail);
link.Text = SiteUtilities.SpamBlocker(comment.AuthorEmail);
mailto.Controls.Add(link);
}
}
if (!requestPage.HideAdminTools && SiteSecurity.IsInRole("admin"))
{
if (!string.IsNullOrEmpty(comment.AuthorIPAddress))
{
try
{
if (requestPage.SiteConfig.ResolveCommenterIP == true)
{
System.Net.IPHostEntry hostInfo = System.Net.Dns.GetHostEntry(comment.AuthorIPAddress);
footer.Controls.Add(
new LiteralControl(" (" + comment.AuthorIPAddress + " " + hostInfo.HostName + ") "));
}
else
{
footer.Controls.Add(new LiteralControl(" (" + comment.AuthorIPAddress + ") "));
}
}
catch
{
footer.Controls.Add(new LiteralControl(" (" + comment.AuthorIPAddress + ") "));
}
}
footer.Controls.Add(new LiteralControl(" "));
// create delete hyperlink
HyperLink deleteHl = new HyperLink();
deleteHl.CssClass = "deleteLinkStyle";
System.Web.UI.WebControls.Image img = new System.Web.UI.WebControls.Image();
img.CssClass = "deleteLinkImageStyle";
img.ImageUrl = new Uri(new Uri(SiteUtilities.GetBaseUrl(requestPage.SiteConfig)), requestPage.GetThemedImageUrl("deletebutton")).ToString();
img.BorderWidth = 0;
deleteHl.Controls.Add(img);
deleteHl.NavigateUrl = String.Format("javascript:deleteComment(\"{0}\", \"{1}\", \"{2}\")", Comment.TargetEntryId, Comment.EntryId, Comment.Author == null ? String.Empty : Comment.Author.Replace("\"", "\\\""));
ResourceManager resmgr = resmgr = ApplicationResourceTable.Get();
if (!Page.ClientScript.IsClientScriptBlockRegistered(this.GetType(), "deleteCommentScript"))
{
// add the javascript to allow deletion of the comment
string scriptString = "<script type=\"text/javascript\" language=\"JavaScript\">\n";
scriptString += "function deleteComment(entryId, commentId, commentFrom)\n";
scriptString += "{\n";
scriptString += String.Format(" if(confirm(\"{0} \\n\\n\" + commentFrom))\n", resmgr.GetString("text_delete_confirm"));
scriptString += " {\n";
scriptString += " location.href=\"deleteItem.ashx?entryid=\" + entryId + \"&commentId=\" + commentId\n";
scriptString += " }\n";
scriptString += "}\n";
scriptString += "</script>";
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "deleteCommentScript", scriptString);
}
footer.Controls.Add(deleteHl);
// create approve hyperlink, when a comment is not public or if its marked as spam
if ((!Comment.IsPublic) || (Comment.SpamState == SpamState.Spam))
{
HyperLink approveHl = new HyperLink();
approveHl.CssClass = "approveLinkStyle";
System.Web.UI.WebControls.Image okImg = new System.Web.UI.WebControls.Image();
okImg.CssClass = "approveImageStyle";
okImg.ImageUrl = new Uri(new Uri(SiteUtilities.GetBaseUrl(requestPage.SiteConfig)), requestPage.GetThemedImageUrl("okbutton-list")).ToString();
okImg.BorderWidth = 0;
approveHl.Controls.Add(okImg);
approveHl.NavigateUrl = String.Format("javascript:approveComment(\"{0}\", \"{1}\")", Comment.TargetEntryId, Comment.EntryId);
if (!Page.ClientScript.IsClientScriptBlockRegistered(this.GetType(), "approveCommentScript"))
{
string approveScript = "<script type=\"text/javascript\" language=\"JavaScript\">\n";
approveScript += "function approveComment(entryId, commentId)\n";
approveScript += "{\n";
approveScript += " location.href=\"approveItem.ashx?entryid=\" + entryId + \"&commentId=\" + commentId\n";
approveScript += "}\n";
approveScript += "</script>";
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "approveCommentScript", approveScript);
}
footer.Controls.Add(approveHl);
}
ISpamBlockingService spamBlockingService = requestPage.SiteConfig.SpamBlockingService;
if ((spamBlockingService != null) && (comment.SpamState != SpamState.Spam))
{
HyperLink reportSpamLink = new HyperLink();
reportSpamLink.CssClass = "approveLinkStyle";
System.Web.UI.WebControls.Image spamImg = new System.Web.UI.WebControls.Image();
spamImg.CssClass = "approveImageStyle";
spamImg.ImageUrl = new Uri(new Uri(SiteUtilities.GetBaseUrl(requestPage.SiteConfig)), requestPage.GetThemedImageUrl("reportspambutton")).ToString();
spamImg.BorderWidth = 0;
reportSpamLink.Controls.Add(spamImg);
reportSpamLink.NavigateUrl = String.Format("javascript:reportComment(\"{0}\", \"{1}\", \"{2}\")", Comment.TargetEntryId, Comment.EntryId, Comment.Author == null ? String.Empty : Comment.Author.Replace("\"", "\\\""));
string reportScript = "<script type=\"text/javascript\" language=\"JavaScript\">\n";
reportScript += "function reportComment(entryId, commentId, commentFrom)\n";
reportScript += "{\n";
reportScript += String.Format(" if(confirm(\"{0} \\n\\n\" + commentFrom))\n", resmgr.GetString("text_reportspam_confirm"));
reportScript += " {\n";
reportScript += " location.href=\"deleteItem.ashx?report=true&entryid=\" + entryId + \"&commentId=\" + commentId\n";
reportScript += " }\n";
reportScript += "}\n";
reportScript += "</script>";
if (!Page.ClientScript.IsClientScriptBlockRegistered(this.GetType(), "reportCommentScript"))
{
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "reportCommentScript", reportScript);
}
footer.Controls.Add(reportSpamLink);
}
}
}
}
}
| |
//
// Copyright (c) 2004-2021 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.
//
#define DEBUG
using NLog.Config;
namespace NLog.UnitTests
{
using System;
using System.Globalization;
using System.Threading;
using System.Diagnostics;
using Xunit;
public class NLogTraceListenerTests : NLogTestBase, IDisposable
{
private readonly CultureInfo previousCultureInfo;
public NLogTraceListenerTests()
{
previousCultureInfo = Thread.CurrentThread.CurrentCulture;
// set the culture info with the decimal separator (comma) different from InvariantCulture separator (point)
Thread.CurrentThread.CurrentCulture = new CultureInfo("fr-FR");
}
public void Dispose()
{
// restore previous culture info
Thread.CurrentThread.CurrentCulture = previousCultureInfo;
}
#if !NETSTANDARD1_5
[Fact]
public void TraceWriteTest()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${logger} ${level} ${message}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
Trace.Listeners.Clear();
Trace.Listeners.Add(new NLogTraceListener { Name = "Logger1" });
Trace.Write("Hello");
AssertDebugLastMessage("debug", "Logger1 Debug Hello");
Trace.Write("Hello", "Cat1");
AssertDebugLastMessage("debug", "Logger1 Debug Cat1: Hello");
Trace.Write(3.1415);
AssertDebugLastMessage("debug", $"Logger1 Debug {3.1415}");
Trace.Write(3.1415, "Cat2");
AssertDebugLastMessage("debug", $"Logger1 Debug Cat2: {3.1415}");
}
[Fact]
public void TraceWriteLineTest()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${logger} ${level} ${message}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
Trace.Listeners.Clear();
Trace.Listeners.Add(new NLogTraceListener { Name = "Logger1" });
Trace.WriteLine("Hello");
AssertDebugLastMessage("debug", "Logger1 Debug Hello");
Trace.WriteLine("Hello", "Cat1");
AssertDebugLastMessage("debug", "Logger1 Debug Cat1: Hello");
Trace.WriteLine(3.1415);
AssertDebugLastMessage("debug", $"Logger1 Debug {3.1415}");
Trace.WriteLine(3.1415, "Cat2");
AssertDebugLastMessage("debug", $"Logger1 Debug Cat2: {3.1415}");
}
[Fact]
public void TraceWriteNonDefaultLevelTest()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${logger} ${level} ${message}' /></targets>
<rules>
<logger name='*' minlevel='Trace' writeTo='debug' />
</rules>
</nlog>");
Trace.Listeners.Clear();
Trace.Listeners.Add(new NLogTraceListener { Name = "Logger1", DefaultLogLevel = LogLevel.Trace });
Trace.Write("Hello");
AssertDebugLastMessage("debug", "Logger1 Trace Hello");
}
[Fact]
public void TraceConfiguration()
{
var listener = new NLogTraceListener();
listener.Attributes.Add("defaultLogLevel", "Warn");
listener.Attributes.Add("forceLogLevel", "Error");
listener.Attributes.Add("autoLoggerName", "1");
listener.Attributes.Add("DISABLEFLUSH", "true");
Assert.Equal(LogLevel.Warn, listener.DefaultLogLevel);
Assert.Equal(LogLevel.Error, listener.ForceLogLevel);
Assert.True(listener.AutoLoggerName);
Assert.True(listener.DisableFlush);
}
[Fact]
public void TraceFailTest()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${logger} ${level} ${message}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
Trace.Listeners.Clear();
Trace.Listeners.Add(new NLogTraceListener { Name = "Logger1" });
Trace.Fail("Message");
AssertDebugLastMessage("debug", "Logger1 Error Message");
Trace.Fail("Message", "Detailed Message");
AssertDebugLastMessage("debug", "Logger1 Error Message Detailed Message");
}
[Fact]
public void AutoLoggerNameTest()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${logger} ${level} ${message}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
Trace.Listeners.Clear();
Trace.Listeners.Add(new NLogTraceListener { Name = "Logger1", AutoLoggerName = true });
Trace.Write("Hello");
AssertDebugLastMessage("debug", GetType().FullName + " Debug Hello");
}
[Fact]
public void TraceDataTests()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${logger} ${level} ${message} ${event-context:EventID}' /></targets>
<rules>
<logger name='*' minlevel='Trace' writeTo='debug' />
</rules>
</nlog>");
TraceSource ts = CreateTraceSource();
ts.Listeners.Add(new NLogTraceListener { Name = "Logger1", DefaultLogLevel = LogLevel.Trace });
ts.TraceData(TraceEventType.Critical, 123, 42);
AssertDebugLastMessage("debug", "MySource1 Fatal 42 123");
ts.TraceData(TraceEventType.Critical, 145, 42, 3.14, "foo");
AssertDebugLastMessage("debug", $"MySource1 Fatal 42, {3.14.ToString(CultureInfo.CurrentCulture)}, foo 145");
}
#if MONO
[Fact(Skip="Not working under MONO - not sure if unit test is wrong, or the code")]
#else
[Fact]
#endif
public void LogInformationTest()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${logger} ${level} ${message} ${event-context:EventID}' /></targets>
<rules>
<logger name='*' minlevel='Trace' writeTo='debug' />
</rules>
</nlog>");
TraceSource ts = CreateTraceSource();
ts.Listeners.Add(new NLogTraceListener { Name = "Logger1", DefaultLogLevel = LogLevel.Trace });
ts.TraceInformation("Quick brown fox");
AssertDebugLastMessage("debug", "MySource1 Info Quick brown fox 0");
ts.TraceInformation("Mary had {0} lamb", "a little");
AssertDebugLastMessage("debug", "MySource1 Info Mary had a little lamb 0");
}
[Fact]
public void TraceEventTests()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${logger} ${level} ${message} ${event-context:EventID}' /></targets>
<rules>
<logger name='*' minlevel='Trace' writeTo='debug' />
</rules>
</nlog>");
TraceSource ts = CreateTraceSource();
ts.Listeners.Add(new NLogTraceListener { Name = "Logger1", DefaultLogLevel = LogLevel.Trace });
ts.TraceEvent(TraceEventType.Information, 123, "Quick brown {0} jumps over the lazy {1}.", "fox", "dog");
AssertDebugLastMessage("debug", "MySource1 Info Quick brown fox jumps over the lazy dog. 123");
ts.TraceEvent(TraceEventType.Information, 123);
AssertDebugLastMessage("debug", "MySource1 Info 123");
ts.TraceEvent(TraceEventType.Verbose, 145, "Bar");
AssertDebugLastMessage("debug", "MySource1 Trace Bar 145");
ts.TraceEvent(TraceEventType.Error, 145, "Foo");
AssertDebugLastMessage("debug", "MySource1 Error Foo 145");
ts.TraceEvent(TraceEventType.Suspend, 145, "Bar");
AssertDebugLastMessage("debug", "MySource1 Debug Bar 145");
ts.TraceEvent(TraceEventType.Resume, 145, "Foo");
AssertDebugLastMessage("debug", "MySource1 Debug Foo 145");
ts.TraceEvent(TraceEventType.Warning, 145, "Bar");
AssertDebugLastMessage("debug", "MySource1 Warn Bar 145");
ts.TraceEvent(TraceEventType.Critical, 145, "Foo");
AssertDebugLastMessage("debug", "MySource1 Fatal Foo 145");
}
#if MONO
[Fact(Skip="Not working under MONO - not sure if unit test is wrong, or the code")]
#else
[Fact]
#endif
public void ForceLogLevelTest()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${logger} ${level} ${message} ${event-context:EventID}' /></targets>
<rules>
<logger name='*' minlevel='Trace' writeTo='debug' />
</rules>
</nlog>");
TraceSource ts = CreateTraceSource();
ts.Listeners.Add(new NLogTraceListener { Name = "Logger1", DefaultLogLevel = LogLevel.Trace, ForceLogLevel = LogLevel.Warn });
// force all logs to be Warn, DefaultLogLevel has no effect on TraceSource
ts.TraceInformation("Quick brown fox");
AssertDebugLastMessage("debug", "MySource1 Warn Quick brown fox 0");
ts.TraceInformation("Mary had {0} lamb", "a little");
AssertDebugLastMessage("debug", "MySource1 Warn Mary had a little lamb 0");
}
[Fact]
public void FilterTraceTest()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${logger} ${level} ${message} ${event-context:EventID}' /></targets>
<rules>
<logger name='*' minlevel='Trace' writeTo='debug' />
</rules>
</nlog>");
TraceSource ts = CreateTraceSource();
ts.Listeners.Add(new NLogTraceListener { Name = "Logger1", DefaultLogLevel = LogLevel.Trace, ForceLogLevel = LogLevel.Warn, Filter = new EventTypeFilter(SourceLevels.Error) });
// force all logs to be Warn, DefaultLogLevel has no effect on TraceSource
ts.TraceEvent(TraceEventType.Error, 0, "Quick brown fox");
AssertDebugLastMessage("debug", "MySource1 Warn Quick brown fox 0");
ts.TraceInformation("Mary had {0} lamb", "a little");
AssertDebugLastMessage("debug", "MySource1 Warn Quick brown fox 0");
}
#endif
[Fact]
public void TraceTargetWriteLineTest()
{
var logger = new LogFactory().Setup().LoadConfiguration(builder =>
{
builder.ForLogger().WriteToTrace(layout: "${logger} ${level} ${message}", rawWrite: true);
}).GetLogger("MySource1");
var sw = new System.IO.StringWriter();
try
{
Trace.Listeners.Clear();
Trace.Listeners.Add(new TextWriterTraceListener(sw));
foreach (var logLevel in LogLevel.AllLevels)
{
if (logLevel == LogLevel.Off)
continue;
logger.Log(logLevel, "Quick brown fox");
Trace.Flush();
Assert.Equal($"MySource1 {logLevel} Quick brown fox" + Environment.NewLine, sw.GetStringBuilder().ToString());
sw.GetStringBuilder().Length = 0;
}
Trace.Flush();
}
finally
{
Trace.Listeners.Clear();
}
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void TraceTargetEnableTraceFailTest(bool enableTraceFail)
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString($@"
<nlog>
<targets>
<target name='trace' type='Trace' layout='${{logger}} ${{level}} ${{message}}' enableTraceFail='{enableTraceFail}' />
</targets>
<rules>
<logger name='*' minlevel='Trace' writeTo='trace' />
</rules>
</nlog>");
var logger = LogManager.GetLogger(nameof(TraceTargetEnableTraceFailTest));
var sw = new System.IO.StringWriter();
try
{
Trace.Listeners.Clear();
Trace.Listeners.Add(new TextWriterTraceListener(sw));
foreach (var logLevel in LogLevel.AllLevels)
{
if (logLevel == LogLevel.Off)
continue;
logger.Log(logLevel, "Quick brown fox");
Trace.Flush();
if (logLevel == LogLevel.Fatal)
{
if (enableTraceFail)
Assert.Equal($"Fail: {logger.Name} Fatal Quick brown fox" + Environment.NewLine, sw.GetStringBuilder().ToString());
else
Assert.NotEqual($"Fail: {logger.Name} Fatal Quick brown fox" + Environment.NewLine, sw.GetStringBuilder().ToString());
}
Assert.Contains($"{logger.Name} {logLevel} Quick brown fox" + Environment.NewLine, sw.GetStringBuilder().ToString());
sw.GetStringBuilder().Length = 0;
}
}
finally
{
Trace.Listeners.Clear();
}
}
private static TraceSource CreateTraceSource()
{
var ts = new TraceSource("MySource1", SourceLevels.All);
#if MONO
// for some reason needed on Mono
ts.Switch = new SourceSwitch("MySource1", "Verbose");
ts.Switch.Level = SourceLevels.All;
#endif
return ts;
}
}
}
| |
/* ====================================================================
*/
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
using System.Xml;
using System.IO;
namespace Oranikle.ReportDesigner
{
/// <summary>
/// Summary description for ModulesClassesCtl.
/// </summary>
internal class ModulesClassesCtl : Oranikle.ReportDesigner.Base.BaseControl, IProperty
{
private DesignXmlDraw _Draw;
private DataTable _DTCM;
private DataTable _DTCL;
private System.Windows.Forms.Label label1;
private Oranikle.Studio.Controls.StyledButton bDeleteCM;
private System.Windows.Forms.DataGrid dgCodeModules;
private Oranikle.Studio.Controls.StyledButton bDeleteClass;
private System.Windows.Forms.DataGrid dgClasses;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.DataGridTableStyle dgTableStyleCM;
private System.Windows.Forms.DataGridTableStyle dgTableStyleCL;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
internal ModulesClassesCtl(DesignXmlDraw dxDraw)
{
_Draw = dxDraw;
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
// Initialize form using the style node values
InitValues();
}
private void InitValues()
{
BuildCodeModules();
BuildClasses();
}
private void BuildCodeModules()
{
XmlNode rNode = _Draw.GetReportNode();
// Initialize the DataGrid columns
DataGridTextBoxColumn dgtbCM = new DataGridTextBoxColumn();
this.dgTableStyleCM.GridColumnStyles.AddRange(new DataGridColumnStyle[] {dgtbCM});
//
// dgtbGE
//
dgtbCM.HeaderText = "Code Module";
dgtbCM.MappingName = "Code Module";
dgtbCM.Width = 175;
// Initialize the DataTable
_DTCM = new DataTable();
_DTCM.Columns.Add(new DataColumn("Code Module", typeof(string)));
string[] rowValues = new string[1];
XmlNode cmsNode = _Draw.GetNamedChildNode(rNode, "CodeModules");
if (cmsNode != null)
foreach (XmlNode cmNode in cmsNode.ChildNodes)
{
if (cmNode.NodeType != XmlNodeType.Element ||
cmNode.Name != "CodeModule")
continue;
rowValues[0] = cmNode.InnerText;
_DTCM.Rows.Add(rowValues);
}
this.dgCodeModules.DataSource = _DTCM;
DataGridTableStyle ts = dgCodeModules.TableStyles[0];
ts.GridColumnStyles[0].Width = 330;
}
private void BuildClasses()
{
XmlNode rNode = _Draw.GetReportNode();
// Initialize the DataGrid columns
DataGridTextBoxColumn dgtbCL = new DataGridTextBoxColumn();
DataGridTextBoxColumn dgtbIn = new DataGridTextBoxColumn();
this.dgTableStyleCL.GridColumnStyles.AddRange(new DataGridColumnStyle[] {dgtbCL, dgtbIn});
dgtbCL.HeaderText = "Class Name";
dgtbCL.MappingName = "Class Name";
dgtbCL.Width = 80;
dgtbIn.HeaderText = "Instance Name";
dgtbIn.MappingName = "Instance Name";
dgtbIn.Width = 80;
// Initialize the DataTable
_DTCL = new DataTable();
_DTCL.Columns.Add(new DataColumn("Class Name", typeof(string)));
_DTCL.Columns.Add(new DataColumn("Instance Name", typeof(string)));
string[] rowValues = new string[2];
XmlNode clsNode = _Draw.GetNamedChildNode(rNode, "Classes");
if (clsNode != null)
foreach (XmlNode clNode in clsNode.ChildNodes)
{
if (clNode.NodeType != XmlNodeType.Element ||
clNode.Name != "Class")
continue;
XmlNode node = _Draw.GetNamedChildNode(clNode, "ClassName");
if (node != null)
rowValues[0] = node.InnerText;
node = _Draw.GetNamedChildNode(clNode, "InstanceName");
if (node != null)
rowValues[1] = node.InnerText;
_DTCL.Rows.Add(rowValues);
}
this.dgClasses.DataSource = _DTCL;
DataGridTableStyle ts = dgClasses.TableStyles[0];
ts.GridColumnStyles[0].Width = 200;
ts.GridColumnStyles[1].Width = 130;
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.label1 = new System.Windows.Forms.Label();
this.bDeleteCM = new Oranikle.Studio.Controls.StyledButton();
this.dgCodeModules = new System.Windows.Forms.DataGrid();
this.dgTableStyleCM = new System.Windows.Forms.DataGridTableStyle();
this.bDeleteClass = new Oranikle.Studio.Controls.StyledButton();
this.dgClasses = new System.Windows.Forms.DataGrid();
this.dgTableStyleCL = new System.Windows.Forms.DataGridTableStyle();
this.label2 = new System.Windows.Forms.Label();
((System.ComponentModel.ISupportInitialize)(this.dgCodeModules)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.dgClasses)).BeginInit();
this.SuspendLayout();
//
// label1
//
this.label1.Location = new System.Drawing.Point(8, 8);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(448, 23);
this.label1.TabIndex = 0;
this.label1.Text = "Enter the names of the code module for use in expressions (e.g. MyRoutines.dll)";
//
// bDeleteCM
//
this.bDeleteCM.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(245)))), ((int)(((byte)(245)))), ((int)(((byte)(245)))));
this.bDeleteCM.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(225)))), ((int)(((byte)(225)))), ((int)(((byte)(225)))));
this.bDeleteCM.BackFillMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal;
this.bDeleteCM.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(200)))), ((int)(((byte)(200)))), ((int)(((byte)(200)))));
this.bDeleteCM.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.bDeleteCM.Font = new System.Drawing.Font("Arial", 9F);
this.bDeleteCM.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(90)))), ((int)(((byte)(90)))), ((int)(((byte)(90)))));
this.bDeleteCM.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.bDeleteCM.Location = new System.Drawing.Point(400, 32);
this.bDeleteCM.Name = "bDeleteCM";
this.bDeleteCM.OverriddenSize = null;
this.bDeleteCM.Size = new System.Drawing.Size(48, 21);
this.bDeleteCM.TabIndex = 4;
this.bDeleteCM.Text = "Delete";
this.bDeleteCM.UseVisualStyleBackColor = true;
this.bDeleteCM.Click += new System.EventHandler(this.bDeleteCM_Click);
//
// dgCodeModules
//
this.dgCodeModules.BackgroundColor = System.Drawing.Color.White;
this.dgCodeModules.CaptionVisible = false;
this.dgCodeModules.DataMember = "";
this.dgCodeModules.HeaderForeColor = System.Drawing.SystemColors.ControlText;
this.dgCodeModules.Location = new System.Drawing.Point(16, 32);
this.dgCodeModules.Name = "dgCodeModules";
this.dgCodeModules.Size = new System.Drawing.Size(376, 88);
this.dgCodeModules.TabIndex = 3;
this.dgCodeModules.TableStyles.AddRange(new System.Windows.Forms.DataGridTableStyle[] {
this.dgTableStyleCM});
//
// dgTableStyleCM
//
this.dgTableStyleCM.DataGrid = this.dgCodeModules;
this.dgTableStyleCM.HeaderForeColor = System.Drawing.SystemColors.ControlText;
//
// bDeleteClass
//
this.bDeleteClass.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(245)))), ((int)(((byte)(245)))), ((int)(((byte)(245)))));
this.bDeleteClass.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(225)))), ((int)(((byte)(225)))), ((int)(((byte)(225)))));
this.bDeleteClass.BackFillMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal;
this.bDeleteClass.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(200)))), ((int)(((byte)(200)))), ((int)(((byte)(200)))));
this.bDeleteClass.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.bDeleteClass.Font = new System.Drawing.Font("Arial", 9F);
this.bDeleteClass.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(90)))), ((int)(((byte)(90)))), ((int)(((byte)(90)))));
this.bDeleteClass.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.bDeleteClass.Location = new System.Drawing.Point(400, 160);
this.bDeleteClass.Name = "bDeleteClass";
this.bDeleteClass.OverriddenSize = null;
this.bDeleteClass.Size = new System.Drawing.Size(48, 21);
this.bDeleteClass.TabIndex = 7;
this.bDeleteClass.Text = "Delete";
this.bDeleteClass.UseVisualStyleBackColor = true;
this.bDeleteClass.Click += new System.EventHandler(this.bDeleteClass_Click);
//
// dgClasses
//
this.dgClasses.BackgroundColor = System.Drawing.Color.White;
this.dgClasses.CaptionVisible = false;
this.dgClasses.DataMember = "";
this.dgClasses.HeaderForeColor = System.Drawing.SystemColors.ControlText;
this.dgClasses.Location = new System.Drawing.Point(16, 160);
this.dgClasses.Name = "dgClasses";
this.dgClasses.Size = new System.Drawing.Size(376, 88);
this.dgClasses.TabIndex = 6;
this.dgClasses.TableStyles.AddRange(new System.Windows.Forms.DataGridTableStyle[] {
this.dgTableStyleCL});
//
// dgTableStyleCL
//
this.dgTableStyleCL.DataGrid = this.dgClasses;
this.dgTableStyleCL.HeaderForeColor = System.Drawing.SystemColors.ControlText;
//
// label2
//
this.label2.Location = new System.Drawing.Point(8, 136);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(448, 23);
this.label2.TabIndex = 5;
this.label2.Text = "Enter the classes with names that will be instantiated for use in expressions";
//
// ModulesClassesCtl
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.Controls.Add(this.bDeleteClass);
this.Controls.Add(this.dgClasses);
this.Controls.Add(this.label2);
this.Controls.Add(this.bDeleteCM);
this.Controls.Add(this.dgCodeModules);
this.Controls.Add(this.label1);
this.Name = "ModulesClassesCtl";
this.Size = new System.Drawing.Size(472, 288);
((System.ComponentModel.ISupportInitialize)(this.dgCodeModules)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.dgClasses)).EndInit();
this.ResumeLayout(false);
}
#endregion
public bool IsValid()
{
return true;
}
public void Apply()
{
ApplyCodeModules();
ApplyClasses();
}
private void ApplyCodeModules()
{
XmlNode rNode = _Draw.GetReportNode();
_Draw.RemoveElement(rNode, "CodeModules");
if (!HasRows(this._DTCM, 1))
return;
// Set the CodeModules
XmlNode cms = _Draw.CreateElement(rNode, "CodeModules", null);
foreach (DataRow dr in _DTCM.Rows)
{
if (dr[0] == DBNull.Value ||
dr[0].ToString().Trim().Length <= 0)
continue;
_Draw.CreateElement(cms, "CodeModule", dr[0].ToString());
}
}
private void ApplyClasses()
{
XmlNode rNode = _Draw.GetReportNode();
_Draw.RemoveElement(rNode, "Classes");
if (!HasRows(this._DTCL, 2))
return;
// Set the classes
XmlNode cs = _Draw.CreateElement(rNode, "Classes", null);
foreach (DataRow dr in _DTCL.Rows)
{
if (dr[0] == DBNull.Value ||
dr[1] == DBNull.Value ||
dr[0].ToString().Trim().Length <= 0 ||
dr[1].ToString().Trim().Length <= 0)
continue;
XmlNode c = _Draw.CreateElement(cs, "Class", null);
_Draw.CreateElement(c, "ClassName", dr[0].ToString());
_Draw.CreateElement(c, "InstanceName", dr[1].ToString());
}
}
private bool HasRows(DataTable dt, int columns)
{
foreach (DataRow dr in dt.Rows)
{
bool bCompleteRow = true;
for (int i=0; i < columns; i++)
{
if (dr[i] == DBNull.Value)
{
bCompleteRow = false;
break;
}
string ge = (string) dr[i];
if (ge.Length <= 0)
{
bCompleteRow = false;
break;
}
}
if (bCompleteRow)
return true;
}
return false;
}
private void bDeleteCM_Click(object sender, System.EventArgs e)
{
int cr = this.dgCodeModules.CurrentRowIndex;
if (cr < 0) // already at the top
return;
_DTCM.Rows.RemoveAt(cr);
}
private void bDeleteClass_Click(object sender, System.EventArgs e)
{
int cr = this.dgClasses.CurrentRowIndex;
if (cr < 0) // already at the top
return;
_DTCL.Rows.RemoveAt(cr);
}
}
}
| |
//-----------------------------------------------------------------------------
// Torque
// Copyright GarageGames, LLC 2011
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Message Hud
//-----------------------------------------------------------------------------
// chat hud sizes in lines
$outerChatLenY[1] = 4;
$outerChatLenY[2] = 9;
$outerChatLenY[3] = 13;
// Only play sound files that are <= 5000ms in length.
$MaxMessageWavLength = 5000;
// Helper function to play a sound file if the message indicates.
// Returns starting position of wave file indicator.
function playMessageSound(%message, %voice, %pitch)
{
// Search for wav tag marker.
%wavStart = strstr(%message, "~w");
if (%wavStart == -1)
{
return -1;
}
%wav = getSubStr(%message, %wavStart + 2, 1000);
if (%voice !$= "")
{
%wavFile = "art/sound/voice/" @ %voice @ "/" @ %wav;
}
else
%wavFile = "art/sound/" @ %wav;
if (strstr(%wavFile, ".wav") != (strlen(%wavFile) - 4))
%wavFile = %wavFile @ ".wav";
// XXX This only expands to a single filepath, of course; it
// would be nice to support checking in each mod path if we
// have multiple mods active.
%wavFile = ExpandFilename(%wavFile);
%wavSource = sfxCreateSource(AudioMessage, %wavFile);
if (isObject(%wavSource))
{
%wavLengthMS = %wavSource.getDuration() * %pitch;
if (%wavLengthMS == 0)
error("** WAV file \"" @ %wavFile @ "\" is nonexistent or sound is zero-length **");
else if (%wavLengthMS <= $MaxMessageWavLength)
{
if (isObject($ClientChatHandle[%sender]))
$ClientChatHandle[%sender].delete();
$ClientChatHandle[%sender] = %wavSource;
if (%pitch != 1.0)
$ClientChatHandle[%sender].setPitch(%pitch);
$ClientChatHandle[%sender].play();
}
else
error("** WAV file \"" @ %wavFile @ "\" is too long **");
}
else
error("** Unable to load WAV file : \"" @ %wavFile @ "\" **");
return %wavStart;
}
// All messages are stored in this HudMessageVector, the actual
// MainChatHud only displays the contents of this vector.
new MessageVector(HudMessageVector);
$LastHudTarget = 0;
//-----------------------------------------------------------------------------
function onChatMessage(%message, %voice, %pitch)
{
// XXX Client objects on the server must have voiceTag and voicePitch
// fields for values to be passed in for %voice and %pitch... in
// this example mod, they don't have those fields.
// Clients are not allowed to trigger general game sounds with their
// chat messages... a voice directory MUST be specified.
if (%voice $= "") {
%voice = "default";
}
// See if there's a sound at the end of the message, and play it.
if ((%wavStart = playMessageSound(%message, %voice, %pitch)) != -1) {
// Remove the sound marker from the end of the message.
%message = getSubStr(%message, 0, %wavStart);
}
// Chat goes to the chat HUD.
if (getWordCount(%message)) {
ChatHud.addLine(%message);
}
}
function onServerMessage(%message)
{
// See if there's a sound at the end of the message, and play it.
if ((%wavStart = playMessageSound(%message)) != -1) {
// Remove the sound marker from the end of the message.
%message = getSubStr(%message, 0, %wavStart);
}
// Server messages go to the chat HUD too.
if (getWordCount(%message)) {
ChatHud.addLine(%message);
}
}
//-----------------------------------------------------------------------------
// MainChatHud methods
//-----------------------------------------------------------------------------
function MainChatHud::onWake( %this )
{
// set the chat hud to the users pref
%this.setChatHudLength( $Pref::ChatHudLength );
}
//------------------------------------------------------------------------------
function MainChatHud::setChatHudLength( %this, %length )
{
%textHeight = ChatHud.Profile.fontSize + ChatHud.lineSpacing;
if (%textHeight <= 0)
%textHeight = 12;
%lengthInPixels = $outerChatLenY[%length] * %textHeight;
%chatMargin = getWord(OuterChatHud.extent, 1) - getWord(ChatScrollHud.Extent, 1)
+ 2 * ChatScrollHud.profile.borderThickness;
OuterChatHud.setExtent(firstWord(OuterChatHud.extent), %lengthInPixels + %chatMargin);
ChatScrollHud.scrollToBottom();
ChatPageDown.setVisible(false);
}
//------------------------------------------------------------------------------
function MainChatHud::nextChatHudLen( %this )
{
%len = $pref::ChatHudLength++;
if ($pref::ChatHudLength == 4)
$pref::ChatHudLength = 1;
%this.setChatHudLength($pref::ChatHudLength);
}
//-----------------------------------------------------------------------------
// ChatHud methods
// This is the actual message vector/text control which is part of
// the MainChatHud dialog
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
function ChatHud::addLine(%this,%text)
{
//first, see if we're "scrolled up"...
%textHeight = %this.profile.fontSize + %this.lineSpacing;
if (%textHeight <= 0)
%textHeight = 12;
%scrollBox = %this.getGroup();
%chatScrollHeight = getWord(%scrollBox.extent, 1) - 2 * %scrollBox.profile.borderThickness;
%chatPosition = getWord(%this.extent, 1) - %chatScrollHeight + getWord(%this.position, 1) - %scrollBox.profile.borderThickness;
%linesToScroll = mFloor((%chatPosition / %textHeight) + 0.5);
if (%linesToScroll > 0)
%origPosition = %this.position;
//remove old messages from the top only if scrolled down all the way
while( !chatPageDown.isVisible() && HudMessageVector.getNumLines() && (HudMessageVector.getNumLines() >= $pref::HudMessageLogSize))
{
%tag = HudMessageVector.getLineTag(0);
if(%tag != 0)
%tag.delete();
HudMessageVector.popFrontLine();
}
//add the message...
HudMessageVector.pushBackLine(%text, $LastHudTarget);
$LastHudTarget = 0;
//now that we've added the message, see if we need to reset the position
if (%linesToScroll > 0)
{
chatPageDown.setVisible(true);
%this.position = %origPosition;
}
else
chatPageDown.setVisible(false);
}
//-----------------------------------------------------------------------------
function ChatHud::pageUp(%this)
{
// Find out the text line height
%textHeight = %this.profile.fontSize + %this.lineSpacing;
if (%textHeight <= 0)
%textHeight = 12;
%scrollBox = %this.getGroup();
// Find out how many lines per page are visible
%chatScrollHeight = getWord(%scrollBox.extent, 1) - 2 * %scrollBox.profile.borderThickness;
if (%chatScrollHeight <= 0)
return;
%pageLines = mFloor(%chatScrollHeight / %textHeight) - 1; // have a 1 line overlap on pages
if (%pageLines <= 0)
%pageLines = 1;
// See how many lines we actually can scroll up:
%chatPosition = -1 * (getWord(%this.position, 1) - %scrollBox.profile.borderThickness);
%linesToScroll = mFloor((%chatPosition / %textHeight) + 0.5);
if (%linesToScroll <= 0)
return;
if (%linesToScroll > %pageLines)
%scrollLines = %pageLines;
else
%scrollLines = %linesToScroll;
// Now set the position
%this.position = firstWord(%this.position) SPC (getWord(%this.position, 1) + (%scrollLines * %textHeight));
// Display the pageup icon
chatPageDown.setVisible(true);
}
//-----------------------------------------------------------------------------
function ChatHud::pageDown(%this)
{
// Find out the text line height
%textHeight = %this.profile.fontSize + %this.lineSpacing;
if (%textHeight <= 0)
%textHeight = 12;
%scrollBox = %this.getGroup();
// Find out how many lines per page are visible
%chatScrollHeight = getWord(%scrollBox.extent, 1) - 2 * %scrollBox.profile.borderThickness;
if (%chatScrollHeight <= 0)
return;
%pageLines = mFloor(%chatScrollHeight / %textHeight) - 1;
if (%pageLines <= 0)
%pageLines = 1;
// See how many lines we actually can scroll down:
%chatPosition = getWord(%this.extent, 1) - %chatScrollHeight + getWord(%this.position, 1) - %scrollBox.profile.borderThickness;
%linesToScroll = mFloor((%chatPosition / %textHeight) + 0.5);
if (%linesToScroll <= 0)
return;
if (%linesToScroll > %pageLines)
%scrollLines = %pageLines;
else
%scrollLines = %linesToScroll;
// Now set the position
%this.position = firstWord(%this.position) SPC (getWord(%this.position, 1) - (%scrollLines * %textHeight));
// See if we have should (still) display the pagedown icon
if (%scrollLines < %linesToScroll)
chatPageDown.setVisible(true);
else
chatPageDown.setVisible(false);
}
//-----------------------------------------------------------------------------
// Support functions
//-----------------------------------------------------------------------------
function pageUpMessageHud()
{
ChatHud.pageUp();
}
function pageDownMessageHud()
{
ChatHud.pageDown();
}
function cycleMessageHudSize()
{
MainChatHud.nextChatHudLen();
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the workspaces-2015-04-08.normal.json service model.
*/
using System;
using System.IO;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Amazon.WorkSpaces;
using Amazon.WorkSpaces.Model;
using Amazon.WorkSpaces.Model.Internal.MarshallTransformations;
using Amazon.Runtime.Internal.Transform;
using ServiceClientGenerator;
using AWSSDK_DotNet35.UnitTests.TestTools;
namespace AWSSDK_DotNet35.UnitTests.Marshalling
{
[TestClass]
public class WorkSpacesMarshallingTests
{
static readonly ServiceModel service_model = Utils.LoadServiceModel("workspaces-2015-04-08.normal.json", "workspaces.customizations.json");
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("WorkSpaces")]
public void CreateWorkspacesMarshallTest()
{
var request = InstantiateClassGenerator.Execute<CreateWorkspacesRequest>();
var marshaller = new CreateWorkspacesRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<CreateWorkspacesRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("CreateWorkspaces").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = CreateWorkspacesResponseUnmarshaller.Instance.Unmarshall(context)
as CreateWorkspacesResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("WorkSpaces")]
public void DescribeWorkspaceBundlesMarshallTest()
{
var request = InstantiateClassGenerator.Execute<DescribeWorkspaceBundlesRequest>();
var marshaller = new DescribeWorkspaceBundlesRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<DescribeWorkspaceBundlesRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("DescribeWorkspaceBundles").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = DescribeWorkspaceBundlesResponseUnmarshaller.Instance.Unmarshall(context)
as DescribeWorkspaceBundlesResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("WorkSpaces")]
public void DescribeWorkspaceDirectoriesMarshallTest()
{
var request = InstantiateClassGenerator.Execute<DescribeWorkspaceDirectoriesRequest>();
var marshaller = new DescribeWorkspaceDirectoriesRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<DescribeWorkspaceDirectoriesRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("DescribeWorkspaceDirectories").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = DescribeWorkspaceDirectoriesResponseUnmarshaller.Instance.Unmarshall(context)
as DescribeWorkspaceDirectoriesResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("WorkSpaces")]
public void DescribeWorkspacesMarshallTest()
{
var request = InstantiateClassGenerator.Execute<DescribeWorkspacesRequest>();
var marshaller = new DescribeWorkspacesRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<DescribeWorkspacesRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("DescribeWorkspaces").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = DescribeWorkspacesResponseUnmarshaller.Instance.Unmarshall(context)
as DescribeWorkspacesResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("WorkSpaces")]
public void RebootWorkspacesMarshallTest()
{
var request = InstantiateClassGenerator.Execute<RebootWorkspacesRequest>();
var marshaller = new RebootWorkspacesRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<RebootWorkspacesRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("RebootWorkspaces").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = RebootWorkspacesResponseUnmarshaller.Instance.Unmarshall(context)
as RebootWorkspacesResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("WorkSpaces")]
public void RebuildWorkspacesMarshallTest()
{
var request = InstantiateClassGenerator.Execute<RebuildWorkspacesRequest>();
var marshaller = new RebuildWorkspacesRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<RebuildWorkspacesRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("RebuildWorkspaces").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = RebuildWorkspacesResponseUnmarshaller.Instance.Unmarshall(context)
as RebuildWorkspacesResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("WorkSpaces")]
public void TerminateWorkspacesMarshallTest()
{
var request = InstantiateClassGenerator.Execute<TerminateWorkspacesRequest>();
var marshaller = new TerminateWorkspacesRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<TerminateWorkspacesRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("TerminateWorkspaces").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = TerminateWorkspacesResponseUnmarshaller.Instance.Unmarshall(context)
as TerminateWorkspacesResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
}
}
| |
using System;
using System.Data;
using Csla;
using Csla.Data;
using ParentLoad.DataAccess;
using ParentLoad.DataAccess.ERCLevel;
namespace ParentLoad.Business.ERCLevel
{
/// <summary>
/// B01_ContinentColl (editable root list).<br/>
/// This is a generated base class of <see cref="B01_ContinentColl"/> business object.
/// </summary>
/// <remarks>
/// The items of the collection are <see cref="B02_Continent"/> objects.
/// </remarks>
[Serializable]
public partial class B01_ContinentColl : BusinessListBase<B01_ContinentColl, B02_Continent>
{
#region Collection Business Methods
/// <summary>
/// Removes a <see cref="B02_Continent"/> item from the collection.
/// </summary>
/// <param name="continent_ID">The Continent_ID of the item to be removed.</param>
public void Remove(int continent_ID)
{
foreach (var b02_Continent in this)
{
if (b02_Continent.Continent_ID == continent_ID)
{
Remove(b02_Continent);
break;
}
}
}
/// <summary>
/// Determines whether a <see cref="B02_Continent"/> item is in the collection.
/// </summary>
/// <param name="continent_ID">The Continent_ID of the item to search for.</param>
/// <returns><c>true</c> if the B02_Continent is a collection item; otherwise, <c>false</c>.</returns>
public bool Contains(int continent_ID)
{
foreach (var b02_Continent in this)
{
if (b02_Continent.Continent_ID == continent_ID)
{
return true;
}
}
return false;
}
/// <summary>
/// Determines whether a <see cref="B02_Continent"/> item is in the collection's DeletedList.
/// </summary>
/// <param name="continent_ID">The Continent_ID of the item to search for.</param>
/// <returns><c>true</c> if the B02_Continent is a deleted collection item; otherwise, <c>false</c>.</returns>
public bool ContainsDeleted(int continent_ID)
{
foreach (var b02_Continent in DeletedList)
{
if (b02_Continent.Continent_ID == continent_ID)
{
return true;
}
}
return false;
}
#endregion
#region Find Methods
/// <summary>
/// Finds a <see cref="B02_Continent"/> item of the <see cref="B01_ContinentColl"/> collection, based on item key properties.
/// </summary>
/// <param name="continent_ID">The Continent_ID.</param>
/// <returns>A <see cref="B02_Continent"/> object.</returns>
public B02_Continent FindB02_ContinentByParentProperties(int continent_ID)
{
for (var i = 0; i < this.Count; i++)
{
if (this[i].Continent_ID.Equals(continent_ID))
{
return this[i];
}
}
return null;
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="B01_ContinentColl"/> collection.
/// </summary>
/// <returns>A reference to the created <see cref="B01_ContinentColl"/> collection.</returns>
public static B01_ContinentColl NewB01_ContinentColl()
{
return DataPortal.Create<B01_ContinentColl>();
}
/// <summary>
/// Factory method. Loads a <see cref="B01_ContinentColl"/> collection.
/// </summary>
/// <returns>A reference to the fetched <see cref="B01_ContinentColl"/> collection.</returns>
public static B01_ContinentColl GetB01_ContinentColl()
{
return DataPortal.Fetch<B01_ContinentColl>();
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="B01_ContinentColl"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public B01_ContinentColl()
{
// Use factory methods and do not use direct creation.
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = false;
AllowNew = true;
AllowEdit = true;
AllowRemove = true;
RaiseListChangedEvents = rlce;
}
#endregion
#region Data Access
/// <summary>
/// Loads a <see cref="B01_ContinentColl"/> collection from the database.
/// </summary>
protected void DataPortal_Fetch()
{
var args = new DataPortalHookArgs();
OnFetchPre(args);
using (var dalManager = DalFactoryParentLoad.GetManager())
{
var dal = dalManager.GetProvider<IB01_ContinentCollDal>();
var data = dal.Fetch();
LoadCollection(data);
}
OnFetchPost(args);
}
private void LoadCollection(IDataReader data)
{
using (var dr = new SafeDataReader(data))
{
Fetch(dr);
if (this.Count > 0)
this[0].FetchChildren(dr);
}
}
/// <summary>
/// Loads all <see cref="B01_ContinentColl"/> collection items from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = false;
while (dr.Read())
{
Add(B02_Continent.GetB02_Continent(dr));
}
RaiseListChangedEvents = rlce;
}
/// <summary>
/// Updates in the database all changes made to the <see cref="B01_ContinentColl"/> object.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_Update()
{
using (var dalManager = DalFactoryParentLoad.GetManager())
{
base.Child_Update();
}
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
#endregion
}
}
| |
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Web.Mail;
using System.Xml;
namespace WebApplication2
{
/// <summary>
/// Summary description for frmSendMail.
/// </summary>
public partial class frmSendMail : System.Web.UI.Page
{
private string emailAddresses = "";
private static string strURL =
System.Configuration.ConfigurationSettings.AppSettings["local_url"];
private static string strDB =
System.Configuration.ConfigurationSettings.AppSettings["local_db"];
private static string strSMTP =
System.Configuration.ConfigurationSettings.AppSettings["local_smtp"];
public SqlConnection epsDbConn=new SqlConnection(strDB);
protected void Page_Load(object sender, System.EventArgs e)
{
if (Request.Params["MailType"] == "Single")
{
lblSenderName.Text=Request.Params["SenderName"];
lblSenderEmail.Text=Request.Params["SenderEmail"];
lblRecipientName.Text=Request.Params["RecipientName"];
lblRecipientEmail.Text=Request.Params["RecipientEmail"];
}
else if ((Request.Params["MailType"] == "Multiple")
& (Session["CallerSendMail"].ToString() == "frmOrgs"))
{
lblSenderName.Text=Request.Params["SenderName"];
lblSenderEmail.Text=Request.Params["SenderEmail"];
lblRecipientName.Text="All " + Session["OrgType"].ToString();
lblRecipientEmail.Visible=false;
lblEmailR.Visible=false;
}
else if ((Request.Params["MailType"] == "Multiple")
&(Session["CallerSendMail"].ToString() == "frmStaffing"))
{
lblSenderName.Text=Request.Params["SenderName"];
lblSenderEmail.Text=Request.Params["SenderEmail"];
lblRecipientName.Text="All Individuals in " + Session["OrgType"].ToString();
lblRecipientEmail.Visible=false;
lblEmailR.Visible=false;
}
else if ((Request.Params["MailType"] == "Multiple")
&((Session["CallerSendMail"].ToString() == "frmActPeople")
|| (Session["CallerSendMail"].ToString() == "frmActClients")))
{
lblSenderName.Text=Request.Params["SenderName"];
lblSenderEmail.Text=Request.Params["SenderEmail"];
lblRecipientName.Text="All Members: " + Session["ServiceName"].ToString();
lblRecipientEmail.Visible=false;
lblEmailR.Visible=false;
}
}
#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
}
#endregion
protected void btnSend_Click(object sender, System.EventArgs e)
{
SqlCommand cmd=new SqlCommand();
cmd.Connection=this.epsDbConn;
cmd.CommandType=CommandType.StoredProcedure;
if (Request.Params["MailType"] == "Single")
{
MailMessage msg = new MailMessage();
msg.From = Request.Params["SenderEmail"];//"tauheedahmed@hotmail.com";
msg.To = Request.Params["RecipientEmail"];//"tauheedahmed@hotmail.com";
msg.Cc = Request.Params["SenderEmail"];//emailAddresses;
msg.Subject = txtSubject.Text;
msg.Body = txtBody.Text;
SmtpMail.SmtpServer.Insert (0, strSMTP);
SmtpMail.Send(msg);
}
else if ((Request.Params["MailType"] == "Multiple")
&(Request.Params["CallerSendMail"].ToString() == "frmOrgs"))
{
cmd.CommandText="eps_RetrieveEmailOrg";
cmd.Parameters.Add ("@OrgId",SqlDbType.Int);
cmd.Parameters["@OrgId"].Value= Request.Params["OrgId"];
cmd.Parameters.Add ("@OrgType",SqlDbType.NVarChar);
cmd.Parameters["@OrgType"].Value=Session["OrgType"].ToString();
DataSet ds=new DataSet();
SqlDataAdapter da=new SqlDataAdapter (cmd);
da.Fill(ds,"Emails");
foreach (DataRow dr in ds.Tables["Emails"].Rows)
emailAddresses = emailAddresses + dr[0].ToString() + ";";
MailMessage msg = new MailMessage();
msg.From = Request.Params["Sender"];//"tauheedahmed@hotmail.com";
msg.To = Request.Params["Sender"];//"tauheedahmed@hotmail.com";
msg.Cc = emailAddresses;//emailAddresses;
msg.Subject = txtSubject.Text;
msg.Body = txtBody.Text;
SmtpMail.SmtpServer = "mail.spsnet.com";//172.27.10.2";
SmtpMail.Send(msg);
}
else if ((Request.Params["MailType"] == "Multiple")
&(Request.Params["CallerSendMail"].ToString() == "frmStaffing"))
{
cmd.CommandText="eps_RetrieveEmailPeople";
cmd.Parameters.Add ("@OrgIdt",SqlDbType.Int);
cmd.Parameters["@OrgIdt"].Value=Session["OrgIdt"].ToString();
DataSet ds=new DataSet();
SqlDataAdapter da=new SqlDataAdapter (cmd);
da.Fill(ds,"Emails");
foreach (DataRow dr in ds.Tables["Emails"].Rows)
emailAddresses = emailAddresses + dr[0].ToString() + ";";
MailMessage msg = new MailMessage();
msg.From = Request.Params["Sender"];
msg.To = Request.Params["Sender"];
msg.Cc = emailAddresses;
msg.Subject = txtSubject.Text;
msg.Body = txtBody.Text;
SmtpMail.SmtpServer = "mail.spsnet.com";//172.27.10.2";
SmtpMail.Send(msg);
}
else if ((Request.Params["MailType"] == "Multiple")
&(Request.Params["CallerSendMail"].ToString() == "frmActPeople"))
{
cmd.CommandText="eps_RetrieveEmailPeopleAct";
cmd.Parameters.Add ("@ActId",SqlDbType.Int);
cmd.Parameters["@ActId"].Value=Session["ActivationId"].ToString();
DataSet ds=new DataSet();
SqlDataAdapter da=new SqlDataAdapter (cmd);
da.Fill(ds,"Emails");
foreach (DataRow dr in ds.Tables["Emails"].Rows)
emailAddresses = emailAddresses + dr[0].ToString() + ";";
MailMessage msg = new MailMessage();
msg.From = Request.Params["Sender"];
msg.To = Request.Params["Sender"];
msg.Cc = emailAddresses;
msg.Subject = txtSubject.Text;
msg.Body = txtBody.Text;
SmtpMail.SmtpServer = "mail.spsnet.com";//172.27.10.2";
SmtpMail.Send(msg);
}
Response.Redirect (strURL + Session["CallerSendMail"].ToString() + ".aspx?");
}
protected void btnCancel_Click(object sender, System.EventArgs e)
{
Response.Redirect (strURL + Session["CallerSendMail"].ToString() + ".aspx?");
}
protected void btnXML_Click(object sender, System.EventArgs e)
{
if (Request.Params["MailType"] == "MultipleOrg")
{
SqlCommand cmd=new SqlCommand();
cmd.Connection=this.epsDbConn;
cmd.CommandType=CommandType.StoredProcedure;
cmd.CommandText="eps_RetrieveEmailMOrg";
cmd.Parameters.Add ("@OrgId",SqlDbType.Int);
cmd.Parameters["@OrgId"].Value= Request.Params["OrgId"];
DataSet ds=new DataSet();
SqlDataAdapter da=new SqlDataAdapter (cmd);
da.Fill(ds,"Emails");
ds.WriteXml ("C:\\eps_emailExchange.xml");
}
else if (Request.Params["MailType"] == "Single")
{
XmlTextWriter w = new XmlTextWriter("c:\\eps_data.xml", System.Text.Encoding.Default);
w.WriteStartDocument();
w.WriteStartElement ("ROOT");
w.WriteStartElement ("FROM");
w.WriteElementString ("FROM_NAME", lblSenderName.Text);
w.WriteElementString ("FROM_EMAIL", lblSenderEmail.Text);
w.WriteEndElement();
w.WriteStartElement ("TO");
w.WriteElementString ("TO_NAME", lblRecipientName.Text);
w.WriteElementString ("TO_EMAIL", lblRecipientEmail.Text);
w.WriteEndElement();
w.WriteEndDocument();
w.Close();
}
Response.Redirect (strURL + Session["CallerSendMail"].ToString() + ".aspx?");
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
namespace System.DirectoryServices.AccountManagement
{
#if TESTHOOK
public class AccountInfo
#else
internal class AccountInfo
#endif
{
//
// Properties exposed to the public through AuthenticablePrincipal
//
// AccountLockoutTime
private Nullable<DateTime> _accountLockoutTime = null;
private LoadState _accountLockoutTimeLoaded = LoadState.NotSet;
public Nullable<DateTime> AccountLockoutTime
{
get
{
return _owningPrincipal.HandleGet<Nullable<DateTime>>(ref _accountLockoutTime, PropertyNames.AcctInfoAcctLockoutTime, ref _accountLockoutTimeLoaded);
}
}
// LastLogon
private Nullable<DateTime> _lastLogon = null;
private LoadState _lastLogonLoaded = LoadState.NotSet;
public Nullable<DateTime> LastLogon
{
get
{
return _owningPrincipal.HandleGet<Nullable<DateTime>>(ref _lastLogon, PropertyNames.AcctInfoLastLogon, ref _lastLogonLoaded);
}
}
// PermittedWorkstations
private PrincipalValueCollection<string> _permittedWorkstations = new PrincipalValueCollection<string>();
private LoadState _permittedWorkstationsLoaded = LoadState.NotSet;
public PrincipalValueCollection<string> PermittedWorkstations
{
get
{
if (!_owningPrincipal.GetStoreCtxToUse().IsValidProperty(_owningPrincipal, PropertyNames.AcctInfoPermittedWorkstations))
throw new InvalidOperationException(SR.InvalidPropertyForStore);
return _owningPrincipal.HandleGet<PrincipalValueCollection<string>>(ref _permittedWorkstations, PropertyNames.AcctInfoPermittedWorkstations, ref _permittedWorkstationsLoaded);
}
}
// PermittedLogonTimes
// We have to handle the change-tracking for this differently than for the other properties, because
// a byte[] is mutable. After calling the get accessor, the app can change the permittedLogonTimes,
// without needing to ever call the set accessor. Therefore, rather than a simple "changed" flag set
// by the set accessor, we need to track the original value of the property, and flag it as changed
// if current value != original value.
private byte[] _permittedLogonTimes = null;
private byte[] _permittedLogonTimesOriginal = null;
private LoadState _permittedLogonTimesLoaded = LoadState.NotSet;
public byte[] PermittedLogonTimes
{
get
{
return _owningPrincipal.HandleGet<byte[]>(ref _permittedLogonTimes, PropertyNames.AcctInfoPermittedLogonTimes, ref _permittedLogonTimesLoaded);
}
set
{
// We don't use HandleSet<T> here because of the slightly non-standard implementation of the change-tracking
// for this property.
// Check that we actually support this propery in our store
//this.owningPrincipal.CheckSupportedProperty(PropertyNames.AcctInfoPermittedLogonTimes);
if (!_owningPrincipal.GetStoreCtxToUse().IsValidProperty(_owningPrincipal, PropertyNames.AcctInfoPermittedLogonTimes))
throw new InvalidOperationException(SR.InvalidPropertyForStore);
// If we get to this point we know that the value of the property has changed and we should not load it from the store.
// If value is retrived the state is set to loaded. Even if user modifies the reference we will
// not overwrite it because we mark it as loaded.
// If the user sets it before reading it we mark it as changed. When the users accesses it we just return the current
// value. All change tracking to the store is done off of an actual object comparison because users can change the value
// either through property set or modifying the reference returned.
_permittedLogonTimesLoaded = LoadState.Changed;
_permittedLogonTimes = value;
}
}
// AccountExpirationDate
private Nullable<DateTime> _expirationDate = null;
private LoadState _expirationDateChanged = LoadState.NotSet;
public Nullable<DateTime> AccountExpirationDate
{
get
{
return _owningPrincipal.HandleGet<Nullable<DateTime>>(ref _expirationDate, PropertyNames.AcctInfoExpirationDate, ref _expirationDateChanged);
}
set
{
if (!_owningPrincipal.GetStoreCtxToUse().IsValidProperty(_owningPrincipal, PropertyNames.AcctInfoExpirationDate))
throw new InvalidOperationException(SR.InvalidPropertyForStore);
_owningPrincipal.HandleSet<Nullable<DateTime>>(ref _expirationDate, value, ref _expirationDateChanged,
PropertyNames.AcctInfoExpirationDate);
}
}
// SmartcardLogonRequired
private bool _smartcardLogonRequired = false;
private LoadState _smartcardLogonRequiredChanged = LoadState.NotSet;
public bool SmartcardLogonRequired
{
get
{
return _owningPrincipal.HandleGet<bool>(ref _smartcardLogonRequired, PropertyNames.AcctInfoSmartcardRequired, ref _smartcardLogonRequiredChanged);
}
set
{
if (!_owningPrincipal.GetStoreCtxToUse().IsValidProperty(_owningPrincipal, PropertyNames.AcctInfoSmartcardRequired))
throw new InvalidOperationException(SR.InvalidPropertyForStore);
_owningPrincipal.HandleSet<bool>(ref _smartcardLogonRequired, value, ref _smartcardLogonRequiredChanged,
PropertyNames.AcctInfoSmartcardRequired);
}
}
// DelegationPermitted
private bool _delegationPermitted = false;
private LoadState _delegationPermittedChanged = LoadState.NotSet;
public bool DelegationPermitted
{
get
{
return _owningPrincipal.HandleGet<bool>(ref _delegationPermitted, PropertyNames.AcctInfoDelegationPermitted, ref _delegationPermittedChanged);
}
set
{
if (!_owningPrincipal.GetStoreCtxToUse().IsValidProperty(_owningPrincipal, PropertyNames.AcctInfoDelegationPermitted))
throw new InvalidOperationException(SR.InvalidPropertyForStore);
_owningPrincipal.HandleSet<bool>(ref _delegationPermitted, value, ref _delegationPermittedChanged,
PropertyNames.AcctInfoDelegationPermitted);
}
}
// BadLogonCount
private int _badLogonCount = 0;
private LoadState _badLogonCountChanged = LoadState.NotSet;
public int BadLogonCount
{
get
{
return _owningPrincipal.HandleGet<int>(ref _badLogonCount, PropertyNames.AcctInfoBadLogonCount, ref _badLogonCountChanged);
}
}
// HomeDirectory
private string _homeDirectory = null;
private LoadState _homeDirectoryChanged = LoadState.NotSet;
public string HomeDirectory
{
get
{
return _owningPrincipal.HandleGet<string>(ref _homeDirectory, PropertyNames.AcctInfoHomeDirectory, ref _homeDirectoryChanged);
}
set
{
if (!_owningPrincipal.GetStoreCtxToUse().IsValidProperty(_owningPrincipal, PropertyNames.AcctInfoHomeDirectory))
throw new InvalidOperationException(SR.InvalidPropertyForStore);
_owningPrincipal.HandleSet<string>(ref _homeDirectory, value, ref _homeDirectoryChanged,
PropertyNames.AcctInfoHomeDirectory);
}
}
// HomeDrive
private string _homeDrive = null;
private LoadState _homeDriveChanged = LoadState.NotSet;
public string HomeDrive
{
get
{
return _owningPrincipal.HandleGet<string>(ref _homeDrive, PropertyNames.AcctInfoHomeDrive, ref _homeDriveChanged);
}
set
{
if (!_owningPrincipal.GetStoreCtxToUse().IsValidProperty(_owningPrincipal, PropertyNames.AcctInfoHomeDrive))
throw new InvalidOperationException(SR.InvalidPropertyForStore);
_owningPrincipal.HandleSet<string>(ref _homeDrive, value, ref _homeDriveChanged,
PropertyNames.AcctInfoHomeDrive);
}
}
// ScriptPath
private string _scriptPath = null;
private LoadState _scriptPathChanged = LoadState.NotSet;
public string ScriptPath
{
get
{
return _owningPrincipal.HandleGet<string>(ref _scriptPath, PropertyNames.AcctInfoScriptPath, ref _scriptPathChanged);
}
set
{
if (!_owningPrincipal.GetStoreCtxToUse().IsValidProperty(_owningPrincipal, PropertyNames.AcctInfoScriptPath))
throw new InvalidOperationException(SR.InvalidPropertyForStore);
_owningPrincipal.HandleSet<string>(ref _scriptPath, value, ref _scriptPathChanged,
PropertyNames.AcctInfoScriptPath);
}
}
//
// Methods exposed to the public through AuthenticablePrincipal
//
public bool IsAccountLockedOut()
{
if (!_owningPrincipal.unpersisted)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "AccountInfo", "IsAccountLockedOut: sending lockout query");
Debug.Assert(_owningPrincipal.Context != null);
return _owningPrincipal.GetStoreCtxToUse().IsLockedOut(_owningPrincipal);
}
else
{
// A Principal that hasn't even been persisted can't be locked out
return false;
}
}
public void UnlockAccount()
{
if (!_owningPrincipal.unpersisted)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "AccountInfo", "UnlockAccount: sending unlock request");
Debug.Assert(_owningPrincipal.Context != null);
_owningPrincipal.GetStoreCtxToUse().UnlockAccount(_owningPrincipal);
}
// Since a Principal that's not persisted can't have been locked-out,
// there's nothing to do in that case
}
//
// Internal constructor
//
internal AccountInfo(AuthenticablePrincipal principal)
{
_owningPrincipal = principal;
}
//
// Private implementation
//
private AuthenticablePrincipal _owningPrincipal;
//
// Load/Store
//
//
// Loading with query results
//
internal void LoadValueIntoProperty(string propertyName, object value)
{
// GlobalDebug.WriteLineIf(GlobalDebug.Info, "AccountInfo", "LoadValueIntoProperty: name=" + propertyName + " value=" + value.ToString());
switch (propertyName)
{
case (PropertyNames.AcctInfoAcctLockoutTime):
_accountLockoutTime = (Nullable<DateTime>)value;
_accountLockoutTimeLoaded = LoadState.Loaded;
break;
case (PropertyNames.AcctInfoLastLogon):
_lastLogon = (Nullable<DateTime>)value;
_lastLogonLoaded = LoadState.Loaded;
break;
case (PropertyNames.AcctInfoPermittedWorkstations):
_permittedWorkstations.Load((List<string>)value);
_permittedWorkstationsLoaded = LoadState.Loaded;
break;
case (PropertyNames.AcctInfoPermittedLogonTimes):
_permittedLogonTimes = (byte[])value;
_permittedLogonTimesOriginal = (byte[])((byte[])value).Clone();
_permittedLogonTimesLoaded = LoadState.Loaded;
break;
case (PropertyNames.AcctInfoExpirationDate):
_expirationDate = (Nullable<DateTime>)value;
_expirationDateChanged = LoadState.Loaded;
break;
case (PropertyNames.AcctInfoSmartcardRequired):
_smartcardLogonRequired = (bool)value;
_smartcardLogonRequiredChanged = LoadState.Loaded;
break;
case (PropertyNames.AcctInfoDelegationPermitted):
_delegationPermitted = (bool)value;
_delegationPermittedChanged = LoadState.Loaded;
break;
case (PropertyNames.AcctInfoBadLogonCount):
_badLogonCount = (int)value;
_badLogonCountChanged = LoadState.Loaded;
break;
case (PropertyNames.AcctInfoHomeDirectory):
_homeDirectory = (string)value;
_homeDirectoryChanged = LoadState.Loaded;
break;
case (PropertyNames.AcctInfoHomeDrive):
_homeDrive = (string)value;
_homeDriveChanged = LoadState.Loaded;
break;
case (PropertyNames.AcctInfoScriptPath):
_scriptPath = (string)value;
_scriptPathChanged = LoadState.Loaded;
break;
default:
Debug.Fail(string.Format(CultureInfo.CurrentCulture, "AccountInfo.LoadValueIntoProperty: fell off end looking for {0}", propertyName));
break;
}
}
//
// Getting changes to persist (or to build a query from a QBE filter)
//
// Given a property name, returns true if that property has changed since it was loaded, false otherwise.
internal bool GetChangeStatusForProperty(string propertyName)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "AccountInfo", "GetChangeStatusForProperty: name=" + propertyName);
switch (propertyName)
{
case (PropertyNames.AcctInfoPermittedWorkstations):
return _permittedWorkstations.Changed;
case (PropertyNames.AcctInfoPermittedLogonTimes):
// If they're equal, they have _not_ changed
if ((_permittedLogonTimes == null) && (_permittedLogonTimesOriginal == null))
return false;
if ((_permittedLogonTimes == null) || (_permittedLogonTimesOriginal == null))
return true;
return !Utils.AreBytesEqual(_permittedLogonTimes, _permittedLogonTimesOriginal);
case (PropertyNames.AcctInfoExpirationDate):
return _expirationDateChanged == LoadState.Changed;
case (PropertyNames.AcctInfoSmartcardRequired):
return _smartcardLogonRequiredChanged == LoadState.Changed;
case (PropertyNames.AcctInfoDelegationPermitted):
return _delegationPermittedChanged == LoadState.Changed;
case (PropertyNames.AcctInfoHomeDirectory):
return _homeDirectoryChanged == LoadState.Changed;
case (PropertyNames.AcctInfoHomeDrive):
return _homeDriveChanged == LoadState.Changed;
case (PropertyNames.AcctInfoScriptPath):
return _scriptPathChanged == LoadState.Changed;
default:
Debug.Fail(string.Format(CultureInfo.CurrentCulture, "AccountInfo.GetChangeStatusForProperty: fell off end looking for {0}", propertyName));
return false;
}
}
// Given a property name, returns the current value for the property.
internal object GetValueForProperty(string propertyName)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "AccountInfo", "GetValueForProperty: name=" + propertyName);
switch (propertyName)
{
case (PropertyNames.AcctInfoPermittedWorkstations):
return _permittedWorkstations;
case (PropertyNames.AcctInfoPermittedLogonTimes):
return _permittedLogonTimes;
case (PropertyNames.AcctInfoExpirationDate):
return _expirationDate;
case (PropertyNames.AcctInfoSmartcardRequired):
return _smartcardLogonRequired;
case (PropertyNames.AcctInfoDelegationPermitted):
return _delegationPermitted;
case (PropertyNames.AcctInfoHomeDirectory):
return _homeDirectory;
case (PropertyNames.AcctInfoHomeDrive):
return _homeDrive;
case (PropertyNames.AcctInfoScriptPath):
return _scriptPath;
default:
Debug.Fail(string.Format(CultureInfo.CurrentCulture, "AccountInfo.GetValueForProperty: fell off end looking for {0}", propertyName));
return null;
}
}
// Reset all change-tracking status for all properties on the object to "unchanged".
internal void ResetAllChangeStatus()
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "AccountInfo", "ResetAllChangeStatus");
_permittedWorkstations.ResetTracking();
_permittedLogonTimesOriginal = (_permittedLogonTimes != null) ?
(byte[])_permittedLogonTimes.Clone() :
null;
_expirationDateChanged = (_expirationDateChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet;
_smartcardLogonRequiredChanged = (_smartcardLogonRequiredChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet;
_delegationPermittedChanged = (_delegationPermittedChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet;
_homeDirectoryChanged = (_homeDirectoryChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet;
_homeDriveChanged = (_homeDriveChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet;
_scriptPathChanged = (_scriptPathChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet;
}
}
}
| |
using System;
using System.Data;
using System.Configuration;
using System.Collections;
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 System.IO;
using System.Collections.Generic;
using System.Xml;
using packageLib;
using System.Text;
public partial class w3c : System.Web.UI.Page
{
class detailData
{
public string name;
public string detail;
public bool expectPass;
}
// const string root = @"D:\home\packaging\w3c-store\test-cases\";
const string root = @"C:\dev\bondi-1009\testFramework\w3c-tests\test-cases\";
Dictionary<string, detailData> detailMap = new Dictionary<string, detailData>();
protected void Page_Load(object sender, EventArgs e)
{
// string xmlFile = "~/w3c-store/test-suite.xml";
string xmlFile = "~/test-suite.xml";
XmlDocument doc = new XmlDocument();
try
{
doc.Load(Server.MapPath(xmlFile));
XmlNodeList tests = doc.SelectNodes("testsuite/test");
foreach (XmlNode test in tests)
{
if (test.Attributes["src"] != null)
{
string src = test.Attributes["src"].Value;
detailData dData = new detailData();
dData.name = src.Substring("test-cases/".Length);
dData.detail = test.InnerText;
if (test.Attributes["expected"] != null)
{
dData.expectPass = test.Attributes["expected"].Value == "pass";
}
else
dData.expectPass = true;
detailMap[dData.name] = dData;
}
}
}
catch (Exception ex)
{
Response.Write("Failed to load detail XML: " + Server.MapPath(xmlFile) + "<br />" + ex.ToString());
}
}
protected string testAll()
{
try
{
Response.Write("<table>");
Response.Write("<tr><th>result</th><th>detail</th><th>reason</th><th>widget</th></tr>");
DirectoryInfo di = new DirectoryInfo(root);
testFolder(di);
Response.Write("</table>");
}
catch (Exception ex)
{
}
return string.Empty;
}
private void testFolder(DirectoryInfo di)
{
FileInfo[] files = di.GetFiles("*.wgt");
foreach (FileInfo f in files)
{
testFile(f);
}
DirectoryInfo[] subFolders = di.GetDirectories();
foreach (DirectoryInfo sub in subFolders)
{
testFolder(sub);
}
}
private void testFile(FileInfo fi)
{
string locale = localeTxt.Text.Trim();
if (locale.Length == 0)
locale = "en";
string fileKey = fi.FullName.Substring(root.Length).Replace('\\', '/');
detailData dData = detailMap.ContainsKey(fileKey) ? detailMap[fileKey] : null;
string detail = dData != null ? dData.detail : string.Format("<span class=\"infoError\">{0} detail info not found in test-suite.xml</span>", fileKey);
string wUrl = dData != null ? string.Format("check.aspx?w={0}&l={1}", dData.name, locale) : string.Empty;
try
{
packageLib.BondiWidgetClass widget = new BondiWidgetClass();
string msg = widget.Load(fi.FullName, locale, false);
if (msg != null && msg.Length > 0)
throw new Exception(msg);
string nonNullData = getNonNull(widget);
if (dData == null || dData.expectPass)
Response.Write(string.Format("<tr><td class=\"passed\">Valid</td><td>{0}</td><td>{1}</td><td><a href=\"{2}\">{3}</a></td></tr>", detail, nonNullData, wUrl, fileKey));
else
Response.Write(string.Format("<tr><td class=\"failed\">Valid</td><td>{0}</td><td>{1}</td><td><a href=\"{2}\">{3}</a></td></tr>", detail, nonNullData, wUrl, fileKey));
}
catch (Exception ex)
{
if (dData == null || dData.expectPass)
{
if (dData == null)
Response.Write(string.Format("<tr><td class=\"failed\">Invalid</td><td>{0}</td><td>{1}</td><td>{2}</td></tr>", detail, ex.Message, fileKey));
else
Response.Write(string.Format("<tr><td class=\"failed\">Invalid</td><td>{0}</td><td>{1}</td><td><a href=\"{2}\">{3}</a></td></tr>", detail, ex.Message, wUrl, fileKey));
}
else
Response.Write(string.Format("<tr><td class=\"passed\">Invalid</td><td>{0}</td><td>{1}</td><td><a href=\"{2}\">{3}</a></td></tr>", detail, ex.Message, wUrl, fileKey));
}
}
private string fixUp(string inp)
{
if (inp == null)
return "<null>";
else if (inp.Length == 0)
return "<empty>";
else
return string.Format("<pre>'{0}'</pre>", inp);
}
private bool wantDisplay(object inp)
{
return inp != null;
}
private string getNonNull(packageLib.BondiWidgetClass widget)
{
StringBuilder sb = new StringBuilder();
sb.Append("<table>");
if (wantDisplay(widget.Configuration.Id))
sb.AppendFormat("<tr><th>id</th><td>{0}</td></tr>", fixUp(widget.Configuration.Id));
if (wantDisplay(widget.Configuration.Version))
sb.AppendFormat("<tr><th>version</th><td>{0}</td></tr>", fixUp(widget.Configuration.Version));
if ((int)widget.Configuration.Width >= 0)
sb.AppendFormat("<tr><th>width</th><td>{0}</td></tr>", fixUp(widget.Configuration.Width.ToString()));
if ((int)widget.Configuration.Height >= 0)
sb.AppendFormat("<tr><th>height</th><td>{0}</td></tr>", fixUp(widget.Configuration.Height.ToString()));
if (wantDisplay(widget.Configuration.Name))
sb.AppendFormat("<tr><th>name</th><td>{0}</td></tr>", fixUp(widget.Configuration.Name));
if (wantDisplay(widget.Configuration.ShortName))
sb.AppendFormat("<tr><th>short name</th><td>{0}</td></tr>", fixUp(widget.Configuration.ShortName));
if (wantDisplay(widget.Configuration.Description))
sb.AppendFormat("<tr><th>description</th><td>{0}</td></tr>", fixUp(widget.Configuration.Description));
if (wantDisplay(widget.Configuration.AuthorName))
sb.AppendFormat("<tr><th>author name</th><td>{0}</td></tr>", fixUp(widget.Configuration.AuthorName));
if (wantDisplay(widget.Configuration.AuthorEmail))
sb.AppendFormat("<tr><th>author email</th><td>{0}</td></tr>", fixUp(widget.Configuration.AuthorEmail));
if (wantDisplay(widget.Configuration.AuthorURL))
sb.AppendFormat("<tr><th>author url</th><td>{0}</td></tr>", fixUp(widget.Configuration.AuthorURL));
if (wantDisplay(widget.Configuration.LicenseHref))
sb.AppendFormat("<tr><th>license href</th><td>{0}</td></tr>", fixUp(widget.Configuration.LicenseHref));
if (wantDisplay(widget.Configuration.LicenseFile))
sb.AppendFormat("<tr><th>license file</th><td>{0}</td></tr>", fixUp(widget.Configuration.LicenseFile));
if (wantDisplay(widget.Configuration.License))
sb.AppendFormat("<tr><th>license</th><td>{0}</td></tr>", fixUp(widget.Configuration.License));
if (wantDisplay(widget.Configuration.StartFile))
sb.AppendFormat("<tr><th>start file</th><td>{0}</td></tr>", fixUp(widget.Configuration.StartFile));
if (wantDisplay(widget.Configuration.StartFileEncoding))
sb.AppendFormat("<tr><th>start file encoding</th><td>{0}</td></tr>", fixUp(widget.Configuration.StartFileEncoding));
if (wantDisplay(widget.Configuration.StartFileContentType))
sb.AppendFormat("<tr><th>start file content type</th><td>{0}</td></tr>", fixUp(widget.Configuration.StartFileContentType));
if (wantDisplay(widget.Configuration.ViewModes))
sb.AppendFormat("<tr><th>view modes</th><td>{0}</td></tr>", fixUp(widget.Configuration.ViewModes));
if (wantDisplay(widget.Configuration.DistributorCommonName))
sb.AppendFormat("<tr><th>distributor cn</th><td>{0}</td></tr>", fixUp(widget.Configuration.DistributorCommonName));
if (wantDisplay(widget.Configuration.DistributorFingerprint))
sb.AppendFormat("<tr><th>distributor fingerprint</th><td>{0}</td></tr>", fixUp(widget.Configuration.DistributorFingerprint));
if (wantDisplay(widget.Configuration.DistributorRootCommonName))
sb.AppendFormat("<tr><th>distributor root cn</th><td>{0}</td></tr>", fixUp(widget.Configuration.DistributorRootCommonName));
if (wantDisplay(widget.Configuration.DistributorRootFingerprint))
sb.AppendFormat("<tr><th>distributor root fingerprint</th><td>{0}</td></tr>", fixUp(widget.Configuration.DistributorRootFingerprint));
if (wantDisplay(widget.Configuration.AuthorCommonName))
sb.AppendFormat("<tr><th>author cn</th><td>{0}</td></tr>", fixUp(widget.Configuration.AuthorCommonName));
if (wantDisplay(widget.Configuration.AuthorFingerprint))
sb.AppendFormat("<tr><th>author fingerprint</th><td>{0}</td></tr>", fixUp(widget.Configuration.AuthorFingerprint));
if (wantDisplay(widget.Configuration.AuthorRootCommonName))
sb.AppendFormat("<tr><th>author root cn</th><td>{0}</td></tr>", fixUp(widget.Configuration.AuthorRootCommonName));
if (wantDisplay(widget.Configuration.AuthorRootFingerprint))
sb.AppendFormat("<tr><th>author root fingerprint</th><td>{0}</td></tr>", fixUp(widget.Configuration.AuthorRootFingerprint));
for (ushort iconIdx = 0; iconIdx < widget.Configuration.IconCount; iconIdx++)
{
string iconPath;
uint width;
uint height;
widget.Configuration.GetIcon(iconIdx,out iconPath,out width,out height);
sb.AppendFormat("<tr><th>icon</th><td>{0}</td></tr>", fixUp(iconPath));
if ((int)width >= 0)
sb.AppendFormat("<tr><th>icon width</th><td>{0}</td></tr>", width);
if ((int)height >= 0)
sb.AppendFormat("<tr><th>icon height</th><td>{0}</td></tr>", height);
}
for (ushort featureIdx = 0; featureIdx < widget.Configuration.FeatureCount; featureIdx++)
{
packageLib.BondiWidgetFeature feature = widget.Configuration.get_Feature(featureIdx);
sb.AppendFormat("<tr><th>feature</th><td>{0}</td></tr>", fixUp(feature.Name));
if (feature.Required)
sb.AppendFormat("<tr><th>feature required</th><td>yes</td></tr>");
else
sb.AppendFormat("<tr><th>feature required</th><td>no</td></tr>");
for (ushort paramIdx = 0; paramIdx < feature.ParamCount; paramIdx++)
{
packageLib.BondiFeatureParam param = feature.get_Param(paramIdx);
sb.AppendFormat("<tr><th>param name</th><td>{0}</td></tr>", fixUp(param.Name));
sb.AppendFormat("<tr><th>param value</th><td>{0}</td></tr>", fixUp(param.Value));
}
}
for (ushort prefIdx = 0; prefIdx < widget.Configuration.PreferenceCount; prefIdx++)
{
packageLib.BondiWidgetPreference pref = widget.Configuration.get_Preference(prefIdx);
sb.AppendFormat("<tr><th>preference name</th><td>{0}</td></tr>", fixUp(pref.Name));
sb.AppendFormat("<tr><th>preference value</th><td>{0}</td></tr>", fixUp(pref.Value));
if (pref.ReadOnly)
sb.AppendFormat("<tr><th>preference readonly</th><td>true</td></tr>");
else
sb.AppendFormat("<tr><th>preference readonly</th><td>false</td></tr>");
}
sb.Append("</table>");
return sb.ToString();
}
}
| |
/* ====================================================================
Copyright (C) 2004-2008 fyiReporting Software, LLC
Copyright (C) 2011 Peter Gill <peter@majorsilence.com>
This file is part of the fyiReporting RDL project.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
For additional information, email info@fyireporting.com or visit
the website www.fyiReporting.com.
*/
using System;
using System.Drawing;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;
using System.Xml;
using System.Text;
using System.Reflection;
using fyiReporting.RDL;
namespace fyiReporting.RdlDesign
{
/// <summary>
/// DialogListOfStrings: puts up a dialog that lets a user enter a list of strings
/// </summary>
public partial class DialogExprEditor
{
Type[] BASE_TYPES = new Type[]
{
typeof(string),
typeof(double),
typeof(Single),
typeof(decimal),
typeof(DateTime),
typeof(char),
typeof(bool),
typeof(int),
typeof(short),
typeof(long),
typeof(byte),
typeof(UInt16),
typeof(UInt32),
typeof(UInt64)
};
// design draw
private bool _Color; // true if color list should be displayed
internal DialogExprEditor(DesignXmlDraw dxDraw, string expr, XmlNode node) :
this(dxDraw, expr, node, false)
{
}
internal DialogExprEditor(DesignXmlDraw dxDraw, string expr, XmlNode node, bool bColor)
{
_Draw = dxDraw;
_Color = bColor;
//
// Required for Windows Form Designer support
//
InitializeComponent();
if(expr != null)
tbExpr.Text = expr.Replace("\r\n", "\n").Replace("\n", Environment.NewLine);
// Fill out the fields list
string[] fields = null;
// Find the dataregion that contains the item (if any)
for (XmlNode pNode = node; pNode != null; pNode = pNode.ParentNode)
{
if (pNode.Name == "List" ||
pNode.Name == "Table" ||
pNode.Name == "Matrix" ||
pNode.Name == "Chart")
{
string dsname = _Draw.GetDataSetNameValue(pNode);
if (dsname != null) // found it
{
fields = _Draw.GetFields(dsname, true);
}
}
}
BuildTree(fields);
return;
}
void BuildTree(string[] flds)
{
// suppress redraw until tree view is complete
tvOp.BeginUpdate();
//AJM GJL Adding Missing 'User' Menu
// Handle the user
InitUsers();
// Handle the globals
InitGlobals();
// Fields - only when a dataset is specified
InitFields(flds);
// Report parameters
InitReportParameters();
// Handle the functions
InitFunctions();
// Aggregate functions
InitAggrFunctions();
// Operators
InitOperators();
// Colors (if requested)
InitColors();
// Modules and class (if any)
// EBN 30/03/2014
InitReportModulesAndClass();
tvOp.EndUpdate();
}
// Josh: 6:22:10 Added as a uniform method of addind nodes to the TreeView.
void InitTreeNodes(string node, IEnumerable<string> list)
{
TreeNode ndRoot = new TreeNode(node);
tvOp.Nodes.Add(ndRoot);
foreach (string item in list)
{
TreeNode aRoot = new TreeNode(item);
ndRoot.Nodes.Add(aRoot);
}
}
//Josh: 6:22:10 Added to place the start and end shortcut "caps" on the fields.
List<string> ArrayToFormattedList(IEnumerable<string> array, string frontCap, string endCap)
{
List<string> returnList = new List<string>(array);
returnList.ForEach(
delegate(string item)
{
returnList[returnList.IndexOf(item)] =
item.StartsWith("=") ?
string.Format("{0}{1}{2}",
frontCap,
item.Split('!')[1].Replace(".Value", string.Empty),
endCap)
: item;
});
return returnList;
}
// Josh: 6:22:10 Begin Init Methods.
// Methods have been changed to use InitTreeNodes
// and ArrayToFormattedList methods
// Initializes the user functions
void InitUsers()
{
List<string> users = ArrayToFormattedList(StaticLists.UserList, "{!", "}");
InitTreeNodes("User", users);
}
// Initializes the Globals
void InitGlobals()
{
List<string> globals = ArrayToFormattedList(StaticLists.GlobalList, "{@", "}");
InitTreeNodes("Globals", globals);
}
// Initializes the database fields
void InitFields(string[] flds)
{
if (flds != null && flds.Length > 0)
{
List<string> fields = ArrayToFormattedList(flds, "{", "}");
InitTreeNodes("Fields", fields);
}
}
// Initializes the aggregate functions
void InitAggrFunctions()
{
InitTreeNodes("Aggregate Functions", StaticLists.AggrFunctionList);
}
// Initializes the operators
void InitOperators()
{
InitTreeNodes("Operators", StaticLists.OperatorList);
}
// Initializes the colors
void InitColors()
{
if (_Color)
{
InitTreeNodes("Colors", StaticLists.ColorList);
}
}
/// <summary>
/// Populate tree view with the report parameters (if any)
/// </summary>
void InitReportParameters()
{
string[] ps = _Draw.GetReportParameters(true);
if (ps != null && ps.Length != 0)
{
List<string> parameters = ArrayToFormattedList(ps, "{?", "}");
InitTreeNodes("Parameters", parameters);
}
}
/// <summary>
/// Populate tree view with the Module and Class parameters (if any)
/// EBN 30/03/2014
/// </summary>
void InitReportModulesAndClass()
{
string[] ms = _Draw.GetReportModules(false);
string[] qs = _Draw.GetReportClasses(false);
List<string> mc = new List<string>();
if (ms == null) return;
if (qs == null) return;
// Try to load the assembly if not already loaded
foreach (string s in ms)
{
try
{
Assembly a = Assembly.LoadFrom(s);
foreach (string c in qs)
{
Type t = a.GetType(c);
if (t != null)
{
// Class is found in this assembly
BuildMethods(mc, t, c + ".");
}
}
}
catch
{
// Nothing to do, we can not load the assembly...
}
}
if (qs != null && qs.Length != 0)
{
InitTreeNodes("Modules", mc);
}
}
//Done: Look at grouping items, such as Math, Financial, etc
// Josh: 6:21:10 added grouping for common items.
void InitFunctions()
{
List<string> ar = new List<string>();
ar.AddRange(StaticLists.FunctionList);
// Build list of methods in the VBFunctions class
fyiReporting.RDL.FontStyleEnum fsi = FontStyleEnum.Italic; // just want a class from RdlEngine.dll assembly
Assembly a = Assembly.GetAssembly(fsi.GetType());
if (a == null)
return;
Type ft = a.GetType("fyiReporting.RDL.VBFunctions");
BuildMethods(ar, ft, "");
// build list of financial methods in Financial class
ft = a.GetType("fyiReporting.RDL.Financial");
BuildMethods(ar, ft, "Financial.");
a = Assembly.GetAssembly("".GetType());
ft = a.GetType("System.Math");
BuildMethods(ar, ft, "Math.");
ft = a.GetType("System.Convert");
BuildMethods(ar, ft, "Convert.");
ft = a.GetType("System.String");
BuildMethods(ar, ft, "String.");
ar.Sort();
TreeNode ndRoot = new TreeNode("Functions");
tvOp.Nodes.Add(ndRoot);
foreach (TreeNode node in GroupMethods(RemoveDuplicates(ar)))
{
ndRoot.Nodes.Add(node);
}
}
// Josh: 6:22:10 End Init Methods
List<string> RemoveDuplicates(IEnumerable<string> ar)
{
List<string> newAr = new List<string>();
string previous = "";
foreach (string str in ar)
{
if (str != previous)
newAr.Add(str);
previous = str;
}
return newAr;
}
List<TreeNode> GroupMethods(List<string> ar)
{
List<TreeNode> nodeList = new List<TreeNode>();
string group = " ";
foreach (string str in ar)
{
if (!str.StartsWith(group))
{
if (str.Contains("."))
{
if (str.IndexOf("(") > str.IndexOf("."))
{
group = str.Split('.')[0];
TreeNode aRoot = new TreeNode(group);
List<string> groupList = ar.FindAll(
delegate(string methodName)
{
return methodName.StartsWith(group);
}
);
if (groupList != null)
{
foreach (string method in groupList)
{
aRoot.Nodes.Add(new TreeNode(
method.Replace(group, string.Empty)
.Replace(".", string.Empty)));
}
}
nodeList.Add(aRoot);
}
else
{
nodeList.Add(new TreeNode(str));
}
}
else
{
nodeList.Add(new TreeNode(str));
}
}
}
return nodeList;
}
void InitFunctions(TreeNode ndRoot)
{
List<string> ar = new List<string>();
ar.AddRange(StaticLists.FunctionList);
// Build list of methods in the VBFunctions class
fyiReporting.RDL.FontStyleEnum fsi = FontStyleEnum.Italic; // just want a class from RdlEngine.dll assembly
Assembly a = Assembly.GetAssembly(fsi.GetType());
if (a == null)
return;
Type ft = a.GetType("fyiReporting.RDL.VBFunctions");
BuildMethods(ar, ft, "");
// build list of financial methods in Financial class
ft = a.GetType("fyiReporting.RDL.Financial");
BuildMethods(ar, ft, "Financial.");
a = Assembly.GetAssembly("".GetType());
ft = a.GetType("System.Math");
BuildMethods(ar, ft, "Math.");
ft = a.GetType("System.Convert");
BuildMethods(ar, ft, "Convert.");
ft = a.GetType("System.String");
BuildMethods(ar, ft, "String.");
ar.Sort();
string previous = "";
foreach (string item in ar)
{
if (item != previous) // don't add duplicates
{
// Add the node to the tree
TreeNode aRoot = new TreeNode(item);
ndRoot.Nodes.Add(aRoot);
}
previous = item;
}
}
void BuildMethods(List<string> ar, Type ft, string prefix)
{
if (ft == null)
return;
MethodInfo[] mis = ft.GetMethods(BindingFlags.Static | BindingFlags.Public);
foreach (MethodInfo mi in mis)
{
// Add the node to the tree
string name = BuildMethodName(mi);
if (name != null)
ar.Add(prefix + name);
}
}
string BuildMethodName(MethodInfo mi)
{
StringBuilder sb = new StringBuilder(mi.Name);
sb.Append("(");
ParameterInfo[] pis = mi.GetParameters();
bool bFirst = true;
foreach (ParameterInfo pi in pis)
{
if (!IsBaseType(pi.ParameterType))
return null;
if (bFirst)
bFirst = false;
else
sb.Append(", ");
sb.Append(pi.Name);
}
sb.Append(")");
return sb.ToString();
}
// Determines if underlying type is a primitive
bool IsBaseType(Type t)
{
foreach (Type bt in BASE_TYPES)
{
if (bt == t)
return true;
}
return false;
}
public string Expression
{
get { return tbExpr.Text; }
}
private void bCopy_Click(object sender, System.EventArgs e)
{
if (tvOp.SelectedNode == null ||
tvOp.SelectedNode.Parent == null ||
tvOp.SelectedNode.Nodes.Count > 0)
return; // this is the top level nodes (Fields, Parameters, ...)
TreeNode node = tvOp.SelectedNode;
string t = string.Empty;
// Josh: 6:21:10 Changed to add parent node name for grouped nodes (eg: Convert.ToByte(value))
// and not to add it for the root functions (the non grouped).
if (tvOp.Nodes.Contains(node.Parent))
t = node.Text;
else
t = node.Parent.Text + "." + node.Text;
if (tbExpr.Text.Length == 0)
t = "=" + t;
tbExpr.SelectedText = t;
}
}
}
| |
// 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
{
[OuterLoop("Modifies system state")]
[PlatformSpecific(TestPlatforms.OSX)]
public static class X509StoreMutableTests_OSX
{
public static bool PermissionsAllowStoreWrite { get; } = TestPermissions();
private static bool TestPermissions()
{
try
{
AddToStore_Exportable();
}
catch (CryptographicException e)
{
const int errSecWrPerm = -61;
if (e.HResult == errSecWrPerm)
{
return false;
}
}
catch
{
}
return true;
}
[ConditionalFact(nameof(PermissionsAllowStoreWrite))]
public static void PersistKeySet_OSX()
{
using (var store = new X509Store(StoreName.My, StoreLocation.CurrentUser))
using (var cert = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword, X509KeyStorageFlags.DefaultKeySet))
{
store.Open(OpenFlags.ReadWrite);
// Defensive removal.
store.Remove(cert);
Assert.False(IsCertInStore(cert, store), "PtxData certificate was found on pre-condition");
// Opening this as persisted has now added it to login.keychain, aka CU\My.
using (var persistedCert = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword, X509KeyStorageFlags.PersistKeySet))
{
Assert.True(IsCertInStore(cert, store), "PtxData certificate was found upon PersistKeySet import");
}
// And ensure it didn't get removed when the certificate got disposed.
Assert.True(IsCertInStore(cert, store), "PtxData certificate was found after PersistKeySet Dispose");
// Cleanup.
store.Remove(cert);
}
}
[ConditionalFact(nameof(PermissionsAllowStoreWrite))]
public static void AddToStore_NonExportable_OSX()
{
using (var store = new X509Store(StoreName.My, StoreLocation.CurrentUser))
using (var cert = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword, X509KeyStorageFlags.DefaultKeySet))
{
store.Open(OpenFlags.ReadWrite);
int countBefore = GetStoreCertificateCount(store);
// Because this has to export the key from the temporary keychain to the permanent one,
// a non-exportable PFX load will fail.
Assert.ThrowsAny<CryptographicException>(() => store.Add(cert));
int countAfter = GetStoreCertificateCount(store);
Assert.Equal(countBefore, countAfter);
}
}
[ConditionalFact(nameof(PermissionsAllowStoreWrite))]
public static void AddToStore_Exportable()
{
using (var store = new X509Store(StoreName.My, StoreLocation.CurrentUser))
using (var cert = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword, X509KeyStorageFlags.Exportable))
using (var certOnly = new X509Certificate2(cert.RawData))
{
store.Open(OpenFlags.ReadWrite);
// Defensive removal.
store.Remove(certOnly);
Assert.False(IsCertInStore(cert, store), "PtxData certificate was found on pre-condition");
store.Add(cert);
Assert.True(IsCertInStore(certOnly, store), "PtxData certificate was found after add");
// Cleanup
store.Remove(certOnly);
}
}
[ConditionalFact(nameof(PermissionsAllowStoreWrite))]
public static void AddToStoreTwice()
{
using (var store = new X509Store(StoreName.My, StoreLocation.CurrentUser))
using (var cert = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword, X509KeyStorageFlags.Exportable))
using (var certOnly = new X509Certificate2(cert.RawData))
{
store.Open(OpenFlags.ReadWrite);
// Defensive removal.
store.Remove(certOnly);
Assert.False(IsCertInStore(cert, store), "PtxData certificate was found on pre-condition");
store.Add(cert);
Assert.True(IsCertInStore(certOnly, store), "PtxData certificate was found after add");
// No exception for duplicate item.
store.Add(cert);
// Cleanup
store.Remove(certOnly);
}
}
[ConditionalFact(nameof(PermissionsAllowStoreWrite))]
public static void AddPrivateAfterPublic()
{
using (var store = new X509Store(StoreName.My, StoreLocation.CurrentUser))
using (var cert = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword, X509KeyStorageFlags.Exportable))
using (var certOnly = new X509Certificate2(cert.RawData))
{
store.Open(OpenFlags.ReadWrite);
// Defensive removal.
store.Remove(certOnly);
Assert.False(IsCertInStore(cert, store), "PtxData certificate was found on pre-condition");
store.Add(certOnly);
Assert.True(IsCertInStore(certOnly, store), "PtxData certificate was found after add");
Assert.False(StoreHasPrivateKey(store, certOnly), "Store has a private key for PfxData after public-only add");
// Add the private key
store.Add(cert);
Assert.True(StoreHasPrivateKey(store, certOnly), "Store has a private key for PfxData after PFX add");
// Cleanup
store.Remove(certOnly);
}
}
[ConditionalFact(nameof(PermissionsAllowStoreWrite))]
public static void AddPublicAfterPrivate()
{
using (var store = new X509Store(StoreName.My, StoreLocation.CurrentUser))
using (var cert = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword, X509KeyStorageFlags.Exportable))
using (var certOnly = new X509Certificate2(cert.RawData))
{
store.Open(OpenFlags.ReadWrite);
// Defensive removal.
store.Remove(certOnly);
Assert.False(IsCertInStore(cert, store), "PtxData certificate was found on pre-condition");
// Add the private key
store.Add(cert);
Assert.True(IsCertInStore(certOnly, store), "PtxData certificate was found after add");
Assert.True(StoreHasPrivateKey(store, certOnly), "Store has a private key for PfxData after PFX add");
// Add the public key with no private key
store.Add(certOnly);
Assert.True(StoreHasPrivateKey(store, certOnly), "Store has a private key for PfxData after public-only add");
// Cleanup
store.Remove(certOnly);
}
}
[ConditionalFact(nameof(PermissionsAllowStoreWrite))]
public static void VerifyRemove()
{
using (var store = new X509Store(StoreName.My, StoreLocation.CurrentUser))
using (var cert = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword, X509KeyStorageFlags.Exportable))
{
store.Open(OpenFlags.ReadWrite);
// Defensive removal. Sort of circular, but it's the best we can do.
store.Remove(cert);
Assert.False(IsCertInStore(cert, store), "PtxData certificate was found on pre-condition");
store.Add(cert);
Assert.True(IsCertInStore(cert, store), "PtxData certificate was found after add");
store.Remove(cert);
Assert.False(IsCertInStore(cert, store), "PtxData certificate was found after remove");
}
}
[ConditionalFact(nameof(PermissionsAllowStoreWrite))]
public static void RemovePublicDeletesPrivateKey()
{
using (var store = new X509Store(StoreName.My, StoreLocation.CurrentUser))
using (var cert = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword, X509KeyStorageFlags.Exportable))
using (var certOnly = new X509Certificate2(cert.RawData))
{
store.Open(OpenFlags.ReadWrite);
// Defensive removal.
store.Remove(cert);
Assert.False(IsCertInStore(cert, store), "PtxData certificate was found on pre-condition");
// Add the private key
store.Add(cert);
Assert.True(IsCertInStore(cert, store), "PtxData certificate was found after add");
store.Remove(certOnly);
Assert.False(IsCertInStore(cert, store), "PtxData certificate was found after remove");
// Add back the public key only
store.Add(certOnly);
Assert.True(IsCertInStore(cert, store), "PtxData certificate was found after public-only add");
Assert.False(StoreHasPrivateKey(store, cert), "Store has a private key for cert after public-only add");
// Cleanup
store.Remove(certOnly);
}
}
[ConditionalFact(nameof(PermissionsAllowStoreWrite))]
public static void CustomStore_ReadWrite()
{
using (var store = new X509Store("CustomKeyChain_CoreFX", StoreLocation.CurrentUser))
using (new TemporaryX509Store(store))
using (var cert = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword, X509KeyStorageFlags.Exportable))
using (var certOnly = new X509Certificate2(cert.RawData))
{
store.Open(OpenFlags.ReadWrite);
// Defensive removal.
store.Remove(certOnly);
Assert.False(IsCertInStore(cert, store), "PfxData certificate was found on pre-condition");
store.Add(cert);
Assert.True(IsCertInStore(certOnly, store), "PfxData certificate was found after add");
// Cleanup
store.Remove(certOnly);
}
}
[ConditionalFact(nameof(PermissionsAllowStoreWrite))]
public static void CustomStore_ReadOnly()
{
using (var store = new X509Store("CustomKeyChain_CoreFX", StoreLocation.CurrentUser))
using (new TemporaryX509Store(store))
using (var cert = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword, X509KeyStorageFlags.Exportable))
using (var certOnly = new X509Certificate2(cert.RawData))
{
store.Open(OpenFlags.ReadOnly);
Assert.ThrowsAny<CryptographicException>(() => store.Add(certOnly));
}
}
[ConditionalFact(nameof(PermissionsAllowStoreWrite))]
public static void CustomStore_OpenExistingOnly()
{
using (var store = new X509Store("CustomKeyChain_CoreFX_" + Guid.NewGuid().ToString(), StoreLocation.CurrentUser))
using (new TemporaryX509Store(store))
{
Assert.ThrowsAny<CryptographicException>(() => store.Open(OpenFlags.OpenExistingOnly));
}
}
[ConditionalFact(nameof(PermissionsAllowStoreWrite))]
public static void CustomStore_CaseInsensitive()
{
using (var store1 = new X509Store("CustomKeyChain_CoreFX", StoreLocation.CurrentUser))
using (new TemporaryX509Store(store1))
using (var store2 = new X509Store("customkeychain_CoreFX", StoreLocation.CurrentUser))
using (var cert = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword, X509KeyStorageFlags.Exportable))
using (var certOnly = new X509Certificate2(cert.RawData))
{
store1.Open(OpenFlags.ReadWrite);
store2.Open(OpenFlags.ReadOnly);
// Defensive removal.
store1.Remove(certOnly);
Assert.False(IsCertInStore(cert, store1), "PfxData certificate was found on pre-condition");
store1.Add(cert);
Assert.True(IsCertInStore(certOnly, store1), "PfxData certificate was found after add");
Assert.True(IsCertInStore(certOnly, store2), "PfxData certificate was found after add (second store)");
// Cleanup
store1.Remove(certOnly);
}
}
[ConditionalFact(nameof(PermissionsAllowStoreWrite))]
public static void CustomStore_InvalidFileName()
{
using (var store = new X509Store("../corefx", StoreLocation.CurrentUser))
Assert.ThrowsAny<CryptographicException>(() => store.Open(OpenFlags.ReadWrite));
}
private static bool StoreHasPrivateKey(X509Store store, X509Certificate2 forCert)
{
using (ImportedCollection coll = new ImportedCollection(store.Certificates))
{
foreach (X509Certificate2 storeCert in coll.Collection)
{
if (forCert.Equals(storeCert))
{
return storeCert.HasPrivateKey;
}
}
}
Assert.True(false, $"Certificate ({forCert.Subject}) exists in the store");
return false;
}
private static bool IsCertInStore(X509Certificate2 cert, X509Store store)
{
using (ImportedCollection coll = new ImportedCollection(store.Certificates))
{
foreach (X509Certificate2 storeCert in coll.Collection)
{
if (cert.Equals(storeCert))
{
return true;
}
}
}
return false;
}
private static int GetStoreCertificateCount(X509Store store)
{
using (var coll = new ImportedCollection(store.Certificates))
{
return coll.Collection.Count;
}
}
private class TemporaryX509Store : IDisposable
{
private X509Store _store;
public TemporaryX509Store(X509Store store)
{
_store = store;
}
public void Dispose()
{
if (_store.IsOpen)
Interop.AppleCrypto.SecKeychainDelete(_store.StoreHandle, throwOnError: false);
}
}
}
}
| |
//---------------------------------------------------------------------------
//
// <copyright file="DrawingContextWalker.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
// This file was generated, please do not edit it directly.
//
// Please see http://wiki/default.aspx/Microsoft.Projects.Avalon/MilCodeGen.html for more information.
//
//---------------------------------------------------------------------------
using MS.Internal;
using MS.Internal.PresentationCore;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Windows.Threading;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Composition;
using System.Windows.Media.Effects;
using System.Windows.Media.Imaging;
using System.Windows.Media.Media3D;
using System.Diagnostics;
using SR=MS.Internal.PresentationCore.SR;
using SRID=MS.Internal.PresentationCore.SRID;
using System.Security;
using System.Security.Permissions;
namespace System.Windows.Media
{
/// <summary>
/// DrawingContextWalker : The base class for DrawingContext iterators.
/// This is *not* thread safe
/// </summary>
internal abstract partial class DrawingContextWalker : DrawingContext
{
/// <summary>
/// DrawLine -
/// Draws a line with the specified pen.
/// Note that this API does not accept a Brush, as there is no area to fill.
/// </summary>
/// <param name="pen"> The Pen with which to stroke the line. </param>
/// <param name="point0"> The start Point for the line. </param>
/// <param name="point1"> The end Point for the line. </param>
public override void DrawLine(
Pen pen,
Point point0,
Point point1)
{
Debug.Assert(false);
}
/// <summary>
/// DrawLine -
/// Draws a line with the specified pen.
/// Note that this API does not accept a Brush, as there is no area to fill.
/// </summary>
/// <param name="pen"> The Pen with which to stroke the line. </param>
/// <param name="point0"> The start Point for the line. </param>
/// <param name="point0Animations"> Optional AnimationClock for point0. </param>
/// <param name="point1"> The end Point for the line. </param>
/// <param name="point1Animations"> Optional AnimationClock for point1. </param>
public override void DrawLine(
Pen pen,
Point point0,
AnimationClock point0Animations,
Point point1,
AnimationClock point1Animations)
{
Debug.Assert(false);
}
/// <summary>
/// DrawRectangle -
/// Draw a rectangle with the provided Brush and/or Pen.
/// If both the Brush and Pen are null this call is a no-op.
/// </summary>
/// <param name="brush">
/// The Brush with which to fill the rectangle.
/// This is optional, and can be null, in which case no fill is performed.
/// </param>
/// <param name="pen">
/// The Pen with which to stroke the rectangle.
/// This is optional, and can be null, in which case no stroke is performed.
/// </param>
/// <param name="rectangle"> The Rect to fill and/or stroke. </param>
public override void DrawRectangle(
Brush brush,
Pen pen,
Rect rectangle)
{
Debug.Assert(false);
}
/// <summary>
/// DrawRectangle -
/// Draw a rectangle with the provided Brush and/or Pen.
/// If both the Brush and Pen are null this call is a no-op.
/// </summary>
/// <param name="brush">
/// The Brush with which to fill the rectangle.
/// This is optional, and can be null, in which case no fill is performed.
/// </param>
/// <param name="pen">
/// The Pen with which to stroke the rectangle.
/// This is optional, and can be null, in which case no stroke is performed.
/// </param>
/// <param name="rectangle"> The Rect to fill and/or stroke. </param>
/// <param name="rectangleAnimations"> Optional AnimationClock for rectangle. </param>
public override void DrawRectangle(
Brush brush,
Pen pen,
Rect rectangle,
AnimationClock rectangleAnimations)
{
Debug.Assert(false);
}
/// <summary>
/// DrawRoundedRectangle -
/// Draw a rounded rectangle with the provided Brush and/or Pen.
/// If both the Brush and Pen are null this call is a no-op.
/// </summary>
/// <param name="brush">
/// The Brush with which to fill the rectangle.
/// This is optional, and can be null, in which case no fill is performed.
/// </param>
/// <param name="pen">
/// The Pen with which to stroke the rectangle.
/// This is optional, and can be null, in which case no stroke is performed.
/// </param>
/// <param name="rectangle"> The Rect to fill and/or stroke. </param>
/// <param name="radiusX">
/// The radius in the X dimension of the rounded corners of this
/// rounded Rect. This value will be clamped to the range [0..rectangle.Width/2]
/// </param>
/// <param name="radiusY">
/// The radius in the Y dimension of the rounded corners of this
/// rounded Rect. This value will be clamped to the range [0..rectangle.Height/2].
/// </param>
public override void DrawRoundedRectangle(
Brush brush,
Pen pen,
Rect rectangle,
Double radiusX,
Double radiusY)
{
Debug.Assert(false);
}
/// <summary>
/// DrawRoundedRectangle -
/// Draw a rounded rectangle with the provided Brush and/or Pen.
/// If both the Brush and Pen are null this call is a no-op.
/// </summary>
/// <param name="brush">
/// The Brush with which to fill the rectangle.
/// This is optional, and can be null, in which case no fill is performed.
/// </param>
/// <param name="pen">
/// The Pen with which to stroke the rectangle.
/// This is optional, and can be null, in which case no stroke is performed.
/// </param>
/// <param name="rectangle"> The Rect to fill and/or stroke. </param>
/// <param name="rectangleAnimations"> Optional AnimationClock for rectangle. </param>
/// <param name="radiusX">
/// The radius in the X dimension of the rounded corners of this
/// rounded Rect. This value will be clamped to the range [0..rectangle.Width/2]
/// </param>
/// <param name="radiusXAnimations"> Optional AnimationClock for radiusX. </param>
/// <param name="radiusY">
/// The radius in the Y dimension of the rounded corners of this
/// rounded Rect. This value will be clamped to the range [0..rectangle.Height/2].
/// </param>
/// <param name="radiusYAnimations"> Optional AnimationClock for radiusY. </param>
public override void DrawRoundedRectangle(
Brush brush,
Pen pen,
Rect rectangle,
AnimationClock rectangleAnimations,
Double radiusX,
AnimationClock radiusXAnimations,
Double radiusY,
AnimationClock radiusYAnimations)
{
Debug.Assert(false);
}
/// <summary>
/// DrawEllipse -
/// Draw an ellipse with the provided Brush and/or Pen.
/// If both the Brush and Pen are null this call is a no-op.
/// </summary>
/// <param name="brush">
/// The Brush with which to fill the ellipse.
/// This is optional, and can be null, in which case no fill is performed.
/// </param>
/// <param name="pen">
/// The Pen with which to stroke the ellipse.
/// This is optional, and can be null, in which case no stroke is performed.
/// </param>
/// <param name="center">
/// The center of the ellipse to fill and/or stroke.
/// </param>
/// <param name="radiusX">
/// The radius in the X dimension of the ellipse.
/// The absolute value of the radius provided will be used.
/// </param>
/// <param name="radiusY">
/// The radius in the Y dimension of the ellipse.
/// The absolute value of the radius provided will be used.
/// </param>
public override void DrawEllipse(
Brush brush,
Pen pen,
Point center,
Double radiusX,
Double radiusY)
{
Debug.Assert(false);
}
/// <summary>
/// DrawEllipse -
/// Draw an ellipse with the provided Brush and/or Pen.
/// If both the Brush and Pen are null this call is a no-op.
/// </summary>
/// <param name="brush">
/// The Brush with which to fill the ellipse.
/// This is optional, and can be null, in which case no fill is performed.
/// </param>
/// <param name="pen">
/// The Pen with which to stroke the ellipse.
/// This is optional, and can be null, in which case no stroke is performed.
/// </param>
/// <param name="center">
/// The center of the ellipse to fill and/or stroke.
/// </param>
/// <param name="centerAnimations"> Optional AnimationClock for center. </param>
/// <param name="radiusX">
/// The radius in the X dimension of the ellipse.
/// The absolute value of the radius provided will be used.
/// </param>
/// <param name="radiusXAnimations"> Optional AnimationClock for radiusX. </param>
/// <param name="radiusY">
/// The radius in the Y dimension of the ellipse.
/// The absolute value of the radius provided will be used.
/// </param>
/// <param name="radiusYAnimations"> Optional AnimationClock for radiusY. </param>
public override void DrawEllipse(
Brush brush,
Pen pen,
Point center,
AnimationClock centerAnimations,
Double radiusX,
AnimationClock radiusXAnimations,
Double radiusY,
AnimationClock radiusYAnimations)
{
Debug.Assert(false);
}
/// <summary>
/// DrawGeometry -
/// Draw a Geometry with the provided Brush and/or Pen.
/// If both the Brush and Pen are null this call is a no-op.
/// </summary>
/// <param name="brush">
/// The Brush with which to fill the Geometry.
/// This is optional, and can be null, in which case no fill is performed.
/// </param>
/// <param name="pen">
/// The Pen with which to stroke the Geometry.
/// This is optional, and can be null, in which case no stroke is performed.
/// </param>
/// <param name="geometry"> The Geometry to fill and/or stroke. </param>
public override void DrawGeometry(
Brush brush,
Pen pen,
Geometry geometry)
{
Debug.Assert(false);
}
/// <summary>
/// DrawImage -
/// Draw an Image into the region specified by the Rect.
/// The Image will potentially be stretched and distorted to fit the Rect.
/// For more fine grained control, consider filling a Rect with an ImageBrush via
/// DrawRectangle.
/// </summary>
/// <param name="imageSource"> The ImageSource to draw. </param>
/// <param name="rectangle">
/// The Rect into which the ImageSource will be fit.
/// </param>
public override void DrawImage(
ImageSource imageSource,
Rect rectangle)
{
Debug.Assert(false);
}
/// <summary>
/// DrawImage -
/// Draw an Image into the region specified by the Rect.
/// The Image will potentially be stretched and distorted to fit the Rect.
/// For more fine grained control, consider filling a Rect with an ImageBrush via
/// DrawRectangle.
/// </summary>
/// <param name="imageSource"> The ImageSource to draw. </param>
/// <param name="rectangle">
/// The Rect into which the ImageSource will be fit.
/// </param>
/// <param name="rectangleAnimations"> Optional AnimationClock for rectangle. </param>
public override void DrawImage(
ImageSource imageSource,
Rect rectangle,
AnimationClock rectangleAnimations)
{
Debug.Assert(false);
}
/// <summary>
/// DrawGlyphRun -
/// Draw a GlyphRun
/// </summary>
/// <param name="foregroundBrush">
/// Foreground brush to draw the GlyphRun with.
/// </param>
/// <param name="glyphRun"> The GlyphRun to draw. </param>
public override void DrawGlyphRun(
Brush foregroundBrush,
GlyphRun glyphRun)
{
Debug.Assert(false);
}
/// <summary>
/// DrawDrawing -
/// Draw a Drawing by appending a sub-Drawing to the current Drawing.
/// </summary>
/// <param name="drawing"> The drawing to draw. </param>
public override void DrawDrawing(
Drawing drawing)
{
if (drawing != null)
{
drawing.WalkCurrentValue(this);
}
}
/// <summary>
/// DrawVideo -
/// Draw a Video into the region specified by the Rect.
/// The Video will potentially be stretched and distorted to fit the Rect.
/// For more fine grained control, consider filling a Rect with an VideoBrush via
/// DrawRectangle.
/// </summary>
/// <param name="player"> The MediaPlayer to draw. </param>
/// <param name="rectangle"> The Rect into which the media will be fit. </param>
public override void DrawVideo(
MediaPlayer player,
Rect rectangle)
{
Debug.Assert(false);
}
/// <summary>
/// DrawVideo -
/// Draw a Video into the region specified by the Rect.
/// The Video will potentially be stretched and distorted to fit the Rect.
/// For more fine grained control, consider filling a Rect with an VideoBrush via
/// DrawRectangle.
/// </summary>
/// <param name="player"> The MediaPlayer to draw. </param>
/// <param name="rectangle"> The Rect into which the media will be fit. </param>
/// <param name="rectangleAnimations"> Optional AnimationClock for rectangle. </param>
public override void DrawVideo(
MediaPlayer player,
Rect rectangle,
AnimationClock rectangleAnimations)
{
Debug.Assert(false);
}
/// <summary>
/// PushClip -
/// Push a clip region, which will apply to all drawing primitives until the
/// corresponding Pop call.
/// </summary>
/// <param name="clipGeometry"> The Geometry to which we will clip. </param>
public override void PushClip(
Geometry clipGeometry)
{
Debug.Assert(false);
}
/// <summary>
/// PushOpacityMask -
/// Push an opacity mask which will blend the composite of all drawing primitives added
/// until the corresponding Pop call.
/// </summary>
/// <param name="opacityMask"> The opacity mask </param>
public override void PushOpacityMask(
Brush opacityMask)
{
Debug.Assert(false);
}
/// <summary>
/// PushOpacity -
/// Push an opacity which will blend the composite of all drawing primitives added
/// until the corresponding Pop call.
/// </summary>
/// <param name="opacity">
/// The opacity with which to blend - 0 is transparent, 1 is opaque.
/// </param>
public override void PushOpacity(
Double opacity)
{
Debug.Assert(false);
}
/// <summary>
/// PushOpacity -
/// Push an opacity which will blend the composite of all drawing primitives added
/// until the corresponding Pop call.
/// </summary>
/// <param name="opacity">
/// The opacity with which to blend - 0 is transparent, 1 is opaque.
/// </param>
/// <param name="opacityAnimations"> Optional AnimationClock for opacity. </param>
public override void PushOpacity(
Double opacity,
AnimationClock opacityAnimations)
{
Debug.Assert(false);
}
/// <summary>
/// PushTransform -
/// Push a Transform which will apply to all drawing operations until the corresponding
/// Pop.
/// </summary>
/// <param name="transform"> The Transform to push. </param>
public override void PushTransform(
Transform transform)
{
Debug.Assert(false);
}
/// <summary>
/// PushGuidelineSet -
/// Push a set of guidelines which will apply to all drawing operations until the
/// corresponding Pop.
/// </summary>
/// <param name="guidelines"> The GuidelineSet to push. </param>
public override void PushGuidelineSet(
GuidelineSet guidelines)
{
Debug.Assert(false);
}
/// <summary>
/// PushGuidelineY1 -
/// Explicitly push one horizontal guideline.
/// </summary>
/// <param name="coordinate"> The coordinate of leading guideline. </param>
internal override void PushGuidelineY1(
Double coordinate)
{
Debug.Assert(false);
}
/// <summary>
/// PushGuidelineY2 -
/// Explicitly push a pair of horizontal guidelines.
/// </summary>
/// <param name="leadingCoordinate">
/// The coordinate of leading guideline.
/// </param>
/// <param name="offsetToDrivenCoordinate">
/// The offset from leading guideline to driven guideline.
/// </param>
internal override void PushGuidelineY2(
Double leadingCoordinate,
Double offsetToDrivenCoordinate)
{
Debug.Assert(false);
}
/// <summary>
/// PushEffect -
/// Push a BitmapEffect which will apply to all drawing operations until the
/// corresponding Pop.
/// </summary>
/// <param name="effect"> The BitmapEffect to push. </param>
/// <param name="effectInput"> The BitmapEffectInput. </param>
[Obsolete(MS.Internal.Media.VisualTreeUtils.BitmapEffectObsoleteMessage)]
public override void PushEffect(
BitmapEffect effect,
BitmapEffectInput effectInput)
{
Debug.Assert(false);
}
/// <summary>
/// Pop
/// </summary>
public override void Pop(
)
{
Debug.Assert(false);
}
}
}
| |
/*
* UltraCart Rest API V2
*
* UltraCart REST API Version 2
*
* OpenAPI spec version: 2.0.0
* Contact: support@ultracart.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using SwaggerDateConverter = com.ultracart.admin.v2.Client.SwaggerDateConverter;
namespace com.ultracart.admin.v2.Model
{
/// <summary>
/// EmailWebhookEditorValuesResponse
/// </summary>
[DataContract]
public partial class EmailWebhookEditorValuesResponse : IEquatable<EmailWebhookEditorValuesResponse>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="EmailWebhookEditorValuesResponse" /> class.
/// </summary>
/// <param name="availableExpansions">availableExpansions.</param>
/// <param name="availableTokens">availableTokens.</param>
/// <param name="error">error.</param>
/// <param name="metadata">metadata.</param>
/// <param name="restObjectType">restObjectType.</param>
/// <param name="success">Indicates if API call was successful.</param>
/// <param name="warning">warning.</param>
public EmailWebhookEditorValuesResponse(List<string> availableExpansions = default(List<string>), List<string> availableTokens = default(List<string>), Error error = default(Error), ResponseMetadata metadata = default(ResponseMetadata), string restObjectType = default(string), bool? success = default(bool?), Warning warning = default(Warning))
{
this.AvailableExpansions = availableExpansions;
this.AvailableTokens = availableTokens;
this.Error = error;
this.Metadata = metadata;
this.RestObjectType = restObjectType;
this.Success = success;
this.Warning = warning;
}
/// <summary>
/// Gets or Sets AvailableExpansions
/// </summary>
[DataMember(Name="available_expansions", EmitDefaultValue=false)]
public List<string> AvailableExpansions { get; set; }
/// <summary>
/// Gets or Sets AvailableTokens
/// </summary>
[DataMember(Name="available_tokens", EmitDefaultValue=false)]
public List<string> AvailableTokens { get; set; }
/// <summary>
/// Gets or Sets Error
/// </summary>
[DataMember(Name="error", EmitDefaultValue=false)]
public Error Error { get; set; }
/// <summary>
/// Gets or Sets Metadata
/// </summary>
[DataMember(Name="metadata", EmitDefaultValue=false)]
public ResponseMetadata Metadata { get; set; }
/// <summary>
/// Gets or Sets RestObjectType
/// </summary>
[DataMember(Name="rest_object_type", EmitDefaultValue=false)]
public string RestObjectType { get; set; }
/// <summary>
/// Indicates if API call was successful
/// </summary>
/// <value>Indicates if API call was successful</value>
[DataMember(Name="success", EmitDefaultValue=false)]
public bool? Success { get; set; }
/// <summary>
/// Gets or Sets Warning
/// </summary>
[DataMember(Name="warning", EmitDefaultValue=false)]
public Warning Warning { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class EmailWebhookEditorValuesResponse {\n");
sb.Append(" AvailableExpansions: ").Append(AvailableExpansions).Append("\n");
sb.Append(" AvailableTokens: ").Append(AvailableTokens).Append("\n");
sb.Append(" Error: ").Append(Error).Append("\n");
sb.Append(" Metadata: ").Append(Metadata).Append("\n");
sb.Append(" RestObjectType: ").Append(RestObjectType).Append("\n");
sb.Append(" Success: ").Append(Success).Append("\n");
sb.Append(" Warning: ").Append(Warning).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public virtual string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as EmailWebhookEditorValuesResponse);
}
/// <summary>
/// Returns true if EmailWebhookEditorValuesResponse instances are equal
/// </summary>
/// <param name="input">Instance of EmailWebhookEditorValuesResponse to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(EmailWebhookEditorValuesResponse input)
{
if (input == null)
return false;
return
(
this.AvailableExpansions == input.AvailableExpansions ||
this.AvailableExpansions != null &&
this.AvailableExpansions.SequenceEqual(input.AvailableExpansions)
) &&
(
this.AvailableTokens == input.AvailableTokens ||
this.AvailableTokens != null &&
this.AvailableTokens.SequenceEqual(input.AvailableTokens)
) &&
(
this.Error == input.Error ||
(this.Error != null &&
this.Error.Equals(input.Error))
) &&
(
this.Metadata == input.Metadata ||
(this.Metadata != null &&
this.Metadata.Equals(input.Metadata))
) &&
(
this.RestObjectType == input.RestObjectType ||
(this.RestObjectType != null &&
this.RestObjectType.Equals(input.RestObjectType))
) &&
(
this.Success == input.Success ||
(this.Success != null &&
this.Success.Equals(input.Success))
) &&
(
this.Warning == input.Warning ||
(this.Warning != null &&
this.Warning.Equals(input.Warning))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.AvailableExpansions != null)
hashCode = hashCode * 59 + this.AvailableExpansions.GetHashCode();
if (this.AvailableTokens != null)
hashCode = hashCode * 59 + this.AvailableTokens.GetHashCode();
if (this.Error != null)
hashCode = hashCode * 59 + this.Error.GetHashCode();
if (this.Metadata != null)
hashCode = hashCode * 59 + this.Metadata.GetHashCode();
if (this.RestObjectType != null)
hashCode = hashCode * 59 + this.RestObjectType.GetHashCode();
if (this.Success != null)
hashCode = hashCode * 59 + this.Success.GetHashCode();
if (this.Warning != null)
hashCode = hashCode * 59 + this.Warning.GetHashCode();
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
/*
* UUnit system from UnityCommunity
* Heavily modified
* 0.4 release by pboechat
* http://wiki.unity3d.com/index.php?title=UUnit
* http://creativecommons.org/licenses/by-sa/3.0/
*/
using System;
using System.Collections.Generic;
namespace PlayFab.UUnit
{
public enum UUnitActiveState
{
PENDING, // Not started
ACTIVE, // Currently testing
READY, // An answer is sent by the http thread, but the main thread hasn't finalized the test yet
COMPLETE, // Test is finalized and recorded
ABORTED // todo
};
public class UUnitTestContext
{
public const float DefaultFloatPrecision = 0.0001f;
public const double DefaultDoublePrecision = 0.000001;
public UUnitActiveState ActiveState;
public UUnitFinishState FinishState;
public Action<UUnitTestContext> TestDelegate;
public UUnitTestCase TestInstance;
public DateTime StartTime;
public DateTime EndTime;
public string TestResultMsg;
public string Name;
public int retryCount;
public UUnitTestContext(UUnitTestCase testInstance, Action<UUnitTestContext> testDelegate, string name)
{
TestInstance = testInstance;
TestDelegate = testDelegate;
ActiveState = UUnitActiveState.PENDING;
Name = name;
}
public void AttemptRetry()
{
ActiveState = UUnitActiveState.PENDING;
FinishState = UUnitFinishState.PENDING;
TestResultMsg = null;
retryCount++;
}
public void EndTest(UUnitFinishState finishState, string resultMsg)
{
if (FinishState == UUnitFinishState.PENDING)
{
EndTime = DateTime.UtcNow;
TestResultMsg = resultMsg;
FinishState = finishState;
ActiveState = UUnitActiveState.READY;
return;
}
// Otherwise describe the additional end-state and fail the test
TestResultMsg += "\n" + FinishState + "->" + finishState + " - Cannot declare test finished twice.";
if (finishState == UUnitFinishState.FAILED && FinishState == UUnitFinishState.FAILED)
TestResultMsg += "\nSecond message: " + resultMsg;
FinishState = UUnitFinishState.FAILED;
}
public void Skip(string message = "")
{
EndTime = DateTime.UtcNow;
EndTest(UUnitFinishState.SKIPPED, message);
throw new UUnitSkipException(message);
}
public void Fail(string message = null)
{
if (string.IsNullOrEmpty(message))
message = "fail";
EndTest(UUnitFinishState.FAILED, message);
throw new UUnitAssertException(message);
}
public void True(bool boolean, string message = null)
{
if (boolean)
return;
if (string.IsNullOrEmpty(message))
message = "Expected: true, Actual: false";
Fail(message);
}
public void False(bool boolean, string message = null)
{
if (!boolean)
return;
if (string.IsNullOrEmpty(message))
message = "Expected: false, Actual: true";
Fail(message);
}
public void NotNull(object something, string message = null)
{
if (something != null)
return; // Success
if (string.IsNullOrEmpty(message))
message = "Null object";
Fail(message);
}
public void IsNull(object something, string message = null)
{
if (something == null)
return;
if (string.IsNullOrEmpty(message))
message = "Not null object";
Fail(message);
}
public void StringEquals(string wanted, string got, string message = null)
{
if (wanted == got)
return;
if (string.IsNullOrEmpty(message))
message = "Expected: " + wanted + ", Actual: " + got;
Fail(message);
}
public void SbyteEquals(sbyte? wanted, sbyte? got, string message = null)
{
if (wanted == got)
return;
if (string.IsNullOrEmpty(message))
message = "Expected: " + wanted + ", Actual: " + got;
Fail(message);
}
public void ByteEquals(byte? wanted, byte? got, string message = null)
{
if (wanted == got)
return;
if (string.IsNullOrEmpty(message))
message = "Expected: " + wanted + ", Actual: " + got;
Fail(message);
}
public void ShortEquals(short? wanted, short? got, string message = null)
{
if (wanted == got)
return;
if (string.IsNullOrEmpty(message))
message = "Expected: " + wanted + ", Actual: " + got;
Fail(message);
}
public void UshortEquals(ushort? wanted, ushort? got, string message = null)
{
if (wanted == got)
return;
if (string.IsNullOrEmpty(message))
message = "Expected: " + wanted + ", Actual: " + got;
Fail(message);
}
public void IntEquals(int? wanted, int? got, string message = null)
{
if (wanted == got)
return;
if (string.IsNullOrEmpty(message))
message = "Expected: " + wanted + ", Actual: " + got;
Fail(message);
}
public void UintEquals(uint? wanted, uint? got, string message = null)
{
if (wanted == got)
return;
if (string.IsNullOrEmpty(message))
message = "Expected: " + wanted + ", Actual: " + got;
Fail(message);
}
public void LongEquals(long? wanted, long? got, string message = null)
{
if (wanted == got)
return;
if (string.IsNullOrEmpty(message))
message = "Expected: " + wanted + ", Actual: " + got;
Fail(message);
}
public void ULongEquals(ulong? wanted, ulong? got, string message = null)
{
if (wanted == got)
return;
if (string.IsNullOrEmpty(message))
message = "Expected: " + wanted + ", Actual: " + got;
Fail(message);
}
public void FloatEquals(float? wanted, float? got, float precision = DefaultFloatPrecision, string message = null)
{
if (wanted == null && got == null)
return;
if (wanted != null && got != null && Math.Abs(wanted.Value - got.Value) < precision)
return;
if (string.IsNullOrEmpty(message))
message = "Expected: " + wanted + ", Actual: " + got;
Fail(message);
}
public void DoubleEquals(double? wanted, double? got, double precision = DefaultDoublePrecision, string message = null)
{
if (wanted == null && got == null)
return;
if (wanted != null && got != null && Math.Abs(wanted.Value - got.Value) < precision)
return;
if (string.IsNullOrEmpty(message))
message = "Expected: " + wanted + ", Actual: " + got;
Fail(message);
}
public void DateTimeEquals(DateTime? wanted, DateTime? got, TimeSpan precision, string message = null)
{
if (wanted == null && got == null)
return;
if (wanted != null && got != null
&& wanted + precision > got
&& got + precision > wanted)
return;
if (string.IsNullOrEmpty(message))
message = "Expected: " + wanted + ", Actual: " + got;
Fail(message);
}
public void ObjEquals(object wanted, object got, string message = null)
{
if (wanted == null && got == null)
return;
if (wanted != null && got != null && wanted.Equals(got))
return;
if (string.IsNullOrEmpty(message))
message = "Expected: " + wanted + ", Actual: " + got;
Fail(message);
}
public void SequenceEquals<T>(IEnumerable<T> wanted, IEnumerable<T> got, string message = null)
{
var wEnum = wanted.GetEnumerator();
var gEnum = got.GetEnumerator();
bool wNext, gNext;
var count = 0;
while (true)
{
wNext = wEnum.MoveNext();
gNext = gEnum.MoveNext();
if (wNext != gNext)
Fail(message);
if (!wNext)
break;
count++;
ObjEquals(wEnum.Current, gEnum.Current, "Element at " + count + ": " + message);
}
}
}
}
| |
#region Copyright notice and license
// Copyright 2015, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Grpc.Core.Internal;
using Grpc.Core.Utils;
namespace Grpc.Core.Internal
{
/// <summary>
/// Manages server side native call lifecycle.
/// </summary>
internal class AsyncCallServer<TRequest, TResponse> : AsyncCallBase<TResponse, TRequest>
{
readonly TaskCompletionSource<object> finishedServersideTcs = new TaskCompletionSource<object>();
readonly CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
readonly GrpcEnvironment environment;
readonly Server server;
public AsyncCallServer(Func<TResponse, byte[]> serializer, Func<byte[], TRequest> deserializer, GrpcEnvironment environment, Server server) : base(serializer, deserializer)
{
this.environment = Preconditions.CheckNotNull(environment);
this.server = Preconditions.CheckNotNull(server);
}
public void Initialize(CallSafeHandle call)
{
call.SetCompletionRegistry(environment.CompletionRegistry);
server.AddCallReference(this);
InitializeInternal(call);
}
/// <summary>
/// Starts a server side call.
/// </summary>
public Task ServerSideCallAsync()
{
lock (myLock)
{
Preconditions.CheckNotNull(call);
started = true;
call.StartServerSide(HandleFinishedServerside);
return finishedServersideTcs.Task;
}
}
/// <summary>
/// Sends a streaming response. Only one pending send action is allowed at any given time.
/// completionDelegate is called when the operation finishes.
/// </summary>
public void StartSendMessage(TResponse msg, WriteFlags writeFlags, AsyncCompletionDelegate<object> completionDelegate)
{
StartSendMessageInternal(msg, writeFlags, completionDelegate);
}
/// <summary>
/// Receives a streaming request. Only one pending read action is allowed at any given time.
/// completionDelegate is called when the operation finishes.
/// </summary>
public void StartReadMessage(AsyncCompletionDelegate<TRequest> completionDelegate)
{
StartReadMessageInternal(completionDelegate);
}
/// <summary>
/// Initiates sending a initial metadata.
/// Even though C-core allows sending metadata in parallel to sending messages, we will treat sending metadata as a send message operation
/// to make things simpler.
/// completionDelegate is invoked upon completion.
/// </summary>
public void StartSendInitialMetadata(Metadata headers, AsyncCompletionDelegate<object> completionDelegate)
{
lock (myLock)
{
Preconditions.CheckNotNull(headers, "metadata");
Preconditions.CheckNotNull(completionDelegate, "Completion delegate cannot be null");
Preconditions.CheckState(!initialMetadataSent, "Response headers can only be sent once per call.");
Preconditions.CheckState(streamingWritesCounter == 0, "Response headers can only be sent before the first write starts.");
CheckSendingAllowed();
Preconditions.CheckNotNull(completionDelegate, "Completion delegate cannot be null");
using (var metadataArray = MetadataArraySafeHandle.Create(headers))
{
call.StartSendInitialMetadata(HandleSendFinished, metadataArray);
}
this.initialMetadataSent = true;
sendCompletionDelegate = completionDelegate;
}
}
/// <summary>
/// Sends call result status, also indicating server is done with streaming responses.
/// Only one pending send action is allowed at any given time.
/// completionDelegate is called when the operation finishes.
/// </summary>
public void StartSendStatusFromServer(Status status, Metadata trailers, AsyncCompletionDelegate<object> completionDelegate)
{
lock (myLock)
{
Preconditions.CheckNotNull(completionDelegate, "Completion delegate cannot be null");
CheckSendingAllowed();
using (var metadataArray = MetadataArraySafeHandle.Create(trailers))
{
call.StartSendStatusFromServer(HandleHalfclosed, status, metadataArray, !initialMetadataSent);
}
halfcloseRequested = true;
readingDone = true;
sendCompletionDelegate = completionDelegate;
}
}
/// <summary>
/// Gets cancellation token that gets cancelled once close completion
/// is received and the cancelled flag is set.
/// </summary>
public CancellationToken CancellationToken
{
get
{
return cancellationTokenSource.Token;
}
}
public string Peer
{
get
{
return call.GetPeer();
}
}
protected override void CheckReadingAllowed()
{
base.CheckReadingAllowed();
Preconditions.CheckArgument(!cancelRequested);
}
protected override void OnAfterReleaseResources()
{
server.RemoveCallReference(this);
}
/// <summary>
/// Handles the server side close completion.
/// </summary>
private void HandleFinishedServerside(bool success, BatchContextSafeHandle ctx)
{
bool cancelled = ctx.GetReceivedCloseOnServerCancelled();
lock (myLock)
{
finished = true;
if (cancelled)
{
// Once we cancel, we don't have to care that much
// about reads and writes.
// TODO(jtattermusch): is this still necessary?
Cancel();
}
ReleaseResourcesIfPossible();
}
// TODO(jtattermusch): handle error
if (cancelled)
{
cancellationTokenSource.Cancel();
}
finishedServersideTcs.SetResult(null);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel.Design;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.Versioning;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using Ionic.Zip;
using NuGet;
using ReactiveUIMicro;
using Shimmer.Core.Extensions;
namespace Shimmer.Core
{
internal static class FrameworkTargetVersion
{
public static FrameworkName Net40 = new FrameworkName(".NETFramework,Version=v4.0");
public static FrameworkName Net45 = new FrameworkName(".NETFramework,Version=v4.5");
}
public interface IReleasePackage
{
string InputPackageFile { get; }
string ReleasePackageFile { get; }
string SuggestedReleaseFileName { get; }
string CreateReleasePackage(string outputFile, string packagesRootDir = null, Func<string, string> releaseNotesProcessor = null);
}
public static class VersionComparer
{
public static bool Matches(IVersionSpec versionSpec, SemanticVersion version)
{
if (versionSpec == null)
return true; // I CAN'T DEAL WITH THIS
bool minVersion;
if (versionSpec.MinVersion == null) {
minVersion = true; // no preconditon? LET'S DO IT
} else if (versionSpec.IsMinInclusive) {
minVersion = version >= versionSpec.MinVersion;
} else {
minVersion = version > versionSpec.MinVersion;
}
bool maxVersion;
if (versionSpec.MaxVersion == null) {
maxVersion = true; // no preconditon? LET'S DO IT
} else if (versionSpec.IsMaxInclusive) {
maxVersion = version <= versionSpec.MaxVersion;
} else {
maxVersion = version < versionSpec.MaxVersion;
}
return maxVersion && minVersion;
}
}
public class ReleasePackage : IEnableLogger, IReleasePackage
{
IEnumerable<IPackage> localPackageCache;
public ReleasePackage(string inputPackageFile, bool isReleasePackage = false)
{
InputPackageFile = inputPackageFile;
if (isReleasePackage) {
ReleasePackageFile = inputPackageFile;
}
}
public string InputPackageFile { get; protected set; }
public string ReleasePackageFile { get; protected set; }
public string SuggestedReleaseFileName {
get {
var zp = new ZipPackage(InputPackageFile);
return String.Format("{0}-{1}-full.nupkg", zp.Id, zp.Version);
}
}
public Version Version { get { return InputPackageFile.ToVersion(); } }
public string CreateReleasePackage(string outputFile, string packagesRootDir = null, Func<string, string> releaseNotesProcessor = null)
{
Contract.Requires(!String.IsNullOrEmpty(outputFile));
if (ReleasePackageFile != null) {
return ReleasePackageFile;
}
var package = new ZipPackage(InputPackageFile);
// we can tell from here what platform(s) the package targets
// but given this is a simple package we only
// ever expect one entry here (crash hard otherwise)
var frameworks = package.GetSupportedFrameworks();
if (frameworks.Count() > 1) {
var platforms = frameworks
.Aggregate(new StringBuilder(), (sb, f) => sb.Append(f.ToString() + "; "));
throw new InvalidOperationException(String.Format(
"The input package file {0} targets multiple platforms - {1} - and cannot be transformed into a release package.", InputPackageFile, platforms));
}
var targetFramework = frameworks.Single();
// Recursively walk the dependency tree and extract all of the
// dependent packages into the a temporary directory
var dependencies = findAllDependentPackages(
package,
packagesRootDir,
frameworkName: targetFramework);
string tempPath = null;
using (Utility.WithTempDirectory(out tempPath)) {
var tempDir = new DirectoryInfo(tempPath);
using(var zf = new ZipFile(InputPackageFile)) {
zf.ExtractAll(tempPath);
}
extractDependentPackages(dependencies, tempDir, targetFramework);
var specPath = tempDir.GetFiles("*.nuspec").First().FullName;
removeDependenciesFromPackageSpec(specPath);
removeDeveloperDocumentation(tempDir);
if (releaseNotesProcessor != null) {
renderReleaseNotesMarkdown(specPath, releaseNotesProcessor);
}
addDeltaFilesToContentTypes(tempDir.FullName);
using (var zf = new ZipFile(outputFile)) {
zf.AddDirectory(tempPath);
zf.Save();
}
ReleasePackageFile = outputFile;
return ReleasePackageFile;
}
}
void extractDependentPackages(IEnumerable<IPackage> dependencies, DirectoryInfo tempPath, FrameworkName framework = null)
{
dependencies.ForEach(pkg => {
this.Log().Info("Scanning {0}", pkg.Id);
pkg.GetLibFiles().ForEach(file => {
var outPath = new FileInfo(Path.Combine(tempPath.FullName, file.Path));
if(isNonDesktopAssembly(file.Path)) {
this.Log().Info("Ignoring {0} as the platform is not acceptable", outPath);
return;
}
if (framework != null) {
if (framework == FrameworkTargetVersion.Net40
&& file.TargetFramework == FrameworkTargetVersion.Net45)
{
this.Log().Info("Ignoring {0} as we do not want to ship net45 assemblies for our net40 app", outPath);
return;
}
}
Directory.CreateDirectory(outPath.Directory.FullName);
using (var of = File.Create(outPath.FullName)) {
this.Log().Info("Writing {0} to {1}", file.Path, outPath);
file.GetStream().CopyTo(of);
}
});
});
}
void removeDeveloperDocumentation(DirectoryInfo expandedRepoPath)
{
expandedRepoPath.GetAllFilesRecursively()
.Where(x => x.Name.EndsWith(".dll", true, CultureInfo.InvariantCulture))
.Select(x => new FileInfo(x.FullName.ToLowerInvariant().Replace(".dll", ".xml")))
.Where(x => x.Exists)
.ForEach(x => x.Delete());
}
bool isNonDesktopAssembly(string path)
{
// NB: Nuke Silverlight, WinRT, WindowsPhone and Xamarin assemblies.
// We can't tell as easily if other profiles can be removed because
// you can load net20 DLLs inside .NET 4.0 apps
var bannedFrameworks = new[] {"sl", "winrt", "netcore", "win8", "windows8", "MonoAndroid", "MonoTouch", "MonoMac", "wp", };
string frameworkPath = path.Substring(4);
return bannedFrameworks.Any(x => frameworkPath.StartsWith(x, StringComparison.InvariantCultureIgnoreCase));
}
void renderReleaseNotesMarkdown(string specPath, Func<string, string> releaseNotesProcessor)
{
var doc = new XmlDocument();
doc.Load(specPath);
// XXX: This code looks full tart
var metadata = doc.DocumentElement.ChildNodes
.OfType<XmlElement>()
.First(x => x.Name.ToLowerInvariant() == "metadata");
var releaseNotes = metadata.ChildNodes
.OfType<XmlElement>()
.FirstOrDefault(x => x.Name.ToLowerInvariant() == "releasenotes");
if (releaseNotes == null) {
this.Log().Info("No release notes found in {0}", specPath);
return;
}
releaseNotes.InnerText = String.Format("<![CDATA[\n" + "{0}\n" + "]]>",
releaseNotesProcessor(releaseNotes.InnerText));
doc.Save(specPath);
}
void removeDependenciesFromPackageSpec(string specPath)
{
var xdoc = new XmlDocument();
xdoc.Load(specPath);
var metadata = xdoc.DocumentElement.FirstChild;
var dependenciesNode = metadata.ChildNodes.OfType<XmlElement>().FirstOrDefault(x => x.Name.ToLowerInvariant() == "dependencies");
if (dependenciesNode != null) {
metadata.RemoveChild(dependenciesNode);
}
xdoc.Save(specPath);
}
IEnumerable<IPackage> findAllDependentPackages(
IPackage package = null,
string packagesRootDir = null,
HashSet<string> packageCache = null,
FrameworkName frameworkName = null)
{
package = package ?? new ZipPackage(InputPackageFile);
packageCache = packageCache ?? new HashSet<string>();
var deps = package.DependencySets
.Where(x => x.TargetFramework == null
|| x.TargetFramework == frameworkName)
.SelectMany(x => x.Dependencies);
return deps.SelectMany(dependency => {
var ret = findPackageFromName(dependency.Id, dependency.VersionSpec, packagesRootDir);
if (ret == null) {
var message = String.Format("Couldn't find file for package in {1}: {0}", dependency.Id, packagesRootDir);
this.Log().Error(message);
throw new Exception(message);
}
if (packageCache.Contains(ret.GetFullName())) {
return Enumerable.Empty<IPackage>();
}
packageCache.Add(ret.GetFullName());
return findAllDependentPackages(ret, packagesRootDir, packageCache, frameworkName).StartWith(ret).Distinct(y => y.GetFullName());
}).ToArray();
}
IPackage findPackageFromName(
string id,
IVersionSpec versionSpec,
string packagesRootDir = null,
IQueryable<IPackage> machineCache = null)
{
machineCache = machineCache ?? Enumerable.Empty<IPackage>().AsQueryable();
if (packagesRootDir != null && localPackageCache == null) {
localPackageCache = Utility.GetAllFilePathsRecursively(packagesRootDir)
.Where(PackageHelper.IsPackageFile)
.Select(x => new ZipPackage(x))
.ToArray();
}
return findPackageFromNameInList(id, versionSpec, localPackageCache ?? Enumerable.Empty<IPackage>()) ??
findPackageFromNameInList(id, versionSpec, machineCache);
}
static IPackage findPackageFromNameInList(string id, IVersionSpec versionSpec, IEnumerable<IPackage> packageList)
{
return packageList.Where(x => String.Equals(x.Id, id, StringComparison.OrdinalIgnoreCase)).ToArray()
.FirstOrDefault(x => VersionComparer.Matches(versionSpec, x.Version));
}
static internal void addDeltaFilesToContentTypes(string rootDirectory)
{
var doc = new XmlDocument();
var path = Path.Combine(rootDirectory, "[Content_Types].xml");
doc.Load(path);
ContentType.Merge(doc);
using (var sw = new StreamWriter(path, false, Encoding.UTF8)) {
doc.Save(sw);
}
}
}
public class ChecksumFailedException : Exception
{
public string Filename { 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 Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NuGet.Frameworks;
using NuGet.Versioning;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using PropertyNames = NuGet.Client.ManagedCodeConventions.PropertyNames;
namespace Microsoft.DotNet.Build.Tasks.Packaging
{
public class ValidatePackage : PackagingTask
{
[Required]
public string ContractName
{
get;
set;
}
[Required]
public string PackageId
{
get;
set;
}
[Required]
public string PackageVersion
{
get;
set;
}
/// <summary>
/// Frameworks supported by this package
/// Identity: name of framework, can suffx '+' to indicate all later frameworks under validation.
/// RuntimeIDs: Semi-colon seperated list of runtime IDs. If specified overrides the value specified in Frameworks.
/// Version: version of API supported
/// </summary>
[Required]
public ITaskItem[] SupportedFrameworks
{
get;
set;
}
/// <summary>
/// Frameworks to evaluate.
/// Identity: Framework
/// RuntimeIDs: Semi-colon seperated list of runtime IDs
/// </summary>
[Required]
public ITaskItem[] Frameworks
{
get;
set;
}
/// <summary>
/// Path to runtime.json that contains the runtime graph.
/// </summary>
[Required]
public string RuntimeFile
{
get;
set;
}
/// <summary>
/// Suppressions
/// Identity: suppression name
/// Value: optional semicolon-delimited list of values for the suppression
/// </summary>
public ITaskItem[] Suppressions { get;set; }
/// <summary>
/// A file containing names of suppressions with optional semi-colon values specified as follows
/// suppression1
/// suppression2=foo
/// suppression3=foo;bar
/// </summary>
public string SuppressionFile
{
get;
set;
}
[Required]
public string FrameworkListsPath
{
get;
set;
}
public bool SkipGenerationCheck
{
get;
set;
}
public bool SkipIndexCheck
{
get;
set;
}
public bool SkipSupportCheck
{
get;
set;
}
public bool UseNetPlatform
{
get { return _generationIdentifier == FrameworkConstants.FrameworkIdentifiers.NetPlatform; }
set { _generationIdentifier = value ? FrameworkConstants.FrameworkIdentifiers.NetPlatform : FrameworkConstants.FrameworkIdentifiers.NetStandard; }
}
/// <summary>
/// List of frameworks which were validated and determined to be supported
/// Identity: framework short name
/// Framework: framework full name
/// Version: assembly version of API that is supported
/// Inbox: true if assembly is expected to come from targeting pack
/// ValidatedRIDs: all RIDs that were scanned
/// </summary>
[Output]
public ITaskItem[] AllSupportedFrameworks
{
get;
set;
}
/// <summary>
/// JSON file describing results of validation
/// </summary>
public string ReportFile
{
get;
set;
}
/// <summary>
/// Package index files used to define package version mapping.
/// </summary>
[Required]
public ITaskItem[] PackageIndexes { get; set; }
/// <summary>
/// property bag of error suppressions
/// </summary>
private Dictionary<Suppression, HashSet<string>> _suppressions;
private Dictionary<NuGetFramework, ValidationFramework> _frameworks;
private FrameworkSet _frameworkSet;
private PackageReport _report;
private string _generationIdentifier = FrameworkConstants.FrameworkIdentifiers.NetStandard;
private static Version s_maxVersion = new Version(int.MaxValue, int.MaxValue, int.MaxValue, int.MaxValue);
public override bool Execute()
{
LoadSuppressions();
LoadReport();
if (!SkipSupportCheck)
{
LoadSupport();
if (!SkipGenerationCheck)
{
ValidateGenerations();
}
// TODO: need to validate dependencies.
ValidateSupport();
}
ValidateIndex();
return !Log.HasLoggedErrors;
}
private void ValidateGenerations()
{
// get the generation of all portable implementation dlls.
var allRuntimeGenerations = _report.Targets.Values.SelectMany(t => t.RuntimeAssets.NullAsEmpty())
.Select(r => r.TargetFramework)
.Where(fx => fx != null && fx.Framework == _generationIdentifier && fx.Version != null)
.Select(fx => fx.Version);
// get the generation of all supported frameworks (some may have framework specific implementations
// or placeholders).
var allSupportedGenerations = _frameworks.Values.Where(vf => vf.SupportedVersion != null && FrameworkUtilities.IsGenerationMoniker(vf.Framework) && vf.Framework.Version != null)
.Select(vf => vf.Framework.Version);
// find the minimum supported version as the minimum of any generation explicitly implemented
// with a portable implementation, or the generation of a framework with a platform specific
// implementation.
Version minSupportedGeneration = allRuntimeGenerations.Concat(allSupportedGenerations).Min();
// validate API version against generation for all files
foreach (var compileAsset in _report.Targets.Values.SelectMany(t => t.CompileAssets)
.Where(f => IsDll(f.LocalPath) && FrameworkUtilities.IsGenerationMoniker(f.TargetFramework)))
{
if (compileAsset.TargetFramework.Version < minSupportedGeneration)
{
Log.LogError($"Invalid generation {compileAsset.TargetFramework.Version} for {compileAsset.LocalPath}, must be at least {minSupportedGeneration} based on the implementations in the package. If you meant to target the lower generation you may be missing an implementation for a framework on that lower generation. If not you should raise the generation of the reference assembly to match that of the lowest supported generation of all implementations/placeholders.");
}
}
}
private void ValidateSupport()
{
var runtimeFxSuppression = GetSuppressionValues(Suppression.PermitRuntimeTargetMonikerMismatch) ?? new HashSet<string>();
// validate support for each TxM:RID
foreach (var validateFramework in _frameworks.Values)
{
NuGetFramework fx = validateFramework.Framework;
Version supportedVersion = validateFramework.SupportedVersion;
Target compileTarget;
if (!_report.Targets.TryGetValue(fx.ToString(), out compileTarget))
{
Log.LogError($"Missing target {fx.ToString()} from validation report {ReportFile}");
continue;
}
var compileAssetPaths = compileTarget.CompileAssets.Select(ca => ca.PackagePath);
bool hasCompileAsset, hasCompilePlaceHolder;
NuGetAssetResolver.ExamineAssets(Log, "Compile", ContractName, fx.ToString(), compileAssetPaths, out hasCompileAsset, out hasCompilePlaceHolder);
// resolve/test for each RID associated with this framework.
foreach (string runtimeId in validateFramework.RuntimeIds)
{
string target = String.IsNullOrEmpty(runtimeId) ? fx.ToString() : $"{fx}/{runtimeId}";
Target runtimeTarget;
if (!_report.Targets.TryGetValue(target, out runtimeTarget))
{
Log.LogError($"Missing target {target} from validation report {ReportFile}");
continue;
}
var runtimeAssetPaths = runtimeTarget.RuntimeAssets.Select(ra => ra.PackagePath);
bool hasRuntimeAsset, hasRuntimePlaceHolder;
NuGetAssetResolver.ExamineAssets(Log, "Runtime", ContractName, target, runtimeAssetPaths, out hasRuntimeAsset, out hasRuntimePlaceHolder);
if (null == supportedVersion)
{
// Contract should not be supported on this platform.
bool permitImplementation = HasSuppression(Suppression.PermitImplementation, target);
if (hasCompileAsset && (hasRuntimeAsset & !permitImplementation))
{
Log.LogError($"{ContractName} should not be supported on {target} but has both compile and runtime assets.");
}
else if (hasRuntimeAsset & !permitImplementation)
{
Log.LogError($"{ContractName} should not be supported on {target} but has runtime assets.");
}
if (hasRuntimePlaceHolder && hasCompilePlaceHolder)
{
Log.LogError($"{ContractName} should not be supported on {target} but has placeholders for both compile and runtime which will permit the package to install.");
}
}
else
{
if (validateFramework.IsInbox)
{
if (!hasCompileAsset && !hasCompilePlaceHolder)
{
Log.LogError($"Framework {fx} should support {ContractName} inbox but was missing a placeholder for compile-time. You may need to add <InboxOnTargetFramework Include=\"{fx.GetShortFolderName()}\" /> to your project.");
}
else if (hasCompileAsset)
{
Log.LogError($"Framework {fx} should support {ContractName} inbox but contained a reference assemblies: {String.Join(", ", compileAssetPaths)}. You may need to add <InboxOnTargetFramework Include=\"{fx.GetShortFolderName()}\" /> to your project.");
}
if (!hasRuntimeAsset && !hasRuntimePlaceHolder)
{
Log.LogError($"Framework {fx} should support {ContractName} inbox but was missing a placeholder for run-time. You may need to add <InboxOnTargetFramework Include=\"{fx.GetShortFolderName()}\" /> to your project.");
}
else if (hasRuntimeAsset)
{
Log.LogError($"Framework {fx} should support {ContractName} inbox but contained a implementation assemblies: {String.Join(", ", runtimeAssetPaths)}. You may need to add <InboxOnTargetFramework Include=\"{fx.GetShortFolderName()}\" /> to your project.");
}
}
else
{
Version referenceAssemblyVersion = null;
if (!hasCompileAsset)
{
Log.LogError($"{ContractName} should be supported on {target} but has no compile assets.");
}
else
{
var referenceAssemblies = compileTarget.CompileAssets.Where(ca => IsDll(ca.PackagePath));
if (referenceAssemblies.Count() > 1)
{
Log.LogError($"{ContractName} should only contain a single compile asset for {target}.");
}
foreach (var referenceAssembly in referenceAssemblies)
{
referenceAssemblyVersion = referenceAssembly.Version;
if (!VersionUtility.IsCompatibleApiVersion(supportedVersion, referenceAssemblyVersion))
{
Log.LogError($"{ContractName} should support API version {supportedVersion} on {target} but {referenceAssembly.LocalPath} was found to support {referenceAssemblyVersion?.ToString() ?? "<unknown version>"}.");
}
}
}
if (!hasRuntimeAsset && !FrameworkUtilities.IsGenerationMoniker(validateFramework.Framework))
{
Log.LogError($"{ContractName} should be supported on {target} but has no runtime assets.");
}
else
{
var implementationAssemblies = runtimeTarget.RuntimeAssets.Where(ra => IsDll(ra.PackagePath));
Dictionary<string, PackageAsset> implementationFiles = new Dictionary<string, PackageAsset>();
foreach (var implementationAssembly in implementationAssemblies)
{
Version implementationVersion = implementationAssembly.Version;
if (!VersionUtility.IsCompatibleApiVersion(supportedVersion, implementationVersion))
{
Log.LogError($"{ContractName} should support API version {supportedVersion} on {target} but {implementationAssembly.LocalPath} was found to support {implementationVersion?.ToString() ?? "<unknown version>"}.");
}
// Previously we only permitted compatible mismatch if Suppression.PermitHigherCompatibleImplementationVersion was specified
// this is a permitted thing on every framework but desktop (which requires exact match to ensure bindingRedirects exist)
// Now make this the default, we'll check desktop, where it matters, more strictly
if (referenceAssemblyVersion != null &&
!VersionUtility.IsCompatibleApiVersion(referenceAssemblyVersion, implementationVersion))
{
Log.LogError($"{ContractName} has mismatched compile ({referenceAssemblyVersion}) and runtime ({implementationVersion}) versions on {target}.");
}
if (fx.Framework == FrameworkConstants.FrameworkIdentifiers.Net &&
referenceAssemblyVersion != null &&
!referenceAssemblyVersion.Equals(implementationVersion))
{
Log.LogError($"{ContractName} has a higher runtime version ({implementationVersion}) than compile version ({referenceAssemblyVersion}) on .NET Desktop framework {target}. This will break bindingRedirects. If the live reference was replaced with a harvested reference you may need to set <Preserve>true</Preserve> on your reference assembly ProjectReference.");
}
string fileName = Path.GetFileName(implementationAssembly.PackagePath);
if (implementationFiles.ContainsKey(fileName))
{
Log.LogError($"{ContractName} includes both {implementationAssembly.LocalPath} and {implementationFiles[fileName].LocalPath} an on {target} which have the same name and will clash when both packages are used.");
}
else
{
implementationFiles[fileName] = implementationAssembly;
}
if (!implementationAssembly.Equals(fx) && !runtimeFxSuppression.Contains(fx.ToString()))
{
// the selected asset wasn't an exact framework match, let's see if we have an exact match in any other runtime asset.
var matchingFxAssets = _report.UnusedAssets.Where(i => i.TargetFramework == fx && // exact framework
// Same file
Path.GetFileName(i.PackagePath).Equals(fileName, StringComparison.OrdinalIgnoreCase) &&
// Is implementation
(i.PackagePath.StartsWith("lib") || i.PackagePath.StartsWith("runtimes")) &&
// is not the same source file as was already selected
i.LocalPath != implementationAssembly.LocalPath);
if (matchingFxAssets.Any())
{
Log.LogError($"When targeting {target} {ContractName} will use {implementationAssembly.LocalPath} which targets {implementationAssembly.TargetFramework.GetShortFolderName()} but {String.Join(";", matchingFxAssets.Select(i => i.PackagePath))} targets {fx.GetShortFolderName()} specifically.");
}
}
}
}
}
}
}
}
// Set output items
AllSupportedFrameworks = _frameworks.Values.Where(fx => fx.SupportedVersion != null).Select(fx => fx.ToItem()).OrderBy(i => i.ItemSpec).ToArray();
}
private void ValidateIndex()
{
if (SkipIndexCheck)
{
return;
}
if (PackageIndexes == null || PackageIndexes.Length == 0)
{
return;
}
PackageIndex.Current.Merge(PackageIndexes.Select(pi => pi.GetMetadata("FullPath")));
PackageInfo info;
if (!PackageIndex.Current.Packages.TryGetValue(PackageId, out info))
{
Log.LogError($"PackageIndex from {String.Join(", ", PackageIndexes.Select(i => i.ItemSpec))} is missing an entry for package {PackageId}. Please run /t:UpdatePackageIndex on this project to commit an update.");
return;
}
var allDlls = _report.Targets.Values.SelectMany(t => t.CompileAssets.NullAsEmpty().Concat(t.RuntimeAssets.NullAsEmpty()));
var allAssemblies = allDlls.Where(f => f.Version != null);
var assemblyVersions = new HashSet<Version>(allAssemblies.Select(f => VersionUtility.As4PartVersion(f.Version)));
var thisPackageVersion = VersionUtility.As3PartVersion(NuGetVersion.Parse(PackageVersion).Version);
foreach (var fileVersion in assemblyVersions)
{
Version packageVersion;
// determine if we're missing a mapping for this package
if (!info.AssemblyVersionInPackageVersion.TryGetValue(fileVersion, out packageVersion))
{
Log.LogError($"PackageIndex from {String.Join(", ", PackageIndexes.Select(i => i.ItemSpec))} is missing an assembly version entry for {fileVersion} for package {PackageId}. Please run /t:UpdatePackageIndex on this project to commit an update.");
}
else
{
// determine if we have a mapping for an unstable package and that unstable package is not this one
if (!info.StableVersions.Contains(packageVersion) && packageVersion != thisPackageVersion)
{
Log.LogError($"PackageIndex from {String.Join(", ", PackageIndexes.Select(i => i.ItemSpec))} indicates that assembly version {fileVersion} is contained in non-stable package version {packageVersion} which differs from this package version {thisPackageVersion}.");
}
}
}
var orphanedAssemblyVersions = info.AssemblyVersionInPackageVersion
.Where(pair => pair.Value == thisPackageVersion && !assemblyVersions.Contains(pair.Key))
.Select(pair => pair.Key);
if (orphanedAssemblyVersions.Any())
{
Log.LogError($"PackageIndex from {String.Join(", ", PackageIndexes.Select(i => i.ItemSpec))} is has an assembly version entry(s) for {String.Join(", ", orphanedAssemblyVersions)} which are no longer in package {PackageId}. Please run /t:UpdatePackageIndex on this project to commit an update.");
}
// if no assemblies are present in this package nor were ever present
if (assemblyVersions.Count == 0 &&
info.AssemblyVersionInPackageVersion.Count == 0)
{
// if in the native module map
if (PackageIndex.Current.ModulesToPackages.Values.Any(p => p.Equals(PackageId)))
{
// ensure the baseline is set
if (info.BaselineVersion != thisPackageVersion)
{
Log.LogError($"PackageIndex from {String.Join(", ", PackageIndexes.Select(i => i.ItemSpec))} is missing an baseline entry(s) for native module {PackageId}. Please run /t:UpdatePackageIndex on this project to commit an update.");
}
}
else
{
// not in the native module map, see if any of the modules in this package are present
// (with a different package, as would be the case for runtime-specific packages)
var moduleNames = allDlls.Select(d => Path.GetFileNameWithoutExtension(d.LocalPath));
if (moduleNames.Any() && !moduleNames.Any(m => PackageIndex.Current.ModulesToPackages.ContainsKey(m)))
{
Log.LogError($"PackageIndex from {String.Join(", ", PackageIndexes.Select(i => i.ItemSpec))} is missing ModulesToPackages entry(s) for {String.Join(", ", allDlls)} to package {PackageId}. Please add a an entry for the appropriate package.");
}
}
}
}
private static bool IsDll(string path)
{
return !String.IsNullOrWhiteSpace(path) && Path.GetExtension(path).Equals(".dll", StringComparison.OrdinalIgnoreCase);
}
private HashSet<string> GetSuppressionValues(Suppression key)
{
HashSet<string> values;
_suppressions.TryGetValue(key, out values);
return values;
}
private string GetSingleSuppressionValue(Suppression key)
{
var values = GetSuppressionValues(key);
return (values != null && values.Count == 1) ? values.Single() : null;
}
private bool HasSuppression(Suppression key)
{
return _suppressions.ContainsKey(key);
}
private bool HasSuppression(Suppression key, string value)
{
HashSet<string> values;
if (_suppressions.TryGetValue(key, out values) && values != null)
{
return values.Contains(value);
}
return false;
}
private void LoadSuppressions()
{
_suppressions = new Dictionary<Suppression, HashSet<string>>();
if (Suppressions != null)
{
foreach(var suppression in Suppressions)
{
AddSuppression(suppression.ItemSpec, suppression.GetMetadata("Value"));
}
}
if (File.Exists(SuppressionFile))
{
foreach (string suppression in File.ReadAllLines(SuppressionFile))
{
if (suppression.TrimStart().StartsWith(@"//", StringComparison.OrdinalIgnoreCase) || String.IsNullOrWhiteSpace(suppression))
{
continue;
}
var parts = suppression.Split(new[] { '=' }, 2);
AddSuppression(parts[0], parts.Length > 1 ? parts[1] : null);
}
}
}
private void AddSuppression(string keyString, string valueString)
{
Suppression key;
HashSet<string> values = null;
if (!Enum.TryParse<Suppression>(keyString, out key))
{
Log.LogError($"{SuppressionFile} contained unknown suppression {keyString}");
return;
}
_suppressions.TryGetValue(key, out values);
if (valueString != null)
{
var valuesToAdd = valueString.Split(';');
if (values == null)
{
values = new HashSet<string>(valuesToAdd);
}
else
{
foreach(var valueToAdd in valuesToAdd)
{
values.Add(valueToAdd);
}
}
}
_suppressions[key] = values;
}
private void LoadReport()
{
_report = PackageReport.Load(ReportFile);
}
private void LoadSupport()
{
_frameworks = new Dictionary<NuGetFramework, ValidationFramework>();
// determine which TxM:RIDs should be considered for support based on Frameworks item
foreach (var framework in Frameworks)
{
NuGetFramework fx;
try
{
fx = FrameworkUtilities.ParseNormalized(framework.ItemSpec);
}
catch (Exception ex)
{
Log.LogError($"Could not parse Framework {framework.ItemSpec}. {ex}");
continue;
}
if (fx.Equals(NuGetFramework.UnsupportedFramework))
{
Log.LogError($"Did not recognize {framework.ItemSpec} as valid Framework.");
continue;
}
string runtimeIdList = framework.GetMetadata("RuntimeIDs");
if (_frameworks.ContainsKey(fx))
{
Log.LogError($"Framework {fx} has been listed in Frameworks more than once.");
continue;
}
_frameworks[fx] = new ValidationFramework(fx);
if (!String.IsNullOrWhiteSpace(runtimeIdList))
{
_frameworks[fx].RuntimeIds = runtimeIdList.Split(';');
}
}
// keep a list of explicitly listed supported frameworks so that we can check for conflicts.
HashSet<NuGetFramework> explicitlySupportedFrameworks = new HashSet<NuGetFramework>();
// determine what version should be supported based on SupportedFramework items
foreach (var supportedFramework in SupportedFrameworks)
{
NuGetFramework fx;
string fxString = supportedFramework.ItemSpec;
bool isExclusiveVersion = fxString.Length > 1 && fxString[0] == '[' && fxString[fxString.Length - 1] == ']';
if (isExclusiveVersion)
{
fxString = fxString.Substring(1, fxString.Length - 2);
}
try
{
fx = FrameworkUtilities.ParseNormalized(fxString);
}
catch (Exception ex)
{
Log.LogError($"Could not parse TargetFramework {fxString} as a SupportedFramework. {ex}");
continue;
}
if (fx.Equals(NuGetFramework.UnsupportedFramework))
{
Log.LogError($"Did not recognize TargetFramework {fxString} as a SupportedFramework.");
continue;
}
Version supportedVersion;
string version = supportedFramework.GetMetadata("Version");
try
{
supportedVersion = Version.Parse(version);
}
catch (Exception ex)
{
Log.LogError($"Could not parse Version {version} on SupportedFramework item {supportedFramework.ItemSpec}. {ex}");
continue;
}
ValidationFramework validationFramework = null;
if (!_frameworks.TryGetValue(fx, out validationFramework))
{
Log.LogError($"SupportedFramework {fx} was specified but is not part of the Framework list to use for validation.");
continue;
}
if (explicitlySupportedFrameworks.Contains(fx))
{
if (supportedVersion <= validationFramework.SupportedVersion)
{
// if we've already picked up a higher/equal version, prefer it
continue;
}
}
else
{
explicitlySupportedFrameworks.Add(fx);
}
validationFramework.SupportedVersion = supportedVersion;
if (!isExclusiveVersion)
{
// find all frameworks of higher version, sorted by version ascending
IEnumerable<ValidationFramework> higherFrameworks = _frameworks.Values.Where(vf => vf.Framework.Framework == fx.Framework && vf.Framework.Version > fx.Version).OrderBy(vf => vf.Framework.Version);
// netcore50 is the last `netcore` framework, after that we use `uap`
if (fx.Framework == FrameworkConstants.FrameworkIdentifiers.NetCore)
{
var uapFrameworks = _frameworks.Values.Where(vf => vf.Framework.Framework == FrameworkConstants.FrameworkIdentifiers.UAP).OrderBy(vf => vf.Framework.Version);
higherFrameworks = higherFrameworks.Concat(uapFrameworks);
}
foreach (var higherFramework in higherFrameworks)
{
if (higherFramework.SupportedVersion != null && higherFramework.SupportedVersion > supportedVersion)
{
// found an higher framework version a higher API version, stop applying this supported version
break;
}
higherFramework.SupportedVersion = supportedVersion;
}
}
}
// determine which Frameworks should support inbox
_frameworkSet = FrameworkSet.Load(FrameworkListsPath);
foreach (IEnumerable<Framework> inboxFxGroup in _frameworkSet.Frameworks.Values)
{
foreach (Framework inboxFx in inboxFxGroup)
{
// get currently supported version to see if we have OOB'ed it
Version inboxVersion = null;
inboxFx.Assemblies.TryGetValue(ContractName, out inboxVersion);
if (inboxVersion != null)
{
NuGetFramework fx = FrameworkUtilities.ParseNormalized(inboxFx.ShortName);
ValidationFramework validationFramework = null;
if (_frameworks.TryGetValue(fx, out validationFramework))
{
Version supportedVersion = validationFramework.SupportedVersion;
if (supportedVersion != null &&
(supportedVersion.Major > inboxVersion.Major ||
(supportedVersion.Major == inboxVersion.Major && supportedVersion.Minor > inboxVersion.Minor)))
{
// Higher major.minor
Log.LogMessage(LogImportance.Low, $"Framework {fx} supported {ContractName} as inbox but the current supported version {supportedVersion} is higher in major.minor than inbox version {inboxVersion}. Assuming out of box.");
continue;
}
else if (supportedVersion != null && supportedVersion < inboxVersion && inboxVersion != s_maxVersion)
{
// Lower version
Log.LogError($"Framework {fx} supports {ContractName} as inbox but the current supported version {supportedVersion} is lower than the inbox version {inboxVersion}");
}
// equal major.minor, build.revision difference is permitted, prefer the version listed by ContractSupport item
}
if (validationFramework == null)
{
// we may not be explicitly validating for this framework so add it to validate inbox assets.
_frameworks[fx] = validationFramework = new ValidationFramework(fx)
{
SupportedVersion = inboxVersion
};
}
validationFramework.IsInbox = true;
}
}
}
// for every framework we know about, also infer it's netstandard version to ensure it can
// be targeted by PCL. Even if a package only supports a single framework we still
// want to include a portable reference assembly. This allows 3rd parties to add
// their own implementation via a lineup/runtime.json.
// only consider frameworks that support the contract at a specific version
var inferFrameworks = _frameworks.Values.Where(fx => fx.SupportedVersion != null && fx.SupportedVersion != s_maxVersion).ToArray();
var genVersionSuppression = GetSuppressionValues(Suppression.PermitPortableVersionMismatch) ?? new HashSet<string>();
var inferNETStandardSuppression = GetSuppressionValues(Suppression.SuppressNETStandardInference) ?? new HashSet<string>();
Dictionary<NuGetFramework, ValidationFramework> generationsToValidate = new Dictionary<NuGetFramework, ValidationFramework>();
foreach (var inferFramework in inferFrameworks)
{
var inferFrameworkMoniker = inferFramework.Framework.ToString();
if (inferNETStandardSuppression.Contains(inferFrameworkMoniker))
{
continue;
}
NuGetFramework generation = new NuGetFramework(_generationIdentifier, Generations.DetermineGenerationForFramework(inferFramework.Framework, UseNetPlatform));
Log.LogMessage(LogImportance.Low, $"Validating {generation} for {ContractName}, {inferFramework.SupportedVersion} since it is supported by {inferFrameworkMoniker}");
ValidationFramework existingGeneration = null;
if (generationsToValidate.TryGetValue(generation, out existingGeneration))
{
// the netstandard version should be the minimum version supported by all platforms that support that netstandard version.
if (inferFramework.SupportedVersion < existingGeneration.SupportedVersion)
{
Log.LogMessage($"Framework {inferFramework.Framework} supports {ContractName} at {inferFramework.SupportedVersion} which is lower than {existingGeneration.SupportedVersion} supported by generation {generation.GetShortFolderName()}. Lowering the version supported by {generation.GetShortFolderName()}.");
existingGeneration.SupportedVersion = inferFramework.SupportedVersion;
}
}
else
{
generationsToValidate.Add(generation, new ValidationFramework(generation) { SupportedVersion = inferFramework.SupportedVersion });
}
}
foreach (var generation in generationsToValidate)
{
_frameworks.Add(generation.Key, generation.Value);
}
}
private string GetVersionString(Version version)
{
// normalize to API version
return version == s_maxVersion ? "Any" : _frameworkSet.GetApiVersion(ContractName, version)?.ToString();
}
private class ValidationFramework
{
private static readonly string[] s_nullRidList = new string[] { null };
public ValidationFramework(NuGetFramework framework)
{
Framework = framework;
RuntimeIds = s_nullRidList;
}
public NuGetFramework Framework { get; }
public string[] RuntimeIds { get; set; }
// if null indicates the contract should not be supported.
public Version SupportedVersion { get; set; }
public bool IsInbox { get; set; }
public string ShortName { get { return Framework.GetShortFolderName(); } }
public ITaskItem ToItem()
{
ITaskItem item = new TaskItem(Framework.ToString());
item.SetMetadata("ShortName", ShortName);
item.SetMetadata("Version", SupportedVersion.ToString());
item.SetMetadata("Inbox", IsInbox.ToString());
item.SetMetadata("ValidatedRIDs", String.Join(";", RuntimeIds));
return item;
}
}
}
public enum Suppression
{
/// <summary>
/// Permits a runtime asset of the targets specified, semicolon delimited
/// </summary>
PermitImplementation,
/// <summary>
/// Permits a lower version on specified frameworks, semicolon delimitied, than the generation supported by that framework
/// </summary>
PermitPortableVersionMismatch,
/// <summary>
/// Permits a compatible API version match between ref and impl, rather than exact match
/// </summary>
PermitHigherCompatibleImplementationVersion,
/// <summary>
/// Permits a non-matching targetFramework asset to be used even when a matching one exists.
/// </summary>
PermitRuntimeTargetMonikerMismatch,
/// <summary>
/// Suppresses a particular set of SupportedFrameworks from inferring NETStandard support.
/// EG: package supports netcore45, wp8, net451, wpa81.
/// package cannot support net45, and thus doesn't wish to expose netstandard1.0 or netstandard1.1
/// reference assemblies.
/// It can use SuppressNETStandardInference=WindowsPhone,Version=v8.0;.NETCore,Version=v4.5 to still
/// validate support for wp8 and netcore45 without forcing it to support netstandard1.0 and 1.1.
/// </summary>
SuppressNETStandardInference
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using System.Windows;
using System.Xml;
using Microsoft.PythonTools.Infrastructure;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
namespace Microsoft.PythonTools.Profiling {
/// <summary>
/// Factory for creating our editor object. Extends from the IVsEditoryFactory interface
/// </summary>
[Guid(GuidList.guidEditorFactoryString)]
sealed class ProfilingSessionEditorFactory : IVsEditorFactory, IDisposable {
private readonly PythonProfilingPackage _editorPackage;
private ServiceProvider _vsServiceProvider;
public ProfilingSessionEditorFactory(PythonProfilingPackage package) {
Trace.WriteLine(string.Format(CultureInfo.CurrentCulture, "Entering {0} constructor", this.ToString()));
_editorPackage = package;
}
/// <summary>
/// Since we create a ServiceProvider which implements IDisposable we
/// also need to implement IDisposable to make sure that the ServiceProvider's
/// Dispose method gets called.
/// </summary>
public void Dispose() {
if (_vsServiceProvider != null) {
_vsServiceProvider.Dispose();
}
}
#region IVsEditorFactory Members
/// <summary>
/// Used for initialization of the editor in the environment
/// </summary>
/// <param name="psp">pointer to the service provider. Can be used to obtain instances of other interfaces
/// </param>
/// <returns></returns>
public int SetSite(Microsoft.VisualStudio.OLE.Interop.IServiceProvider psp) {
_vsServiceProvider = new ServiceProvider(psp);
return VSConstants.S_OK;
}
public object GetService(Type serviceType) {
return _vsServiceProvider.GetService(serviceType);
}
// This method is called by the Environment (inside IVsUIShellOpenDocument::
// OpenStandardEditor and OpenSpecificEditor) to map a LOGICAL view to a
// PHYSICAL view. A LOGICAL view identifies the purpose of the view that is
// desired (e.g. a view appropriate for Debugging [LOGVIEWID_Debugging], or a
// view appropriate for text view manipulation as by navigating to a find
// result [LOGVIEWID_TextView]). A PHYSICAL view identifies an actual type
// of view implementation that an IVsEditorFactory can create.
//
// NOTE: Physical views are identified by a string of your choice with the
// one constraint that the default/primary physical view for an editor
// *MUST* use a NULL string as its physical view name (*pbstrPhysicalView = NULL).
//
// NOTE: It is essential that the implementation of MapLogicalView properly
// validates that the LogicalView desired is actually supported by the editor.
// If an unsupported LogicalView is requested then E_NOTIMPL must be returned.
//
// NOTE: The special Logical Views supported by an Editor Factory must also
// be registered in the local registry hive. LOGVIEWID_Primary is implicitly
// supported by all editor types and does not need to be registered.
// For example, an editor that supports a ViewCode/ViewDesigner scenario
// might register something like the following:
// HKLM\Software\Microsoft\VisualStudio\<version>\Editors\
// {...guidEditor...}\
// LogicalViews\
// {...LOGVIEWID_TextView...} = s ''
// {...LOGVIEWID_Code...} = s ''
// {...LOGVIEWID_Debugging...} = s ''
// {...LOGVIEWID_Designer...} = s 'Form'
//
public int MapLogicalView(ref Guid rguidLogicalView, out string pbstrPhysicalView) {
pbstrPhysicalView = null; // initialize out parameter
// we support only a single physical view
if (VSConstants.LOGVIEWID_Primary == rguidLogicalView)
return VSConstants.S_OK; // primary view uses NULL as pbstrPhysicalView
else
return VSConstants.E_NOTIMPL; // you must return E_NOTIMPL for any unrecognized rguidLogicalView values
}
public int Close() {
return VSConstants.S_OK;
}
/// <summary>
/// Used by the editor factory to create an editor instance. the environment first determines the
/// editor factory with the highest priority for opening the file and then calls
/// IVsEditorFactory.CreateEditorInstance. If the environment is unable to instantiate the document data
/// in that editor, it will find the editor with the next highest priority and attempt to so that same
/// thing.
/// NOTE: The priority of our editor is 32 as mentioned in the attributes on the package class.
///
/// Since our editor supports opening only a single view for an instance of the document data, if we
/// are requested to open document data that is already instantiated in another editor, or even our
/// editor, we return a value VS_E_INCOMPATIBLEDOCDATA.
/// </summary>
/// <param name="grfCreateDoc">Flags determining when to create the editor. Only open and silent flags
/// are valid
/// </param>
/// <param name="pszMkDocument">path to the file to be opened</param>
/// <param name="pszPhysicalView">name of the physical view</param>
/// <param name="pvHier">pointer to the IVsHierarchy interface</param>
/// <param name="itemid">Item identifier of this editor instance</param>
/// <param name="punkDocDataExisting">This parameter is used to determine if a document buffer
/// (DocData object) has already been created
/// </param>
/// <param name="ppunkDocView">Pointer to the IUnknown interface for the DocView object</param>
/// <param name="ppunkDocData">Pointer to the IUnknown interface for the DocData object</param>
/// <param name="pbstrEditorCaption">Caption mentioned by the editor for the doc window</param>
/// <param name="pguidCmdUI">the Command UI Guid. Any UI element that is visible in the editor has
/// to use this GUID. This is specified in the .vsct file
/// </param>
/// <param name="pgrfCDW">Flags for CreateDocumentWindow</param>
/// <returns></returns>
[SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security.Xml", "CA3053:UseXmlSecureResolver")]
public int CreateEditorInstance(
uint grfCreateDoc,
string pszMkDocument,
string pszPhysicalView,
IVsHierarchy pvHier,
uint itemid,
System.IntPtr punkDocDataExisting,
out System.IntPtr ppunkDocView,
out System.IntPtr ppunkDocData,
out string pbstrEditorCaption,
out Guid pguidCmdUI,
out int pgrfCDW) {
Trace.WriteLine(string.Format(CultureInfo.CurrentCulture, "Entering {0} CreateEditorInstace()", this.ToString()));
// Initialize to null
ppunkDocView = IntPtr.Zero;
ppunkDocData = IntPtr.Zero;
pguidCmdUI = GuidList.guidEditorFactory;
pgrfCDW = 0;
pbstrEditorCaption = null;
// Validate inputs
if ((grfCreateDoc & (VSConstants.CEF_OPENFILE | VSConstants.CEF_SILENT)) == 0) {
return VSConstants.E_INVALIDARG;
}
if (punkDocDataExisting != IntPtr.Zero) {
return VSConstants.VS_E_INCOMPATIBLEDOCDATA;
}
// Create the Document (editor)
var perfWin = _editorPackage.JoinableTaskFactory.Run(() => _editorPackage.ShowPerformanceExplorerAsync());
ProfilingTarget target;
try {
var settings = new XmlReaderSettings { XmlResolver = null };
using (var fs = new FileStream(pszMkDocument, FileMode.Open))
using (var reader = XmlReader.Create(fs, settings)) {
target = (ProfilingTarget)ProfilingTarget.Serializer.Deserialize(reader);
}
} catch (IOException e) {
MessageBox.Show(Strings.FailedToOpenPerformanceSessionFile.FormatUI(pszMkDocument, e.Message), Strings.ProductTitle);
return VSConstants.E_FAIL;
} catch (InvalidOperationException e) {
MessageBox.Show(Strings.FailedToReadPerformanceSession.FormatUI(pszMkDocument, e.Message), Strings.ProductTitle);
return VSConstants.E_FAIL;
}
perfWin.Sessions.OpenTarget(
target,
pszMkDocument
);
pbstrEditorCaption = "";
return VSConstants.S_OK;
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using Microsoft.CSharp.RuntimeBinder.Syntax;
namespace Microsoft.CSharp.RuntimeBinder.Semantics
{
internal sealed class BSYMMGR
{
// Special nullable members.
public PropertySymbol propNubValue;
public MethodSymbol methNubCtor;
private readonly SymFactory _symFactory;
private SYMTBL tableGlobal;
// The hash table for type arrays.
private Dictionary<TypeArrayKey, TypeArray> tableTypeArrays;
private static readonly TypeArray s_taEmpty = new TypeArray(Array.Empty<CType>());
public BSYMMGR()
{
this.tableGlobal = new SYMTBL();
_symFactory = new SymFactory(this.tableGlobal);
this.tableTypeArrays = new Dictionary<TypeArrayKey, TypeArray>();
////////////////////////////////////////////////////////////////////////////////
// Build the data structures needed to make FPreLoad fast. Make sure the
// namespaces are created. Compute and sort hashes of the NamespaceSymbol * value and type
// name (sans arity indicator).
for (int i = 0; i < (int)PredefinedType.PT_COUNT; ++i)
{
NamespaceSymbol ns = NamespaceSymbol.Root;
string name = PredefinedTypeFacts.GetName((PredefinedType)i);
int start = 0;
while (start < name.Length)
{
int iDot = name.IndexOf('.', start);
if (iDot == -1)
break;
string sub = (iDot > start) ? name.Substring(start, iDot - start) : name.Substring(start);
Name nm = NameManager.Add(sub);
ns = LookupGlobalSymCore(nm, ns, symbmask_t.MASK_NamespaceSymbol) as NamespaceSymbol ?? _symFactory.CreateNamespace(nm, ns);
start += sub.Length + 1;
}
}
}
public SYMTBL GetSymbolTable()
{
return tableGlobal;
}
public static TypeArray EmptyTypeArray()
{
return s_taEmpty;
}
public BetterType CompareTypes(TypeArray ta1, TypeArray ta2)
{
if (ta1 == ta2)
{
return BetterType.Same;
}
if (ta1.Count != ta2.Count)
{
// The one with more parameters is more specific.
return ta1.Count > ta2.Count ? BetterType.Left : BetterType.Right;
}
BetterType nTot = BetterType.Neither;
for (int i = 0; i < ta1.Count; i++)
{
CType type1 = ta1[i];
CType type2 = ta2[i];
BetterType nParam = BetterType.Neither;
LAgain:
if (type1.TypeKind != type2.TypeKind)
{
if (type1 is TypeParameterType)
{
nParam = BetterType.Right;
}
else if (type2 is TypeParameterType)
{
nParam = BetterType.Left;
}
}
else
{
switch (type1.TypeKind)
{
default:
Debug.Assert(false, "Bad kind in CompareTypes");
break;
case TypeKind.TK_TypeParameterType:
break;
case TypeKind.TK_PointerType:
case TypeKind.TK_ParameterModifierType:
case TypeKind.TK_ArrayType:
case TypeKind.TK_NullableType:
type1 = type1.BaseOrParameterOrElementType;
type2 = type2.BaseOrParameterOrElementType;
goto LAgain;
case TypeKind.TK_AggregateType:
nParam = CompareTypes(((AggregateType)type1).TypeArgsAll, ((AggregateType)type2).TypeArgsAll);
break;
}
}
if (nParam == BetterType.Right || nParam == BetterType.Left)
{
if (nTot == BetterType.Same || nTot == BetterType.Neither)
{
nTot = nParam;
}
else if (nParam != nTot)
{
return BetterType.Neither;
}
}
}
return nTot;
}
public SymFactory GetSymFactory()
{
return _symFactory;
}
public Symbol LookupGlobalSymCore(Name name, ParentSymbol parent, symbmask_t kindmask)
{
return tableGlobal.LookupSym(name, parent, kindmask);
}
public Symbol LookupAggMember(Name name, AggregateSymbol agg, symbmask_t mask)
{
return tableGlobal.LookupSym(name, agg, mask);
}
public static Symbol LookupNextSym(Symbol sym, ParentSymbol parent, symbmask_t kindmask)
{
Debug.Assert(sym.parent == parent);
sym = sym.nextSameName;
Debug.Assert(sym == null || sym.parent == parent);
// Keep traversing the list of symbols with same name and parent.
while (sym != null)
{
if ((kindmask & sym.mask()) > 0)
return sym;
sym = sym.nextSameName;
Debug.Assert(sym == null || sym.parent == parent);
}
return null;
}
////////////////////////////////////////////////////////////////////////////////
// Allocate a type array; used to represent a parameter list.
// We use a hash table to make sure that allocating the same type array twice
// returns the same value. This does two things:
//
// 1) Save a lot of memory.
// 2) Make it so parameter lists can be compared by a simple pointer comparison
// 3) Allow us to associate a token with each signature for faster metadata emit
private readonly struct TypeArrayKey : IEquatable<TypeArrayKey>
{
private readonly CType[] _types;
private readonly int _hashCode;
public TypeArrayKey(CType[] types)
{
_types = types;
int hashCode = 0x162A16FE;
foreach (CType type in types)
{
hashCode = (hashCode << 5) - hashCode;
if (type != null)
{
hashCode ^= type.GetHashCode();
}
}
_hashCode = hashCode;
}
public bool Equals(TypeArrayKey other)
{
CType[] types = _types;
CType[] otherTypes = other._types;
if (otherTypes == types)
{
return true;
}
if (other._hashCode != _hashCode || otherTypes.Length != types.Length)
{
return false;
}
for (int i = 0; i < types.Length; i++)
{
if (types[i] != otherTypes[i])
{
return false;
}
}
return true;
}
#if DEBUG
[ExcludeFromCodeCoverage] // Typed overload should always be the method called.
#endif
public override bool Equals(object obj)
{
Debug.Fail("Sub-optimal overload called. Check if this can be avoided.");
return obj is TypeArrayKey && Equals((TypeArrayKey)obj);
}
public override int GetHashCode()
{
return _hashCode;
}
}
public TypeArray AllocParams(int ctype, CType[] prgtype)
{
if (ctype == 0)
{
return s_taEmpty;
}
Debug.Assert(ctype == prgtype.Length);
return AllocParams(prgtype);
}
public TypeArray AllocParams(int ctype, TypeArray array, int offset)
{
if (ctype == 0)
{
return s_taEmpty;
}
if (ctype == array.Count)
{
return array;
}
CType[] types = array.Items;
CType[] newTypes = new CType[ctype];
Array.ConstrainedCopy(types, offset, newTypes, 0, ctype);
return AllocParams(newTypes);
}
public TypeArray AllocParams(params CType[] types)
{
if (types == null || types.Length == 0)
{
return s_taEmpty;
}
TypeArrayKey key = new TypeArrayKey(types);
TypeArray result;
if (!tableTypeArrays.TryGetValue(key, out result))
{
result = new TypeArray(types);
tableTypeArrays.Add(key, result);
}
return result;
}
private TypeArray ConcatParams(CType[] prgtype1, CType[] prgtype2)
{
CType[] combined = new CType[prgtype1.Length + prgtype2.Length];
Array.Copy(prgtype1, 0, combined, 0, prgtype1.Length);
Array.Copy(prgtype2, 0, combined, prgtype1.Length, prgtype2.Length);
return AllocParams(combined);
}
public TypeArray ConcatParams(TypeArray pta1, TypeArray pta2)
{
return ConcatParams(pta1.Items, pta2.Items);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Umbraco.Core;
using Umbraco.Core.Models;
using umbraco;
using umbraco.cms.businesslogic.web;
namespace Umbraco.Web.Cache
{
/// <summary>
/// Extension methods for DistrubutedCache
/// </summary>
internal static class DistributedCacheExtensions
{
#region Application tree cache
public static void RefreshAllApplicationTreeCache(this DistributedCache dc)
{
dc.RefreshAll(new Guid(DistributedCache.ApplicationTreeCacheRefresherId));
}
#endregion
#region Application cache
public static void RefreshAllApplicationCache(this DistributedCache dc)
{
dc.RefreshAll(new Guid(DistributedCache.ApplicationCacheRefresherId));
}
#endregion
#region User type cache
public static void RemoveUserTypeCache(this DistributedCache dc, int userTypeId)
{
dc.Remove(new Guid(DistributedCache.UserTypeCacheRefresherId), userTypeId);
}
public static void RefreshUserTypeCache(this DistributedCache dc, int userTypeId)
{
dc.Refresh(new Guid(DistributedCache.UserTypeCacheRefresherId), userTypeId);
}
public static void RefreshAllUserTypeCache(this DistributedCache dc)
{
dc.RefreshAll(new Guid(DistributedCache.UserTypeCacheRefresherId));
}
#endregion
#region User cache
public static void RemoveUserCache(this DistributedCache dc, int userId)
{
dc.Remove(new Guid(DistributedCache.UserCacheRefresherId), userId);
}
public static void RefreshUserCache(this DistributedCache dc, int userId)
{
dc.Refresh(new Guid(DistributedCache.UserCacheRefresherId), userId);
}
public static void RefreshAllUserCache(this DistributedCache dc)
{
dc.RefreshAll(new Guid(DistributedCache.UserCacheRefresherId));
}
#endregion
#region Template cache
/// <summary>
/// Refreshes the cache amongst servers for a template
/// </summary>
/// <param name="dc"></param>
/// <param name="templateId"></param>
public static void RefreshTemplateCache(this DistributedCache dc, int templateId)
{
dc.Refresh(new Guid(DistributedCache.TemplateRefresherId), templateId);
}
/// <summary>
/// Removes the cache amongst servers for a template
/// </summary>
/// <param name="dc"></param>
/// <param name="templateId"></param>
public static void RemoveTemplateCache(this DistributedCache dc, int templateId)
{
dc.Remove(new Guid(DistributedCache.TemplateRefresherId), templateId);
}
#endregion
#region Dictionary cache
/// <summary>
/// Refreshes the cache amongst servers for a dictionary item
/// </summary>
/// <param name="dc"></param>
/// <param name="dictionaryItemId"></param>
public static void RefreshDictionaryCache(this DistributedCache dc, int dictionaryItemId)
{
dc.Refresh(new Guid(DistributedCache.DictionaryCacheRefresherId), dictionaryItemId);
}
/// <summary>
/// Refreshes the cache amongst servers for a dictionary item
/// </summary>
/// <param name="dc"></param>
/// <param name="dictionaryItemId"></param>
public static void RemoveDictionaryCache(this DistributedCache dc, int dictionaryItemId)
{
dc.Remove(new Guid(DistributedCache.DictionaryCacheRefresherId), dictionaryItemId);
}
#endregion
#region Data type cache
/// <summary>
/// Refreshes the cache amongst servers for a data type
/// </summary>
/// <param name="dc"></param>
/// <param name="dataType"></param>
public static void RefreshDataTypeCache(this DistributedCache dc, global::umbraco.cms.businesslogic.datatype.DataTypeDefinition dataType)
{
if (dataType != null)
{
dc.RefreshByJson(new Guid(DistributedCache.DataTypeCacheRefresherId),
DataTypeCacheRefresher.SerializeToJsonPayload(dataType));
}
}
/// <summary>
/// Removes the cache amongst servers for a data type
/// </summary>
/// <param name="dc"></param>
/// <param name="dataType"></param>
public static void RemoveDataTypeCache(this DistributedCache dc, global::umbraco.cms.businesslogic.datatype.DataTypeDefinition dataType)
{
if (dataType != null)
{
dc.RefreshByJson(new Guid(DistributedCache.DataTypeCacheRefresherId),
DataTypeCacheRefresher.SerializeToJsonPayload(dataType));
}
}
/// <summary>
/// Refreshes the cache amongst servers for a data type
/// </summary>
/// <param name="dc"></param>
/// <param name="dataType"></param>
public static void RefreshDataTypeCache(this DistributedCache dc, IDataTypeDefinition dataType)
{
if (dataType != null)
{
dc.RefreshByJson(new Guid(DistributedCache.DataTypeCacheRefresherId),
DataTypeCacheRefresher.SerializeToJsonPayload(dataType));
}
}
/// <summary>
/// Removes the cache amongst servers for a data type
/// </summary>
/// <param name="dc"></param>
/// <param name="dataType"></param>
public static void RemoveDataTypeCache(this DistributedCache dc, IDataTypeDefinition dataType)
{
if (dataType != null)
{
dc.RefreshByJson(new Guid(DistributedCache.DataTypeCacheRefresherId),
DataTypeCacheRefresher.SerializeToJsonPayload(dataType));
}
}
#endregion
#region Page cache
/// <summary>
/// Refreshes the cache amongst servers for all pages
/// </summary>
/// <param name="dc"></param>
public static void RefreshAllPageCache(this DistributedCache dc)
{
dc.RefreshAll(new Guid(DistributedCache.PageCacheRefresherId));
}
/// <summary>
/// Refreshes the cache amongst servers for a page
/// </summary>
/// <param name="dc"></param>
/// <param name="documentId"></param>
public static void RefreshPageCache(this DistributedCache dc, int documentId)
{
dc.Refresh(new Guid(DistributedCache.PageCacheRefresherId), documentId);
}
/// <summary>
/// Refreshes page cache for all instances passed in
/// </summary>
/// <param name="dc"></param>
/// <param name="content"></param>
public static void RefreshPageCache(this DistributedCache dc, params IContent[] content)
{
dc.Refresh(new Guid(DistributedCache.PageCacheRefresherId), x => x.Id, content);
}
/// <summary>
/// Removes the cache amongst servers for a page
/// </summary>
/// <param name="dc"></param>
/// <param name="content"></param>
public static void RemovePageCache(this DistributedCache dc, params IContent[] content)
{
dc.Remove(new Guid(DistributedCache.PageCacheRefresherId), x => x.Id, content);
}
/// <summary>
/// Removes the cache amongst servers for a page
/// </summary>
/// <param name="dc"></param>
/// <param name="documentId"></param>
public static void RemovePageCache(this DistributedCache dc, int documentId)
{
dc.Remove(new Guid(DistributedCache.PageCacheRefresherId), documentId);
}
#endregion
#region Member cache
/// <summary>
/// Refreshes the cache amongst servers for a member
/// </summary>
/// <param name="dc"></param>
/// <param name="memberId"></param>
public static void RefreshMemberCache(this DistributedCache dc, int memberId)
{
dc.Refresh(new Guid(DistributedCache.MemberCacheRefresherId), memberId);
}
/// <summary>
/// Removes the cache amongst servers for a member
/// </summary>
/// <param name="dc"></param>
/// <param name="memberId"></param>
public static void RemoveMemberCache(this DistributedCache dc, int memberId)
{
dc.Remove(new Guid(DistributedCache.MemberCacheRefresherId), memberId);
}
#endregion
#region Media Cache
/// <summary>
/// Refreshes the cache amongst servers for a media item
/// </summary>
/// <param name="dc"></param>
/// <param name="media"></param>
public static void RefreshMediaCache(this DistributedCache dc, params IMedia[] media)
{
dc.RefreshByJson(new Guid(DistributedCache.MediaCacheRefresherId),
MediaCacheRefresher.SerializeToJsonPayload(media));
}
/// <summary>
/// Removes the cache amongst servers for a media item
/// </summary>
/// <param name="dc"></param>
/// <param name="mediaId"></param>
/// <remarks>
/// Clearing by Id will never work for load balanced scenarios for media since we require a Path
/// to clear all of the cache but the media item will be removed before the other servers can
/// look it up. Only here for legacy purposes.
/// </remarks>
public static void RemoveMediaCache(this DistributedCache dc, int mediaId)
{
dc.Remove(new Guid(DistributedCache.MediaCacheRefresherId), mediaId);
}
/// <summary>
/// Removes the cache amongst servers for media items
/// </summary>
/// <param name="dc"></param>
/// <param name="media"></param>
public static void RemoveMediaCache(this DistributedCache dc, params IMedia[] media)
{
dc.RefreshByJson(new Guid(DistributedCache.MediaCacheRefresherId),
MediaCacheRefresher.SerializeToJsonPayload(media));
}
#endregion
#region Macro Cache
/// <summary>
/// Clears the cache for all macros on the current server
/// </summary>
/// <param name="dc"></param>
public static void ClearAllMacroCacheOnCurrentServer(this DistributedCache dc)
{
//NOTE: The 'false' ensure that it will only refresh on the current server, not post to all servers
dc.RefreshAll(new Guid(DistributedCache.MacroCacheRefresherId), false);
}
/// <summary>
/// Refreshes the cache amongst servers for a macro item
/// </summary>
/// <param name="dc"></param>
/// <param name="macro"></param>
public static void RefreshMacroCache(this DistributedCache dc, global::umbraco.cms.businesslogic.macro.Macro macro)
{
if (macro != null)
{
dc.RefreshByJson(new Guid(DistributedCache.MacroCacheRefresherId),
MacroCacheRefresher.SerializeToJsonPayload(macro));
}
}
/// <summary>
/// Removes the cache amongst servers for a macro item
/// </summary>
/// <param name="dc"></param>
/// <param name="macro"></param>
public static void RemoveMacroCache(this DistributedCache dc, global::umbraco.cms.businesslogic.macro.Macro macro)
{
if (macro != null)
{
dc.RefreshByJson(new Guid(DistributedCache.MacroCacheRefresherId),
MacroCacheRefresher.SerializeToJsonPayload(macro));
}
}
/// <summary>
/// Removes the cache amongst servers for a macro item
/// </summary>
/// <param name="dc"></param>
/// <param name="macro"></param>
public static void RemoveMacroCache(this DistributedCache dc, macro macro)
{
if (macro != null && macro.Model != null)
{
dc.RefreshByJson(new Guid(DistributedCache.MacroCacheRefresherId),
MacroCacheRefresher.SerializeToJsonPayload(macro));
}
}
#endregion
#region Content type cache
/// <summary>
/// Remove all cache for a given content type
/// </summary>
/// <param name="dc"></param>
/// <param name="contentType"></param>
public static void RefreshContentTypeCache(this DistributedCache dc, IContentType contentType)
{
if (contentType != null)
{
//dc.Refresh(new Guid(DistributedCache.ContentTypeCacheRefresherId), x => x.Id, contentType);
dc.RefreshByJson(new Guid(DistributedCache.ContentTypeCacheRefresherId),
ContentTypeCacheRefresher.SerializeToJsonPayload(false, contentType));
}
}
/// <summary>
/// Remove all cache for a given media type
/// </summary>
/// <param name="dc"></param>
/// <param name="mediaType"></param>
public static void RefreshMediaTypeCache(this DistributedCache dc, IMediaType mediaType)
{
if (mediaType != null)
{
//dc.Refresh(new Guid(DistributedCache.ContentTypeCacheRefresherId), x => x.Id, mediaType);
dc.RefreshByJson(new Guid(DistributedCache.ContentTypeCacheRefresherId),
ContentTypeCacheRefresher.SerializeToJsonPayload(false, mediaType));
}
}
/// <summary>
/// Remove all cache for a given content type
/// </summary>
/// <param name="dc"></param>
/// <param name="contentType"></param>
public static void RemoveContentTypeCache(this DistributedCache dc, IContentType contentType)
{
if (contentType != null)
{
//dc.Remove(new Guid(DistributedCache.ContentTypeCacheRefresherId), x => x.Id, contentType);
dc.RefreshByJson(new Guid(DistributedCache.ContentTypeCacheRefresherId),
ContentTypeCacheRefresher.SerializeToJsonPayload(true, contentType));
}
}
/// <summary>
/// Remove all cache for a given media type
/// </summary>
/// <param name="dc"></param>
/// <param name="mediaType"></param>
public static void RemoveMediaTypeCache(this DistributedCache dc, IMediaType mediaType)
{
if (mediaType != null)
{
//dc.Remove(new Guid(DistributedCache.ContentTypeCacheRefresherId), x => x.Id, mediaType);
dc.RefreshByJson(new Guid(DistributedCache.ContentTypeCacheRefresherId),
ContentTypeCacheRefresher.SerializeToJsonPayload(true, mediaType));
}
}
#endregion
#region Stylesheet Cache
public static void RefreshStylesheetPropertyCache(this DistributedCache dc, global::umbraco.cms.businesslogic.web.StylesheetProperty styleSheetProperty)
{
if (styleSheetProperty != null)
{
dc.Refresh(new Guid(DistributedCache.StylesheetPropertyCacheRefresherId), styleSheetProperty.Id);
}
}
public static void RemoveStylesheetPropertyCache(this DistributedCache dc, global::umbraco.cms.businesslogic.web.StylesheetProperty styleSheetProperty)
{
if (styleSheetProperty != null)
{
dc.Remove(new Guid(DistributedCache.StylesheetPropertyCacheRefresherId), styleSheetProperty.Id);
}
}
public static void RefreshStylesheetCache(this DistributedCache dc, StyleSheet styleSheet)
{
if (styleSheet != null)
{
dc.Refresh(new Guid(DistributedCache.StylesheetCacheRefresherId), styleSheet.Id);
}
}
public static void RemoveStylesheetCache(this DistributedCache dc, StyleSheet styleSheet)
{
if (styleSheet != null)
{
dc.Remove(new Guid(DistributedCache.StylesheetCacheRefresherId), styleSheet.Id);
}
}
public static void RefreshStylesheetCache(this DistributedCache dc, Umbraco.Core.Models.Stylesheet styleSheet)
{
if (styleSheet != null)
{
dc.Refresh(new Guid(DistributedCache.StylesheetCacheRefresherId), styleSheet.Id);
}
}
public static void RemoveStylesheetCache(this DistributedCache dc, Umbraco.Core.Models.Stylesheet styleSheet)
{
if (styleSheet != null)
{
dc.Remove(new Guid(DistributedCache.StylesheetCacheRefresherId), styleSheet.Id);
}
}
#endregion
#region Domain Cache
public static void RefreshDomainCache(this DistributedCache dc, Domain domain)
{
if (domain != null)
{
dc.Refresh(new Guid(DistributedCache.DomainCacheRefresherId), domain.Id);
}
}
public static void RemoveDomainCache(this DistributedCache dc, Domain domain)
{
if (domain != null)
{
dc.Remove(new Guid(DistributedCache.DomainCacheRefresherId), domain.Id);
}
}
#endregion
#region Language Cache
public static void RefreshLanguageCache(this DistributedCache dc, ILanguage language)
{
if (language != null)
{
dc.Refresh(new Guid(DistributedCache.LanguageCacheRefresherId), language.Id);
}
}
public static void RemoveLanguageCache(this DistributedCache dc, ILanguage language)
{
if (language != null)
{
dc.Remove(new Guid(DistributedCache.LanguageCacheRefresherId), language.Id);
}
}
public static void RefreshLanguageCache(this DistributedCache dc, global::umbraco.cms.businesslogic.language.Language language)
{
if (language != null)
{
dc.Refresh(new Guid(DistributedCache.LanguageCacheRefresherId), language.id);
}
}
public static void RemoveLanguageCache(this DistributedCache dc, global::umbraco.cms.businesslogic.language.Language language)
{
if (language != null)
{
dc.Remove(new Guid(DistributedCache.LanguageCacheRefresherId), language.id);
}
}
#endregion
public static void ClearXsltCacheOnCurrentServer(this DistributedCache dc)
{
if (UmbracoSettings.UmbracoLibraryCacheDuration > 0)
{
ApplicationContext.Current.ApplicationCache.ClearCacheObjectTypes("MS.Internal.Xml.XPath.XPathSelectionIterator");
}
}
}
}
| |
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Globalization;
using System.Runtime.InteropServices;
using Lightstreamer.DotNet.Client;
using DotNetStockListDemo.Properties;
namespace DotNetStockListDemo
{
public delegate void LightstreamerUpdateDelegate(int item, IUpdateInfo values);
public delegate void LightstreamerStatusChangedDelegate(int cStatus, string status);
public delegate void StopDelegate();
public delegate void BlinkOffDelegate(DataGridViewCell[] cells);
public partial class DemoForm : Form, IMessageFilter {
private static readonly Color blinkOnColor = Color.Yellow;
private static readonly Color blinkOffColor = Color.White;
private const long blinkTime = 300; // millisecs
private StocklistClient stocklistClient;
private ArrayList blinkingCells;
private bool blinkEnabled;
private bool blinkMenu;
private bool isDirty = false;
private string pushServerUrl;
#region API Declarations
[DllImport("user32.dll")]
private static extern int GetSystemMenu(int hwnd, bool bRevert);
[DllImport("user32.dll")]
private static extern long AppendMenuA(int hMenu, int wFlags, int wIDNewItem, string lpNewItem);
[DllImport("user32.dll")]
private static extern long RemoveMenu(int hMenu, int nPosition, int wFlags);
private const int MF_BYPOSITION = 1024;
private const int MF_SEPERATOR = 2048;
private const int MF_REMOVE = 4096;
private const int WM_SYSCOMMAND = 274;
private const int WM_KEYDOWN = 256;
#endregion // API Declarations
public DemoForm(string pushServerHost, int pushServerPort ) {
stocklistClient = null;
blinkingCells = new ArrayList();
blinkEnabled = true;
blinkMenu = false;
pushServerUrl = "http://" + pushServerHost + ":" + pushServerPort;
Thread t = new Thread(new ThreadStart(DeblinkingThread));
t.Start();
InitializeComponent();
}
private void OnFormLoaded(object sender, EventArgs e) {
for (int i = 0; i < 30; i++) {
dataGridview.Rows.Add();
}
dataGridview.Refresh();
Thread t = new Thread(new ThreadStart(StartLightstreamer));
t.Start();
}
private void OnFormClosed(object sender, FormClosedEventArgs e) {
Environment.Exit(0);
}
private void AddBlinkMenu() {
if (blinkMenu) return;
blinkMenu = true;
int sysMenuHandle = GetSysMenuHandle((int)Handle);
AppendSeperator(sysMenuHandle);
AppendSysMenu(sysMenuHandle, 54321, "Toggle cell blink effect");
}
private void StartLightstreamer() {
stocklistClient = new StocklistClient(
pushServerUrl,
this,
new LightstreamerUpdateDelegate(OnLightstreamerUpdate),
new LightstreamerStatusChangedDelegate(OnLightstreamerStatusChanged));
stocklistClient.Start();
}
private void OnLightstreamerUpdate(int item, IUpdateInfo values)
{
dataGridview.SuspendLayout();
if (this.isDirty)
{
this.isDirty = false;
CleanGrid();
}
DataGridViewRow row = dataGridview.Rows[item - 1];
ArrayList cells = new ArrayList();
int len = values.NumFields;
for (int i = 0; i < len; i++) {
if (values.IsValueChanged(i + 1)) {
string val = values.GetNewValue(i + 1);
DataGridViewCell cell = row.Cells[i];
switch (i) {
case 1: // last_price
case 5: // bid
case 6: // ask
case 8: // min
case 9: // max
case 10: // ref_price
case 11: // open_price
double dVal = Double.Parse(val, CultureInfo.GetCultureInfo("en-US").NumberFormat);
cell.Value = dVal;
break;
case 3: // pct_change
double dVal2 = Double.Parse(val, CultureInfo.GetCultureInfo("en-US").NumberFormat);
cell.Value = dVal2;
cell.Style.ForeColor = ((dVal2 < 0.0) ? Color.Red : Color.Green);
break;
case 4: // bid_quantity
case 7: // ask_quantity
int lVal = Int32.Parse(val);
cell.Value = lVal;
break;
case 2: // time
DateTime dtVal = DateTime.Parse(val);
cell.Value = dtVal;
break;
default: // stock_name, ...
cell.Value = val;
break;
}
if (blinkEnabled) {
cell.Style.BackColor = blinkOnColor;
cells.Add(cell);
}
}
}
dataGridview.ResumeLayout();
if (blinkEnabled) {
long now = DateTime.Now.Ticks;
ScheduleBlinkOff(cells, now);
}
}
private void OnLightstreamerStatusChanged(int cStatus, string status) {
statusLabel.Text = status;
switch (cStatus)
{
case StocklistConnectionListener.STREAMING:
statusImg.Image = Resources.status_connected_streaming;
break;
case StocklistConnectionListener.POLLING:
statusImg.Image = Resources.status_connected_polling;
break;
case StocklistConnectionListener.STALLED:
statusImg.Image = Resources.status_stalled;
break;
case StocklistConnectionListener.DISCONNECTED:
this.isDirty = true;
statusImg.Image = Resources.status_disconnected;
break;
default:
break;
}
this.Refresh();
}
private void CleanGrid() {
for (int row = 0; row < dataGridview.Rows.Count; row++)
{
for (int col = 0; col < dataGridview.Rows[row].Cells.Count; col++)
{
dataGridview.Rows[row].Cells[col].Value = "";
}
}
}
private class BlinkingCell {
public readonly DataGridViewCell cell;
public readonly long timestamp;
public BlinkingCell(DataGridViewCell dataGridviewCell, long blinkOnTimestamp) {
cell = dataGridviewCell;
timestamp = blinkOnTimestamp;
}
}
private void ScheduleBlinkOff(ArrayList cells, long blinkOnTimestamp) {
lock (blinkingCells) {
for (int j = 0; j < cells.Count; j++) {
DataGridViewCell cell = (DataGridViewCell)cells[j];
blinkingCells.Add(new BlinkingCell(cell, blinkOnTimestamp));
}
Monitor.Pulse(blinkingCells);
}
}
private void BlinkOff(DataGridViewCell[] cells) {
dataGridview.SuspendLayout();
for (int i = 0; i < cells.Length; i++) {
cells[i].Style.BackColor = blinkOffColor;
}
dataGridview.ResumeLayout();
}
private void DeblinkingThread() {
ArrayList expiredBlinkingCells = new ArrayList();
do {
expiredBlinkingCells.Clear();
lock (blinkingCells) {
if (blinkingCells.Count == 0)
Monitor.Wait(blinkingCells);
expiredBlinkingCells.AddRange(blinkingCells);
blinkingCells.Clear();
}
DataGridViewCell[] cells = new DataGridViewCell[expiredBlinkingCells.Count];
for (int i = 0; i < expiredBlinkingCells.Count; i++) {
cells[i] = ((BlinkingCell)expiredBlinkingCells[i]).cell;
}
BlinkingCell lastBlinkingCell = (BlinkingCell)expiredBlinkingCells[expiredBlinkingCells.Count - 1];
long now = DateTime.Now.Ticks;
long diff = (now - lastBlinkingCell.timestamp) / 10000; // millisecs
if (diff < blinkTime)
Thread.Sleep((int)(blinkTime - diff));
Invoke(new BlinkOffDelegate(BlinkOff), new object[] { cells });
} while (true);
}
#region System Menu API
public int GetSysMenuHandle(int frmHandle) {
return GetSystemMenu(frmHandle, false);
}
private long RemoveSysMenu(int mnuHandle, int mnuPosition) {
return RemoveMenu(mnuHandle, mnuPosition, MF_REMOVE);
}
private long AppendSysMenu(int mnuHandle, int MenuID, string mnuText) {
return AppendMenuA(mnuHandle, 0, MenuID, mnuText);
}
private long AppendSeperator(int mnuHandle) {
return AppendMenuA(mnuHandle, MF_SEPERATOR, 0, null);
}
public bool PreFilterMessage(ref Message msg) {
switch (msg.Msg) {
case WM_KEYDOWN:
Keys key = ((Keys)msg.WParam.ToInt32()) & Keys.KeyCode;
switch (key) {
case Keys.F12:
AddBlinkMenu();
break;
}
break;
}
return false;
}
protected override void WndProc(ref Message messg) {
switch (messg.Msg) {
case WM_SYSCOMMAND:
switch (messg.WParam.ToInt32()) {
case 54321:
blinkEnabled = !blinkEnabled;
break;
}
break;
}
base.WndProc(ref messg);
}
#endregion // System Menu API
}
}
| |
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 csv_import.webapi.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;
}
}
}
| |
#region LGPL License
/*
Axiom Game Engine Library
Copyright (C) 2003 Axiom Project Team
The overall design, and a majority of the core engine and rendering code
contained within this library is a derivative of the open source Object Oriented
Graphics Engine OGRE, which can be found at http://ogre.sourceforge.net.
Many thanks to the OGRE team for maintaining such a high quality project.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#endregion
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace Axiom.Graphics {
/// <summary>
/// Summary description for SoftwareBufferManager.
/// </summary>
// TODO: Switch go using GCHandle for array pointer after resolving stack overflow in TerrainSceneManager.
public class SoftwareBufferManager : HardwareBufferManager {
#region Methods
/// <summary>
///
/// </summary>
/// <param name="type"></param>
/// <param name="numIndices"></param>
/// <param name="usage"></param>
/// <returns></returns>
/// DOC
public override HardwareIndexBuffer CreateIndexBuffer(IndexType type, int numIndices, BufferUsage usage) {
return new SoftwareIndexBuffer(type, numIndices, usage);
}
/// <summary>
///
/// </summary>
/// <param name="type"></param>
/// <param name="numIndices"></param>
/// <param name="usage"></param>
/// <param name="useShadowBuffer"></param>
/// <returns></returns>
/// DOC
public override HardwareIndexBuffer CreateIndexBuffer(IndexType type, int numIndices, BufferUsage usage, bool useShadowBuffer) {
return new SoftwareIndexBuffer(type, numIndices, usage);
}
/// <summary>
///
/// </summary>
/// <param name="vertexSize"></param>
/// <param name="numVerts"></param>
/// <param name="usage"></param>
/// <returns></returns>
/// DOC
public override HardwareVertexBuffer CreateVertexBuffer(int vertexSize, int numVerts, BufferUsage usage) {
return new SoftwareVertexBuffer(vertexSize, numVerts, usage);
}
/// <summary>
///
/// </summary>
/// <param name="vertexSize"></param>
/// <param name="numVerts"></param>
/// <param name="usage"></param>
/// <param name="useShadowBuffer"></param>
/// <returns></returns>
/// DOC
public override HardwareVertexBuffer CreateVertexBuffer(int vertexSize, int numVerts, BufferUsage usage, bool useShadowBuffer) {
return new SoftwareVertexBuffer(vertexSize, numVerts, usage);
}
#endregion
#region Properties
#endregion
}
/// <summary>
///
/// </summary>
public class SoftwareVertexBuffer : HardwareVertexBuffer {
#region Fields
/// <summary>
/// Holds the buffer data.
/// </summary>
protected byte[] data;
protected GCHandle handle;
#endregion Fields
#region Constructors
/// <summary>
///
/// </summary>
/// <remarks>
/// This is already in system memory, so no need to use a shadow buffer.
/// </remarks>
/// <param name="vertexSize"></param>
/// <param name="numVertices"></param>
/// <param name="usage"></param>
/// DOC
public SoftwareVertexBuffer(int vertexSize, int numVertices, BufferUsage usage)
: base(vertexSize, numVertices, usage, true, false) {
data = new byte[sizeInBytes];
}
#endregion
#region Methods
public override IntPtr Lock(int offset, int length, BufferLocking locking) {
isLocked = true;
// return the offset into the array as a pointer
// return Marshal.UnsafeAddrOfPinnedArrayElement(data, offset);
handle = GCHandle.Alloc(data, GCHandleType.Pinned);
return handle.AddrOfPinnedObject();
}
protected override IntPtr LockImpl(int offset, int length, BufferLocking locking) {
isLocked = true;
// return the offset into the array as a pointer
// return Marshal.UnsafeAddrOfPinnedArrayElement(data, offset);
handle = GCHandle.Alloc(data, GCHandleType.Pinned);
return handle.AddrOfPinnedObject();
}
public override void ReadData(int offset, int length, IntPtr dest) {
Debug.Assert((offset + length) <= sizeInBytes, "Buffer overrun while trying to read a software buffer.");
unsafe {
// get a pointer to the destination intptr
byte* pDest = (byte*)dest.ToPointer();
// copy the src data to the destination buffer
for (int i = 0; i < length; i++) {
pDest[offset + i] = data[offset + i];
}
}
}
public override void Unlock() {
isLocked = false;
handle.Free();
}
public override void UnlockImpl() {
isLocked = false;
handle.Free();
}
public override void WriteData(int offset, int length, IntPtr src, bool discardWholeBuffer) {
Debug.Assert((offset + length) <= sizeInBytes, "Buffer overrun while trying to write to a software buffer.");
unsafe {
// get a pointer to the destination intptr
byte* pSrc = (byte*)src.ToPointer();
// copy the src data to the destination buffer
for (int i = 0; i < length; i++) {
data[offset + i] = pSrc[offset + i];
}
}
}
/// <summary>
/// Allows direct access to the software buffer data in cases when it is known that the underlying
/// buffer is software and not hardware.
/// </summary>
public IntPtr GetDataPointer(int offset) {
return Marshal.UnsafeAddrOfPinnedArrayElement(data, offset);
//return handle.AddrOfPinnedObject();
}
#endregion
}
/// <summary>
///
/// </summary>
public class SoftwareIndexBuffer : HardwareIndexBuffer {
#region Member variables
/// <summary>
/// Holds the buffer data.
/// </summary>
protected byte[] data;
#endregion
#region Constructors
/// <summary>
///
/// </summary>
/// <remarks>
/// This is already in system memory, so no need to use a shadow buffer.
/// </remarks>
/// <param name="type"></param>
/// <param name="numIndices"></param>
/// <param name="usage"></param>
/// DOC
public SoftwareIndexBuffer(IndexType type, int numIndices, BufferUsage usage)
: base(type, numIndices, usage, true, false) {
data = new byte[sizeInBytes];
}
#endregion
#region Methods
public override IntPtr Lock(int offset, int length, BufferLocking locking) {
isLocked = true;
// return the offset into the array as a pointer
return Marshal.UnsafeAddrOfPinnedArrayElement(data, offset);
}
protected override IntPtr LockImpl(int offset, int length, BufferLocking locking) {
isLocked = true;
// return the offset into the array as a pointer
return Marshal.UnsafeAddrOfPinnedArrayElement(data, offset);
}
public override void ReadData(int offset, int length, IntPtr dest) {
Debug.Assert((offset + length) <= sizeInBytes, "Buffer overrun while trying to read a software buffer.");
unsafe {
// get a pointer to the destination intptr
byte* pDest = (byte*)dest.ToPointer();
// copy the src data to the destination buffer
for (int i = 0; i < length; i++) {
pDest[offset + i] = data[offset + i];
}
}
}
public override void Unlock() {
isLocked = false;
}
public override void UnlockImpl() {
isLocked = false;
}
public override void WriteData(int offset, int length, IntPtr src, bool discardWholeBuffer) {
Debug.Assert((offset + length) <= sizeInBytes, "Buffer overrun while trying to write to a software buffer.");
unsafe {
// get a pointer to the destination intptr
byte* pSrc = (byte*)src.ToPointer();
// copy the src data to the destination buffer
for (int i = 0; i < length; i++) {
data[offset + i] = pSrc[offset + i];
}
}
}
/// <summary>
/// Allows direct access to the software buffer data in cases when it is known that the underlying
/// buffer is software and not hardware.
/// </summary>
public IntPtr GetDataPointer(int offset) {
return Marshal.UnsafeAddrOfPinnedArrayElement(data, offset);
}
#endregion
}
}
| |
#region Apache License
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to you under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System;
using System.Collections;
#if !NETSTANDARD1_3
using System.Configuration;
#endif
using System.Diagnostics;
namespace log4net.Util
{
/// <summary>
///
/// </summary>
/// <param name="source"></param>
/// <param name="e"></param>
public delegate void LogReceivedEventHandler(object source, LogReceivedEventArgs e);
/// <summary>
/// Outputs log statements from within the log4net assembly.
/// </summary>
/// <remarks>
/// <para>
/// Log4net components cannot make log4net logging calls. However, it is
/// sometimes useful for the user to learn about what log4net is
/// doing.
/// </para>
/// <para>
/// All log4net internal debug calls go to the standard output stream
/// whereas internal error messages are sent to the standard error output
/// stream.
/// </para>
/// </remarks>
/// <author>Nicko Cadell</author>
/// <author>Gert Driesen</author>
public sealed class LogLog
{
/// <summary>
/// The event raised when an internal message has been received.
/// </summary>
public static event LogReceivedEventHandler LogReceived;
private readonly Type source;
private readonly DateTime timeStampUtc;
private readonly string prefix;
private readonly string message;
private readonly Exception exception;
/// <summary>
/// The Type that generated the internal message.
/// </summary>
public Type Source
{
get { return source; }
}
/// <summary>
/// The DateTime stamp of when the internal message was received.
/// </summary>
public DateTime TimeStamp
{
get { return timeStampUtc.ToLocalTime(); }
}
/// <summary>
/// The UTC DateTime stamp of when the internal message was received.
/// </summary>
public DateTime TimeStampUtc
{
get { return timeStampUtc; }
}
/// <summary>
/// A string indicating the severity of the internal message.
/// </summary>
/// <remarks>
/// "log4net: ",
/// "log4net:ERROR ",
/// "log4net:WARN "
/// </remarks>
public string Prefix
{
get { return prefix; }
}
/// <summary>
/// The internal log message.
/// </summary>
public string Message
{
get { return message; }
}
/// <summary>
/// The Exception related to the message.
/// </summary>
/// <remarks>
/// Optional. Will be null if no Exception was passed.
/// </remarks>
public Exception Exception
{
get { return exception; }
}
/// <summary>
/// Formats Prefix, Source, and Message in the same format as the value
/// sent to Console.Out and Trace.Write.
/// </summary>
/// <returns></returns>
public override string ToString()
{
return Prefix + Source.Name + ": " + Message;
}
#region Private Instance Constructors
/// <summary>
/// Initializes a new instance of the <see cref="LogLog" /> class.
/// </summary>
/// <param name="source"></param>
/// <param name="prefix"></param>
/// <param name="message"></param>
/// <param name="exception"></param>
public LogLog(Type source, string prefix, string message, Exception exception)
{
timeStampUtc = DateTime.UtcNow;
this.source = source;
this.prefix = prefix;
this.message = message;
this.exception = exception;
}
#endregion Private Instance Constructors
#region Static Constructor
/// <summary>
/// Static constructor that initializes logging by reading
/// settings from the application configuration file.
/// </summary>
/// <remarks>
/// <para>
/// The <c>log4net.Internal.Debug</c> application setting
/// controls internal debugging. This setting should be set
/// to <c>true</c> to enable debugging.
/// </para>
/// <para>
/// The <c>log4net.Internal.Quiet</c> application setting
/// suppresses all internal logging including error messages.
/// This setting should be set to <c>true</c> to enable message
/// suppression.
/// </para>
/// </remarks>
static LogLog()
{
#if !NETCF
try
{
InternalDebugging = OptionConverter.ToBoolean(SystemInfo.GetAppSetting("log4net.Internal.Debug"), false);
QuietMode = OptionConverter.ToBoolean(SystemInfo.GetAppSetting("log4net.Internal.Quiet"), false);
EmitInternalMessages = OptionConverter.ToBoolean(SystemInfo.GetAppSetting("log4net.Internal.Emit"), true);
}
catch(Exception ex)
{
// If an exception is thrown here then it looks like the config file does not
// parse correctly.
//
// We will leave debug OFF and print an Error message
Error(typeof(LogLog), "Exception while reading ConfigurationSettings. Check your .config file is well formed XML.", ex);
}
#endif
}
#endregion Static Constructor
#region Public Static Properties
/// <summary>
/// Gets or sets a value indicating whether log4net internal logging
/// is enabled or disabled.
/// </summary>
/// <value>
/// <c>true</c> if log4net internal logging is enabled, otherwise
/// <c>false</c>.
/// </value>
/// <remarks>
/// <para>
/// When set to <c>true</c>, internal debug level logging will be
/// displayed.
/// </para>
/// <para>
/// This value can be set by setting the application setting
/// <c>log4net.Internal.Debug</c> in the application configuration
/// file.
/// </para>
/// <para>
/// The default value is <c>false</c>, i.e. debugging is
/// disabled.
/// </para>
/// </remarks>
/// <example>
/// <para>
/// The following example enables internal debugging using the
/// application configuration file :
/// </para>
/// <code lang="XML" escaped="true">
/// <configuration>
/// <appSettings>
/// <add key="log4net.Internal.Debug" value="true" />
/// </appSettings>
/// </configuration>
/// </code>
/// </example>
public static bool InternalDebugging
{
get { return s_debugEnabled; }
set { s_debugEnabled = value; }
}
/// <summary>
/// Gets or sets a value indicating whether log4net should generate no output
/// from internal logging, not even for errors.
/// </summary>
/// <value>
/// <c>true</c> if log4net should generate no output at all from internal
/// logging, otherwise <c>false</c>.
/// </value>
/// <remarks>
/// <para>
/// When set to <c>true</c> will cause internal logging at all levels to be
/// suppressed. This means that no warning or error reports will be logged.
/// This option overrides the <see cref="InternalDebugging"/> setting and
/// disables all debug also.
/// </para>
/// <para>This value can be set by setting the application setting
/// <c>log4net.Internal.Quiet</c> in the application configuration file.
/// </para>
/// <para>
/// The default value is <c>false</c>, i.e. internal logging is not
/// disabled.
/// </para>
/// </remarks>
/// <example>
/// The following example disables internal logging using the
/// application configuration file :
/// <code lang="XML" escaped="true">
/// <configuration>
/// <appSettings>
/// <add key="log4net.Internal.Quiet" value="true" />
/// </appSettings>
/// </configuration>
/// </code>
/// </example>
public static bool QuietMode
{
get { return s_quietMode; }
set { s_quietMode = value; }
}
/// <summary>
///
/// </summary>
public static bool EmitInternalMessages
{
get { return s_emitInternalMessages; }
set { s_emitInternalMessages = value; }
}
#endregion Public Static Properties
#region Public Static Methods
/// <summary>
/// Raises the LogReceived event when an internal messages is received.
/// </summary>
/// <param name="source"></param>
/// <param name="prefix"></param>
/// <param name="message"></param>
/// <param name="exception"></param>
public static void OnLogReceived(Type source, string prefix, string message, Exception exception)
{
if (LogReceived != null)
{
LogReceived(null, new LogReceivedEventArgs(new LogLog(source, prefix, message, exception)));
}
}
/// <summary>
/// Test if LogLog.Debug is enabled for output.
/// </summary>
/// <value>
/// <c>true</c> if Debug is enabled
/// </value>
/// <remarks>
/// <para>
/// Test if LogLog.Debug is enabled for output.
/// </para>
/// </remarks>
public static bool IsDebugEnabled
{
get { return s_debugEnabled && !s_quietMode; }
}
/// <summary>
/// Writes log4net internal debug messages to the
/// standard output stream.
/// </summary>
/// <param name="source"></param>
/// <param name="message">The message to log.</param>
/// <remarks>
/// <para>
/// All internal debug messages are prepended with
/// the string "log4net: ".
/// </para>
/// </remarks>
public static void Debug(Type source, string message)
{
if (IsDebugEnabled)
{
if (EmitInternalMessages)
{
EmitOutLine(PREFIX + message);
}
OnLogReceived(source, PREFIX, message, null);
}
}
/// <summary>
/// Writes log4net internal debug messages to the
/// standard output stream.
/// </summary>
/// <param name="source">The Type that generated this message.</param>
/// <param name="message">The message to log.</param>
/// <param name="exception">An exception to log.</param>
/// <remarks>
/// <para>
/// All internal debug messages are prepended with
/// the string "log4net: ".
/// </para>
/// </remarks>
public static void Debug(Type source, string message, Exception exception)
{
if (IsDebugEnabled)
{
if (EmitInternalMessages)
{
EmitOutLine(PREFIX + message);
if (exception != null)
{
EmitOutLine(exception.ToString());
}
}
OnLogReceived(source, PREFIX, message, exception);
}
}
/// <summary>
/// Test if LogLog.Warn is enabled for output.
/// </summary>
/// <value>
/// <c>true</c> if Warn is enabled
/// </value>
/// <remarks>
/// <para>
/// Test if LogLog.Warn is enabled for output.
/// </para>
/// </remarks>
public static bool IsWarnEnabled
{
get { return !s_quietMode; }
}
/// <summary>
/// Writes log4net internal warning messages to the
/// standard error stream.
/// </summary>
/// <param name="source">The Type that generated this message.</param>
/// <param name="message">The message to log.</param>
/// <remarks>
/// <para>
/// All internal warning messages are prepended with
/// the string "log4net:WARN ".
/// </para>
/// </remarks>
public static void Warn(Type source, string message)
{
if (IsWarnEnabled)
{
if (EmitInternalMessages)
{
EmitErrorLine(WARN_PREFIX + message);
}
OnLogReceived(source, WARN_PREFIX, message, null);
}
}
/// <summary>
/// Writes log4net internal warning messages to the
/// standard error stream.
/// </summary>
/// <param name="source">The Type that generated this message.</param>
/// <param name="message">The message to log.</param>
/// <param name="exception">An exception to log.</param>
/// <remarks>
/// <para>
/// All internal warning messages are prepended with
/// the string "log4net:WARN ".
/// </para>
/// </remarks>
public static void Warn(Type source, string message, Exception exception)
{
if (IsWarnEnabled)
{
if (EmitInternalMessages)
{
EmitErrorLine(WARN_PREFIX + message);
if (exception != null)
{
EmitErrorLine(exception.ToString());
}
}
OnLogReceived(source, WARN_PREFIX, message, exception);
}
}
/// <summary>
/// Test if LogLog.Error is enabled for output.
/// </summary>
/// <value>
/// <c>true</c> if Error is enabled
/// </value>
/// <remarks>
/// <para>
/// Test if LogLog.Error is enabled for output.
/// </para>
/// </remarks>
public static bool IsErrorEnabled
{
get { return !s_quietMode; }
}
/// <summary>
/// Writes log4net internal error messages to the
/// standard error stream.
/// </summary>
/// <param name="source">The Type that generated this message.</param>
/// <param name="message">The message to log.</param>
/// <remarks>
/// <para>
/// All internal error messages are prepended with
/// the string "log4net:ERROR ".
/// </para>
/// </remarks>
public static void Error(Type source, string message)
{
if (IsErrorEnabled)
{
if (EmitInternalMessages)
{
EmitErrorLine(ERR_PREFIX + message);
}
OnLogReceived(source, ERR_PREFIX, message, null);
}
}
/// <summary>
/// Writes log4net internal error messages to the
/// standard error stream.
/// </summary>
/// <param name="source">The Type that generated this message.</param>
/// <param name="message">The message to log.</param>
/// <param name="exception">An exception to log.</param>
/// <remarks>
/// <para>
/// All internal debug messages are prepended with
/// the string "log4net:ERROR ".
/// </para>
/// </remarks>
public static void Error(Type source, string message, Exception exception)
{
if (IsErrorEnabled)
{
if (EmitInternalMessages)
{
EmitErrorLine(ERR_PREFIX + message);
if (exception != null)
{
EmitErrorLine(exception.ToString());
}
}
OnLogReceived(source, ERR_PREFIX, message, exception);
}
}
#endregion Public Static Methods
/// <summary>
/// Writes output to the standard output stream.
/// </summary>
/// <param name="message">The message to log.</param>
/// <remarks>
/// <para>
/// Writes to both Console.Out and System.Diagnostics.Trace.
/// Note that the System.Diagnostics.Trace is not supported
/// on the Compact Framework.
/// </para>
/// <para>
/// If the AppDomain is not configured with a config file then
/// the call to System.Diagnostics.Trace may fail. This is only
/// an issue if you are programmatically creating your own AppDomains.
/// </para>
/// </remarks>
private static void EmitOutLine(string message)
{
try
{
#if NETCF
Console.WriteLine(message);
//System.Diagnostics.Debug.WriteLine(message);
#else
Console.Out.WriteLine(message);
Trace.WriteLine(message);
#endif
}
catch
{
// Ignore exception, what else can we do? Not really a good idea to propagate back to the caller
}
}
/// <summary>
/// Writes output to the standard error stream.
/// </summary>
/// <param name="message">The message to log.</param>
/// <remarks>
/// <para>
/// Writes to both Console.Error and System.Diagnostics.Trace.
/// Note that the System.Diagnostics.Trace is not supported
/// on the Compact Framework.
/// </para>
/// <para>
/// If the AppDomain is not configured with a config file then
/// the call to System.Diagnostics.Trace may fail. This is only
/// an issue if you are programmatically creating your own AppDomains.
/// </para>
/// </remarks>
private static void EmitErrorLine(string message)
{
try
{
#if NETCF
Console.WriteLine(message);
//System.Diagnostics.Debug.WriteLine(message);
#else
Console.Error.WriteLine(message);
Trace.WriteLine(message);
#endif
}
catch
{
// Ignore exception, what else can we do? Not really a good idea to propagate back to the caller
}
}
#region Private Static Fields
/// <summary>
/// Default debug level
/// </summary>
private static bool s_debugEnabled = false;
/// <summary>
/// In quietMode not even errors generate any output.
/// </summary>
private static bool s_quietMode = false;
private static bool s_emitInternalMessages = true;
private const string PREFIX = "log4net: ";
private const string ERR_PREFIX = "log4net:ERROR ";
private const string WARN_PREFIX = "log4net:WARN ";
#endregion Private Static Fields
/// <summary>
/// Subscribes to the LogLog.LogReceived event and stores messages
/// to the supplied IList instance.
/// </summary>
public class LogReceivedAdapter : IDisposable
{
private readonly IList items;
private readonly LogReceivedEventHandler handler;
/// <summary>
///
/// </summary>
/// <param name="items"></param>
public LogReceivedAdapter(IList items)
{
this.items = items;
handler = new LogReceivedEventHandler(LogLog_LogReceived);
LogReceived += handler;
}
void LogLog_LogReceived(object source, LogReceivedEventArgs e)
{
items.Add(e.LogLog);
}
/// <summary>
///
/// </summary>
public IList Items
{
get { return items; }
}
/// <summary>
///
/// </summary>
public void Dispose()
{
LogReceived -= handler;
}
}
}
/// <summary>
///
/// </summary>
public class LogReceivedEventArgs : EventArgs
{
private readonly LogLog loglog;
/// <summary>
///
/// </summary>
/// <param name="loglog"></param>
public LogReceivedEventArgs(LogLog loglog)
{
this.loglog = loglog;
}
/// <summary>
///
/// </summary>
public LogLog LogLog
{
get { return loglog; }
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.DataFactory
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// PipelineRunsOperations operations.
/// </summary>
internal partial class PipelineRunsOperations : IServiceOperations<DataFactoryManagementClient>, IPipelineRunsOperations
{
/// <summary>
/// Initializes a new instance of the PipelineRunsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal PipelineRunsOperations(DataFactoryManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the DataFactoryManagementClient
/// </summary>
public DataFactoryManagementClient Client { get; private set; }
/// <summary>
/// Query pipeline runs in the factory based on input filter conditions.
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='factoryName'>
/// The factory name.
/// </param>
/// <param name='filterParameters'>
/// Parameters to filter the pipeline run.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<PipelineRunQueryResponse>> QueryByFactoryWithHttpMessagesAsync(string resourceGroupName, string factoryName, PipelineRunFilterParameters filterParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (resourceGroupName != null)
{
if (resourceGroupName.Length > 90)
{
throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90);
}
if (resourceGroupName.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+$"))
{
throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+$");
}
}
if (factoryName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "factoryName");
}
if (factoryName != null)
{
if (factoryName.Length > 63)
{
throw new ValidationException(ValidationRules.MaxLength, "factoryName", 63);
}
if (factoryName.Length < 3)
{
throw new ValidationException(ValidationRules.MinLength, "factoryName", 3);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(factoryName, "^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$"))
{
throw new ValidationException(ValidationRules.Pattern, "factoryName", "^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$");
}
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (filterParameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "filterParameters");
}
if (filterParameters != null)
{
filterParameters.Validate();
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("factoryName", factoryName);
tracingParameters.Add("filterParameters", filterParameters);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "QueryByFactory", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataFactory/factories/{factoryName}/pipelineruns").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{factoryName}", System.Uri.EscapeDataString(factoryName));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(filterParameters != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(filterParameters, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.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<PipelineRunQueryResponse>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<PipelineRunQueryResponse>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get a pipeline run by its run ID.
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='factoryName'>
/// The factory name.
/// </param>
/// <param name='runId'>
/// The pipeline run identifier.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<PipelineRun>> GetWithHttpMessagesAsync(string resourceGroupName, string factoryName, string runId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (resourceGroupName != null)
{
if (resourceGroupName.Length > 90)
{
throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90);
}
if (resourceGroupName.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+$"))
{
throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+$");
}
}
if (factoryName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "factoryName");
}
if (factoryName != null)
{
if (factoryName.Length > 63)
{
throw new ValidationException(ValidationRules.MaxLength, "factoryName", 63);
}
if (factoryName.Length < 3)
{
throw new ValidationException(ValidationRules.MinLength, "factoryName", 3);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(factoryName, "^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$"))
{
throw new ValidationException(ValidationRules.Pattern, "factoryName", "^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$");
}
}
if (runId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "runId");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("factoryName", factoryName);
tracingParameters.Add("runId", runId);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataFactory/factories/{factoryName}/pipelineruns/{runId}").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{factoryName}", System.Uri.EscapeDataString(factoryName));
_url = _url.Replace("{runId}", System.Uri.EscapeDataString(runId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.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<PipelineRun>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<PipelineRun>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
namespace EffectEditor.Controls
{
partial class ComponentParameterList
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.parameterListBox = new System.Windows.Forms.ListBox();
this.paramTypeBox = new System.Windows.Forms.ComboBox();
this.paramNameBox = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.paramTypeSizeBox = new System.Windows.Forms.ComboBox();
this.paramTypeSizeA = new System.Windows.Forms.NumericUpDown();
this.paramTypeSizeB = new System.Windows.Forms.NumericUpDown();
this.paramSizeDividerLabel = new System.Windows.Forms.Label();
this.paramEditPanel = new System.Windows.Forms.Panel();
this.semanticNumberBox = new System.Windows.Forms.NumericUpDown();
this.semanticBox = new System.Windows.Forms.ComboBox();
this.semanticLabel = new System.Windows.Forms.Label();
this.storageClassBox = new System.Windows.Forms.ComboBox();
this.storageClassLabel = new System.Windows.Forms.Label();
this.newParamButton = new System.Windows.Forms.Button();
this.deleteParamButton = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.paramTypeSizeA)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.paramTypeSizeB)).BeginInit();
this.paramEditPanel.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.semanticNumberBox)).BeginInit();
this.SuspendLayout();
//
// parameterListBox
//
this.parameterListBox.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.parameterListBox.FormattingEnabled = true;
this.parameterListBox.Location = new System.Drawing.Point(0, 0);
this.parameterListBox.Name = "parameterListBox";
this.parameterListBox.Size = new System.Drawing.Size(244, 277);
this.parameterListBox.TabIndex = 0;
this.parameterListBox.SelectedIndexChanged += new System.EventHandler(this.parameterListBox_SelectedIndexChanged);
//
// paramTypeBox
//
this.paramTypeBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.paramTypeBox.FormattingEnabled = true;
this.paramTypeBox.Location = new System.Drawing.Point(47, 29);
this.paramTypeBox.Name = "paramTypeBox";
this.paramTypeBox.Size = new System.Drawing.Size(194, 21);
this.paramTypeBox.TabIndex = 1;
this.paramTypeBox.SelectedIndexChanged += new System.EventHandler(this.paramTypeBox_SelectedIndexChanged);
//
// paramNameBox
//
this.paramNameBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.paramNameBox.Location = new System.Drawing.Point(47, 3);
this.paramNameBox.Name = "paramNameBox";
this.paramNameBox.Size = new System.Drawing.Size(197, 20);
this.paramNameBox.TabIndex = 2;
this.paramNameBox.TextChanged += new System.EventHandler(this.paramEdited);
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(6, 6);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(35, 13);
this.label1.TabIndex = 3;
this.label1.Text = "Name";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(6, 32);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(31, 13);
this.label2.TabIndex = 4;
this.label2.Text = "Type";
//
// paramTypeSizeBox
//
this.paramTypeSizeBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.paramTypeSizeBox.FormattingEnabled = true;
this.paramTypeSizeBox.Items.AddRange(new object[] {
"Scalar",
"Vector",
"Matrix",
"Array"});
this.paramTypeSizeBox.Location = new System.Drawing.Point(47, 56);
this.paramTypeSizeBox.Name = "paramTypeSizeBox";
this.paramTypeSizeBox.Size = new System.Drawing.Size(94, 21);
this.paramTypeSizeBox.TabIndex = 5;
this.paramTypeSizeBox.Text = "Scalar";
this.paramTypeSizeBox.SelectedIndexChanged += new System.EventHandler(this.paramTypeSizeBox_SelectedIndexChanged);
//
// paramTypeSizeA
//
this.paramTypeSizeA.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.paramTypeSizeA.Location = new System.Drawing.Point(148, 56);
this.paramTypeSizeA.Maximum = new decimal(new int[] {
4,
0,
0,
0});
this.paramTypeSizeA.Minimum = new decimal(new int[] {
1,
0,
0,
0});
this.paramTypeSizeA.Name = "paramTypeSizeA";
this.paramTypeSizeA.Size = new System.Drawing.Size(35, 20);
this.paramTypeSizeA.TabIndex = 6;
this.paramTypeSizeA.Value = new decimal(new int[] {
1,
0,
0,
0});
this.paramTypeSizeA.Visible = false;
this.paramTypeSizeA.ValueChanged += new System.EventHandler(this.paramEdited);
//
// paramTypeSizeB
//
this.paramTypeSizeB.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.paramTypeSizeB.Location = new System.Drawing.Point(206, 56);
this.paramTypeSizeB.Maximum = new decimal(new int[] {
4,
0,
0,
0});
this.paramTypeSizeB.Minimum = new decimal(new int[] {
1,
0,
0,
0});
this.paramTypeSizeB.Name = "paramTypeSizeB";
this.paramTypeSizeB.Size = new System.Drawing.Size(35, 20);
this.paramTypeSizeB.TabIndex = 7;
this.paramTypeSizeB.Value = new decimal(new int[] {
1,
0,
0,
0});
this.paramTypeSizeB.Visible = false;
this.paramTypeSizeB.ValueChanged += new System.EventHandler(this.paramEdited);
//
// paramSizeDividerLabel
//
this.paramSizeDividerLabel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.paramSizeDividerLabel.AutoSize = true;
this.paramSizeDividerLabel.Location = new System.Drawing.Point(188, 58);
this.paramSizeDividerLabel.Name = "paramSizeDividerLabel";
this.paramSizeDividerLabel.Size = new System.Drawing.Size(12, 13);
this.paramSizeDividerLabel.TabIndex = 8;
this.paramSizeDividerLabel.Text = "x";
this.paramSizeDividerLabel.Visible = false;
//
// paramEditPanel
//
this.paramEditPanel.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.paramEditPanel.Controls.Add(this.semanticNumberBox);
this.paramEditPanel.Controls.Add(this.semanticBox);
this.paramEditPanel.Controls.Add(this.semanticLabel);
this.paramEditPanel.Controls.Add(this.storageClassBox);
this.paramEditPanel.Controls.Add(this.storageClassLabel);
this.paramEditPanel.Controls.Add(this.paramNameBox);
this.paramEditPanel.Controls.Add(this.paramSizeDividerLabel);
this.paramEditPanel.Controls.Add(this.paramTypeBox);
this.paramEditPanel.Controls.Add(this.paramTypeSizeB);
this.paramEditPanel.Controls.Add(this.label1);
this.paramEditPanel.Controls.Add(this.paramTypeSizeA);
this.paramEditPanel.Controls.Add(this.label2);
this.paramEditPanel.Controls.Add(this.paramTypeSizeBox);
this.paramEditPanel.Location = new System.Drawing.Point(0, 312);
this.paramEditPanel.Name = "paramEditPanel";
this.paramEditPanel.Size = new System.Drawing.Size(244, 140);
this.paramEditPanel.TabIndex = 9;
//
// semanticNumberBox
//
this.semanticNumberBox.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.semanticNumberBox.Location = new System.Drawing.Point(206, 110);
this.semanticNumberBox.Name = "semanticNumberBox";
this.semanticNumberBox.Size = new System.Drawing.Size(35, 20);
this.semanticNumberBox.TabIndex = 13;
this.semanticNumberBox.ValueChanged += new System.EventHandler(this.semanticNumberBox_ValueChanged);
//
// semanticBox
//
this.semanticBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.semanticBox.FormattingEnabled = true;
this.semanticBox.Location = new System.Drawing.Point(79, 109);
this.semanticBox.Name = "semanticBox";
this.semanticBox.Size = new System.Drawing.Size(121, 21);
this.semanticBox.TabIndex = 12;
this.semanticBox.SelectedIndexChanged += new System.EventHandler(this.semanticBox_SelectedIndexChanged);
//
// semanticLabel
//
this.semanticLabel.AutoSize = true;
this.semanticLabel.Location = new System.Drawing.Point(6, 112);
this.semanticLabel.Name = "semanticLabel";
this.semanticLabel.Size = new System.Drawing.Size(51, 13);
this.semanticLabel.TabIndex = 11;
this.semanticLabel.Text = "Semantic";
//
// storageClassBox
//
this.storageClassBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.storageClassBox.FormattingEnabled = true;
this.storageClassBox.Location = new System.Drawing.Point(79, 82);
this.storageClassBox.Name = "storageClassBox";
this.storageClassBox.Size = new System.Drawing.Size(162, 21);
this.storageClassBox.TabIndex = 10;
this.storageClassBox.SelectedIndexChanged += new System.EventHandler(this.storageClassBox_SelectedIndexChanged);
//
// storageClassLabel
//
this.storageClassLabel.AutoSize = true;
this.storageClassLabel.Location = new System.Drawing.Point(6, 85);
this.storageClassLabel.Name = "storageClassLabel";
this.storageClassLabel.Size = new System.Drawing.Size(72, 13);
this.storageClassLabel.TabIndex = 9;
this.storageClassLabel.Text = "Storage Class";
//
// newParamButton
//
this.newParamButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.newParamButton.Location = new System.Drawing.Point(3, 283);
this.newParamButton.Name = "newParamButton";
this.newParamButton.Size = new System.Drawing.Size(75, 23);
this.newParamButton.TabIndex = 10;
this.newParamButton.Text = "New";
this.newParamButton.UseVisualStyleBackColor = true;
this.newParamButton.Click += new System.EventHandler(this.newParamButton_Click);
//
// deleteParamButton
//
this.deleteParamButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.deleteParamButton.Enabled = false;
this.deleteParamButton.Location = new System.Drawing.Point(166, 283);
this.deleteParamButton.Name = "deleteParamButton";
this.deleteParamButton.Size = new System.Drawing.Size(75, 23);
this.deleteParamButton.TabIndex = 12;
this.deleteParamButton.Text = "Delete";
this.deleteParamButton.UseVisualStyleBackColor = true;
this.deleteParamButton.Click += new System.EventHandler(this.deleteParamButton_Click);
//
// ComponentParameterList
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.deleteParamButton);
this.Controls.Add(this.newParamButton);
this.Controls.Add(this.paramEditPanel);
this.Controls.Add(this.parameterListBox);
this.Name = "ComponentParameterList";
this.Size = new System.Drawing.Size(244, 452);
((System.ComponentModel.ISupportInitialize)(this.paramTypeSizeA)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.paramTypeSizeB)).EndInit();
this.paramEditPanel.ResumeLayout(false);
this.paramEditPanel.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.semanticNumberBox)).EndInit();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.ListBox parameterListBox;
private System.Windows.Forms.ComboBox paramTypeBox;
private System.Windows.Forms.TextBox paramNameBox;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.ComboBox paramTypeSizeBox;
private System.Windows.Forms.NumericUpDown paramTypeSizeA;
private System.Windows.Forms.NumericUpDown paramTypeSizeB;
private System.Windows.Forms.Label paramSizeDividerLabel;
private System.Windows.Forms.Panel paramEditPanel;
private System.Windows.Forms.Button newParamButton;
private System.Windows.Forms.Button deleteParamButton;
private System.Windows.Forms.NumericUpDown semanticNumberBox;
private System.Windows.Forms.ComboBox semanticBox;
private System.Windows.Forms.Label semanticLabel;
private System.Windows.Forms.ComboBox storageClassBox;
private System.Windows.Forms.Label storageClassLabel;
}
}
| |
// ***********************************************************************
// Copyright (c) 2015 Charlie Poole, Rob Prouse
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
#if ASYNC
using System;
using System.Threading.Tasks;
using NUnit.Framework;
#if NET40
using Task = System.Threading.Tasks.TaskEx;
#endif
namespace NUnit.TestData
{
public class AsyncRealFixture
{
[Test]
public async void AsyncVoid()
{
var result = await ReturnOne();
Assert.AreEqual(1, result);
}
#region async Task
[Test]
public async System.Threading.Tasks.Task AsyncTaskSuccess()
{
var result = await ReturnOne();
Assert.AreEqual(1, result);
}
[Test]
public async System.Threading.Tasks.Task AsyncTaskFailure()
{
var result = await ReturnOne();
Assert.AreEqual(2, result);
}
[Test]
public async System.Threading.Tasks.Task AsyncTaskError()
{
await ThrowException();
Assert.Fail("Should never get here");
}
#endregion
#region non-async Task
[Test]
public System.Threading.Tasks.Task TaskSuccess()
{
return Task.Run(() => Assert.AreEqual(1, 1));
}
[Test]
public System.Threading.Tasks.Task TaskFailure()
{
return Task.Run(() => Assert.AreEqual(1, 2));
}
[Test]
public System.Threading.Tasks.Task TaskError()
{
throw new InvalidOperationException();
}
#endregion
[Test]
public async Task<int> AsyncTaskResult()
{
return await ReturnOne();
}
[Test]
public Task<int> TaskResult()
{
return ReturnOne();
}
#region async Task<T>
[TestCase(ExpectedResult = 1)]
public async Task<int> AsyncTaskResultCheckSuccess()
{
return await ReturnOne();
}
[TestCase(ExpectedResult = 2)]
public async Task<int> AsyncTaskResultCheckFailure()
{
return await ReturnOne();
}
[TestCase(ExpectedResult = 0)]
public async Task<int> AsyncTaskResultCheckError()
{
return await ThrowException();
}
#endregion
#region non-async Task<T>
[TestCase(ExpectedResult = 1)]
public Task<int> TaskResultCheckSuccess()
{
return ReturnOne();
}
[TestCase(ExpectedResult = 2)]
public Task<int> TaskResultCheckFailure()
{
return ReturnOne();
}
[TestCase(ExpectedResult = 0)]
public Task<int> TaskResultCheckError()
{
return ThrowException();
}
#endregion
[TestCase(1, 2)]
public async System.Threading.Tasks.Task AsyncTaskTestCaseWithParametersSuccess(int a, int b)
{
Assert.AreEqual(await ReturnOne(), b - a);
}
[TestCase(ExpectedResult = null)]
public async Task<object> AsyncTaskResultCheckSuccessReturningNull()
{
return await Task.Run(() => (object)null);
}
[TestCase(ExpectedResult = null)]
public Task<object> TaskResultCheckSuccessReturningNull()
{
return Task.Run(() => (object)null);
}
[Test]
public async System.Threading.Tasks.Task NestedAsyncTaskSuccess()
{
var result = await Task.Run(async () => await ReturnOne());
Assert.AreEqual(1, result);
}
[Test]
public async System.Threading.Tasks.Task NestedAsyncTaskFailure()
{
var result = await Task.Run(async () => await ReturnOne());
Assert.AreEqual(2, result);
}
[Test]
public async System.Threading.Tasks.Task NestedAsyncTaskError()
{
await Task.Run(async () => await ThrowException());
Assert.Fail("Should never get here");
}
[Test]
public async System.Threading.Tasks.Task AsyncTaskMultipleSuccess()
{
var result = await ReturnOne();
Assert.AreEqual(await ReturnOne(), result);
}
[Test]
public async System.Threading.Tasks.Task AsyncTaskMultipleFailure()
{
var result = await ReturnOne();
Assert.AreEqual(await ReturnOne() + 1, result);
}
[Test]
public async System.Threading.Tasks.Task AsyncTaskMultipleError()
{
await ThrowException();
Assert.Fail("Should never get here");
}
[Test]
public async System.Threading.Tasks.Task TaskCheckTestContextAcrossTasks()
{
var testName = await GetTestNameFromContext();
Assert.IsNotNull(testName);
Assert.AreEqual(testName, TestContext.CurrentContext.Test.Name);
}
[Test]
public async System.Threading.Tasks.Task TaskCheckTestContextWithinTestBody()
{
var testName = TestContext.CurrentContext.Test.Name;
await ReturnOne();
Assert.IsNotNull(testName);
Assert.AreEqual(testName, TestContext.CurrentContext.Test.Name);
}
private static Task<string> GetTestNameFromContext()
{
return Task.Run(() => TestContext.CurrentContext.Test.Name);
}
private static Task<int> ReturnOne()
{
return Task.Run(() => 1);
}
private static Task<int> ThrowException()
{
Func<int> throws = () => { throw new InvalidOperationException(); };
return Task.Run( throws );
}
}
}
#endif
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using log4net;
using Nini.Config;
using NUnit.Framework;
using OpenMetaverse;
using OpenMetaverse.Assets;
using OpenMetaverse.StructuredData;
using OpenSim.Framework;
using OpenSim.Region.CoreModules.Avatar.AvatarFactory;
using OpenSim.Region.OptionalModules.World.NPC;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.ScriptEngine.Shared;
using OpenSim.Region.ScriptEngine.Shared.Api;
using OpenSim.Region.ScriptEngine.Shared.Instance;
using OpenSim.Services.Interfaces;
using OpenSim.Tests.Common;
using OpenSim.Tests.Common.Mock;
using PermissionMask = OpenSim.Framework.PermissionMask;
namespace OpenSim.Region.ScriptEngine.Shared.Tests
{
/// <summary>
/// Tests for inventory functions in LSL
/// </summary>
[TestFixture]
public class LSL_ApiInventoryTests : OpenSimTestCase
{
protected Scene m_scene;
protected XEngine.XEngine m_engine;
[SetUp]
public override void SetUp()
{
base.SetUp();
IConfigSource initConfigSource = new IniConfigSource();
IConfig config = initConfigSource.AddConfig("XEngine");
config.Set("Enabled", "true");
m_scene = new SceneHelpers().SetupScene();
SceneHelpers.SetupSceneModules(m_scene, initConfigSource);
m_engine = new XEngine.XEngine();
m_engine.Initialise(initConfigSource);
m_engine.AddRegion(m_scene);
}
/// <summary>
/// Test giving inventory from an object to an object where both are owned by the same user.
/// </summary>
[Test]
public void TestLlGiveInventoryO2OSameOwner()
{
TestHelpers.InMethod();
// log4net.Config.XmlConfigurator.Configure();
UUID userId = TestHelpers.ParseTail(0x1);
string inventoryItemName = "item1";
SceneObjectGroup so1 = SceneHelpers.CreateSceneObject(1, userId, "so1", 0x10);
m_scene.AddSceneObject(so1);
// Create an object embedded inside the first
UUID itemId = TestHelpers.ParseTail(0x20);
TaskInventoryHelpers.AddSceneObject(m_scene, so1.RootPart, inventoryItemName, itemId, userId);
LSL_Api api = new LSL_Api();
api.Initialize(m_engine, so1.RootPart, null, null);
// Create a second object
SceneObjectGroup so2 = SceneHelpers.CreateSceneObject(1, userId, "so2", 0x100);
m_scene.AddSceneObject(so2);
api.llGiveInventory(so2.UUID.ToString(), inventoryItemName);
// Item has copy permissions so original should stay intact.
List<TaskInventoryItem> originalItems = so1.RootPart.Inventory.GetInventoryItems();
Assert.That(originalItems.Count, Is.EqualTo(1));
List<TaskInventoryItem> copiedItems = so2.RootPart.Inventory.GetInventoryItems(inventoryItemName);
Assert.That(copiedItems.Count, Is.EqualTo(1));
Assert.That(copiedItems[0].Name, Is.EqualTo(inventoryItemName));
}
/// <summary>
/// Test giving inventory from an object to an object where they have different owners
/// </summary>
[Test]
public void TestLlGiveInventoryO2ODifferentOwners()
{
TestHelpers.InMethod();
// log4net.Config.XmlConfigurator.Configure();
UUID user1Id = TestHelpers.ParseTail(0x1);
UUID user2Id = TestHelpers.ParseTail(0x2);
string inventoryItemName = "item1";
SceneObjectGroup so1 = SceneHelpers.CreateSceneObject(1, user1Id, "so1", 0x10);
m_scene.AddSceneObject(so1);
LSL_Api api = new LSL_Api();
api.Initialize(m_engine, so1.RootPart, null, null);
// Create an object embedded inside the first
UUID itemId = TestHelpers.ParseTail(0x20);
TaskInventoryHelpers.AddSceneObject(m_scene, so1.RootPart, inventoryItemName, itemId, user1Id);
// Create a second object
SceneObjectGroup so2 = SceneHelpers.CreateSceneObject(1, user2Id, "so2", 0x100);
m_scene.AddSceneObject(so2);
LSL_Api api2 = new LSL_Api();
api2.Initialize(m_engine, so2.RootPart, null, null);
// *** Firstly, we test where llAllowInventoryDrop() has not been called. ***
api.llGiveInventory(so2.UUID.ToString(), inventoryItemName);
{
// Item has copy permissions so original should stay intact.
List<TaskInventoryItem> originalItems = so1.RootPart.Inventory.GetInventoryItems();
Assert.That(originalItems.Count, Is.EqualTo(1));
// Should have not copied
List<TaskInventoryItem> copiedItems = so2.RootPart.Inventory.GetInventoryItems(inventoryItemName);
Assert.That(copiedItems.Count, Is.EqualTo(0));
}
// *** Secondly, we turn on allow inventory drop in the target and retest. ***
api2.llAllowInventoryDrop(1);
api.llGiveInventory(so2.UUID.ToString(), inventoryItemName);
{
// Item has copy permissions so original should stay intact.
List<TaskInventoryItem> originalItems = so1.RootPart.Inventory.GetInventoryItems();
Assert.That(originalItems.Count, Is.EqualTo(1));
// Should now have copied.
List<TaskInventoryItem> copiedItems = so2.RootPart.Inventory.GetInventoryItems(inventoryItemName);
Assert.That(copiedItems.Count, Is.EqualTo(1));
Assert.That(copiedItems[0].Name, Is.EqualTo(inventoryItemName));
}
}
/// <summary>
/// Test giving inventory from an object to an avatar that is not the object's owner.
/// </summary>
[Test]
public void TestLlGiveInventoryO2DifferentAvatar()
{
TestHelpers.InMethod();
// TestHelpers.EnableLogging();
UUID user1Id = TestHelpers.ParseTail(0x1);
UUID user2Id = TestHelpers.ParseTail(0x2);
string inventoryItemName = "item1";
SceneObjectGroup so1 = SceneHelpers.CreateSceneObject(1, user1Id, "so1", 0x10);
m_scene.AddSceneObject(so1);
LSL_Api api = new LSL_Api();
api.Initialize(m_engine, so1.RootPart, null, null);
// Create an object embedded inside the first
UUID itemId = TestHelpers.ParseTail(0x20);
TaskInventoryHelpers.AddSceneObject(m_scene, so1.RootPart, inventoryItemName, itemId, user1Id);
UserAccountHelpers.CreateUserWithInventory(m_scene, user2Id);
api.llGiveInventory(user2Id.ToString(), inventoryItemName);
InventoryItemBase receivedItem
= UserInventoryHelpers.GetInventoryItem(
m_scene.InventoryService, user2Id, string.Format("Objects/{0}", inventoryItemName));
Assert.IsNotNull(receivedItem);
}
/// <summary>
/// Test giving inventory from an object to an avatar that is not the object's owner and where the next
/// permissions do not include mod.
/// </summary>
[Test]
public void TestLlGiveInventoryO2DifferentAvatarNoMod()
{
TestHelpers.InMethod();
// TestHelpers.EnableLogging();
UUID user1Id = TestHelpers.ParseTail(0x1);
UUID user2Id = TestHelpers.ParseTail(0x2);
string inventoryItemName = "item1";
SceneObjectGroup so1 = SceneHelpers.CreateSceneObject(1, user1Id, "so1", 0x10);
m_scene.AddSceneObject(so1);
LSL_Api api = new LSL_Api();
api.Initialize(m_engine, so1.RootPart, null, null);
// Create an object embedded inside the first
UUID itemId = TestHelpers.ParseTail(0x20);
TaskInventoryItem tii
= TaskInventoryHelpers.AddSceneObject(m_scene, so1.RootPart, inventoryItemName, itemId, user1Id);
tii.NextPermissions &= ~((uint)PermissionMask.Modify);
UserAccountHelpers.CreateUserWithInventory(m_scene, user2Id);
api.llGiveInventory(user2Id.ToString(), inventoryItemName);
InventoryItemBase receivedItem
= UserInventoryHelpers.GetInventoryItem(
m_scene.InventoryService, user2Id, string.Format("Objects/{0}", inventoryItemName));
Assert.IsNotNull(receivedItem);
Assert.AreEqual(0, receivedItem.CurrentPermissions & (uint)PermissionMask.Modify);
}
[Test]
public void TestLlRemoteLoadScriptPin()
{
TestHelpers.InMethod();
// TestHelpers.EnableLogging();
UUID user1Id = TestHelpers.ParseTail(0x1);
UUID user2Id = TestHelpers.ParseTail(0x2);
SceneObjectGroup sourceSo = SceneHelpers.AddSceneObject(m_scene, 1, user1Id, "sourceSo", 0x10);
m_scene.AddSceneObject(sourceSo);
LSL_Api api = new LSL_Api();
api.Initialize(m_engine, sourceSo.RootPart, null, null);
TaskInventoryHelpers.AddScript(m_scene, sourceSo.RootPart, "script", "Hello World");
SceneObjectGroup targetSo = SceneHelpers.AddSceneObject(m_scene, 1, user1Id, "targetSo", 0x20);
SceneObjectGroup otherOwnedTargetSo
= SceneHelpers.AddSceneObject(m_scene, 1, user2Id, "otherOwnedTargetSo", 0x30);
// Test that we cannot load a script when the target pin has never been set (i.e. it is zero)
api.llRemoteLoadScriptPin(targetSo.UUID.ToString(), "script", 0, 0, 0);
Assert.IsNull(targetSo.RootPart.Inventory.GetInventoryItem("script"));
// Test that we cannot load a script when the given pin does not match the target
targetSo.RootPart.ScriptAccessPin = 5;
api.llRemoteLoadScriptPin(targetSo.UUID.ToString(), "script", 3, 0, 0);
Assert.IsNull(targetSo.RootPart.Inventory.GetInventoryItem("script"));
// Test that we cannot load into a prim with a different owner
otherOwnedTargetSo.RootPart.ScriptAccessPin = 3;
api.llRemoteLoadScriptPin(otherOwnedTargetSo.UUID.ToString(), "script", 3, 0, 0);
Assert.IsNull(otherOwnedTargetSo.RootPart.Inventory.GetInventoryItem("script"));
// Test that we can load a script when given pin and dest pin match.
targetSo.RootPart.ScriptAccessPin = 3;
api.llRemoteLoadScriptPin(targetSo.UUID.ToString(), "script", 3, 0, 0);
TaskInventoryItem insertedItem = targetSo.RootPart.Inventory.GetInventoryItem("script");
Assert.IsNotNull(insertedItem);
// Test that we can no longer load if access pin is unset
targetSo.RootPart.Inventory.RemoveInventoryItem(insertedItem.ItemID);
Assert.IsNull(targetSo.RootPart.Inventory.GetInventoryItem("script"));
targetSo.RootPart.ScriptAccessPin = 0;
api.llRemoteLoadScriptPin(otherOwnedTargetSo.UUID.ToString(), "script", 3, 0, 0);
Assert.IsNull(otherOwnedTargetSo.RootPart.Inventory.GetInventoryItem("script"));
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Collections;
using System.Globalization;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using Microsoft.Win32;
namespace System.Management.Automation
{
/// <summary>
/// <para>
/// Encapsulates $PSVersionTable.
/// </para>
/// <para>
/// Provides a simple interface to retrieve details from the PowerShell version table:
/// <code>
/// PSVersionInfo.PSVersion;
/// </code>
/// The above statement retrieves the PowerShell version.
/// <code>
/// PSVersionInfo.PSEdition;
/// </code>
/// The above statement retrieves the PowerShell edition.
/// </para>
/// </summary>
public static class PSVersionInfo
{
internal const string PSVersionTableName = "PSVersionTable";
internal const string PSRemotingProtocolVersionName = "PSRemotingProtocolVersion";
internal const string PSVersionName = "PSVersion";
internal const string PSEditionName = "PSEdition";
internal const string PSGitCommitIdName = "GitCommitId";
internal const string PSCompatibleVersionsName = "PSCompatibleVersions";
internal const string PSPlatformName = "Platform";
internal const string PSOSName = "OS";
internal const string SerializationVersionName = "SerializationVersion";
internal const string WSManStackVersionName = "WSManStackVersion";
private static readonly PSVersionHashTable s_psVersionTable;
/// <summary>
/// A constant to track current PowerShell Version.
/// </summary>
/// <remarks>
/// We can't depend on assembly version for PowerShell version.
///
/// This is why we hard code the PowerShell version here.
///
/// For each later release of PowerShell, this constant needs to
/// be updated to reflect the right version.
/// </remarks>
private static readonly Version s_psV1Version = new Version(1, 0);
private static readonly Version s_psV2Version = new Version(2, 0);
private static readonly Version s_psV3Version = new Version(3, 0);
private static readonly Version s_psV4Version = new Version(4, 0);
private static readonly Version s_psV5Version = new Version(5, 0);
private static readonly Version s_psV51Version = new Version(5, 1, NTVerpVars.PRODUCTBUILD, NTVerpVars.PRODUCTBUILD_QFE);
private static readonly SemanticVersion s_psV6Version = new SemanticVersion(6, 0, 0, preReleaseLabel: null, buildLabel: null);
private static readonly SemanticVersion s_psV61Version = new SemanticVersion(6, 1, 0, preReleaseLabel: null, buildLabel: null);
private static readonly SemanticVersion s_psV62Version = new SemanticVersion(6, 2, 0, preReleaseLabel: null, buildLabel: null);
private static readonly SemanticVersion s_psV7Version = new SemanticVersion(7, 0, 0, preReleaseLabel: null, buildLabel: null);
private static readonly SemanticVersion s_psV71Version = new SemanticVersion(7, 1, 0, preReleaseLabel: null, buildLabel: null);
private static readonly SemanticVersion s_psSemVersion;
private static readonly Version s_psVersion;
/// <summary>
/// A constant to track current PowerShell Edition.
/// </summary>
internal const string PSEditionValue = "Core";
// Static Constructor.
static PSVersionInfo()
{
s_psVersionTable = new PSVersionHashTable(StringComparer.OrdinalIgnoreCase);
Assembly currentAssembly = typeof(PSVersionInfo).Assembly;
ProductVersion = currentAssembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>().InformationalVersion;
// Get 'GitCommitId' and 'PSVersion' from the 'productVersion' assembly attribute.
//
// The strings can be one of the following format examples:
// when powershell is built from a commit:
// productVersion = '6.0.0-beta.7 Commits: 29 SHA: 52c6b...' convert to GitCommitId = 'v6.0.0-beta.7-29-g52c6b...'
// PSVersion = '6.0.0-beta.7'
// when powershell is built from a release tag:
// productVersion = '6.0.0-beta.7 SHA: f1ec9...' convert to GitCommitId = 'v6.0.0-beta.7'
// PSVersion = '6.0.0-beta.7'
// when powershell is built from a release tag for RTM:
// productVersion = '6.0.0 SHA: f1ec9...' convert to GitCommitId = 'v6.0.0'
// PSVersion = '6.0.0'
string rawGitCommitId;
string mainVersion = ProductVersion.Substring(0, ProductVersion.IndexOf(' '));
if (ProductVersion.Contains(" Commits: "))
{
rawGitCommitId = ProductVersion.Replace(" Commits: ", "-").Replace(" SHA: ", "-g");
}
else
{
rawGitCommitId = mainVersion;
}
s_psSemVersion = new SemanticVersion(mainVersion);
s_psVersion = (Version)s_psSemVersion;
s_psVersionTable[PSVersionInfo.PSVersionName] = s_psSemVersion;
s_psVersionTable[PSVersionInfo.PSEditionName] = PSEditionValue;
s_psVersionTable[PSGitCommitIdName] = rawGitCommitId;
s_psVersionTable[PSCompatibleVersionsName] = new Version[] { s_psV1Version, s_psV2Version, s_psV3Version, s_psV4Version, s_psV5Version, s_psV51Version, s_psV6Version, s_psV61Version, s_psV62Version, s_psV7Version, s_psV71Version, s_psVersion };
s_psVersionTable[PSVersionInfo.SerializationVersionName] = new Version(InternalSerializer.DefaultVersion);
s_psVersionTable[PSVersionInfo.PSRemotingProtocolVersionName] = RemotingConstants.ProtocolVersion;
s_psVersionTable[PSVersionInfo.WSManStackVersionName] = GetWSManStackVersion();
s_psVersionTable[PSPlatformName] = Environment.OSVersion.Platform.ToString();
s_psVersionTable[PSOSName] = Runtime.InteropServices.RuntimeInformation.OSDescription;
}
internal static PSVersionHashTable GetPSVersionTable()
{
return s_psVersionTable;
}
internal static Hashtable GetPSVersionTableForDownLevel()
{
var result = (Hashtable)s_psVersionTable.Clone();
// Downlevel systems don't support SemanticVersion, but Version is most likely good enough anyway.
result[PSVersionInfo.PSVersionName] = s_psVersion;
return result;
}
#region Private helper methods
// Gets the current WSMan stack version from the registry.
private static Version GetWSManStackVersion()
{
Version version = null;
#if !UNIX
try
{
using (RegistryKey wsManStackVersionKey = Registry.LocalMachine.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\WSMAN"))
{
if (wsManStackVersionKey != null)
{
object wsManStackVersionObj = wsManStackVersionKey.GetValue("ServiceStackVersion");
string wsManStackVersion = (wsManStackVersionObj != null) ? (string)wsManStackVersionObj : null;
if (!string.IsNullOrEmpty(wsManStackVersion))
{
version = new Version(wsManStackVersion.Trim());
}
}
}
}
catch (ObjectDisposedException) { }
catch (System.Security.SecurityException) { }
catch (ArgumentException) { }
catch (System.IO.IOException) { }
catch (UnauthorizedAccessException) { }
catch (FormatException) { }
catch (OverflowException) { }
catch (InvalidCastException) { }
#endif
return version ?? System.Management.Automation.Remoting.Client.WSManNativeApi.WSMAN_STACK_VERSION;
}
#endregion
#region Programmer APIs
/// <summary>
/// Gets the version of PowerShell.
/// </summary>
public static Version PSVersion
{
get
{
return s_psVersion;
}
}
internal static string ProductVersion { get; }
internal static string GitCommitId
{
get
{
return (string)s_psVersionTable[PSGitCommitIdName];
}
}
internal static Version[] PSCompatibleVersions
{
get
{
return (Version[])s_psVersionTable[PSCompatibleVersionsName];
}
}
/// <summary>
/// Gets the edition of PowerShell.
/// </summary>
public static string PSEdition
{
get
{
return (string)s_psVersionTable[PSVersionInfo.PSEditionName];
}
}
internal static Version SerializationVersion
{
get
{
return (Version)s_psVersionTable[SerializationVersionName];
}
}
/// <summary>
/// </summary>
/// <remarks>
/// For 2.0 PowerShell, we still use "1" as the registry version key.
/// For >=3.0 PowerShell, we still use "1" as the registry version key for
/// Snapin and Custom shell lookup/discovery.
/// </remarks>
internal static string RegistryVersion1Key
{
get
{
return "1";
}
}
/// <summary>
/// </summary>
/// <remarks>
/// For 3.0 PowerShell, we use "3" as the registry version key only for Engine
/// related data like ApplicationBase.
/// For 3.0 PowerShell, we still use "1" as the registry version key for
/// Snapin and Custom shell lookup/discovery.
/// </remarks>
internal static string RegistryVersionKey
{
get
{
// PowerShell >=4 is compatible with PowerShell 3 and hence reg key is 3.
return "3";
}
}
internal static string GetRegistryVersionKeyForSnapinDiscovery(string majorVersion)
{
int tempMajorVersion = 0;
LanguagePrimitives.TryConvertTo<int>(majorVersion, out tempMajorVersion);
if ((tempMajorVersion >= 1) && (tempMajorVersion <= PSVersionInfo.PSVersion.Major))
{
// PowerShell version 3 took a dependency on CLR4 and went with:
// SxS approach in GAC/Registry and in-place upgrade approach for
// FileSystem.
// For >=3.0 PowerShell, we still use "1" as the registry version key for
// Snapin and Custom shell lookup/discovery.
return "1";
}
return null;
}
internal static string FeatureVersionString
{
get
{
return string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}.{1}", PSVersionInfo.PSVersion.Major, PSVersionInfo.PSVersion.Minor);
}
}
internal static bool IsValidPSVersion(Version version)
{
if (version.Major == s_psSemVersion.Major)
{
return version.Minor == s_psSemVersion.Minor;
}
if (version.Major == s_psV6Version.Major)
{
return version.Minor == s_psV6Version.Minor;
}
if (version.Major == s_psV5Version.Major)
{
return (version.Minor == s_psV5Version.Minor || version.Minor == s_psV51Version.Minor);
}
if (version.Major == s_psV4Version.Major)
{
return (version.Minor == s_psV4Version.Minor);
}
else if (version.Major == s_psV3Version.Major)
{
return version.Minor == s_psV3Version.Minor;
}
else if (version.Major == s_psV2Version.Major)
{
return version.Minor == s_psV2Version.Minor;
}
else if (version.Major == s_psV1Version.Major)
{
return version.Minor == s_psV1Version.Minor;
}
return false;
}
internal static Version PSV4Version
{
get { return s_psV4Version; }
}
internal static Version PSV5Version
{
get { return s_psV5Version; }
}
internal static Version PSV51Version
{
get { return s_psV51Version; }
}
internal static SemanticVersion PSV6Version
{
get { return s_psV6Version; }
}
internal static SemanticVersion PSV7Version
{
get { return s_psV7Version; }
}
internal static SemanticVersion PSCurrentVersion
{
get { return s_psSemVersion; }
}
#endregion
}
/// <summary>
/// Represents an implementation of '$PSVersionTable' variable.
/// The implementation contains ordered 'Keys' and 'GetEnumerator' to get user-friendly output.
/// </summary>
public sealed class PSVersionHashTable : Hashtable, IEnumerable
{
private static readonly PSVersionTableComparer s_keysComparer = new PSVersionTableComparer();
internal PSVersionHashTable(IEqualityComparer equalityComparer) : base(equalityComparer)
{
}
/// <summary>
/// Returns ordered collection with Keys of 'PSVersionHashTable'
/// We want see special order:
/// 1. PSVersionName
/// 2. PSEditionName
/// 3. Remaining properties in alphabetical order.
/// </summary>
public override ICollection Keys
{
get
{
ArrayList keyList = new ArrayList(base.Keys);
keyList.Sort(s_keysComparer);
return keyList;
}
}
private sealed class PSVersionTableComparer : IComparer
{
public int Compare(object x, object y)
{
string xString = (string)LanguagePrimitives.ConvertTo(x, typeof(string), CultureInfo.CurrentCulture);
string yString = (string)LanguagePrimitives.ConvertTo(y, typeof(string), CultureInfo.CurrentCulture);
if (PSVersionInfo.PSVersionName.Equals(xString, StringComparison.OrdinalIgnoreCase))
{
return -1;
}
else if (PSVersionInfo.PSVersionName.Equals(yString, StringComparison.OrdinalIgnoreCase))
{
return 1;
}
else if (PSVersionInfo.PSEditionName.Equals(xString, StringComparison.OrdinalIgnoreCase))
{
return -1;
}
else if (PSVersionInfo.PSEditionName.Equals(yString, StringComparison.OrdinalIgnoreCase))
{
return 1;
}
else
{
return string.Compare(xString, yString, StringComparison.OrdinalIgnoreCase);
}
}
}
/// <summary>
/// Returns an enumerator for 'PSVersionHashTable'.
/// The enumeration is ordered (based on ordered version of 'Keys').
/// </summary>
IEnumerator IEnumerable.GetEnumerator()
{
foreach (object key in Keys)
{
yield return new DictionaryEntry(key, this[key]);
}
}
}
/// <summary>
/// An implementation of semantic versioning (https://semver.org)
/// that can be converted to/from <see cref="System.Version"/>.
///
/// When converting to <see cref="Version"/>, a PSNoteProperty is
/// added to the instance to store the semantic version label so
/// that it can be recovered when creating a new SemanticVersion.
/// </summary>
public sealed class SemanticVersion : IComparable, IComparable<SemanticVersion>, IEquatable<SemanticVersion>
{
private const string VersionSansRegEx = @"^(?<major>\d+)(\.(?<minor>\d+))?(\.(?<patch>\d+))?$";
private const string LabelRegEx = @"^((?<preLabel>[0-9A-Za-z][0-9A-Za-z\-\.]*))?(\+(?<buildLabel>[0-9A-Za-z][0-9A-Za-z\-\.]*))?$";
private const string LabelUnitRegEx = @"^[0-9A-Za-z][0-9A-Za-z\-\.]*$";
private const string PreLabelPropertyName = "PSSemVerPreReleaseLabel";
private const string BuildLabelPropertyName = "PSSemVerBuildLabel";
private const string TypeNameForVersionWithLabel = "System.Version#IncludeLabel";
private string versionString;
/// <summary>
/// Construct a SemanticVersion from a string.
/// </summary>
/// <param name="version">The version to parse.</param>
/// <exception cref="FormatException"></exception>
/// <exception cref="OverflowException"></exception>
public SemanticVersion(string version)
{
var v = SemanticVersion.Parse(version);
Major = v.Major;
Minor = v.Minor;
Patch = v.Patch < 0 ? 0 : v.Patch;
PreReleaseLabel = v.PreReleaseLabel;
BuildLabel = v.BuildLabel;
}
/// <summary>
/// Construct a SemanticVersion.
/// </summary>
/// <param name="major">The major version.</param>
/// <param name="minor">The minor version.</param>
/// <param name="patch">The patch version.</param>
/// <param name="preReleaseLabel">The pre-release label for the version.</param>
/// <param name="buildLabel">The build metadata for the version.</param>
/// <exception cref="FormatException">
/// If <paramref name="preReleaseLabel"/> don't match 'LabelUnitRegEx'.
/// If <paramref name="buildLabel"/> don't match 'LabelUnitRegEx'.
/// </exception>
public SemanticVersion(int major, int minor, int patch, string preReleaseLabel, string buildLabel)
: this(major, minor, patch)
{
if (!string.IsNullOrEmpty(preReleaseLabel))
{
if (!Regex.IsMatch(preReleaseLabel, LabelUnitRegEx)) throw new FormatException(nameof(preReleaseLabel));
PreReleaseLabel = preReleaseLabel;
}
if (!string.IsNullOrEmpty(buildLabel))
{
if (!Regex.IsMatch(buildLabel, LabelUnitRegEx)) throw new FormatException(nameof(buildLabel));
BuildLabel = buildLabel;
}
}
/// <summary>
/// Construct a SemanticVersion.
/// </summary>
/// <param name="major">The major version.</param>
/// <param name="minor">The minor version.</param>
/// <param name="patch">The minor version.</param>
/// <param name="label">The label for the version.</param>
/// <exception cref="PSArgumentException">
/// <exception cref="FormatException">
/// If <paramref name="label"/> don't match 'LabelRegEx'.
/// </exception>
public SemanticVersion(int major, int minor, int patch, string label)
: this(major, minor, patch)
{
// We presume the SymVer :
// 1) major.minor.patch-label
// 2) 'label' starts with letter or digit.
if (!string.IsNullOrEmpty(label))
{
var match = Regex.Match(label, LabelRegEx);
if (!match.Success) throw new FormatException(nameof(label));
PreReleaseLabel = match.Groups["preLabel"].Value;
BuildLabel = match.Groups["buildLabel"].Value;
}
}
/// <summary>
/// Construct a SemanticVersion.
/// </summary>
/// <param name="major">The major version.</param>
/// <param name="minor">The minor version.</param>
/// <param name="patch">The minor version.</param>
/// <exception cref="PSArgumentException">
/// If <paramref name="major"/>, <paramref name="minor"/>, or <paramref name="patch"/> is less than 0.
/// </exception>
public SemanticVersion(int major, int minor, int patch)
{
if (major < 0) throw PSTraceSource.NewArgumentException(nameof(major));
if (minor < 0) throw PSTraceSource.NewArgumentException(nameof(minor));
if (patch < 0) throw PSTraceSource.NewArgumentException(nameof(patch));
Major = major;
Minor = minor;
Patch = patch;
// We presume:
// PreReleaseLabel = null;
// BuildLabel = null;
}
/// <summary>
/// Construct a SemanticVersion.
/// </summary>
/// <param name="major">The major version.</param>
/// <param name="minor">The minor version.</param>
/// <exception cref="PSArgumentException">
/// If <paramref name="major"/> or <paramref name="minor"/> is less than 0.
/// </exception>
public SemanticVersion(int major, int minor) : this(major, minor, 0) { }
/// <summary>
/// Construct a SemanticVersion.
/// </summary>
/// <param name="major">The major version.</param>
/// <exception cref="PSArgumentException">
/// If <paramref name="major"/> is less than 0.
/// </exception>
public SemanticVersion(int major) : this(major, 0, 0) { }
/// <summary>
/// Construct a <see cref="SemanticVersion"/> from a <see cref="Version"/>,
/// copying the NoteProperty storing the label if the expected property exists.
/// </summary>
/// <param name="version">The version.</param>
/// <exception cref="ArgumentNullException">
/// If <paramref name="version"/> is null.
/// </exception>
/// <exception cref="PSArgumentException">
/// If <paramref name="version.Revision"/> is more than 0.
/// </exception>
public SemanticVersion(Version version)
{
if (version == null) throw PSTraceSource.NewArgumentNullException(nameof(version));
if (version.Revision > 0) throw PSTraceSource.NewArgumentException(nameof(version));
Major = version.Major;
Minor = version.Minor;
Patch = version.Build == -1 ? 0 : version.Build;
var psobj = new PSObject(version);
var preLabelNote = psobj.Properties[PreLabelPropertyName];
if (preLabelNote != null)
{
PreReleaseLabel = preLabelNote.Value as string;
}
var buildLabelNote = psobj.Properties[BuildLabelPropertyName];
if (buildLabelNote != null)
{
BuildLabel = buildLabelNote.Value as string;
}
}
/// <summary>
/// Convert a <see cref="SemanticVersion"/> to a <see cref="Version"/>.
/// If there is a <see cref="PreReleaseLabel"/> or/and a <see cref="BuildLabel"/>,
/// it is added as a NoteProperty to the result so that you can round trip
/// back to a <see cref="SemanticVersion"/> without losing the label.
/// </summary>
/// <param name="semver"></param>
public static implicit operator Version(SemanticVersion semver)
{
PSObject psobj;
var result = new Version(semver.Major, semver.Minor, semver.Patch);
if (!string.IsNullOrEmpty(semver.PreReleaseLabel) || !string.IsNullOrEmpty(semver.BuildLabel))
{
psobj = new PSObject(result);
if (!string.IsNullOrEmpty(semver.PreReleaseLabel))
{
psobj.Properties.Add(new PSNoteProperty(PreLabelPropertyName, semver.PreReleaseLabel));
}
if (!string.IsNullOrEmpty(semver.BuildLabel))
{
psobj.Properties.Add(new PSNoteProperty(BuildLabelPropertyName, semver.BuildLabel));
}
psobj.TypeNames.Insert(0, TypeNameForVersionWithLabel);
}
return result;
}
/// <summary>
/// The major version number, never negative.
/// </summary>
public int Major { get; }
/// <summary>
/// The minor version number, never negative.
/// </summary>
public int Minor { get; }
/// <summary>
/// The patch version, -1 if not specified.
/// </summary>
public int Patch { get; }
/// <summary>
/// PreReleaseLabel position in the SymVer string 'major.minor.patch-PreReleaseLabel+BuildLabel'.
/// </summary>
public string PreReleaseLabel { get; }
/// <summary>
/// BuildLabel position in the SymVer string 'major.minor.patch-PreReleaseLabel+BuildLabel'.
/// </summary>
public string BuildLabel { get; }
/// <summary>
/// Parse <paramref name="version"/> and return the result if it is a valid <see cref="SemanticVersion"/>, otherwise throws an exception.
/// </summary>
/// <param name="version">The string to parse.</param>
/// <returns></returns>
/// <exception cref="PSArgumentException"></exception>
/// <exception cref="FormatException"></exception>
/// <exception cref="OverflowException"></exception>
public static SemanticVersion Parse(string version)
{
if (version == null) throw PSTraceSource.NewArgumentNullException(nameof(version));
if (version == string.Empty) throw new FormatException(nameof(version));
var r = new VersionResult();
r.Init(true);
TryParseVersion(version, ref r);
return r._parsedVersion;
}
/// <summary>
/// Parse <paramref name="version"/> and return true if it is a valid <see cref="SemanticVersion"/>, otherwise return false.
/// No exceptions are raised.
/// </summary>
/// <param name="version">The string to parse.</param>
/// <param name="result">The return value when the string is a valid <see cref="SemanticVersion"/></param>
public static bool TryParse(string version, out SemanticVersion result)
{
if (version != null)
{
var r = new VersionResult();
r.Init(false);
if (TryParseVersion(version, ref r))
{
result = r._parsedVersion;
return true;
}
}
result = null;
return false;
}
private static bool TryParseVersion(string version, ref VersionResult result)
{
if (version.EndsWith('-') || version.EndsWith('+') || version.EndsWith('.'))
{
result.SetFailure(ParseFailureKind.FormatException);
return false;
}
string versionSansLabel = null;
var major = 0;
var minor = 0;
var patch = 0;
string preLabel = null;
string buildLabel = null;
// We parse the SymVer 'version' string 'major.minor.patch-PreReleaseLabel+BuildLabel'.
var dashIndex = version.IndexOf('-');
var plusIndex = version.IndexOf('+');
if (dashIndex > plusIndex)
{
// 'PreReleaseLabel' can contains dashes.
if (plusIndex == -1)
{
// No buildLabel: buildLabel == null
// Format is 'major.minor.patch-PreReleaseLabel'
preLabel = version.Substring(dashIndex + 1);
versionSansLabel = version.Substring(0, dashIndex);
}
else
{
// No PreReleaseLabel: preLabel == null
// Format is 'major.minor.patch+BuildLabel'
buildLabel = version.Substring(plusIndex + 1);
versionSansLabel = version.Substring(0, plusIndex);
dashIndex = -1;
}
}
else
{
if (dashIndex == -1)
{
// Here dashIndex == plusIndex == -1
// No preLabel - preLabel == null;
// No buildLabel - buildLabel == null;
// Format is 'major.minor.patch'
versionSansLabel = version;
}
else
{
// Format is 'major.minor.patch-PreReleaseLabel+BuildLabel'
preLabel = version.Substring(dashIndex + 1, plusIndex - dashIndex - 1);
buildLabel = version.Substring(plusIndex + 1);
versionSansLabel = version.Substring(0, dashIndex);
}
}
if ((dashIndex != -1 && string.IsNullOrEmpty(preLabel)) ||
(plusIndex != -1 && string.IsNullOrEmpty(buildLabel)) ||
string.IsNullOrEmpty(versionSansLabel))
{
// We have dash and no preReleaseLabel or
// we have plus and no buildLabel or
// we have no main version part (versionSansLabel==null)
result.SetFailure(ParseFailureKind.FormatException);
return false;
}
var match = Regex.Match(versionSansLabel, VersionSansRegEx);
if (!match.Success)
{
result.SetFailure(ParseFailureKind.FormatException);
return false;
}
if (!int.TryParse(match.Groups["major"].Value, out major))
{
result.SetFailure(ParseFailureKind.FormatException);
return false;
}
if (match.Groups["minor"].Success && !int.TryParse(match.Groups["minor"].Value, out minor))
{
result.SetFailure(ParseFailureKind.FormatException);
return false;
}
if (match.Groups["patch"].Success && !int.TryParse(match.Groups["patch"].Value, out patch))
{
result.SetFailure(ParseFailureKind.FormatException);
return false;
}
if (preLabel != null && !Regex.IsMatch(preLabel, LabelUnitRegEx) ||
(buildLabel != null && !Regex.IsMatch(buildLabel, LabelUnitRegEx)))
{
result.SetFailure(ParseFailureKind.FormatException);
return false;
}
result._parsedVersion = new SemanticVersion(major, minor, patch, preLabel, buildLabel);
return true;
}
/// <summary>
/// Implement ToString()
/// </summary>
public override string ToString()
{
if (versionString == null)
{
StringBuilder result = new StringBuilder();
result.Append(Major).Append(Utils.Separators.Dot).Append(Minor).Append(Utils.Separators.Dot).Append(Patch);
if (!string.IsNullOrEmpty(PreReleaseLabel))
{
result.Append('-').Append(PreReleaseLabel);
}
if (!string.IsNullOrEmpty(BuildLabel))
{
result.Append('+').Append(BuildLabel);
}
versionString = result.ToString();
}
return versionString;
}
/// <summary>
/// Implement Compare.
/// </summary>
public static int Compare(SemanticVersion versionA, SemanticVersion versionB)
{
if (versionA != null)
{
return versionA.CompareTo(versionB);
}
if (versionB != null)
{
return -1;
}
return 0;
}
/// <summary>
/// Implement <see cref="IComparable.CompareTo"/>
/// </summary>
public int CompareTo(object version)
{
if (version == null)
{
return 1;
}
if (!(version is SemanticVersion v))
{
throw PSTraceSource.NewArgumentException(nameof(version));
}
return CompareTo(v);
}
/// <summary>
/// Implement <see cref="IComparable{T}.CompareTo"/>.
/// Meets SymVer 2.0 p.11 https://semver.org/
/// </summary>
public int CompareTo(SemanticVersion value)
{
if (value is null)
return 1;
if (Major != value.Major)
return Major > value.Major ? 1 : -1;
if (Minor != value.Minor)
return Minor > value.Minor ? 1 : -1;
if (Patch != value.Patch)
return Patch > value.Patch ? 1 : -1;
// SymVer 2.0 standard requires to ignore 'BuildLabel' (Build metadata).
return ComparePreLabel(this.PreReleaseLabel, value.PreReleaseLabel);
}
/// <summary>
/// Override <see cref="object.Equals(object)"/>
/// </summary>
public override bool Equals(object obj)
{
return Equals(obj as SemanticVersion);
}
/// <summary>
/// Implement <see cref="IEquatable{T}.Equals(T)"/>
/// </summary>
public bool Equals(SemanticVersion other)
{
// SymVer 2.0 standard requires to ignore 'BuildLabel' (Build metadata).
return other != null &&
(Major == other.Major) && (Minor == other.Minor) && (Patch == other.Patch) &&
string.Equals(PreReleaseLabel, other.PreReleaseLabel, StringComparison.Ordinal);
}
/// <summary>
/// Override <see cref="object.GetHashCode()"/>
/// </summary>
public override int GetHashCode()
{
return this.ToString().GetHashCode();
}
/// <summary>
/// Overloaded == operator.
/// </summary>
public static bool operator ==(SemanticVersion v1, SemanticVersion v2)
{
if (v1 is null)
{
return v2 is null;
}
return v1.Equals(v2);
}
/// <summary>
/// Overloaded != operator.
/// </summary>
public static bool operator !=(SemanticVersion v1, SemanticVersion v2)
{
return !(v1 == v2);
}
/// <summary>
/// Overloaded < operator.
/// </summary>
public static bool operator <(SemanticVersion v1, SemanticVersion v2)
{
return (Compare(v1, v2) < 0);
}
/// <summary>
/// Overloaded <= operator.
/// </summary>
public static bool operator <=(SemanticVersion v1, SemanticVersion v2)
{
return (Compare(v1, v2) <= 0);
}
/// <summary>
/// Overloaded > operator.
/// </summary>
public static bool operator >(SemanticVersion v1, SemanticVersion v2)
{
return (Compare(v1, v2) > 0);
}
/// <summary>
/// Overloaded >= operator.
/// </summary>
public static bool operator >=(SemanticVersion v1, SemanticVersion v2)
{
return (Compare(v1, v2) >= 0);
}
private static int ComparePreLabel(string preLabel1, string preLabel2)
{
// Symver 2.0 standard p.9
// Pre-release versions have a lower precedence than the associated normal version.
// Comparing each dot separated identifier from left to right
// until a difference is found as follows:
// identifiers consisting of only digits are compared numerically
// and identifiers with letters or hyphens are compared lexically in ASCII sort order.
// Numeric identifiers always have lower precedence than non-numeric identifiers.
// A larger set of pre-release fields has a higher precedence than a smaller set,
// if all of the preceding identifiers are equal.
if (string.IsNullOrEmpty(preLabel1)) { return string.IsNullOrEmpty(preLabel2) ? 0 : 1; }
if (string.IsNullOrEmpty(preLabel2)) { return -1; }
var units1 = preLabel1.Split('.');
var units2 = preLabel2.Split('.');
var minLength = units1.Length < units2.Length ? units1.Length : units2.Length;
for (int i = 0; i < minLength; i++)
{
var ac = units1[i];
var bc = units2[i];
int number1, number2;
var isNumber1 = Int32.TryParse(ac, out number1);
var isNumber2 = Int32.TryParse(bc, out number2);
if (isNumber1 && isNumber2)
{
if (number1 != number2) { return number1 < number2 ? -1 : 1; }
}
else
{
if (isNumber1) { return -1; }
if (isNumber2) { return 1; }
int result = string.CompareOrdinal(ac, bc);
if (result != 0) { return result; }
}
}
return units1.Length.CompareTo(units2.Length);
}
internal enum ParseFailureKind
{
ArgumentException,
ArgumentOutOfRangeException,
FormatException
}
internal struct VersionResult
{
internal SemanticVersion _parsedVersion;
internal ParseFailureKind _failure;
internal string _exceptionArgument;
internal bool _canThrow;
internal void Init(bool canThrow)
{
_canThrow = canThrow;
}
internal void SetFailure(ParseFailureKind failure)
{
SetFailure(failure, string.Empty);
}
internal void SetFailure(ParseFailureKind failure, string argument)
{
_failure = failure;
_exceptionArgument = argument;
if (_canThrow)
{
throw GetVersionParseException();
}
}
internal Exception GetVersionParseException()
{
switch (_failure)
{
case ParseFailureKind.ArgumentException:
return PSTraceSource.NewArgumentException("version");
case ParseFailureKind.ArgumentOutOfRangeException:
throw new ValidationMetadataException("ValidateRangeTooSmall",
null, Metadata.ValidateRangeSmallerThanMinRangeFailure,
_exceptionArgument, "0");
case ParseFailureKind.FormatException:
// Regenerate the FormatException as would be thrown by Int32.Parse()
try
{
Int32.Parse(_exceptionArgument, CultureInfo.InvariantCulture);
}
catch (FormatException e)
{
return e;
}
catch (OverflowException e)
{
return e;
}
break;
}
return PSTraceSource.NewArgumentException("version");
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Management.Automation;
using Microsoft.Management.Infrastructure;
using Microsoft.PowerShell.Cim;
using Dbg = System.Management.Automation.Diagnostics;
namespace Microsoft.PowerShell.Cmdletization.Cim
{
/// <summary>
/// Client-side filtering for
/// 1) filtering that cannot be translated into a server-side query (i.e. when CimQuery.WildcardToWqlLikeOperand reports that it cannot translate into WQL)
/// 2) detecting if all expected results have been received and giving friendly user errors otherwise (i.e. could not find process with name='foo'; details in Windows 8 Bugs: #60926)
/// </summary>
internal class ClientSideQuery : QueryBuilder
{
internal class NotFoundError
{
public NotFoundError()
{
this.ErrorMessageGenerator = GetErrorMessageForNotFound;
}
public NotFoundError(string propertyName, object propertyValue, bool wildcardsEnabled)
{
this.PropertyName = propertyName;
this.PropertyValue = propertyValue;
if (wildcardsEnabled)
{
var propertyValueAsString = propertyValue as string;
if ((propertyValueAsString != null) && (WildcardPattern.ContainsWildcardCharacters(propertyValueAsString)))
{
this.ErrorMessageGenerator =
(queryDescription, className) => GetErrorMessageForNotFound_ForWildcard(this.PropertyName, this.PropertyValue, className);
}
else
{
this.ErrorMessageGenerator =
(queryDescription, className) => GetErrorMessageForNotFound_ForEquality(this.PropertyName, this.PropertyValue, className);
}
}
else
{
this.ErrorMessageGenerator =
(queryDescription, className) => GetErrorMessageForNotFound_ForEquality(this.PropertyName, this.PropertyValue, className);
}
}
public string PropertyName { get; private set; }
public object PropertyValue { get; private set; }
public Func<string, string, string> ErrorMessageGenerator { get; private set; }
private static string GetErrorMessageForNotFound(string queryDescription, string className)
{
string message = string.Format(
CultureInfo.InvariantCulture, // queryDescription should already be in the right format - can use invariant culture here
CmdletizationResources.CimJob_NotFound_ComplexCase,
queryDescription,
className);
return message;
}
private static string GetErrorMessageForNotFound_ForEquality(string propertyName, object propertyValue, string className)
{
string message = string.Format(
CultureInfo.InvariantCulture, // queryDescription should already be in the right format - can use invariant culture here
CmdletizationResources.CimJob_NotFound_SimpleGranularCase_Equality,
propertyName,
propertyValue,
className);
return message;
}
private static string GetErrorMessageForNotFound_ForWildcard(string propertyName, object propertyValue, string className)
{
string message = string.Format(
CultureInfo.InvariantCulture, // queryDescription should already be in the right format - can use invariant culture here
CmdletizationResources.CimJob_NotFound_SimpleGranularCase_Wildcard,
propertyName,
propertyValue,
className);
return message;
}
}
private abstract class CimInstanceFilterBase
{
protected abstract bool IsMatchCore(CimInstance cimInstance);
protected BehaviorOnNoMatch BehaviorOnNoMatch { get; set; }
private bool HadMatches { get; set; }
public bool IsMatch(CimInstance cimInstance)
{
bool isMatch = this.IsMatchCore(cimInstance);
this.HadMatches = this.HadMatches || isMatch;
return isMatch;
}
public virtual bool ShouldReportErrorOnNoMatches_IfMultipleFilters()
{
switch (this.BehaviorOnNoMatch)
{
case BehaviorOnNoMatch.ReportErrors:
return true;
case BehaviorOnNoMatch.SilentlyContinue:
return false;
case BehaviorOnNoMatch.Default:
default:
Dbg.Assert(false, "BehaviorOnNoMatch.Default should be handled by derived classes");
return false;
}
}
public virtual IEnumerable<NotFoundError> GetNotFoundErrors_IfThisIsTheOnlyFilter()
{
switch (this.BehaviorOnNoMatch)
{
case BehaviorOnNoMatch.ReportErrors:
if (this.HadMatches)
{
return Enumerable.Empty<NotFoundError>();
}
else
{
return new[] { new NotFoundError() };
}
case BehaviorOnNoMatch.SilentlyContinue:
return Enumerable.Empty<NotFoundError>();
case BehaviorOnNoMatch.Default:
default:
Dbg.Assert(false, "BehaviorOnNoMatch.Default should be handled by derived classes");
return Enumerable.Empty<NotFoundError>();
}
}
}
private abstract class CimInstancePropertyBasedFilter : CimInstanceFilterBase
{
private readonly List<PropertyValueFilter> _propertyValueFilters = new List<PropertyValueFilter>();
protected IEnumerable<PropertyValueFilter> PropertyValueFilters { get { return _propertyValueFilters; } }
protected void AddPropertyValueFilter(PropertyValueFilter propertyValueFilter)
{
_propertyValueFilters.Add(propertyValueFilter);
}
protected override bool IsMatchCore(CimInstance cimInstance)
{
bool isMatch = false;
foreach (PropertyValueFilter propertyValueFilter in this.PropertyValueFilters)
{
if (propertyValueFilter.IsMatch(cimInstance))
{
isMatch = true;
if (this.BehaviorOnNoMatch == BehaviorOnNoMatch.SilentlyContinue)
{
break;
}
}
}
return isMatch;
}
}
private class CimInstanceRegularFilter : CimInstancePropertyBasedFilter
{
public CimInstanceRegularFilter(string propertyName, IEnumerable allowedPropertyValues, bool wildcardsEnabled, BehaviorOnNoMatch behaviorOnNoMatch)
{
var valueBehaviors = new HashSet<BehaviorOnNoMatch>();
foreach (object allowedPropertyValue in allowedPropertyValues)
{
PropertyValueFilter filter =
new PropertyValueRegularFilter(
propertyName,
allowedPropertyValue,
wildcardsEnabled,
behaviorOnNoMatch);
this.AddPropertyValueFilter(filter);
valueBehaviors.Add(filter.BehaviorOnNoMatch);
}
if (valueBehaviors.Count == 1)
{
this.BehaviorOnNoMatch = valueBehaviors.Single();
}
else
{
this.BehaviorOnNoMatch = behaviorOnNoMatch;
}
}
public override bool ShouldReportErrorOnNoMatches_IfMultipleFilters()
{
switch (this.BehaviorOnNoMatch)
{
case BehaviorOnNoMatch.ReportErrors:
return true;
case BehaviorOnNoMatch.SilentlyContinue:
return false;
case BehaviorOnNoMatch.Default:
default:
return this.PropertyValueFilters
.Where(f => !f.HadMatch).Any(f => f.BehaviorOnNoMatch == BehaviorOnNoMatch.ReportErrors);
}
}
public override IEnumerable<NotFoundError> GetNotFoundErrors_IfThisIsTheOnlyFilter()
{
foreach (PropertyValueFilter propertyValueFilter in this.PropertyValueFilters)
{
if (propertyValueFilter.BehaviorOnNoMatch != BehaviorOnNoMatch.ReportErrors)
{
continue;
}
if (propertyValueFilter.HadMatch)
{
continue;
}
var propertyValueRegularFilter = (PropertyValueRegularFilter)propertyValueFilter;
yield return propertyValueRegularFilter.GetGranularNotFoundError();
}
}
}
private class CimInstanceExcludeFilter : CimInstancePropertyBasedFilter
{
public CimInstanceExcludeFilter(string propertyName, IEnumerable excludedPropertyValues, bool wildcardsEnabled, BehaviorOnNoMatch behaviorOnNoMatch)
{
if (behaviorOnNoMatch == BehaviorOnNoMatch.Default)
{
this.BehaviorOnNoMatch = BehaviorOnNoMatch.SilentlyContinue;
}
else
{
this.BehaviorOnNoMatch = behaviorOnNoMatch;
}
foreach (object excludedPropertyValue in excludedPropertyValues)
{
this.AddPropertyValueFilter(
new PropertyValueExcludeFilter(
propertyName,
excludedPropertyValue,
wildcardsEnabled,
behaviorOnNoMatch));
}
}
}
private class CimInstanceMinFilter : CimInstancePropertyBasedFilter
{
public CimInstanceMinFilter(string propertyName, object minPropertyValue, BehaviorOnNoMatch behaviorOnNoMatch)
{
if (behaviorOnNoMatch == BehaviorOnNoMatch.Default)
{
this.BehaviorOnNoMatch = BehaviorOnNoMatch.SilentlyContinue;
}
else
{
this.BehaviorOnNoMatch = behaviorOnNoMatch;
}
this.AddPropertyValueFilter(
new PropertyValueMinFilter(
propertyName,
minPropertyValue,
behaviorOnNoMatch));
}
}
private class CimInstanceMaxFilter : CimInstancePropertyBasedFilter
{
public CimInstanceMaxFilter(string propertyName, object minPropertyValue, BehaviorOnNoMatch behaviorOnNoMatch)
{
if (behaviorOnNoMatch == BehaviorOnNoMatch.Default)
{
this.BehaviorOnNoMatch = BehaviorOnNoMatch.SilentlyContinue;
}
else
{
this.BehaviorOnNoMatch = behaviorOnNoMatch;
}
this.AddPropertyValueFilter(
new PropertyValueMaxFilter(
propertyName,
minPropertyValue,
behaviorOnNoMatch));
}
}
private class CimInstanceAssociationFilter : CimInstanceFilterBase
{
public CimInstanceAssociationFilter(BehaviorOnNoMatch behaviorOnNoMatch)
{
if (behaviorOnNoMatch == BehaviorOnNoMatch.Default)
{
this.BehaviorOnNoMatch = BehaviorOnNoMatch.ReportErrors;
}
else
{
this.BehaviorOnNoMatch = behaviorOnNoMatch;
}
}
protected override bool IsMatchCore(CimInstance cimInstance)
{
return true; // the fact that this method is getting called means that CIM found associated instances (i.e. by definition the argument *is* matching)
}
}
internal abstract class PropertyValueFilter
{
protected PropertyValueFilter(string propertyName, object expectedPropertyValue, BehaviorOnNoMatch behaviorOnNoMatch)
{
PropertyName = propertyName;
_behaviorOnNoMatch = behaviorOnNoMatch;
OriginalExpectedPropertyValue = expectedPropertyValue;
CimTypedExpectedPropertyValue = CimValueConverter.ConvertFromDotNetToCim(expectedPropertyValue);
}
public BehaviorOnNoMatch BehaviorOnNoMatch
{
get
{
if (_behaviorOnNoMatch == BehaviorOnNoMatch.Default)
{
_behaviorOnNoMatch = this.GetDefaultBehaviorWhenNoMatchesFound(this.CimTypedExpectedPropertyValue);
}
return _behaviorOnNoMatch;
}
}
protected abstract BehaviorOnNoMatch GetDefaultBehaviorWhenNoMatchesFound(object cimTypedExpectedPropertyValue);
private BehaviorOnNoMatch _behaviorOnNoMatch;
public string PropertyName { get; }
public object CimTypedExpectedPropertyValue { get; }
public object OriginalExpectedPropertyValue { get; }
public bool HadMatch { get; private set; }
public bool IsMatch(CimInstance o)
{
if (o == null)
{
return false;
}
CimProperty propertyInfo = o.CimInstanceProperties[PropertyName];
if (propertyInfo == null)
{
return false;
}
object actualPropertyValue = propertyInfo.Value;
if (CimTypedExpectedPropertyValue == null)
{
HadMatch = HadMatch || (actualPropertyValue == null);
return actualPropertyValue == null;
}
CimValueConverter.AssertIntrinsicCimValue(actualPropertyValue);
CimValueConverter.AssertIntrinsicCimValue(CimTypedExpectedPropertyValue);
actualPropertyValue = ConvertActualValueToExpectedType(actualPropertyValue, CimTypedExpectedPropertyValue);
Dbg.Assert(IsSameType(actualPropertyValue, CimTypedExpectedPropertyValue), "Types of actual vs expected property value should always match");
bool isMatch = this.IsMatchingValue(actualPropertyValue);
HadMatch = HadMatch || isMatch;
return isMatch;
}
protected abstract bool IsMatchingValue(object actualPropertyValue);
private object ConvertActualValueToExpectedType(object actualPropertyValue, object expectedPropertyValue)
{
if ((actualPropertyValue is string) && (!(expectedPropertyValue is string)))
{
actualPropertyValue = LanguagePrimitives.ConvertTo(actualPropertyValue, expectedPropertyValue.GetType(), CultureInfo.InvariantCulture);
}
if (!IsSameType(actualPropertyValue, expectedPropertyValue))
{
var errorMessage = string.Format(
CultureInfo.InvariantCulture,
CmdletizationResources.CimJob_MismatchedTypeOfPropertyReturnedByQuery,
PropertyName,
actualPropertyValue.GetType().FullName,
expectedPropertyValue.GetType().FullName);
throw CimJobException.CreateWithoutJobContext(
errorMessage,
"CimJob_PropertyTypeUnexpectedByClientSideQuery",
ErrorCategory.InvalidType);
}
return actualPropertyValue;
}
private static bool IsSameType(object actualPropertyValue, object expectedPropertyValue)
{
if (actualPropertyValue == null)
{
return true;
}
if (expectedPropertyValue == null)
{
return true;
}
if (actualPropertyValue is TimeSpan || actualPropertyValue is DateTime)
{
return expectedPropertyValue is TimeSpan || expectedPropertyValue is DateTime;
}
return actualPropertyValue.GetType() == expectedPropertyValue.GetType();
}
}
internal class PropertyValueRegularFilter : PropertyValueFilter
{
private readonly bool _wildcardsEnabled;
public PropertyValueRegularFilter(string propertyName, object expectedPropertyValue, bool wildcardsEnabled, BehaviorOnNoMatch behaviorOnNoMatch)
: base(propertyName, expectedPropertyValue, behaviorOnNoMatch)
{
_wildcardsEnabled = wildcardsEnabled;
}
protected override BehaviorOnNoMatch GetDefaultBehaviorWhenNoMatchesFound(object cimTypedExpectedPropertyValue)
{
if (!_wildcardsEnabled)
{
return BehaviorOnNoMatch.ReportErrors;
}
else
{
string expectedPropertyValueAsString = cimTypedExpectedPropertyValue as string;
if (expectedPropertyValueAsString != null && WildcardPattern.ContainsWildcardCharacters(expectedPropertyValueAsString))
{
return BehaviorOnNoMatch.SilentlyContinue;
}
else
{
return BehaviorOnNoMatch.ReportErrors;
}
}
}
internal NotFoundError GetGranularNotFoundError()
{
return new NotFoundError(this.PropertyName, this.OriginalExpectedPropertyValue, _wildcardsEnabled);
}
protected override bool IsMatchingValue(object actualPropertyValue)
{
if (_wildcardsEnabled)
{
return WildcardEqual(this.PropertyName, actualPropertyValue, this.CimTypedExpectedPropertyValue);
}
else
{
return NonWildcardEqual(this.PropertyName, actualPropertyValue, this.CimTypedExpectedPropertyValue);
}
}
private static bool NonWildcardEqual(string propertyName, object actualPropertyValue, object expectedPropertyValue)
{
// perform .NET-based, case-insensitive equality test for 1) characters and 2) strings
if (expectedPropertyValue is char)
{
expectedPropertyValue = expectedPropertyValue.ToString();
actualPropertyValue = actualPropertyValue.ToString();
}
var expectedPropertyValueAsString = expectedPropertyValue as string;
if (expectedPropertyValueAsString != null)
{
var actualPropertyValueAsString = (string)actualPropertyValue;
return actualPropertyValueAsString.Equals(expectedPropertyValueAsString, StringComparison.OrdinalIgnoreCase);
}
// perform .NET based equality for everything else
return actualPropertyValue.Equals(expectedPropertyValue);
}
private static bool WildcardEqual(string propertyName, object actualPropertyValue, object expectedPropertyValue)
{
string actualPropertyValueAsString;
string expectedPropertyValueAsString;
if (!LanguagePrimitives.TryConvertTo(actualPropertyValue, out actualPropertyValueAsString))
{
return false;
}
if (!LanguagePrimitives.TryConvertTo(expectedPropertyValue, out expectedPropertyValueAsString))
{
return false;
}
return WildcardPattern.Get(expectedPropertyValueAsString, WildcardOptions.IgnoreCase).IsMatch(actualPropertyValueAsString);
}
}
internal class PropertyValueExcludeFilter : PropertyValueRegularFilter
{
public PropertyValueExcludeFilter(string propertyName, object expectedPropertyValue, bool wildcardsEnabled, BehaviorOnNoMatch behaviorOnNoMatch)
: base(propertyName, expectedPropertyValue, wildcardsEnabled, behaviorOnNoMatch)
{
}
protected override BehaviorOnNoMatch GetDefaultBehaviorWhenNoMatchesFound(object cimTypedExpectedPropertyValue)
{
return BehaviorOnNoMatch.SilentlyContinue;
}
protected override bool IsMatchingValue(object actualPropertyValue)
{
return !base.IsMatchingValue(actualPropertyValue);
}
}
internal class PropertyValueMinFilter : PropertyValueFilter
{
public PropertyValueMinFilter(string propertyName, object expectedPropertyValue, BehaviorOnNoMatch behaviorOnNoMatch)
: base(propertyName, expectedPropertyValue, behaviorOnNoMatch)
{
}
protected override BehaviorOnNoMatch GetDefaultBehaviorWhenNoMatchesFound(object cimTypedExpectedPropertyValue)
{
return BehaviorOnNoMatch.SilentlyContinue;
}
protected override bool IsMatchingValue(object actualPropertyValue)
{
return ActualValueGreaterThanOrEqualToExpectedValue(this.PropertyName, actualPropertyValue, this.CimTypedExpectedPropertyValue);
}
private static bool ActualValueGreaterThanOrEqualToExpectedValue(string propertyName, object actualPropertyValue, object expectedPropertyValue)
{
try
{
var expectedComparable = expectedPropertyValue as IComparable;
if (expectedComparable == null)
{
return false;
}
return expectedComparable.CompareTo(actualPropertyValue) <= 0;
}
catch (ArgumentException)
{
return false;
}
}
}
internal class PropertyValueMaxFilter : PropertyValueFilter
{
public PropertyValueMaxFilter(string propertyName, object expectedPropertyValue, BehaviorOnNoMatch behaviorOnNoMatch)
: base(propertyName, expectedPropertyValue, behaviorOnNoMatch)
{
}
protected override BehaviorOnNoMatch GetDefaultBehaviorWhenNoMatchesFound(object cimTypedExpectedPropertyValue)
{
return BehaviorOnNoMatch.SilentlyContinue;
}
protected override bool IsMatchingValue(object actualPropertyValue)
{
return ActualValueLessThanOrEqualToExpectedValue(this.PropertyName, actualPropertyValue, this.CimTypedExpectedPropertyValue);
}
private static bool ActualValueLessThanOrEqualToExpectedValue(string propertyName, object actualPropertyValue, object expectedPropertyValue)
{
try
{
var actualComparable = actualPropertyValue as IComparable;
if (actualComparable == null)
{
return false;
}
return actualComparable.CompareTo(expectedPropertyValue) <= 0;
}
catch (ArgumentException)
{
return false;
}
}
}
private int _numberOfResultsFromMi;
private int _numberOfMatchingResults;
private readonly List<CimInstanceFilterBase> _filters = new List<CimInstanceFilterBase>();
private readonly object _myLock = new object();
#region "Public" interface for client-side filtering
internal bool IsResultMatchingClientSideQuery(CimInstance result)
{
lock (_myLock)
{
_numberOfResultsFromMi++;
if (_filters.All(f => f.IsMatch(result)))
{
_numberOfMatchingResults++;
return true;
}
else
{
return false;
}
}
}
internal IEnumerable<NotFoundError> GenerateNotFoundErrors()
{
if (_filters.Count > 1)
{
if (_numberOfMatchingResults > 0)
{
return Enumerable.Empty<NotFoundError>();
}
if (_filters.All(f => !f.ShouldReportErrorOnNoMatches_IfMultipleFilters()))
{
return Enumerable.Empty<NotFoundError>();
}
return new[] { new NotFoundError() };
}
CimInstanceFilterBase filter = _filters.SingleOrDefault();
if (filter != null)
{
return filter.GetNotFoundErrors_IfThisIsTheOnlyFilter();
}
return Enumerable.Empty<NotFoundError>();
}
#endregion
#region QueryBuilder interface
public override void FilterByProperty(string propertyName, IEnumerable allowedPropertyValues, bool wildcardsEnabled, BehaviorOnNoMatch behaviorOnNoMatch)
{
_filters.Add(new CimInstanceRegularFilter(propertyName, allowedPropertyValues, wildcardsEnabled, behaviorOnNoMatch));
}
public override void ExcludeByProperty(string propertyName, IEnumerable excludedPropertyValues, bool wildcardsEnabled, BehaviorOnNoMatch behaviorOnNoMatch)
{
_filters.Add(new CimInstanceExcludeFilter(propertyName, excludedPropertyValues, wildcardsEnabled, behaviorOnNoMatch));
}
public override void FilterByMinPropertyValue(string propertyName, object minPropertyValue, BehaviorOnNoMatch behaviorOnNoMatch)
{
_filters.Add(new CimInstanceMinFilter(propertyName, minPropertyValue, behaviorOnNoMatch));
}
public override void FilterByMaxPropertyValue(string propertyName, object maxPropertyValue, BehaviorOnNoMatch behaviorOnNoMatch)
{
_filters.Add(new CimInstanceMaxFilter(propertyName, maxPropertyValue, behaviorOnNoMatch));
}
public override void FilterByAssociatedInstance(object associatedInstance, string associationName, string sourceRole, string resultRole, BehaviorOnNoMatch behaviorOnNoMatch)
{
_filters.Add(new CimInstanceAssociationFilter(behaviorOnNoMatch));
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace System.Numerics.Tests
{
public class logTest
{
private static int s_samples = 10;
private static Random s_random = new Random(100);
[Fact]
public static void RunLogTests()
{
byte[] tempByteArray1 = new byte[0];
byte[] tempByteArray2 = new byte[0];
BigInteger bi;
// Log Method - Log(1,+Infinity)
Assert.Equal(0, BigInteger.Log(1, Double.PositiveInfinity));
// Log Method - Log(1,0)
VerifyLogString("0 1 bLog");
// Log Method - Log(0, >1)
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomPosByteArray(s_random, 10);
VerifyLogString(Print(tempByteArray1) + "0 bLog");
}
// Log Method - Log(0, 0>x>1)
for (int i = 0; i < s_samples; i++)
{
Assert.Equal(Double.PositiveInfinity, BigInteger.Log(0, s_random.NextDouble()));
}
// Log Method - base = 0
for (int i = 0; i < s_samples; i++)
{
bi = 1;
while (bi == 1)
{
bi = new BigInteger(GetRandomPosByteArray(s_random, 8));
}
Assert.True((Double.IsNaN(BigInteger.Log(bi, 0))));
}
// Log Method - base = 1
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(s_random);
VerifyLogString("1 " + Print(tempByteArray1) + "bLog");
}
// Log Method - base = NaN
for (int i = 0; i < s_samples; i++)
{
Assert.True(Double.IsNaN(BigInteger.Log(new BigInteger(GetRandomByteArray(s_random, 10)), Double.NaN)));
}
// Log Method - base = +Infinity
for (int i = 0; i < s_samples; i++)
{
Assert.True(Double.IsNaN(BigInteger.Log(new BigInteger(GetRandomByteArray(s_random, 10)), Double.PositiveInfinity)));
}
// Log Method - Log(0,1)
VerifyLogString("1 0 bLog");
// Log Method - base < 0
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(s_random, 10);
tempByteArray2 = GetRandomNegByteArray(s_random, 1);
VerifyLogString(Print(tempByteArray2) + Print(tempByteArray1) + "bLog");
Assert.True(Double.IsNaN(BigInteger.Log(new BigInteger(GetRandomByteArray(s_random, 10)), -s_random.NextDouble())));
}
// Log Method - value < 0
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomNegByteArray(s_random, 10);
tempByteArray2 = GetRandomPosByteArray(s_random, 1);
VerifyLogString(Print(tempByteArray2) + Print(tempByteArray1) + "bLog");
}
// Log Method - Small BigInteger and 0<base<0.5
for (int i = 0; i < s_samples; i++)
{
BigInteger temp = new BigInteger(GetRandomPosByteArray(s_random, 10));
Double newbase = Math.Min(s_random.NextDouble(), 0.5);
Assert.True(ApproxEqual(BigInteger.Log(temp, newbase), Math.Log((double)temp, newbase)));
}
// Log Method - Large BigInteger and 0<base<0.5
for (int i = 0; i < s_samples; i++)
{
BigInteger temp = new BigInteger(GetRandomPosByteArray(s_random, s_random.Next(1, 100)));
Double newbase = Math.Min(s_random.NextDouble(), 0.5);
Assert.True(ApproxEqual(BigInteger.Log(temp, newbase), Math.Log((double)temp, newbase)));
}
// Log Method - two small BigIntegers
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomPosByteArray(s_random, 2);
tempByteArray2 = GetRandomPosByteArray(s_random, 3);
VerifyLogString(Print(tempByteArray1) + Print(tempByteArray2) + "bLog");
}
// Log Method - one small and one large BigIntegers
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomPosByteArray(s_random, 1);
tempByteArray2 = GetRandomPosByteArray(s_random, s_random.Next(1, 100));
VerifyLogString(Print(tempByteArray1) + Print(tempByteArray2) + "bLog");
}
// Log Method - two large BigIntegers
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomPosByteArray(s_random, s_random.Next(1, 100));
tempByteArray2 = GetRandomPosByteArray(s_random, s_random.Next(1, 100));
VerifyLogString(Print(tempByteArray1) + Print(tempByteArray2) + "bLog");
}
// Log Method - Very Large BigInteger 1 << 128 << Int.MaxValue and 2
LargeValueLogTests(128, 1);
}
[Fact]
[OuterLoop]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
public static void RunLargeValueLogTests()
{
LargeValueLogTests(0, 4, 64, 3);
}
/// <summary>
/// Test Log Method on Very Large BigInteger more than (1 << Int.MaxValue) by base 2
/// Tested BigInteger are: pow(2, startShift + smallLoopShift * [1..smallLoopLimit] + Int32.MaxValue * [1..bigLoopLimit])
/// Note:
/// ToString() can not operate such large values
/// VerifyLogString() can not operate such large values,
/// Math.Log() can not operate such large values
/// </summary>
private static void LargeValueLogTests(int startShift, int bigShiftLoopLimit, int smallShift = 0, int smallShiftLoopLimit = 1)
{
BigInteger init = BigInteger.One << startShift;
double logbase = 2D;
for (int i = 0; i < smallShiftLoopLimit; i++)
{
BigInteger temp = init << ((i + 1) * smallShift);
for (int j = 0; j<bigShiftLoopLimit; j++)
{
temp = temp << (int.MaxValue / 2);
double expected =
(double)startShift +
smallShift * (double)(i + 1) +
(int.MaxValue / 2) * (double)(j + 1);
Assert.True(ApproxEqual(BigInteger.Log(temp, logbase), expected));
}
}
}
private static void VerifyLogString(string opstring)
{
StackCalc sc = new StackCalc(opstring);
while (sc.DoNextOperation())
{
Assert.Equal(sc.snCalc.Peek().ToString(), sc.myCalc.Peek().ToString());
}
}
private static void VerifyIdentityString(string opstring1, string opstring2)
{
StackCalc sc1 = new StackCalc(opstring1);
while (sc1.DoNextOperation())
{
//Run the full calculation
sc1.DoNextOperation();
}
StackCalc sc2 = new StackCalc(opstring2);
while (sc2.DoNextOperation())
{
//Run the full calculation
sc2.DoNextOperation();
}
Assert.Equal(sc1.snCalc.Peek().ToString(), sc2.snCalc.Peek().ToString());
}
private static byte[] GetRandomByteArray(Random random)
{
return GetRandomByteArray(random, random.Next(0, 100));
}
private static byte[] GetRandomByteArray(Random random, int size)
{
return MyBigIntImp.GetRandomByteArray(random, size);
}
private static Byte[] GetRandomPosByteArray(Random random, int size)
{
byte[] value = new byte[size];
for (int i = 0; i < value.Length; i++)
{
value[i] = (byte)random.Next(0, 256);
}
value[value.Length - 1] &= 0x7F;
return value;
}
private static Byte[] GetRandomNegByteArray(Random random, int size)
{
byte[] value = new byte[size];
for (int i = 0; i < value.Length; ++i)
{
value[i] = (byte)random.Next(0, 256);
}
value[value.Length - 1] |= 0x80;
return value;
}
private static String Print(byte[] bytes)
{
return MyBigIntImp.Print(bytes);
}
private static bool ApproxEqual(double value1, double value2)
{
//Special case values;
if (Double.IsNaN(value1))
{
return Double.IsNaN(value2);
}
if (Double.IsNegativeInfinity(value1))
{
return Double.IsNegativeInfinity(value2);
}
if (Double.IsPositiveInfinity(value1))
{
return Double.IsPositiveInfinity(value2);
}
if (value2 == 0)
{
return (value1 == 0);
}
double result = Math.Abs((value1 / value2) - 1);
return (result <= Double.Parse("1e-15"));
}
}
}
| |
// MbUnit Test Framework
//
// Copyright (c) 2004 Jonathan de Halleux
//
// This software is provided 'as-is', without any express or implied warranty.
//
// In no event will the authors be held liable for any damages arising from
// the use of this software.
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment in the product
// documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must
// not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
// MbUnit HomePage: http://www.mbunit.com
// Author: Jonathan de Halleux
namespace MbUnit.Core.Reports.Serialization
{
using System;
using System.Xml;
using System.Xml.Serialization;
using System.Reflection;
using System.IO;
using System.Collections;
/// <summary />
/// <remarks />
[XmlType(IncludeInSchema=true, TypeName="report-exception")]
[XmlRoot(ElementName="report-exception")]
[Serializable]
public sealed class ReportException {
/// <summary />
/// <remarks />
private string _stackTrace=null;
/// <summary />
/// <remarks />
private string _message=null;
/// <summary />
/// <remarks />
private string _source=null;
/// <summary />
/// <remarks />
private ReportException _exception=null;
/// <summary />
/// <remarks />
private string _type;
private PropertyCollection properties = new PropertyCollection();
[XmlArray("properties")]
[XmlArrayItem("property",Type = typeof(ReportProperty), IsNullable =false)]
public PropertyCollection Properties
{
get
{
return this.properties;
}
}
/// <summary />
/// <remarks />
[XmlElement(ElementName="message")]
public string Message {
get {
return this._message;
}
set {
this._message = value;
}
}
/// <summary />
/// <remarks />
[XmlElement(ElementName="source")]
public string Source {
get {
return this._source;
}
set {
this._source = value;
}
}
/// <summary />
/// <remarks />
[XmlElement(ElementName="stack-trace")]
public string StackTrace {
get {
return this._stackTrace;
}
set {
this._stackTrace = value;
}
}
/// <summary />
/// <remarks />
[XmlElement(ElementName="exception")]
public ReportException Exception {
get {
return this._exception;
}
set {
this._exception = value;
}
}
/// <summary />
/// <remarks />
[XmlAttribute(AttributeName="type")]
public string Type {
get {
return this._type;
}
set {
this._type = value;
}
}
public override string ToString()
{
StringWriter sw =new StringWriter();
sw.WriteLine("{0}",this.Type);
sw.WriteLine("Message: {0}",this.Message);
sw.WriteLine("Source: {0}",this.Source);
sw.WriteLine("StackTrace:");
sw.WriteLine(this.StackTrace);
if (this.Exception!=null)
{
sw.WriteLine("Inner Exception");
sw.WriteLine(this.Exception.ToString());
}
return sw.ToString();
}
public static ReportException FromException(Exception ex)
{
if (ex==null)
throw new ArgumentNullException("ex");
ReportException rex = new ReportException();
if (ex.GetType() == typeof(TargetInvocationException) && ex.InnerException!=null)
ex = ex.InnerException;
rex.Type = ex.GetType().ToString();
rex.Message = String.Format("{0}",ex.Message);
rex.Source = String.Format("{0}",ex.Source);
rex.StackTrace = ex.StackTrace;
if (ex.InnerException!=null)
rex.Exception = FromException(ex.InnerException);
foreach (PropertyInfo property in ex.GetType().GetProperties())
{
if (property.Name == "Message"
|| property.Name == "Source"
|| property.Name == "StackTrace"
|| property.Name == "InnerException"
|| property.Name == "Data")
continue;
ReportProperty p = new ReportProperty(ex, property);
rex.Properties.AddReportProperty(p);
}
/*
if (ex.Data!=null)
{
foreach (DictionaryEntry de in ex.Data)
{
ReportProperty p = new ReportProperty(de);
rex.Properties.Add(p);
}
}
*/
return rex;
}
[Serializable]
public sealed class PropertyCollection : CollectionBase
{
/// <summary />
/// <remarks />
public PropertyCollection()
{
}
/// <summary />
/// <remarks />
public object this[int index] {
get {
return this.List[index];
}
set {
this.List[index] = value;
}
}
/// <summary />
/// <remarks />
public void Add(object o) {
this.List.Add(o);
}
/// <summary />
/// <remarks />
public void AddReportProperty(ReportProperty o) {
this.List.Add(o);
}
/// <summary />
/// <remarks />
public bool ContainsReportProperty(ReportProperty o)
{
return this.List.Contains(o);
}
/// <summary />
/// <remarks />
public void RemoveReportProperty(ReportProperty o)
{
this.List.Remove(o);
}
}
}
}
| |
// 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.Diagnostics;
using System.Linq;
using System.Security.Claims;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.Net.Http.Headers;
namespace Microsoft.AspNetCore.Authentication.Cookies
{
/// <summary>
/// Implementation for the cookie-based authentication handler.
/// </summary>
public class CookieAuthenticationHandler : SignInAuthenticationHandler<CookieAuthenticationOptions>
{
private const string HeaderValueNoCache = "no-cache";
private const string HeaderValueNoCacheNoStore = "no-cache,no-store";
private const string HeaderValueEpocDate = "Thu, 01 Jan 1970 00:00:00 GMT";
private const string SessionIdClaim = "Microsoft.AspNetCore.Authentication.Cookies-SessionId";
private bool _shouldRefresh;
private bool _signInCalled;
private bool _signOutCalled;
private DateTimeOffset? _refreshIssuedUtc;
private DateTimeOffset? _refreshExpiresUtc;
private string? _sessionKey;
private Task<AuthenticateResult>? _readCookieTask;
private AuthenticationTicket? _refreshTicket;
/// <summary>
/// Initializes a new instance of <see cref="CookieAuthenticationHandler"/>.
/// </summary>
/// <param name="options">Accessor to <see cref="CookieAuthenticationOptions"/>.</param>
/// <param name="logger">The <see cref="ILoggerFactory"/>.</param>
/// <param name="encoder">The <see cref="UrlEncoder"/>.</param>
/// <param name="clock">The <see cref="ISystemClock"/>.</param>
public CookieAuthenticationHandler(IOptionsMonitor<CookieAuthenticationOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock)
: base(options, logger, encoder, clock)
{ }
/// <summary>
/// The handler calls methods on the events which give the application control at certain points where processing is occurring.
/// If it is not provided a default instance is supplied which does nothing when the methods are called.
/// </summary>
protected new CookieAuthenticationEvents Events
{
get { return (CookieAuthenticationEvents)base.Events!; }
set { base.Events = value; }
}
/// <inheritdoc />
protected override Task InitializeHandlerAsync()
{
// Cookies needs to finish the response
Context.Response.OnStarting(FinishResponseAsync);
return Task.CompletedTask;
}
/// <summary>
/// Creates a new instance of the events instance.
/// </summary>
/// <returns>A new instance of the events instance.</returns>
protected override Task<object> CreateEventsAsync() => Task.FromResult<object>(new CookieAuthenticationEvents());
private Task<AuthenticateResult> EnsureCookieTicket()
{
// We only need to read the ticket once
if (_readCookieTask == null)
{
_readCookieTask = ReadCookieTicket();
}
return _readCookieTask;
}
private async Task CheckForRefreshAsync(AuthenticationTicket ticket)
{
var currentUtc = Clock.UtcNow;
var issuedUtc = ticket.Properties.IssuedUtc;
var expiresUtc = ticket.Properties.ExpiresUtc;
var allowRefresh = ticket.Properties.AllowRefresh ?? true;
if (issuedUtc != null && expiresUtc != null && Options.SlidingExpiration && allowRefresh)
{
var timeElapsed = currentUtc.Subtract(issuedUtc.Value);
var timeRemaining = expiresUtc.Value.Subtract(currentUtc);
var eventContext = new CookieSlidingExpirationContext(Context, Scheme, Options, ticket, timeElapsed, timeRemaining)
{
ShouldRenew = timeRemaining < timeElapsed,
};
await Options.Events.OnCheckSlidingExpiration(eventContext);
if (eventContext.ShouldRenew)
{
RequestRefresh(ticket);
}
}
}
private void RequestRefresh(AuthenticationTicket ticket, ClaimsPrincipal? replacedPrincipal = null)
{
var issuedUtc = ticket.Properties.IssuedUtc;
var expiresUtc = ticket.Properties.ExpiresUtc;
if (issuedUtc != null && expiresUtc != null)
{
_shouldRefresh = true;
var currentUtc = Clock.UtcNow;
_refreshIssuedUtc = currentUtc;
var timeSpan = expiresUtc.Value.Subtract(issuedUtc.Value);
_refreshExpiresUtc = currentUtc.Add(timeSpan);
_refreshTicket = CloneTicket(ticket, replacedPrincipal);
}
}
private static AuthenticationTicket CloneTicket(AuthenticationTicket ticket, ClaimsPrincipal? replacedPrincipal)
{
var principal = replacedPrincipal ?? ticket.Principal;
var newPrincipal = new ClaimsPrincipal();
foreach (var identity in principal.Identities)
{
newPrincipal.AddIdentity(identity.Clone());
}
var newProperties = new AuthenticationProperties();
foreach (var item in ticket.Properties.Items)
{
newProperties.Items[item.Key] = item.Value;
}
return new AuthenticationTicket(newPrincipal, newProperties, ticket.AuthenticationScheme);
}
private async Task<AuthenticateResult> ReadCookieTicket()
{
var cookie = Options.CookieManager.GetRequestCookie(Context, Options.Cookie.Name!);
if (string.IsNullOrEmpty(cookie))
{
return AuthenticateResult.NoResult();
}
var ticket = Options.TicketDataFormat.Unprotect(cookie, GetTlsTokenBinding());
if (ticket == null)
{
return AuthenticateResult.Fail("Unprotect ticket failed");
}
if (Options.SessionStore != null)
{
var claim = ticket.Principal.Claims.FirstOrDefault(c => c.Type.Equals(SessionIdClaim));
if (claim == null)
{
return AuthenticateResult.Fail("SessionId missing");
}
// Only store _sessionKey if it matches an existing session. Otherwise we'll create a new one.
ticket = await Options.SessionStore.RetrieveAsync(claim.Value, Context.RequestAborted);
if (ticket == null)
{
return AuthenticateResult.Fail("Identity missing in session store");
}
_sessionKey = claim.Value;
}
var currentUtc = Clock.UtcNow;
var expiresUtc = ticket.Properties.ExpiresUtc;
if (expiresUtc != null && expiresUtc.Value < currentUtc)
{
if (Options.SessionStore != null)
{
await Options.SessionStore.RemoveAsync(_sessionKey!, Context.RequestAborted);
}
return AuthenticateResult.Fail("Ticket expired");
}
// Finally we have a valid ticket
return AuthenticateResult.Success(ticket);
}
/// <inheritdoc />
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
var result = await EnsureCookieTicket();
if (!result.Succeeded)
{
return result;
}
// We check this before the ValidatePrincipal event because we want to make sure we capture a clean clone
// without picking up any per-request modifications to the principal.
await CheckForRefreshAsync(result.Ticket);
Debug.Assert(result.Ticket != null);
var context = new CookieValidatePrincipalContext(Context, Scheme, Options, result.Ticket);
await Events.ValidatePrincipal(context);
if (context.Principal == null)
{
return AuthenticateResult.Fail("No principal.");
}
if (context.ShouldRenew)
{
RequestRefresh(result.Ticket, context.Principal);
}
return AuthenticateResult.Success(new AuthenticationTicket(context.Principal, context.Properties, Scheme.Name));
}
private CookieOptions BuildCookieOptions()
{
var cookieOptions = Options.Cookie.Build(Context);
// ignore the 'Expires' value as this will be computed elsewhere
cookieOptions.Expires = null;
return cookieOptions;
}
/// <inheritdoc />
protected virtual async Task FinishResponseAsync()
{
// Only renew if requested, and neither sign in or sign out was called
if (!_shouldRefresh || _signInCalled || _signOutCalled)
{
return;
}
var ticket = _refreshTicket;
if (ticket != null)
{
var properties = ticket.Properties;
if (_refreshIssuedUtc.HasValue)
{
properties.IssuedUtc = _refreshIssuedUtc;
}
if (_refreshExpiresUtc.HasValue)
{
properties.ExpiresUtc = _refreshExpiresUtc;
}
if (Options.SessionStore != null && _sessionKey != null)
{
await Options.SessionStore.RenewAsync(_sessionKey, ticket, Context.RequestAborted);
var principal = new ClaimsPrincipal(
new ClaimsIdentity(
new[] { new Claim(SessionIdClaim, _sessionKey, ClaimValueTypes.String, Options.ClaimsIssuer) },
Scheme.Name));
ticket = new AuthenticationTicket(principal, null, Scheme.Name);
}
var cookieValue = Options.TicketDataFormat.Protect(ticket, GetTlsTokenBinding());
var cookieOptions = BuildCookieOptions();
if (properties.IsPersistent && _refreshExpiresUtc.HasValue)
{
cookieOptions.Expires = _refreshExpiresUtc.Value.ToUniversalTime();
}
Options.CookieManager.AppendResponseCookie(
Context,
Options.Cookie.Name!,
cookieValue,
cookieOptions);
await ApplyHeaders(shouldRedirectToReturnUrl: false, properties: properties);
}
}
/// <inheritdoc />
protected override async Task HandleSignInAsync(ClaimsPrincipal user, AuthenticationProperties? properties)
{
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
properties = properties ?? new AuthenticationProperties();
_signInCalled = true;
// Process the request cookie to initialize members like _sessionKey.
await EnsureCookieTicket();
var cookieOptions = BuildCookieOptions();
var signInContext = new CookieSigningInContext(
Context,
Scheme,
Options,
user,
properties,
cookieOptions);
DateTimeOffset issuedUtc;
if (signInContext.Properties.IssuedUtc.HasValue)
{
issuedUtc = signInContext.Properties.IssuedUtc.Value;
}
else
{
issuedUtc = Clock.UtcNow;
signInContext.Properties.IssuedUtc = issuedUtc;
}
if (!signInContext.Properties.ExpiresUtc.HasValue)
{
signInContext.Properties.ExpiresUtc = issuedUtc.Add(Options.ExpireTimeSpan);
}
await Events.SigningIn(signInContext);
if (signInContext.Properties.IsPersistent)
{
var expiresUtc = signInContext.Properties.ExpiresUtc ?? issuedUtc.Add(Options.ExpireTimeSpan);
signInContext.CookieOptions.Expires = expiresUtc.ToUniversalTime();
}
var ticket = new AuthenticationTicket(signInContext.Principal!, signInContext.Properties, signInContext.Scheme.Name);
if (Options.SessionStore != null)
{
if (_sessionKey != null)
{
// Renew the ticket in cases of multiple requests see: https://github.com/dotnet/aspnetcore/issues/22135
await Options.SessionStore.RenewAsync(_sessionKey, ticket, Context.RequestAborted);
}
else
{
_sessionKey = await Options.SessionStore.StoreAsync(ticket, Context.RequestAborted);
}
var principal = new ClaimsPrincipal(
new ClaimsIdentity(
new[] { new Claim(SessionIdClaim, _sessionKey, ClaimValueTypes.String, Options.ClaimsIssuer) },
Options.ClaimsIssuer));
ticket = new AuthenticationTicket(principal, null, Scheme.Name);
}
var cookieValue = Options.TicketDataFormat.Protect(ticket, GetTlsTokenBinding());
Options.CookieManager.AppendResponseCookie(
Context,
Options.Cookie.Name!,
cookieValue,
signInContext.CookieOptions);
var signedInContext = new CookieSignedInContext(
Context,
Scheme,
signInContext.Principal!,
signInContext.Properties,
Options);
await Events.SignedIn(signedInContext);
// Only redirect on the login path
var shouldRedirect = Options.LoginPath.HasValue && OriginalPath == Options.LoginPath;
await ApplyHeaders(shouldRedirect, signedInContext.Properties);
Logger.AuthenticationSchemeSignedIn(Scheme.Name);
}
/// <inheritdoc />
protected override async Task HandleSignOutAsync(AuthenticationProperties? properties)
{
properties = properties ?? new AuthenticationProperties();
_signOutCalled = true;
// Process the request cookie to initialize members like _sessionKey.
await EnsureCookieTicket();
var cookieOptions = BuildCookieOptions();
if (Options.SessionStore != null && _sessionKey != null)
{
await Options.SessionStore.RemoveAsync(_sessionKey, Context.RequestAborted);
}
var context = new CookieSigningOutContext(
Context,
Scheme,
Options,
properties,
cookieOptions);
await Events.SigningOut(context);
Options.CookieManager.DeleteCookie(
Context,
Options.Cookie.Name!,
context.CookieOptions);
// Only redirect on the logout path
var shouldRedirect = Options.LogoutPath.HasValue && OriginalPath == Options.LogoutPath;
await ApplyHeaders(shouldRedirect, context.Properties);
Logger.AuthenticationSchemeSignedOut(Scheme.Name);
}
private async Task ApplyHeaders(bool shouldRedirectToReturnUrl, AuthenticationProperties properties)
{
Response.Headers.CacheControl = HeaderValueNoCacheNoStore;
Response.Headers.Pragma = HeaderValueNoCache;
Response.Headers.Expires = HeaderValueEpocDate;
if (shouldRedirectToReturnUrl && Response.StatusCode == 200)
{
// set redirect uri in order:
// 1. properties.RedirectUri
// 2. query parameter ReturnUrlParameter
//
// Absolute uri is not allowed if it is from query string as query string is not
// a trusted source.
var redirectUri = properties.RedirectUri;
if (string.IsNullOrEmpty(redirectUri))
{
redirectUri = Request.Query[Options.ReturnUrlParameter];
if (string.IsNullOrEmpty(redirectUri) || !IsHostRelative(redirectUri))
{
redirectUri = null;
}
}
if (redirectUri != null)
{
await Events.RedirectToReturnUrl(
new RedirectContext<CookieAuthenticationOptions>(Context, Scheme, Options, properties, redirectUri));
}
}
}
private static bool IsHostRelative(string path)
{
if (string.IsNullOrEmpty(path))
{
return false;
}
if (path.Length == 1)
{
return path[0] == '/';
}
return path[0] == '/' && path[1] != '/' && path[1] != '\\';
}
/// <inheritdoc />
protected override async Task HandleForbiddenAsync(AuthenticationProperties properties)
{
var returnUrl = properties.RedirectUri;
if (string.IsNullOrEmpty(returnUrl))
{
returnUrl = OriginalPathBase + OriginalPath + Request.QueryString;
}
var accessDeniedUri = Options.AccessDeniedPath + QueryString.Create(Options.ReturnUrlParameter, returnUrl);
var redirectContext = new RedirectContext<CookieAuthenticationOptions>(Context, Scheme, Options, properties, BuildRedirectUri(accessDeniedUri));
await Events.RedirectToAccessDenied(redirectContext);
}
/// <inheritdoc />
protected override async Task HandleChallengeAsync(AuthenticationProperties properties)
{
var redirectUri = properties.RedirectUri;
if (string.IsNullOrEmpty(redirectUri))
{
redirectUri = OriginalPathBase + OriginalPath + Request.QueryString;
}
var loginUri = Options.LoginPath + QueryString.Create(Options.ReturnUrlParameter, redirectUri);
var redirectContext = new RedirectContext<CookieAuthenticationOptions>(Context, Scheme, Options, properties, BuildRedirectUri(loginUri));
await Events.RedirectToLogin(redirectContext);
}
private string? GetTlsTokenBinding()
{
var binding = Context.Features.Get<ITlsTokenBindingFeature>()?.GetProvidedTokenBindingId();
return binding == null ? null : Convert.ToBase64String(binding);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using SafeWinHttpHandle = Interop.WinHttp.SafeWinHttpHandle;
namespace System.Net.Http
{
internal class WinHttpResponseStream : Stream
{
private volatile bool _disposed;
private readonly WinHttpRequestState _state;
// TODO (Issue 2505): temporary pinned buffer caches of 1 item. Will be replaced by PinnableBufferCache.
private GCHandle _cachedReceivePinnedBuffer = new GCHandle();
internal WinHttpResponseStream(WinHttpRequestState state)
{
_state = state;
}
public override bool CanRead
{
get
{
return !_disposed;
}
}
public override bool CanSeek
{
get
{
return false;
}
}
public override bool CanWrite
{
get
{
return false;
}
}
public override long Length
{
get
{
CheckDisposed();
throw new NotSupportedException();
}
}
public override long Position
{
get
{
CheckDisposed();
throw new NotSupportedException();
}
set
{
CheckDisposed();
throw new NotSupportedException();
}
}
public override void Flush()
{
// Nothing to do.
}
public override Task FlushAsync(CancellationToken cancellationToken)
{
return cancellationToken.IsCancellationRequested ?
Task.FromCanceled(cancellationToken) :
Task.CompletedTask;
}
public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken token)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
if (offset < 0)
{
throw new ArgumentOutOfRangeException(nameof(offset));
}
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count));
}
if (count > buffer.Length - offset)
{
throw new ArgumentException(nameof(buffer));
}
if (token.IsCancellationRequested)
{
return Task.FromCanceled<int>(token);
}
CheckDisposed();
if (_state.TcsReadFromResponseStream != null && !_state.TcsReadFromResponseStream.Task.IsCompleted)
{
throw new InvalidOperationException(SR.net_http_no_concurrent_io_allowed);
}
// TODO (Issue 2505): replace with PinnableBufferCache.
if (!_cachedReceivePinnedBuffer.IsAllocated || _cachedReceivePinnedBuffer.Target != buffer)
{
if (_cachedReceivePinnedBuffer.IsAllocated)
{
_cachedReceivePinnedBuffer.Free();
}
_cachedReceivePinnedBuffer = GCHandle.Alloc(buffer, GCHandleType.Pinned);
}
_state.TcsReadFromResponseStream =
new TaskCompletionSource<int>(TaskCreationOptions.RunContinuationsAsynchronously);
_state.TcsQueryDataAvailable =
new TaskCompletionSource<int>(TaskCreationOptions.RunContinuationsAsynchronously);
_state.TcsQueryDataAvailable.Task.ContinueWith((previousTask) =>
{
if (previousTask.IsFaulted)
{
_state.TcsReadFromResponseStream.TrySetException(previousTask.Exception.InnerException);
}
else if (previousTask.IsCanceled || token.IsCancellationRequested)
{
_state.TcsReadFromResponseStream.TrySetCanceled(token);
}
else
{
int bytesToRead;
int bytesAvailable = previousTask.Result;
if (bytesAvailable > count)
{
bytesToRead = count;
}
else
{
bytesToRead = bytesAvailable;
}
lock (_state.Lock)
{
if (!Interop.WinHttp.WinHttpReadData(
_state.RequestHandle,
Marshal.UnsafeAddrOfPinnedArrayElement(buffer, offset),
(uint)bytesToRead,
IntPtr.Zero))
{
_state.TcsReadFromResponseStream.TrySetException(
new IOException(SR.net_http_io_read, WinHttpException.CreateExceptionUsingLastError()));
}
}
}
},
CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default);
// TODO: Issue #2165. Register callback on cancellation token to cancel WinHTTP operation.
lock (_state.Lock)
{
if (!Interop.WinHttp.WinHttpQueryDataAvailable(_state.RequestHandle, IntPtr.Zero))
{
_state.TcsReadFromResponseStream.TrySetException(
new IOException(SR.net_http_io_read, WinHttpException.CreateExceptionUsingLastError()));
}
}
return _state.TcsReadFromResponseStream.Task;
}
public override int Read(byte[] buffer, int offset, int count)
{
return ReadAsync(buffer, offset, count, CancellationToken.None).GetAwaiter().GetResult();
}
public override long Seek(long offset, SeekOrigin origin)
{
CheckDisposed();
throw new NotSupportedException();
}
public override void SetLength(long value)
{
CheckDisposed();
throw new NotSupportedException();
}
public override void Write(byte[] buffer, int offset, int count)
{
CheckDisposed();
throw new NotSupportedException();
}
protected override void Dispose(bool disposing)
{
if (!_disposed)
{
_disposed = true;
if (disposing)
{
// TODO (Issue 2508): Pinned buffers must be released in the callback, when it is guaranteed no further
// operations will be made to the send/receive buffers.
if (_cachedReceivePinnedBuffer.IsAllocated)
{
_cachedReceivePinnedBuffer.Free();
}
if (_state.RequestHandle != null)
{
_state.RequestHandle.Dispose();
_state.RequestHandle = null;
}
}
}
base.Dispose(disposing);
}
private void CheckDisposed()
{
if (_disposed)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
}
}
}
| |
// 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.Collections.Generic;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Input.Events;
using osu.Game.Tournament.Models;
using osuTK;
using osuTK.Graphics;
using osuTK.Input;
using SixLabors.Primitives;
namespace osu.Game.Tournament.Screens.Ladder.Components
{
public class DrawableTournamentMatch : CompositeDrawable
{
public readonly TournamentMatch Match;
private readonly bool editor;
protected readonly FillFlowContainer<DrawableMatchTeam> Flow;
private readonly Drawable selectionBox;
private readonly Drawable currentMatchSelectionBox;
private Bindable<TournamentMatch> globalSelection;
[Resolved(CanBeNull = true)]
private LadderEditorInfo editorInfo { get; set; }
[Resolved(CanBeNull = true)]
private LadderInfo ladderInfo { get; set; }
public DrawableTournamentMatch(TournamentMatch match, bool editor = false)
{
Match = match;
this.editor = editor;
AutoSizeAxes = Axes.Both;
Margin = new MarginPadding(5);
InternalChildren = new[]
{
selectionBox = new Container
{
CornerRadius = 5,
Masking = true,
Scale = new Vector2(1.05f),
RelativeSizeAxes = Axes.Both,
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Alpha = 0,
Colour = Color4.YellowGreen,
Child = new Box { RelativeSizeAxes = Axes.Both }
},
currentMatchSelectionBox = new Container
{
CornerRadius = 5,
Masking = true,
Scale = new Vector2(1.05f),
RelativeSizeAxes = Axes.Both,
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Alpha = 0,
Colour = Color4.OrangeRed,
Child = new Box { RelativeSizeAxes = Axes.Both }
},
Flow = new FillFlowContainer<DrawableMatchTeam>
{
AutoSizeAxes = Axes.Both,
Direction = FillDirection.Vertical,
Spacing = new Vector2(2)
}
};
boundReference(match.Team1).BindValueChanged(_ => updateTeams());
boundReference(match.Team2).BindValueChanged(_ => updateTeams());
boundReference(match.Team1Score).BindValueChanged(_ => updateWinConditions());
boundReference(match.Team2Score).BindValueChanged(_ => updateWinConditions());
boundReference(match.Round).BindValueChanged(_ =>
{
updateWinConditions();
Changed?.Invoke();
});
boundReference(match.Completed).BindValueChanged(_ => updateProgression());
boundReference(match.Progression).BindValueChanged(_ => updateProgression());
boundReference(match.LosersProgression).BindValueChanged(_ => updateProgression());
boundReference(match.Losers).BindValueChanged(_ =>
{
updateTeams();
Changed?.Invoke();
});
boundReference(match.Current).BindValueChanged(_ => updateCurrentMatch(), true);
boundReference(match.Position).BindValueChanged(pos =>
{
if (!IsDragged)
Position = new Vector2(pos.NewValue.X, pos.NewValue.Y);
Changed?.Invoke();
}, true);
updateTeams();
}
/// <summary>
/// Fired when somethign changed that requires a ladder redraw.
/// </summary>
public Action Changed;
private readonly List<IUnbindable> refBindables = new List<IUnbindable>();
private T boundReference<T>(T obj)
where T : IBindable
{
obj = (T)obj.GetBoundCopy();
refBindables.Add(obj);
return obj;
}
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
foreach (var b in refBindables)
b.UnbindAll();
}
private void updateCurrentMatch()
{
if (Match.Current.Value)
currentMatchSelectionBox.Show();
else
currentMatchSelectionBox.Hide();
}
private bool selected;
public bool Selected
{
get => selected;
set
{
if (value == selected) return;
selected = value;
if (selected)
{
selectionBox.Show();
if (editor)
editorInfo.Selected.Value = Match;
else
ladderInfo.CurrentMatch.Value = Match;
}
else
selectionBox.Hide();
}
}
private void updateProgression()
{
if (!Match.Completed.Value)
{
// ensure we clear any of our teams from our progression.
// this is not pretty logic but should suffice for now.
if (Match.Progression.Value != null && Match.Progression.Value.Team1.Value == Match.Team1.Value)
Match.Progression.Value.Team1.Value = null;
if (Match.Progression.Value != null && Match.Progression.Value.Team2.Value == Match.Team2.Value)
Match.Progression.Value.Team2.Value = null;
if (Match.LosersProgression.Value != null && Match.LosersProgression.Value.Team1.Value == Match.Team1.Value)
Match.LosersProgression.Value.Team1.Value = null;
if (Match.LosersProgression.Value != null && Match.LosersProgression.Value.Team2.Value == Match.Team2.Value)
Match.LosersProgression.Value.Team2.Value = null;
}
else
{
transferProgression(Match.Progression?.Value, Match.Winner);
transferProgression(Match.LosersProgression?.Value, Match.Loser);
}
Changed?.Invoke();
}
private void transferProgression(TournamentMatch destination, TournamentTeam team)
{
if (destination == null) return;
bool progressionAbove = destination.ID < Match.ID;
Bindable<TournamentTeam> destinationTeam;
// check for the case where we have already transferred out value
if (destination.Team1.Value == team)
destinationTeam = destination.Team1;
else if (destination.Team2.Value == team)
destinationTeam = destination.Team2;
else
{
destinationTeam = progressionAbove ? destination.Team2 : destination.Team1;
if (destinationTeam.Value != null)
destinationTeam = progressionAbove ? destination.Team1 : destination.Team2;
}
destinationTeam.Value = team;
}
private void updateWinConditions()
{
if (Match.Round.Value == null) return;
var instaWinAmount = Match.Round.Value.BestOf.Value / 2;
Match.Completed.Value = Match.Round.Value.BestOf.Value > 0
&& (Match.Team1Score.Value + Match.Team2Score.Value >= Match.Round.Value.BestOf.Value || Match.Team1Score.Value > instaWinAmount || Match.Team2Score.Value > instaWinAmount);
}
protected override void LoadComplete()
{
base.LoadComplete();
updateTeams();
if (editorInfo != null)
{
globalSelection = editorInfo.Selected.GetBoundCopy();
globalSelection.BindValueChanged(s =>
{
if (s.NewValue != Match) Selected = false;
});
}
}
private void updateTeams()
{
if (LoadState != LoadState.Loaded)
return;
// todo: teams may need to be bindable for transitions at a later point.
if (Match.Team1.Value == null || Match.Team2.Value == null)
Match.CancelMatchStart();
if (Match.ConditionalMatches.Count > 0)
{
foreach (var conditional in Match.ConditionalMatches)
{
var team1Match = conditional.Acronyms.Contains(Match.Team1Acronym);
var team2Match = conditional.Acronyms.Contains(Match.Team2Acronym);
if (team1Match && team2Match)
Match.Date.Value = conditional.Date.Value;
}
}
Flow.Children = new[]
{
new DrawableMatchTeam(Match.Team1.Value, Match, Match.Losers.Value),
new DrawableMatchTeam(Match.Team2.Value, Match, Match.Losers.Value)
};
SchedulerAfterChildren.Add(() => Scheduler.Add(updateProgression));
updateWinConditions();
}
protected override bool OnMouseDown(MouseDownEvent e) => e.Button == MouseButton.Left && editorInfo != null;
protected override bool OnDragStart(DragStartEvent e) => editorInfo != null;
protected override bool OnKeyDown(KeyDownEvent e)
{
if (Selected && editorInfo != null && e.Key == Key.Delete)
{
Remove();
return true;
}
return base.OnKeyDown(e);
}
protected override bool OnClick(ClickEvent e)
{
if (editorInfo == null || Match is ConditionalTournamentMatch)
return false;
Selected = true;
return true;
}
protected override void OnDrag(DragEvent e)
{
base.OnDrag(e);
Selected = true;
this.MoveToOffset(e.Delta);
var pos = Position;
Match.Position.Value = new Point((int)pos.X, (int)pos.Y);
}
public void Remove()
{
Selected = false;
Match.Progression.Value = null;
Match.LosersProgression.Value = null;
ladderInfo.Matches.Remove(Match);
}
}
}
| |
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;
// ReSharper disable once CheckNamespace
namespace Sandbox4.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");
}
var controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
var actionName = api.ActionDescriptor.ActionName;
var parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
var enumerable = parameterNames as IList<string> ?? parameterNames.ToList();
var type = ResolveType(api, controllerName, actionName, enumerable, sampleDirection, out formatters);
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, enumerable, sampleDirection);
var samples = actionSamples.ToDictionary(actionSample => actionSample.Key.MediaType, actionSample => 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))
{
var sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (var mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
var sample = GetActionSample(controllerName, actionName, enumerable, 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 (var factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
// ReSharper disable once EmptyGeneralCatchClause
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)
{
var controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
var actionName = api.ActionDescriptor.ActionName;
var 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
var 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:
var requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
// ReSharper disable once RedundantCaseLabel
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");
}
// ReSharper disable once RedundantAssignment
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;
var reader = new StreamReader(ms);
var 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)
{
var 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
var 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
{
var 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
{
var 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)
{
var parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
return from sample in ActionSamples
let sampleKey = sample.Key
where 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
select sample;
}
private static object WrapSampleIfString(object sample)
{
var stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
using ClosedXML.Extensions;
using System;
using System.Diagnostics;
namespace ClosedXML.Excel
{
internal struct XLAddress : IXLAddress, IEquatable<XLAddress>
{
#region Static
/// <summary>
/// Create address without worksheet. For calculation only!
/// </summary>
/// <param name="cellAddressString"></param>
/// <returns></returns>
public static XLAddress Create(string cellAddressString)
{
return Create(null, cellAddressString);
}
public static XLAddress Create(XLWorksheet worksheet, string cellAddressString)
{
var fixedColumn = cellAddressString[0] == '$';
Int32 startPos;
if (fixedColumn)
{
startPos = 1;
}
else
{
startPos = 0;
}
int rowPos = startPos;
while (cellAddressString[rowPos] > '9')
{
rowPos++;
}
var fixedRow = cellAddressString[rowPos] == '$';
string columnLetter;
int rowNumber;
if (fixedRow)
{
if (fixedColumn)
{
columnLetter = cellAddressString.Substring(startPos, rowPos - 1);
}
else
{
columnLetter = cellAddressString.Substring(startPos, rowPos);
}
rowNumber = int.Parse(cellAddressString.Substring(rowPos + 1), XLHelper.NumberStyle, XLHelper.ParseCulture);
}
else
{
if (fixedColumn)
{
columnLetter = cellAddressString.Substring(startPos, rowPos - 1);
}
else
{
columnLetter = cellAddressString.Substring(startPos, rowPos);
}
rowNumber = Int32.Parse(cellAddressString.Substring(rowPos), XLHelper.NumberStyle, XLHelper.ParseCulture);
}
return new XLAddress(worksheet, rowNumber, columnLetter, fixedRow, fixedColumn);
}
#endregion Static
#region Private fields
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private bool _fixedRow;
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private bool _fixedColumn;
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private readonly int _rowNumber;
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private readonly int _columnNumber;
private string _trimmedAddress;
#endregion Private fields
#region Constructors
/// <summary>
/// Initializes a new <see cref = "XLAddress" /> struct using a mixed notation. Attention: without worksheet for calculation only!
/// </summary>
/// <param name = "rowNumber">The row number of the cell address.</param>
/// <param name = "columnLetter">The column letter of the cell address.</param>
/// <param name = "fixedRow"></param>
/// <param name = "fixedColumn"></param>
public XLAddress(int rowNumber, string columnLetter, bool fixedRow, bool fixedColumn)
: this(null, rowNumber, columnLetter, fixedRow, fixedColumn)
{
}
/// <summary>
/// Initializes a new <see cref = "XLAddress" /> struct using a mixed notation.
/// </summary>
/// <param name = "worksheet"></param>
/// <param name = "rowNumber">The row number of the cell address.</param>
/// <param name = "columnLetter">The column letter of the cell address.</param>
/// <param name = "fixedRow"></param>
/// <param name = "fixedColumn"></param>
public XLAddress(XLWorksheet worksheet, int rowNumber, string columnLetter, bool fixedRow, bool fixedColumn)
: this(worksheet, rowNumber, XLHelper.GetColumnNumberFromLetter(columnLetter), fixedRow, fixedColumn)
{
}
/// <summary>
/// Initializes a new <see cref = "XLAddress" /> struct using R1C1 notation. Attention: without worksheet for calculation only!
/// </summary>
/// <param name = "rowNumber">The row number of the cell address.</param>
/// <param name = "columnNumber">The column number of the cell address.</param>
/// <param name = "fixedRow"></param>
/// <param name = "fixedColumn"></param>
public XLAddress(int rowNumber, int columnNumber, bool fixedRow, bool fixedColumn)
: this(null, rowNumber, columnNumber, fixedRow, fixedColumn)
{
}
/// <summary>
/// Initializes a new <see cref = "XLAddress" /> struct using R1C1 notation.
/// </summary>
/// <param name = "worksheet"></param>
/// <param name = "rowNumber">The row number of the cell address.</param>
/// <param name = "columnNumber">The column number of the cell address.</param>
/// <param name = "fixedRow"></param>
/// <param name = "fixedColumn"></param>
public XLAddress(XLWorksheet worksheet, int rowNumber, int columnNumber, bool fixedRow, bool fixedColumn) : this()
{
Worksheet = worksheet;
_rowNumber = rowNumber;
_columnNumber = columnNumber;
_fixedColumn = fixedColumn;
_fixedRow = fixedRow;
}
#endregion Constructors
#region Properties
public XLWorksheet Worksheet { get; internal set; }
IXLWorksheet IXLAddress.Worksheet
{
[DebuggerStepThrough]
get { return Worksheet; }
}
public bool HasWorksheet
{
[DebuggerStepThrough]
get { return Worksheet != null; }
}
public bool FixedRow
{
get { return _fixedRow; }
}
public bool FixedColumn
{
get { return _fixedColumn; }
}
/// <summary>
/// Gets the row number of this address.
/// </summary>
public Int32 RowNumber
{
get { return _rowNumber; }
}
/// <summary>
/// Gets the column number of this address.
/// </summary>
public Int32 ColumnNumber
{
get { return _columnNumber; }
}
/// <summary>
/// Gets the column letter(s) of this address.
/// </summary>
public String ColumnLetter
{
get { return XLHelper.GetColumnLetterFromNumber(_columnNumber); }
}
#endregion Properties
#region Overrides
public override string ToString()
{
if (!IsValid)
return "#REF!";
String retVal = ColumnLetter;
if (_fixedColumn)
{
retVal = "$" + retVal;
}
if (_fixedRow)
{
retVal += "$";
}
retVal += _rowNumber.ToInvariantString();
return retVal;
}
public string ToString(XLReferenceStyle referenceStyle)
{
return ToString(referenceStyle, false);
}
public string ToString(XLReferenceStyle referenceStyle, bool includeSheet)
{
string address;
if (!IsValid)
address = "#REF!";
else if (referenceStyle == XLReferenceStyle.A1)
address = GetTrimmedAddress();
else if (referenceStyle == XLReferenceStyle.R1C1
|| HasWorksheet && Worksheet.Workbook.ReferenceStyle == XLReferenceStyle.R1C1)
address = "R" + _rowNumber.ToInvariantString() + "C" + ColumnNumber.ToInvariantString();
else
address = GetTrimmedAddress();
if (includeSheet)
return String.Concat(
WorksheetIsDeleted ? "#REF" : Worksheet.Name.EscapeSheetName(),
'!',
address);
return address;
}
#endregion Overrides
#region Methods
public string GetTrimmedAddress()
{
return _trimmedAddress ?? (_trimmedAddress = ColumnLetter + _rowNumber.ToInvariantString());
}
#endregion Methods
#region Operator Overloads
public static XLAddress operator +(XLAddress left, XLAddress right)
{
return new XLAddress(left.Worksheet,
left.RowNumber + right.RowNumber,
left.ColumnNumber + right.ColumnNumber,
left._fixedRow,
left._fixedColumn);
}
public static XLAddress operator -(XLAddress left, XLAddress right)
{
return new XLAddress(left.Worksheet,
left.RowNumber - right.RowNumber,
left.ColumnNumber - right.ColumnNumber,
left._fixedRow,
left._fixedColumn);
}
public static XLAddress operator +(XLAddress left, Int32 right)
{
return new XLAddress(left.Worksheet,
left.RowNumber + right,
left.ColumnNumber + right,
left._fixedRow,
left._fixedColumn);
}
public static XLAddress operator -(XLAddress left, Int32 right)
{
return new XLAddress(left.Worksheet,
left.RowNumber - right,
left.ColumnNumber - right,
left._fixedRow,
left._fixedColumn);
}
public static Boolean operator ==(XLAddress left, XLAddress right)
{
if (ReferenceEquals(left, right))
{
return true;
}
return !ReferenceEquals(left, null) && left.Equals(right);
}
public static Boolean operator !=(XLAddress left, XLAddress right)
{
return !(left == right);
}
#endregion Operator Overloads
#region Interface Requirements
#region IEqualityComparer<XLCellAddress> Members
public Boolean Equals(IXLAddress x, IXLAddress y)
{
return x == y;
}
public new Boolean Equals(object x, object y)
{
return x == y;
}
#endregion IEqualityComparer<XLCellAddress> Members
#region IEquatable<XLCellAddress> Members
public bool Equals(IXLAddress other)
{
if (other == null)
return false;
return _rowNumber == other.RowNumber &&
_columnNumber == other.ColumnNumber &&
_fixedRow == other.FixedRow &&
_fixedColumn == other.FixedColumn;
}
public bool Equals(XLAddress other)
{
return _rowNumber == other._rowNumber &&
_columnNumber == other._columnNumber &&
_fixedRow == other._fixedRow &&
_fixedColumn == other._fixedColumn;
}
public override Boolean Equals(Object other)
{
return Equals(other as IXLAddress);
}
public override int GetHashCode()
{
var hashCode = 2122234362;
hashCode = hashCode * -1521134295 + _fixedRow.GetHashCode();
hashCode = hashCode * -1521134295 + _fixedColumn.GetHashCode();
hashCode = hashCode * -1521134295 + _rowNumber.GetHashCode();
hashCode = hashCode * -1521134295 + _columnNumber.GetHashCode();
return hashCode;
}
public int GetHashCode(IXLAddress obj)
{
return ((XLAddress)obj).GetHashCode();
}
#endregion IEquatable<XLCellAddress> Members
#endregion Interface Requirements
public String ToStringRelative()
{
return ToStringRelative(false);
}
public String ToStringFixed()
{
return ToStringFixed(XLReferenceStyle.Default);
}
public String ToStringRelative(Boolean includeSheet)
{
var address = IsValid ? GetTrimmedAddress() : "#REF!";
if (includeSheet)
return String.Concat(
WorksheetIsDeleted ? "#REF" : Worksheet.Name.EscapeSheetName(),
'!',
address
);
return address;
}
internal XLAddress WithoutWorksheet()
{
return new XLAddress(RowNumber, ColumnNumber, FixedRow, FixedColumn);
}
public String ToStringFixed(XLReferenceStyle referenceStyle)
{
return ToStringFixed(referenceStyle, false);
}
public String ToStringFixed(XLReferenceStyle referenceStyle, Boolean includeSheet)
{
String address;
if (referenceStyle == XLReferenceStyle.Default && HasWorksheet)
referenceStyle = Worksheet.Workbook.ReferenceStyle;
if (referenceStyle == XLReferenceStyle.Default)
referenceStyle = XLReferenceStyle.A1;
Debug.Assert(referenceStyle != XLReferenceStyle.Default);
if (!IsValid)
{
address = "#REF!";
}
else
{
switch (referenceStyle)
{
case XLReferenceStyle.A1:
address = String.Concat('$', ColumnLetter, '$', _rowNumber.ToInvariantString());
break;
case XLReferenceStyle.R1C1:
address = String.Concat('R', _rowNumber.ToInvariantString(), 'C', ColumnNumber);
break;
default:
throw new NotImplementedException();
}
}
if (includeSheet)
return String.Concat(
WorksheetIsDeleted ? "#REF" : Worksheet.Name.EscapeSheetName(),
'!',
address);
return address;
}
public String UniqueId { get { return RowNumber.ToString("0000000") + ColumnNumber.ToString("00000"); } }
public bool IsValid
{
get
{
return 0 < RowNumber && RowNumber <= XLHelper.MaxRowNumber &&
0 < ColumnNumber && ColumnNumber <= XLHelper.MaxColumnNumber;
}
}
private bool WorksheetIsDeleted => Worksheet?.IsDeleted == true;
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Xml;
namespace V1EstimationTool
{
public class Config
{
private static readonly string ConfigFilePath = Path.Combine(Environment.CurrentDirectory, "config.xml");
private IList<String> _buckets;
private IList<String> _selectedBuckets;
public string ApplicationPath
{
get { return Read<string>("ApplicationPath"); }
set { Set("ApplicationPath", value); }
}
public bool UseWindowsIntegrated
{
get { return Convert.ToBoolean(Read<string>("UseWindowsIntegrated")); }
set { Set("UseWindowsIntegrated", value); }
}
public string Username
{
get { return Read<string>("Username"); }
set { Set("Username", value); }
}
public string Password
{
get { return Read<string>("Password"); }
set { Set("Password", value); }
}
public bool SingleLevelProjectView
{
get { return Read("SingleLevelProjectView", false); }
set { Set("SingleLevelProjectView", value, false); }
}
public string SelectedProject
{
get { return Read<string>("SelectedProject"); }
set { Set("SelectedProject", value, false); }
}
public IList<String> Buckets
{
get { return _buckets ?? (_buckets = ReadStringCollection("Buckets")); }
}
public string DefaultSort
{
get { return Read("DefaultSort", "Order"); }
}
public IList<String> SelectedBuckets
{
get { return _selectedBuckets ?? (_selectedBuckets = ReadStringCollection("SelectedBuckets")); }
}
public bool IsValid
{
get { return ApplicationPath != null && Username != null && Password != null; }
}
public event EventHandler OnChanged;
public static void UpdateRecentList(IList<string> messages, string content, int maxitems)
{
if (messages.Contains(content))
messages.Remove(content);
messages.Insert(0, content);
while (messages.Count > maxitems)
messages.RemoveAt(messages.Count - 1);
}
public static IList<double> GetDoubleList(IEnumerable<string> buckets)
{
List<double> list = buckets.Select(s => double.Parse(s, CultureInfo.InvariantCulture)).ToList();
list.Sort();
return list;
}
#region Config Reading
private XmlDocument _doc;
private XmlDocument Doc
{
get
{
if (_doc == null)
{
_doc = new XmlDocument();
if (File.Exists(ConfigFilePath))
_doc.Load(ConfigFilePath);
if (_doc.DocumentElement == null)
_doc.AppendChild(_doc.CreateElement("Configuration"));
}
return _doc;
}
}
private XmlNode EnsureNode(string name)
{
XmlNode node = Doc.DocumentElement.SelectSingleNode(name) ??
Doc.DocumentElement.AppendChild(Doc.CreateElement(name));
return node;
}
private T Read<T>(string name)
{
return Read(name, default(T));
}
private T Read<T>(string name, T def)
{
string text = EnsureNode(name).InnerText;
if (string.IsNullOrEmpty(text))
return def;
return (T) Convert.ChangeType(text, typeof (T));
}
private void Set<T>(string name, T value)
{
Set(name, value, true);
}
private void Set<T>(string name, T value, bool announce)
{
EnsureNode(name).InnerText = (string) Convert.ChangeType(value, typeof (string));
Save();
if (announce && OnChanged != null)
OnChanged(this, EventArgs.Empty);
}
private void Save()
{
Doc.Save(ConfigFilePath);
}
private IList<string> ReadStringCollection(string name)
{
return new XmlStringCollection(EnsureNode(name), this);
}
private class XmlStringCollection : IList<string>
{
private readonly Config _config;
private readonly XmlNode _node;
private readonly IList<string> _values = new List<string>();
public XmlStringCollection(XmlNode node, Config config)
{
_node = node;
_config = config;
ParseNode();
}
#region IList<string> Members
public void Add(string item)
{
_values.Add(item);
SaveNode();
}
public void Clear()
{
_values.Clear();
SaveNode();
}
public bool Contains(string item)
{
return _values.Contains(item);
}
public void CopyTo(string[] array, int arrayIndex)
{
_values.CopyTo(array, arrayIndex);
}
public bool Remove(string item)
{
bool b = _values.Remove(item);
SaveNode();
return b;
}
public int Count
{
get { return _values.Count; }
}
public bool IsReadOnly
{
get { return false; }
}
IEnumerator<string> IEnumerable<string>.GetEnumerator()
{
return _values.GetEnumerator();
}
public IEnumerator GetEnumerator()
{
return ((IEnumerable<string>) this).GetEnumerator();
}
public int IndexOf(string item)
{
return _values.IndexOf(item);
}
public void Insert(int index, string item)
{
_values.Insert(index, item);
SaveNode();
}
public void RemoveAt(int index)
{
_values.RemoveAt(index);
SaveNode();
}
public string this[int index]
{
get { return _values[index]; }
set
{
_values[index] = value;
SaveNode();
}
}
#endregion
private static XmlAttribute EnsureAttribute(XmlNode node, string name)
{
XmlAttribute attrib = node.Attributes[name] ??
node.Attributes.Append(node.OwnerDocument.CreateAttribute(name));
return attrib;
}
private static XmlNode EnsureElement(XmlNode parent, string name)
{
XmlNode node = parent.SelectSingleNode(name) ??
parent.AppendChild(parent.OwnerDocument.CreateElement(name));
return node;
}
private static XmlNode EnsureCData(XmlNode parent)
{
if (parent.ChildNodes.Count == 0)
return parent.AppendChild(parent.OwnerDocument.CreateCDataSection(string.Empty));
return parent.ChildNodes[0];
}
private void ParseNode()
{
XmlAttribute attrib = EnsureAttribute(_node, "Count");
int count = 0;
string text = attrib.InnerText;
if (!string.IsNullOrEmpty(text))
count = int.Parse(text);
for (int i = 0; i < count; i++)
{
XmlNode subNode = _node.SelectSingleNode("Node" + i);
if (subNode != null)
{
XmlNode cDataNode = subNode.ChildNodes[0];
if (cDataNode != null && cDataNode.NodeType == XmlNodeType.CDATA)
_values.Add(cDataNode.InnerText);
}
}
}
private void SaveNode()
{
_node.RemoveAll();
EnsureAttribute(_node, "Count").InnerText = _values.Count.ToString(CultureInfo.InvariantCulture);
for (int i = 0; i < _values.Count; i++)
{
XmlNode subNode = EnsureElement(_node, "Node" + i);
XmlNode cDataNode = EnsureCData(subNode);
cDataNode.InnerText = _values[i];
}
_config.Save();
}
}
#endregion
}
}
| |
using System;
using System.Diagnostics;
using System.Web;
using Umbraco.Core.Logging;
using Umbraco.Core.Profiling;
namespace Umbraco.Core
{
/// <summary>
/// Starts the timer and invokes a callback upon disposal. Provides a simple way of timing an operation by wrapping it in a <code>using</code> (C#) statement.
/// </summary>
/// <example>
/// <code>
///
/// using (DisposableTimer.TraceDuration{MyType}("starting", "finished"))
/// {
/// Thread.Sleep(567);
/// }
///
/// Console.WriteLine("Testing Stopwatchdisposable, should be 567:");
/// using (var timer = new DisposableTimer(result => Console.WriteLine("Took {0}ms", result)))
/// {
/// Thread.Sleep(567);
/// }
/// </code>
/// </example>
public class DisposableTimer : DisposableObject
{
private readonly Stopwatch _stopwatch = Stopwatch.StartNew();
private readonly Action<long> _callback;
protected DisposableTimer(Action<long> callback)
{
_callback = callback;
}
public Stopwatch Stopwatch
{
get { return _stopwatch; }
}
/// <summary>
/// Starts the timer and invokes the specified callback upon disposal.
/// </summary>
/// <param name="callback">The callback.</param>
/// <returns></returns>
[Obsolete("Use either TraceDuration or DebugDuration instead of using Start")]
public static DisposableTimer Start(Action<long> callback)
{
return new DisposableTimer(callback);
}
#region TraceDuration
public static DisposableTimer TraceDuration<T>(Func<string> startMessage, Func<string> completeMessage)
{
return TraceDuration(typeof(T), startMessage, completeMessage);
}
public static DisposableTimer TraceDuration(Type loggerType, Func<string> startMessage, Func<string> completeMessage)
{
var startMsg = startMessage();
LogHelper.Info(loggerType, startMsg);
if (HttpContext.Current != null)
HttpContext.Current.Trace.Write("Start: " + startMsg);
var profiler = ActivateProfiler(loggerType, startMsg);
return new DisposableTimer(x =>
{
profiler.DisposeIfDisposable();
LogHelper.Info(loggerType, () => completeMessage() + " (took " + x + "ms)");
if (HttpContext.Current != null)
HttpContext.Current.Trace.Write("End: " + startMsg);
});
}
/// <summary>
/// Adds a start and end log entry as Info and tracks how long it takes until disposed.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="startMessage"></param>
/// <param name="completeMessage"></param>
/// <returns></returns>
public static DisposableTimer TraceDuration<T>(string startMessage, string completeMessage)
{
return TraceDuration(typeof(T), startMessage, completeMessage);
}
public static DisposableTimer TraceDuration<T>(string startMessage)
{
return TraceDuration(typeof(T), startMessage, "Complete");
}
/// <summary>
/// Adds a start and end log entry as Info and tracks how long it takes until disposed.
/// </summary>
/// <param name="loggerType"></param>
/// <param name="startMessage"></param>
/// <param name="completeMessage"></param>
/// <returns></returns>
public static DisposableTimer TraceDuration(Type loggerType, string startMessage, string completeMessage)
{
LogHelper.Info(loggerType, startMessage);
if (HttpContext.Current != null)
HttpContext.Current.Trace.Write("Start: " + startMessage);
var profiler = ActivateProfiler(loggerType, startMessage);
return new DisposableTimer(x =>
{
profiler.DisposeIfDisposable();
LogHelper.Info(loggerType, () => completeMessage + " (took " + x + "ms)");
if (HttpContext.Current != null)
HttpContext.Current.Trace.Write("End: " + startMessage);
});
}
#endregion
#region DebugDuration
/// <summary>
/// Adds a start and end log entry as Debug and tracks how long it takes until disposed.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="startMessage"></param>
/// <param name="completeMessage"></param>
/// <returns></returns>
public static DisposableTimer DebugDuration<T>(string startMessage, string completeMessage)
{
return DebugDuration(typeof(T), startMessage, completeMessage);
}
public static DisposableTimer DebugDuration<T>(string startMessage)
{
return DebugDuration(typeof(T), startMessage, "Complete");
}
/// <summary>
/// Adds a start and end log entry as Debug and tracks how long it takes until disposed.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="startMessage"></param>
/// <param name="completeMessage"></param>
/// <returns></returns>
public static DisposableTimer DebugDuration<T>(Func<string> startMessage, Func<string> completeMessage)
{
return DebugDuration(typeof(T), startMessage, completeMessage);
}
/// <summary>
/// Adds a start and end log entry as Debug and tracks how long it takes until disposed.
/// </summary>
/// <param name="loggerType"></param>
/// <param name="startMessage"></param>
/// <param name="completeMessage"></param>
/// <returns></returns>
public static DisposableTimer DebugDuration(Type loggerType, string startMessage, string completeMessage)
{
LogHelper.Debug(loggerType, startMessage);
if (HttpContext.Current != null)
HttpContext.Current.Trace.Write("Start: " + startMessage);
var profiler = ActivateProfiler(loggerType, startMessage);
return new DisposableTimer(x =>
{
profiler.DisposeIfDisposable();
LogHelper.Debug(loggerType, () => completeMessage + " (took " + x + "ms)");
if (HttpContext.Current != null)
HttpContext.Current.Trace.Write("End: " + startMessage);
});
}
/// <summary>
/// Adds a start and end log entry as Debug and tracks how long it takes until disposed.
/// </summary>
/// <param name="loggerType"></param>
/// <param name="startMessage"></param>
/// <param name="completeMessage"></param>
/// <returns></returns>
public static DisposableTimer DebugDuration(Type loggerType, Func<string> startMessage, Func<string> completeMessage)
{
var msg = startMessage();
LogHelper.Debug(loggerType, msg);
if (HttpContext.Current != null)
HttpContext.Current.Trace.Write("Start: " + startMessage);
var profiler = ActivateProfiler(loggerType, msg);
return new DisposableTimer(x =>
{
profiler.DisposeIfDisposable();
LogHelper.Debug(loggerType, () => completeMessage() + " (took " + x + "ms)");
if (HttpContext.Current != null)
HttpContext.Current.Trace.Write("End: " + startMessage);
});
}
#endregion
/// <summary>
/// Handles the disposal of resources. Derived from abstract class <see cref="DisposableObject"/> which handles common required locking logic.
/// </summary>
protected override void DisposeResources()
{
_callback.Invoke(Stopwatch.ElapsedMilliseconds);
}
private static IDisposable ActivateProfiler(Type loggerType, string profileName)
{
try
{
return ProfilerResolver.Current.Profiler.Step(loggerType, profileName);
}
catch (InvalidOperationException)
{
//swallow this exception, it will occur if the ProfilerResolver is not initialized... generally only in
// unit tests.
}
return null;
}
}
}
| |
//
// MonoMac.CFNetwork.Test.Views.PreferencesController
//
// Authors:
// Martin Baulig (martin.baulig@gmail.com)
//
// Copyright 2012 Xamarin Inc. (http://www.xamarin.com)
//
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.Linq;
using AsyncTests.Framework;
using AsyncTests.HttpClientTests.Test;
using MonoMac.Foundation;
using MonoMac.AppKit;
namespace MonoMac.CFNetwork.Test.Views {
public partial class PreferencesController : MonoMac.AppKit.NSWindowController {
#region Constructors
// Called when created from unmanaged code
public PreferencesController (IntPtr handle) : base (handle)
{
Initialize ();
}
// Called when created directly from a XIB file
[Export ("initWithCoder:")]
public PreferencesController (NSCoder coder) : base (coder)
{
Initialize ();
}
// Call to load from the XIB/NIB file
public PreferencesController () : base ("Preferences")
{
Initialize ();
}
// Shared initialization code
void Initialize ()
{
}
#endregion
public static PreferencesController Global {
get { return ((AppDelegate)NSApplication.SharedApplication.Delegate).Settings; }
}
//strongly typed window accessor
public new Preferences Window {
get {
return (Preferences)base.Window;
}
}
bool autoRedirect;
bool downloadWithoutLength;
bool useRelativeURL;
bool useAuthentication;
bool usePersistentAuthentication;
NSString localServerAddress;
NSString relativeURL;
NSString userName;
NSString password;
WebDavConfiguration webDav;
const string kAutoRedirect = "AutoRedirect";
const string kDownloadWithoutLength = "DownloadWithoutLength";
const string kUseRelativeURL = "UseRelativeURL";
const string kRelativeURL = "RelativeURL";
const string kUseAuthentication = "UseAuthentication";
const string kUsePersistentAuthentication = "UsePersistentAuthentication";
const string kUserName = "UserName";
const string kPassword = "Password";
const string kLocalServerAddress = "LocalServerAddress";
const string kEnableWebDavTests = "EnableWebDavTests";
const string kWebDavServer = "WebDavServer";
const string kWebDavUserName = "WebDavUserName";
const string kWebDavPassword = "WebDavPassword";
public void RegisterDefaults ()
{
var dict = new NSMutableDictionary ();
dict [kAutoRedirect] = NSNumber.FromBoolean (true);
dict [kDownloadWithoutLength] = NSNumber.FromBoolean (false);
dict [kUseRelativeURL] = NSNumber.FromBoolean (false);
dict [kUseAuthentication] = NSNumber.FromBoolean (false);
dict [kUsePersistentAuthentication] = NSNumber.FromBoolean (false);
dict [kUserName] = (NSString)"mono";
dict [kPassword] = (NSString)"monkey";
dict [kLocalServerAddress] = (NSString)"http://localhost:8088/";
dict [kEnableWebDavTests] = NSNumber.FromBoolean (false);
dict [kWebDavServer] = (NSString)"http://localhost/uploads/";
dict [kWebDavUserName] = (NSString)"admin";
dict [kWebDavPassword] = (NSString)"monkey";
NSUserDefaults.StandardUserDefaults.RegisterDefaults (dict);
}
public void LoadDefaults ()
{
var defaults = NSUserDefaults.StandardUserDefaults;
webDav = TestSuite.GetConfiguration<WebDavConfiguration> ();
autoRedirect = ((NSNumber)defaults [kAutoRedirect]).BoolValue;
downloadWithoutLength = ((NSNumber)defaults [kDownloadWithoutLength]).BoolValue;
useRelativeURL = ((NSNumber)defaults [kUseRelativeURL]).BoolValue;
useAuthentication = ((NSNumber)defaults [kUseAuthentication]).BoolValue;
usePersistentAuthentication = ((NSNumber)defaults [kUsePersistentAuthentication]).BoolValue;
userName = (NSString)defaults [kUserName];
password = (NSString)defaults [kPassword];
localServerAddress = (NSString)defaults [kLocalServerAddress];
webDav.IsEnabled = ((NSNumber)defaults [kEnableWebDavTests]).BoolValue;
webDav.Server = (NSString)defaults [kWebDavServer];
webDav.UserName = (NSString)defaults [kWebDavUserName];
webDav.Password = (NSString)defaults [kWebDavPassword];
}
public void SaveDefaults ()
{
var defaults = NSUserDefaults.StandardUserDefaults;
defaults [kAutoRedirect] = NSNumber.FromBoolean (autoRedirect);
defaults [kDownloadWithoutLength] = NSNumber.FromBoolean (downloadWithoutLength);
defaults [kUseRelativeURL] = NSNumber.FromBoolean (useRelativeURL);
defaults [kUseAuthentication] = NSNumber.FromBoolean (useAuthentication);
defaults [kUsePersistentAuthentication] = NSNumber.FromBoolean (usePersistentAuthentication);
defaults [kUserName] = userName;
defaults [kPassword] = password;
defaults [kLocalServerAddress] = localServerAddress;
defaults [kEnableWebDavTests] = NSNumber.FromBoolean (webDav.IsEnabled);
defaults [kWebDavServer] = (NSString)webDav.Server;
defaults [kWebDavUserName] = (NSString)webDav.UserName;
defaults [kWebDavPassword] = (NSString)webDav.Password;
}
[Export (kAutoRedirect)]
public bool AutoRedirect {
get {
return autoRedirect;
}
set {
WillChangeValue (kAutoRedirect);
autoRedirect = value;
DidChangeValue (kAutoRedirect);
}
}
[Export (kDownloadWithoutLength)]
public bool DownloadWithoutLength {
get {
return downloadWithoutLength;
}
set {
WillChangeValue (kDownloadWithoutLength);
downloadWithoutLength = value;
DidChangeValue (kDownloadWithoutLength);
}
}
[Export (kUseRelativeURL)]
public bool UseRelativeURL {
get {
return useRelativeURL;
}
set {
WillChangeValue (kUseRelativeURL);
useRelativeURL = value;
DidChangeValue (kUseRelativeURL);
}
}
[Export (kRelativeURL)]
public NSString RelativeURL {
get {
return relativeURL;
}
set {
WillChangeValue (kUseRelativeURL);
relativeURL = value;
DidChangeValue (kUseRelativeURL);
}
}
[Export (kUseAuthentication)]
public bool UseAuthentication {
get {
return useAuthentication;
}
set {
WillChangeValue (kUseAuthentication);
useAuthentication = value;
DidChangeValue (kUseAuthentication);
}
}
[Export (kUsePersistentAuthentication)]
public bool UsePersistentAuthentication {
get {
return usePersistentAuthentication;
}
set {
WillChangeValue (kUsePersistentAuthentication);
usePersistentAuthentication = value;
DidChangeValue (kUsePersistentAuthentication);
}
}
[Export (kUserName)]
public NSString UserName {
get {
return userName;
}
set {
WillChangeValue (kUserName);
userName = value;
DidChangeValue (kUserName);
}
}
[Export (kPassword)]
public NSString Password {
get {
return password;
}
set {
WillChangeValue (kPassword);
password = value;
DidChangeValue (kPassword);
}
}
[Export (kLocalServerAddress)]
public NSString LocalServerAddress {
get {
return localServerAddress;
}
set {
WillChangeValue (kLocalServerAddress);
localServerAddress = value;
DidChangeValue (kLocalServerAddress);
}
}
[Export (kEnableWebDavTests)]
public bool EnableWebDavTests {
get {
return webDav.IsEnabled;
}
set {
WillChangeValue (kEnableWebDavTests);
webDav.IsEnabled = value;
DidChangeValue (kEnableWebDavTests);
}
}
[Export (kWebDavServer)]
public string WebDavServer {
get {
return webDav.Server;
}
set {
WillChangeValue (kWebDavServer);
webDav.Server = value;
DidChangeValue (kWebDavServer);
}
}
[Export (kWebDavUserName)]
public string WebDavUserName {
get {
return webDav.UserName;
}
set {
WillChangeValue (kWebDavUserName);
webDav.UserName = value;
DidChangeValue (kWebDavUserName);
}
}
[Export (kWebDavPassword)]
public string WebDavPassword {
get {
return webDav.Password;
}
set {
WillChangeValue (kWebDavPassword);
webDav.Password = value;
DidChangeValue (kWebDavPassword);
}
}
}
}
| |
using System;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Runtime.InteropServices;
using Avalonia.Collections;
using Avalonia.Controls;
using Avalonia.Controls.Platform;
using Avalonia.Threading;
namespace Avalonia.Dialogs
{
internal class ManagedFileChooserViewModel : InternalViewModelBase
{
private readonly ManagedFileDialogOptions _options;
public event Action CancelRequested;
public event Action<string[]> CompleteRequested;
public AvaloniaList<ManagedFileChooserItemViewModel> QuickLinks { get; } =
new AvaloniaList<ManagedFileChooserItemViewModel>();
public AvaloniaList<ManagedFileChooserItemViewModel> Items { get; } =
new AvaloniaList<ManagedFileChooserItemViewModel>();
public AvaloniaList<ManagedFileChooserFilterViewModel> Filters { get; } =
new AvaloniaList<ManagedFileChooserFilterViewModel>();
public AvaloniaList<ManagedFileChooserItemViewModel> SelectedItems { get; } =
new AvaloniaList<ManagedFileChooserItemViewModel>();
string _location;
string _fileName;
private bool _showHiddenFiles;
private ManagedFileChooserFilterViewModel _selectedFilter;
private bool _selectingDirectory;
private bool _savingFile;
private bool _scheduledSelectionValidation;
private bool _alreadyCancelled = false;
private string _defaultExtension;
private CompositeDisposable _disposables;
public string Location
{
get => _location;
private set => this.RaiseAndSetIfChanged(ref _location, value);
}
public string FileName
{
get => _fileName;
private set => this.RaiseAndSetIfChanged(ref _fileName, value);
}
public bool SelectingFolder => _selectingDirectory;
public bool ShowFilters { get; }
public SelectionMode SelectionMode { get; }
public string Title { get; }
public int QuickLinksSelectedIndex
{
get
{
for (var index = 0; index < QuickLinks.Count; index++)
{
var i = QuickLinks[index];
if (i.Path == Location)
{
return index;
}
}
return -1;
}
set => this.RaisePropertyChanged(nameof(QuickLinksSelectedIndex));
}
public ManagedFileChooserFilterViewModel SelectedFilter
{
get => _selectedFilter;
set
{
this.RaiseAndSetIfChanged(ref _selectedFilter, value);
Refresh();
}
}
public bool ShowHiddenFiles
{
get => _showHiddenFiles;
set
{
this.RaiseAndSetIfChanged(ref _showHiddenFiles, value);
Refresh();
}
}
private void RefreshQuickLinks(ManagedFileChooserSources quickSources)
{
QuickLinks.Clear();
QuickLinks.AddRange(quickSources.GetAllItems().Select(i => new ManagedFileChooserItemViewModel(i)));
}
public ManagedFileChooserViewModel(FileSystemDialog dialog, ManagedFileDialogOptions options)
{
_options = options;
_disposables = new CompositeDisposable();
var quickSources = AvaloniaLocator.Current
.GetService<ManagedFileChooserSources>()
?? new ManagedFileChooserSources();
var sub1 = AvaloniaLocator.Current
.GetService<IMountedVolumeInfoProvider>()
.Listen(ManagedFileChooserSources.MountedVolumes);
var sub2 = Observable.FromEventPattern(ManagedFileChooserSources.MountedVolumes,
nameof(ManagedFileChooserSources.MountedVolumes.CollectionChanged))
.ObserveOn(AvaloniaScheduler.Instance)
.Subscribe(x => RefreshQuickLinks(quickSources));
_disposables.Add(sub1);
_disposables.Add(sub2);
CompleteRequested += delegate { _disposables?.Dispose(); };
CancelRequested += delegate { _disposables?.Dispose(); };
RefreshQuickLinks(quickSources);
Title = dialog.Title ?? (
dialog is OpenFileDialog ? "Open file"
: dialog is SaveFileDialog ? "Save file"
: dialog is OpenFolderDialog ? "Select directory"
: throw new ArgumentException(nameof(dialog)));
var directory = dialog.Directory;
if (directory == null || !Directory.Exists(directory))
{
directory = Directory.GetCurrentDirectory();
}
if (dialog is FileDialog fd)
{
if (fd.Filters?.Count > 0)
{
Filters.AddRange(fd.Filters.Select(f => new ManagedFileChooserFilterViewModel(f)));
_selectedFilter = Filters[0];
ShowFilters = true;
}
if (dialog is OpenFileDialog ofd)
{
if (ofd.AllowMultiple)
{
SelectionMode = SelectionMode.Multiple;
}
}
}
_selectingDirectory = dialog is OpenFolderDialog;
if (dialog is SaveFileDialog sfd)
{
_savingFile = true;
_defaultExtension = sfd.DefaultExtension;
FileName = sfd.InitialFileName;
}
Navigate(directory, (dialog as FileDialog)?.InitialFileName);
SelectedItems.CollectionChanged += OnSelectionChangedAsync;
}
public void EnterPressed()
{
if (Directory.Exists(Location))
{
Navigate(Location);
}
else if (File.Exists(Location))
{
CompleteRequested?.Invoke(new[] { Location });
}
}
private async void OnSelectionChangedAsync(object sender, NotifyCollectionChangedEventArgs e)
{
if (_scheduledSelectionValidation)
{
return;
}
_scheduledSelectionValidation = true;
await Dispatcher.UIThread.InvokeAsync(() =>
{
try
{
if (_selectingDirectory)
{
SelectedItems.Clear();
}
else
{
if (!_options.AllowDirectorySelection)
{
var invalidItems = SelectedItems.Where(i => i.ItemType == ManagedFileChooserItemType.Folder)
.ToList();
foreach (var item in invalidItems)
SelectedItems.Remove(item);
}
if (!_selectingDirectory)
{
var selectedItem = SelectedItems.FirstOrDefault();
if (selectedItem != null)
{
FileName = selectedItem.DisplayName;
}
}
}
}
finally
{
_scheduledSelectionValidation = false;
}
});
}
void NavigateRoot(string initialSelectionName)
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
Navigate(Path.GetPathRoot(Environment.GetFolderPath(Environment.SpecialFolder.System)), initialSelectionName);
}
else
{
Navigate("/", initialSelectionName);
}
}
public void Refresh() => Navigate(Location);
public void Navigate(string path, string initialSelectionName = null)
{
if (!Directory.Exists(path))
{
NavigateRoot(initialSelectionName);
}
else
{
Location = path;
Items.Clear();
SelectedItems.Clear();
try
{
var infos = new DirectoryInfo(path).EnumerateFileSystemInfos();
if (!ShowHiddenFiles)
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
infos = infos.Where(i => (i.Attributes & (FileAttributes.Hidden | FileAttributes.System)) == 0);
}
else
{
infos = infos.Where(i => !i.Name.StartsWith("."));
}
}
if (SelectedFilter != null)
{
infos = infos.Where(i => i is DirectoryInfo || SelectedFilter.Match(i.Name));
}
Items.AddRange(infos.Where(x =>
{
if (_selectingDirectory)
{
if (!(x is DirectoryInfo))
{
return false;
}
}
return true;
})
.Where(x => x.Exists)
.Select(info => new ManagedFileChooserItemViewModel
{
DisplayName = info.Name,
Path = info.FullName,
Type = info is FileInfo ? info.Extension : "File Folder",
ItemType = info is FileInfo ? ManagedFileChooserItemType.File
: ManagedFileChooserItemType.Folder,
Size = info is FileInfo f ? f.Length : 0,
Modified = info.LastWriteTime
})
.OrderByDescending(x => x.ItemType == ManagedFileChooserItemType.Folder)
.ThenBy(x => x.DisplayName, StringComparer.InvariantCultureIgnoreCase));
if (initialSelectionName != null)
{
var sel = Items.FirstOrDefault(i => i.ItemType == ManagedFileChooserItemType.File && i.DisplayName == initialSelectionName);
if (sel != null)
{
SelectedItems.Add(sel);
}
}
this.RaisePropertyChanged(nameof(QuickLinksSelectedIndex));
}
catch (System.UnauthorizedAccessException)
{
}
}
}
public void GoUp()
{
var parent = Path.GetDirectoryName(Location);
if (string.IsNullOrWhiteSpace(parent))
{
return;
}
Navigate(parent);
}
public void Cancel()
{
if (!_alreadyCancelled)
{
// INFO: Don't misplace this check or it might cause
// StackOverflowException because of recursive
// event invokes.
_alreadyCancelled = true;
CancelRequested?.Invoke();
}
}
public void Ok()
{
if (_selectingDirectory)
{
CompleteRequested?.Invoke(new[] { Location });
}
else if (_savingFile)
{
if (!string.IsNullOrWhiteSpace(FileName))
{
if (!Path.HasExtension(FileName) && !string.IsNullOrWhiteSpace(_defaultExtension))
{
FileName = Path.ChangeExtension(FileName, _defaultExtension);
}
CompleteRequested?.Invoke(new[] { Path.Combine(Location, FileName) });
}
}
else
{
CompleteRequested?.Invoke(SelectedItems.Select(i => i.Path).ToArray());
}
}
public void SelectSingleFile(ManagedFileChooserItemViewModel item)
{
CompleteRequested?.Invoke(new[] { item.Path });
}
}
}
| |
#region --- License ---
/* Copyright (c) 2006-2008 the OpenTK team.
* See license.txt for license info
*
* Contributions by Andy Gill.
*/
#endregion
// flibit added this!
#pragma warning disable 3021
#region --- Using Directives ---
using System;
using System.Collections.Generic;
#if !MINIMAL
using System.Drawing;
#endif
using System.Text;
using System.Runtime.InteropServices;
using System.Reflection;
using System.Diagnostics;
using System.Reflection.Emit;
#endregion
namespace OpenTK.Graphics.OpenGL
{
/// <summary>
/// OpenGL bindings for .NET, implementing the full OpenGL API, including extensions.
/// </summary>
/// <remarks>
/// <para>
/// This class contains all OpenGL enums and functions defined in the latest OpenGL specification.
/// The official .spec files can be found at: http://opengl.org/registry/.
/// </para>
/// <para> A valid OpenGL context must be created before calling any OpenGL function.</para>
/// <para>
/// Use the GL.Load and GL.LoadAll methods to prepare function entry points prior to use. To maintain
/// cross-platform compatibility, this must be done for both core and extension functions. The GameWindow
/// and the GLControl class will take care of this automatically.
/// </para>
/// <para>
/// You can use the GL.SupportsExtension method to check whether any given category of extension functions
/// exists in the current OpenGL context. Keep in mind that different OpenGL contexts may support different
/// extensions, and under different entry points. Always check if all required extensions are still supported
/// when changing visuals or pixel formats.
/// </para>
/// <para>
/// You may retrieve the entry point for an OpenGL function using the GL.GetDelegate method.
/// </para>
/// </remarks>
/// <see href="http://opengl.org/registry/"/>
public sealed partial class GL : GraphicsBindingsBase
{
#region --- Fields ---
internal const string Library = "opengl32.dll";
// flibit commented this out.
// static SortedList<string, bool> AvailableExtensions = new SortedList<string, bool>();
static readonly object sync_root = new object();
#endregion
#region --- Constructor ---
static GL()
{
}
#endregion
#region --- Public Members ---
// flibit un-Obsoleted this.
/// <summary>
/// Loads all OpenGL entry points (core and extension).
/// This method is provided for compatibility purposes with older OpenTK versions.
/// </summary>
//[Obsolete("If you are using a context constructed outside of OpenTK, create a new GraphicsContext and pass your context handle to it. Otherwise, there is no need to call this method.")]
public static void LoadAll()
{
new GL().LoadEntryPoints();
}
#endregion
#region --- Protected Members ---
/// <summary>
/// Returns a synchronization token unique for the GL class.
/// </summary>
protected override object SyncRoot
{
get { return sync_root; }
}
#endregion
#region --- GL Overloads ---
#pragma warning disable 3019
#pragma warning disable 1591
#pragma warning disable 1572
#pragma warning disable 1573
// Note: Mono 1.9.1 truncates StringBuilder results (for 'out string' parameters).
// We work around this issue by doubling the StringBuilder capacity.
#region public static void Color[34]() overloads
public static void Color3(Color color)
{
GL.Color3(color.R, color.G, color.B);
}
public static void Color4(Color color)
{
GL.Color4(color.R, color.G, color.B, color.A);
}
public static void Color3(Vector3 color)
{
GL.Color3(color.X, color.Y, color.Z);
}
public static void Color4(Vector4 color)
{
GL.Color4(color.X, color.Y, color.Z, color.W);
}
public static void Color4(Color4 color)
{
GL.Color4(color.R, color.G, color.B, color.A);
}
#endregion
#region public static void ClearColor() overloads
public static void ClearColor(Color color)
{
GL.ClearColor(color.R / 255.0f, color.G / 255.0f, color.B / 255.0f, color.A / 255.0f);
}
public static void ClearColor(Color4 color)
{
GL.ClearColor(color.R, color.G, color.B, color.A);
}
#endregion
#region public static void BlendColor() overloads
public static void BlendColor(Color color)
{
GL.BlendColor(color.R / 255.0f, color.G / 255.0f, color.B / 255.0f, color.A / 255.0f);
}
public static void BlendColor(Color4 color)
{
GL.BlendColor(color.R, color.G, color.B, color.A);
}
#endregion
#region public static void Material() overloads
public static void Material(MaterialFace face, MaterialParameter pname, Vector4 @params)
{
unsafe { Material(face, pname, (float*)&@params.X); }
}
public static void Material(MaterialFace face, MaterialParameter pname, Color4 @params)
{
unsafe { GL.Material(face, pname, (float*)&@params); }
}
#endregion
#region public static void Light() overloads
public static void Light(LightName name, LightParameter pname, Vector4 @params)
{
unsafe { GL.Light(name, pname, (float*)&@params.X); }
}
public static void Light(LightName name, LightParameter pname, Color4 @params)
{
unsafe { GL.Light(name, pname, (float*)&@params); }
}
#endregion
#region Normal|RasterPos|Vertex|TexCoord|Rotate|Scale|Translate|*Matrix
public static void Normal3(Vector3 normal)
{
GL.Normal3(normal.X, normal.Y, normal.Z);
}
public static void RasterPos2(Vector2 pos)
{
GL.RasterPos2(pos.X, pos.Y);
}
public static void RasterPos3(Vector3 pos)
{
GL.RasterPos3(pos.X, pos.Y, pos.Z);
}
public static void RasterPos4(Vector4 pos)
{
GL.RasterPos4(pos.X, pos.Y, pos.Z, pos.W);
}
public static void Vertex2(Vector2 v)
{
GL.Vertex2(v.X, v.Y);
}
public static void Vertex3(Vector3 v)
{
GL.Vertex3(v.X, v.Y, v.Z);
}
public static void Vertex4(Vector4 v)
{
GL.Vertex4(v.X, v.Y, v.Z, v.W);
}
public static void TexCoord2(Vector2 v)
{
GL.TexCoord2(v.X, v.Y);
}
public static void TexCoord3(Vector3 v)
{
GL.TexCoord3(v.X, v.Y, v.Z);
}
public static void TexCoord4(Vector4 v)
{
GL.TexCoord4(v.X, v.Y, v.Z, v.W);
}
public static void Rotate(Single angle, Vector3 axis)
{
GL.Rotate((Single)angle, axis.X, axis.Y, axis.Z);
}
public static void Scale(Vector3 scale)
{
GL.Scale(scale.X, scale.Y, scale.Z);
}
public static void Translate(Vector3 trans)
{
GL.Translate(trans.X, trans.Y, trans.Z);
}
public static void MultMatrix(ref Matrix4 mat)
{
unsafe
{
fixed (Single* m_ptr = &mat.Row0.X)
{
GL.MultMatrix((Single*)m_ptr);
}
}
}
public static void LoadMatrix(ref Matrix4 mat)
{
unsafe
{
fixed (Single* m_ptr = &mat.Row0.X)
{
GL.LoadMatrix((Single*)m_ptr);
}
}
}
public static void LoadTransposeMatrix(ref Matrix4 mat)
{
unsafe
{
fixed (Single* m_ptr = &mat.Row0.X)
{
GL.LoadTransposeMatrix((Single*)m_ptr);
}
}
}
public static void MultTransposeMatrix(ref Matrix4 mat)
{
unsafe
{
fixed (Single* m_ptr = &mat.Row0.X)
{
GL.MultTransposeMatrix((Single*)m_ptr);
}
}
}
public static void UniformMatrix4(int location, bool transpose, ref Matrix4 matrix)
{
unsafe
{
fixed (float* matrix_ptr = &matrix.Row0.X)
{
GL.UniformMatrix4(location, 1, transpose, matrix_ptr);
}
}
}
public static void Normal3(Vector3d normal)
{
GL.Normal3(normal.X, normal.Y, normal.Z);
}
public static void RasterPos2(Vector2d pos)
{
GL.RasterPos2(pos.X, pos.Y);
}
public static void RasterPos3(Vector3d pos)
{
GL.RasterPos3(pos.X, pos.Y, pos.Z);
}
public static void RasterPos4(Vector4d pos)
{
GL.RasterPos4(pos.X, pos.Y, pos.Z, pos.W);
}
public static void Vertex2(Vector2d v)
{
GL.Vertex2(v.X, v.Y);
}
public static void Vertex3(Vector3d v)
{
GL.Vertex3(v.X, v.Y, v.Z);
}
public static void Vertex4(Vector4d v)
{
GL.Vertex4(v.X, v.Y, v.Z, v.W);
}
public static void TexCoord2(Vector2d v)
{
GL.TexCoord2(v.X, v.Y);
}
public static void TexCoord3(Vector3d v)
{
GL.TexCoord3(v.X, v.Y, v.Z);
}
public static void TexCoord4(Vector4d v)
{
GL.TexCoord4(v.X, v.Y, v.Z, v.W);
}
public static void Rotate(double angle, Vector3d axis)
{
GL.Rotate((double)angle, axis.X, axis.Y, axis.Z);
}
public static void Scale(Vector3d scale)
{
GL.Scale(scale.X, scale.Y, scale.Z);
}
public static void Translate(Vector3d trans)
{
GL.Translate(trans.X, trans.Y, trans.Z);
}
public static void MultMatrix(ref Matrix4d mat)
{
unsafe
{
fixed (Double* m_ptr = &mat.Row0.X)
{
GL.MultMatrix((Double*)m_ptr);
}
}
}
public static void LoadMatrix(ref Matrix4d mat)
{
unsafe
{
fixed (Double* m_ptr = &mat.Row0.X)
{
GL.LoadMatrix((Double*)m_ptr);
}
}
}
public static void LoadTransposeMatrix(ref Matrix4d mat)
{
unsafe
{
fixed (Double* m_ptr = &mat.Row0.X)
{
GL.LoadTransposeMatrix((Double*)m_ptr);
}
}
}
public static void MultTransposeMatrix(ref Matrix4d mat)
{
unsafe
{
fixed (Double* m_ptr = &mat.Row0.X)
{
GL.MultTransposeMatrix((Double*)m_ptr);
}
}
}
#region Uniform
[CLSCompliant(false)]
public static void Uniform2(int location, ref Vector2 vector)
{
GL.Uniform2(location, vector.X, vector.Y);
}
[CLSCompliant(false)]
public static void Uniform3(int location, ref Vector3 vector)
{
GL.Uniform3(location, vector.X, vector.Y, vector.Z);
}
[CLSCompliant(false)]
public static void Uniform4(int location, ref Vector4 vector)
{
GL.Uniform4(location, vector.X, vector.Y, vector.Z, vector.W);
}
public static void Uniform2(int location, Vector2 vector)
{
GL.Uniform2(location, vector.X, vector.Y);
}
public static void Uniform3(int location, Vector3 vector)
{
GL.Uniform3(location, vector.X, vector.Y, vector.Z);
}
public static void Uniform4(int location, Vector4 vector)
{
GL.Uniform4(location, vector.X, vector.Y, vector.Z, vector.W);
}
public static void Uniform4(int location, Color4 color)
{
GL.Uniform4(location, color.R, color.G, color.B, color.A);
}
public static void Uniform4(int location, Quaternion quaternion)
{
GL.Uniform4(location, quaternion.X, quaternion.Y, quaternion.Z, quaternion.W);
}
#endregion
#endregion
#region Shaders
#region GetActiveAttrib
public static string GetActiveAttrib(int program, int index, out int size, out ActiveAttribType type)
{
int length;
GetProgram(program, OpenTK.Graphics.OpenGL.ProgramParameter.ActiveAttributeMaxLength, out length);
StringBuilder sb = new StringBuilder(length == 0 ? 1 : length * 2);
GetActiveAttrib(program, index, sb.Capacity, out length, out size, out type, sb);
return sb.ToString();
}
#endregion
#region GetActiveUniform
public static string GetActiveUniform(int program, int uniformIndex, out int size, out ActiveUniformType type)
{
int length;
GetProgram(program, OpenTK.Graphics.OpenGL.ProgramParameter.ActiveUniformMaxLength, out length);
StringBuilder sb = new StringBuilder(length == 0 ? 1 : length);
GetActiveUniform(program, uniformIndex, sb.Capacity, out length, out size, out type, sb);
return sb.ToString();
}
#endregion
#region GetActiveUniformName
public static string GetActiveUniformName(int program, int uniformIndex)
{
int length;
GetProgram(program, OpenTK.Graphics.OpenGL.ProgramParameter.ActiveUniformMaxLength, out length);
StringBuilder sb = new StringBuilder(length == 0 ? 1 : length * 2);
GetActiveUniformName(program, uniformIndex, sb.Capacity, out length, sb);
return sb.ToString();
}
#endregion
#region GetActiveUniformBlockName
public static string GetActiveUniformBlockName(int program, int uniformIndex)
{
int length;
GetProgram(program, OpenTK.Graphics.OpenGL.ProgramParameter.ActiveUniformBlockMaxNameLength, out length);
StringBuilder sb = new StringBuilder(length == 0 ? 1 : length * 2);
GetActiveUniformBlockName(program, uniformIndex, sb.Capacity, out length, sb);
return sb.ToString();
}
#endregion
#region public static void ShaderSource(Int32 shader, System.String @string)
public static void ShaderSource(Int32 shader, System.String @string)
{
unsafe
{
int length = @string.Length;
GL.ShaderSource((UInt32)shader, 1, new string[] { @string }, &length);
}
}
#endregion
#region public static string GetShaderInfoLog(Int32 shader)
public static string GetShaderInfoLog(Int32 shader)
{
string info;
GetShaderInfoLog(shader, out info);
return info;
}
#endregion
#region public static void GetShaderInfoLog(Int32 shader, out string info)
public static void GetShaderInfoLog(Int32 shader, out string info)
{
unsafe
{
int length;
GL.GetShader(shader, ShaderParameter.InfoLogLength, out length);
if (length == 0)
{
info = String.Empty;
return;
}
StringBuilder sb = new StringBuilder(length * 2);
GL.GetShaderInfoLog((UInt32)shader, sb.Capacity, &length, sb);
info = sb.ToString();
}
}
#endregion
#region public static string GetProgramInfoLog(Int32 program)
public static string GetProgramInfoLog(Int32 program)
{
string info;
GetProgramInfoLog(program, out info);
return info;
}
#endregion
#region public static void GetProgramInfoLog(Int32 program, out string info)
public static void GetProgramInfoLog(Int32 program, out string info)
{
unsafe
{
int length;
GL.GetProgram(program, OpenTK.Graphics.OpenGL.ProgramParameter.InfoLogLength, out length); if (length == 0)
{
info = String.Empty;
return;
}
StringBuilder sb = new StringBuilder(length * 2);
GL.GetProgramInfoLog((UInt32)program, sb.Capacity, &length, sb);
info = sb.ToString();
}
}
#endregion
#endregion
#region public static void PointParameter(PointSpriteCoordOriginParameter param)
/// <summary>
/// Helper function that defines the coordinate origin of the Point Sprite.
/// </summary>
/// <param name="param">
/// A OpenTK.Graphics.OpenGL.GL.PointSpriteCoordOriginParameter token,
/// denoting the origin of the Point Sprite.
/// </param>
public static void PointParameter(PointSpriteCoordOriginParameter param)
{
GL.PointParameter(PointParameterName.PointSpriteCoordOrigin, (int)param);
}
#endregion
#region VertexAttrib|MultiTexCoord
[CLSCompliant(false)]
public static void VertexAttrib2(Int32 index, ref Vector2 v)
{
GL.VertexAttrib2(index, v.X, v.Y);
}
[CLSCompliant(false)]
public static void VertexAttrib3(Int32 index, ref Vector3 v)
{
GL.VertexAttrib3(index, v.X, v.Y, v.Z);
}
[CLSCompliant(false)]
public static void VertexAttrib4(Int32 index, ref Vector4 v)
{
GL.VertexAttrib4(index, v.X, v.Y, v.Z, v.W);
}
public static void VertexAttrib2(Int32 index, Vector2 v)
{
GL.VertexAttrib2(index, v.X, v.Y);
}
public static void VertexAttrib3(Int32 index, Vector3 v)
{
GL.VertexAttrib3(index, v.X, v.Y, v.Z);
}
public static void VertexAttrib4(Int32 index, Vector4 v)
{
GL.VertexAttrib4(index, v.X, v.Y, v.Z, v.W);
}
public static void MultiTexCoord2(TextureUnit target, ref Vector2 v)
{
GL.MultiTexCoord2(target, v.X, v.Y);
}
public static void MultiTexCoord3(TextureUnit target, ref Vector3 v)
{
GL.MultiTexCoord3(target, v.X, v.Y, v.Z);
}
public static void MultiTexCoord4(TextureUnit target, ref Vector4 v)
{
GL.MultiTexCoord4(target, v.X, v.Y, v.Z, v.W);
}
[CLSCompliant(false)]
public static void VertexAttrib2(Int32 index, ref Vector2d v)
{
GL.VertexAttrib2(index, v.X, v.Y);
}
[CLSCompliant(false)]
public static void VertexAttrib3(Int32 index, ref Vector3d v)
{
GL.VertexAttrib3(index, v.X, v.Y, v.Z);
}
[CLSCompliant(false)]
public static void VertexAttrib4(Int32 index, ref Vector4d v)
{
GL.VertexAttrib4(index, v.X, v.Y, v.Z, v.W);
}
public static void VertexAttrib2(Int32 index, Vector2d v)
{
GL.VertexAttrib2(index, v.X, v.Y);
}
public static void VertexAttrib3(Int32 index, Vector3d v)
{
GL.VertexAttrib3(index, v.X, v.Y, v.Z);
}
public static void VertexAttrib4(Int32 index, Vector4d v)
{
GL.VertexAttrib4(index, v.X, v.Y, v.Z, v.W);
}
public static void MultiTexCoord2(TextureUnit target, ref Vector2d v)
{
GL.MultiTexCoord2(target, v.X, v.Y);
}
public static void MultiTexCoord3(TextureUnit target, ref Vector3d v)
{
GL.MultiTexCoord3(target, v.X, v.Y, v.Z);
}
public static void MultiTexCoord4(TextureUnit target, ref Vector4d v)
{
GL.MultiTexCoord4(target, v.X, v.Y, v.Z, v.W);
}
#endregion
#region Rect
public static void Rect(RectangleF rect)
{
GL.Rect(rect.Left, rect.Top, rect.Right, rect.Bottom);
}
public static void Rect(Rectangle rect)
{
GL.Rect(rect.Left, rect.Top, rect.Right, rect.Bottom);
}
[CLSCompliant(false)]
public static void Rect(ref RectangleF rect)
{
GL.Rect(rect.Left, rect.Top, rect.Right, rect.Bottom);
}
[CLSCompliant(false)]
public static void Rect(ref Rectangle rect)
{
GL.Rect(rect.Left, rect.Top, rect.Right, rect.Bottom);
}
#endregion
#region GenBuffer
/// <summary>[requires: v1.5]
/// Generates a single buffer object name
/// </summary>
/// <returns>The generated buffer object name</returns>
public static int GenBuffer()
{
int id;
GenBuffers(1, out id);
return id;
}
#endregion
#region DeleteBuffer
/// <summary>[requires: v1.5]
/// Deletes a single buffer object
/// </summary>
/// <param name="id">The buffer object to be deleted</param>
public static void DeleteBuffer(int id)
{
DeleteBuffers(1, ref id);
}
/// <summary>[requires: v1.5]
/// Deletes a single buffer object
/// </summary>
/// <param name="id">The buffer object to be deleted</param>
[CLSCompliant(false)]
public static void DeleteBuffer(uint id)
{
DeleteBuffers(1, ref id);
}
#endregion
#region GenFramebuffer
/// <summary>[requires: v3.0 and ARB_framebuffer_object]
/// Generates a single framebuffer object name
/// </summary>
/// <returns>The generated framebuffer object name</returns>
public static int GenFramebuffer()
{
int id;
GenFramebuffers(1, out id);
return id;
}
#endregion
#region DeleteFramebuffer
/// <summary>[requires: v3.0 and ARB_framebuffer_object]
/// Deletes a single framebuffer object
/// </summary>
/// <param name="id">The framebuffer object to be deleted</param>
public static void DeleteFramebuffer(int id)
{
DeleteFramebuffers(1, ref id);
}
/// <summary>[requires: v3.0 and ARB_framebuffer_object]
/// Deletes a single framebuffer object
/// </summary>
/// <param name="id">The framebuffer object to be deleted</param>
[CLSCompliant(false)]
public static void DeleteFramebuffer(uint id)
{
DeleteFramebuffers(1, ref id);
}
#endregion
#region GenProgramPipeline
/// <summary>[requires: v4.1 and ARB_separate_shader_objects]
/// Generates a single single pipeline object name
/// </summary>
/// <returns>The generated single pipeline object name</returns>
public static int GenProgramPipeline()
{
int id;
GenProgramPipelines(1, out id);
return id;
}
#endregion
#region DeleteProgramPipeline
/// <summary>[requires: v4.1 and ARB_separate_shader_objects]
/// Deletes a single program pipeline object
/// </summary>
/// <param name="id">The program pipeline object to be deleted</param>
public static void DeleteProgramPipeline(int id)
{
DeleteProgramPipelines(1, ref id);
}
/// <summary>[requires: v4.1 and ARB_separate_shader_objects]
/// Deletes a single program pipeline object
/// </summary>
/// <param name="id">The program pipeline object to be deleted</param>
[CLSCompliant(false)]
public static void DeleteProgramPipeline(uint id)
{
DeleteProgramPipelines(1, ref id);
}
#endregion
#region GenQuery
/// <summary>[requires: v1.5]
/// Generates a single query object name
/// </summary>
/// <returns>The generated query object name</returns>
public static int GenQuery()
{
int id;
GenQueries(1, out id);
return id;
}
#endregion
#region DeleteQuery
/// <summary>[requires: v1.5]
/// Deletes a single query object
/// </summary>
/// <param name="id">The query object to be deleted</param>
public static void DeleteQuery(int id)
{
DeleteQueries(1, ref id);
}
/// <summary>
/// Deletes a single query object
/// </summary>
/// <param name="id">The query object to be deleted</param>
[CLSCompliant(false)]
public static void DeleteQuery(uint id)
{
DeleteQueries(1, ref id);
}
#endregion
#region GenRenderbuffer
/// <summary>[requires: v3.0 and ARB_framebuffer_object]
/// Generates a single renderbuffer object name
/// </summary>
/// <returns>The generated renderbuffer object name</returns>
public static int GenRenderbuffer()
{
int id;
GenRenderbuffers(1, out id);
return id;
}
#endregion
#region DeleteRenderbuffer
/// <summary>[requires: v3.0 and ARB_framebuffer_object]
/// Deletes a single renderbuffer object
/// </summary>
/// <param name="id">The renderbuffer object to be deleted</param>
public static void DeleteRenderbuffer(int id)
{
DeleteRenderbuffers(1, ref id);
}
/// <summary>[requires: v3.0 and ARB_framebuffer_object]
/// Deletes a single renderbuffer object
/// </summary>
/// <param name="id">The renderbuffer object to be deleted</param>
[CLSCompliant(false)]
public static void DeleteRenderbuffer(uint id)
{
DeleteRenderbuffers(1, ref id);
}
#endregion
#region GenSampler
/// <summary>
/// Generates a single sampler object name
/// </summary>
/// <returns>The generated sampler object name</returns>
public static int GenSampler()
{
int id;
GenSamplers(1, out id);
return id;
}
#endregion
#region DeleteSampler
/// <summary>
/// Deletes a single sampler object
/// </summary>
/// <param name="id">The sampler object to be deleted</param>
public static void DeleteSampler(int id)
{
DeleteSamplers(1, ref id);
}
/// <summary>
/// Deletes a single sampler object
/// </summary>
/// <param name="id">The sampler object to be deleted</param>
[CLSCompliant(false)]
public static void DeleteSampler(uint id)
{
DeleteSamplers(1, ref id);
}
#endregion
#region GenTexture
/// <summary>[requires: v1.1]
/// Generate a single texture name
/// </summary>
/// <returns>The generated texture name</returns>
public static int GenTexture()
{
int id;
GenTextures(1, out id);
return id;
}
#endregion
#region DeleteTexture
/// <summary>[requires: v1.1]
/// Delete a single texture name
/// </summary>
/// <param name="id">The texture to be deleted</param>
public static void DeleteTexture(int id)
{
DeleteTextures(1, ref id);
}
/// <summary>[requires: v1.1]
/// Delete a single texture name
/// </summary>
/// <param name="id">The texture to be deleted</param>
[CLSCompliant(false)]
public static void DeleteTexture(uint id)
{
DeleteTextures(1, ref id);
}
#endregion
#region GenTransformFeedback
/// <summary>[requires: v1.2 and ARB_transform_feedback2]
/// Generates a single transform feedback object name
/// </summary>
/// <returns>The generated transform feedback object name</returns>
public static int GenTransformFeedback()
{
int id;
GenTransformFeedback(1, out id);
return id;
}
#endregion
#region DeleteTransformFeedback
/// <summary>[requires: v1.2 and ARB_transform_feedback2]
/// Deletes a single transform feedback object
/// </summary>
/// <param name="id">The transform feedback object to be deleted</param>
public static void DeleteTransformFeedback(int id)
{
DeleteTransformFeedback(1, ref id);
}
/// <summary>[requires: v1.2 and ARB_transform_feedback2]
/// Deletes a single transform feedback object
/// </summary>
/// <param name="id">The transform feedback object to be deleted</param>
[CLSCompliant(false)]
public static void DeleteTransformFeedback(uint id)
{
DeleteTransformFeedback(1, ref id);
}
#endregion
#region GenVertexArray
/// <summary>[requires: v3.0 and ARB_vertex_array_object]
/// Generates a single vertex array object name
/// </summary>
/// <returns>The generated vertex array object name</returns>
public static int GenVertexArray()
{
int id;
GenVertexArrays(1, out id);
return id;
}
#endregion
#region DeleteVertexArray
/// <summary>[requires: v3.0 and ARB_vertex_array_object]
/// Deletes a single vertex array object
/// </summary>
/// <param name="id">The vertex array object to be deleted</param>
public static void DeleteVertexArray(int id)
{
DeleteVertexArrays(1, ref id);
}
/// <summary>[requires: v3.0 and ARB_vertex_array_object]
/// Deletes a single vertex array object
/// </summary>
/// <param name="id">The vertex array object to be deleted</param>
[CLSCompliant(false)]
public static void DeleteVertexArray(uint id)
{
DeleteVertexArrays(1, ref id);
}
#endregion
#region [Vertex|Normal|Index|Color|FogCoord|VertexAttrib]Pointer
public static void VertexPointer(int size, VertexPointerType type, int stride, int offset)
{
VertexPointer(size, type, stride, (IntPtr)offset);
}
public static void NormalPointer(NormalPointerType type, int stride, int offset)
{
NormalPointer(type, stride, (IntPtr)offset);
}
public static void IndexPointer(IndexPointerType type, int stride, int offset)
{
IndexPointer(type, stride, (IntPtr)offset);
}
public static void ColorPointer(int size, ColorPointerType type, int stride, int offset)
{
ColorPointer(size, type, stride, (IntPtr)offset);
}
public static void FogCoordPointer(FogPointerType type, int stride, int offset)
{
FogCoordPointer(type, stride, (IntPtr)offset);
}
public static void EdgeFlagPointer(int stride, int offset)
{
EdgeFlagPointer(stride, (IntPtr)offset);
}
public static void TexCoordPointer(int size, TexCoordPointerType type, int stride, int offset)
{
TexCoordPointer(size, type, stride, (IntPtr)offset);
}
public static void VertexAttribPointer(int index, int size, VertexAttribPointerType type, bool normalized, int stride, int offset)
{
VertexAttribPointer(index, size, type, normalized, stride, (IntPtr)offset);
}
#endregion
#region DrawElements
public static void DrawElements(BeginMode mode, int count, DrawElementsType type, int offset)
{
DrawElements(mode, count, type, new IntPtr(offset));
}
#endregion
#region Get[Float|Double]
public static void GetFloat(GetPName pname, out Vector2 vector)
{
unsafe
{
fixed (Vector2* ptr = &vector)
GetFloat(pname, (float*)ptr);
}
}
public static void GetFloat(GetPName pname, out Vector3 vector)
{
unsafe
{
fixed (Vector3* ptr = &vector)
GetFloat(pname, (float*)ptr);
}
}
public static void GetFloat(GetPName pname, out Vector4 vector)
{
unsafe
{
fixed (Vector4* ptr = &vector)
GetFloat(pname, (float*)ptr);
}
}
public static void GetFloat(GetPName pname, out Matrix4 matrix)
{
unsafe
{
fixed (Matrix4* ptr = &matrix)
GetFloat(pname, (float*)ptr);
}
}
public static void GetDouble(GetPName pname, out Vector2d vector)
{
unsafe
{
fixed (Vector2d* ptr = &vector)
GetDouble(pname, (double*)ptr);
}
}
public static void GetDouble(GetPName pname, out Vector3d vector)
{
unsafe
{
fixed (Vector3d* ptr = &vector)
GetDouble(pname, (double*)ptr);
}
}
public static void GetDouble(GetPName pname, out Vector4d vector)
{
unsafe
{
fixed (Vector4d* ptr = &vector)
GetDouble(pname, (double*)ptr);
}
}
public static void GetDouble(GetPName pname, out Matrix4d matrix)
{
unsafe
{
fixed (Matrix4d* ptr = &matrix)
GetDouble(pname, (double*)ptr);
}
}
#endregion
#region Viewport
public static void Viewport(Size size)
{
GL.Viewport(0, 0, size.Width, size.Height);
}
public static void Viewport(Point location, Size size)
{
GL.Viewport(location.X, location.Y, size.Width, size.Height);
}
public static void Viewport(Rectangle rectangle)
{
GL.Viewport(rectangle.X, rectangle.Y, rectangle.Width, rectangle.Height);
}
#if NO_SYSDRAWING
public static void Viewport(OpenTK.Point location, OpenTK.Size size)
{
GL.Viewport(location.X, location.Y, size.Width, size.Height);
}
public static void Viewport(OpenTK.Rectangle rectangle)
{
GL.Viewport(rectangle.X, rectangle.Y, rectangle.Width, rectangle.Height);
}
#endif
#endregion
#region TexEnv
public static void TexEnv(TextureEnvTarget target, TextureEnvParameter pname, Color color)
{
Color4 c = new Color4(color.R, color.G, color.B, color.A);
unsafe
{
TexEnv(target, pname, &c.R);
}
}
public static void TexEnv(TextureEnvTarget target, TextureEnvParameter pname, Color4 color)
{
unsafe
{
TexEnv(target, pname, &color.R);
}
}
#endregion
#region Obsolete
[AutoGenerated(Category = "Version11Deprecated", Version = "1.1", EntryPoint = "glDisableClientState")]
[Obsolete("Use DisableClientState(ArrayCap) instead.")]
public static void DisableClientState(OpenTK.Graphics.OpenGL.EnableCap array)
{
DisableClientState((ArrayCap)array);
}
[AutoGenerated(Category = "Version11Deprecated", Version = "1.1", EntryPoint = "glEnableClientState")]
[Obsolete("Use EnableClientState(ArrayCap) instead.")]
public static void EnableClientState(OpenTK.Graphics.OpenGL.EnableCap array)
{
EnableClientState((ArrayCap)array);
}
[AutoGenerated(Category = "ArbUniformBufferObject", Version = "2.0", EntryPoint = "glGetActiveUniformsiv")]
[Obsolete("Use GetActiveUniforms(..., ActiveUniformParameter, ...) instead.")]
public static void GetActiveUniforms(Int32 program, Int32 uniformCount, Int32[] uniformIndices, ArbUniformBufferObject pname, [OutAttribute] Int32[] @params)
{
GetActiveUniforms(program, uniformCount, uniformIndices, (ActiveUniformParameter)pname, @params);
}
[AutoGenerated(Category = "ArbUniformBufferObject", Version = "2.0", EntryPoint = "glGetActiveUniformsiv")]
[Obsolete("Use GetActiveUniforms(..., ActiveUniformParameter, ...) instead.")]
public static void GetActiveUniforms(Int32 program, Int32 uniformCount, ref Int32 uniformIndices, ArbUniformBufferObject pname, [OutAttribute] out Int32 @params)
{
GetActiveUniforms(program, uniformCount, ref uniformIndices, (ActiveUniformParameter)pname, out @params);
}
[System.CLSCompliant(false)]
[AutoGenerated(Category = "ArbUniformBufferObject", Version = "2.0", EntryPoint = "glGetActiveUniformsiv")]
[Obsolete("Use GetActiveUniforms(..., ActiveUniformParameter, ...) instead.")]
public static unsafe void GetActiveUniforms(Int32 program, Int32 uniformCount, Int32* uniformIndices, ArbUniformBufferObject pname, [OutAttribute] Int32* @params)
{
GetActiveUniforms(program, uniformCount, uniformIndices, (ActiveUniformParameter)pname, @params);
}
[System.CLSCompliant(false)]
[AutoGenerated(Category = "ArbUniformBufferObject", Version = "2.0", EntryPoint = "glGetActiveUniformsiv")]
[Obsolete("Use GetActiveUniforms(..., ActiveUniformParameter, ...) instead.")]
public static void GetActiveUniforms(UInt32 program, Int32 uniformCount, UInt32[] uniformIndices, ArbUniformBufferObject pname, [OutAttribute] Int32[] @params)
{
GetActiveUniforms(program, uniformCount, uniformIndices, (ActiveUniformParameter)pname, @params);
}
[System.CLSCompliant(false)]
[AutoGenerated(Category = "ArbUniformBufferObject", Version = "2.0", EntryPoint = "glGetActiveUniformsiv")]
[Obsolete("Use GetActiveUniforms(..., ActiveUniformParameter, ...) instead.")]
public static void GetActiveUniforms(UInt32 program, Int32 uniformCount, ref UInt32 uniformIndices, ArbUniformBufferObject pname, [OutAttribute] out Int32 @params)
{
GetActiveUniforms(program, uniformCount, ref uniformIndices, (ActiveUniformParameter)pname, out @params);
}
[System.CLSCompliant(false)]
[AutoGenerated(Category = "ArbUniformBufferObject", Version = "2.0", EntryPoint = "glGetActiveUniformsiv")]
[Obsolete("Use GetActiveUniforms(..., ActiveUniformParameter, ...) instead.")]
public static unsafe void GetActiveUniforms(UInt32 program, Int32 uniformCount, UInt32* uniformIndices, ArbUniformBufferObject pname, [OutAttribute] Int32* @params)
{
GetActiveUniforms(program, uniformCount, uniformIndices, (ActiveUniformParameter)pname, @params);
}
public static partial class Arb
{
[AutoGenerated(Category = "ArbGeometryShader4", Version = "3.0", EntryPoint = "glProgramParameteriARB")]
[Obsolete("Use ProgramParameter(..., AssemblyProgramParameterArb, ...) instead.")]
public static void ProgramParameter(Int32 program, ArbGeometryShader4 pname, Int32 value)
{
ProgramParameter(program, (AssemblyProgramParameterArb)pname, value);
}
[AutoGenerated(Category = "ArbGeometryShader4", Version = "3.0", EntryPoint = "glProgramParameteriARB")]
[Obsolete("Use ProgramParameter(..., AssemblyProgramParameterArb, ...) instead.")]
[CLSCompliant(false)]
public static void ProgramParameter(UInt32 program, ArbGeometryShader4 pname, Int32 value)
{
ProgramParameter(program, (AssemblyProgramParameterArb)pname, value);
}
}
public static partial class Ext
{
[AutoGenerated(Category = "EXT_geometry_shader4", Version = "2.0", EntryPoint = "glProgramParameteriEXT")]
[Obsolete("Use ProgramParameter(..., AssemblyProgramParameterArb, ...) instead.")]
public static void ProgramParameter(Int32 program, ExtGeometryShader4 pname, Int32 value)
{
ProgramParameter(program, (AssemblyProgramParameterArb)pname, value);
}
[AutoGenerated(Category = "ArbGeometryShader4", Version = "3.0", EntryPoint = "glProgramParameteriARB")]
[Obsolete("Use ProgramParameter(..., AssemblyProgramParameterArb, ...) instead.")]
[CLSCompliant(false)]
public static void ProgramParameter(UInt32 program, ExtGeometryShader4 pname, Int32 value)
{
ProgramParameter(program, (AssemblyProgramParameterArb)pname, value);
}
}
#endregion
#pragma warning restore 3019
#pragma warning restore 1591
#pragma warning restore 1572
#pragma warning restore 1573
#endregion
}
public delegate void DebugProcAmd(int id,
AmdDebugOutput category, AmdDebugOutput severity,
IntPtr length, string message, IntPtr userParam);
public delegate void DebugProcArb(int id,
ArbDebugOutput category, ArbDebugOutput severity,
IntPtr length, string message, IntPtr userParam);
}
// flibit added this!
#pragma warning restore 3021
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Xml.Serialization;
namespace System.Xml
{
internal abstract class IncrementalReadDecoder
{
internal abstract int DecodedCount { get; }
internal abstract bool IsFull { get; }
internal abstract void SetNextOutputBuffer(Array array, int offset, int len);
internal abstract int Decode(char[] chars, int startPos, int len);
internal abstract int Decode(string str, int startPos, int len);
internal abstract void Reset();
}
internal class BinHexDecoder : IncrementalReadDecoder
{
//
// Fields
//
private byte[] _buffer;
private int _startIndex;
private int _curIndex;
private int _endIndex;
private bool _hasHalfByteCached;
private byte _cachedHalfByte;
//
// IncrementalReadDecoder interface
//
internal override int DecodedCount
{
get
{
return _curIndex - _startIndex;
}
}
internal override bool IsFull
{
get
{
return _curIndex == _endIndex;
}
}
internal override unsafe int Decode(char[] chars, int startPos, int len)
{
Debug.Assert(chars != null);
Debug.Assert(len >= 0);
Debug.Assert(startPos >= 0);
Debug.Assert(chars.Length - startPos >= len);
if (len == 0)
{
return 0;
}
int bytesDecoded, charsDecoded;
fixed (char* pChars = &chars[startPos])
{
fixed (byte* pBytes = &_buffer[_curIndex])
{
Decode(pChars, pChars + len, pBytes, pBytes + (_endIndex - _curIndex),
ref _hasHalfByteCached, ref _cachedHalfByte, out charsDecoded, out bytesDecoded);
}
}
_curIndex += bytesDecoded;
return charsDecoded;
}
internal override unsafe int Decode(string str, int startPos, int len)
{
Debug.Assert(str != null);
Debug.Assert(len >= 0);
Debug.Assert(startPos >= 0);
Debug.Assert(str.Length - startPos >= len);
if (len == 0)
{
return 0;
}
int bytesDecoded, charsDecoded;
fixed (char* pChars = str)
{
fixed (byte* pBytes = &_buffer[_curIndex])
{
Decode(pChars + startPos, pChars + startPos + len, pBytes, pBytes + (_endIndex - _curIndex),
ref _hasHalfByteCached, ref _cachedHalfByte, out charsDecoded, out bytesDecoded);
}
}
_curIndex += bytesDecoded;
return charsDecoded;
}
internal override void Reset()
{
_hasHalfByteCached = false;
_cachedHalfByte = 0;
}
internal override void SetNextOutputBuffer(Array buffer, int index, int count)
{
Debug.Assert(buffer != null);
Debug.Assert(count >= 0);
Debug.Assert(index >= 0);
Debug.Assert(buffer.Length - index >= count);
Debug.Assert((buffer as byte[]) != null);
_buffer = (byte[])buffer;
_startIndex = index;
_curIndex = index;
_endIndex = index + count;
}
//
// Static methods
//
public static unsafe byte[] Decode(char[] chars, bool allowOddChars)
{
if (chars == null)
{
throw new ArgumentNullException(nameof(chars));
}
int len = chars.Length;
if (len == 0)
{
return Array.Empty<byte>();
}
byte[] bytes = new byte[(len + 1) / 2];
int bytesDecoded, charsDecoded;
bool hasHalfByteCached = false;
byte cachedHalfByte = 0;
fixed (char* pChars = &chars[0])
{
fixed (byte* pBytes = &bytes[0])
{
Decode(pChars, pChars + len, pBytes, pBytes + bytes.Length, ref hasHalfByteCached, ref cachedHalfByte, out charsDecoded, out bytesDecoded);
}
}
if (hasHalfByteCached && !allowOddChars)
{
throw new XmlException(SR.Format(SR.Xml_InvalidBinHexValueOddCount, new string(chars)));
}
if (bytesDecoded < bytes.Length)
{
byte[] tmp = new byte[bytesDecoded];
Buffer.BlockCopy(bytes, 0, tmp, 0, bytesDecoded);
bytes = tmp;
}
return bytes;
}
//
// Private methods
//
private static unsafe void Decode(char* pChars, char* pCharsEndPos,
byte* pBytes, byte* pBytesEndPos,
ref bool hasHalfByteCached, ref byte cachedHalfByte,
out int charsDecoded, out int bytesDecoded)
{
#if DEBUG
Debug.Assert(pCharsEndPos - pChars >= 0);
Debug.Assert(pBytesEndPos - pBytes >= 0);
#endif
char* pChar = pChars;
byte* pByte = pBytes;
XmlCharType xmlCharType = XmlCharType.Instance;
while (pChar < pCharsEndPos && pByte < pBytesEndPos)
{
byte halfByte;
char ch = *pChar++;
if (ch >= 'a' && ch <= 'f')
{
halfByte = (byte)(ch - 'a' + 10);
}
else if (ch >= 'A' && ch <= 'F')
{
halfByte = (byte)(ch - 'A' + 10);
}
else if (ch >= '0' && ch <= '9')
{
halfByte = (byte)(ch - '0');
}
else if ((xmlCharType.charProperties[ch] & XmlCharType.fWhitespace) != 0)
{ // else if ( xmlCharType.IsWhiteSpace( ch ) ) {
continue;
}
else
{
throw new XmlException(SR.Format(SR.Xml_InvalidBinHexValue, new string(pChars, 0, (int)(pCharsEndPos - pChars))));
}
if (hasHalfByteCached)
{
*pByte++ = (byte)((cachedHalfByte << 4) + halfByte);
hasHalfByteCached = false;
}
else
{
cachedHalfByte = halfByte;
hasHalfByteCached = true;
}
}
bytesDecoded = (int)(pByte - pBytes);
charsDecoded = (int)(pChar - pChars);
}
}
}
| |
// 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.IO.Tests
{
public class File_Create_str : FileSystemTest
{
#region Utilities
public virtual FileStream Create(string path)
{
return File.Create(path);
}
#endregion
#region UniversalTests
[Fact]
public void NullPath()
{
Assert.Throws<ArgumentNullException>(() => Create(null));
}
[Fact]
public void EmptyPath()
{
Assert.Throws<ArgumentException>(() => Create(string.Empty));
}
[Fact]
public void NonExistentPath()
{
Assert.Throws<DirectoryNotFoundException>(() => Create(Path.Combine(TestDirectory, GetTestFileName(), GetTestFileName())));
}
[Fact]
public void CreateCurrentDirectory()
{
Assert.Throws<UnauthorizedAccessException>(() => Create("."));
}
[Fact]
public void ValidCreation()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
string testFile = Path.Combine(testDir.FullName, GetTestFileName());
using (FileStream stream = Create(testFile))
{
Assert.True(File.Exists(testFile));
Assert.Equal(0, stream.Length);
Assert.Equal(0, stream.Position);
}
}
[ConditionalFact(nameof(UsingNewNormalization))]
[PlatformSpecific(TestPlatforms.Windows)] // Valid Windows path extended prefix
[ActiveIssue(20117, TargetFrameworkMonikers.Uap)]
public void ValidCreation_ExtendedSyntax()
{
DirectoryInfo testDir = Directory.CreateDirectory(IOInputs.ExtendedPrefix + GetTestFilePath());
Assert.StartsWith(IOInputs.ExtendedPrefix, testDir.FullName);
string testFile = Path.Combine(testDir.FullName, GetTestFileName());
using (FileStream stream = Create(testFile))
{
Assert.True(File.Exists(testFile));
Assert.Equal(0, stream.Length);
Assert.Equal(0, stream.Position);
}
}
[ConditionalFact(nameof(AreAllLongPathsAvailable))]
[PlatformSpecific(TestPlatforms.Windows)] // Valid Windows path extended prefix, long path
[ActiveIssue(20117, TargetFrameworkMonikers.Uap)]
public void ValidCreation_LongPathExtendedSyntax()
{
DirectoryInfo testDir = Directory.CreateDirectory(IOServices.GetPath(IOInputs.ExtendedPrefix + TestDirectory, characterCount: 500).FullPath);
Assert.StartsWith(IOInputs.ExtendedPrefix, testDir.FullName);
string testFile = Path.Combine(testDir.FullName, GetTestFileName());
using (FileStream stream = Create(testFile))
{
Assert.True(File.Exists(testFile));
Assert.Equal(0, stream.Length);
Assert.Equal(0, stream.Position);
}
}
[Fact]
public void CreateInParentDirectory()
{
string testFile = GetTestFileName();
using (FileStream stream = Create(Path.Combine(TestDirectory, "DoesntExists", "..", testFile)))
{
Assert.True(File.Exists(Path.Combine(TestDirectory, testFile)));
}
}
[Fact]
public void LegalSymbols()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
string testFile = Path.Combine(testDir.FullName, GetTestFileName() + "!@#$%^&");
using (FileStream stream = Create(testFile))
{
Assert.True(File.Exists(testFile));
}
}
[Fact]
public void InvalidDirectory()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
string testFile = Path.Combine(testDir.FullName, GetTestFileName(), GetTestFileName());
Assert.Throws<DirectoryNotFoundException>(() => Create(testFile));
}
[Fact]
public void FileInUse()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
string testFile = Path.Combine(testDir.FullName, GetTestFileName());
using (FileStream stream = Create(testFile))
{
Assert.True(File.Exists(testFile));
Assert.Throws<IOException>(() => Create(testFile));
}
}
[Fact]
public void FileAlreadyExists()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
string testFile = Path.Combine(testDir.FullName, GetTestFileName());
Create(testFile).Dispose();
Assert.True(File.Exists(testFile));
Create(testFile).Dispose();
Assert.True(File.Exists(testFile));
}
[Fact]
public void OverwriteReadOnly()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
string testFile = Path.Combine(testDir.FullName, GetTestFileName());
Create(testFile).Dispose();
Assert.True(File.Exists(testFile));
Create(testFile).Dispose();
Assert.True(File.Exists(testFile));
}
[Fact]
public void LongPath()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
Assert.Throws<PathTooLongException>(() => Create(Path.Combine(testDir.FullName, new string('a', 300))));
//TODO #645: File creation does not yet have long path support on Unix or Windows
//using (Create(Path.Combine(testDir.FullName, new string('k', 257))))
//{
// Assert.True(File.Exists(Path.Combine(testDir.FullName, new string('k', 257))));
//}
}
#endregion
#region PlatformSpecific
[Fact]
[PlatformSpecific(CaseSensitivePlatforms)]
public void CaseSensitive()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
string testFile = Path.Combine(testDir.FullName, GetTestFileName());
using (File.Create(testFile + "AAAA"))
using (File.Create(testFile + "aAAa"))
{
Assert.False(File.Exists(testFile + "AaAa"));
Assert.True(File.Exists(testFile + "AAAA"));
Assert.True(File.Exists(testFile + "aAAa"));
Assert.Equal(2, Directory.GetFiles(testDir.FullName).Length);
}
Assert.Throws<DirectoryNotFoundException>(() => File.Create(testFile.ToLowerInvariant()));
}
[Fact]
[PlatformSpecific(CaseInsensitivePlatforms)]
public void CaseInsensitive()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
string testFile = Path.Combine(testDir.FullName, GetTestFileName());
File.Create(testFile + "AAAA").Dispose();
File.Create(testFile.ToLowerInvariant() + "aAAa").Dispose();
Assert.Equal(1, Directory.GetFiles(testDir.FullName).Length);
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Invalid file name with wildcard characters on Windows
public void WindowsWildCharacterPath()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
Assert.Throws<ArgumentException>(() => Create(Path.Combine(testDir.FullName, "dls;d", "442349-0", "v443094(*)(+*$#$*", new string(Path.DirectorySeparatorChar, 3))));
Assert.Throws<ArgumentException>(() => Create(Path.Combine(testDir.FullName, "*")));
Assert.Throws<ArgumentException>(() => Create(Path.Combine(testDir.FullName, "Test*t")));
Assert.Throws<ArgumentException>(() => Create(Path.Combine(testDir.FullName, "*Tes*t")));
}
[Theory,
InlineData(" "),
InlineData(" "),
InlineData("\n"),
InlineData(">"),
InlineData("<"),
InlineData("\0"),
InlineData("\t")]
[PlatformSpecific(TestPlatforms.Windows)] // Invalid file name with whitespace on Windows
public void WindowsWhitespacePath(string path)
{
Assert.Throws<ArgumentException>(() => Create(path));
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)]
public void CreateNullThrows_Unix()
{
Assert.Throws<ArgumentException>(() => Create("\0"));
}
[Theory,
InlineData(" "),
InlineData(" "),
InlineData("\n"),
InlineData(">"),
InlineData("<"),
InlineData("\t")]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Valid file name with Whitespace on Unix
public void UnixWhitespacePath(string path)
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
using (Create(Path.Combine(testDir.FullName, path)))
{
Assert.True(File.Exists(Path.Combine(testDir.FullName, path)));
}
}
#endregion
}
public class File_Create_str_i : File_Create_str
{
public override FileStream Create(string path)
{
return File.Create(path, 4096); // Default buffer size
}
public virtual FileStream Create(string path, int bufferSize)
{
return File.Create(path, bufferSize);
}
[Fact]
public void NegativeBuffer()
{
Assert.Throws<ArgumentOutOfRangeException>(() => Create(GetTestFilePath(), -1));
Assert.Throws<ArgumentOutOfRangeException>(() => Create(GetTestFilePath(), -100));
}
}
public class File_Create_str_i_fo : File_Create_str_i
{
public override FileStream Create(string path)
{
return File.Create(path, 4096, FileOptions.Asynchronous);
}
public override FileStream Create(string path, int bufferSize)
{
return File.Create(path, bufferSize, FileOptions.Asynchronous);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
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 IBits = Lucene.Net.Util.IBits;
using IndexReader = Lucene.Net.Index.IndexReader;
using Term = Lucene.Net.Index.Term;
using ToStringUtils = Lucene.Net.Util.ToStringUtils;
/// <summary>
/// A query that applies a filter to the results of another query.
///
/// <para/>Note: the bits are retrieved from the filter each time this
/// query is used in a search - use a <see cref="CachingWrapperFilter"/> to avoid
/// regenerating the bits every time.
/// <para/>
/// @since 1.4 </summary>
/// <seealso cref="CachingWrapperFilter"/>
public class FilteredQuery : Query
{
private readonly Query query;
private readonly Filter filter;
private readonly FilterStrategy strategy;
/// <summary>
/// Constructs a new query which applies a filter to the results of the original query.
/// <see cref="Filter.GetDocIdSet(AtomicReaderContext, IBits)"/> will be called every time this query is used in a search. </summary>
/// <param name="query"> Query to be filtered, cannot be <c>null</c>. </param>
/// <param name="filter"> Filter to apply to query results, cannot be <c>null</c>. </param>
public FilteredQuery(Query query, Filter filter)
: this(query, filter, RANDOM_ACCESS_FILTER_STRATEGY)
{
}
/// <summary>
/// Expert: Constructs a new query which applies a filter to the results of the original query.
/// <see cref="Filter.GetDocIdSet(AtomicReaderContext, IBits)"/> will be called every time this query is used in a search. </summary>
/// <param name="query"> Query to be filtered, cannot be <c>null</c>. </param>
/// <param name="filter"> Filter to apply to query results, cannot be <c>null</c>. </param>
/// <param name="strategy"> A filter strategy used to create a filtered scorer.
/// </param>
/// <seealso cref="FilterStrategy"/>
public FilteredQuery(Query query, Filter filter, FilterStrategy strategy)
{
if (query == null || filter == null)
{
throw new ArgumentException("Query and filter cannot be null.");
}
if (strategy == null)
{
throw new ArgumentException("FilterStrategy can not be null");
}
this.strategy = strategy;
this.query = query;
this.filter = filter;
}
/// <summary>
/// Returns a <see cref="Weight"/> that applies the filter to the enclosed query's <see cref="Weight"/>.
/// this is accomplished by overriding the <see cref="Scorer"/> returned by the <see cref="Weight"/>.
/// </summary>
public override Weight CreateWeight(IndexSearcher searcher)
{
Weight weight = query.CreateWeight(searcher);
return new WeightAnonymousInnerClassHelper(this, weight);
}
private class WeightAnonymousInnerClassHelper : Weight
{
private readonly FilteredQuery outerInstance;
private Lucene.Net.Search.Weight weight;
public WeightAnonymousInnerClassHelper(FilteredQuery outerInstance, Lucene.Net.Search.Weight weight)
{
this.outerInstance = outerInstance;
this.weight = weight;
}
public override bool ScoresDocsOutOfOrder => true;
public override float GetValueForNormalization()
{
return weight.GetValueForNormalization() * outerInstance.Boost * outerInstance.Boost; // boost sub-weight
}
public override void Normalize(float norm, float topLevelBoost)
{
weight.Normalize(norm, topLevelBoost * outerInstance.Boost); // incorporate boost
}
public override Explanation Explain(AtomicReaderContext ir, int i)
{
Explanation inner = weight.Explain(ir, i);
Filter f = outerInstance.filter;
DocIdSet docIdSet = f.GetDocIdSet(ir, ir.AtomicReader.LiveDocs);
DocIdSetIterator docIdSetIterator = docIdSet == null ? DocIdSetIterator.GetEmpty() : docIdSet.GetIterator();
if (docIdSetIterator == null)
{
docIdSetIterator = DocIdSetIterator.GetEmpty();
}
if (docIdSetIterator.Advance(i) == i)
{
return inner;
}
else
{
Explanation result = new Explanation(0.0f, "failure to match filter: " + f.ToString());
result.AddDetail(inner);
return result;
}
}
// return this query
public override Query Query => outerInstance;
// return a filtering scorer
public override Scorer GetScorer(AtomicReaderContext context, IBits acceptDocs)
{
Debug.Assert(outerInstance.filter != null);
DocIdSet filterDocIdSet = outerInstance.filter.GetDocIdSet(context, acceptDocs);
if (filterDocIdSet == null)
{
// this means the filter does not accept any documents.
return null;
}
return outerInstance.strategy.FilteredScorer(context, weight, filterDocIdSet);
}
// return a filtering top scorer
public override BulkScorer GetBulkScorer(AtomicReaderContext context, bool scoreDocsInOrder, IBits acceptDocs)
{
Debug.Assert(outerInstance.filter != null);
DocIdSet filterDocIdSet = outerInstance.filter.GetDocIdSet(context, acceptDocs);
if (filterDocIdSet == null)
{
// this means the filter does not accept any documents.
return null;
}
return outerInstance.strategy.FilteredBulkScorer(context, weight, scoreDocsInOrder, filterDocIdSet);
}
}
/// <summary>
/// A scorer that consults the filter if a document was matched by the
/// delegate scorer. This is useful if the filter computation is more expensive
/// than document scoring or if the filter has a linear running time to compute
/// the next matching doc like exact geo distances.
/// </summary>
private sealed class QueryFirstScorer : Scorer
{
private readonly Scorer scorer;
private int scorerDoc = -1;
private readonly IBits filterBits;
internal QueryFirstScorer(Weight weight, IBits filterBits, Scorer other)
: base(weight)
{
this.scorer = other;
this.filterBits = filterBits;
}
public override int NextDoc()
{
int doc;
for (; ; )
{
doc = scorer.NextDoc();
if (doc == Scorer.NO_MORE_DOCS || filterBits.Get(doc))
{
return scorerDoc = doc;
}
}
}
public override int Advance(int target)
{
int doc = scorer.Advance(target);
if (doc != Scorer.NO_MORE_DOCS && !filterBits.Get(doc))
{
return scorerDoc = NextDoc();
}
else
{
return scorerDoc = doc;
}
}
public override int DocID => scorerDoc;
public override float GetScore()
{
return scorer.GetScore();
}
public override int Freq => scorer.Freq;
public override ICollection<ChildScorer> GetChildren()
{
return new[] { new ChildScorer(scorer, "FILTERED") };
}
public override long GetCost()
{
return scorer.GetCost();
}
}
private class QueryFirstBulkScorer : BulkScorer
{
private readonly Scorer scorer;
private readonly IBits filterBits;
public QueryFirstBulkScorer(Scorer scorer, IBits filterBits)
{
this.scorer = scorer;
this.filterBits = filterBits;
}
public override bool Score(ICollector collector, int maxDoc)
{
// the normalization trick already applies the boost of this query,
// so we can use the wrapped scorer directly:
collector.SetScorer(scorer);
if (scorer.DocID == -1)
{
scorer.NextDoc();
}
while (true)
{
int scorerDoc = scorer.DocID;
if (scorerDoc < maxDoc)
{
if (filterBits.Get(scorerDoc))
{
collector.Collect(scorerDoc);
}
scorer.NextDoc();
}
else
{
break;
}
}
return scorer.DocID != Scorer.NO_MORE_DOCS;
}
}
/// <summary>
/// A <see cref="Scorer"/> that uses a "leap-frog" approach (also called "zig-zag join"). The scorer and the filter
/// take turns trying to advance to each other's next matching document, often
/// jumping past the target document. When both land on the same document, it's
/// collected.
/// </summary>
private class LeapFrogScorer : Scorer
{
private readonly DocIdSetIterator secondary;
private readonly DocIdSetIterator primary;
private readonly Scorer scorer;
protected int m_primaryDoc = -1;
protected int m_secondaryDoc = -1;
protected internal LeapFrogScorer(Weight weight, DocIdSetIterator primary, DocIdSetIterator secondary, Scorer scorer)
: base(weight)
{
this.primary = primary;
this.secondary = secondary;
this.scorer = scorer;
}
private int AdvanceToNextCommonDoc()
{
for (; ; )
{
if (m_secondaryDoc < m_primaryDoc)
{
m_secondaryDoc = secondary.Advance(m_primaryDoc);
}
else if (m_secondaryDoc == m_primaryDoc)
{
return m_primaryDoc;
}
else
{
m_primaryDoc = primary.Advance(m_secondaryDoc);
}
}
}
public override sealed int NextDoc()
{
m_primaryDoc = PrimaryNext();
return AdvanceToNextCommonDoc();
}
protected virtual int PrimaryNext()
{
return primary.NextDoc();
}
public override sealed int Advance(int target)
{
if (target > m_primaryDoc)
{
m_primaryDoc = primary.Advance(target);
}
return AdvanceToNextCommonDoc();
}
public override sealed int DocID => m_secondaryDoc;
public override sealed float GetScore()
{
return scorer.GetScore();
}
public override sealed int Freq => scorer.Freq;
public override sealed ICollection<ChildScorer> GetChildren()
{
return new[] { new ChildScorer(scorer, "FILTERED") };
}
public override long GetCost()
{
return Math.Min(primary.GetCost(), secondary.GetCost());
}
}
// TODO once we have way to figure out if we use RA or LeapFrog we can remove this scorer
private sealed class PrimaryAdvancedLeapFrogScorer : LeapFrogScorer
{
private readonly int firstFilteredDoc;
internal PrimaryAdvancedLeapFrogScorer(Weight weight, int firstFilteredDoc, DocIdSetIterator filterIter, Scorer other)
: base(weight, filterIter, other, other)
{
this.firstFilteredDoc = firstFilteredDoc;
this.m_primaryDoc = firstFilteredDoc; // initialize to prevent and advance call to move it further
}
protected override int PrimaryNext()
{
if (m_secondaryDoc != -1)
{
return base.PrimaryNext();
}
else
{
return firstFilteredDoc;
}
}
}
/// <summary>
/// Rewrites the query. If the wrapped is an instance of
/// <see cref="MatchAllDocsQuery"/> it returns a <see cref="ConstantScoreQuery"/>. Otherwise
/// it returns a new <see cref="FilteredQuery"/> wrapping the rewritten query.
/// </summary>
public override Query Rewrite(IndexReader reader)
{
Query queryRewritten = query.Rewrite(reader);
if (queryRewritten != query)
{
// rewrite to a new FilteredQuery wrapping the rewritten query
Query rewritten = new FilteredQuery(queryRewritten, filter, strategy);
rewritten.Boost = this.Boost;
return rewritten;
}
else
{
// nothing to rewrite, we are done!
return this;
}
}
/// <summary>
/// Returns this <see cref="FilteredQuery"/>'s (unfiltered) <see cref="Query"/> </summary>
public Query Query => query;
/// <summary>
/// Returns this <see cref="FilteredQuery"/>'s filter </summary>
public Filter Filter => filter;
/// <summary>
/// Returns this <see cref="FilteredQuery"/>'s <seealso cref="FilterStrategy"/> </summary>
public virtual FilterStrategy Strategy => this.strategy;
/// <summary>
/// Expert: adds all terms occurring in this query to the terms set. Only
/// works if this query is in its rewritten (<see cref="Rewrite(IndexReader)"/>) form.
/// </summary>
/// <exception cref="InvalidOperationException"> If this query is not yet rewritten </exception>
public override void ExtractTerms(ISet<Term> terms)
{
Query.ExtractTerms(terms);
}
/// <summary>
/// Prints a user-readable version of this query. </summary>
public override string ToString(string s)
{
StringBuilder buffer = new StringBuilder();
buffer.Append("filtered(");
buffer.Append(query.ToString(s));
buffer.Append(")->");
buffer.Append(filter);
buffer.Append(ToStringUtils.Boost(Boost));
return buffer.ToString();
}
/// <summary>
/// Returns true if <paramref name="o"/> is equal to this. </summary>
public override bool Equals(object o)
{
if (o == this)
{
return true;
}
if (!base.Equals(o))
{
return false;
}
Debug.Assert(o is FilteredQuery);
FilteredQuery fq = (FilteredQuery)o;
return fq.query.Equals(this.query) && fq.filter.Equals(this.filter) && fq.strategy.Equals(this.strategy);
}
/// <summary>
/// Returns a hash code value for this object. </summary>
public override int GetHashCode()
{
int hash = base.GetHashCode();
hash = hash * 31 + strategy.GetHashCode();
hash = hash * 31 + query.GetHashCode();
hash = hash * 31 + filter.GetHashCode();
return hash;
}
/// <summary>
/// A <see cref="FilterStrategy"/> that conditionally uses a random access filter if
/// the given <see cref="DocIdSet"/> supports random access (returns a non-null value
/// from <see cref="DocIdSet.Bits"/>) and
/// <see cref="RandomAccessFilterStrategy.UseRandomAccess(IBits, int)"/> returns
/// <c>true</c>. Otherwise this strategy falls back to a "zig-zag join" (
/// <see cref="FilteredQuery.LEAP_FROG_FILTER_FIRST_STRATEGY"/>) strategy.
///
/// <para>
/// Note: this strategy is the default strategy in <see cref="FilteredQuery"/>
/// </para>
/// </summary>
public static readonly FilterStrategy RANDOM_ACCESS_FILTER_STRATEGY = new RandomAccessFilterStrategy();
/// <summary>
/// A filter strategy that uses a "leap-frog" approach (also called "zig-zag join").
/// The scorer and the filter
/// take turns trying to advance to each other's next matching document, often
/// jumping past the target document. When both land on the same document, it's
/// collected.
/// <para>
/// Note: this strategy uses the filter to lead the iteration.
/// </para>
/// </summary>
public static readonly FilterStrategy LEAP_FROG_FILTER_FIRST_STRATEGY = new LeapFrogFilterStrategy(false);
/// <summary>
/// A filter strategy that uses a "leap-frog" approach (also called "zig-zag join").
/// The scorer and the filter
/// take turns trying to advance to each other's next matching document, often
/// jumping past the target document. When both land on the same document, it's
/// collected.
/// <para>
/// Note: this strategy uses the query to lead the iteration.
/// </para>
/// </summary>
public static readonly FilterStrategy LEAP_FROG_QUERY_FIRST_STRATEGY = new LeapFrogFilterStrategy(true);
/// <summary>
/// A filter strategy that advances the <see cref="Search.Query"/> or rather its <see cref="Scorer"/> first and consults the
/// filter <see cref="DocIdSet"/> for each matched document.
/// <para>
/// Note: this strategy requires a <see cref="DocIdSet.Bits"/> to return a non-null value. Otherwise
/// this strategy falls back to <see cref="FilteredQuery.LEAP_FROG_QUERY_FIRST_STRATEGY"/>
/// </para>
/// <para>
/// Use this strategy if the filter computation is more expensive than document
/// scoring or if the filter has a linear running time to compute the next
/// matching doc like exact geo distances.
/// </para>
/// </summary>
public static readonly FilterStrategy QUERY_FIRST_FILTER_STRATEGY = new QueryFirstFilterStrategy();
/// <summary>
/// Abstract class that defines how the filter (<see cref="DocIdSet"/>) applied during document collection. </summary>
public abstract class FilterStrategy
{
/// <summary>
/// Returns a filtered <see cref="Scorer"/> based on this strategy.
/// </summary>
/// <param name="context">
/// the <see cref="AtomicReaderContext"/> for which to return the <see cref="Scorer"/>. </param>
/// <param name="weight"> the <see cref="FilteredQuery"/> <see cref="Weight"/> to create the filtered scorer. </param>
/// <param name="docIdSet"> the filter <see cref="DocIdSet"/> to apply </param>
/// <returns> a filtered scorer
/// </returns>
/// <exception cref="IOException"> if an <see cref="IOException"/> occurs </exception>
public abstract Scorer FilteredScorer(AtomicReaderContext context, Weight weight, DocIdSet docIdSet);
/// <summary>
/// Returns a filtered <see cref="BulkScorer"/> based on this
/// strategy. this is an optional method: the default
/// implementation just calls <see cref="FilteredScorer(AtomicReaderContext, Weight, DocIdSet)"/> and
/// wraps that into a <see cref="BulkScorer"/>.
/// </summary>
/// <param name="context">
/// the <seealso cref="AtomicReaderContext"/> for which to return the <seealso cref="Scorer"/>. </param>
/// <param name="weight"> the <seealso cref="FilteredQuery"/> <seealso cref="Weight"/> to create the filtered scorer. </param>
/// <param name="scoreDocsInOrder"> <c>true</c> to score docs in order </param>
/// <param name="docIdSet"> the filter <seealso cref="DocIdSet"/> to apply </param>
/// <returns> a filtered top scorer </returns>
public virtual BulkScorer FilteredBulkScorer(AtomicReaderContext context, Weight weight, bool scoreDocsInOrder, DocIdSet docIdSet)
{
Scorer scorer = FilteredScorer(context, weight, docIdSet);
if (scorer == null)
{
return null;
}
// this impl always scores docs in order, so we can
// ignore scoreDocsInOrder:
return new Weight.DefaultBulkScorer(scorer);
}
}
/// <summary>
/// A <see cref="FilterStrategy"/> that conditionally uses a random access filter if
/// the given <see cref="DocIdSet"/> supports random access (returns a non-null value
/// from <see cref="DocIdSet.Bits"/>) and
/// <see cref="RandomAccessFilterStrategy.UseRandomAccess(IBits, int)"/> returns
/// <code>true</code>. Otherwise this strategy falls back to a "zig-zag join" (
/// <see cref="FilteredQuery.LEAP_FROG_FILTER_FIRST_STRATEGY"/>) strategy .
/// </summary>
public class RandomAccessFilterStrategy : FilterStrategy
{
public override Scorer FilteredScorer(AtomicReaderContext context, Weight weight, DocIdSet docIdSet)
{
DocIdSetIterator filterIter = docIdSet.GetIterator();
if (filterIter == null)
{
// this means the filter does not accept any documents.
return null;
}
int firstFilterDoc = filterIter.NextDoc();
if (firstFilterDoc == DocIdSetIterator.NO_MORE_DOCS)
{
return null;
}
IBits filterAcceptDocs = docIdSet.Bits;
// force if RA is requested
bool useRandomAccess = filterAcceptDocs != null && UseRandomAccess(filterAcceptDocs, firstFilterDoc);
if (useRandomAccess)
{
// if we are using random access, we return the inner scorer, just with other acceptDocs
return weight.GetScorer(context, filterAcceptDocs);
}
else
{
Debug.Assert(firstFilterDoc > -1);
// we are gonna advance() this scorer, so we set inorder=true/toplevel=false
// we pass null as acceptDocs, as our filter has already respected acceptDocs, no need to do twice
Scorer scorer = weight.GetScorer(context, null);
// TODO once we have way to figure out if we use RA or LeapFrog we can remove this scorer
return (scorer == null) ? null : new PrimaryAdvancedLeapFrogScorer(weight, firstFilterDoc, filterIter, scorer);
}
}
/// <summary>
/// Expert: decides if a filter should be executed as "random-access" or not.
/// Random-access means the filter "filters" in a similar way as deleted docs are filtered
/// in Lucene. This is faster when the filter accepts many documents.
/// However, when the filter is very sparse, it can be faster to execute the query+filter
/// as a conjunction in some cases.
/// <para/>
/// The default implementation returns <c>true</c> if the first document accepted by the
/// filter is < 100.
/// <para/>
/// @lucene.internal
/// </summary>
protected virtual bool UseRandomAccess(IBits bits, int firstFilterDoc)
{
//TODO once we have a cost API on filters and scorers we should rethink this heuristic
return firstFilterDoc < 100;
}
}
private sealed class LeapFrogFilterStrategy : FilterStrategy
{
private readonly bool scorerFirst;
internal LeapFrogFilterStrategy(bool scorerFirst)
{
this.scorerFirst = scorerFirst;
}
public override Scorer FilteredScorer(AtomicReaderContext context, Weight weight, DocIdSet docIdSet)
{
DocIdSetIterator filterIter = docIdSet.GetIterator();
if (filterIter == null)
{
// this means the filter does not accept any documents.
return null;
}
// we pass null as acceptDocs, as our filter has already respected acceptDocs, no need to do twice
Scorer scorer = weight.GetScorer(context, null);
if (scorer == null)
{
return null;
}
if (scorerFirst)
{
return new LeapFrogScorer(weight, scorer, filterIter, scorer);
}
else
{
return new LeapFrogScorer(weight, filterIter, scorer, scorer);
}
}
}
/// <summary>
/// A filter strategy that advances the <see cref="Scorer"/> first and consults the
/// <see cref="DocIdSet"/> for each matched document.
/// <para>
/// Note: this strategy requires a <see cref="DocIdSet.Bits"/> to return a non-null value. Otherwise
/// this strategy falls back to <see cref="FilteredQuery.LEAP_FROG_QUERY_FIRST_STRATEGY"/>
/// </para>
/// <para>
/// Use this strategy if the filter computation is more expensive than document
/// scoring or if the filter has a linear running time to compute the next
/// matching doc like exact geo distances.
/// </para>
/// </summary>
private sealed class QueryFirstFilterStrategy : FilterStrategy
{
public override Scorer FilteredScorer(AtomicReaderContext context, Weight weight, DocIdSet docIdSet)
{
IBits filterAcceptDocs = docIdSet.Bits;
if (filterAcceptDocs == null)
{
// Filter does not provide random-access Bits; we
// must fallback to leapfrog:
return LEAP_FROG_QUERY_FIRST_STRATEGY.FilteredScorer(context, weight, docIdSet);
}
Scorer scorer = weight.GetScorer(context, null);
return scorer == null ? null : new QueryFirstScorer(weight, filterAcceptDocs, scorer);
}
public override BulkScorer FilteredBulkScorer(AtomicReaderContext context, Weight weight, bool scoreDocsInOrder, DocIdSet docIdSet) // ignored (we always top-score in order)
{
IBits filterAcceptDocs = docIdSet.Bits;
if (filterAcceptDocs == null)
{
// Filter does not provide random-access Bits; we
// must fallback to leapfrog:
return LEAP_FROG_QUERY_FIRST_STRATEGY.FilteredBulkScorer(context, weight, scoreDocsInOrder, docIdSet);
}
Scorer scorer = weight.GetScorer(context, null);
return scorer == null ? null : new QueryFirstBulkScorer(scorer, filterAcceptDocs);
}
}
}
}
| |
// 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.
//
// CSP-based implementation of RSA
//
namespace System.Security.Cryptography {
using System;
using System.Globalization;
using System.IO;
using System.Security;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security.Cryptography.X509Certificates;
using System.Security.Permissions;
using System.Diagnostics.Contracts;
// Object layout of the RSAParameters structure
internal class RSACspObject {
internal byte[] Exponent;
internal byte[] Modulus;
internal byte[] P;
internal byte[] Q;
internal byte[] DP;
internal byte[] DQ;
internal byte[] InverseQ;
internal byte[] D;
}
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class RSACryptoServiceProvider : RSA
, ICspAsymmetricAlgorithm
{
private int _dwKeySize;
private CspParameters _parameters;
private bool _randomKeyContainer;
[System.Security.SecurityCritical] // auto-generated
private SafeProvHandle _safeProvHandle;
[System.Security.SecurityCritical] // auto-generated
private SafeKeyHandle _safeKeyHandle;
private static volatile CspProviderFlags s_UseMachineKeyStore = 0;
//
// QCalls
//
[System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void DecryptKey(SafeKeyHandle pKeyContext,
[MarshalAs(UnmanagedType.LPArray)] byte[] pbEncryptedKey,
int cbEncryptedKey,
[MarshalAs(UnmanagedType.Bool)] bool fOAEP,
ObjectHandleOnStack ohRetDecryptedKey);
[System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void EncryptKey(SafeKeyHandle pKeyContext,
[MarshalAs(UnmanagedType.LPArray)] byte[] pbKey,
int cbKey,
[MarshalAs(UnmanagedType.Bool)] bool fOAEP,
ObjectHandleOnStack ohRetEncryptedKey);
//
// public constructors
//
[System.Security.SecuritySafeCritical] // auto-generated
public RSACryptoServiceProvider()
: this(0, new CspParameters(Utils.DefaultRsaProviderType, null, null, s_UseMachineKeyStore), true) {
}
[System.Security.SecuritySafeCritical] // auto-generated
public RSACryptoServiceProvider(int dwKeySize)
: this(dwKeySize, new CspParameters(Utils.DefaultRsaProviderType, null, null, s_UseMachineKeyStore), false) {
}
[System.Security.SecuritySafeCritical] // auto-generated
public RSACryptoServiceProvider(CspParameters parameters)
: this(0, parameters, true) {
}
[System.Security.SecuritySafeCritical] // auto-generated
public RSACryptoServiceProvider(int dwKeySize, CspParameters parameters)
: this(dwKeySize, parameters, false) {
}
//
// private methods
//
[System.Security.SecurityCritical] // auto-generated
private RSACryptoServiceProvider(int dwKeySize, CspParameters parameters, bool useDefaultKeySize) {
if (dwKeySize < 0)
throw new ArgumentOutOfRangeException("dwKeySize", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
_parameters = Utils.SaveCspParameters(CspAlgorithmType.Rsa, parameters, s_UseMachineKeyStore, ref _randomKeyContainer);
LegalKeySizesValue = new KeySizes[] { new KeySizes(384, 16384, 8) };
_dwKeySize = useDefaultKeySize ? 1024 : dwKeySize;
// If this is not a random container we generate, create it eagerly
// in the constructor so we can report any errors now.
if (!_randomKeyContainer
#if !FEATURE_CORECLR
|| Environment.GetCompatibilityFlag(CompatibilityFlag.EagerlyGenerateRandomAsymmKeys)
#endif //!FEATURE_CORECLR
)
GetKeyPair();
}
[System.Security.SecurityCritical] // auto-generated
private void GetKeyPair () {
if (_safeKeyHandle == null) {
lock (this) {
if (_safeKeyHandle == null) {
// We only attempt to generate a random key on desktop runtimes because the CoreCLR
// RSA surface area is limited to simply verifying signatures. Since generating a
// random key to verify signatures will always lead to failure (unless we happend to
// win the lottery and randomly generate the signing key ...), there is no need
// to add this functionality to CoreCLR at this point.
Utils.GetKeyPairHelper(CspAlgorithmType.Rsa, _parameters, _randomKeyContainer, _dwKeySize, ref _safeProvHandle, ref _safeKeyHandle);
}
}
}
}
[System.Security.SecuritySafeCritical] // overrides public transparent member
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (_safeKeyHandle != null && !_safeKeyHandle.IsClosed)
_safeKeyHandle.Dispose();
if (_safeProvHandle != null && !_safeProvHandle.IsClosed)
_safeProvHandle.Dispose();
}
//
// public properties
//
[System.Runtime.InteropServices.ComVisible(false)]
public bool PublicOnly {
[System.Security.SecuritySafeCritical] // auto-generated
get {
GetKeyPair();
byte[] publicKey = (byte[]) Utils._GetKeyParameter(_safeKeyHandle, Constants.CLR_PUBLICKEYONLY);
return (publicKey[0] == 1);
}
}
[System.Runtime.InteropServices.ComVisible(false)]
public CspKeyContainerInfo CspKeyContainerInfo {
[System.Security.SecuritySafeCritical] // auto-generated
get {
GetKeyPair();
return new CspKeyContainerInfo(_parameters, _randomKeyContainer);
}
}
public override int KeySize {
[System.Security.SecuritySafeCritical] // auto-generated
get {
GetKeyPair();
byte[] keySize = (byte[]) Utils._GetKeyParameter(_safeKeyHandle, Constants.CLR_KEYLEN);
_dwKeySize = (keySize[0] | (keySize[1] << 8) | (keySize[2] << 16) | (keySize[3] << 24));
return _dwKeySize;
}
}
public override string KeyExchangeAlgorithm {
get {
if (_parameters.KeyNumber == Constants.AT_KEYEXCHANGE)
return "RSA-PKCS1-KeyEx";
return null;
}
}
public override string SignatureAlgorithm {
get { return "http://www.w3.org/2000/09/xmldsig#rsa-sha1"; }
}
public static bool UseMachineKeyStore {
get { return (s_UseMachineKeyStore == CspProviderFlags.UseMachineKeyStore); }
set { s_UseMachineKeyStore = (value ? CspProviderFlags.UseMachineKeyStore : 0); }
}
public bool PersistKeyInCsp {
[System.Security.SecuritySafeCritical] // auto-generated
get {
if (_safeProvHandle == null) {
lock (this) {
if (_safeProvHandle == null)
_safeProvHandle = Utils.CreateProvHandle(_parameters, _randomKeyContainer);
}
}
return Utils.GetPersistKeyInCsp(_safeProvHandle);
}
[System.Security.SecuritySafeCritical] // auto-generated
set {
bool oldPersistKeyInCsp = this.PersistKeyInCsp;
if (value == oldPersistKeyInCsp)
return;
if (!CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) {
KeyContainerPermission kp = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags);
if (!value) {
KeyContainerPermissionAccessEntry entry = new KeyContainerPermissionAccessEntry(_parameters, KeyContainerPermissionFlags.Delete);
kp.AccessEntries.Add(entry);
} else {
KeyContainerPermissionAccessEntry entry = new KeyContainerPermissionAccessEntry(_parameters, KeyContainerPermissionFlags.Create);
kp.AccessEntries.Add(entry);
}
kp.Demand();
}
Utils.SetPersistKeyInCsp(_safeProvHandle, value);
}
}
//
// public methods
//
[System.Security.SecuritySafeCritical] // auto-generated
public override RSAParameters ExportParameters (bool includePrivateParameters) {
GetKeyPair();
if (includePrivateParameters) {
if (!CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) {
KeyContainerPermission kp = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags);
KeyContainerPermissionAccessEntry entry = new KeyContainerPermissionAccessEntry(_parameters, KeyContainerPermissionFlags.Export);
kp.AccessEntries.Add(entry);
kp.Demand();
}
}
RSACspObject rsaCspObject = new RSACspObject();
int blobType = includePrivateParameters ? Constants.PRIVATEKEYBLOB : Constants.PUBLICKEYBLOB;
// _ExportKey will check for failures and throw an exception
Utils._ExportKey(_safeKeyHandle, blobType, rsaCspObject);
return RSAObjectToStruct(rsaCspObject);
}
#if FEATURE_LEGACYNETCFCRYPTO
[System.Security.SecurityCritical]
#else
[System.Security.SecuritySafeCritical] // auto-generated
#endif
[System.Runtime.InteropServices.ComVisible(false)]
public byte[] ExportCspBlob (bool includePrivateParameters) {
GetKeyPair();
return Utils.ExportCspBlobHelper(includePrivateParameters, _parameters, _safeKeyHandle);
}
[System.Security.SecuritySafeCritical] // auto-generated
public override void ImportParameters(RSAParameters parameters) {
// Free the current key handle
if (_safeKeyHandle != null && !_safeKeyHandle.IsClosed) {
_safeKeyHandle.Dispose();
_safeKeyHandle = null;
}
RSACspObject rsaCspObject = RSAStructToObject(parameters);
_safeKeyHandle = SafeKeyHandle.InvalidHandle;
if (IsPublic(parameters)) {
// Use our CRYPT_VERIFYCONTEXT handle, CRYPT_EXPORTABLE is not applicable to public only keys, so pass false
Utils._ImportKey(Utils.StaticProvHandle, Constants.CALG_RSA_KEYX, (CspProviderFlags) 0, rsaCspObject, ref _safeKeyHandle);
} else {
if (!CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) {
KeyContainerPermission kp = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags);
KeyContainerPermissionAccessEntry entry = new KeyContainerPermissionAccessEntry(_parameters, KeyContainerPermissionFlags.Import);
kp.AccessEntries.Add(entry);
kp.Demand();
}
if (_safeProvHandle == null)
_safeProvHandle = Utils.CreateProvHandle(_parameters, _randomKeyContainer);
// Now, import the key into the CSP; _ImportKey will check for failures.
Utils._ImportKey(_safeProvHandle, Constants.CALG_RSA_KEYX, _parameters.Flags, rsaCspObject, ref _safeKeyHandle);
}
}
#if FEATURE_LEGACYNETCFCRYPTO
[System.Security.SecurityCritical]
#else
[System.Security.SecuritySafeCritical] // auto-generated
#endif
[System.Runtime.InteropServices.ComVisible(false)]
public void ImportCspBlob (byte[] keyBlob) {
Utils.ImportCspBlobHelper(CspAlgorithmType.Rsa, keyBlob, IsPublic(keyBlob), ref _parameters, _randomKeyContainer, ref _safeProvHandle, ref _safeKeyHandle);
}
public byte[] SignData(Stream inputStream, Object halg) {
int calgHash = Utils.ObjToAlgId(halg, OidGroup.HashAlgorithm);
HashAlgorithm hash = Utils.ObjToHashAlgorithm(halg);
byte[] hashVal = hash.ComputeHash(inputStream);
return SignHash(hashVal, calgHash);
}
public byte[] SignData(byte[] buffer, Object halg) {
int calgHash = Utils.ObjToAlgId(halg, OidGroup.HashAlgorithm);
HashAlgorithm hash = Utils.ObjToHashAlgorithm(halg);
byte[] hashVal = hash.ComputeHash(buffer);
return SignHash(hashVal, calgHash);
}
public byte[] SignData(byte[] buffer, int offset, int count, Object halg) {
int calgHash = Utils.ObjToAlgId(halg, OidGroup.HashAlgorithm);
HashAlgorithm hash = Utils.ObjToHashAlgorithm(halg);
byte[] hashVal = hash.ComputeHash(buffer, offset, count);
return SignHash(hashVal, calgHash);
}
public bool VerifyData(byte[] buffer, Object halg, byte[] signature) {
int calgHash = Utils.ObjToAlgId(halg, OidGroup.HashAlgorithm);
HashAlgorithm hash = Utils.ObjToHashAlgorithm(halg);
byte[] hashVal = hash.ComputeHash(buffer);
return VerifyHash(hashVal, calgHash, signature);
}
public byte[] SignHash(byte[] rgbHash, string str) {
if (rgbHash == null)
throw new ArgumentNullException("rgbHash");
Contract.EndContractBlock();
if (PublicOnly)
throw new CryptographicException(Environment.GetResourceString("Cryptography_CSP_NoPrivateKey"));
int calgHash = X509Utils.NameOrOidToAlgId(str, OidGroup.HashAlgorithm);
return SignHash(rgbHash, calgHash);
}
[SecuritySafeCritical]
internal byte[] SignHash(byte[] rgbHash, int calgHash) {
Contract.Requires(rgbHash != null);
GetKeyPair();
if (!CspKeyContainerInfo.RandomlyGenerated) {
if (!CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) {
KeyContainerPermission kp = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags);
KeyContainerPermissionAccessEntry entry = new KeyContainerPermissionAccessEntry(_parameters, KeyContainerPermissionFlags.Sign);
kp.AccessEntries.Add(entry);
kp.Demand();
}
}
return Utils.SignValue(_safeKeyHandle, _parameters.KeyNumber, Constants.CALG_RSA_SIGN, calgHash, rgbHash);
}
public bool VerifyHash(byte[] rgbHash, string str, byte[] rgbSignature) {
if (rgbHash == null)
throw new ArgumentNullException("rgbHash");
if (rgbSignature == null)
throw new ArgumentNullException("rgbSignature");
Contract.EndContractBlock();
int calgHash = X509Utils.NameOrOidToAlgId(str, OidGroup.HashAlgorithm);
return VerifyHash(rgbHash, calgHash, rgbSignature);
}
[SecuritySafeCritical]
internal bool VerifyHash(byte[] rgbHash, int calgHash, byte[] rgbSignature) {
Contract.Requires(rgbHash != null);
Contract.Requires(rgbSignature != null);
GetKeyPair();
return Utils.VerifySign(_safeKeyHandle, Constants.CALG_RSA_SIGN, calgHash, rgbHash, rgbSignature);
}
/// <summary>
/// Encrypt raw data, generally used for encrypting symmetric key material.
/// </summary>
/// <remarks>
/// This method can only encrypt (keySize - 88 bits) of data, so should not be used for encrypting
/// arbitrary byte arrays. Instead, encrypt a symmetric key with this method, and use the symmetric
/// key to encrypt the sensitive data.
/// </remarks>
/// <param name="rgb">raw data to encryt</param>
/// <param name="fOAEP">true to use OAEP padding (PKCS #1 v2), false to use PKCS #1 type 2 padding</param>
/// <returns>Encrypted key</returns>
[System.Security.SecuritySafeCritical] // auto-generated
public byte[] Encrypt(byte[] rgb, bool fOAEP) {
if (rgb == null)
throw new ArgumentNullException("rgb");
Contract.EndContractBlock();
GetKeyPair();
byte[] encryptedKey = null;
EncryptKey(_safeKeyHandle, rgb, rgb.Length, fOAEP, JitHelpers.GetObjectHandleOnStack(ref encryptedKey));
return encryptedKey;
}
/// <summary>
/// Decrypt raw data, generally used for decrypting symmetric key material
/// </summary>
/// <param name="rgb">encrypted data</param>
/// <param name="fOAEP">true to use OAEP padding (PKCS #1 v2), false to use PKCS #1 type 2 padding</param>
/// <returns>decrypted data</returns>
[System.Security.SecuritySafeCritical] // auto-generated
public byte [] Decrypt(byte[] rgb, bool fOAEP) {
if (rgb == null)
throw new ArgumentNullException("rgb");
Contract.EndContractBlock();
GetKeyPair();
// size check -- must be at most the modulus size
if (rgb.Length > (KeySize / 8))
throw new CryptographicException(Environment.GetResourceString("Cryptography_Padding_DecDataTooBig", KeySize / 8));
if (!CspKeyContainerInfo.RandomlyGenerated) {
if (!CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) {
KeyContainerPermission kp = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags);
KeyContainerPermissionAccessEntry entry = new KeyContainerPermissionAccessEntry(_parameters, KeyContainerPermissionFlags.Decrypt);
kp.AccessEntries.Add(entry);
kp.Demand();
}
}
byte[] decryptedKey = null;
DecryptKey(_safeKeyHandle, rgb, rgb.Length, fOAEP, JitHelpers.GetObjectHandleOnStack(ref decryptedKey));
return decryptedKey;
}
public override byte[] DecryptValue(byte[] rgb) {
throw new NotSupportedException(Environment.GetResourceString("NotSupported_Method"));
}
public override byte[] EncryptValue(byte[] rgb) {
throw new NotSupportedException(Environment.GetResourceString("NotSupported_Method"));
}
//
// private static methods
//
private static RSAParameters RSAObjectToStruct (RSACspObject rsaCspObject) {
RSAParameters rsaParams = new RSAParameters();
rsaParams.Exponent = rsaCspObject.Exponent;
rsaParams.Modulus = rsaCspObject.Modulus;
rsaParams.P = rsaCspObject.P;
rsaParams.Q = rsaCspObject.Q;
rsaParams.DP = rsaCspObject.DP;
rsaParams.DQ = rsaCspObject.DQ;
rsaParams.InverseQ = rsaCspObject.InverseQ;
rsaParams.D = rsaCspObject.D;
return rsaParams;
}
private static RSACspObject RSAStructToObject (RSAParameters rsaParams) {
RSACspObject rsaCspObject = new RSACspObject();
rsaCspObject.Exponent = rsaParams.Exponent;
rsaCspObject.Modulus = rsaParams.Modulus;
rsaCspObject.P = rsaParams.P;
rsaCspObject.Q = rsaParams.Q;
rsaCspObject.DP = rsaParams.DP;
rsaCspObject.DQ = rsaParams.DQ;
rsaCspObject.InverseQ = rsaParams.InverseQ;
rsaCspObject.D = rsaParams.D;
return rsaCspObject;
}
// find whether an RSA key blob is public.
private static bool IsPublic (byte[] keyBlob) {
if (keyBlob == null)
throw new ArgumentNullException("keyBlob");
Contract.EndContractBlock();
// The CAPI RSA public key representation consists of the following sequence:
// - BLOBHEADER
// - RSAPUBKEY
// The first should be PUBLICKEYBLOB and magic should be RSA_PUB_MAGIC "RSA1"
if (keyBlob[0] != Constants.PUBLICKEYBLOB)
return false;
if (keyBlob[11] != 0x31 || keyBlob[10] != 0x41 || keyBlob[9] != 0x53 || keyBlob[8] != 0x52)
return false;
return true;
}
// Since P is required, we will assume its presence is synonymous to a private key.
private static bool IsPublic(RSAParameters rsaParams) {
return (rsaParams.P == null);
}
#if !FEATURE_CORECLR
//
// Adapt new RSA abstraction to legacy RSACryptoServiceProvider surface area.
//
// NOTE: For the new API, we go straight to CAPI for fixed set of hash algorithms and don't use crypto config here.
//
// Reasons:
// 1. We're moving away from crypto config and we won't have it when porting to .NET Core
//
// 2. It's slow to lookup and slow to use as the base HashAlgorithm adds considerable overhead
// (redundant defensive copy + double-initialization for the single-use case).
//
[SecuritySafeCritical]
protected override byte[] HashData(byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm) {
// we're sealed and the base should have checked this already
Contract.Assert(data != null);
Contract.Assert(offset >= 0 && offset <= data.Length);
Contract.Assert(count >= 0 && count <= data.Length);
Contract.Assert(!String.IsNullOrEmpty(hashAlgorithm.Name));
using (SafeHashHandle hashHandle = Utils.CreateHash(Utils.StaticProvHandle, GetAlgorithmId(hashAlgorithm))) {
Utils.HashData(hashHandle, data, offset, count);
return Utils.EndHash(hashHandle);
}
}
[SecuritySafeCritical]
protected override byte[] HashData(Stream data, HashAlgorithmName hashAlgorithm) {
// we're sealed and the base should have checked this already
Contract.Assert(data != null);
Contract.Assert(!String.IsNullOrEmpty(hashAlgorithm.Name));
using (SafeHashHandle hashHandle = Utils.CreateHash(Utils.StaticProvHandle, GetAlgorithmId(hashAlgorithm))) {
// Read the data 4KB at a time, providing similar read characteristics to a standard HashAlgorithm
byte[] buffer = new byte[4096];
int bytesRead = 0;
do {
bytesRead = data.Read(buffer, 0, buffer.Length);
if (bytesRead > 0) {
Utils.HashData(hashHandle, buffer, 0, bytesRead);
}
} while (bytesRead > 0);
return Utils.EndHash(hashHandle);
}
}
private static int GetAlgorithmId(HashAlgorithmName hashAlgorithm) {
switch (hashAlgorithm.Name) {
case "MD5":
return Constants.CALG_MD5;
case "SHA1":
return Constants.CALG_SHA1;
case "SHA256":
return Constants.CALG_SHA_256;
case "SHA384":
return Constants.CALG_SHA_384;
case "SHA512":
return Constants.CALG_SHA_512;
default:
throw new CryptographicException(Environment.GetResourceString("Cryptography_UnknownHashAlgorithm", hashAlgorithm.Name));
}
}
public override byte[] Encrypt(byte[] data, RSAEncryptionPadding padding) {
if (data == null) {
throw new ArgumentNullException("data");
}
if (padding == null) {
throw new ArgumentNullException("padding");
}
if (padding == RSAEncryptionPadding.Pkcs1) {
return Encrypt(data, fOAEP: false);
} else if (padding == RSAEncryptionPadding.OaepSHA1) {
return Encrypt(data, fOAEP: true);
} else {
throw PaddingModeNotSupported();
}
}
public override byte[] Decrypt(byte[] data, RSAEncryptionPadding padding) {
if (data == null) {
throw new ArgumentNullException("data");
}
if (padding == null) {
throw new ArgumentNullException("padding");
}
if (padding == RSAEncryptionPadding.Pkcs1) {
return Decrypt(data, fOAEP: false);
} else if (padding == RSAEncryptionPadding.OaepSHA1) {
return Decrypt(data, fOAEP: true);
} else {
throw PaddingModeNotSupported();
}
}
public override byte[] SignHash(byte[] hash, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) {
if (hash == null) {
throw new ArgumentNullException("hash");
}
if (String.IsNullOrEmpty(hashAlgorithm.Name)) {
throw HashAlgorithmNameNullOrEmpty();
}
if (padding == null) {
throw new ArgumentNullException("padding");
}
if (padding != RSASignaturePadding.Pkcs1) {
throw PaddingModeNotSupported();
}
return SignHash(hash, GetAlgorithmId(hashAlgorithm));
}
public override bool VerifyHash(byte[] hash, byte[] signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) {
if (hash == null) {
throw new ArgumentNullException("hash");
}
if (signature == null) {
throw new ArgumentNullException("signature");
}
if (String.IsNullOrEmpty(hashAlgorithm.Name)) {
throw HashAlgorithmNameNullOrEmpty();
}
if (padding == null) {
throw new ArgumentNullException("padding");
}
if (padding != RSASignaturePadding.Pkcs1) {
throw PaddingModeNotSupported();
}
return VerifyHash(hash, GetAlgorithmId(hashAlgorithm), signature);
}
private static Exception PaddingModeNotSupported() {
return new CryptographicException(Environment.GetResourceString("Cryptography_InvalidPaddingMode"));
}
#endif
}
}
| |
using System;
using System.Globalization;
using MetroFramework.Drawing.Html.Core.Parse;
using MetroFramework.Drawing.Html.Core.Utils;
namespace MetroFramework.Drawing.Html.Core.Dom
{
/// <summary>
/// Represents and gets info about a CSS Length
/// </summary>
/// <remarks>
/// http://www.w3.org/TR/CSS21/syndata.html#length-units
/// </remarks>
internal sealed class CssLength
{
#region Fields
private readonly double _number;
private readonly bool _isRelative;
private readonly CssUnit _unit;
private readonly string _length;
private readonly bool _isPercentage;
private readonly bool _hasError;
#endregion
/// <summary>
/// Creates a new CssLength from a length specified on a CSS style sheet or fragment
/// </summary>
/// <param name="length">Length as specified in the Style Sheet or style fragment</param>
public CssLength(string length)
{
_length = length;
_number = 0f;
_unit = CssUnit.None;
_isPercentage = false;
//Return zero if no length specified, zero specified
if (string.IsNullOrEmpty(length) || length == "0")
return;
//If percentage, use ParseNumber
if (length.EndsWith("%"))
{
_number = CssValueParser.ParseNumber(length, 1);
_isPercentage = true;
return;
}
//If no units, has error
if (length.Length < 3)
{
double.TryParse(length, out _number);
_hasError = true;
return;
}
//Get units of the length
string u = length.Substring(length.Length - 2, 2);
//Number of the length
string number = length.Substring(0, length.Length - 2);
//TODO: Units behave different in paper and in screen!
switch (u)
{
case CssConstants.Em:
_unit = CssUnit.Ems;
_isRelative = true;
break;
case CssConstants.Ex:
_unit = CssUnit.Ex;
_isRelative = true;
break;
case CssConstants.Px:
_unit = CssUnit.Pixels;
_isRelative = true;
break;
case CssConstants.Mm:
_unit = CssUnit.Milimeters;
break;
case CssConstants.Cm:
_unit = CssUnit.Centimeters;
break;
case CssConstants.In:
_unit = CssUnit.Inches;
break;
case CssConstants.Pt:
_unit = CssUnit.Points;
break;
case CssConstants.Pc:
_unit = CssUnit.Picas;
break;
default:
_hasError = true;
return;
}
if (!double.TryParse(number, NumberStyles.Number, NumberFormatInfo.InvariantInfo, out _number))
{
_hasError = true;
}
}
#region Props
/// <summary>
/// Gets the number in the length
/// </summary>
public double Number
{
get { return _number; }
}
/// <summary>
/// Gets if the length has some parsing error
/// </summary>
public bool HasError
{
get { return _hasError; }
}
/// <summary>
/// Gets if the length represents a precentage (not actually a length)
/// </summary>
public bool IsPercentage
{
get { return _isPercentage; }
}
/// <summary>
/// Gets if the length is specified in relative units
/// </summary>
public bool IsRelative
{
get { return _isRelative; }
}
/// <summary>
/// Gets the unit of the length
/// </summary>
public CssUnit Unit
{
get { return _unit; }
}
/// <summary>
/// Gets the length as specified in the string
/// </summary>
public string Length
{
get { return _length; }
}
#endregion
#region Methods
/// <summary>
/// If length is in Ems, returns its value in points
/// </summary>
/// <param name="emSize">Em size factor to multiply</param>
/// <returns>Points size of this em</returns>
/// <exception cref="InvalidOperationException">If length has an error or isn't in ems</exception>
public CssLength ConvertEmToPoints(double emSize)
{
if (HasError)
throw new InvalidOperationException("Invalid length");
if (Unit != CssUnit.Ems)
throw new InvalidOperationException("Length is not in ems");
return new CssLength(string.Format("{0}pt", Convert.ToSingle(Number * emSize).ToString("0.0", NumberFormatInfo.InvariantInfo)));
}
/// <summary>
/// If length is in Ems, returns its value in pixels
/// </summary>
/// <param name="pixelFactor">Pixel size factor to multiply</param>
/// <returns>Pixels size of this em</returns>
/// <exception cref="InvalidOperationException">If length has an error or isn't in ems</exception>
public CssLength ConvertEmToPixels(double pixelFactor)
{
if (HasError)
throw new InvalidOperationException("Invalid length");
if (Unit != CssUnit.Ems)
throw new InvalidOperationException("Length is not in ems");
return new CssLength(string.Format("{0}px", Convert.ToSingle(Number * pixelFactor).ToString("0.0", NumberFormatInfo.InvariantInfo)));
}
/// <summary>
/// Returns the length formatted ready for CSS interpreting.
/// </summary>
/// <returns></returns>
public override string ToString()
{
if (HasError)
{
return string.Empty;
}
else if (IsPercentage)
{
return string.Format(NumberFormatInfo.InvariantInfo, "{0}%", Number);
}
else
{
string u = string.Empty;
switch (Unit)
{
case CssUnit.None:
break;
case CssUnit.Ems:
u = "em";
break;
case CssUnit.Pixels:
u = "px";
break;
case CssUnit.Ex:
u = "ex";
break;
case CssUnit.Inches:
u = "in";
break;
case CssUnit.Centimeters:
u = "cm";
break;
case CssUnit.Milimeters:
u = "mm";
break;
case CssUnit.Points:
u = "pt";
break;
case CssUnit.Picas:
u = "pc";
break;
}
return string.Format(NumberFormatInfo.InvariantInfo, "{0}{1}", Number, u);
}
}
#endregion
}
}
| |
/*
* MindTouch DekiWiki - a commercial grade open source wiki
* Copyright (C) 2006 MindTouch, Inc.
* www.mindtouch.com oss@mindtouch.com
*
* For community documentation and downloads visit www.opengarden.org;
* please review the licensing section.
*
* 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.
* http://www.gnu.org/copyleft/gpl.html
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using System.Web;
using MindTouch.Dream;
namespace MindTouch.Deki {
using HttpPostedFile = MindTouch.Dream.Http.HttpPostedFile;
[DreamService("MindTouch Dream Wiki API", "Copyright (c) 2006 MindTouch, Inc.", "https://tech.mindtouch.com/Product/Dream/Service_WikiAPI")]
public class WikiApiService : DekiWikiServiceBase {
//--- Class Fields ---
private static log4net.ILog _log = LogUtils.CreateLog<WikiApiService>();
//--- Methods ---
/// <summary>
/// functional
/// </summary>
/// <param name="context"></param>
[DreamFeature("users", "/", "GET", "List of users", "https://tech.mindtouch.com/Product/Dream/Service_Wiki-API")]
public DreamMessage GetUsersHandler(DreamContext context, DreamMessage message) {
//DekiContext deki = new DekiContext(message, this.DekiConfig);
//if (!deki.Authenticate()) { //Max: Commented out to allow compilation
// return DreamMessage.AccessDenied("DekiWiki", "Authorization Required");
//}
XDoc ret = new XDoc("users");
foreach (user cur in user.GetUsers())
AddUser(cur, ret);
return DreamMessage.Ok(ret);
}
/// <summary>
/// mode=raw functional
/// </summary>
/// <param name="context"></param>
[DreamFeature("page", "//*", "GET",
"Input: " +
"suffixes == page name, " +
"optional query/mode [raw|view|print|edit|export|meta] (default: raw), " +
"optional query/output [json|xml|html] (default: xml), " +
"optional query/history, " +
"HTTP basic authentication. " +
"Output: page content. " +
"Comments: Retrieve the page content of the given page and version in the given format", "https://tech.mindtouch.com/Product/Dream/Service_Wiki-API")]
public DreamMessage GetPageHandler(DreamContext context, DreamMessage message) {
page cur = null;//deki.GetCur(true); Max: commented out to allow compilation
if (cur == null)
return DreamMessage.BadRequest("can't load page");
string mode = context.Uri.GetParam("mode", "raw").ToLowerInvariant();
switch (mode) {
case "raw":
return DreamMessage.Ok(MimeType.HTML, cur.Text);
case "xml":
string xml = string.Format(DekiWikiService.XHTML_LOOSE, cur.Text);
XDoc result = XDoc.FromXml(xml);
return DreamMessage.Ok(MimeType.XHTML, result.ToXHtml());
case "export":
case "edit":
case "print":
case "view":
return DreamMessage.Ok(MimeType.HTML, /*deki.Render(cur.Text, mode) Max:Removed to allow compilation*/ "" );
}
return DreamMessage.NotImplemented(string.Format("'mode={0}' is not supported"));
}
/// <summary>
/// functional
/// </summary>
/// <summary>
/// usage:
/// http://localhost:8081/wiki-api/nav/Home?max-level=100
/// http://localhost:8081/wiki-api/nav/Project_A?max-level=4&column=id&column=children&column=name
/// </summary>
/// <param name="context"></param>
[DreamFeature("nav", "//*", "GET", "Input: suffixes == page name, " +
"optional query/max-level (default: 1), " +
"optional query/column[] (default: [name, id, TIP, modified, user]), " +
"HTTP basic authentication. " +
"Output: info doc. " +
"Comment: get navigation tree given page context and columns", "https://tech.mindtouch.com/Product/Dream/Service_Wiki-API")]
public DreamMessage GetNavHandler(DreamContext context, DreamMessage message) {
DekiContext deki = null; // new DekiContext(message, this.DekiConfig);
page cur = null; // deki.GetCur(true); Max: Commented out to allow compilation
if (cur == null)
return DreamMessage.BadRequest("can't load page");
int maxLevel = context.Uri.GetParam<int>("max-level", 1);
bool filterRedirects = context.Uri.GetParam<bool>("redirects", true);
ICollection<string> columns = context.Uri.GetParams("column");
string filter = filterRedirects ? " AND page_is_redirect=0" : "";
XDoc ret = new XDoc("nav");
AddCur(deki, cur, ret, columns, filter, maxLevel);
return DreamMessage.Ok(ret);
}
/// <summary>
/// functional
/// </summary>
/// <param name="context"></param>
[DreamFeature("list", "//*", "GET", "Input: suffixes == page name[/filename], query/column[] [files|images|children|siblings|history], optional query/column[] (default: [name, id, TIP, modified, user]), HTTP basic authentication. Output: info doc", "https://tech.mindtouch.com/Product/Dream/Service_Wiki-API")]
public DreamMessage GetListHandler(DreamContext context, DreamMessage message) {
/* Max: Commented out to allow compilation
DekiContext deki = new DekiContext(context, message, this.DekiConfig);
cur cur = deki.GetCur(false);
if (cur == null)
return DreamMessage.BadRequest("can't load page");
if(cur.Namespace == NS.ATTACHMENT) {
attachments attachment = deki.GetAttachment();
if (attachment == null)
return DreamMessage.BadRequest("can't load attachment");
XDoc file = new XDoc("file");
AddFile(attachment, file, false);
return DreamMessage.Ok(file);
}
bool filterRedirects = context.Uri.GetParamAsBool("redirects", true);
ICollection<string> columns = context.Uri.GetParams("column");
string filter = filterRedirects ? " AND page_is_redirect=0" : "";
XDoc page = new XDoc("page");
AddCur(deki, cur, page, columns, filter, 1, true, false);
return DreamMessage.Ok(page);
*/
throw new NotImplementedException();
}
#region -- Implementation --
static void AddUser(user user, XDoc doc) {
doc.Start("user")
.Attr("id", user.ID.ToString())
.Start("name").Value(user.Name).End()
.Start("real-name").Value(user.RealName).End()
.Start("email").Value(user.Email).End()
.Start("touched").Value(user.Touched).End()
.End();
}
void AddCur(DekiContext deki, page cur, XDoc doc, ICollection<string> columns, string filter, int level) {
AddCur(deki, cur, doc, columns, filter, level, false, true);
}
void AddCur(DekiContext deki, page cur, XDoc doc, ICollection<string> columns, string filter, int level, bool flat, bool addWrap) {
if (level < 0)
return;
if (addWrap)
doc.Start("page");
doc.Attr("cur-id", cur.ID.ToString());
if (columns.Count == 0 || columns.Contains("parent"))
doc.Start("parent").Value(cur.ParentID).End();
if (columns.Count == 0 || columns.Contains("name"))
doc.Start("name").Value(cur.PrefixedName).End();
if (columns.Count == 0 || columns.Contains("modified"))
doc.Start("modified").Value(cur.TimeStamp).End();
if (columns.Count == 0 || columns.Contains("comment"))
doc.Start("comment").Value(cur.Comment).End();
if (columns.Count == 0 || columns.Contains("preview"))
doc.Start("preview").Value(cur.TIP).End();
if (columns.Count == 0 || columns.Contains("table-of-contents"))
doc.Start("table-of-contents").Value(cur.TOC).End();
if (columns.Count == 0 || columns.Contains("is-redirect"))
doc.Start("is-redirect").Value(cur.IsRedirect.ToString()).End();
if (columns.Count == 0 || columns.Contains("from-links"))
AddCurIDList(cur.GetLinkIDsFrom(), "from-links", doc);
if (columns.Count == 0 || columns.Contains("to-links"))
AddCurIDList(cur.GetLinkIDsTo(), "to-links", doc);
if (columns.Count == 0 || columns.Contains("files")) {
doc.Start("files");
foreach (attachments attachment in cur.GetAttachments())
AddFile(attachment, doc);
doc.End();
}
if (level < 1) {
if (addWrap)
doc.End();
return;
}
if (columns.Count == 0 || columns.Contains("children")) {
if (flat)
AddCurIDList(cur.GetChildIDs(filter), "children", doc);
else {
doc.Start("children");
foreach (page child in cur.LoadChildren(filter))
AddCur(deki, child, doc, columns, filter, level - 1);
doc.End();
}
}
if (addWrap)
doc.End();
}
static void AddCurIDList(ICollection<ulong> list, string tag, XDoc doc) {
doc.Start(tag);
foreach (ulong ID in list)
doc.Start("id").Value(ID).End();
doc.End();
}
static void AddCurIDList(ICollection<page> list, string tag, XDoc doc) {
doc.Start(tag);
foreach (page link in list)
doc.Start("id").Value(link.ID).End();
doc.End();
}
static void AddFile(attachments attachment, XDoc doc) {
AddFile(attachment, doc, true);
}
static void AddFile(attachments attachment, XDoc doc, bool wrap) {
if (wrap)
doc.Start("file");
doc
.Attr("id", attachment.ID.ToString())
.Attr("page", attachment.From.ToString())
.Start("full-name").Value(attachment.GetFullName()).End()
.Start("name").Value(attachment.Name).End()
.Start("extension").Value(attachment.Extension).End()
.Start("filename").Value(attachment.FileName).End()
.Start("description").Value(attachment.Description).End()
.Start("size").Value(attachment.FileSize.ToString()).End()
.Start("type").Value(attachment.FileType).End()
.Start("timestamp").Value(attachment.TimeStamp).End()
.Start("user").Value(attachment.UserText).End();
if (attachment.Removed != DateTime.MinValue) {
doc.Start("removed").Value(attachment.Removed).End()
.Start("removed-by").Value(attachment.RemovedByText).End();
}
if (wrap)
doc.End();
}
#endregion
}
public enum MKS_STAT {
EDIT_FULL = 0,
EDIT_SECTION = 1,
EDIT_CANCEL = 2,
EDIT_QUICK_SAVE = 3,
EDIT_SAVE = 4,
BREADCRUMB = 5,
NAV_PARENT = 6,
NAV_SIBLING = 7,
NAV_CHILD = 8,
NAV_NEXT = 9,
NAV_PREVIOUS = 10,
CONTENT = 11,
BACKLINK = 12,
PRINT = 13,
SAVE_HTML = 14,
SAVE_PDF = 15,
PRINT_CANCEL = 16,
UPLOAD_FILE = 17,
UPLOAD_SIZE = 18,
REVISION = 19,
MENU_WHATS_NEW = 20,
MENU_CP = 21,
CP_ADD_USER = 22,
CP_DEACTIVATE_USER = 23,
CP_REINSTALL = 24,
CP_RESTART = 25,
CP_SHUTDOWN = 26,
CP_SUPPORT_ADDED = 27,
CP_BACKUP_SETTINGS = 28,
CP_CREATE_BACKUP = 29,
CP_RESTORE_BACKUP = 30,
CP_CRLNK_ADDED = 31,
CP_CRLNK_CHANGED = 32,
CP_CRLNK_DELETED = 33,
MENU_SHOW_USERS = 34,
MENU_ALL_PAGES = 35,
MENU_POPULAR_PAGES = 36,
MENU_WANTED_PAGES = 37,
MENU_ORPHANED_PAGES = 38,
MENU_DOUBLE_REDIRECTS = 39,
MY_PREFERENCES = 40,
MY_CONTRIBUTIONS = 41,
MY_WATCHLIST = 42,
CREATE_SUB_PAGE = 43,
PAGE_RENAMED = 44,
MENU_WATCH_PAGE = 45,
MENU_UNWATCH_PAGE = 46,
VIEWS = 47,
EDIT_CONFLICT = 48,
DELETE_PAGE = 49,
PASSWORD_CHANGED = 50,
MENU_LOGIN = 51,
MENU_LOGOUT = 52,
TOP_MY_PAGE = 53,
TOP_HOME = 54,
TOP_COMMUNITY = 55,
TOP_EVENTS = 56,
TOP_HELP = 57,
EDIT_PREVIEW = 58,
PREVIEW_SHOW_TOC = 59,
PREVIEW_SHOW_FOOTER = 60,
PREVIEW_SHOW_LINK_ENDNOTES = 61,
EDITOR_ADVANCED = 62,
RESPONSE_COUNT = 63,
RESPONSE_TIME_MIN = 64,
RESPONSE_TIME_MAX = 65,
RESPONSE_TIME_SUM = 66,
RESPONSE_TIME_STD_DEV = 67,
RESPONSE_SIZE_MIN = 68,
RESPONSE_SIZE_MAX = 69,
MENU_DELETE = 70,
RESPONSE_SIZE_SUM = 71,
RESPONSE_SIZE_STD_DEV = 72,
NAV_CURRENT = 73,
TOP_CUSTOM = 74,
TOC = 75,
UPLOAD_FAILED = 76,
NEW_PAGE = 77,
COMPARE_REVISION = 78,
VIEW_PAGE_AT_GIVEN_REVISION = 79,
PREVIEW_HIDE_TOC = 80,
PREVIEW_HIDE_FOOTER = 81,
PREVIEW_HIDE_LINK_ENDNOTES = 82,
EDITOR_SIMPLE = 83,
CP_AUTO_LOGIN_ON = 84,
CP_AUTO_LOGIN_OFF = 85,
CP_ANONYMOUS_VIEWING_ON = 86,
CP_ANONYMOUS_VIEWING_OFF = 87,
CP_HTTP_AUTHENTICATION_ON = 88,
CP_HTTP_AUTHENTICATION_OFF = 89,
MENU_PRINT = 90,
NET_COLLISIONS = 91,
NET_PACKETS_SENT = 92,
NET_PACKETS_RECEIVED = 93,
NET_BYTES_SENT = 94,
NET_BYTES_RECEIVED = 95,
}
}
| |
#region Copyright and License
// Copyright 2010..2017 Alexander Reinert
//
// This file is part of the ARSoft.Tools.Net - C# DNS client/server and SPF Library (http://arsofttoolsnet.codeplex.com/)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
using Org.BouncyCastle.Crypto.Prng;
using Org.BouncyCastle.Security;
namespace ARSoft.Tools.Net.Dns
{
public abstract class DnsClientBase
{
private static readonly SecureRandom _secureRandom = new SecureRandom(new CryptoApiRandomGenerator());
private readonly List<IPAddress> _servers;
private readonly bool _isAnyServerMulticast;
private readonly int _port;
internal DnsClientBase(IEnumerable<IPAddress> servers, int queryTimeout, int port)
{
_servers = servers.OrderBy(s => s.AddressFamily == AddressFamily.InterNetworkV6 ? 0 : 1).ToList();
_isAnyServerMulticast = _servers.Any(s => s.IsMulticast());
QueryTimeout = queryTimeout;
_port = port;
}
/// <summary>
/// Milliseconds after which a query times out.
/// </summary>
public int QueryTimeout { get; }
/// <summary>
/// Gets or set a value indicating whether the response is validated as described in
/// <see
/// cref="!:http://tools.ietf.org/id/draft-vixie-dnsext-dns0x20-00.txt">
/// draft-vixie-dnsext-dns0x20-00
/// </see>
/// </summary>
public bool IsResponseValidationEnabled { get; set; }
/// <summary>
/// Gets or set a value indicating whether the query labels are used for additional validation as described in
/// <see
/// cref="!:http://tools.ietf.org/id/draft-vixie-dnsext-dns0x20-00.txt">
/// draft-vixie-dnsext-dns0x20-00
/// </see>
/// </summary>
// ReSharper disable once InconsistentNaming
public bool Is0x20ValidationEnabled { get; set; }
protected abstract int MaximumQueryMessageSize { get; }
protected virtual bool IsUdpEnabled { get; set; }
protected virtual bool IsTcpEnabled { get; set; }
#if !NETSTANDARD
protected TMessage SendMessage<TMessage>(TMessage message)
where TMessage : DnsMessageBase, new()
{
int messageLength;
byte[] messageData;
DnsServer.SelectTsigKey tsigKeySelector;
byte[] tsigOriginalMac;
PrepareMessage(message, out messageLength, out messageData, out tsigKeySelector, out tsigOriginalMac);
bool sendByTcp = ((messageLength > MaximumQueryMessageSize) || message.IsTcpUsingRequested || !IsUdpEnabled);
var endpointInfos = GetEndpointInfos();
for (int i = 0; i < endpointInfos.Count; i++)
{
TcpClient tcpClient = null;
NetworkStream tcpStream = null;
try
{
var endpointInfo = endpointInfos[i];
IPAddress responderAddress;
byte[] resultData = sendByTcp ? QueryByTcp(endpointInfo.ServerAddress, messageData, messageLength, ref tcpClient, ref tcpStream, out responderAddress) : QueryByUdp(endpointInfo, messageData, messageLength, out responderAddress);
if (resultData != null)
{
TMessage result;
try
{
result = DnsMessageBase.Parse<TMessage>(resultData, tsigKeySelector, tsigOriginalMac);
}
catch (Exception e)
{
Trace.TraceError("Error on dns query: " + e);
continue;
}
if (!ValidateResponse(message, result))
continue;
if ((result.ReturnCode == ReturnCode.ServerFailure) && (i != endpointInfos.Count - 1))
{
continue;
}
if (result.IsTcpResendingRequested)
{
resultData = QueryByTcp(responderAddress, messageData, messageLength, ref tcpClient, ref tcpStream, out responderAddress);
if (resultData != null)
{
TMessage tcpResult;
try
{
tcpResult = DnsMessageBase.Parse<TMessage>(resultData, tsigKeySelector, tsigOriginalMac);
}
catch (Exception e)
{
Trace.TraceError("Error on dns query: " + e);
continue;
}
if (tcpResult.ReturnCode == ReturnCode.ServerFailure)
{
if (i != endpointInfos.Count - 1)
{
continue;
}
}
else
{
result = tcpResult;
}
}
}
bool isTcpNextMessageWaiting = result.IsTcpNextMessageWaiting(false);
bool isSucessfullFinished = true;
while (isTcpNextMessageWaiting)
{
resultData = QueryByTcp(responderAddress, null, 0, ref tcpClient, ref tcpStream, out responderAddress);
if (resultData != null)
{
TMessage tcpResult;
try
{
tcpResult = DnsMessageBase.Parse<TMessage>(resultData, tsigKeySelector, tsigOriginalMac);
}
catch (Exception e)
{
Trace.TraceError("Error on dns query: " + e);
isSucessfullFinished = false;
break;
}
if (tcpResult.ReturnCode == ReturnCode.ServerFailure)
{
isSucessfullFinished = false;
break;
}
else
{
result.AnswerRecords.AddRange(tcpResult.AnswerRecords);
isTcpNextMessageWaiting = tcpResult.IsTcpNextMessageWaiting(true);
}
}
else
{
isSucessfullFinished = false;
break;
}
}
if (isSucessfullFinished)
return result;
}
}
finally
{
try
{
tcpStream?.Dispose();
tcpClient?.Close();
}
catch
{
// ignored
}
}
}
return null;
}
#endif
protected List<TMessage> SendMessageParallel<TMessage>(TMessage message)
where TMessage : DnsMessageBase, new()
{
Task<List<TMessage>> result = SendMessageParallelAsync(message, default(CancellationToken));
result.Wait();
return result.Result;
}
private bool ValidateResponse<TMessage>(TMessage message, TMessage result)
where TMessage : DnsMessageBase
{
if (IsResponseValidationEnabled)
{
if ((result.ReturnCode == ReturnCode.NoError) || (result.ReturnCode == ReturnCode.NxDomain))
{
if (message.TransactionID != result.TransactionID)
return false;
if ((message.Questions == null) || (result.Questions == null))
return false;
if ((message.Questions.Count != result.Questions.Count))
return false;
for (int j = 0; j < message.Questions.Count; j++)
{
DnsQuestion queryQuestion = message.Questions[j];
DnsQuestion responseQuestion = result.Questions[j];
if ((queryQuestion.RecordClass != responseQuestion.RecordClass)
|| (queryQuestion.RecordType != responseQuestion.RecordType)
|| (!queryQuestion.Name.Equals(responseQuestion.Name, false)))
{
return false;
}
}
}
}
return true;
}
private void PrepareMessage<TMessage>(TMessage message, out int messageLength, out byte[] messageData, out DnsServer.SelectTsigKey tsigKeySelector, out byte[] tsigOriginalMac)
where TMessage : DnsMessageBase, new()
{
if (message.TransactionID == 0)
{
message.TransactionID = (ushort) _secureRandom.Next(1, 0xffff);
}
if (Is0x20ValidationEnabled)
{
message.Questions.ForEach(q => q.Name = q.Name.Add0x20Bits());
}
messageLength = message.Encode(false, out messageData);
if (message.TSigOptions != null)
{
tsigKeySelector = (n, a) => message.TSigOptions.KeyData;
tsigOriginalMac = message.TSigOptions.Mac;
}
else
{
tsigKeySelector = null;
tsigOriginalMac = null;
}
}
private byte[] QueryByUdp(DnsClientEndpointInfo endpointInfo, byte[] messageData, int messageLength, out IPAddress responderAddress)
{
using (var udpClient = new Socket(endpointInfo.LocalAddress.AddressFamily, SocketType.Dgram, ProtocolType.Udp))
{
try
{
udpClient.ReceiveTimeout = QueryTimeout;
PrepareAndBindUdpSocket(endpointInfo, udpClient);
EndPoint serverEndpoint = new IPEndPoint(endpointInfo.ServerAddress, _port);
udpClient.SendTo(messageData, messageLength, SocketFlags.None, serverEndpoint);
if (endpointInfo.IsMulticast)
serverEndpoint = new IPEndPoint(udpClient.AddressFamily == AddressFamily.InterNetwork ? IPAddress.Any : IPAddress.IPv6Any, _port);
byte[] buffer = new byte[65535];
int length = udpClient.ReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref serverEndpoint);
responderAddress = ((IPEndPoint) serverEndpoint).Address;
byte[] res = new byte[length];
Buffer.BlockCopy(buffer, 0, res, 0, length);
return res;
}
catch (Exception e)
{
Trace.TraceError("Error on dns query: " + e);
responderAddress = default(IPAddress);
return null;
}
}
}
private void PrepareAndBindUdpSocket(DnsClientEndpointInfo endpointInfo, Socket udpClient)
{
if (endpointInfo.IsMulticast)
{
udpClient.Bind(new IPEndPoint(endpointInfo.LocalAddress, 0));
}
else
{
udpClient.Connect(endpointInfo.ServerAddress, _port);
}
}
#if !NETSTANDARD
private byte[] QueryByTcp(IPAddress nameServer, byte[] messageData, int messageLength, ref TcpClient tcpClient, ref NetworkStream tcpStream, out IPAddress responderAddress)
{
responderAddress = nameServer;
if (!IsTcpEnabled)
return null;
IPEndPoint endPoint = new IPEndPoint(nameServer, _port);
try
{
if (tcpClient == null)
{
tcpClient = new TcpClient(nameServer.AddressFamily)
{
ReceiveTimeout = QueryTimeout,
SendTimeout = QueryTimeout
};
if (!tcpClient.TryConnect(endPoint, QueryTimeout))
return null;
tcpStream = tcpClient.GetStream();
}
int tmp = 0;
byte[] lengthBuffer = new byte[2];
if (messageLength > 0)
{
DnsMessageBase.EncodeUShort(lengthBuffer, ref tmp, (ushort) messageLength);
tcpStream.Write(lengthBuffer, 0, 2);
tcpStream.Write(messageData, 0, messageLength);
}
if (!TryRead(tcpClient, tcpStream, lengthBuffer, 2))
return null;
tmp = 0;
int length = DnsMessageBase.ParseUShort(lengthBuffer, ref tmp);
byte[] resultData = new byte[length];
return TryRead(tcpClient, tcpStream, resultData, length) ? resultData : null;
}
catch (Exception e)
{
Trace.TraceError("Error on dns query: " + e);
return null;
}
}
#endif
private bool TryRead(TcpClient client, NetworkStream stream, byte[] buffer, int length)
{
int readBytes = 0;
while (readBytes < length)
{
if (!client.IsConnected())
return false;
readBytes += stream.Read(buffer, readBytes, length - readBytes);
}
return true;
}
protected async Task<TMessage> SendMessageAsync<TMessage>(TMessage message, CancellationToken token)
where TMessage : DnsMessageBase, new()
{
int messageLength;
byte[] messageData;
DnsServer.SelectTsigKey tsigKeySelector;
byte[] tsigOriginalMac;
PrepareMessage(message, out messageLength, out messageData, out tsigKeySelector, out tsigOriginalMac);
bool sendByTcp = ((messageLength > MaximumQueryMessageSize) || message.IsTcpUsingRequested || !IsUdpEnabled);
var endpointInfos = GetEndpointInfos();
for (int i = 0; i < endpointInfos.Count; i++)
{
token.ThrowIfCancellationRequested();
var endpointInfo = endpointInfos[i];
QueryResponse resultData = null;
try
{
resultData = await (sendByTcp ? QueryByTcpAsync(endpointInfo.ServerAddress, messageData, messageLength, null, null, token) : QuerySingleResponseByUdpAsync(endpointInfo, messageData, messageLength, token));
if (resultData == null)
return null;
TMessage result;
try
{
result = DnsMessageBase.Parse<TMessage>(resultData.Buffer, tsigKeySelector, tsigOriginalMac);
}
catch (Exception e)
{
Trace.TraceError("Error on dns query: " + e);
continue;
}
if (!ValidateResponse(message, result))
continue;
if ((result.ReturnCode != ReturnCode.NoError) && (result.ReturnCode != ReturnCode.NxDomain) && (i != endpointInfos.Count - 1))
continue;
if (result.IsTcpResendingRequested)
{
resultData = await QueryByTcpAsync(resultData.ResponderAddress, messageData, messageLength, resultData.TcpClient, resultData.TcpStream, token);
if (resultData != null)
{
TMessage tcpResult;
try
{
tcpResult = DnsMessageBase.Parse<TMessage>(resultData.Buffer, tsigKeySelector, tsigOriginalMac);
}
catch (Exception e)
{
Trace.TraceError("Error on dns query: " + e);
return null;
}
if (tcpResult.ReturnCode == ReturnCode.ServerFailure)
{
return result;
}
else
{
result = tcpResult;
}
}
}
bool isTcpNextMessageWaiting = result.IsTcpNextMessageWaiting(false);
bool isSucessfullFinished = true;
while (isTcpNextMessageWaiting)
{
// ReSharper disable once PossibleNullReferenceException
resultData = await QueryByTcpAsync(resultData.ResponderAddress, null, 0, resultData.TcpClient, resultData.TcpStream, token);
if (resultData != null)
{
TMessage tcpResult;
try
{
tcpResult = DnsMessageBase.Parse<TMessage>(resultData.Buffer, tsigKeySelector, tsigOriginalMac);
}
catch (Exception e)
{
Trace.TraceError("Error on dns query: " + e);
isSucessfullFinished = false;
break;
}
if (tcpResult.ReturnCode == ReturnCode.ServerFailure)
{
isSucessfullFinished = false;
break;
}
else
{
result.AnswerRecords.AddRange(tcpResult.AnswerRecords);
isTcpNextMessageWaiting = tcpResult.IsTcpNextMessageWaiting(true);
}
}
else
{
isSucessfullFinished = false;
break;
}
}
if (isSucessfullFinished)
return result;
}
finally
{
if (resultData != null)
{
try
{
resultData.TcpStream?.Dispose();
#if !NETSTANDARD
resultData.TcpClient?.Close();
#endif
}
catch
{
// ignored
}
}
}
}
return null;
}
private async Task<QueryResponse> QuerySingleResponseByUdpAsync(DnsClientEndpointInfo endpointInfo, byte[] messageData, int messageLength, CancellationToken token)
{
try
{
if (endpointInfo.IsMulticast)
{
using (UdpClient udpClient = new UdpClient(new IPEndPoint(endpointInfo.LocalAddress, 0)))
{
IPEndPoint serverEndpoint = new IPEndPoint(endpointInfo.ServerAddress, _port);
await udpClient.SendAsync(messageData, messageLength, serverEndpoint);
udpClient.Client.SendTimeout = QueryTimeout;
udpClient.Client.ReceiveTimeout = QueryTimeout;
UdpReceiveResult response = await udpClient.ReceiveAsync(QueryTimeout, token);
return new QueryResponse(response.Buffer, response.RemoteEndPoint.Address);
}
}
else
{
using (UdpClient udpClient = new UdpClient(endpointInfo.LocalAddress.AddressFamily))
{
#if !NETSTANDARD
udpClient.Connect(endpointInfo.ServerAddress, _port);
#endif
udpClient.Client.SendTimeout = QueryTimeout;
udpClient.Client.ReceiveTimeout = QueryTimeout;
#if NETSTANDARD
await udpClient.SendAsync(messageData, messageLength, new IPEndPoint(endpointInfo.ServerAddress, _port));
#else
await udpClient.SendAsync(messageData, messageLength);
#endif
UdpReceiveResult response = await udpClient.ReceiveAsync(QueryTimeout, token);
return new QueryResponse(response.Buffer, response.RemoteEndPoint.Address);
}
}
}
catch (Exception e)
{
Trace.TraceError("Error on dns query: " + e);
return null;
}
}
private class QueryResponse
{
public byte[] Buffer { get; }
public IPAddress ResponderAddress { get; }
public TcpClient TcpClient { get; }
public NetworkStream TcpStream { get; }
public QueryResponse(byte[] buffer, IPAddress responderAddress)
{
Buffer = buffer;
ResponderAddress = responderAddress;
}
public QueryResponse(byte[] buffer, IPAddress responderAddress, TcpClient tcpClient, NetworkStream tcpStream)
{
Buffer = buffer;
ResponderAddress = responderAddress;
TcpClient = tcpClient;
TcpStream = tcpStream;
}
}
private async Task<QueryResponse> QueryByTcpAsync(IPAddress nameServer, byte[] messageData, int messageLength, TcpClient tcpClient, NetworkStream tcpStream, CancellationToken token)
{
if (!IsTcpEnabled)
return null;
try
{
if (tcpClient == null)
{
tcpClient = new TcpClient(nameServer.AddressFamily)
{
ReceiveTimeout = QueryTimeout,
SendTimeout = QueryTimeout
};
if (!await tcpClient.TryConnectAsync(nameServer, _port, QueryTimeout, token))
{
return null;
}
tcpStream = tcpClient.GetStream();
}
int tmp = 0;
byte[] lengthBuffer = new byte[2];
if (messageLength > 0)
{
DnsMessageBase.EncodeUShort(lengthBuffer, ref tmp, (ushort) messageLength);
await tcpStream.WriteAsync(lengthBuffer, 0, 2, token);
await tcpStream.WriteAsync(messageData, 0, messageLength, token);
}
if (!await TryReadAsync(tcpClient, tcpStream, lengthBuffer, 2, token))
return null;
tmp = 0;
int length = DnsMessageBase.ParseUShort(lengthBuffer, ref tmp);
byte[] resultData = new byte[length];
return await TryReadAsync(tcpClient, tcpStream, resultData, length, token) ? new QueryResponse(resultData, nameServer, tcpClient, tcpStream) : null;
}
catch (Exception e)
{
Trace.TraceError("Error on dns query: " + e);
return null;
}
}
private async Task<bool> TryReadAsync(TcpClient client, NetworkStream stream, byte[] buffer, int length, CancellationToken token)
{
int readBytes = 0;
while (readBytes < length)
{
if (token.IsCancellationRequested || !client.IsConnected())
return false;
readBytes += await stream.ReadAsync(buffer, readBytes, length - readBytes, token);
}
return true;
}
protected async Task<List<TMessage>> SendMessageParallelAsync<TMessage>(TMessage message, CancellationToken token)
where TMessage : DnsMessageBase, new()
{
int messageLength;
byte[] messageData;
DnsServer.SelectTsigKey tsigKeySelector;
byte[] tsigOriginalMac;
PrepareMessage(message, out messageLength, out messageData, out tsigKeySelector, out tsigOriginalMac);
if (messageLength > MaximumQueryMessageSize)
throw new ArgumentException("Message exceeds maximum size");
if (message.IsTcpUsingRequested)
throw new NotSupportedException("Using tcp is not supported in parallel mode");
BlockingCollection<TMessage> results = new BlockingCollection<TMessage>();
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
// ReSharper disable once ReturnValueOfPureMethodIsNotUsed
GetEndpointInfos().Select(x => SendMessageParallelAsync(x, message, messageData, messageLength, tsigKeySelector, tsigOriginalMac, results, CancellationTokenSource.CreateLinkedTokenSource(token, cancellationTokenSource.Token).Token)).ToArray();
await Task.Delay(QueryTimeout, token);
cancellationTokenSource.Cancel();
return results.ToList();
}
private async Task SendMessageParallelAsync<TMessage>(DnsClientEndpointInfo endpointInfo, TMessage message, byte[] messageData, int messageLength, DnsServer.SelectTsigKey tsigKeySelector, byte[] tsigOriginalMac, BlockingCollection<TMessage> results, CancellationToken token)
where TMessage : DnsMessageBase, new()
{
using (UdpClient udpClient = new UdpClient(new IPEndPoint(endpointInfo.LocalAddress, 0)))
{
IPEndPoint serverEndpoint = new IPEndPoint(endpointInfo.ServerAddress, _port);
await udpClient.SendAsync(messageData, messageLength, serverEndpoint);
udpClient.Client.SendTimeout = QueryTimeout;
udpClient.Client.ReceiveTimeout = QueryTimeout;
while (true)
{
TMessage result;
UdpReceiveResult response = await udpClient.ReceiveAsync(Int32.MaxValue, token);
try
{
result = DnsMessageBase.Parse<TMessage>(response.Buffer, tsigKeySelector, tsigOriginalMac);
}
catch (Exception e)
{
Trace.TraceError("Error on dns query: " + e);
continue;
}
if (!ValidateResponse(message, result))
continue;
if (result.ReturnCode == ReturnCode.ServerFailure)
continue;
results.Add(result, token);
if (token.IsCancellationRequested)
break;
}
}
}
private List<DnsClientEndpointInfo> GetEndpointInfos()
{
List<DnsClientEndpointInfo> endpointInfos;
if (_isAnyServerMulticast)
{
var localIPs = NetworkInterface.GetAllNetworkInterfaces()
.Where(n => n.SupportsMulticast && (n.OperationalStatus == OperationalStatus.Up) && (n.NetworkInterfaceType != NetworkInterfaceType.Loopback))
.SelectMany(n => n.GetIPProperties().UnicastAddresses.Select(a => a.Address))
.Where(a => !IPAddress.IsLoopback(a) && ((a.AddressFamily == AddressFamily.InterNetwork) || a.IsIPv6LinkLocal))
.ToList();
endpointInfos = _servers
.SelectMany(
s =>
{
if (s.IsMulticast())
{
return localIPs
.Where(l => l.AddressFamily == s.AddressFamily)
.Select(
l => new DnsClientEndpointInfo
{
IsMulticast = true,
ServerAddress = s,
LocalAddress = l
});
}
else
{
return new[]
{
new DnsClientEndpointInfo
{
IsMulticast = false,
ServerAddress = s,
LocalAddress = s.AddressFamily == AddressFamily.InterNetwork ? IPAddress.Any : IPAddress.IPv6Any
}
};
}
}).ToList();
}
else
{
endpointInfos = _servers
.Where(x => IsIPv6Enabled || (x.AddressFamily == AddressFamily.InterNetwork))
.Select(
s => new DnsClientEndpointInfo
{
IsMulticast = false,
ServerAddress = s,
LocalAddress = s.AddressFamily == AddressFamily.InterNetwork ? IPAddress.Any : IPAddress.IPv6Any
}
).ToList();
}
return endpointInfos;
}
private static bool IsIPv6Enabled { get; } = IsAnyIPv6Configured();
private static readonly IPAddress _ipvMappedNetworkAddress = IPAddress.Parse("0:0:0:0:0:FFFF::");
private static bool IsAnyIPv6Configured()
{
return NetworkInterface.GetAllNetworkInterfaces()
.Where(n => (n.OperationalStatus == OperationalStatus.Up) && (n.NetworkInterfaceType != NetworkInterfaceType.Loopback))
.SelectMany(n => n.GetIPProperties().UnicastAddresses.Select(a => a.Address))
.Any(a => !IPAddress.IsLoopback(a) && (a.AddressFamily == AddressFamily.InterNetworkV6) && !a.IsIPv6LinkLocal && !a.IsIPv6Teredo && !a.GetNetworkAddress(96).Equals(_ipvMappedNetworkAddress));
}
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.WebApiCompatShim;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Azure.WebJobs.Host.Executors;
using Microsoft.Azure.WebJobs.Script.WebHost.Authentication;
using Microsoft.Azure.WebJobs.Script.WebHost.Filters;
using Microsoft.Azure.WebJobs.Script.WebHost.Management;
using Microsoft.Azure.WebJobs.Script.WebHost.Models;
using Microsoft.Azure.WebJobs.Script.WebHost.Security;
using Microsoft.Azure.WebJobs.Script.WebHost.Security.Authorization;
using Microsoft.Azure.WebJobs.Script.WebHost.Security.Authorization.Policies;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using HttpHandler = Microsoft.Azure.WebJobs.IAsyncConverter<System.Net.Http.HttpRequestMessage, System.Net.Http.HttpResponseMessage>;
namespace Microsoft.Azure.WebJobs.Script.WebHost.Controllers
{
/// <summary>
/// Controller responsible for handling all administrative requests for host operations
/// example host status, ping, log, etc
/// </summary>
public class HostController : Controller
{
private readonly IOptions<ScriptApplicationHostOptions> _applicationHostOptions;
private readonly IOptions<JobHostOptions> _hostOptions;
private readonly ILogger _logger;
private readonly IAuthorizationService _authorizationService;
private readonly IWebFunctionsManager _functionsManager;
private readonly IEnvironment _environment;
private readonly IScriptHostManager _scriptHostManager;
private readonly IFunctionsSyncManager _functionsSyncManager;
public HostController(IOptions<ScriptApplicationHostOptions> applicationHostOptions,
IOptions<JobHostOptions> hostOptions,
ILoggerFactory loggerFactory,
IAuthorizationService authorizationService,
IWebFunctionsManager functionsManager,
IEnvironment environment,
IScriptHostManager scriptHostManager,
IFunctionsSyncManager functionsSyncManager)
{
_applicationHostOptions = applicationHostOptions;
_hostOptions = hostOptions;
_logger = loggerFactory.CreateLogger(ScriptConstants.LogCategoryHostController);
_authorizationService = authorizationService;
_functionsManager = functionsManager;
_environment = environment;
_scriptHostManager = scriptHostManager;
_functionsSyncManager = functionsSyncManager;
}
[HttpGet]
[Route("admin/host/status")]
[Authorize(Policy = PolicyNames.AdminAuthLevelOrInternal)]
[TypeFilter(typeof(EnableDebugModeFilter))]
public async Task<IActionResult> GetHostStatus([FromServices] IScriptHostManager scriptHostManager, [FromServices] IHostIdProvider hostIdProvider)
{
var status = new HostStatus
{
State = scriptHostManager.State.ToString(),
Version = ScriptHost.Version,
VersionDetails = Utility.GetInformationalVersion(typeof(ScriptHost)),
Id = await hostIdProvider.GetHostIdAsync(CancellationToken.None),
ProcessUptime = (long)(DateTime.UtcNow - Process.GetCurrentProcess().StartTime).TotalMilliseconds
};
var lastError = scriptHostManager.LastError;
if (lastError != null)
{
status.Errors = new Collection<string>();
status.Errors.Add(Utility.FlattenException(lastError));
}
string message = $"Host Status: {JsonConvert.SerializeObject(status, Formatting.Indented)}";
_logger.LogInformation(message);
return Ok(status);
}
[HttpGet]
[HttpPost]
[Route("admin/host/ping")]
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
public IActionResult Ping([FromServices] IScriptHostManager scriptHostManager)
{
var pingStatus = new JObject
{
{ "hostState", scriptHostManager.State.ToString() }
};
string message = $"Ping Status: {pingStatus.ToString()}";
_logger.Log(LogLevel.Debug, new EventId(0, "PingStatus"), message);
return Ok();
}
[HttpPost]
[Route("admin/host/log")]
[Authorize(Policy = PolicyNames.AdminAuthLevelOrInternal)]
public IActionResult Log([FromBody]IEnumerable<HostLogEntry> logEntries)
{
if (logEntries == null)
{
return BadRequest("An array of log entry objects is expected.");
}
foreach (var logEntry in logEntries)
{
var traceEvent = new TraceEvent(logEntry.Level, logEntry.Message, logEntry.Source);
if (!string.IsNullOrEmpty(logEntry.FunctionName))
{
traceEvent.Properties.Add(ScriptConstants.LogPropertyFunctionNameKey, logEntry.FunctionName);
}
var logLevel = Utility.ToLogLevel(traceEvent.Level);
var logData = new Dictionary<string, object>
{
[ScriptConstants.LogPropertySourceKey] = logEntry.Source,
[ScriptConstants.LogPropertyFunctionNameKey] = logEntry.FunctionName
};
_logger.Log(logLevel, 0, logData, null, (s, e) => logEntry.Message);
}
return Ok();
}
[HttpPost]
[Route("admin/host/debug")]
[Authorize(Policy = PolicyNames.AdminAuthLevel)]
[TypeFilter(typeof(EnableDebugModeFilter))]
public IActionResult LaunchDebugger()
{
if (_applicationHostOptions.Value.IsSelfHost)
{
// If debugger is already running, this will be a no-op returning true.
if (Debugger.Launch())
{
return Ok();
}
else
{
return StatusCode(StatusCodes.Status409Conflict);
}
}
return StatusCode(StatusCodes.Status501NotImplemented);
}
[HttpPost]
[Route("admin/host/synctriggers")]
[Authorize(Policy = PolicyNames.AdminAuthLevelOrInternal)]
public async Task<IActionResult> SyncTriggers()
{
var result = await _functionsSyncManager.TrySyncTriggersAsync();
// Return a dummy body to make it valid in ARM template action evaluation
return result.Success
? Ok(new { status = "success" })
: StatusCode(StatusCodes.Status500InternalServerError, new { status = result.Error });
}
[HttpPost]
[Route("admin/host/restart")]
[Authorize(Policy = PolicyNames.AdminAuthLevel)]
public IActionResult Restart([FromServices] IScriptHostManager hostManager)
{
Task ignore = hostManager.RestartHostAsync();
return Ok(_applicationHostOptions.Value);
}
/// <summary>
/// Currently this endpoint only supports taking the host offline and bringing it back online.
/// </summary>
/// <param name="state">The desired host state. See <see cref="ScriptHostState"/>.</param>
[HttpPut]
[Route("admin/host/state")]
[Authorize(Policy = PolicyNames.AdminAuthLevel)]
public async Task<IActionResult> SetState([FromBody] string state)
{
if (!Enum.TryParse<ScriptHostState>(state, ignoreCase: true, out ScriptHostState desiredState) ||
!(desiredState == ScriptHostState.Offline || desiredState == ScriptHostState.Running))
{
// currently we only allow states Offline and Running
return BadRequest();
}
var currentState = _scriptHostManager.State;
if (desiredState == currentState)
{
return Ok();
}
else if (desiredState == ScriptHostState.Running && currentState == ScriptHostState.Offline)
{
if (_environment.FileSystemIsReadOnly())
{
return BadRequest();
}
// we're currently offline and the request is to bring the host back online
await FileMonitoringService.SetAppOfflineState(_applicationHostOptions.Value.ScriptPath, false);
}
else if (desiredState == ScriptHostState.Offline && currentState != ScriptHostState.Offline)
{
if (_environment.FileSystemIsReadOnly())
{
return BadRequest();
}
// we're currently online and the request is to take the host offline
await FileMonitoringService.SetAppOfflineState(_applicationHostOptions.Value.ScriptPath, true);
}
else
{
return BadRequest();
}
return Accepted();
}
/// <summary>
/// This endpoint generates a temporary x-ms-site-restricted-token for core tool
/// to access KuduLite zipdeploy endpoint in Linux Consumption
/// </summary>
/// <returns>
/// 200 on token generated
/// 400 on non-Linux container environment
/// </returns>
[HttpGet]
[Route("admin/host/token")]
[Authorize(Policy = PolicyNames.AdminAuthLevel)]
public IActionResult GetAdminToken()
{
if (!_environment.IsLinuxContainerEnvironment())
{
return BadRequest("Endpoint is only available when running in Linux Container");
}
string requestHeaderToken = SimpleWebTokenHelper.CreateToken(DateTime.UtcNow.AddMinutes(5));
return Ok(requestHeaderToken);
}
[AcceptVerbs("GET", "POST", "DELETE")]
[Authorize(AuthenticationSchemes = AuthLevelAuthenticationDefaults.AuthenticationScheme)]
[Route("runtime/webhooks/{name}/{*extra}")]
[RequiresRunningHost]
public async Task<IActionResult> ExtensionWebHookHandler(string name, CancellationToken token, [FromServices] IScriptWebHookProvider provider)
{
if (provider.TryGetHandler(name, out HttpHandler handler))
{
// must either be authorized at the admin level, or system level with
// a matching key name
string keyName = DefaultScriptWebHookProvider.GetKeyName(name);
if (!AuthUtility.PrincipalHasAuthLevelClaim(User, AuthorizationLevel.System, keyName))
{
return Unauthorized();
}
var requestMessage = new HttpRequestMessageFeature(this.HttpContext).HttpRequestMessage;
HttpResponseMessage response = await handler.ConvertAsync(requestMessage, token);
var result = new ObjectResult(response);
result.Formatters.Add(new HttpResponseMessageOutputFormatter());
return result;
}
return NotFound();
}
}
}
| |
using System;
using System.IO;
using NUnit.Framework;
using TheFactory.Datastore;
using System.Text;
using System.Collections.Generic;
using Splat;
using TheFactory.FileSystem;
namespace TheFactory.DatastoreTests {
public class BenchmarkArgs {
public BenchmarkArgs() {
}
// write key/value pairs sequentially
public bool Seq = true;
// number of key/value pairs to write
public int Count = 100000;
// key/value entries per batch
public int EntriesPerBatch = 1;
public int ValueLen = 100;
}
// benchmark / scale tests for datastore
[TestFixture, Explicit]
public class BenchmarkTests {
String tmpDir;
[SetUp]
public void setUp() {
tmpDir = Path.Combine(Path.GetTempPath(), "benchmark" + Utils.RandomString(4));
Directory.CreateDirectory(tmpDir);
}
[TearDown]
public void tearDown() {
Directory.Delete(tmpDir, true);
tmpDir = null;
}
void RunBenchmark(String name, BenchmarkArgs args) {
var db = Database.Open(tmpDir) as Database;
var stats = new Stats();
stats.Start();
DoWrite(db, args, stats);
stats.Finish();
Console.WriteLine(Header(name, args) + stats.Report(name));
}
public String Header(String name, BenchmarkArgs args) {
var buf = new StringWriter();
buf.Write("{0} args:\n", name);
buf.Write("Keys: {0} bytes each. sequential: {1}\n", 16, args.Seq);
buf.Write("Values: {0} bytes each\n", args.ValueLen);
buf.Write("Entries: {0}. batches of {1}\n", args.Count, args.EntriesPerBatch);
buf.Write("-------------------------------------------------------------------\n");
return buf.ToString();
}
[Test]
public void DbFillSeq() {
var args = new BenchmarkArgs();
RunBenchmark("DbFillSeq", args);
}
[Test]
public void DbFillRandom() {
var args = new BenchmarkArgs();
args.Seq = false;
RunBenchmark("DbFillRandom", args);
}
[Test]
public void DbFindAll() {
var name = "DbFindAll";
var args = new BenchmarkArgs();
// fill the database but throw away the writing stats
var db = Database.Open(tmpDir) as Database;
DoWrite(db, args, new Stats());
var stats = new Stats();
stats.Start();
foreach (var kv in db.Find(Slice.Empty)) {
stats.AddBytes(kv.Key.Length + kv.Value.Length);
stats.FinishedSingleOp();
}
stats.Finish();
Report(name, args, stats);
}
[Test]
public void DbReadSeq() {
var name = "DbReadSeq";
var args = new BenchmarkArgs();
// fill the database but throw away the writing stats
var db = Database.Open(tmpDir) as Database;
DoWrite(db, args, new Stats());
var stats = new Stats();
stats.Start();
DoRead(db, args, stats);
stats.Finish();
Report(name, args, stats);
}
[Test]
public void DbReadRandom() {
var name = "DbReadRandom";
var args = new BenchmarkArgs();
// fill the database but throw away the writing stats
var db = Database.Open(tmpDir) as Database;
DoWrite(db, args, new Stats());
var stats = new Stats();
stats.Start();
DoRead(db, args, stats);
stats.Finish();
Report(name, args, stats);
}
[Test]
public void TabletFillSeq() {
var name = "TabletFillSeq";
var args = new BenchmarkArgs();
var filename = Path.Combine(tmpDir, "tablet.tab");
var stats = new Stats();
stats.Start();
WriteTablet(filename, StatsWrapper(KVStream(args), stats), new TabletWriterOptions());
stats.Finish();
Report(name, args, stats);
}
public void WriteTablet(string filename, IEnumerable<IKeyValuePair> kvs, TabletWriterOptions opts) {
var writer = new TabletWriter();
using (var output = new BinaryWriter(File.OpenWrite(filename))) {
writer.WriteTablet(output, kvs, opts);
}
}
[Test]
public void TabletFindAll() {
var name = "TabletFindAll";
var args = new BenchmarkArgs();
var filename = Path.Combine(tmpDir, "tablet.tab");
WriteTablet(filename, KVStream(args), new TabletWriterOptions());
var reader = new FileTablet(filename, new TabletReaderOptions());
var stats = new Stats();
stats.Start();
foreach (var kv in StatsWrapper(reader.Find(Slice.Empty), stats)) {
// nop: StatsWrapper is tracking our work
}
stats.Finish();
Report(name, args, stats);
}
[Test]
public void TabletReadSeq() {
var name = "TabletReadSeq";
var args = new BenchmarkArgs();
args.Count = 10000; // single-key tablet read is slow for now
var filename = Path.Combine(tmpDir, "tablet.tab");
WriteTablet(filename, KVStream(args), new TabletWriterOptions());
var reader = new FileTablet(filename, new TabletReaderOptions());
var stats = new Stats();
stats.Start();
DoRead(reader, args, stats);
stats.Finish();
Report(name, args, stats);
}
[Test]
public void TabletReadRandom() {
var name = "TabletReadRandom";
var args = new BenchmarkArgs();
args.Count = 10000; // single-key tablet read is slow for now
var filename = Path.Combine(tmpDir, "tablet.tab");
WriteTablet(filename, KVStream(args), new TabletWriterOptions());
var reader = new FileTablet(filename, new TabletReaderOptions());
var stats = new Stats();
// read keys in random order
args.Seq = false;
stats.Start();
DoRead(reader, args, stats);
stats.Finish();
Report(name, args, stats);
}
[Test]
public void ReplayTransactionLog() {
var name = "ReplayTransactionLog";
var args = new BenchmarkArgs();
var options = new Options();
using (var db = (Database)Database.Open(tmpDir)) {
DoWrite(db, args, new Stats());
}
// manually replay the transaction log for stats gathering
var path = Path.Combine(tmpDir, "write.log");
var tablet = new MemoryTablet();
var stats = new Stats();
stats.Start();
using (var stream = Locator.Current.GetService<IFileSystem>().GetStream(path, TheFactory.FileSystem.FileMode.Open, TheFactory.FileSystem.FileAccess.Read))
using (var log = new TransactionLogReader(stream)) {
foreach (var transaction in log.Transactions()) {
tablet.Apply(new Batch(transaction));
stats.AddBytes(transaction.Length);
stats.FinishedSingleOp();
}
}
stats.Finish();
Report(name, args, stats);
}
public void Report(string name, BenchmarkArgs args, Stats stats) {
Console.WriteLine(Header(name, args) + stats.Report(name));
}
public IEnumerable<IKeyValuePair> StatsWrapper(IEnumerable<IKeyValuePair> kvs, Stats stats) {
long bytes = 0;
foreach (var kv in kvs) {
yield return kv;
bytes += kv.Key.Length + kv.Value.Length;
stats.FinishedSingleOp();
}
stats.AddBytes(bytes);
yield break;
}
public IEnumerable<IKeyValuePair> KVStream(BenchmarkArgs args) {
var rand = new Random();
var enc = new ASCIIEncoding();
Pair pair = new Pair();
for (int i=0; i<args.Count; i++) {
int k = args.Seq ? i : rand.Next(args.Count);
var key = enc.GetBytes(String.Format("{0:d16}", k));
var val = enc.GetBytes(Utils.RandomString(args.ValueLen));
pair.Key = (Slice)key;
pair.Value = (Slice)val;
yield return pair;
}
yield break;
}
public void DoWrite(Database db, BenchmarkArgs args, Stats stats) {
var batch = new Batch();
stats.AddMessage(String.Format("({0:d} ops)", args.Count));
var kvs = KVStream(args).GetEnumerator();
long bytes = 0;
for (int i=0; i<args.Count; i += args.EntriesPerBatch) {
batch.Clear();
for (int j=0; j<args.EntriesPerBatch; j++) {
if (!kvs.MoveNext()) {
Assert.Fail("Unexpected short iterator in DoWrite");
}
var key = kvs.Current.Key;
var val = kvs.Current.Value;
batch.Put(key, val);
bytes += key.Length + val.Length;
stats.FinishedSingleOp();
}
db.Apply(batch);
}
stats.AddBytes(bytes);
}
private void DoRead(Database db, BenchmarkArgs args, Stats stats) {
Random rand = new Random();
for (int i = 0; i < args.Count; i++) {
int num = args.Seq ? i : rand.Next(args.Count);
var key = String.Format("{0:d16}", num);
try {
var val = db.Get(key);
stats.AddBytes(val.Length);
} catch (KeyNotFoundException) {
}
stats.FinishedSingleOp();
}
}
private void DoRead(ITablet tab, BenchmarkArgs args, Stats stats) {
var enc = new ASCIIEncoding();
Random rand = new Random();
long bytes = 0;
for (int i = 0; i < args.Count; i++) {
int num = args.Seq ? i : rand.Next(args.Count);
var keyStr = String.Format("{0:d16}", num);
var key = (Slice)enc.GetBytes(keyStr);
var iter = tab.Find(key).GetEnumerator();
iter.MoveNext();
bytes += iter.Current.Value.Length;
stats.FinishedSingleOp();
}
stats.AddBytes(bytes);
}
}
}
| |
/*Copyright 2015 Esri
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.?*/
using System;
using System.IO;
using System.Windows.Forms;
using System.Text;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using ESRI.ArcGIS.JTX;
using ESRI.ArcGIS.JTX.Utilities;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geoprocessing;
#if (!SERVER)
using ESRI.ArcGIS.GeoprocessingUI;
#endif
namespace JTXSamples
{
[Guid("76F3BC8F-7941-46b9-94F9-0856A6E86E87")]
public class ExecuteGPTool : IJTXCustomStep
{
internal const string ARG_TOOLBOXPATH = "toolboxpath";
internal const string ARG_TOOL = "tool";
internal const string ARG_PARAM = "param";
internal const string ARG_ATTACH = "attach";
#region Registration Code
[ComRegisterFunction()]
static void Reg(String regKey)
{
ESRI.ArcGIS.JTX.Utilities.JTXUtilities.RegisterJTXCustomStep(regKey);
}
[ComUnregisterFunction()]
static void Unreg(String regKey)
{
ESRI.ArcGIS.JTX.Utilities.JTXUtilities.UnregisterJTXCustomStep(regKey);
}
#endregion
////////////////////////////////////////////////////////////////////////
// DECLARE: Data Members
private readonly string[] m_expectedArgs = { ARG_TOOLBOXPATH, ARG_TOOL, ARG_PARAM, ARG_ATTACH };
private IJTXDatabase m_ipDatabase = null;
private StringBuilder m_pStrLogMessages = null;
#region IJTXCustomStep Members
/// <summary>
/// A description of the expected arguments for the step type. This should
/// include the syntax of the argument, whether or not it is required/optional,
/// and any return codes coming from the step type.
/// </summary>
public string ArgumentDescriptions
{
get
{
StringBuilder sb = new StringBuilder();
sb.AppendLine(@"Toolbox Path (explicit full path to the tbx file combined with toolbox name):");
sb.AppendFormat("\t/{0}:<{0}> (required)\r\n", ARG_TOOLBOXPATH);
sb.AppendLine(@"Display Name of the Tool in the toolbox:");
sb.AppendFormat("\t/{0}:<{0}> (required)\r\n", ARG_TOOL);
sb.AppendLine(@"Parameter to override on the tool (can be specified multiple times):");
sb.AppendFormat("\t/{0}:<ParamName>:<ParamValue> (optional)\r\n", ARG_PARAM);
sb.AppendLine(@"Flag to attach the log to the job once the tool has completed:");
sb.AppendFormat("\t/{0} (optional)\r\n", ARG_ATTACH);
return sb.ToString();
}
}
/// <summary>
/// Called when a step of this type is executed in the workflow.
/// </summary>
/// <param name="JobID">ID of the job being executed</param>
/// <param name="StepID">ID of the step being executed</param>
/// <param name="argv">Array of arguments passed into the step's execution</param>
/// <param name="ipFeedback">Feedback object to return status messages and files</param>
/// <returns>Return code of execution for workflow path traversal</returns>
public int Execute(int jobID, int stepID, ref object[] argv, ref IJTXCustomStepFeedback ipFeedback)
{
#if (!SERVER)
StatusForm sfd = null;
#endif
bool success = true;
// Reset the message logging
this.ClearCachedLogMessages();
try
{
Log("ExecuteGPTool.Execute beginning..");
// Define variables
string strToolboxPath = "";
string strTool = "";
string strToolboxRoot = "";
string strToolboxName = "";
// Get the toolbox name (check for errors)
if (!StepUtilities.GetArgument(ref argv, "toolboxpath", true, out strToolboxPath) || strToolboxPath.Equals(String.Empty))
{
success = false;
Log("Error getting 'toolboxpath' argument");
#if (!SERVER)
MessageBox.Show("Missing toolbox argument.");
#endif
}
// Get the tool name (check for errors)
else if (!StepUtilities.GetArgument(ref argv, "tool", true, out strTool) || strTool.Equals(String.Empty))
{
success = false;
Log("Error getting 'tool' argument");
#if (!SERVER)
MessageBox.Show("Missing tool argument.");
#endif
}
else
{
#if (!SERVER)
// Display status dialog
sfd = new StatusForm();
sfd.ToolName = strTool;
sfd.Show();
sfd.Refresh();
#endif
// Get directory of toolbox
strToolboxRoot = Path.GetDirectoryName(strToolboxPath);
// Get toolbox name without .tbx extension
strToolboxName = Path.GetFileNameWithoutExtension(strToolboxPath);
// Open toolbox and tool
IWorkspaceFactory pToolboxWorkspaceFactory = new ToolboxWorkspaceFactoryClass();
IToolboxWorkspace pToolboxWorkspace = pToolboxWorkspaceFactory.OpenFromFile(strToolboxRoot, 0) as IToolboxWorkspace;
IGPToolbox pGPToolbox = pToolboxWorkspace.OpenToolbox(strToolboxName);
IGPTool pGPTool = pGPToolbox.OpenTool(strTool);
Log("ExecuteGPTool.Execute successfully opened Tool " + strTool + " in Toolbox " + strToolboxPath + "..");
// Generate the arrays for parameters
IVariantArray parameters = new VarArrayClass(); // For Execute method
ESRI.ArcGIS.esriSystem.IArray pParameterArray = pGPTool.ParameterInfo; // For Validate and InvokeModal methods
// Get parameter "pairs"; "GetDoubleArguments" supports the GP-style,
// two-colon argument strings, like "/param:tool_param_name:tool_param_value"
string[] argNames;
string[] argValues;
if (StepUtilities.GetDoubleArguments(ref argv, "param", true, out argNames, out argValues))
{
// Stash away the variables that were passed in
Dictionary<string, string> argTable = new Dictionary<string, string>();
for (int i = 0; i < argNames.Length; i++)
{
string uppercaseName = argNames[i].ToUpper();
argTable[uppercaseName] = argValues[i];
}
// The GP tool's parameter list may include parameters that weren't specified in the
// JTX step arguments. So iterate through the tool's parameters, setting the values
// from the input where you can. Where no value was passed in, just skip the
// parameter and go with the default.
for (int i = 0; i < pParameterArray.Count; i++)
{
IGPParameter pGPParam = (IGPParameter)pParameterArray.get_Element(i);
IGPParameterEdit pGPParamEdit = (IGPParameterEdit)pGPParam;
string uppercaseName = pGPParam.Name.ToUpper();
// Override the default value, if something was passed in
if (argTable.ContainsKey(uppercaseName))
{
IGPDataType pGPType = pGPParam.DataType;
string strValue = argTable[uppercaseName];
pGPParamEdit.Value = pGPType.CreateValue(strValue);
Log("ExecuteGPTool.Execute Tool Parameter = " + uppercaseName + ", Value = " + strValue + "..");
}
// Always stash away the current parameter value, since we need the complete list
// for "Execute" below.
parameters.Add(pGPParam.Value);
}
}
Log("ExecuteGPTool.Execute successfully setup parameter values..");
// Initialize the geoprocessor
IGeoProcessor pGP = new GeoProcessorClass();
// Create callback object for GP messages
JTXGPCallback pCallback = new JTXGPCallback();
// Set up the geoprocessor
pGP.AddToolbox(strToolboxPath);
pGP.RegisterGeoProcessorEvents(pCallback);
Log("ExecuteGPTool.Execute created and registered GeoProcessor..");
// Create the messages object and a bool to pass to InvokeModal method
IGPMessages pGPMessages = pGPTool.Validate(pParameterArray, true, null);
IGPMessages pInvokeMessages = new GPMessagesClass();
string strMessage = "";
// Check for error messages
if (pGPMessages.MaxSeverity == esriGPMessageSeverity.esriGPMessageSeverityError)
{
#if (!SERVER)
// Only want to invoke a modal dialog if we're running on a workstation
// Set a reference to IGPCommandHelper2 interface
IGPToolCommandHelper2 pToolHelper = new GPToolCommandHelperClass() as IGPToolCommandHelper2;
pToolHelper.SetTool(pGPTool);
bool pOK = true;
// Open tool GUI
pToolHelper.InvokeModal(0, pParameterArray, out pOK, out pInvokeMessages);
if (pOK == true)
{
bool bFailureMessages;
strMessage = ConvertGPMessagesToString(pInvokeMessages, out bFailureMessages);
success = !bFailureMessages;
}
else
{
success = false;
}
#else
Log("ExecuteGPTool.Execute Tool Validate failed..");
// If we're running on a server, then just indicate a failure. (Someone will
// have to use the JTX application to fix the step arguments, if they can be
// fixed.)
success = false;
#endif
}
else // If there are no error messages, execute the tool
{
Log("ExecuteGPTool.Execute successfully validated parameter values, About to Execute..");
IGPMessages ipMessages = new GPMessagesClass();
try
{
pGPTool.Execute(pParameterArray, null, new GPEnvironmentManagerClass(), ipMessages);
Log("ExecuteGPTool.Execute completed call to pGPTool.Execute()");
}
catch (System.Runtime.InteropServices.COMException ex)
{
success = false;
Log("ExecuteGPTool.Execute Tool Execute failed, Message = " + ex.Message + ", DataCode = " + ex.ErrorCode + ", Data = " + ex.StackTrace);
}
// Get Messages
bool bFailureMessages = false;
strMessage += this.ConvertGPMessagesToString(ipMessages, out bFailureMessages);
Log("ExecuteGPTool.Execute got messages from tool");
Log("*** GP MESSAGES ***" + System.Environment.NewLine + strMessage + System.Environment.NewLine);
Log("*** END GP MESSAGES ***");
// If tool failed during execution, indicate a failure
if (pGP.MaxSeverity == (int)esriGPMessageSeverity.esriGPMessageSeverityError)
{
success = false;
Log("ExecuteGPTool.Execute Found Error messages from the tool..");
}
}
// Call AttachMsg
try
{
IJTXJobManager ipJobManager = m_ipDatabase.JobManager;
IJTXJob ipJob = ipJobManager.GetJob(jobID);
AttachMsg(ipJob, strTool, this.GetCachedLogMessages());
this.ClearCachedLogMessages();
}
catch (Exception ex)
{
string strEx = ex.Message;
Log("Caught exception: " + ex.Message);
}
pGP.UnRegisterGeoProcessorEvents(pCallback);
}
}
catch (Exception ex2)
{
success = false;
Log("Caught exception: " + ex2.Message);
#if (!SERVER)
string msg = "";
if (ex2.InnerException == null)
{
msg = "Inner Exception is null";
}
else
{
msg = "Inner Exception is not null";
}
MessageBox.Show("Stack Trace: " + ex2.StackTrace + Environment.NewLine + "Message: " + ex2.Message + Environment.NewLine + "Source: " + ex2.Source + Environment.NewLine + msg);
#endif
}
// Clean up
#if (!SERVER)
if (sfd != null)
{
sfd.Close();
}
#endif
// Indicate success or failure
if (success == true)
{
return 1;
}
else
{
return 0;
}
}
/// <summary>
/// Invoke an editor tool for managing custom step arguments. This is
/// an optional feature of the custom step and may not be implemented.
/// </summary>
/// <param name="hWndParent">Handle to the parent application window</param>
/// <param name="argsIn">Array of arguments already configured for this custom step</param>
/// <returns>Returns a list of newely configured arguments as specified via the editor tool</returns>
public object[] InvokeEditor(int hWndParent, object[] argsIn)
{
throw new NotImplementedException("No edit dialog available for this step type");
}
/// <summary>
/// Called when the step is instantiated in the workflow.
/// </summary>
/// <param name="ipDatabase">Database connection to the JTX repository.</param>
public void OnCreate(IJTXDatabase ipDatabase)
{
m_ipDatabase = ipDatabase;
m_pStrLogMessages = new StringBuilder();
Log("JTXTempLog: ExecuteGPTool.OnCreate Initializing logging..");
}
/// <summary>
/// Method to validate the configured arguments for the step type. The
/// logic of this method depends on the implementation of the custom step
/// but typically checks for proper argument names and syntax.
/// </summary>
/// <param name="argv">Array of arguments configured for the step type</param>
/// <returns>Returns 'true' if arguments are valid, 'false' if otherwise</returns>
public bool ValidateArguments(ref object[] argv)
{
return true;
}
#endregion
#region Helper Methods
private void AttachMsg(IJTXJob ipJob, string strTool, string strMessage)
{
// Attach the messages as a file
string strFileName = strTool + "_" + DateTime.Now.ToString("yyyyMMddHHmmss") + "_Results.log";
string strPath = Path.Combine(Environment.GetEnvironmentVariable("TEMP"), strFileName);
using (TextWriter pTextWriter = new StreamWriter(strPath))
{
pTextWriter.Write(strMessage);
pTextWriter.Close();
}
if (File.Exists(strPath))
{
try
{
Log("JTXTempLog: ExecuteGPTool.AttachMsg adding Job Attachment..");
ipJob.AddAttachment(strPath, jtxFileStorageType.jtxStoreInDB, "");
Log("JTXTempLog: ExecuteGPTool.AttachMsg added Job Attachment..");
}
catch (Exception ex)
{
String strMsg = ex.Message;
}
File.Delete(strPath);
}
}
/// <summary>
/// Helper function to log messages out tools running through this tool.
/// </summary>
/// <param name="s">The logging string to be captured.</param>
private void Log(string s)
{
string dateString = String.Format("{0:yyyy-MM-dd HH:mm:ss}", DateTime.Now);
string msgString = dateString + ": ExecuteGPTool: " + s;
m_pStrLogMessages.AppendLine(msgString);
m_ipDatabase.LogMessage(3, 1000, msgString);
}
/// <summary>
/// Retrieves the logging messages cached by this tool.
/// </summary>
/// <returns>A single string containing the messages.</returns>
private string GetCachedLogMessages()
{
return m_pStrLogMessages.ToString();
}
/// <summary>
/// Clears the logging messages captured by this tool.
/// </summary>
private void ClearCachedLogMessages()
{
m_pStrLogMessages.Remove(0, m_pStrLogMessages.Length);
}
/// <summary>
/// Takes an IGPMessages object and converts it to a nicely-formatted string.
/// </summary>
/// <param name="messages">An IGPMessages object containing one or more messages.</param>
/// <param name="bFailureMessages">Set to true if any failure messages (aborts or errors) were detected; false otherwise</param>
/// <returns>A string formatted in the GP-style message.</returns>
private string ConvertGPMessagesToString(IGPMessages messages, out bool bFailureMessages)
{
string msgsAsString = String.Empty;
StringBuilder sb = new StringBuilder();
bFailureMessages = false;
if (messages != null)
{
// Iterate through each of the messages
for (int i = 0; i < messages.Count; i++)
{
IGPMessage message = messages.GetMessage(i);
if ((message != null) && !string.IsNullOrEmpty(message.Description))
{
string strType = "";
switch (message.Type)
{
case esriGPMessageType.esriGPMessageTypeAbort:
strType = "Abort:";
bFailureMessages = true;
break;
case esriGPMessageType.esriGPMessageTypeEmpty:
strType = "Empty:";
break;
case esriGPMessageType.esriGPMessageTypeError:
strType = "Error:";
bFailureMessages = true;
break;
case esriGPMessageType.esriGPMessageTypeInformative:
strType = "Info:";
break;
case esriGPMessageType.esriGPMessageTypeProcessDefinition:
strType = "ProcessDef:";
break;
case esriGPMessageType.esriGPMessageTypeProcessStart:
strType = "ProcessStart:";
break;
case esriGPMessageType.esriGPMessageTypeProcessStop:
strType = "ProcessStop:";
break;
case esriGPMessageType.esriGPMessageTypeWarning:
strType = "Warning:";
break;
}
sb.AppendLine(strType + " " + message.Description);
}
}
}
return sb.ToString();
}
#endregion
// Private callback class
private class JTXGPCallback : IGeoProcessorEvents
{
private string m_strMessages = "";
private bool bFailureMessages = false;
public string Messages
{
get { return m_strMessages; }
}
public bool FailureMessages
{
get
{
return bFailureMessages;
}
}
#region IGeoProcessorEvents Members
public void OnMessageAdded(IGPMessage message)
{
if ((message != null) && !string.IsNullOrEmpty(message.Description))
{
string strType = "";
switch (message.Type)
{
case esriGPMessageType.esriGPMessageTypeAbort:
strType = "Abort:";
bFailureMessages = true;
break;
case esriGPMessageType.esriGPMessageTypeEmpty:
strType = "Empty:";
break;
case esriGPMessageType.esriGPMessageTypeError:
strType = "Error:";
bFailureMessages = true;
break;
case esriGPMessageType.esriGPMessageTypeInformative:
strType = "Info:";
break;
case esriGPMessageType.esriGPMessageTypeProcessDefinition:
strType = "ProcessDef:";
break;
case esriGPMessageType.esriGPMessageTypeProcessStart:
strType = "ProcessStart:";
break;
case esriGPMessageType.esriGPMessageTypeProcessStop:
strType = "ProcessStop:";
break;
case esriGPMessageType.esriGPMessageTypeWarning:
strType = "Warning:";
break;
}
m_strMessages += strType + " " + message.Description + Environment.NewLine;
}
}
public void PostToolExecute(IGPTool Tool, IArray Values, int result, IGPMessages Messages)
{
}
public void PreToolExecute(IGPTool Tool, IArray Values, int processID)
{
}
public void ToolboxChange()
{
}
#endregion
}
} // End Class
} // End Namespace
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Class: Double
**
**
** Purpose: A representation of an IEEE double precision
** floating point number.
**
**
===========================================================*/
namespace System {
using System;
using System.Globalization;
///#if GENERICS_WORK
/// using System.Numerics;
///#endif
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Diagnostics.Contracts;
[Serializable]
[StructLayout(LayoutKind.Sequential)]
[System.Runtime.InteropServices.ComVisible(true)]
#if GENERICS_WORK
public struct Double : IComparable, IFormattable, IConvertible
, IComparable<Double>, IEquatable<Double>
/// , IArithmetic<Double>
#else
public struct Double : IComparable, IFormattable, IConvertible
#endif
{
internal double m_value;
//
// Public Constants
//
public const double MinValue = -1.7976931348623157E+308;
public const double MaxValue = 1.7976931348623157E+308;
// Note Epsilon should be a double whose hex representation is 0x1
// on little endian machines.
public const double Epsilon = 4.9406564584124654E-324;
public const double NegativeInfinity = (double)-1.0 / (double)(0.0);
public const double PositiveInfinity = (double)1.0 / (double)(0.0);
public const double NaN = (double)0.0 / (double)0.0;
internal static double NegativeZero = BitConverter.Int64BitsToDouble(unchecked((long)0x8000000000000000));
[Pure]
[System.Security.SecuritySafeCritical] // auto-generated
[System.Runtime.Versioning.NonVersionable]
public unsafe static bool IsInfinity(double d) {
return (*(long*)(&d) & 0x7FFFFFFFFFFFFFFF) == 0x7FF0000000000000;
}
[Pure]
[System.Runtime.Versioning.NonVersionable]
public static bool IsPositiveInfinity(double d) {
//Jit will generate inlineable code with this
if (d == double.PositiveInfinity)
{
return true;
}
else
{
return false;
}
}
[Pure]
[System.Runtime.Versioning.NonVersionable]
public static bool IsNegativeInfinity(double d) {
//Jit will generate inlineable code with this
if (d == double.NegativeInfinity)
{
return true;
}
else
{
return false;
}
}
[Pure]
[System.Security.SecuritySafeCritical] // auto-generated
internal unsafe static bool IsNegative(double d) {
return (*(UInt64*)(&d) & 0x8000000000000000) == 0x8000000000000000;
}
[Pure]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[System.Security.SecuritySafeCritical]
[System.Runtime.Versioning.NonVersionable]
public unsafe static bool IsNaN(double d)
{
return (*(UInt64*)(&d) & 0x7FFFFFFFFFFFFFFFL) > 0x7FF0000000000000L;
}
// Compares this object to another object, returning an instance of System.Relation.
// Null is considered less than any instance.
//
// If object is not of type Double, this method throws an ArgumentException.
//
// Returns a value less than zero if this object
//
public int CompareTo(Object value) {
if (value == null) {
return 1;
}
if (value is Double) {
double d = (double)value;
if (m_value < d) return -1;
if (m_value > d) return 1;
if (m_value == d) return 0;
// At least one of the values is NaN.
if (IsNaN(m_value))
return (IsNaN(d) ? 0 : -1);
else
return 1;
}
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDouble"));
}
public int CompareTo(Double value) {
if (m_value < value) return -1;
if (m_value > value) return 1;
if (m_value == value) return 0;
// At least one of the values is NaN.
if (IsNaN(m_value))
return (IsNaN(value) ? 0 : -1);
else
return 1;
}
// True if obj is another Double with the same value as the current instance. This is
// a method of object equality, that only returns true if obj is also a double.
public override bool Equals(Object obj) {
if (!(obj is Double)) {
return false;
}
double temp = ((Double)obj).m_value;
// This code below is written this way for performance reasons i.e the != and == check is intentional.
if (temp == m_value) {
return true;
}
return IsNaN(temp) && IsNaN(m_value);
}
[System.Runtime.Versioning.NonVersionable]
public static bool operator ==(Double left, Double right) {
return left == right;
}
[System.Runtime.Versioning.NonVersionable]
public static bool operator !=(Double left, Double right) {
return left != right;
}
[System.Runtime.Versioning.NonVersionable]
public static bool operator <(Double left, Double right) {
return left < right;
}
[System.Runtime.Versioning.NonVersionable]
public static bool operator >(Double left, Double right) {
return left > right;
}
[System.Runtime.Versioning.NonVersionable]
public static bool operator <=(Double left, Double right) {
return left <= right;
}
[System.Runtime.Versioning.NonVersionable]
public static bool operator >=(Double left, Double right) {
return left >= right;
}
public bool Equals(Double obj)
{
if (obj == m_value) {
return true;
}
return IsNaN(obj) && IsNaN(m_value);
}
//The hashcode for a double is the absolute value of the integer representation
//of that double.
//
[System.Security.SecuritySafeCritical]
public unsafe override int GetHashCode() {
double d = m_value;
if (d == 0) {
// Ensure that 0 and -0 have the same hash code
return 0;
}
long value = *(long*)(&d);
return unchecked((int)value) ^ ((int)(value >> 32));
}
[System.Security.SecuritySafeCritical] // auto-generated
public override String ToString() {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatDouble(m_value, null, NumberFormatInfo.CurrentInfo);
}
[System.Security.SecuritySafeCritical] // auto-generated
public String ToString(String format) {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatDouble(m_value, format, NumberFormatInfo.CurrentInfo);
}
[System.Security.SecuritySafeCritical] // auto-generated
public String ToString(IFormatProvider provider) {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatDouble(m_value, null, NumberFormatInfo.GetInstance(provider));
}
[System.Security.SecuritySafeCritical] // auto-generated
public String ToString(String format, IFormatProvider provider) {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatDouble(m_value, format, NumberFormatInfo.GetInstance(provider));
}
public static double Parse(String s) {
return Parse(s, NumberStyles.Float| NumberStyles.AllowThousands, NumberFormatInfo.CurrentInfo);
}
public static double Parse(String s, NumberStyles style) {
NumberFormatInfo.ValidateParseStyleFloatingPoint(style);
return Parse(s, style, NumberFormatInfo.CurrentInfo);
}
public static double Parse(String s, IFormatProvider provider) {
return Parse(s, NumberStyles.Float| NumberStyles.AllowThousands, NumberFormatInfo.GetInstance(provider));
}
public static double Parse(String s, NumberStyles style, IFormatProvider provider) {
NumberFormatInfo.ValidateParseStyleFloatingPoint(style);
return Parse(s, style, NumberFormatInfo.GetInstance(provider));
}
// Parses a double from a String in the given style. If
// a NumberFormatInfo isn't specified, the current culture's
// NumberFormatInfo is assumed.
//
// This method will not throw an OverflowException, but will return
// PositiveInfinity or NegativeInfinity for a number that is too
// large or too small.
//
private static double Parse(String s, NumberStyles style, NumberFormatInfo info) {
return Number.ParseDouble(s, style, info);
}
public static bool TryParse(String s, out double result) {
return TryParse(s, NumberStyles.Float| NumberStyles.AllowThousands, NumberFormatInfo.CurrentInfo, out result);
}
public static bool TryParse(String s, NumberStyles style, IFormatProvider provider, out double result) {
NumberFormatInfo.ValidateParseStyleFloatingPoint(style);
return TryParse(s, style, NumberFormatInfo.GetInstance(provider), out result);
}
private static bool TryParse(String s, NumberStyles style, NumberFormatInfo info, out double result) {
if (s == null) {
result = 0;
return false;
}
bool success = Number.TryParseDouble(s, style, info, out result);
if (!success) {
String sTrim = s.Trim();
if (sTrim.Equals(info.PositiveInfinitySymbol)) {
result = PositiveInfinity;
} else if (sTrim.Equals(info.NegativeInfinitySymbol)) {
result = NegativeInfinity;
} else if (sTrim.Equals(info.NaNSymbol)) {
result = NaN;
} else
return false; // We really failed
}
return true;
}
//
// IConvertible implementation
//
public TypeCode GetTypeCode() {
return TypeCode.Double;
}
/// <internalonly/>
bool IConvertible.ToBoolean(IFormatProvider provider) {
return Convert.ToBoolean(m_value);
}
/// <internalonly/>
char IConvertible.ToChar(IFormatProvider provider) {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "Double", "Char"));
}
/// <internalonly/>
sbyte IConvertible.ToSByte(IFormatProvider provider) {
return Convert.ToSByte(m_value);
}
/// <internalonly/>
byte IConvertible.ToByte(IFormatProvider provider) {
return Convert.ToByte(m_value);
}
/// <internalonly/>
short IConvertible.ToInt16(IFormatProvider provider) {
return Convert.ToInt16(m_value);
}
/// <internalonly/>
ushort IConvertible.ToUInt16(IFormatProvider provider) {
return Convert.ToUInt16(m_value);
}
/// <internalonly/>
int IConvertible.ToInt32(IFormatProvider provider) {
return Convert.ToInt32(m_value);
}
/// <internalonly/>
uint IConvertible.ToUInt32(IFormatProvider provider) {
return Convert.ToUInt32(m_value);
}
/// <internalonly/>
long IConvertible.ToInt64(IFormatProvider provider) {
return Convert.ToInt64(m_value);
}
/// <internalonly/>
ulong IConvertible.ToUInt64(IFormatProvider provider) {
return Convert.ToUInt64(m_value);
}
/// <internalonly/>
float IConvertible.ToSingle(IFormatProvider provider) {
return Convert.ToSingle(m_value);
}
/// <internalonly/>
double IConvertible.ToDouble(IFormatProvider provider) {
return m_value;
}
/// <internalonly/>
Decimal IConvertible.ToDecimal(IFormatProvider provider) {
return Convert.ToDecimal(m_value);
}
/// <internalonly/>
DateTime IConvertible.ToDateTime(IFormatProvider provider) {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "Double", "DateTime"));
}
/// <internalonly/>
Object IConvertible.ToType(Type type, IFormatProvider provider) {
return Convert.DefaultToType((IConvertible)this, type, provider);
}
///#if GENERICS_WORK
/// //
/// // IArithmetic<Double> implementation
/// //
///
/// /// <internalonly/>
/// Double IArithmetic<Double>.AbsoluteValue(out bool overflowed) {
/// Double abs = (m_value < 0 ? -m_value : m_value);
/// overflowed = IsInfinity(abs) || IsNaN(abs);
/// return abs;
/// }
///
/// /// <internalonly/>
/// Double IArithmetic<Double>.Negate(out bool overflowed) {
/// Double neg= -m_value;
/// overflowed = IsInfinity(neg) || IsNaN(neg);
/// return neg;
/// }
///
/// /// <internalonly/>
/// Double IArithmetic<Double>.Sign(out bool overflowed) {
/// overflowed = IsNaN(m_value);
/// if (overflowed) {
/// return m_value;
/// }
/// return (m_value >= 0 ? (m_value == 0 ? 0 : 1) : -1);
/// }
///
/// /// <internalonly/>
/// Double IArithmetic<Double>.Add(Double addend, out bool overflowed) {
/// Double s = m_value + addend;
/// overflowed = IsInfinity(s) || IsNaN(s);
/// return s;
/// }
///
/// /// <internalonly/>
/// Double IArithmetic<Double>.Subtract(Double subtrahend, out bool overflowed) {
/// Double s = m_value - subtrahend;
/// overflowed = IsInfinity(s) || IsNaN(s);
/// return s;
/// }
///
/// /// <internalonly/>
/// Double IArithmetic<Double>.Multiply(Double multiplier, out bool overflowed) {
/// Double s = m_value * multiplier;
/// overflowed = IsInfinity(s) || IsNaN(s);
/// return s;
/// }
///
///
/// /// <internalonly/>
/// Double IArithmetic<Double>.Divide(Double divisor, out bool overflowed) {
/// Double s = m_value / divisor;
/// overflowed = IsInfinity(s) || IsNaN(s);
/// return s;
/// }
///
/// /// <internalonly/>
/// Double IArithmetic<Double>.DivideRemainder(Double divisor, out Double remainder, out bool overflowed) {
/// remainder = m_value % divisor;
/// Double s = m_value / divisor;
/// overflowed = IsInfinity(s) || IsInfinity(remainder) || IsNaN(s) || IsNaN(remainder);
/// return s;
/// }
///
/// /// <internalonly/>
/// Double IArithmetic<Double>.Remainder(Double divisor, out bool overflowed) {
/// Double d = m_value % divisor;
/// overflowed = IsInfinity(d) || IsNaN(d);
/// return d;
/// }
///
/// /// <internalonly/>
/// ArithmeticDescriptor<Double> IArithmetic<Double>.GetDescriptor() {
/// if (s_descriptor == null) {
/// s_descriptor = new DoubleArithmeticDescriptor( ArithmeticCapabilities.One
/// | ArithmeticCapabilities.Zero
/// | ArithmeticCapabilities.MaxValue
/// | ArithmeticCapabilities.MinValue
/// | ArithmeticCapabilities.PositiveInfinity
/// | ArithmeticCapabilities.NegativeInfinity);
/// }
/// return s_descriptor;
/// }
///
/// private static DoubleArithmeticDescriptor s_descriptor;
///
/// class DoubleArithmeticDescriptor : ArithmeticDescriptor<Double> {
/// public DoubleArithmeticDescriptor(ArithmeticCapabilities capabilities) : base(capabilities) {}
///
/// public override Double One {
/// get {
/// return (Double) 1;
/// }
/// }
///
/// public override Double Zero {
/// get {
/// return (Double) 0;
/// }
/// }
///
/// public override Double MinValue {
/// get {
/// return Double.MinValue;
/// }
/// }
///
/// public override Double MaxValue {
/// get {
/// return Double.MaxValue;
/// }
/// }
///
/// public override Double PositiveInfinity {
/// get {
/// return Double.PositiveInfinity;
/// }
/// }
///
/// public override Double NegativeInfinity {
/// get {
/// return Double.NegativeInfinity;
/// }
/// }
///
/// }
///#endif // #if GENERICS_WORK
}
}
| |
/*
* Copyright (c) Contributors, http://aurora-sim.org/, 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 Aurora-Sim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using Aurora.DataManager;
using Aurora.Simulation.Base;
using Nini.Config;
using OpenMetaverse;
using Aurora.Framework;
using OpenSim.Services.Connectors;
using OpenSim.Services.Interfaces;
namespace OpenSim.Services.UserAccountService
{
public class UserAccountService : ConnectorBase, IUserAccountService, IService
{
#region Declares
protected IAuthenticationService m_AuthenticationService;
protected IUserAccountData m_Database;
protected IGridService m_GridService;
protected IInventoryService m_InventoryService;
protected GenericAccountCache<UserAccount> m_cache = new GenericAccountCache<UserAccount>();
#endregion
#region IService Members
public virtual string Name
{
get { return GetType().Name; }
}
public void Initialize(IConfigSource config, IRegistryCore registry)
{
IConfig handlerConfig = config.Configs["Handlers"];
if (handlerConfig.GetString("UserAccountHandler", "") != Name)
return;
Configure(config, registry);
Init(registry, Name);
}
public void Configure(IConfigSource config, IRegistryCore registry)
{
if (MainConsole.Instance != null)
{
MainConsole.Instance.Commands.AddCommand(
"create user",
"create user [<first> [<last> [<pass> [<email>]]]]",
"Create a new user", HandleCreateUser);
MainConsole.Instance.Commands.AddCommand("reset user password",
"reset user password [<first> [<last> [<password>]]]",
"Reset a user password", HandleResetUserPassword);
MainConsole.Instance.Commands.AddCommand(
"show account",
"show account <first> <last>",
"Show account details for the given user", HandleShowAccount);
MainConsole.Instance.Commands.AddCommand(
"set user level",
"set user level [<first> [<last> [<level>]]]",
"Set user level. If the user's level is > 0, "
+ "this account will be treated as god-moded. "
+ "It will also affect the 'login level' command. ",
HandleSetUserLevel);
MainConsole.Instance.Commands.AddCommand(
"set user profile title",
"set user profile title [<first> [<last> [<Title>]]]",
"Sets the title (Normally resident) in a user's title to some custom value.",
HandleSetTitle);
MainConsole.Instance.Commands.AddCommand(
"set partner",
"set partner",
"Sets the partner in a user's profile.",
HandleSetPartner);
}
registry.RegisterModuleInterface<IUserAccountService>(this);
}
public void Start(IConfigSource config, IRegistryCore registry)
{
m_GridService = registry.RequestModuleInterface<IGridService>();
m_AuthenticationService = registry.RequestModuleInterface<IAuthenticationService>();
m_InventoryService = registry.RequestModuleInterface<IInventoryService>();
m_Database = DataManager.RequestPlugin<IUserAccountData>();
if (m_Database == null)
throw new Exception("Could not find a storage interface in the given module");
}
public void FinishedStartup()
{
}
#endregion
#region IUserAccountService Members
public virtual IUserAccountService InnerService
{
get { return this; }
}
[CanBeReflected(ThreatLevel = OpenSim.Services.Interfaces.ThreatLevel.Low)]
public UserAccount GetUserAccount(UUID scopeID, string firstName, string lastName)
{
UserAccount account;
if (m_cache.Get(firstName + " " + lastName, out account))
return account;
object remoteValue = DoRemote(scopeID, firstName, lastName);
if (remoteValue != null || m_doRemoteOnly)
{
UserAccount acc = (UserAccount)remoteValue;
if (remoteValue != null)
m_cache.Cache(acc.PrincipalID, acc);
return acc;
}
UserAccount[] d;
if (scopeID != UUID.Zero)
{
d = m_Database.Get(
new[] {"ScopeID", "FirstName", "LastName"},
new[] {scopeID.ToString(), firstName, lastName});
if (d.Length < 1)
{
d = m_Database.Get(
new[] {"ScopeID", "FirstName", "LastName"},
new[] {UUID.Zero.ToString(), firstName, lastName});
}
}
else
{
d = m_Database.Get(
new[] {"FirstName", "LastName"},
new[] {firstName, lastName});
}
if (d.Length < 1)
return null;
CacheAccount(d[0]);
return d[0];
}
public void CacheAccount(UserAccount account)
{
if ((account != null) && (account.UserLevel <= -1))
return;
m_cache.Cache(account.PrincipalID, account);
}
[CanBeReflected(ThreatLevel = OpenSim.Services.Interfaces.ThreatLevel.Low)]
public UserAccount GetUserAccount(UUID scopeID, string name)
{
UserAccount account;
if (m_cache.Get(name, out account))
return account;
object remoteValue = DoRemote(scopeID, name);
if (remoteValue != null || m_doRemoteOnly)
{
UserAccount acc = (UserAccount)remoteValue;
if (remoteValue != null)
m_cache.Cache(acc.PrincipalID, acc);
return acc;
}
UserAccount[] d;
if (scopeID != UUID.Zero)
{
d = m_Database.Get(
new[] {"ScopeID", "Name"},
new[] {scopeID.ToString(), name});
}
else
{
d = m_Database.Get(
new[] {"Name"},
new[] {name});
}
if (d.Length < 1)
{
string[] split = name.Split(' ');
if (split.Length == 2)
return GetUserAccount(scopeID, split[0], split[1]);
return null;
}
CacheAccount(d[0]);
return d[0];
}
[CanBeReflected(ThreatLevel = OpenSim.Services.Interfaces.ThreatLevel.Low, RenamedMethod="GetUserAccountUUID")]
public UserAccount GetUserAccount(UUID scopeID, UUID principalID)
{
UserAccount account;
if (m_cache.Get(principalID, out account))
return account;
object remoteValue = DoRemote(scopeID, principalID);
if (remoteValue != null || m_doRemoteOnly)
{
UserAccount acc = (UserAccount)remoteValue;
if (remoteValue != null)
m_cache.Cache(principalID, acc);
return acc;
}
UserAccount[] d;
if (scopeID != UUID.Zero)
{
d = m_Database.Get(
new[] {"ScopeID", "PrincipalID"},
new[] {scopeID.ToString(), principalID.ToString()});
if (d.Length < 1)
{
d = m_Database.Get(
new[] {"ScopeID", "PrincipalID"},
new[] {UUID.Zero.ToString(), principalID.ToString()});
}
}
else
{
d = m_Database.Get(
new[] {"PrincipalID"},
new[] {principalID.ToString()});
}
if (d.Length < 1)
{
m_cache.Cache(principalID, null);
return null;
}
CacheAccount(d[0]);
return d[0];
}
[CanBeReflected(ThreatLevel = OpenSim.Services.Interfaces.ThreatLevel.Full)]
public bool StoreUserAccount(UserAccount data)
{
object remoteValue = DoRemote(data);
if (remoteValue != null || m_doRemoteOnly)
return remoteValue == null ? false : (bool)remoteValue;
if (data.UserTitle == null)
data.UserTitle = "";
return m_Database.Store(data);
}
[CanBeReflected(ThreatLevel = OpenSim.Services.Interfaces.ThreatLevel.Low)]
public List<UserAccount> GetUserAccounts(UUID scopeID, string query)
{
object remoteValue = DoRemote(scopeID, query);
if (remoteValue != null || m_doRemoteOnly)
return (List<UserAccount>)remoteValue;
UserAccount[] d = m_Database.GetUsers(scopeID, query);
if (d == null)
return new List<UserAccount>();
List<UserAccount> ret = new List<UserAccount>(d);
return ret;
}
[CanBeReflected(ThreatLevel = OpenSim.Services.Interfaces.ThreatLevel.Low)]
public List<UserAccount> GetUserAccounts(UUID scopeID, string query, uint? start, uint? count)
{
object remoteValue = DoRemote(scopeID, query);
if (remoteValue != null || m_doRemoteOnly)
return (List<UserAccount>)remoteValue;
UserAccount[] d = m_Database.GetUsers(scopeID, query, start, count);
if (d == null)
return new List<UserAccount>();
List<UserAccount> ret = new List<UserAccount>(d);
return ret;
}
[CanBeReflected(ThreatLevel = OpenSim.Services.Interfaces.ThreatLevel.Low)]
public uint NumberOfUserAccounts(UUID scopeID, string query)
{
object remoteValue = DoRemote(scopeID, query);
if (remoteValue != null || m_doRemoteOnly)
return (uint)remoteValue;
return m_Database.NumberOfUsers(scopeID, query);
}
public void CreateUser(string name, string password, string email)
{
CreateUser(UUID.Random(), UUID.Zero, name, password, email);
}
/// <summary>
/// Create a user
/// </summary>
/// <param name = "firstName"></param>
/// <param name = "lastName"></param>
/// <param name = "password"></param>
/// <param name = "email"></param>
[CanBeReflected(ThreatLevel = OpenSim.Services.Interfaces.ThreatLevel.Full)]
public void CreateUser(UUID userID, UUID scopeID, string name, string password, string email)
{
object remoteValue = DoRemote(userID, scopeID, name, password, email);
if (remoteValue != null || m_doRemoteOnly)
return;
UserAccount account = GetUserAccount(UUID.Zero, userID);
UserAccount nameaccount = GetUserAccount(UUID.Zero, name);
if (null == account && nameaccount == null)
{
account = new UserAccount(scopeID, userID, name, email);
if (StoreUserAccount(account))
{
bool success;
if (m_AuthenticationService != null && password != "")
{
success = m_AuthenticationService.SetPasswordHashed(account.PrincipalID, "UserAccount", password);
if (!success)
MainConsole.Instance.WarnFormat("[USER ACCOUNT SERVICE]: Unable to set password for account {0}.",
name);
}
MainConsole.Instance.InfoFormat("[USER ACCOUNT SERVICE]: Account {0} created successfully", name);
//Cache it as well
CacheAccount(account);
}
else
{
MainConsole.Instance.ErrorFormat("[USER ACCOUNT SERVICE]: Account creation failed for account {0}", name);
}
}
else
{
MainConsole.Instance.ErrorFormat("[USER ACCOUNT SERVICE]: A user with the name {0} already exists!", name);
}
}
[CanBeReflected(ThreatLevel = OpenSim.Services.Interfaces.ThreatLevel.Full)]
public void DeleteUser(UUID userID, string password, bool archiveInformation, bool wipeFromDatabase)
{
object remoteValue = DoRemote(userID, password, archiveInformation, wipeFromDatabase);
if (remoteValue != null || m_doRemoteOnly)
return;
if (m_AuthenticationService.Authenticate(userID, "UserAccount", password, 0) == "")
return;//Not authed
if (!m_Database.DeleteAccount(userID, archiveInformation))
{
MainConsole.Instance.WarnFormat("Failed to remove the account for {0}, please check that the database is valid after this operation!", userID);
return;
}
if(wipeFromDatabase)
m_registry.RequestModuleInterface<ISimulationBase>().EventManager.FireGenericEventHandler("DeleteUserInformation", userID);
}
#endregion
#region Console commands
protected void HandleSetPartner(string[] cmdParams)
{
string first = MainConsole.Instance.Prompt("First User's name");
string second = MainConsole.Instance.Prompt("Second User's name");
IProfileConnector profileConnector = Aurora.DataManager.DataManager.RequestPlugin<IProfileConnector>();
if (profileConnector != null)
{
IUserProfileInfo firstProfile = profileConnector.GetUserProfile(GetUserAccount(UUID.Zero, first).PrincipalID);
IUserProfileInfo secondProfile = profileConnector.GetUserProfile(GetUserAccount(UUID.Zero, second).PrincipalID);
firstProfile.Partner = secondProfile.PrincipalID;
secondProfile.Partner = firstProfile.PrincipalID;
profileConnector.UpdateUserProfile(firstProfile);
profileConnector.UpdateUserProfile(secondProfile);
MainConsole.Instance.Warn("Partner information updated. ");
}
}
protected void HandleSetTitle(string[] cmdparams)
{
string firstName;
string lastName;
string title;
firstName = cmdparams.Length < 5 ? MainConsole.Instance.Prompt("First name") : cmdparams[4];
lastName = cmdparams.Length < 6 ? MainConsole.Instance.Prompt("Last name") : cmdparams[5];
UserAccount account = GetUserAccount(UUID.Zero, firstName, lastName);
if (account == null)
{
MainConsole.Instance.Info("No such user");
return;
}
title = cmdparams.Length < 7 ? MainConsole.Instance.Prompt("User Title") : Util.CombineParams(cmdparams, 6);
account.UserTitle = title;
Aurora.Framework.IProfileConnector profileConnector = Aurora.DataManager.DataManager.RequestPlugin<Aurora.Framework.IProfileConnector>();
if (profileConnector != null)
{
Aurora.Framework.IUserProfileInfo profile = profileConnector.GetUserProfile(account.PrincipalID);
profile.MembershipGroup = title;
profile.CustomType = title;
profileConnector.UpdateUserProfile(profile);
}
bool success = StoreUserAccount(account);
if (!success)
MainConsole.Instance.InfoFormat("Unable to set user profile title for account {0} {1}.", firstName, lastName);
else
MainConsole.Instance.InfoFormat("User profile title set for user {0} {1} to {2}", firstName, lastName, title);
}
protected void HandleSetUserLevel(string[] cmdparams)
{
string firstName;
string lastName;
string rawLevel;
int level;
firstName = cmdparams.Length < 4 ? MainConsole.Instance.Prompt("First name") : cmdparams[3];
lastName = cmdparams.Length < 5 ? MainConsole.Instance.Prompt("Last name") : cmdparams[4];
UserAccount account = GetUserAccount(UUID.Zero, firstName, lastName);
if (account == null)
{
MainConsole.Instance.Info("No such user");
return;
}
rawLevel = cmdparams.Length < 6 ? MainConsole.Instance.Prompt("User level") : cmdparams[5];
if (int.TryParse(rawLevel, out level) == false)
{
MainConsole.Instance.Info("Invalid user level");
return;
}
account.UserLevel = level;
bool success = StoreUserAccount(account);
if (!success)
MainConsole.Instance.InfoFormat("Unable to set user level for account {0} {1}.", firstName, lastName);
else
MainConsole.Instance.InfoFormat("User level set for user {0} {1} to {2}", firstName, lastName, level);
}
protected void HandleShowAccount(string[] cmdparams)
{
if (cmdparams.Length != 4)
{
MainConsole.Instance.Output("Usage: show account <first-name> <last-name>");
return;
}
string firstName = cmdparams[2];
string lastName = cmdparams[3];
UserAccount ua = GetUserAccount(UUID.Zero, firstName, lastName);
if (ua == null)
{
MainConsole.Instance.InfoFormat("No user named {0} {1}", firstName, lastName);
return;
}
MainConsole.Instance.InfoFormat("Name: {0}", ua.Name);
MainConsole.Instance.InfoFormat("ID: {0}", ua.PrincipalID);
MainConsole.Instance.InfoFormat("Title: {0}", ua.UserTitle);
MainConsole.Instance.InfoFormat("E-mail: {0}", ua.Email);
MainConsole.Instance.InfoFormat("Created: {0}", Utils.UnixTimeToDateTime(ua.Created));
MainConsole.Instance.InfoFormat("Level: {0}", ua.UserLevel);
MainConsole.Instance.InfoFormat("Flags: {0}", ua.UserFlags);
}
/// <summary>
/// Handle the create user command from the console.
/// </summary>
/// <param name = "cmdparams">string array with parameters: firstname, lastname, password, locationX, locationY, email</param>
protected void HandleCreateUser(string[] cmdparams)
{
string name, password, email, uuid, scopeID;
name = MainConsole.Instance.Prompt("Name", "Default User");
password = MainConsole.Instance.PasswordPrompt("Password");
email = MainConsole.Instance.Prompt("Email", "");
uuid = MainConsole.Instance.Prompt("UUID (Don't change unless you have a reason)", UUID.Random().ToString());
scopeID = MainConsole.Instance.Prompt("Scope (Don't change unless you know what this is)", UUID.Zero.ToString());
CreateUser(UUID.Parse(uuid), UUID.Parse(scopeID), name, Util.Md5Hash(password), email);
}
protected void HandleResetUserPassword(string[] cmdparams)
{
string name;
string newPassword;
name = MainConsole.Instance.Prompt("Name");
newPassword = MainConsole.Instance.PasswordPrompt("New password");
UserAccount account = GetUserAccount(UUID.Zero, name);
if (account == null)
MainConsole.Instance.ErrorFormat("[USER ACCOUNT SERVICE]: No such user");
bool success = false;
if (m_AuthenticationService != null)
success = m_AuthenticationService.SetPassword(account.PrincipalID, "UserAccount", newPassword);
if (!success)
MainConsole.Instance.ErrorFormat("[USER ACCOUNT SERVICE]: Unable to reset password for account {0}.",
name);
else
MainConsole.Instance.InfoFormat("[USER ACCOUNT SERVICE]: Password reset for user {0}", name);
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.IO;
using System.Reflection.Metadata;
using System.Reflection.PortableExecutable;
namespace System.Diagnostics
{
public sealed partial class FileVersionInfo
{
private FileVersionInfo(string fileName)
{
_fileName = fileName;
// For managed assemblies, read the file version information from the assembly's metadata.
// This isn't quite what's done on Windows, which uses the Win32 GetFileVersionInfo to read
// the Win32 resource information from the file, and the managed compiler uses these attributes
// to fill in that resource information when compiling the assembly. It's possible
// that after compilation, someone could have modified the resource information such that it
// no longer matches what was or wasn't in the assembly. But that's a rare enough case
// that this should match for all intents and purposes. If this ever becomes a problem,
// we can implement a full-fledged Win32 resource parser; that would also enable support
// for native Win32 PE files on Unix, but that should also be an extremely rare case.
if (!TryLoadManagedAssemblyMetadata())
{
// We could try to parse Executable and Linkable Format (ELF) files, but at present
// for executables they don't store version information, which is typically just
// available in the filename itself. For now, we won't do anything special, but
// we can add more cases here as we find need and opportunity.
}
}
// -----------------------------
// ---- PAL layer ends here ----
// -----------------------------
/// <summary>Attempt to load our fields from the metadata of the file, if it's a managed assembly.</summary>
/// <returns>true if the file is a managed assembly; otherwise, false.</returns>
private bool TryLoadManagedAssemblyMetadata()
{
try
{
// Try to load the file using the managed metadata reader
using (FileStream assemblyStream = new FileStream(_fileName, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 0x1000, useAsync: false))
using (PEReader peReader = new PEReader(assemblyStream))
{
if (peReader.HasMetadata)
{
MetadataReader metadataReader = peReader.GetMetadataReader();
if (metadataReader.IsAssembly)
{
LoadManagedAssemblyMetadata(metadataReader);
return true;
}
}
}
}
catch (BadImageFormatException) { }
return false;
}
/// <summary>Load our fields from the metadata of the file as represented by the provided metadata reader.</summary>
/// <param name="metadataReader">The metadata reader for the CLI file this represents.</param>
private void LoadManagedAssemblyMetadata(MetadataReader metadataReader)
{
AssemblyDefinition assemblyDefinition = metadataReader.GetAssemblyDefinition();
// Set the internal and original names based on the file name.
_internalName = _originalFilename = Path.GetFileName(_fileName);
// Set the product version based on the assembly's version (this may be overwritten
// later in the method).
Version productVersion = assemblyDefinition.Version;
_productVersion = productVersion.ToString();
_productMajor = productVersion.Major;
_productMinor = productVersion.Minor;
_productBuild = productVersion.Build != -1 ? productVersion.Build : 0;
_productPrivate = productVersion.Revision != -1 ? productVersion.Revision : 0;
// "Language Neutral" is used on Win32 for unknown language identifiers.
_language = "Language Neutral";
// Set other fields to default values in case they're not overwritten by attributes
_companyName = string.Empty;
_comments = string.Empty;
_fileDescription = " "; // this is what the managed compiler outputs when value isn't set
_fileVersion = string.Empty;
_legalCopyright = " "; // this is what the managed compiler outputs when value isn't set
_legalTrademarks = string.Empty;
_productName = string.Empty;
_privateBuild = string.Empty;
_specialBuild = string.Empty;
// Be explicit about initialization to suppress warning about fields not being set
_isDebug = false;
_isPatched = false;
_isPreRelease = false;
_isPrivateBuild = false;
_isSpecialBuild = false;
// Everything else is parsed from assembly attributes
MetadataStringComparer comparer = metadataReader.StringComparer;
foreach (CustomAttributeHandle attrHandle in assemblyDefinition.GetCustomAttributes())
{
CustomAttribute attr = metadataReader.GetCustomAttribute(attrHandle);
StringHandle typeNamespaceHandle = default(StringHandle), typeNameHandle = default(StringHandle);
if (TryGetAttributeName(metadataReader, attr, out typeNamespaceHandle, out typeNameHandle) &&
comparer.Equals(typeNamespaceHandle, "System.Reflection"))
{
if (comparer.Equals(typeNameHandle, "AssemblyCompanyAttribute"))
{
GetStringAttributeArgumentValue(metadataReader, attr, ref _companyName);
}
else if (comparer.Equals(typeNameHandle, "AssemblyCopyrightAttribute"))
{
GetStringAttributeArgumentValue(metadataReader, attr, ref _legalCopyright);
}
else if (comparer.Equals(typeNameHandle, "AssemblyDescriptionAttribute"))
{
GetStringAttributeArgumentValue(metadataReader, attr, ref _comments);
}
else if (comparer.Equals(typeNameHandle, "AssemblyFileVersionAttribute"))
{
string versionString = string.Empty;
GetStringAttributeArgumentValue(metadataReader, attr, ref versionString);
Version v;
if (Version.TryParse(versionString, out v))
{
_fileVersion = v.ToString();
_fileMajor = v.Major;
_fileMinor = v.Minor;
_fileBuild = v.Build != -1 ? v.Build : 0;
_filePrivate = v.Revision != -1 ? v.Revision : 0;
// When the managed compiler sees an [AssemblyVersion(...)] attribute, it uses that to set
// both the assembly version and the product version in the Win32 resources. If it doesn't
// see an [AssemblyVersion(...)], then it sets the assembly version to 0.0.0.0, however it
// sets the product version in the Win32 resources to whatever was defined in the
// [AssemblyFileVersionAttribute(...)] if there was one. Without parsing the Win32 resources,
// we can't differentiate these two cases, so given the rarity of explicitly setting an
// assembly's version number to 0.0.0.0, we assume that if it is 0.0.0.0 then the attribute
// wasn't specified and we use the file version.
if (_productVersion == "0.0.0.0")
{
_productVersion = _fileVersion;
_productMajor = _fileMajor;
_productMinor = _fileMinor;
_productBuild = _fileBuild;
_productPrivate = _filePrivate;
}
}
}
else if (comparer.Equals(typeNameHandle, "AssemblyProductAttribute"))
{
GetStringAttributeArgumentValue(metadataReader, attr, ref _productName);
}
else if (comparer.Equals(typeNameHandle, "AssemblyTrademarkAttribute"))
{
GetStringAttributeArgumentValue(metadataReader, attr, ref _legalTrademarks);
}
else if (comparer.Equals(typeNameHandle, "AssemblyTitleAttribute"))
{
GetStringAttributeArgumentValue(metadataReader, attr, ref _fileDescription);
}
}
}
}
/// <summary>Gets the name of an attribute.</summary>
/// <param name="reader">The metadata reader.</param>
/// <param name="attr">The attribute.</param>
/// <param name="typeNamespaceHandle">The namespace of the attribute.</param>
/// <param name="typeNameHandle">The name of the attribute.</param>
/// <returns>true if the name could be retrieved; otherwise, false.</returns>
private static bool TryGetAttributeName(MetadataReader reader, CustomAttribute attr, out StringHandle typeNamespaceHandle, out StringHandle typeNameHandle)
{
EntityHandle ctorHandle = attr.Constructor;
switch (ctorHandle.Kind)
{
case HandleKind.MemberReference:
EntityHandle container = reader.GetMemberReference((MemberReferenceHandle)ctorHandle).Parent;
if (container.Kind == HandleKind.TypeReference)
{
TypeReference tr = reader.GetTypeReference((TypeReferenceHandle)container);
typeNamespaceHandle = tr.Namespace;
typeNameHandle = tr.Name;
return true;
}
break;
case HandleKind.MethodDefinition:
MethodDefinition md = reader.GetMethodDefinition((MethodDefinitionHandle)ctorHandle);
TypeDefinition td = reader.GetTypeDefinition(md.GetDeclaringType());
typeNamespaceHandle = td.Namespace;
typeNameHandle = td.Name;
return true;
}
// Unusual case, potentially invalid IL
typeNamespaceHandle = default(StringHandle);
typeNameHandle = default(StringHandle);
return false;
}
/// <summary>Gets the string argument value of an attribute with a single fixed string argument.</summary>
/// <param name="reader">The metadata reader.</param>
/// <param name="attr">The attribute.</param>
/// <param name="value">The value parsed from the attribute, if it could be retrieved; otherwise, the value is left unmodified.</param>
private static void GetStringAttributeArgumentValue(MetadataReader reader, CustomAttribute attr, ref string value)
{
EntityHandle ctorHandle = attr.Constructor;
BlobHandle signature;
switch (ctorHandle.Kind)
{
case HandleKind.MemberReference:
signature = reader.GetMemberReference((MemberReferenceHandle)ctorHandle).Signature;
break;
case HandleKind.MethodDefinition:
signature = reader.GetMethodDefinition((MethodDefinitionHandle)ctorHandle).Signature;
break;
default:
// Unusual case, potentially invalid IL
return;
}
BlobReader signatureReader = reader.GetBlobReader(signature);
BlobReader valueReader = reader.GetBlobReader(attr.Value);
const ushort Prolog = 1; // two-byte "prolog" defined by ECMA-335 (II.23.3) to be at the beginning of attribute value blobs
if (valueReader.ReadUInt16() == Prolog)
{
SignatureHeader header = signatureReader.ReadSignatureHeader();
int parameterCount;
if (header.Kind == SignatureKind.Method && // attr ctor must be a method
!header.IsGeneric && // attr ctor must be non-generic
signatureReader.TryReadCompressedInteger(out parameterCount) && // read parameter count
parameterCount == 1 && // attr ctor must have 1 parameter
signatureReader.ReadSignatureTypeCode() == SignatureTypeCode.Void && // attr ctor return type must be void
signatureReader.ReadSignatureTypeCode() == SignatureTypeCode.String) // attr ctor first parameter must be string
{
value = valueReader.ReadSerializedString();
}
}
}
}
}
| |
using System;
using System.Collections.Immutable;
using System.Reactive;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using Android.OS;
using Android.Text;
using Android.Views;
using AndroidX.Fragment.App;
using Toggl.Core.UI.ViewModels.Calendar;
using Toggl.Core.UI.ViewModels.Calendar.ContextualMenu;
using Toggl.Core.UI.Views;
using Toggl.Droid.Adapters;
using Toggl.Droid.Extensions;
using Toggl.Droid.Extensions.Reactive;
using Toggl.Droid.ViewHolders;
using Toggl.Shared.Extensions;
using Toggl.Shared.Extensions.Reactive;
using TimeEntryExtensions = Toggl.Droid.Extensions.TimeEntryExtensions;
namespace Toggl.Droid.Fragments.Calendar
{
public partial class CalendarDayViewPageFragment : Fragment, IView
{
private readonly TimeSpan defaultTimeEntryDurationForCreation = TimeSpan.FromMinutes(30);
private readonly BehaviorSubject<string> timeEntryPeriodObserver = new BehaviorSubject<string>(string.Empty);
private readonly BehaviorSubject<ISpannable> timeEntryDetailsObserver = new BehaviorSubject<ISpannable>(new SpannableString(string.Empty));
private IDisposable dismissActionDisposeBag;
private CompositeDisposable DisposeBag = new CompositeDisposable();
private CalendarContextualMenuActionsAdapter menuActionsAdapter;
public CalendarDayViewModel ViewModel { get; set; }
public BehaviorRelay<int> CurrentPageRelay { get; set; }
public BehaviorRelay<int> HourHeightRelay { get; set; }
public BehaviorRelay<int> ScrollOffsetRelay { get; set; }
public BehaviorRelay<bool> MenuVisibilityRelay { get; set; }
public BehaviorRelay<string> TimeTrackedOnDay { get; set; }
public IObservable<int> ScrollingPage { get; set; }
public IObservable<bool> ScrollToStartSign { get; set; }
public IObservable<Unit> InvalidationListener { get; set; }
public IObservable<Unit> BackPressListener { get; set; }
public int PageNumber { get; set; }
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
var view = inflater.Inflate(Resource.Layout.CalendarDayFragmentPage, container, false);
initializeViews(view);
return view;
}
public override void OnViewCreated(View view, Bundle savedInstanceState)
{
base.OnViewCreated(view, savedInstanceState);
if (ViewModel == null) return;
ViewModel.AttachView(this);
ViewModel.ContextualMenuViewModel.AttachView(this);
ScrollingPage.
Subscribe(scrollingPage => handleCalendarDayViewVisibility(scrollingPage, true))
.DisposedBy(DisposeBag);
CurrentPageRelay
.Subscribe(currentPage => handleCalendarDayViewVisibility(currentPage, false))
.DisposedBy(DisposeBag);
ViewModel.ContextualMenuViewModel
.MenuVisible
.Subscribe(handleMenuVisibility)
.DisposedBy(DisposeBag);
ViewModel.TimeTrackedOnDay
.CombineLatest(CurrentPageRelay, CommonFunctions.First)
.Subscribe(notifyTotalDurationIfCurrentPage)
.DisposedBy(DisposeBag);
ViewModel.ContextualMenuViewModel
.TimeEntryPeriod
.Subscribe(timeEntryPeriodObserver)
.DisposedBy(DisposeBag);
ViewModel.ContextualMenuViewModel
.TimeEntryInfo
.Select(convertTimeEntryInfoToSpannable)
.Subscribe(timeEntryDetailsObserver)
.DisposedBy(DisposeBag);
InvalidationListener?
.Subscribe(_ => invalidatePage())
.DisposedBy(DisposeBag);
BackPressListener?
.Subscribe(_ => discardCurrentItemInEditMode())
.DisposedBy(DisposeBag);
}
private void handleCalendarDayViewVisibility(int page, bool ignorePageNumber)
{
if (calendarDayView != null || !ignorePageNumber && page != PageNumber) return;
initializeCalendarDayView();
initializeDayViewBindings();
}
private void initializeDayViewBindings()
{
calendarDayView.SetCurrentDate(ViewModel.Date);
calendarDayView.SetOffset(ScrollOffsetRelay?.Value ?? 0);
calendarDayView.SetHourHeight(HourHeightRelay?.Value ?? 56.DpToPixels(Context));
calendarDayView.UpdateItems(ViewModel.CalendarItems);
ViewModel.TimeOfDayFormat
.Subscribe(calendarDayView.UpdateCalendarHoursFormat)
.DisposedBy(DisposeBag);
ViewModel.DurationFormat
.Subscribe(calendarDayView.UpdateDurationFormat)
.DisposedBy(DisposeBag);
ViewModel.CalendarItems.CollectionChange
.Subscribe(_ => calendarDayView.UpdateItems(ViewModel.CalendarItems))
.DisposedBy(DisposeBag);
calendarDayView.CalendarItemTappedObservable
.Subscribe(ViewModel.ContextualMenuViewModel.OnCalendarItemUpdated.Inputs)
.DisposedBy(DisposeBag);
calendarDayView.EmptySpansTouchedObservable
.Select(emptySpan => (emptySpan, defaultTimeEntryDurationForCreation))
.Subscribe(ViewModel.OnDurationSelected.Inputs)
.DisposedBy(DisposeBag);
ScrollToStartSign?
.Subscribe(scrollToStart)
.DisposedBy(DisposeBag);
calendarDayView.ScrollOffsetObservable
.Subscribe(updateScrollOffsetIfCurrentPage)
.DisposedBy(DisposeBag);
calendarDayView.HourHeight
.Subscribe(updateHourHeightIfCurrentPage)
.DisposedBy(DisposeBag);
ViewModel.ContextualMenuViewModel
.CalendarItemInEditMode
.Subscribe(calendarDayView.SetCurrentItemInEditMode)
.DisposedBy(DisposeBag);
ViewModel.ContextualMenuViewModel
.MenuVisible
.Where(menuIsVisible => !menuIsVisible)
.Subscribe(_ => calendarDayView.ClearEditMode())
.DisposedBy(DisposeBag);
ViewModel.ContextualMenuViewModel
.DiscardChanges
.Subscribe(_ => calendarDayView.DiscardEditModeChanges())
.DisposedBy(DisposeBag);
}
private void handleMenuVisibility(bool visible)
{
var shouldBeVisible = visible && PageNumber == CurrentPageRelay.Value;
if (shouldBeVisible)
{
if (contextualMenuContainer == null)
{
initializeContextualMenuView();
initializeContextualMenuBindings();
}
contextualMenuContainer.Visibility = ViewStates.Visible;
MenuVisibilityRelay?.Accept(true);
}
if (!shouldBeVisible && contextualMenuContainer != null)
{
contextualMenuContainer.Visibility = ViewStates.Gone;
}
}
private void initializeContextualMenuBindings()
{
ViewModel.ContextualMenuViewModel
.CurrentMenu
.Subscribe(updateMenuBindings)
.DisposedBy(DisposeBag);
ViewModel.ContextualMenuViewModel
.MenuVisible
.Subscribe(notifyMenuVisibilityIfCurrentPage)
.DisposedBy(DisposeBag);
timeEntryPeriodObserver
.Subscribe(periodText.Rx().TextObserver())
.DisposedBy(DisposeBag);
timeEntryDetailsObserver
.Subscribe(timeEntryDetails.Rx().TextFormattedObserver())
.DisposedBy(DisposeBag);
}
private void discardCurrentItemInEditMode()
{
ViewModel.ContextualMenuViewModel.OnCalendarItemUpdated.Execute(null);
}
private void invalidatePage()
{
View.PostInvalidateOnAnimation();
calendarDayView?.PostInvalidateOnAnimation();
contextualMenuContainer?.PostInvalidateOnAnimation();
}
private void updateMenuBindings(CalendarContextualMenu contextualMenu)
{
menuActionsAdapter.Items = contextualMenu.Actions;
dismissActionDisposeBag?.Dispose();
dismissActionDisposeBag = dismissButton.Rx().Tap()
.Subscribe(contextualMenu.Dismiss.Inputs);
}
private void notifyMenuVisibilityIfCurrentPage(bool menuIsVisible)
{
if (CurrentPageRelay?.Value == PageNumber)
{
MenuVisibilityRelay?.Accept(menuIsVisible);
}
}
private void notifyTotalDurationIfCurrentPage(string durationString)
{
if (CurrentPageRelay?.Value == PageNumber)
{
TimeTrackedOnDay?.Accept(durationString);
}
}
private ISpannable convertTimeEntryInfoToSpannable(TimeEntryDisplayInfo timeEntryDisplayInfo)
{
var description = string.IsNullOrEmpty(timeEntryDisplayInfo.Description)
? Shared.Resources.NoDescription
: timeEntryDisplayInfo.Description;
var hasProject = !string.IsNullOrEmpty(timeEntryDisplayInfo.Project);
var builder = new SpannableStringBuilder();
var projectTaskClient = TimeEntryExtensions.ToProjectTaskClient(
Context,
hasProject,
timeEntryDisplayInfo.Project,
timeEntryDisplayInfo.ProjectTaskColor,
timeEntryDisplayInfo.Task,
timeEntryDisplayInfo.Client,
false,
false
);
builder.Append(description);
builder.Append(" ");
builder.Append(projectTaskClient);
return builder;
}
private void updateScrollOffsetIfCurrentPage(int scrollOffset)
{
if (PageNumber != CurrentPageRelay?.Value)
return;
ScrollOffsetRelay?.Accept(scrollOffset);
}
private void updateHourHeightIfCurrentPage(int scrollOffset)
{
if (PageNumber != CurrentPageRelay?.Value)
return;
HourHeightRelay?.Accept(scrollOffset);
}
private void scrollToStart(bool shouldSmoothScroll)
{
if (PageNumber != CurrentPageRelay?.Value)
return;
calendarDayView?.ScrollToCurrentHour(shouldSmoothScroll);
}
public override void OnDestroyView()
{
ViewModel?.DetachView();
dismissActionDisposeBag?.Dispose();
DisposeBag.Dispose();
DisposeBag = new CompositeDisposable();
base.OnDestroyView();
}
private class CalendarContextualMenuActionsAdapter : BaseRecyclerAdapter<CalendarMenuAction>
{
private IImmutableList<CalendarMenuAction> items = ImmutableList<CalendarMenuAction>.Empty;
public override IImmutableList<CalendarMenuAction> Items
{
get => items;
set => SetItems(value ?? ImmutableList<CalendarMenuAction>.Empty);
}
protected override void SetItems(IImmutableList<CalendarMenuAction> newItems)
{
items = newItems;
NotifyDataSetChanged();
}
public override CalendarMenuAction GetItem(int viewPosition)
{
return items[viewPosition];
}
protected override BaseRecyclerViewHolder<CalendarMenuAction> CreateViewHolder(ViewGroup parent, LayoutInflater inflater, int viewType)
{
var view = inflater.Inflate(Resource.Layout.ContextualMenuActionCell, parent, false);
return CalendarMenuActionCellViewHolder.Create(view);
}
public override int ItemCount => items.Count;
}
}
}
| |
/*
* 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.
*/
// ReSharper disable UnusedAutoPropertyAccessor.Global
// ReSharper disable MemberCanBePrivate.Global
namespace Apache.Ignite.Core.Tests.Cache.Query
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Cache;
using Apache.Ignite.Core.Cache.Configuration;
using Apache.Ignite.Core.Cache.Query;
using Apache.Ignite.Core.Common;
using NUnit.Framework;
/// <summary>
/// Queries tests.
/// </summary>
public class CacheQueriesTest
{
/** Grid count. */
private const int GridCnt = 2;
/** Cache name. */
private const string CacheName = "cache";
/** Path to XML configuration. */
private const string CfgPath = "config\\cache-query.xml";
/** Maximum amount of items in cache. */
private const int MaxItemCnt = 100;
/// <summary>
/// Fixture setup.
/// </summary>
[TestFixtureSetUp]
public void StartGrids()
{
for (int i = 0; i < GridCnt; i++)
{
Ignition.Start(new IgniteConfiguration(TestUtils.GetTestConfiguration())
{
BinaryConfiguration = new BinaryConfiguration
{
NameMapper = GetNameMapper()
},
SpringConfigUrl = CfgPath,
IgniteInstanceName = "grid-" + i
});
}
}
/// <summary>
/// Gets the name mapper.
/// </summary>
protected virtual IBinaryNameMapper GetNameMapper()
{
return BinaryBasicNameMapper.FullNameInstance;
}
/// <summary>
/// Fixture teardown.
/// </summary>
[TestFixtureTearDown]
public void StopGrids()
{
Ignition.StopAll(true);
}
/// <summary>
///
/// </summary>
[SetUp]
public void BeforeTest()
{
Console.WriteLine("Test started: " + TestContext.CurrentContext.Test.Name);
}
/// <summary>
///
/// </summary>
[TearDown]
public void AfterTest()
{
var cache = Cache();
for (int i = 0; i < GridCnt; i++)
{
cache.Clear();
Assert.IsTrue(cache.IsEmpty());
}
TestUtils.AssertHandleRegistryIsEmpty(300,
Enumerable.Range(0, GridCnt).Select(x => Ignition.GetIgnite("grid-" + x)).ToArray());
Console.WriteLine("Test finished: " + TestContext.CurrentContext.Test.Name);
}
/// <summary>
/// Gets the ignite.
/// </summary>
private static IIgnite GetIgnite()
{
return Ignition.GetIgnite("grid-0");
}
/// <summary>
///
/// </summary>
/// <returns></returns>
private static ICache<int, QueryPerson> Cache()
{
return GetIgnite().GetCache<int, QueryPerson>(CacheName);
}
/// <summary>
/// Test arguments validation for SQL queries.
/// </summary>
[Test]
public void TestValidationSql()
{
// 1. No sql.
Assert.Throws<ArgumentException>(() =>
{ Cache().Query(new SqlQuery(typeof(QueryPerson), null)); });
// 2. No type.
Assert.Throws<ArgumentException>(() =>
{ Cache().Query(new SqlQuery((string)null, "age >= 50")); });
}
/// <summary>
/// Test arguments validation for SQL fields queries.
/// </summary>
[Test]
public void TestValidationSqlFields()
{
// 1. No sql.
Assert.Throws<ArgumentException>(() => { Cache().QueryFields(new SqlFieldsQuery(null)); });
}
/// <summary>
/// Test arguments validation for TEXT queries.
/// </summary>
[Test]
public void TestValidationText()
{
// 1. No text.
Assert.Throws<ArgumentException>(() =>
{ Cache().Query(new TextQuery(typeof(QueryPerson), null)); });
// 2. No type.
Assert.Throws<ArgumentException>(() =>
{ Cache().Query(new TextQuery((string)null, "Ivanov")); });
}
/// <summary>
/// Cursor tests.
/// </summary>
[Test]
[SuppressMessage("ReSharper", "ReturnValueOfPureMethodIsNotUsed")]
public void TestCursor()
{
Cache().Put(1, new QueryPerson("Ivanov", 30));
Cache().Put(1, new QueryPerson("Petrov", 40));
Cache().Put(1, new QueryPerson("Sidorov", 50));
SqlQuery qry = new SqlQuery(typeof(QueryPerson), "age >= 20");
// 1. Test GetAll().
using (IQueryCursor<ICacheEntry<int, QueryPerson>> cursor = Cache().Query(qry))
{
cursor.GetAll();
Assert.Throws<InvalidOperationException>(() => { cursor.GetAll(); });
Assert.Throws<InvalidOperationException>(() => { cursor.GetEnumerator(); });
}
// 2. Test GetEnumerator.
using (IQueryCursor<ICacheEntry<int, QueryPerson>> cursor = Cache().Query(qry))
{
cursor.GetEnumerator();
Assert.Throws<InvalidOperationException>(() => { cursor.GetAll(); });
Assert.Throws<InvalidOperationException>(() => { cursor.GetEnumerator(); });
}
}
/// <summary>
/// Test enumerator.
/// </summary>
[Test]
[SuppressMessage("ReSharper", "UnusedVariable")]
public void TestEnumerator()
{
Cache().Put(1, new QueryPerson("Ivanov", 30));
Cache().Put(2, new QueryPerson("Petrov", 40));
Cache().Put(3, new QueryPerson("Sidorov", 50));
Cache().Put(4, new QueryPerson("Unknown", 60));
// 1. Empty result set.
using (IQueryCursor<ICacheEntry<int, QueryPerson>> cursor =
Cache().Query(new SqlQuery(typeof(QueryPerson), "age = 100")))
{
IEnumerator<ICacheEntry<int, QueryPerson>> e = cursor.GetEnumerator();
Assert.Throws<InvalidOperationException>(() =>
{ ICacheEntry<int, QueryPerson> entry = e.Current; });
Assert.IsFalse(e.MoveNext());
Assert.Throws<InvalidOperationException>(() =>
{ ICacheEntry<int, QueryPerson> entry = e.Current; });
Assert.Throws<NotSupportedException>(() => e.Reset());
e.Dispose();
}
SqlQuery qry = new SqlQuery(typeof (QueryPerson), "age < 60");
Assert.AreEqual(QueryBase.DefaultPageSize, qry.PageSize);
// 2. Page size is bigger than result set.
qry.PageSize = 4;
CheckEnumeratorQuery(qry);
// 3. Page size equal to result set.
qry.PageSize = 3;
CheckEnumeratorQuery(qry);
// 4. Page size if less than result set.
qry.PageSize = 2;
CheckEnumeratorQuery(qry);
}
/// <summary>
/// Test SQL query arguments passing.
/// </summary>
[Test]
public void TestSqlQueryArguments()
{
Cache().Put(1, new QueryPerson("Ivanov", 30));
Cache().Put(2, new QueryPerson("Petrov", 40));
Cache().Put(3, new QueryPerson("Sidorov", 50));
// 1. Empty result set.
using (
IQueryCursor<ICacheEntry<int, QueryPerson>> cursor =
Cache().Query(new SqlQuery(typeof(QueryPerson), "age < ?", 50)))
{
foreach (ICacheEntry<int, QueryPerson> entry in cursor.GetAll())
Assert.IsTrue(entry.Key == 1 || entry.Key == 2);
}
}
/// <summary>
/// Test SQL fields query arguments passing.
/// </summary>
[Test]
public void TestSqlFieldsQueryArguments()
{
Cache().Put(1, new QueryPerson("Ivanov", 30));
Cache().Put(2, new QueryPerson("Petrov", 40));
Cache().Put(3, new QueryPerson("Sidorov", 50));
// 1. Empty result set.
using (
IQueryCursor<IList> cursor = Cache().QueryFields(
new SqlFieldsQuery("SELECT age FROM QueryPerson WHERE age < ?", 50)))
{
foreach (IList entry in cursor.GetAll())
Assert.IsTrue((int) entry[0] < 50);
}
}
/// <summary>
/// Check query result for enumerator test.
/// </summary>
/// <param name="qry">QUery.</param>
private void CheckEnumeratorQuery(SqlQuery qry)
{
using (IQueryCursor<ICacheEntry<int, QueryPerson>> cursor = Cache().Query(qry))
{
bool first = false;
bool second = false;
bool third = false;
foreach (var entry in cursor)
{
if (entry.Key == 1)
{
first = true;
Assert.AreEqual("Ivanov", entry.Value.Name);
Assert.AreEqual(30, entry.Value.Age);
}
else if (entry.Key == 2)
{
second = true;
Assert.AreEqual("Petrov", entry.Value.Name);
Assert.AreEqual(40, entry.Value.Age);
}
else if (entry.Key == 3)
{
third = true;
Assert.AreEqual("Sidorov", entry.Value.Name);
Assert.AreEqual(50, entry.Value.Age);
}
else
Assert.Fail("Unexpected value: " + entry);
}
Assert.IsTrue(first && second && third);
}
}
/// <summary>
/// Check SQL query.
/// </summary>
[Test]
public void TestSqlQuery([Values(true, false)] bool loc, [Values(true, false)] bool keepBinary,
[Values(true, false)] bool distrJoin)
{
var cache = Cache();
// 1. Populate cache with data, calculating expected count in parallel.
var exp = PopulateCache(cache, loc, MaxItemCnt, x => x < 50);
// 2. Validate results.
var qry = new SqlQuery(typeof(QueryPerson), "age < 50", loc)
{
EnableDistributedJoins = distrJoin,
ReplicatedOnly = false,
Timeout = TimeSpan.FromSeconds(3)
};
Assert.AreEqual(string.Format("SqlQuery [Sql=age < 50, Arguments=[], Local={0}, " +
"PageSize=1024, EnableDistributedJoins={1}, Timeout={2}, " +
"ReplicatedOnly=False]", loc, distrJoin, qry.Timeout), qry.ToString());
ValidateQueryResults(cache, qry, exp, keepBinary);
}
/// <summary>
/// Check SQL fields query.
/// </summary>
[Test]
public void TestSqlFieldsQuery([Values(true, false)] bool loc, [Values(true, false)] bool distrJoin,
[Values(true, false)] bool enforceJoinOrder)
{
int cnt = MaxItemCnt;
var cache = Cache();
// 1. Populate cache with data, calculating expected count in parallel.
var exp = PopulateCache(cache, loc, cnt, x => x < 50);
// 2. Validate results.
var qry = new SqlFieldsQuery("SELECT name, age FROM QueryPerson WHERE age < 50", loc)
{
EnableDistributedJoins = distrJoin,
EnforceJoinOrder = enforceJoinOrder,
Colocated = !distrJoin,
ReplicatedOnly = false,
Timeout = TimeSpan.FromSeconds(2)
};
using (IQueryCursor<IList> cursor = cache.QueryFields(qry))
{
HashSet<int> exp0 = new HashSet<int>(exp);
foreach (var entry in cursor.GetAll())
{
Assert.AreEqual(2, entry.Count);
Assert.AreEqual(entry[0].ToString(), entry[1].ToString());
exp0.Remove((int)entry[1]);
}
Assert.AreEqual(0, exp0.Count);
}
using (IQueryCursor<IList> cursor = cache.QueryFields(qry))
{
HashSet<int> exp0 = new HashSet<int>(exp);
foreach (var entry in cursor)
{
Assert.AreEqual(entry[0].ToString(), entry[1].ToString());
exp0.Remove((int)entry[1]);
}
Assert.AreEqual(0, exp0.Count);
}
}
/// <summary>
/// Check text query.
/// </summary>
[Test]
public void TestTextQuery([Values(true, false)] bool loc, [Values(true, false)] bool keepBinary)
{
var cache = Cache();
// 1. Populate cache with data, calculating expected count in parallel.
var exp = PopulateCache(cache, loc, MaxItemCnt, x => x.ToString().StartsWith("1"));
// 2. Validate results.
var qry = new TextQuery(typeof(QueryPerson), "1*", loc);
ValidateQueryResults(cache, qry, exp, keepBinary);
}
/// <summary>
/// Check scan query.
/// </summary>
[Test]
public void TestScanQuery([Values(true, false)] bool loc)
{
CheckScanQuery<QueryPerson>(loc, false);
}
/// <summary>
/// Check scan query in binary mode.
/// </summary>
[Test]
public void TestScanQueryBinary([Values(true, false)] bool loc)
{
CheckScanQuery<IBinaryObject>(loc, true);
}
/// <summary>
/// Check scan query with partitions.
/// </summary>
[Test]
public void TestScanQueryPartitions([Values(true, false)] bool loc)
{
CheckScanQueryPartitions<QueryPerson>(loc, false);
}
/// <summary>
/// Check scan query with partitions in binary mode.
/// </summary>
[Test]
public void TestScanQueryPartitionsBinary([Values(true, false)] bool loc)
{
CheckScanQueryPartitions<IBinaryObject>(loc, true);
}
/// <summary>
/// Tests that query attempt on non-indexed cache causes an exception.
/// </summary>
[Test]
public void TestIndexingDisabledError()
{
var cache = GetIgnite().GetOrCreateCache<int, QueryPerson>("nonindexed_cache");
var queries = new QueryBase[]
{
new TextQuery(typeof (QueryPerson), "1*"),
new SqlQuery(typeof (QueryPerson), "age < 50")
};
foreach (var qry in queries)
{
var err = Assert.Throws<IgniteException>(() => cache.Query(qry));
Assert.AreEqual("Indexing is disabled for cache: nonindexed_cache. " +
"Use setIndexedTypes or setTypeMetadata methods on CacheConfiguration to enable.", err.Message);
}
}
/// <summary>
/// Check scan query.
/// </summary>
/// <param name="loc">Local query flag.</param>
/// <param name="keepBinary">Keep binary flag.</param>
private static void CheckScanQuery<TV>(bool loc, bool keepBinary)
{
var cache = Cache();
int cnt = MaxItemCnt;
// No predicate
var exp = PopulateCache(cache, loc, cnt, x => true);
var qry = new ScanQuery<int, TV>();
ValidateQueryResults(cache, qry, exp, keepBinary);
// Serializable
exp = PopulateCache(cache, loc, cnt, x => x < 50);
qry = new ScanQuery<int, TV>(new ScanQueryFilter<TV>());
ValidateQueryResults(cache, qry, exp, keepBinary);
// Binarizable
exp = PopulateCache(cache, loc, cnt, x => x < 50);
qry = new ScanQuery<int, TV>(new BinarizableScanQueryFilter<TV>());
ValidateQueryResults(cache, qry, exp, keepBinary);
// Invalid
exp = PopulateCache(cache, loc, cnt, x => x < 50);
qry = new ScanQuery<int, TV>(new InvalidScanQueryFilter<TV>());
Assert.Throws<BinaryObjectException>(() => ValidateQueryResults(cache, qry, exp, keepBinary));
// Exception
exp = PopulateCache(cache, loc, cnt, x => x < 50);
qry = new ScanQuery<int, TV>(new ScanQueryFilter<TV> {ThrowErr = true});
var ex = Assert.Throws<IgniteException>(() => ValidateQueryResults(cache, qry, exp, keepBinary));
Assert.AreEqual(ScanQueryFilter<TV>.ErrMessage, ex.Message);
}
/// <summary>
/// Checks scan query with partitions.
/// </summary>
/// <param name="loc">Local query flag.</param>
/// <param name="keepBinary">Keep binary flag.</param>
private void CheckScanQueryPartitions<TV>(bool loc, bool keepBinary)
{
StopGrids();
StartGrids();
var cache = Cache();
int cnt = MaxItemCnt;
var aff = cache.Ignite.GetAffinity(CacheName);
var exp = PopulateCache(cache, loc, cnt, x => true); // populate outside the loop (slow)
for (var part = 0; part < aff.Partitions; part++)
{
//var exp0 = new HashSet<int>(exp.Where(x => aff.Partition(x) == part)); // filter expected keys
var exp0 = new HashSet<int>();
foreach (var x in exp)
if (aff.GetPartition(x) == part)
exp0.Add(x);
var qry = new ScanQuery<int, TV> { Partition = part };
ValidateQueryResults(cache, qry, exp0, keepBinary);
}
// Partitions with predicate
exp = PopulateCache(cache, loc, cnt, x => x < 50); // populate outside the loop (slow)
for (var part = 0; part < aff.Partitions; part++)
{
//var exp0 = new HashSet<int>(exp.Where(x => aff.Partition(x) == part)); // filter expected keys
var exp0 = new HashSet<int>();
foreach (var x in exp)
if (aff.GetPartition(x) == part)
exp0.Add(x);
var qry = new ScanQuery<int, TV>(new ScanQueryFilter<TV>()) { Partition = part };
ValidateQueryResults(cache, qry, exp0, keepBinary);
}
}
/// <summary>
/// Tests the distributed joins flag.
/// </summary>
[Test]
public void TestDistributedJoins()
{
var cache = GetIgnite().GetOrCreateCache<int, QueryPerson>(
new CacheConfiguration("replicatedCache")
{
QueryEntities = new[]
{
new QueryEntity(typeof(int), typeof(QueryPerson))
{
Fields = new[] {new QueryField("age", "int")}
}
}
});
const int count = 100;
cache.PutAll(Enumerable.Range(0, count).ToDictionary(x => x, x => new QueryPerson("Name" + x, x)));
// Test non-distributed join: returns partial results
var sql = "select T0.Age from QueryPerson as T0 " +
"inner join QueryPerson as T1 on ((? - T1.Age - 1) = T0._key)";
var res = cache.QueryFields(new SqlFieldsQuery(sql, count)).GetAll().Distinct().Count();
Assert.Greater(res, 0);
Assert.Less(res, count);
// Test distributed join: returns complete results
res = cache.QueryFields(new SqlFieldsQuery(sql, count) {EnableDistributedJoins = true})
.GetAll().Distinct().Count();
Assert.AreEqual(count, res);
}
/// <summary>
/// Tests the get configuration.
/// </summary>
[Test]
public void TestGetConfiguration()
{
var entity = Cache().GetConfiguration().QueryEntities.Single();
Assert.AreEqual(typeof(int), entity.Fields.Single(x => x.Name == "age").FieldType);
Assert.AreEqual(typeof(string), entity.Fields.Single(x => x.Name == "name").FieldType);
}
/// <summary>
/// Tests custom key and value field names.
/// </summary>
[Test]
public void TestCustomKeyValueFieldNames()
{
// Check select * with default config - does not include _key, _val.
var cache = Cache();
cache[1] = new QueryPerson("Joe", 48);
var row = cache.QueryFields(new SqlFieldsQuery("select * from QueryPerson")).GetAll()[0];
Assert.AreEqual(2, row.Count);
Assert.AreEqual(48, row[0]);
Assert.AreEqual("Joe", row[1]);
// Check select * with custom names - fields are included.
cache = GetIgnite().GetOrCreateCache<int, QueryPerson>(
new CacheConfiguration("customKeyVal")
{
QueryEntities = new[]
{
new QueryEntity(typeof(int), typeof(QueryPerson))
{
Fields = new[]
{
new QueryField("age", "int"),
new QueryField("FullKey", "int"),
new QueryField("FullVal", "QueryPerson")
},
KeyFieldName = "FullKey",
ValueFieldName = "FullVal"
}
}
});
cache[1] = new QueryPerson("John", 33);
row = cache.QueryFields(new SqlFieldsQuery("select * from QueryPerson")).GetAll()[0];
Assert.AreEqual(3, row.Count);
Assert.AreEqual(33, row[0]);
Assert.AreEqual(1, row[1]);
var person = (QueryPerson) row[2];
Assert.AreEqual("John", person.Name);
// Check explicit select.
row = cache.QueryFields(new SqlFieldsQuery("select FullKey from QueryPerson")).GetAll()[0];
Assert.AreEqual(1, row[0]);
}
/// <summary>
/// Tests query timeouts.
/// </summary>
[Test]
public void TestSqlQueryTimeout()
{
var cache = Cache();
PopulateCache(cache, false, 20000, x => true);
var sqlQry = new SqlQuery(typeof(QueryPerson), "WHERE age < 500 AND name like '%1%'")
{
Timeout = TimeSpan.FromMilliseconds(2)
};
// ReSharper disable once ReturnValueOfPureMethodIsNotUsed
var ex = Assert.Throws<CacheException>(() => cache.Query(sqlQry).ToArray());
Assert.IsTrue(ex.ToString().Contains("QueryCancelledException: The query was cancelled while executing."));
}
/// <summary>
/// Tests fields query timeouts.
/// </summary>
[Test]
public void TestSqlFieldsQueryTimeout()
{
var cache = Cache();
PopulateCache(cache, false, 20000, x => true);
var fieldsQry = new SqlFieldsQuery("SELECT * FROM QueryPerson WHERE age < 5000 AND name like '%0%'")
{
Timeout = TimeSpan.FromMilliseconds(3)
};
// ReSharper disable once ReturnValueOfPureMethodIsNotUsed
var ex = Assert.Throws<CacheException>(() => cache.QueryFields(fieldsQry).ToArray());
Assert.IsTrue(ex.ToString().Contains("QueryCancelledException: The query was cancelled while executing."));
}
/// <summary>
/// Validates the query results.
/// </summary>
/// <param name="cache">Cache.</param>
/// <param name="qry">Query.</param>
/// <param name="exp">Expected keys.</param>
/// <param name="keepBinary">Keep binary flag.</param>
private static void ValidateQueryResults(ICache<int, QueryPerson> cache, QueryBase qry, HashSet<int> exp,
bool keepBinary)
{
if (keepBinary)
{
var cache0 = cache.WithKeepBinary<int, IBinaryObject>();
using (var cursor = cache0.Query(qry))
{
HashSet<int> exp0 = new HashSet<int>(exp);
var all = new List<ICacheEntry<int, object>>();
foreach (var entry in cursor.GetAll())
{
all.Add(entry);
Assert.AreEqual(entry.Key.ToString(), entry.Value.GetField<string>("name"));
Assert.AreEqual(entry.Key, entry.Value.GetField<int>("age"));
exp0.Remove(entry.Key);
}
AssertMissingExpectedKeys(exp0, cache, all);
}
using (var cursor = cache0.Query(qry))
{
HashSet<int> exp0 = new HashSet<int>(exp);
var all = new List<ICacheEntry<int, object>>();
foreach (var entry in cursor)
{
all.Add(entry);
Assert.AreEqual(entry.Key.ToString(), entry.Value.GetField<string>("name"));
Assert.AreEqual(entry.Key, entry.Value.GetField<int>("age"));
exp0.Remove(entry.Key);
}
AssertMissingExpectedKeys(exp0, cache, all);
}
}
else
{
using (var cursor = cache.Query(qry))
{
HashSet<int> exp0 = new HashSet<int>(exp);
var all = new List<ICacheEntry<int, object>>();
foreach (var entry in cursor.GetAll())
{
all.Add(entry);
Assert.AreEqual(entry.Key.ToString(), entry.Value.Name);
Assert.AreEqual(entry.Key, entry.Value.Age);
exp0.Remove(entry.Key);
}
AssertMissingExpectedKeys(exp0, cache, all);
}
using (var cursor = cache.Query(qry))
{
HashSet<int> exp0 = new HashSet<int>(exp);
var all = new List<ICacheEntry<int, object>>();
foreach (var entry in cursor)
{
all.Add(entry);
Assert.AreEqual(entry.Key.ToString(), entry.Value.Name);
Assert.AreEqual(entry.Key, entry.Value.Age);
exp0.Remove(entry.Key);
}
AssertMissingExpectedKeys(exp0, cache, all);
}
}
}
/// <summary>
/// Asserts that all expected entries have been received.
/// </summary>
private static void AssertMissingExpectedKeys(ICollection<int> exp, ICache<int, QueryPerson> cache,
IList<ICacheEntry<int, object>> all)
{
if (exp.Count == 0)
return;
var sb = new StringBuilder();
var aff = cache.Ignite.GetAffinity(cache.Name);
foreach (var key in exp)
{
var part = aff.GetPartition(key);
sb.AppendFormat(
"Query did not return expected key '{0}' (exists: {1}), partition '{2}', partition nodes: ",
key, cache.Get(key) != null, part);
var partNodes = aff.MapPartitionToPrimaryAndBackups(part);
foreach (var node in partNodes)
sb.Append(node).Append(" ");
sb.AppendLine(";");
}
sb.Append("Returned keys: ");
foreach (var e in all)
sb.Append(e.Key).Append(" ");
sb.AppendLine(";");
Assert.Fail(sb.ToString());
}
/// <summary>
/// Populates the cache with random entries and returns expected results set according to filter.
/// </summary>
/// <param name="cache">The cache.</param>
/// <param name="cnt">Amount of cache entries to create.</param>
/// <param name="loc">Local query flag.</param>
/// <param name="expectedEntryFilter">The expected entry filter.</param>
/// <returns>Expected results set.</returns>
private static HashSet<int> PopulateCache(ICache<int, QueryPerson> cache, bool loc, int cnt,
Func<int, bool> expectedEntryFilter)
{
var rand = new Random();
var exp = new HashSet<int>();
var aff = cache.Ignite.GetAffinity(cache.Name);
var localNode = cache.Ignite.GetCluster().GetLocalNode();
for (var i = 0; i < cnt; i++)
{
var val = rand.Next(cnt);
cache.Put(val, new QueryPerson(val.ToString(), val));
if (expectedEntryFilter(val) && (!loc || aff.IsPrimary(localNode, val)))
exp.Add(val);
}
return exp;
}
}
/// <summary>
/// Person.
/// </summary>
public class QueryPerson
{
/// <summary>
/// Constructor.
/// </summary>
/// <param name="name">Name.</param>
/// <param name="age">Age.</param>
public QueryPerson(string name, int age)
{
Name = name;
Age = age % 2000;
Birthday = DateTime.UtcNow.AddYears(-Age);
}
/// <summary>
/// Name.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Age.
/// </summary>
public int Age { get; set; }
/// <summary>
/// Gets or sets the birthday.
/// </summary>
[QuerySqlField] // Enforce Timestamp serialization
public DateTime Birthday { get; set; }
}
/// <summary>
/// Query filter.
/// </summary>
[Serializable]
public class ScanQueryFilter<TV> : ICacheEntryFilter<int, TV>
{
// Error message
public const string ErrMessage = "Error in ScanQueryFilter.Invoke";
// Error flag
public bool ThrowErr { get; set; }
/** <inheritdoc /> */
public bool Invoke(ICacheEntry<int, TV> entry)
{
if (ThrowErr)
throw new Exception(ErrMessage);
return entry.Key < 50;
}
}
/// <summary>
/// binary query filter.
/// </summary>
public class BinarizableScanQueryFilter<TV> : ScanQueryFilter<TV>, IBinarizable
{
/** <inheritdoc /> */
public void WriteBinary(IBinaryWriter writer)
{
var w = writer.GetRawWriter();
w.WriteBoolean(ThrowErr);
}
/** <inheritdoc /> */
public void ReadBinary(IBinaryReader reader)
{
var r = reader.GetRawReader();
ThrowErr = r.ReadBoolean();
}
}
/// <summary>
/// Filter that can't be serialized.
/// </summary>
public class InvalidScanQueryFilter<TV> : ScanQueryFilter<TV>, IBinarizable
{
public void WriteBinary(IBinaryWriter writer)
{
throw new BinaryObjectException("Expected");
}
public void ReadBinary(IBinaryReader reader)
{
throw new BinaryObjectException("Expected");
}
}
}
| |
using ReactNative.Bridge;
using System;
using System.Globalization;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Reactive.Disposables;
using System.Threading;
using System.Threading.Tasks;
#if WINDOWS_UWP
using Windows.UI.Core;
#endif
using static System.FormattableString;
namespace ReactNative.DevSupport
{
/// <summary>
/// Helper class for debug server running in the host machine.
/// </summary>
sealed class DevServerHelper : IDisposable
{
private const string DeviceLocalhost = "localhost:8081";
private const string BundleUrlFormat = "http://{0}/{1}.bundle?platform=windows&dev={2}&hot={3}";
private const string SourceMapUrlFormat = "http://{0}/{1}.map?platform=windows&dev={2}&hot={3}";
private const string LaunchDevToolsCommandUrlFormat = "http://{0}/launch-js-devtools";
private const string OnChangeEndpointUrlFormat = "http://{0}/onchange";
private const string WebsocketProxyUrlFormat = "ws://{0}/debugger-proxy?role=client";
private const string PackagerStatusUrlFormat = "http://{0}/status";
private const string PackagerOkStatus = "packager-status:running";
private const int LongPollFailureDelayMs = 5000;
private readonly DevInternalSettings _settings;
private readonly HttpClient _client;
/// <summary>
/// Instantiates the <see cref="DevServerHelper"/>.
/// </summary>
/// <param name="settings">The settings.</param>
public DevServerHelper(DevInternalSettings settings)
{
_settings = settings;
_client = new HttpClient();
}
/// <summary>
/// The JavaScript debugging proxy URL.
/// </summary>
public string WebSocketProxyUrl
{
get
{
return string.Format(CultureInfo.InvariantCulture, WebSocketProxyUrl, DebugServerHost);
}
}
/// <summary>
/// The host to use when connecting to the bundle server.
/// </summary>
private string DebugServerHost
{
get
{
return _settings.DebugServerHost ?? DeviceLocalhost;
}
}
/// <summary>
/// Signals whether to enable dev mode when requesting JavaScript bundles.
/// </summary>
private bool IsJavaScriptDevModeEnabled
{
get
{
return _settings.IsJavaScriptDevModeEnabled;
}
}
/// <summary>
/// Signals whether hot module replacement is enabled.
/// </summary>
private bool IsHotModuleReplacementEnabled
{
get
{
return _settings.IsHotModuleReplacementEnabled;
}
}
/// <summary>
/// The Websocket proxy URL.
/// </summary>
public string WebsocketProxyUrl
{
get
{
return string.Format(CultureInfo.InvariantCulture, WebsocketProxyUrlFormat, DebugServerHost);
}
}
private string JavaScriptProxyHost
{
get
{
return DeviceLocalhost;
}
}
/// <summary>
/// Download the latest bundle into a local stream.
/// </summary>
/// <param name="jsModulePath">The module path.</param>
/// <param name="outputStream">The output stream.</param>
/// <param name="token">A token to cancel the request.</param>
/// <returns>A task to await completion.</returns>
public async Task DownloadBundleFromUrlAsync(string jsModulePath, Stream outputStream, CancellationToken token)
{
var bundleUrl = GetSourceUrl(jsModulePath);
using (var response = await _client.GetAsync(bundleUrl, token).ConfigureAwait(false))
{
if (!response.IsSuccessStatusCode)
{
var body = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
var exception = DebugServerException.Parse(body);
if (exception == null)
{
var nl = Environment.NewLine;
exception = new DebugServerException(
"The development server returned response error code: " +
Invariant($"{response.StatusCode}{nl}{nl}URL: {bundleUrl}{nl}{nl}Body:{nl}{body}"));
}
throw exception;
}
await response.Content.CopyToAsync(outputStream).ConfigureAwait(false);
}
}
/// <summary>
/// Checks if the packager is running.
/// </summary>
/// <param name="token">A token to cancel the request.</param>
/// <returns>A task to await the packager status.</returns>
public async Task<bool> IsPackagerRunningAsync(CancellationToken token)
{
var statusUrl = CreatePackagerStatusUrl(DebugServerHost);
try
{
using (var response = await _client.GetAsync(statusUrl, token).ConfigureAwait(false))
{
if (!response.IsSuccessStatusCode)
{
return false;
}
var body = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
return body == PackagerOkStatus;
}
}
catch
{
return false;
}
}
/// <summary>
/// Start the bundle change polling service.
/// </summary>
/// <param name="onServerContentChanged">
/// Callback for when the bundle content changes.
/// </param>
/// <returns>A disposable to use to stop polling.</returns>
public IDisposable StartPollingOnChangeEndpoint(Action onServerContentChanged)
{
var disposable = new CancellationDisposable();
var task = Task.Run(async () =>
{
var onChangePollingClient = new HttpClient();
onChangePollingClient.DefaultRequestHeaders.Connection.Add("keep-alive");
while (!disposable.IsDisposed)
{
var onChangeUrl = CreateOnChangeEndpointUrl(DebugServerHost);
try
{
using (var response = await onChangePollingClient.GetAsync(onChangeUrl, disposable.Token).ConfigureAwait(false))
{
if (response.StatusCode == HttpStatusCode.ResetContent)
{
#if WINDOWS_UWP
DispatcherHelpers.RunOnDispatcher(new DispatchedHandler(onServerContentChanged));
#else
DispatcherHelpers.RunOnDispatcher(onServerContentChanged);
#endif
}
}
}
catch (OperationCanceledException)
when (disposable.IsDisposed)
{
}
catch
{
await Task.Delay(LongPollFailureDelayMs).ConfigureAwait(false);
}
}
});
return disposable;
}
/// <summary>
/// Launch the developer tools.
/// </summary>
public async Task LaunchDevToolsAsync(CancellationToken token)
{
var url = CreateLaunchDevToolsCommandUrl();
await _client.GetAsync(url, token).ConfigureAwait(false);
// Ignore response, nothing to report here.
}
/// <summary>
/// Get the source map URL for the JavaScript bundle.
/// </summary>
/// <param name="mainModuleName">The main module name.</param>
/// <returns>The source map URL.</returns>
public string GetSourceMapUrl(string mainModuleName)
{
return string.Format(
CultureInfo.InvariantCulture,
SourceMapUrlFormat,
DebugServerHost,
mainModuleName,
IsJavaScriptDevModeEnabled ? "true" : "false",
IsHotModuleReplacementEnabled ? "true" : "false");
}
/// <summary>
/// Get the source URL for the JavaScript bundle.
/// </summary>
/// <param name="mainModuleName">The main module name.</param>
/// <returns>The source URL.</returns>
public string GetSourceUrl(string mainModuleName)
{
return string.Format(
CultureInfo.InvariantCulture,
BundleUrlFormat,
DebugServerHost,
mainModuleName,
IsJavaScriptDevModeEnabled ? "true" : "false",
IsHotModuleReplacementEnabled ? "true" : "false");
}
/// <summary>
/// Gets the bundle URL for remote debugging.
/// </summary>
/// <param name="mainModuleName">The main module name.</param>
/// <returns>The bundle URL.</returns>
public string GetJavaScriptBundleUrlForRemoteDebugging(string mainModuleName)
{
return string.Format(
CultureInfo.InvariantCulture,
BundleUrlFormat,
JavaScriptProxyHost,
mainModuleName,
IsJavaScriptDevModeEnabled ? "true" : "false",
IsHotModuleReplacementEnabled ? "true" : "false");
}
/// <summary>
/// Disposes the <see cref="DevServerHelper"/>.
/// </summary>
public void Dispose()
{
_client.Dispose();
}
private string CreatePackagerStatusUrl(string host)
{
return string.Format(CultureInfo.InvariantCulture, PackagerStatusUrlFormat, host);
}
private string CreateOnChangeEndpointUrl(string host)
{
return string.Format(CultureInfo.InvariantCulture, OnChangeEndpointUrlFormat, host);
}
private string CreateLaunchDevToolsCommandUrl()
{
return string.Format(
CultureInfo.InvariantCulture,
LaunchDevToolsCommandUrlFormat,
DebugServerHost);
}
}
}
| |
// This file was created automatically, do not modify the contents of this file.
// ReSharper disable InvalidXmlDocComment
// ReSharper disable InconsistentNaming
// ReSharper disable CheckNamespace
// ReSharper disable MemberCanBePrivate.Global
using System;
using System.Runtime.InteropServices;
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\GameFramework\RootMotionSource.h:211
namespace UnrealEngine
{
public partial class FRootMotionSource : NativeStructWrapper
{
public FRootMotionSource(IntPtr NativePointer, bool IsRef = false) : base(NativePointer, IsRef)
{
}
public FRootMotionSource() :
base(E_CreateStruct_FRootMotionSource(), false)
{
}
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern byte E_PROP_FRootMotionSource_AccumulateMode_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_FRootMotionSource_AccumulateMode_SET(IntPtr Ptr, byte Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern bool E_PROP_FRootMotionSource_bInLocalSpace_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_FRootMotionSource_bInLocalSpace_SET(IntPtr Ptr, bool Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern bool E_PROP_FRootMotionSource_bNeedsSimulatedCatchup_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_FRootMotionSource_bNeedsSimulatedCatchup_SET(IntPtr Ptr, bool Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern float E_PROP_FRootMotionSource_CurrentTime_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_FRootMotionSource_CurrentTime_SET(IntPtr Ptr, float Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern float E_PROP_FRootMotionSource_Duration_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_FRootMotionSource_Duration_SET(IntPtr Ptr, float Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr E_PROP_FRootMotionSource_FinishVelocityParams_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_FRootMotionSource_FinishVelocityParams_SET(IntPtr Ptr, IntPtr Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern StringWrapper E_PROP_FRootMotionSource_InstanceName_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_FRootMotionSource_InstanceName_SET(IntPtr Ptr, string Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern float E_PROP_FRootMotionSource_PreviousTime_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_FRootMotionSource_PreviousTime_SET(IntPtr Ptr, float Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr E_PROP_FRootMotionSource_Settings_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_FRootMotionSource_Settings_SET(IntPtr Ptr, IntPtr Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern float E_PROP_FRootMotionSource_StartTime_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_FRootMotionSource_StartTime_SET(IntPtr Ptr, float Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr E_PROP_FRootMotionSource_Status_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_FRootMotionSource_Status_SET(IntPtr Ptr, IntPtr Value);
#region DLLInmport
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr E_CreateStruct_FRootMotionSource();
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_FRootMotionSource_CheckTimeOut(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr E_FRootMotionSource_Clone(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern float E_FRootMotionSource_GetDuration(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern float E_FRootMotionSource_GetStartTime(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern float E_FRootMotionSource_GetTime(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern bool E_FRootMotionSource_IsActive(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern bool E_FRootMotionSource_IsStartTimeValid(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern bool E_FRootMotionSource_IsTimeOutEnabled(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern bool E_FRootMotionSource_Matches(IntPtr self, IntPtr other);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern bool E_FRootMotionSource_MatchesAndHasSameState(IntPtr self, IntPtr other);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_FRootMotionSource_PrepareRootMotion(IntPtr self, float simulationTime, float movementTickTime, IntPtr character, IntPtr moveComponent);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_FRootMotionSource_SetTime(IntPtr self, float newTime);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern StringWrapper E_FRootMotionSource_ToSimpleString(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern bool E_FRootMotionSource_UpdateStateFrom(IntPtr self, IntPtr sourceToTakeStateFrom, bool bMarkForSimulatedCatchup);
#endregion
#region Property
public ERootMotionAccumulateMode AccumulateMode
{
get => (ERootMotionAccumulateMode)E_PROP_FRootMotionSource_AccumulateMode_GET(NativePointer);
set => E_PROP_FRootMotionSource_AccumulateMode_SET(NativePointer, (byte)value);
}
public bool bInLocalSpace
{
get => E_PROP_FRootMotionSource_bInLocalSpace_GET(NativePointer);
set => E_PROP_FRootMotionSource_bInLocalSpace_SET(NativePointer, value);
}
/// <summary>
/// True when this RootMotionSource has been marked for simulated catchup - this Simulated version
/// <para>of the Source needs to catch up to where it was before being corrected by authoritative version. </para>
/// </summary>
public bool bNeedsSimulatedCatchup
{
get => E_PROP_FRootMotionSource_bNeedsSimulatedCatchup_GET(NativePointer);
set => E_PROP_FRootMotionSource_bNeedsSimulatedCatchup_SET(NativePointer, value);
}
public float CurrentTime
{
get => E_PROP_FRootMotionSource_CurrentTime_GET(NativePointer);
set => E_PROP_FRootMotionSource_CurrentTime_SET(NativePointer, value);
}
public float Duration
{
get => E_PROP_FRootMotionSource_Duration_GET(NativePointer);
set => E_PROP_FRootMotionSource_Duration_SET(NativePointer, value);
}
public FRootMotionFinishVelocitySettings FinishVelocityParams
{
get => E_PROP_FRootMotionSource_FinishVelocityParams_GET(NativePointer);
set => E_PROP_FRootMotionSource_FinishVelocityParams_SET(NativePointer, value);
}
public string InstanceName
{
get => E_PROP_FRootMotionSource_InstanceName_GET(NativePointer);
set => E_PROP_FRootMotionSource_InstanceName_SET(NativePointer, value);
}
public float PreviousTime
{
get => E_PROP_FRootMotionSource_PreviousTime_GET(NativePointer);
set => E_PROP_FRootMotionSource_PreviousTime_SET(NativePointer, value);
}
public FRootMotionSourceSettings Settings
{
get => E_PROP_FRootMotionSource_Settings_GET(NativePointer);
set => E_PROP_FRootMotionSource_Settings_SET(NativePointer, value);
}
public float StartTime
{
get => E_PROP_FRootMotionSource_StartTime_GET(NativePointer);
set => E_PROP_FRootMotionSource_StartTime_SET(NativePointer, value);
}
public FRootMotionSourceStatus Status
{
get => E_PROP_FRootMotionSource_Status_GET(NativePointer);
set => E_PROP_FRootMotionSource_Status_SET(NativePointer, value);
}
#endregion
#region ExternMethods
/// <summary>
/// Checks if this source has timed out and marks for removal if necessary
/// </summary>
public virtual void CheckTimeOut()
=> E_FRootMotionSource_CheckTimeOut(this);
/// <summary>
/// </summary>
/// <return>newly</return>
public virtual FRootMotionSource Clone()
=> E_FRootMotionSource_Clone(this);
/// <summary>
/// </summary>
/// <return>the</return>
public float GetDuration()
=> E_FRootMotionSource_GetDuration(this);
/// <summary>
/// </summary>
/// <return>the</return>
public float GetStartTime()
=> E_FRootMotionSource_GetStartTime(this);
/// <summary>
/// </summary>
/// <return>the</return>
public float GetTime()
=> E_FRootMotionSource_GetTime(this);
/// <summary>
/// True when this RootMotionSource should be affecting root motion
/// </summary>
public virtual bool IsActive()
=> E_FRootMotionSource_IsActive(this);
/// <summary>
/// </summary>
/// <return>whether</return>
public bool IsStartTimeValid()
=> E_FRootMotionSource_IsStartTimeValid(this);
/// <summary>
/// </summary>
/// <return>whether</return>
public virtual bool IsTimeOutEnabled()
=> E_FRootMotionSource_IsTimeOutEnabled(this);
/// <summary>
/// This is used for networking when clients receive RootMotionSource data from the server and need
/// <para>to decide which local RootMotionSource to compare and apply the corrections to. </para>
/// This is required due to RootMotionSources in general being added independently on server and
/// <para>clients, not needing to know about each other by default. </para>
/// For well-networked RootMotionSources, any given FRootMotionSource child class could implement
/// <para>their own unique ID and simply use that in the Matches check. This "heuristic-style" default </para>
/// was chosen to simplify addition of new RootMotionSources, and assumes that in a networked setting
/// <para>a given RootMotionSource won't be applied many times in a given frame by the same instigator </para>
/// to the same target with the exact same parameters.
/// <para>Guaranteed uniqueness would also require a strict application order ("RootMotionSources can only </para>
/// be added on Authority") or a prediction-based setup ("Apply on Autonomous and Simulated predictively,
/// <para>then apply on Authority and confirm, and if Authority doesn't confirm remove them"). We avoid </para>
/// that synchronization complexity for now.
/// <para>See UCharacterMovementComponent::ConvertRootMotionServerIDsToLocalIDs </para>
/// Should be overridden by child classes, as default implementation only contains basic equivalency checks
/// </summary>
/// <return>Whether</return>
public virtual bool Matches(FRootMotionSource other)
=> E_FRootMotionSource_Matches(this, other);
/// <summary>
/// Checks that it Matches() and has the same state (time, track position, etc.)
/// </summary>
public virtual bool MatchesAndHasSameState(FRootMotionSource other)
=> E_FRootMotionSource_MatchesAndHasSameState(this, other);
/// <summary>
/// Generates the RootMotion for this Source, can be used for both "live" generation
/// <para>or for playback (client prediction correction, simulated proxies, etc.) </para>
/// Examples:
/// <para>- Animation RootMotionSources use Time as track time into AnimMontage and </para>
/// extract the root motion from AnimMontage chunk of time (Position,Position+DeltaTime)
/// <para>- ConstantForce source uses Time as the time into the application </para>
/// so if its duration ends halfway through the frame it knows how much root
/// <para>motion it should have applied </para>
/// - Spline/curve-based sources use Time for knowing where on spline/curve to extract
/// <para>from </para>
/// </summary>
/// <param name="simulationTime">How far forward in time to simulate root motion</param>
/// <param name="movementTickTime">How much time the movement is going to take that this is being prepared for</param>
public virtual void PrepareRootMotion(float simulationTime, float movementTickTime, ACharacter character, UCharacterMovementComponent moveComponent)
=> E_FRootMotionSource_PrepareRootMotion(this, simulationTime, movementTickTime, character, moveComponent);
/// <summary>
/// Set the CurrentTime of this source. Use this setter so that sources based on duration can get correctly marked for end
/// </summary>
public virtual void SetTime(float newTime)
=> E_FRootMotionSource_SetTime(this, newTime);
public virtual string ToSimpleString()
=> E_FRootMotionSource_ToSimpleString(this);
/// <summary>
/// Mainly for server correction purposes - update this Source's state from
/// <para>another's, usually the authoritative state from the server's version of the Source </para>
/// denotes a complete failure, and the Source will then be marked for removal.
/// <para>We need to remove since we don't have a way of reverting partial updates </para>
/// depending on where the update failed.
/// </summary>
/// <param name="bMarkForSimulatedCatchup">sets the source for needing to "catch up" to current state next Prepare</param>
/// <return>Whether</return>
public virtual bool UpdateStateFrom(FRootMotionSource sourceToTakeStateFrom, bool bMarkForSimulatedCatchup)
=> E_FRootMotionSource_UpdateStateFrom(this, sourceToTakeStateFrom, bMarkForSimulatedCatchup);
#endregion
public static implicit operator IntPtr(FRootMotionSource self)
{
return self?.NativePointer ?? IntPtr.Zero;
}
public static implicit operator FRootMotionSource(IntPtr adress)
{
return adress == IntPtr.Zero ? null : new FRootMotionSource(adress, false);
}
}
}
| |
using AllReady.Areas.Admin.Features.Itineraries;
using AllReady.Models;
using MediatR;
using Moq;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Xunit;
namespace AllReady.UnitTest.Areas.Admin.Features.Itineraries
{
public class ItineraryDetailQueryHandlerShould : InMemoryContextTest
{
protected override void LoadTestData()
{
var htb = new Organization
{
Name = "Humanitarian Toolbox",
LogoUrl = "http://www.htbox.org/upload/home/ht-hero.png",
WebUrl = "http://www.htbox.org",
Campaigns = new List<Campaign>()
};
var firePrev = new Campaign
{
Name = "Neighborhood Fire Prevention Days",
ManagingOrganization = htb
};
htb.Campaigns.Add(firePrev);
var queenAnne = new Event
{
Id = 1,
Name = "Queen Anne Fire Prevention Day",
Campaign = firePrev,
CampaignId = firePrev.Id,
StartDateTime = new DateTime(2015, 7, 4, 10, 0, 0).ToUniversalTime(),
EndDateTime = new DateTime(2015, 12, 31, 15, 0, 0).ToUniversalTime(),
Location = new Location { Id = 1 },
RequiredSkills = new List<EventSkill>(),
EventType = EventType.Itinerary
};
var itinerary = new Itinerary
{
Event = queenAnne,
Name = "1st Itinerary",
Id = 1,
Date = new DateTime(2016, 07, 01),
StartLocation = new Location{ Id = 1 },
EndLocation = new Location { Id = 2}
};
var volunteerTask = new VolunteerTask
{
Id = 1,
Event = queenAnne,
Name = "A Task",
StartDateTime = new DateTime(2015, 7, 4, 10, 0, 0).ToUniversalTime(),
EndDateTime = new DateTime(2015, 7, 4, 18, 0, 0).ToUniversalTime()
};
var user1 = new ApplicationUser
{
Id = Guid.NewGuid().ToString(),
Email = "Smith@example.com",
LastName = "Smith",
FirstName = "Bob"
};
var user2 = new ApplicationUser
{
Id = Guid.NewGuid().ToString(),
Email = "Jones@example.com",
LastName = "Jones",
FirstName = "Carol"
};
var user3 = new ApplicationUser
{
Id = Guid.NewGuid().ToString(),
Email = "Gordon@example.com",
LastName = "Gordon",
FirstName = "Steve"
};
var volunteerTaskSignup1 = new VolunteerTaskSignup
{
Id = 1,
User = user1,
VolunteerTask = volunteerTask,
Itinerary = itinerary,
IsTeamLead = true
};
var volunteerTaskSignup2 = new VolunteerTaskSignup
{
Id = 2,
User = user2,
VolunteerTask = volunteerTask,
Itinerary = itinerary
};
var volunteerTaskSignup3 = new VolunteerTaskSignup
{
Id = 3,
User = user3,
VolunteerTask = volunteerTask,
Itinerary = itinerary
};
var request = new Request
{
RequestId = Guid.NewGuid(),
Name = "Request 1",
Address = "Street Name 1",
City = "Seattle"
};
var itineraryReq = new ItineraryRequest
{
Request = request,
Itinerary = itinerary
};
Context.Organizations.Add(htb);
Context.Campaigns.Add(firePrev);
Context.Events.Add(queenAnne);
Context.Itineraries.Add(itinerary);
Context.VolunteerTasks.Add(volunteerTask);
Context.Users.Add(user1);
Context.Users.Add(user2);
Context.Users.Add(user3);
Context.Requests.Add(request);
Context.ItineraryRequests.Add(itineraryReq);
Context.VolunteerTaskSignups.Add(volunteerTaskSignup1);
Context.VolunteerTaskSignups.Add(volunteerTaskSignup2);
Context.VolunteerTaskSignups.Add(volunteerTaskSignup3);
Context.SaveChanges();
}
[Fact]
public async Task ItineraryExists_ReturnsItinerary()
{
var query = new ItineraryDetailQuery { ItineraryId = 1 };
var handler = new ItineraryDetailQueryHandler(Context, Mock.Of<IMediator>());
var result = await handler.Handle(query);
Assert.NotNull(result);
}
[Fact]
public async Task ItineraryDoesNotExist_ReturnsNull()
{
var query = new ItineraryDetailQuery();
var handler = new ItineraryDetailQueryHandler(Context, Mock.Of<IMediator>());
var result = await handler.Handle(query);
Assert.Null(result);
}
[Fact]
public async Task ItineraryQueryLoadsItineraryDetails()
{
var query = new ItineraryDetailQuery { ItineraryId = 1 };
var handler = new ItineraryDetailQueryHandler(Context, Mock.Of<IMediator>());
var result = await handler.Handle(query);
Assert.Equal(1, result.Id);
Assert.Equal("1st Itinerary", result.Name);
Assert.Equal(new DateTime(2016, 07, 01), result.Date);
}
[Fact]
public async Task ItineraryQueryLoadsEventDetails()
{
var query = new ItineraryDetailQuery { ItineraryId = 1 };
var handler = new ItineraryDetailQueryHandler(Context, Mock.Of<IMediator>());
var result = await handler.Handle(query);
Assert.Equal("Queen Anne Fire Prevention Day", result.EventName);
}
[Fact]
public async Task ItineraryQueryLoadsOrganizationId()
{
var query = new ItineraryDetailQuery { ItineraryId = 1 };
var handler = new ItineraryDetailQueryHandler(Context, Mock.Of<IMediator>());
var result = await handler.Handle(query);
Assert.Equal(1, result.OrganizationId);
}
[Fact]
public async Task ItineraryQueryLoadsCampaignName()
{
var query = new ItineraryDetailQuery { ItineraryId = 1 };
var handler = new ItineraryDetailQueryHandler(Context, Mock.Of<IMediator>());
var result = await handler.Handle(query);
Assert.Equal("Neighborhood Fire Prevention Days", result.CampaignName);
}
[Fact]
public async Task ItineraryQueryLoadsTeamMembers()
{
var query = new ItineraryDetailQuery { ItineraryId = 1 };
var handler = new ItineraryDetailQueryHandler(Context, Mock.Of<IMediator>());
var result = await handler.Handle(query);
Assert.Equal(3, result.TeamMembers.Count);
// Team lead is first
Assert.True(result.TeamMembers[0].IsTeamLead);
// then ordered by LastName and FirstName
Assert.Equal("Gordon, Steve", result.TeamMembers[1].DisplayName);
Assert.Equal("Jones, Carol", result.TeamMembers[2].DisplayName);
}
[Fact]
public async Task ItineraryQueryLoadsRequests()
{
var query = new ItineraryDetailQuery { ItineraryId = 1 };
var handler = new ItineraryDetailQueryHandler(Context, Mock.Of<IMediator>());
var result = await handler.Handle(query);
Assert.Single(result.Requests);
Assert.Equal("Request 1", result.Requests[0].Name);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing.Printing;
using System.Drawing;
using System.Data;
namespace Factotum
{
class RsGrid : ReportSection
{
// If we couldn't fit the whole grid on a page, we need to keep track of
// where in the grid to start up again.
private int startRow;
private int startCol;
private int startWeldIdx; // The starting weld index for the current chunk of rows
private int curWeldIdx; // The current weld index
// This is about as narrow as we can make columns.
private const float colWidth = 36;
public RsGrid(MainReport report, ReportSectionRules rules, int subsections)
: base(report, rules, subsections)
{
startRow = 0;
startCol = 0;
startWeldIdx = 0;
curWeldIdx = 0;
}
// Incude the section only if we have a grid.
public override bool IsIncluded()
{
return (rpt.eInspection != null && rpt.eInspection.InspectionHasGrid
&& rpt.eGrid.GridStartRow != null & rpt.eGrid.GridStartCol != null
&& rpt.eGrid.GridEndRow != null & rpt.eGrid.GridEndCol != null);
}
public override bool CanFitSome(PrintPageEventArgs args, float Y)
{
// We only return true if we can fit the entire grid on the current page.
// This is also the perfect place to decide about page orientation.
// If the number of columns is such that fewer page widths will be required to cover
// the columns in landscape than in portrait, we want to set next page to landscape here.
// If we're not on the first page, we can definitely fit some.
// We'll also leave the orientation the same as prior pages.
if (startRow > 0 || startCol > 0) return true;
// See if we can fit ALL the columns on what's left of the current page and at least a few rows.
// Add 2 to the end column (1 for zero-based + 1 for header row/col)
// Changed to 15 -- it was still splitting tables too often...
int minRows = 15;
if (args.MarginBounds.Width > (rpt.eGrid.GridEndCol - rpt.eGrid.GridStartCol + 2) * colWidth)
{
if (args.MarginBounds.Bottom - Y - rpt.footerHeight > minRows * rowHeight())
return true;
else
return false; // Not too many columns, so keep portrait orientation
}
// We can't fit any on the current page. Decide on the orientation.
if (IsLandscapeBetter(args)) rpt.nextPageLandscape = true;
return false;
}
// Get the row height
private float rowHeight()
{
return rpt.smallTextFont.Height + 2;
}
// Figure out how many rows will fill a page in the current orientation.
private int rowsToFillPage(PrintPageEventArgs args, float curY)
{
return (int)((args.MarginBounds.Bottom - curY - rpt.footerHeight) / rowHeight());
}
// Figure out how many columns will fill a page in the current orientation.
private int colsToFillPage(PrintPageEventArgs args)
{
return (int)(args.MarginBounds.Width / colWidth);
}
// We should be in portrait mode when this function is called.
private bool IsLandscapeBetter(PrintPageEventArgs args)
{
int cols = (int)rpt.eGrid.GridEndCol - (int)rpt.eGrid.GridStartCol + 1; // The data columns in the grid
int rows = (int)rpt.eGrid.GridEndRow - (int)rpt.eGrid.GridStartRow + 1; // The data rows in the grid
float width = args.MarginBounds.Width;
float height = args.MarginBounds.Height;
System.Diagnostics.Debug.Assert(height > width);
int portraitPages;
int landscapePages;
// First get the number of pages to cover all the columns for a single chunk of rows.
// Subtract off a column width in the denominator for the row heading column
int portraitPagesToSpanCols = (int)(cols * colWidth / (width - colWidth) + 1);
int landscapePagesToSpanCols = (int) (cols * colWidth / (height - colWidth) + 1);
float rowsPerPortraitPage = (args.MarginBounds.Height - rpt.footerHeight - rowHeight()) / rowHeight();
float rowsPerLandscapePage = (args.MarginBounds.Width - rpt.footerHeight - rowHeight()) / rowHeight();
portraitPages = portraitPagesToSpanCols * (int)(rows / rowsPerPortraitPage + 1);
landscapePages = landscapePagesToSpanCols * (int)(rows / rowsPerPortraitPage + 1);
// If it's a tie, keep it in portrait
return (landscapePages < portraitPages);
}
public override bool Print(PrintPageEventArgs args, float Y)
{
// The page orientation has been set already..
Graphics g = args.Graphics;
Graphics measure = args.PageSettings.PrinterSettings.CreateMeasurementGraphics();
int curX;
int startY = args.MarginBounds.Top;
int dataRows;
int dataCols;
bool fitAllRows;
bool fitAllCols;
bool sectionDone = false;
int padding = 5;
float curY;
// Update the section info variables for the grid. The weld locations and
// colors will depend on this.
rpt.eGrid.UpdateSectionInfoVars();
curY = (Y > args.MarginBounds.Top ? Y + padding : Y);
int gridCols = (int)rpt.eGrid.GridEndCol - (int)rpt.eGrid.GridStartCol + 1; // The data columns in the grid
int gridRows = (int)rpt.eGrid.GridEndRow - (int)rpt.eGrid.GridStartRow + 1; // The data rows in the grid
// Subtract 1 row and 1 col (headings)
// The data columns that will fit on the page
int dataColsToFit = colsToFillPage(args) - 1;
// The data rows that will fit on the page (this includes weld rows)
int dataRowsToFit = rowsToFillPage(args, curY) - 1;
// Get the weld info. Extra rows are added to the printed grid for welds.
int[] divRows;
int[] divTypes;
rpt.eGrid.GetGridDivisionInfo(out divRows, out divTypes);
int divisions = divRows.Length;
// Print the next chunk of columns
fitAllCols = (gridCols - startCol <= dataColsToFit);
fitAllRows = (gridRows - startRow + divisions <= dataRowsToFit);
// These will be used to size the arrays
dataCols = fitAllCols ? gridCols - startCol : dataColsToFit;
dataRows = fitAllRows ? gridRows - startRow : dataRowsToFit-divisions;
// Get an array with the subset of rows and columns that will fit on the page.
string[,] gridDataArray;
int[,] gridColorArray;
GetGridArray(startRow, startCol, dataRows, dataCols,
out gridDataArray, out gridColorArray);
curX = args.MarginBounds.Left + (int)((args.MarginBounds.Width - (dataCols + 1) * colWidth) / 2);
curY = DrawGridTable(gridDataArray, gridColorArray, divRows, divTypes, fitAllRows, dataRows, dataCols,
g, curX, curY, (int)colWidth, (int)rowHeight(), padding, rpt.boldSmallTextFont, rpt.smallTextFont);
// If the current column + cols per page < max cols per page,
// reset next column to zero after printing the chunk
if (fitAllRows)
{
if (fitAllCols)
{
// We're done.
rpt.nextPageLandscape = false;
sectionDone = true;
curY += padding;
hr(args, curY);
this.Y = curY;
}
else
{
// Leave start row as is.
this.startCol += dataCols;
this.curWeldIdx = this.startWeldIdx;
}
}
else
{
if (fitAllCols)
{
// We finished all the columns for this section of rows
this.startCol = 0;
this.startRow += dataRows;
this.startWeldIdx = this.curWeldIdx;
}
else
{
// We still have some columns for this section of rows
// leave start row as is.
this.startCol += dataCols;
this.curWeldIdx = this.startWeldIdx;
}
}
return sectionDone;
}
// Fill three arrays, one with text strings, one with integer colors, and one with weld indices
private void GetGridArray(int startRow, int startCol, int dataRows, int dataCols,
out string[,] gridDataArray, out int[,] gridColorArray)
{
// Grid row and column indices
int row; int col;
// Grid starting row and column (not necessarily zero)
int gridStartRow = (int)(rpt.eGrid.GridStartRow);
int gridStartCol = (int)(rpt.eGrid.GridStartCol);
// Measurement data
decimal? thick;
bool obstr;
bool empty;
bool error;
// Initialize output arrays
gridDataArray = new string[dataRows + 1, dataCols + 1];
gridColorArray = new int[dataRows + 1, dataCols + 1];
// The current datarow of the datatable and its index.
DataRow dr;
int drIdx = 0;
// Array row and column indices used by gridDataArray and gridColorArray
int aRow; int aCol;
DataTable measurements = EMeasurement.GetForGrid(rpt.eGrid.ID);
// Columns: 0:ID, 1:MeasurementRow, 2:MeasurementCol,
// 3:MeasurementThickness, 4:MeasurementIsObstruction, 5:MeasurementIsError
// Ordered by: MeasurementRow, MeasurementCol
// Fill in the heading row and column.
FillHeadings(startRow, startCol, dataRows, dataCols, gridDataArray, gridColorArray);
// Loop through the entire datatable
while (drIdx < measurements.Rows.Count)
{
dr = measurements.Rows[drIdx++];
row = Convert.ToInt32(dr[1]);
col = Convert.ToInt32(dr[2]);
// If the datarow is not in the range we're interested in, get the next one
if (row - gridStartRow < startRow || row - gridStartRow >= startRow + dataRows ||
col-gridStartCol < startCol || col-gridStartCol >= startCol + dataCols)
continue;
// If we didn't continue, we want to include the info in the array, so get the other data.
if (dr[3] == DBNull.Value) thick = null;
else thick = Convert.ToDecimal(dr[3]);
obstr = (bool)dr[4];
error = (bool)dr[5];
empty = (thick == null && !obstr && !error);
aRow = row - gridStartRow - startRow + 1;
aCol = col - gridStartCol - startCol + 1;
// fill in the text
if (obstr) gridDataArray[aRow, aCol] = "obst.";
else if (error) gridDataArray[aRow, aCol] = "error";
else if (empty) gridDataArray[aRow, aCol] = "empty";
else gridDataArray[aRow, aCol] = GetFormattedThickness(thick);
// fill in the color
gridColorArray[aRow, aCol] = GetTextColor(row - gridStartRow, col, obstr, empty, error, thick);
}
}
// Handle the heading row and column of the data and color arrays
private void FillHeadings(int startRow, int startCol, int dataRows, int dataCols,
string[,] gridDataArray, int[,] gridColorArray)
{
// Fill column headings
int col = startCol;
int? gridStartCol = rpt.eGrid.GridStartCol;
int? gridStartRow = rpt.eGrid.GridStartRow;
for (int c = 1; c <= dataCols; c++)
{
gridDataArray[0, c] = EMeasurement.GetColLabel((short)(col + gridStartCol));
gridColorArray[0, c] = Color.Black.ToArgb();
col++;
}
// Fill row headings
int row = startRow;
for (int r = 1; r <= dataRows; r++)
{
gridDataArray[r, 0] = (row+gridStartRow+1).ToString();
row++;
gridColorArray[r, 0] = Color.Black.ToArgb();
}
}
// Format a thickness value for display
private string GetFormattedThickness(decimal? number)
{
return number == null ? "N/A" :
string.Format("{0:0.000}", number);
}
// Get the color for the text at the given grid row/col
private int GetTextColor(int row, int col, bool obstr, bool empty, bool error, decimal? thick)
{
Color curColor = Color.Black;
if (error) curColor = Color.Black;
else if (obstr) curColor = Color.Black;
else if (empty) curColor = Color.Black;
else
{
ThicknessRange range =
rpt.eGrid.GetThicknessRange(row, (decimal)thick);
switch (range)
{
case ThicknessRange.BelowTscreen:
curColor = Color.Crimson;
break;
case ThicknessRange.TscreenToTnom:
curColor = Color.Green;
break;
case ThicknessRange.TnomTo120pct:
curColor = Color.Black;
break;
case ThicknessRange.Above120pctTnom:
curColor = Color.Blue;
break;
case ThicknessRange.Unknown:
curColor = Color.Magenta;
break;
}
}
return curColor.ToArgb();
}
// Draw a formatted table of UT grid data.
private float DrawGridTable(string[,] table, int[,] colors,
int[] divRows, int[] divTypes, bool fitAllRows, int dataRows, int dataCols,
Graphics g, float X, float Y, int colWidth, int rowHeight,
int padding, Font headingFont, Font dataFont)
{
// Note: the divRows[] array contains the indices of the rows immediately following a division
int gridStartRow = (int)rpt.eGrid.GridStartRow;
float curX;
float curY = Y;
Font curFont;
int totCols = dataCols + 1;
Brush tmpBrush;
for (int r = 0; r <= dataRows; r++)
{
// Reset the X coord each row.
curX = X;
// Insert a weld if needed -- Note: We need to subtract 1 because of the col header row
if ((curWeldIdx < divRows.Length) && r + startRow + gridStartRow - 1 == divRows[curWeldIdx])
{
tmpBrush = ((GridDividerTypeEnum)divTypes[curWeldIdx] == GridDividerTypeEnum.Weld ?
Brushes.Gray : Brushes.SlateBlue);
g.FillRectangle(tmpBrush, X, curY, colWidth * totCols, rowHeight / 2);
// Draw the text "Weld" roughly centered.
//g.DrawString("Weld", dataFont, Brushes.White, X + colWidth * (int)(totCols / 2), curY);
curY += rowHeight / 2;
curWeldIdx++;
}
// Alternate row background
if (r % 2 > 0) g.FillRectangle(Brushes.Beige, curX, curY, colWidth * totCols, rowHeight);
// horizontal grid line
g.DrawLine(Pens.Black, curX, curY, curX + colWidth * totCols, curY);
// Draw the conditionally formatted text
for (int c = 0; c <= dataCols; c++)
{
curFont = (r == 0 || c == 0 ? headingFont : dataFont);
Brush b = new SolidBrush(Color.FromArgb(colors[r, c]));
if (r == 0)
// center column headings
g.DrawString(table[r, c], curFont, b, curX +
(colWidth - g.MeasureString(table[r,c], headingFont).Width) / 2 - 2, curY);
else
g.DrawString(table[r, c], curFont, b, curX, curY);
curX += colWidth;
}
curY += rowHeight;
}
// Insert a weld if needed -- Note: We need to subtract 1 because of the col header row
if (curWeldIdx < divRows.Length && fitAllRows )
{
tmpBrush = ((GridDividerTypeEnum)divTypes[curWeldIdx] == GridDividerTypeEnum.Weld ?
Brushes.Gray : Brushes.SlateBlue);
g.FillRectangle(tmpBrush, X, curY, colWidth * totCols, rowHeight / 2);
// Draw the text "Weld" roughly centered.
//g.DrawString("Weld", dataFont, Brushes.White, X + colWidth * (int)(totCols / 2), curY);
curY += rowHeight / 2;
curWeldIdx++;
}
// horizontal grid line
g.DrawLine(Pens.Black, X, curY, X + colWidth * totCols, curY);
// vertical lines
g.DrawLine(Pens.Black, X, Y, X, curY);
g.DrawLine(Pens.Black, X + colWidth * totCols, Y, X + colWidth * totCols, curY);
return curY;
}
}
}
| |
/*
Copyright (c) 2004-2009 Deepak Nataraj. All rights reserved.
Redistribution and use in source and binary forms,
with or without modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
THIS SOFTWARE IS PROVIDED "AS IS" BY THE ABOVE COPYRIGHT HOLDER(S)
AND ALL OTHER CONTRIBUTORS 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 ABOVE COPYRIGHT HOLDER(S) OR ANY OTHER
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.Runtime.InteropServices;
using GOBaseLibrary.Interfaces;
namespace GOBaseLibrary.Common
{
[Serializable]
[ComVisible(false)]
public struct PriorityQueueItem<TValue, TPriority>
{
private TValue _value;
public TValue Value
{
get { return _value; }
}
private TPriority _priority;
public TPriority Priority
{
get { return _priority; }
}
public PriorityQueueItem(TValue val, TPriority pri)
{
this._value = val;
this._priority = pri;
}
}
[Serializable]
[ComVisible(false)]
public class PriorityQueue<TValue, TPriority> : ICollection,
IEnumerable<PriorityQueueItem<TValue, TPriority>>
{
private PriorityQueueItem<TValue, TPriority>[] items;
private const Int32 DefaultCapacity = 16;
private Int32 capacity;
private Int32 numItems;
private Comparison<TPriority> compareFunc;
/// <summary>
/// Initializes a new instance of the PriorityQueue class that is empty,
/// has the default initial capacity, and uses the default IComparer.
/// </summary>
public PriorityQueue()
: this(DefaultCapacity, Comparer<TPriority>.Default)
{
}
public PriorityQueue(Int32 initialCapacity)
: this(initialCapacity, Comparer<TPriority>.Default)
{
}
public PriorityQueue(IComparer<TPriority> comparer)
: this(DefaultCapacity, comparer)
{
}
public PriorityQueue(int initialCapacity, IComparer<TPriority> comparer)
{
Init(initialCapacity, new Comparison<TPriority>(comparer.Compare));
}
public PriorityQueue(Comparison<TPriority> comparison)
: this(DefaultCapacity, comparison)
{
}
public PriorityQueue(int initialCapacity, Comparison<TPriority> comparison)
{
Init(initialCapacity, comparison);
}
private void Init(int initialCapacity, Comparison<TPriority> comparison)
{
numItems = 0;
compareFunc = comparison;
SetCapacity(initialCapacity);
}
public int Count
{
get { return numItems; }
}
public int Capacity
{
get { return items.Length; }
set { SetCapacity(value); }
}
private void SetCapacity(int newCapacity)
{
int newCap = newCapacity;
if (newCap < DefaultCapacity)
newCap = DefaultCapacity;
// throw exception if newCapacity < NumItems
if (newCap < numItems)
throw new ArgumentOutOfRangeException("newCapacity", "New capacity is less than Count");
this.capacity = newCap;
if (items == null)
{
items = new PriorityQueueItem<TValue, TPriority>[newCap];
return;
}
// Resize the array.
Array.Resize<PriorityQueueItem<TValue, TPriority>>(ref items, newCap);
}
public void Enqueue(PriorityQueueItem<TValue, TPriority> newItem)
{
if (numItems == capacity)
{
// need to increase capacity
// grow by 50 percent
SetCapacity((3 * Capacity) / 2);
}
int i = numItems;
++numItems;
while ((i > 0) && (compareFunc(items[(i - 1) / 2].Priority, newItem.Priority) < 0))
{
items[i] = items[(i - 1) / 2];
i = (i - 1) / 2;
}
items[i] = newItem;
//if (!VerifyQueue())
//{
// Console.WriteLine("ERROR: Queue out of order!");
//}
}
public void Enqueue(TValue value, TPriority priority)
{
Enqueue(new PriorityQueueItem<TValue, TPriority>(value, priority));
}
private PriorityQueueItem<TValue, TPriority> RemoveAt(Int32 index)
{
PriorityQueueItem<TValue, TPriority> o = items[index];
--numItems;
// move the last item to fill the hole
PriorityQueueItem<TValue, TPriority> tmp = items[numItems];
// If you forget to clear this, you have a potential memory leak.
items[numItems] = default(PriorityQueueItem<TValue, TPriority>);
if (numItems > 0 && index != numItems)
{
// If the new item is greater than its parent, bubble up.
int i = index;
int parent = (i - 1) / 2;
while (compareFunc(tmp.Priority, items[parent].Priority) > 0)
{
items[i] = items[parent];
i = parent;
parent = (i - 1) / 2;
}
// if i == index, then we didn't move the item up
if (i == index)
{
// bubble down ...
while (i < (numItems) / 2)
{
int j = (2 * i) + 1;
if ((j < numItems - 1) && (compareFunc(items[j].Priority, items[j + 1].Priority) < 0))
{
++j;
}
if (compareFunc(items[j].Priority, tmp.Priority) <= 0)
{
break;
}
items[i] = items[j];
i = j;
}
}
// Be sure to store the item in its place.
items[i] = tmp;
}
//if (!VerifyQueue())
//{
// Console.WriteLine("ERROR: Queue out of order!");
//}
return o;
}
// Function to check that the queue is coherent.
public bool VerifyQueue()
{
int i = 0;
while (i < numItems / 2)
{
int leftChild = (2 * i) + 1;
int rightChild = leftChild + 1;
if (compareFunc(items[i].Priority, items[leftChild].Priority) < 0)
{
return false;
}
if (rightChild < numItems && compareFunc(items[i].Priority, items[rightChild].Priority) < 0)
{
return false;
}
++i;
}
return true;
}
public PriorityQueueItem<TValue, TPriority> Dequeue()
{
if (Count == 0)
throw new InvalidOperationException("The queue is empty");
return RemoveAt(0);
}
/// <summary>
/// Removes the item with the specified value from the queue.
/// The passed equality comparison is used.
/// </summary>
/// <param name="item">The item to be removed.</param>
/// <param name="comp">An object that implements the IEqualityComparer interface
/// for the type of item in the collection.</param>
public void Remove(TValue item, IEqualityComparer comparer)
{
// need to find the PriorityQueueItem that has the Data value of o
for (int index = 0; index < numItems; ++index)
{
if (comparer.Equals(item, items[index].Value))
{
RemoveAt(index);
return;
}
}
throw new ApplicationException("The specified itemm is not in the queue.");
}
/// <summary>
/// Removes the item with the specified value from the queue.
/// The default type comparison function is used.
/// </summary>
/// <param name="item">The item to be removed.</param>
public void Remove(TValue item)
{
Remove(item, EqualityComparer<TValue>.Default);
}
public PriorityQueueItem<TValue, TPriority> Peek()
{
if (Count == 0)
throw new InvalidOperationException("The queue is empty");
return items[0];
}
// Clear
public void Clear()
{
for (int i = 0; i < numItems; ++i)
{
items[i] = default(PriorityQueueItem<TValue, TPriority>);
}
numItems = 0;
TrimExcess();
}
/// <summary>
/// Set the capacity to the actual number of items, if the current
/// number of items is less than 90 percent of the current capacity.
/// </summary>
public void TrimExcess()
{
if (numItems < (float)0.9 * capacity)
{
SetCapacity(numItems);
}
}
// Contains
public bool Contains(TValue o)
{
foreach (PriorityQueueItem<TValue, TPriority> x in items)
{
if (x.Value == null)
continue;
if (x.Value.Equals(o))
return true;
IGossip rumor = (IGossip)x.Value;
if (rumor.Id == (o as IGossip).Id)
return true;
}
return false;
}
public void CopyTo(PriorityQueueItem<TValue, TPriority>[] array, int arrayIndex)
{
if (array == null)
throw new ArgumentNullException("array");
if (arrayIndex < 0)
throw new ArgumentOutOfRangeException("arrayIndex", "arrayIndex is less than 0.");
if (array.Rank > 1)
throw new ArgumentException("array is multidimensional.");
if (numItems == 0)
return;
if (arrayIndex >= array.Length)
throw new ArgumentException("arrayIndex is equal to or greater than the length of the array.");
if (numItems > (array.Length - arrayIndex))
throw new ArgumentException("The number of elements in the source ICollection is greater than the available space from arrayIndex to the end of the destination array.");
for (int i = 0; i < numItems; i++)
{
array[arrayIndex + i] = items[i];
}
}
#region ICollection Members
public void CopyTo(Array array, int index)
{
this.CopyTo((PriorityQueueItem<TValue, TPriority>[])array, index);
}
public bool IsSynchronized
{
get { return false; }
}
public object SyncRoot
{
get { return items.SyncRoot; }
}
#endregion
#region IEnumerable<PriorityQueueItem<TValue,TPriority>> Members
public IEnumerator<PriorityQueueItem<TValue, TPriority>> GetEnumerator()
{
for (int i = 0; i < numItems; i++)
{
yield return items[i];
}
}
#endregion
#region IEnumerable Members
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
}
}
| |
// ----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// ----------------------------------------------------------------------------
using System;
using System.Diagnostics;
using System.Globalization;
using System.Threading.Tasks;
using Windows.Security.Authentication.Web;
namespace Microsoft.WindowsAzure.MobileServices
{
/// <summary>
/// AuthenticationBroker for the Windows Store Platform that uses the Windows Store
/// <see cref="WebAuthenticationBroker"/> APIs.
/// </summary>
internal class AuthenticationBroker
{
/// <summary>
/// Begins a server-side authentication flow by navigating the
/// <see cref="WebAuthenticationBroker"/> to the <paramref name="startUrl"/>.
/// </summary>
/// <param name="startUrl">The URL that the browser-based control should
/// first navigate to in order to start the authenication flow.
/// </param>
/// <param name="endUrl">The URL that indicates the authentication flow has
/// completed. Upon being redirected to any URL that starts with the
/// endUrl, the browser-based control must stop navigating and
/// return the response data to the <see cref="AuthenticationBroker"/>.
/// </param>
/// <param name="useSingleSignOn">Indicates if single sign-on should be used so
/// that users do not have to re-enter his/her credentials every time.
/// </param>
/// <returns>
/// The response data from the authentication flow that contains a string of JSON
/// that represents a Mobile Services authentication token.
/// </returns>
/// <exception cref="InvalidOperationException">
/// Thrown if the user cancels the authentication flow or an error occurs during
/// the authentication flow.
/// </exception>
public async Task<string> AuthenticateAsync(Uri startUrl, Uri endUrl, bool useSingleSignOn)
{
WebAuthenticationResult result = await AuthenticateWithBroker(startUrl, endUrl, useSingleSignOn);
if (result.ResponseStatus != WebAuthenticationStatus.Success)
{
string message;
if (result.ResponseStatus == WebAuthenticationStatus.UserCancel)
{
message = "Authentication was cancelled by the user.";
}
else
{
message = $"Authentication failed with HTTP response code {result.ResponseErrorDetail}.";
}
throw new InvalidOperationException(message);
}
return GetTokenStringFromResult(result);
}
/// <summary>
/// Begins a server-side authentication flow by navigating the
/// <see cref="WebAuthenticationBroker"/> to the <paramref name="startUrl"/>.
/// Considers if the <paramref name="useSingleSignOn"/> is being used and calls the
/// correct overload of the <see cref="WebAuthenticationBroker"/>.
/// </summary>
/// <param name="startUrl">The URL that the browser-based control should
/// first navigate to in order to start the authenication flow.
/// </param>
/// <param name="endUrl">The URL that indicates the authentication flow has
/// completed. Upon being redirected to any URL that starts with the
/// <paramref name="endUrl"/>, the browser-based control must stop navigating and
/// return the response data to the <see cref="AuthenticationBroker"/>.
/// </param>
/// <param name="useSingleSignOn">Indicates if single sign-on should be used so
/// that users do not have to re-enter his/her credentials every time.
/// </param>
/// <returns>
/// The <see cref="WebAuthenticationResult"/> returned by the
/// <see cref="WebAuthenticationBroker"/>.
/// </returns>
private async Task<WebAuthenticationResult> AuthenticateWithBroker(Uri startUrl, Uri endUrl, bool useSingleSignOn)
{
Arguments.IsNotNull(startUrl, nameof(startUrl));
Arguments.IsNotNull(endUrl, nameof(endUrl));
WebAuthenticationResult result = null;
if (useSingleSignOn)
{
Uri ssoEndUri = WebAuthenticationBroker.GetCurrentApplicationCallbackUri();
Uri ssoStartUrl = GetUrlWithQueryStringParameter(startUrl, "sso_end_uri", ssoEndUri.AbsoluteUri);
result = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, ssoStartUrl);
}
else
{
result = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, startUrl, endUrl);
}
return result;
}
/// <summary>
/// Gets the JSON string that represents the Mobile Service authentication token
/// from the <see cref="WebAuthenticationResult"/>.
/// </summary>
/// <param name="result">The <see cref="WebAuthenticationResult"/> returned
/// from the <see cref="WebAuthenticationBroker"/>.</param>
/// <returns>
/// A JSON string that represents a Mobile Service authentication token.
/// </returns>
/// <exception cref="InvalidOperationException">
/// Thrown if the authentication flow resulted in an error message or an invalid response.
/// </exception>
private string GetTokenStringFromResult(WebAuthenticationResult result)
{
Arguments.IsNotNull(result, nameof(result));
if (result.ResponseStatus != WebAuthenticationStatus.Success)
{
throw new ArgumentException("Successful Web Authentication required", nameof(result));
}
string tokenString = null;
string responseData = result.ResponseData;
if (!string.IsNullOrEmpty(responseData))
{
tokenString = GetSubStringAfterMatch(responseData, "#token=");
}
if (string.IsNullOrEmpty(tokenString))
{
string errorString = GetSubStringAfterMatch(responseData, "#error=");
string message = (string.IsNullOrEmpty(errorString))
? "Invalid format of the authentication response."
: $"Login failed: {errorString}";
throw new InvalidOperationException(message);
}
return tokenString;
}
/// <summary>
/// Returns a substring from the <paramref name="stringToSearch"/> starting from
/// the first character after the <paramref name="matchString"/> if the
/// <paramref name="stringToSearch"/> contains the <paramref name="matchString"/>;
/// otherwise, returns <c>null</c>.
/// </summary>
/// <param name="stringToSearch">The string to search for the <paramref name="matchString"/>.
/// </param>
/// <param name="matchString">The string to look for in the <paramref name="stringToSearch"/>
/// </param>
/// <returns>The substring from <paramref name="stringToSearch"/> that follows the
/// <paramref name="matchString"/> if the <paramref name="stringToSearch"/> contains
/// the <paramref name="matchString"/>; otherwise, returns <c>null</c>.
/// </returns>
private string GetSubStringAfterMatch(string stringToSearch, string matchString)
{
Arguments.IsNotNull(stringToSearch, nameof(stringToSearch));
Arguments.IsNotNull(matchString, nameof(matchString));
string value = null;
int index = stringToSearch.IndexOf(matchString);
if (index > 0)
{
value = Uri.UnescapeDataString(stringToSearch.Substring(index + matchString.Length));
}
return value;
}
/// <summary>
/// Returns a URL that is equivalent to the <paramref name="url"/> provided but which
/// includes in the query string of the URL the <paramref name="queryParameter"/>
/// with the value given by <paramref name="queryValue"/>.
/// </summary>
/// <param name="url">The URL to add the query string parameter and value to.
/// </param>
/// <param name="queryParameter">The name of the query string parameter to add to
/// the URL.
/// </param>
/// <param name="queryValue">The value of the query string parameter to add to the URL.
/// </param>
/// <returns>
/// A URL that is equivalent to the <paramref name="url"/> provided but which
/// includes in the query string of the URL the <paramref name="queryParameter"/>
/// with the value given by <paramref name="queryValue"/>.
/// </returns>
internal Uri GetUrlWithQueryStringParameter(Uri url, string queryParameter, string queryValue)
{
Arguments.IsNotNull(url, nameof(url));
Arguments.IsNotNull(queryParameter, nameof(queryParameter));
Arguments.IsNotNull(queryValue, nameof(queryValue));
string queryParameterEscaped = Uri.EscapeDataString(queryParameter);
string queryValueEscaped = Uri.EscapeDataString(queryValue);
UriBuilder uriBuilder = new UriBuilder(url);
string queryToAppend = string.Format(CultureInfo.InvariantCulture, "{0}={1}", queryParameterEscaped, queryValueEscaped);
string query = uriBuilder.Query;
// Must strip off "?" prefix of query before setting it back to avoid "??" in the query.
// Because UriBuild.Query property (https://msdn.microsoft.com/en-us/library/system.uribuilder.query)
// getter starts with "?", but property setter starts without "?".
if (!string.IsNullOrEmpty(query) && query.Length > 1)
{
query = query.Substring(1) + "&" + queryToAppend;
}
else
{
query = queryToAppend;
}
uriBuilder.Query = query;
return uriBuilder.Uri;
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gagr = Google.Api.Gax.ResourceNames;
using gclv = Google.Cloud.Logging.V2;
namespace Google.Cloud.Logging.V2
{
public partial class DeleteLogRequest
{
/// <summary>
/// <see cref="gclv::LogName"/>-typed view over the <see cref="LogName"/> resource name property.
/// </summary>
public gclv::LogName LogNameAsLogName
{
get => string.IsNullOrEmpty(LogName) ? null : gclv::LogName.Parse(LogName, allowUnparsed: true);
set => LogName = value?.ToString() ?? "";
}
}
public partial class WriteLogEntriesRequest
{
/// <summary>
/// <see cref="gclv::LogName"/>-typed view over the <see cref="LogName"/> resource name property.
/// </summary>
public gclv::LogName LogNameAsLogName
{
get => string.IsNullOrEmpty(LogName) ? null : gclv::LogName.Parse(LogName, allowUnparsed: true);
set => LogName = value?.ToString() ?? "";
}
}
public partial class ListLogEntriesRequest
{
/// <summary>
/// <see cref="gagr::ProjectName"/>-typed view over the <see cref="ResourceNames"/> resource name property.
/// </summary>
public gax::ResourceNameList<gagr::ProjectName> ResourceNamesAsProjectNames
{
get => new gax::ResourceNameList<gagr::ProjectName>(ResourceNames, s => string.IsNullOrEmpty(s) ? null : gagr::ProjectName.Parse(s, allowUnparsed: true));
}
/// <summary>
/// <see cref="gagr::OrganizationName"/>-typed view over the <see cref="ResourceNames"/> resource name property.
/// </summary>
public gax::ResourceNameList<gagr::OrganizationName> ResourceNamesAsOrganizationNames
{
get => new gax::ResourceNameList<gagr::OrganizationName>(ResourceNames, s => string.IsNullOrEmpty(s) ? null : gagr::OrganizationName.Parse(s, allowUnparsed: true));
}
/// <summary>
/// <see cref="gagr::FolderName"/>-typed view over the <see cref="ResourceNames"/> resource name property.
/// </summary>
public gax::ResourceNameList<gagr::FolderName> ResourceNamesAsFolderNames
{
get => new gax::ResourceNameList<gagr::FolderName>(ResourceNames, s => string.IsNullOrEmpty(s) ? null : gagr::FolderName.Parse(s, allowUnparsed: true));
}
/// <summary>
/// <see cref="gagr::BillingAccountName"/>-typed view over the <see cref="ResourceNames"/> resource name
/// property.
/// </summary>
public gax::ResourceNameList<gagr::BillingAccountName> ResourceNamesAsBillingAccountNames
{
get => new gax::ResourceNameList<gagr::BillingAccountName>(ResourceNames, s => string.IsNullOrEmpty(s) ? null : gagr::BillingAccountName.Parse(s, allowUnparsed: true));
}
/// <summary>
/// <see cref="gax::IResourceName"/>-typed view over the <see cref="ResourceNames"/> resource name property.
/// </summary>
public gax::ResourceNameList<gax::IResourceName> ResourceNamesAsResourceNames
{
get => new gax::ResourceNameList<gax::IResourceName>(ResourceNames, s =>
{
if (string.IsNullOrEmpty(s))
{
return null;
}
if (gagr::ProjectName.TryParse(s, out gagr::ProjectName project))
{
return project;
}
if (gagr::OrganizationName.TryParse(s, out gagr::OrganizationName organization))
{
return organization;
}
if (gagr::FolderName.TryParse(s, out gagr::FolderName folder))
{
return folder;
}
if (gagr::BillingAccountName.TryParse(s, out gagr::BillingAccountName billingAccount))
{
return billingAccount;
}
return gax::UnparsedResourceName.Parse(s);
});
}
}
public partial class ListLogsRequest
{
/// <summary>
/// <see cref="gagr::ProjectName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::ProjectName ParentAsProjectName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::ProjectName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gagr::OrganizationName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::OrganizationName ParentAsOrganizationName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::OrganizationName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gagr::FolderName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::FolderName ParentAsFolderName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::FolderName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gagr::BillingAccountName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::BillingAccountName ParentAsBillingAccountName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::BillingAccountName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gax::IResourceName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gax::IResourceName ParentAsResourceName
{
get
{
if (string.IsNullOrEmpty(Parent))
{
return null;
}
if (gagr::ProjectName.TryParse(Parent, out gagr::ProjectName project))
{
return project;
}
if (gagr::OrganizationName.TryParse(Parent, out gagr::OrganizationName organization))
{
return organization;
}
if (gagr::FolderName.TryParse(Parent, out gagr::FolderName folder))
{
return folder;
}
if (gagr::BillingAccountName.TryParse(Parent, out gagr::BillingAccountName billingAccount))
{
return billingAccount;
}
return gax::UnparsedResourceName.Parse(Parent);
}
set => Parent = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gagr::ProjectName"/>-typed view over the <see cref="ResourceNames"/> resource name property.
/// </summary>
public gax::ResourceNameList<gagr::ProjectName> ResourceNamesAsProjectNames
{
get => new gax::ResourceNameList<gagr::ProjectName>(ResourceNames, s => string.IsNullOrEmpty(s) ? null : gagr::ProjectName.Parse(s, allowUnparsed: true));
}
/// <summary>
/// <see cref="gagr::OrganizationName"/>-typed view over the <see cref="ResourceNames"/> resource name property.
/// </summary>
public gax::ResourceNameList<gagr::OrganizationName> ResourceNamesAsOrganizationNames
{
get => new gax::ResourceNameList<gagr::OrganizationName>(ResourceNames, s => string.IsNullOrEmpty(s) ? null : gagr::OrganizationName.Parse(s, allowUnparsed: true));
}
/// <summary>
/// <see cref="gagr::FolderName"/>-typed view over the <see cref="ResourceNames"/> resource name property.
/// </summary>
public gax::ResourceNameList<gagr::FolderName> ResourceNamesAsFolderNames
{
get => new gax::ResourceNameList<gagr::FolderName>(ResourceNames, s => string.IsNullOrEmpty(s) ? null : gagr::FolderName.Parse(s, allowUnparsed: true));
}
/// <summary>
/// <see cref="gagr::BillingAccountName"/>-typed view over the <see cref="ResourceNames"/> resource name
/// property.
/// </summary>
public gax::ResourceNameList<gagr::BillingAccountName> ResourceNamesAsBillingAccountNames
{
get => new gax::ResourceNameList<gagr::BillingAccountName>(ResourceNames, s => string.IsNullOrEmpty(s) ? null : gagr::BillingAccountName.Parse(s, allowUnparsed: true));
}
/// <summary>
/// <see cref="gax::IResourceName"/>-typed view over the <see cref="ResourceNames"/> resource name property.
/// </summary>
public gax::ResourceNameList<gax::IResourceName> ResourceNamesAsResourceNames
{
get => new gax::ResourceNameList<gax::IResourceName>(ResourceNames, s =>
{
if (string.IsNullOrEmpty(s))
{
return null;
}
if (gagr::ProjectName.TryParse(s, out gagr::ProjectName project))
{
return project;
}
if (gagr::OrganizationName.TryParse(s, out gagr::OrganizationName organization))
{
return organization;
}
if (gagr::FolderName.TryParse(s, out gagr::FolderName folder))
{
return folder;
}
if (gagr::BillingAccountName.TryParse(s, out gagr::BillingAccountName billingAccount))
{
return billingAccount;
}
return gax::UnparsedResourceName.Parse(s);
});
}
}
}
| |
using Braintree.Exceptions;
using Braintree.Test;
using Braintree.TestUtil;
using NUnit.Framework;
using System;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Params = System.Collections.Generic.Dictionary<string, object>;
namespace Braintree.Tests.Integration
{
[TestFixture]
public class PaymentMethodIntegrationTest
{
private BraintreeGateway gateway;
private BraintreeGateway partnerMerchantGateway;
private BraintreeGateway oauthGateway;
private BraintreeService service;
[SetUp]
public void Setup()
{
gateway = new BraintreeGateway
{
Environment = Environment.DEVELOPMENT,
MerchantId = "integration_merchant_id",
PublicKey = "integration_public_key",
PrivateKey = "integration_private_key"
};
partnerMerchantGateway = new BraintreeGateway
(
Environment.DEVELOPMENT,
"integration_merchant_public_id",
"oauth_app_partner_user_public_key",
"oauth_app_partner_user_private_key"
);
oauthGateway = new BraintreeGateway
(
"client_id$development$integration_client_id",
"client_secret$development$integration_client_secret"
);
}
public void FraudProtectionEnterpriseSetup()
{
gateway = new BraintreeGateway
{
Environment = Environment.DEVELOPMENT,
MerchantId = "fraud_protection_enterprise_integration_merchant_id",
PublicKey = "fraud_protection_enterprise_integration_public_key",
PrivateKey = "fraud_protection_enterprise_integration_private_key"
};
service = new BraintreeService(gateway.Configuration);
}
[Test]
public void Create_CreatesPayPalAccountWithFuturePaymentNonce()
{
Result<Customer> result = gateway.Customer.Create(new CustomerRequest());
Assert.IsTrue(result.IsSuccess());
string nonce = TestHelper.GenerateFuturePaymentPayPalNonce(gateway);
var request = new PaymentMethodRequest
{
CustomerId = result.Target.Id,
PaymentMethodNonce = nonce
};
Result<PaymentMethod> paymentMethodResult = gateway.PaymentMethod.Create(request);
Assert.IsTrue(paymentMethodResult.IsSuccess());
Assert.IsNotNull(paymentMethodResult.Target.Token);
Assert.IsNotNull(paymentMethodResult.Target.ImageUrl);
Assert.AreEqual(result.Target.Id, paymentMethodResult.Target.CustomerId);
Assert.IsInstanceOf(typeof(PayPalAccount), paymentMethodResult.Target);
PayPalAccount paypalAccount = (PayPalAccount) paymentMethodResult.Target;
Assert.IsNull(paypalAccount.RevokedAt);
}
[Test]
public void Create_CreatesPayPalAccountWithOrderPaymentNonce()
{
Result<Customer> result = gateway.Customer.Create(new CustomerRequest());
Assert.IsTrue(result.IsSuccess());
string nonce = TestHelper.GenerateOrderPaymentPayPalNonce(gateway);
var request = new PaymentMethodRequest
{
CustomerId = result.Target.Id,
PaymentMethodNonce = nonce
};
Result<PaymentMethod> paymentMethodResult = gateway.PaymentMethod.Create(request);
Assert.IsTrue(paymentMethodResult.IsSuccess());
Assert.IsNotNull(paymentMethodResult.Target.Token);
Assert.IsNotNull(paymentMethodResult.Target.ImageUrl);
Assert.AreEqual(result.Target.Id, paymentMethodResult.Target.CustomerId);
Assert.IsInstanceOf(typeof(PayPalAccount), paymentMethodResult.Target);
PayPalAccount paypalAccount = (PayPalAccount) paymentMethodResult.Target;
Assert.IsNotNull(paypalAccount.PayerId);
}
[Test]
public void Create_CreatesPayPalAccountWithOrderPaymentNonceAndPayPalOptions()
{
Result<Customer> result = gateway.Customer.Create(new CustomerRequest());
Assert.IsTrue(result.IsSuccess());
string nonce = TestHelper.GenerateOrderPaymentPayPalNonce(gateway);
var request = new PaymentMethodRequest
{
CustomerId = result.Target.Id,
PaymentMethodNonce = nonce,
Options = new PaymentMethodOptionsRequest {
OptionsPayPal = new PaymentMethodOptionsPayPalRequest {
PayeeEmail = "payee@example.com",
OrderId = "order-id",
CustomField = "custom merchant field",
Description = "merchant description",
Amount = 1.23M,
Shipping = new AddressRequest {
Company = "Braintree P.S.",
CountryName = "Mexico",
ExtendedAddress = "Apt 456",
FirstName = "Thomas",
LastName = "Smithy",
Locality = "Braintree",
PostalCode = "54321",
Region = "MA",
StreetAddress = "456 Road"
}
}
}
};
Result<PaymentMethod> paymentMethodResult = gateway.PaymentMethod.Create(request);
Assert.IsTrue(paymentMethodResult.IsSuccess());
Assert.IsNotNull(paymentMethodResult.Target.Token);
Assert.IsNotNull(paymentMethodResult.Target.ImageUrl);
Assert.AreEqual(result.Target.Id, paymentMethodResult.Target.CustomerId);
Assert.IsInstanceOf(typeof(PayPalAccount), paymentMethodResult.Target);
PayPalAccount paypalAccount = (PayPalAccount) paymentMethodResult.Target;
Assert.IsNotNull(paypalAccount.PayerId);
}
[Test]
public void Create_CreatesPayPalAccountWithOneTimePaymentNonceFails()
{
Result<Customer> result = gateway.Customer.Create(new CustomerRequest());
Assert.IsTrue(result.IsSuccess());
string nonce = TestHelper.GenerateOneTimePayPalNonce(gateway);
var request = new PaymentMethodRequest
{
CustomerId = result.Target.Id,
PaymentMethodNonce = nonce
};
Result<PaymentMethod> paymentMethodResult = gateway.PaymentMethod.Create(request);
Assert.IsFalse(paymentMethodResult.IsSuccess());
Assert.AreEqual(
ValidationErrorCode.PAYPAL_ACCOUNT_CANNOT_VAULT_ONE_TIME_USE_PAYPAL_ACCOUNT,
paymentMethodResult.Errors.ForObject("paypal-account").OnField("base")[0].Code
);
}
[Test]
public void Create_CreatesPayPalAccountWithPayPalRefreshToken()
{
Result<Customer> result = gateway.Customer.Create(new CustomerRequest());
Assert.IsTrue(result.IsSuccess());
string nonce = TestHelper.GenerateFuturePaymentPayPalNonce(gateway);
var request = new PaymentMethodRequest
{
CustomerId = result.Target.Id,
PayPalRefreshToken = "PAYPAL_REFRESH_TOKEN"
};
Result<PaymentMethod> paymentMethodResult = gateway.PaymentMethod.Create(request);
Assert.IsTrue(paymentMethodResult.IsSuccess());
Assert.IsNotNull(paymentMethodResult.Target.Token);
Assert.AreEqual(result.Target.Id, paymentMethodResult.Target.CustomerId);
Assert.IsInstanceOf(typeof(PayPalAccount), paymentMethodResult.Target);
var token = paymentMethodResult.Target.Token;
var foundPaypalAccount = gateway.PayPalAccount.Find(token);
Assert.IsNotNull(foundPaypalAccount);
Assert.IsNotNull(foundPaypalAccount.BillingAgreementId);
}
[Test]
public void Create_CreatesCreditCardWithNonce()
{
string nonce = TestHelper.GenerateUnlockedNonce(gateway);
Result<Customer> result = gateway.Customer.Create(new CustomerRequest());
Assert.IsTrue(result.IsSuccess());
var request = new PaymentMethodRequest
{
CustomerId = result.Target.Id,
PaymentMethodNonce = nonce
};
Result<PaymentMethod> paymentMethodResult = gateway.PaymentMethod.Create(request);
Assert.IsTrue(paymentMethodResult.IsSuccess());
Assert.IsNotNull(paymentMethodResult.Target.Token);
Assert.AreEqual(result.Target.Id, paymentMethodResult.Target.CustomerId);
Assert.IsInstanceOf(typeof(CreditCard), paymentMethodResult.Target);
}
[Test]
public void Create_CreatePaymentMethodWithInvalidThreeDSecurePassThruParams()
{
string nonce = TestHelper.GenerateUnlockedNonce(gateway);
Result<Customer> result = gateway.Customer.Create(new CustomerRequest());
Assert.IsTrue(result.IsSuccess());
ThreeDSecurePassThruRequest passThruParamsWithoutThreeDSecureVersion = new ThreeDSecurePassThruRequest()
{
EciFlag = "05",
Cavv = "some_cavv",
Xid = "some_xid",
AuthenticationResponse = "Y",
DirectoryResponse = "Y",
CavvAlgorithm = "2",
DsTransactionId = "some_ds_transaction_id"
};
var request = new PaymentMethodRequest()
{
CustomerId = result.Target.Id,
PaymentMethodNonce = nonce,
ThreeDSecurePassThru = passThruParamsWithoutThreeDSecureVersion,
Options = new PaymentMethodOptionsRequest()
{
VerifyCard = true
},
};
Result<PaymentMethod> paymentMethodResult = gateway.PaymentMethod.Create(request);
Assert.IsFalse(paymentMethodResult.IsSuccess());
Assert.AreEqual(
ValidationErrorCode.VERIFICATION_THREE_D_SECURE_THREE_D_SECURE_VERSION_IS_REQUIRED,
paymentMethodResult.Errors.ForObject("Verification").OnField("ThreeDSecureVersion")[0].Code
);
}
[Test]
public void Create_CreatePaymentMethodWithThreeDSecurePassThruParams()
{
string nonce = TestHelper.GenerateUnlockedNonce(gateway);
Result<Customer> result = gateway.Customer.Create(new CustomerRequest());
Assert.IsTrue(result.IsSuccess());
ThreeDSecurePassThruRequest passThruParamsWithThreeDSecureVersion = new ThreeDSecurePassThruRequest()
{
EciFlag = "05",
Cavv = "some_cavv",
Xid = "some_xid",
ThreeDSecureVersion = "2.2.2",
AuthenticationResponse = "Y",
DirectoryResponse = "Y",
CavvAlgorithm = "2",
DsTransactionId = "some_ds_transaction_id"
};
var request = new PaymentMethodRequest()
{
CustomerId = result.Target.Id,
PaymentMethodNonce = nonce,
ThreeDSecurePassThru = passThruParamsWithThreeDSecureVersion,
Options = new PaymentMethodOptionsRequest()
{
VerifyCard = true
},
};
Result<PaymentMethod> paymentMethodResult = gateway.PaymentMethod.Create(request);
Assert.IsTrue(paymentMethodResult.IsSuccess());
}
[Test]
public void CreateWithoutSkipAdvancedFraudCheckingIncludesRiskData()
{
FraudProtectionEnterpriseSetup();
string nonce = TestHelper.GenerateUnlockedNonce(gateway);
Result<Customer> result = gateway.Customer.Create(new CustomerRequest());
Assert.IsTrue(result.IsSuccess());
PaymentMethodRequest request = new PaymentMethodRequest()
{
CustomerId = result.Target.Id,
PaymentMethodNonce = nonce,
Options = new PaymentMethodOptionsRequest()
{
SkipAdvancedFraudChecking = false,
VerifyCard = true
},
};
Result<PaymentMethod> paymentMethodResult = gateway.PaymentMethod.Create(request);
Assert.IsTrue(paymentMethodResult.IsSuccess());
CreditCard creditCard = (CreditCard) paymentMethodResult.Target;
CreditCardVerification verification = creditCard.Verification;
Assert.IsNotNull(verification);
Assert.IsNotNull(verification.RiskData);
}
[Test]
public void CreateWithSkipAdvancedFraudCheckingDoesNotIncludeRiskData()
{
FraudProtectionEnterpriseSetup();
string nonce = TestHelper.GenerateUnlockedNonce(gateway);
Result<Customer> result = gateway.Customer.Create(new CustomerRequest());
Assert.IsTrue(result.IsSuccess());
PaymentMethodRequest request = new PaymentMethodRequest()
{
CustomerId = result.Target.Id,
PaymentMethodNonce = nonce,
Options = new PaymentMethodOptionsRequest()
{
SkipAdvancedFraudChecking = true,
VerifyCard = true
},
};
Result<PaymentMethod> paymentMethodResult = gateway.PaymentMethod.Create(request);
Assert.IsTrue(paymentMethodResult.IsSuccess());
CreditCard creditCard = (CreditCard) paymentMethodResult.Target;
CreditCardVerification verification = creditCard.Verification;
Assert.IsNotNull(verification);
Assert.IsNull(verification.RiskData);
}
[Test]
#if netcore
public async Task CreateAsync_CreatesCreditCardWithNonce()
#else
public void CreateAsync_CreatesCreditCardWithNonce()
{
Task.Run(async () =>
#endif
{
string nonce = TestHelper.GenerateUnlockedNonce(gateway);
Result<Customer> result = gateway.Customer.Create(new CustomerRequest());
Assert.IsTrue(result.IsSuccess());
var request = new PaymentMethodRequest
{
CustomerId = result.Target.Id,
PaymentMethodNonce = nonce
};
Result<PaymentMethod> paymentMethodResult = await gateway.PaymentMethod.CreateAsync(request);
Assert.IsTrue(paymentMethodResult.IsSuccess());
Assert.IsNotNull(paymentMethodResult.Target.Token);
Assert.AreEqual(result.Target.Id, paymentMethodResult.Target.CustomerId);
Assert.IsInstanceOf(typeof(CreditCard), paymentMethodResult.Target);
}
#if net452
).GetAwaiter().GetResult();
}
#endif
[Test]
public void Create_CreatesCreditCardWithNonceAndDeviceData()
{
string nonce = TestHelper.GenerateUnlockedNonce(gateway);
Result<Customer> result = gateway.Customer.Create(new CustomerRequest());
Assert.IsTrue(result.IsSuccess());
var request = new PaymentMethodRequest()
{
CustomerId = result.Target.Id,
PaymentMethodNonce = nonce,
Options = new PaymentMethodOptionsRequest()
{
VerifyCard = true
},
DeviceData = "{\"device_session_id\":\"my_dsid\", \"fraud_merchant_id\":\"my_fmid\"}"
};
Result<PaymentMethod> paymentMethodResult = gateway.PaymentMethod.Create(request);
Assert.IsTrue(paymentMethodResult.IsSuccess());
Assert.IsNotNull(paymentMethodResult.Target.Token);
Assert.AreEqual(result.Target.Id, paymentMethodResult.Target.CustomerId);
}
[Test]
public void Create_CreatesCreditCardWithThreeDSecureNonce()
{
Result<Customer> result = gateway.Customer.Create(new CustomerRequest());
Assert.IsTrue(result.IsSuccess());
var request = new PaymentMethodRequest()
{
CustomerId = result.Target.Id,
PaymentMethodNonce = Nonce.ThreeDSecureVisaFullAuthentication,
Options = new PaymentMethodOptionsRequest()
{
VerifyCard = true
},
};
Result<PaymentMethod> paymentMethodResult = gateway.PaymentMethod.Create(request);
Assert.IsTrue(paymentMethodResult.IsSuccess());
CreditCard creditCard = (CreditCard) paymentMethodResult.Target;
CreditCardVerification verification = creditCard.Verification;
Assert.AreEqual("Y", verification.ThreeDSecureInfo.Enrolled);
Assert.AreEqual("cavv_value", verification.ThreeDSecureInfo.Cavv);
Assert.AreEqual("05", verification.ThreeDSecureInfo.EciFlag);
Assert.AreEqual("authenticate_successful", verification.ThreeDSecureInfo.Status);
Assert.AreEqual("1.0.2", verification.ThreeDSecureInfo.ThreeDSecureVersion);
Assert.AreEqual("xid_value", verification.ThreeDSecureInfo.Xid);
Assert.IsTrue(verification.ThreeDSecureInfo.LiabilityShifted);
Assert.IsTrue(verification.ThreeDSecureInfo.LiabilityShiftPossible);
}
[Test]
public void Create_CreatesApplePayCardWithNonce()
{
Result<Customer> result = gateway.Customer.Create(new CustomerRequest());
Assert.IsTrue(result.IsSuccess());
var request = new PaymentMethodRequest
{
CustomerId = result.Target.Id,
PaymentMethodNonce = Nonce.ApplePayAmex
};
Result<PaymentMethod> paymentMethodResult = gateway.PaymentMethod.Create(request);
Assert.IsTrue(paymentMethodResult.IsSuccess());
Assert.IsNotNull(paymentMethodResult.Target.Token);
Assert.IsNotNull(paymentMethodResult.Target.ImageUrl);
Assert.IsInstanceOf(typeof(ApplePayCard), paymentMethodResult.Target);
ApplePayCard applePayCard = (ApplePayCard) paymentMethodResult.Target;
Assert.IsNotNull(applePayCard.Bin);
Assert.IsNotNull(applePayCard.CardType);
Assert.IsNotNull(applePayCard.ExpirationMonth);
Assert.IsNotNull(applePayCard.ExpirationYear);
Assert.IsNotNull(applePayCard.CreatedAt);
Assert.IsNotNull(applePayCard.UpdatedAt);
Assert.IsNotNull(applePayCard.Subscriptions);
Assert.IsNotNull(applePayCard.PaymentInstrumentName);
Assert.IsNotNull(applePayCard.SourceDescription);
Assert.IsNotNull(applePayCard.IsExpired);
Assert.IsNotNull(applePayCard.Prepaid);
Assert.IsNotNull(applePayCard.Healthcare);
Assert.IsNotNull(applePayCard.Debit);
Assert.IsNotNull(applePayCard.DurbinRegulated);
Assert.IsNotNull(applePayCard.Commercial);
Assert.IsNotNull(applePayCard.Payroll);
Assert.IsNotNull(applePayCard.IssuingBank);
Assert.IsNotNull(applePayCard.CountryOfIssuance);
Assert.IsNotNull(applePayCard.ProductId);
Assert.AreEqual(result.Target.Id, applePayCard.CustomerId);
}
[Test]
public void Create_CreatesAndroidPayProxyCardWithNonce()
{
Result<Customer> result = gateway.Customer.Create(new CustomerRequest());
Assert.IsTrue(result.IsSuccess());
var request = new PaymentMethodRequest
{
CustomerId = result.Target.Id,
PaymentMethodNonce = Nonce.AndroidPayDiscover
};
Result<PaymentMethod> paymentMethodResult = gateway.PaymentMethod.Create(request);
Assert.IsTrue(paymentMethodResult.IsSuccess());
Assert.IsNotNull(paymentMethodResult.Target.Token);
Assert.IsNotNull(paymentMethodResult.Target.ImageUrl);
Assert.IsInstanceOf(typeof(AndroidPayCard), paymentMethodResult.Target);
AndroidPayCard androidPayCard = (AndroidPayCard) paymentMethodResult.Target;
Assert.IsNotNull(androidPayCard.IsDefault);
Assert.IsNotNull(androidPayCard.CardType);
Assert.IsNotNull(androidPayCard.VirtualCardType);
Assert.IsNotNull(androidPayCard.SourceCardType);
Assert.IsNotNull(androidPayCard.SourceDescription);
Assert.IsNotNull(androidPayCard.Last4);
Assert.IsNotNull(androidPayCard.VirtualCardLast4);
Assert.IsNotNull(androidPayCard.SourceCardLast4);
Assert.IsNotNull(androidPayCard.Bin);
Assert.IsNotNull(androidPayCard.ExpirationMonth);
Assert.IsNotNull(androidPayCard.ExpirationYear);
Assert.IsNotNull(androidPayCard.GoogleTransactionId);
Assert.IsNotNull(androidPayCard.CreatedAt);
Assert.IsNotNull(androidPayCard.UpdatedAt);
Assert.IsNotNull(androidPayCard.Subscriptions);
Assert.IsFalse(androidPayCard.IsNetworkTokenized);
Assert.IsNotNull(androidPayCard.Prepaid);
Assert.IsNotNull(androidPayCard.Healthcare);
Assert.IsNotNull(androidPayCard.Debit);
Assert.IsNotNull(androidPayCard.DurbinRegulated);
Assert.IsNotNull(androidPayCard.Commercial);
Assert.IsNotNull(androidPayCard.Payroll);
Assert.IsNotNull(androidPayCard.IssuingBank);
Assert.IsNotNull(androidPayCard.CountryOfIssuance);
Assert.IsNotNull(androidPayCard.ProductId);
}
[Test]
public void Create_CreatesAndroidPayNetworkTokenWithNonce()
{
Result<Customer> result = gateway.Customer.Create(new CustomerRequest());
Assert.IsTrue(result.IsSuccess());
var request = new PaymentMethodRequest
{
CustomerId = result.Target.Id,
PaymentMethodNonce = Nonce.AndroidPayMasterCard
};
Result<PaymentMethod> paymentMethodResult = gateway.PaymentMethod.Create(request);
Assert.IsTrue(paymentMethodResult.IsSuccess());
Assert.IsNotNull(paymentMethodResult.Target.Token);
Assert.IsNotNull(paymentMethodResult.Target.ImageUrl);
Assert.IsInstanceOf(typeof(AndroidPayCard), paymentMethodResult.Target);
AndroidPayCard androidPayCard = (AndroidPayCard) paymentMethodResult.Target;
Assert.IsNotNull(androidPayCard.IsDefault);
Assert.IsNotNull(androidPayCard.CardType);
Assert.IsNotNull(androidPayCard.VirtualCardType);
Assert.IsNotNull(androidPayCard.SourceCardType);
Assert.IsNotNull(androidPayCard.SourceDescription);
Assert.IsNotNull(androidPayCard.Last4);
Assert.IsNotNull(androidPayCard.VirtualCardLast4);
Assert.IsNotNull(androidPayCard.SourceCardLast4);
Assert.IsNotNull(androidPayCard.Bin);
Assert.IsNotNull(androidPayCard.ExpirationMonth);
Assert.IsNotNull(androidPayCard.ExpirationYear);
Assert.IsNotNull(androidPayCard.GoogleTransactionId);
Assert.IsNotNull(androidPayCard.CreatedAt);
Assert.IsNotNull(androidPayCard.UpdatedAt);
Assert.IsNotNull(androidPayCard.Subscriptions);
Assert.IsTrue(androidPayCard.IsNetworkTokenized);
Assert.IsNotNull(androidPayCard.Prepaid);
Assert.IsNotNull(androidPayCard.Healthcare);
Assert.IsNotNull(androidPayCard.Debit);
Assert.IsNotNull(androidPayCard.DurbinRegulated);
Assert.IsNotNull(androidPayCard.Commercial);
Assert.IsNotNull(androidPayCard.Payroll);
Assert.IsNotNull(androidPayCard.IssuingBank);
Assert.IsNotNull(androidPayCard.CountryOfIssuance);
Assert.IsNotNull(androidPayCard.ProductId);
}
[Test]
public void Create_CreatesVenmoAccountWithNonce()
{
Result<Customer> result = gateway.Customer.Create(new CustomerRequest());
Assert.IsTrue(result.IsSuccess());
var request = new PaymentMethodRequest
{
CustomerId = result.Target.Id,
PaymentMethodNonce = Nonce.VenmoAccount
};
Result<PaymentMethod> paymentMethodResult = gateway.PaymentMethod.Create(request);
Assert.IsTrue(paymentMethodResult.IsSuccess());
VenmoAccount venmoAccount = (VenmoAccount) paymentMethodResult.Target;
Assert.IsNotNull(venmoAccount.Username);
Assert.IsNotNull(venmoAccount.VenmoUserId);
Assert.IsNotNull(venmoAccount.ImageUrl);
Assert.IsNotNull(venmoAccount.SourceDescription);
Assert.IsNotNull(venmoAccount.IsDefault);
Assert.IsNotNull(venmoAccount.CreatedAt);
Assert.IsNotNull(venmoAccount.UpdatedAt);
Assert.IsNotNull(venmoAccount.CustomerId);
Assert.IsNotNull(venmoAccount.Subscriptions);
}
[Test]
public void Create_CreatesUsBankAccountWithNonce()
{
Result<Customer> result = gateway.Customer.Create(new CustomerRequest());
Assert.IsTrue(result.IsSuccess());
var request = new PaymentMethodRequest
{
CustomerId = result.Target.Id,
PaymentMethodNonce = TestHelper.GenerateValidUsBankAccountNonce(gateway),
Options = new PaymentMethodOptionsRequest {
VerificationMerchantAccountId = MerchantAccountIDs.US_BANK_MERCHANT_ACCOUNT_ID
}
};
Result<PaymentMethod> paymentMethodResult = gateway.PaymentMethod.Create(request);
Assert.IsTrue(paymentMethodResult.IsSuccess());
UsBankAccount usBankAccount = (UsBankAccount) paymentMethodResult.Target;
Assert.IsNotNull(usBankAccount.Token);
Assert.AreEqual("021000021", usBankAccount.RoutingNumber);
Assert.AreEqual("0000", usBankAccount.Last4);
Assert.AreEqual("checking", usBankAccount.AccountType);
Assert.AreEqual("Dan Schulman", usBankAccount.AccountHolderName);
Assert.IsTrue(Regex.IsMatch(usBankAccount.BankName, ".*CHASE.*"));
var found = gateway.PaymentMethod.Find(usBankAccount.Token);
Assert.IsInstanceOf(typeof(UsBankAccount), found);
}
[Test]
public void Create_CreatesAbstractPaymentMethod()
{
Result<Customer> result = gateway.Customer.Create(new CustomerRequest());
Assert.IsTrue(result.IsSuccess());
var request = new PaymentMethodRequest
{
CustomerId = result.Target.Id,
PaymentMethodNonce = Nonce.AbstractTransactable
};
Result<PaymentMethod> paymentMethodResult = gateway.PaymentMethod.Create(request);
Assert.IsTrue(paymentMethodResult.IsSuccess());
Assert.IsNotNull(paymentMethodResult.Target.Token);
Assert.IsNotNull(paymentMethodResult.Target.ImageUrl);
}
[Test]
public void Create_CanMakeDefaultAndSetToken()
{
Result<Customer> customerResult = gateway.Customer.Create(new CustomerRequest());
Assert.IsTrue(customerResult.IsSuccess());
var creditCardRequest = new CreditCardRequest
{
CustomerId = customerResult.Target.Id,
Number = "5105105105105100",
ExpirationDate = "05/12"
};
CreditCard creditCard = gateway.CreditCard.Create(creditCardRequest).Target;
Assert.IsTrue(creditCard.IsDefault.Value);
string nonce = TestHelper.GenerateUnlockedNonce(gateway);
Random random = new Random();
int randomNumber = random.Next(0, 10000);
var token = "token_" + randomNumber;
var request = new PaymentMethodRequest
{
CustomerId = customerResult.Target.Id,
PaymentMethodNonce = nonce,
Token = token,
Options = new PaymentMethodOptionsRequest
{
MakeDefault = true
}
};
Result<PaymentMethod> paymentMethodResult = gateway.PaymentMethod.Create(request);
Assert.IsTrue(paymentMethodResult.IsSuccess());
Assert.IsTrue(paymentMethodResult.Target.IsDefault.Value);
Assert.AreEqual(token, paymentMethodResult.Target.Token);
}
[Test]
public void Create_DoesntReturnErrorIfCreditCardOptionsArePresentForPayPalNonce()
{
var customer = gateway.Customer.Create().Target;
var originalToken = $"paypal-account-{DateTime.Now.Ticks}";
var nonce = TestHelper.GetNonceForPayPalAccount(
gateway,
new Params
{
{ "consent_code", "consent-code" },
{ "token", originalToken }
});
var result = gateway.PaymentMethod.Create(new PaymentMethodRequest
{
PaymentMethodNonce = nonce,
CustomerId = customer.Id,
Options = new PaymentMethodOptionsRequest
{
VerifyCard = true,
FailOnDuplicatePaymentMethod = true,
VerificationMerchantAccountId = "not_a_real_merchant_account_id"
}
});
Assert.IsTrue(result.IsSuccess());
}
[Test]
public void Create_RespectsVerifyCardAndVerificationMerchantAccountIdOutsideTheNonce()
{
var nonce = TestHelper.GetNonceForNewPaymentMethod(
gateway,
new Params
{
{ "number", "4000111111111115" },
{ "expiration_month", "11" },
{ "expiration_year", "2099" }
},
isCreditCard : true);
var customer = gateway.Customer.Create().Target;
var result = gateway.PaymentMethod.Create(new PaymentMethodRequest
{
PaymentMethodNonce = nonce,
CustomerId = customer.Id,
Options = new PaymentMethodOptionsRequest
{
VerifyCard = true,
VerificationMerchantAccountId = MerchantAccountIDs.NON_DEFAULT_MERCHANT_ACCOUNT_ID
}
});
Assert.IsFalse(result.IsSuccess());
Assert.IsNotNull(result.CreditCardVerification);
Assert.AreEqual(VerificationStatus.PROCESSOR_DECLINED, result.CreditCardVerification.Status);
Assert.AreEqual("2000", result.CreditCardVerification.ProcessorResponseCode);
Assert.AreEqual("Do Not Honor", result.CreditCardVerification.ProcessorResponseText);
Assert.AreEqual(MerchantAccountIDs.NON_DEFAULT_MERCHANT_ACCOUNT_ID, result.CreditCardVerification.MerchantAccountId);
}
[Test]
public void Create_AllowsCustomVerificationAmount()
{
var nonce = TestHelper.GetNonceForNewPaymentMethod(
gateway,
new Params
{
{ "number", "4000111111111115" },
{ "expiration_month", "11" },
{ "expiration_year", "2099" }
},
isCreditCard: true);
var customer = gateway.Customer.Create().Target;
var result = gateway.PaymentMethod.Create(new PaymentMethodRequest
{
PaymentMethodNonce = nonce,
CustomerId = customer.Id,
Options = new PaymentMethodOptionsRequest
{
VerifyCard = true,
VerificationAmount = "1.02"
}
});
Assert.IsFalse(result.IsSuccess());
Assert.IsNotNull(result.CreditCardVerification);
Assert.AreEqual(VerificationStatus.PROCESSOR_DECLINED, result.CreditCardVerification.Status);
}
[Test]
public void Create_RespectsFailOnDuplicatePaymentMethodWhenIncludedOutsideNonce()
{
var customer = gateway.Customer.Create().Target;
var creditCardResult = gateway.CreditCard.Create(new CreditCardRequest
{
CustomerId = customer.Id,
Number = SandboxValues.CreditCardNumber.VISA,
ExpirationDate = "05/2012"
});
Assert.IsTrue(creditCardResult.IsSuccess());
var nonce = TestHelper.GetNonceForNewPaymentMethod(
gateway,
new Params
{
{ "number", SandboxValues.CreditCardNumber.VISA },
{ "expiration_date", "05/2012" }
},
isCreditCard : true
);
var paypalResult = gateway.PaymentMethod.Create(new PaymentMethodRequest
{
PaymentMethodNonce = nonce,
CustomerId = customer.Id,
Options = new PaymentMethodOptionsRequest
{
FailOnDuplicatePaymentMethod = true
}
});
Assert.IsFalse(paypalResult.IsSuccess());
Assert.AreEqual(ValidationErrorCode.CREDIT_CARD_DUPLICATE_CARD_EXISTS, paypalResult.Errors.DeepAll().First().Code);
}
[Test]
public void Create_AllowsPassingBillingAddressOutsideTheNonce()
{
var customer = gateway.Customer.Create().Target;
var nonce = TestHelper.GetNonceForNewCreditCard(
gateway,
new Params
{
{ "number", "4111111111111111" },
{ "expirationMonth", "12" },
{ "expirationYear", "2020" },
{ "options", new Params
{
{ "validate", false }
}
}
});
Assert.IsFalse(string.IsNullOrEmpty(nonce));
var result = gateway.PaymentMethod.Create(new PaymentMethodRequest
{
PaymentMethodNonce = nonce,
CustomerId = customer.Id,
BillingAddress = new PaymentMethodAddressRequest
{
StreetAddress = "123 Abc Way"
}
});
Assert.IsTrue(result.IsSuccess());
Assert.That(result.Target, Is.InstanceOf(typeof(CreditCard)));
var token = result.Target.Token;
var foundCreditCard = gateway.CreditCard.Find(token);
Assert.IsNotNull(foundCreditCard);
Assert.AreEqual("123 Abc Way", foundCreditCard.BillingAddress.StreetAddress);
}
[Test]
public void Create_OverridesTheBillingAddressInTheNonce()
{
var customer = gateway.Customer.Create().Target;
var nonce = TestHelper.GetNonceForNewCreditCard(
gateway,
new Params
{
{ "number", "4111111111111111" },
{ "expirationMonth", "12" },
{ "expirationYear", "2020" },
{ "options", new Params
{
{ "validate", false }
}
}
});
Assert.IsFalse(string.IsNullOrEmpty(nonce));
var result = gateway.PaymentMethod.Create(new PaymentMethodRequest
{
PaymentMethodNonce = nonce,
CustomerId = customer.Id,
BillingAddress = new PaymentMethodAddressRequest
{
StreetAddress = "123 Abc Way"
}
});
Assert.IsTrue(result.IsSuccess());
Assert.That(result.Target, Is.InstanceOf(typeof(CreditCard)));
var token = result.Target.Token;
var foundCreditCard = gateway.CreditCard.Find(token);
Assert.IsNotNull(foundCreditCard);
Assert.AreEqual("123 Abc Way", foundCreditCard.BillingAddress.StreetAddress);
}
[Test]
public void Create_DoesNotOverrideTheBillingAddressForVaultedCreditCards()
{
var customer = gateway.Customer.Create().Target;
var nonce = TestHelper.GetNonceForNewCreditCard(
gateway,
new Params
{
{ "number", "4111111111111111" },
{ "expirationMonth", "12" },
{ "expirationYear", "2020" },
{ "billing_address", new Params
{
{ "street_address", "456 Xyz Way" }
}
}
},
customer.Id);
Assert.IsFalse(string.IsNullOrEmpty(nonce));
var result = gateway.PaymentMethod.Create(new PaymentMethodRequest
{
PaymentMethodNonce = nonce,
CustomerId = customer.Id,
BillingAddress = new PaymentMethodAddressRequest
{
StreetAddress = "123 Abc Way"
}
});
Assert.IsTrue(result.IsSuccess());
Assert.That(result.Target, Is.InstanceOf(typeof(CreditCard)));
var token = result.Target.Token;
var foundCreditCard = gateway.CreditCard.Find(token);
Assert.IsNotNull(foundCreditCard);
Assert.AreEqual("456 Xyz Way", foundCreditCard.BillingAddress.StreetAddress);
}
[Test]
public void Create_IgnoresPassedBillingAddressParamsForPayPal()
{
var nonce = TestHelper.GetNonceForPayPalAccount(
gateway,
new Params
{
{ "consent-code", "PAYPAL_CONSENT_CODE" }
});
var customer = gateway.Customer.Create().Target;
var result = gateway.PaymentMethod.Create(new PaymentMethodRequest
{
PaymentMethodNonce = nonce,
CustomerId = customer.Id,
BillingAddress = new PaymentMethodAddressRequest
{
StreetAddress = "123 Abc Way"
}
});
Assert.IsTrue(result.IsSuccess());
Assert.That(result.Target, Is.InstanceOf(typeof(PayPalAccount)));
Assert.IsNotNull(result.Target.ImageUrl);
var token = result.Target.Token;
var foundPaypalAccount = gateway.PayPalAccount.Find(token);
Assert.IsNotNull(foundPaypalAccount);
}
[Test]
public void Create_IgnoresPassedBillingAddressIdForPayPalAccount()
{
var nonce = TestHelper.GetNonceForPayPalAccount(
gateway,
new Params
{
{ "consent-code", "PAYPAL_CONSENT_CODE" }
});
var customer = gateway.Customer.Create().Target;
var result = gateway.PaymentMethod.Create(new PaymentMethodRequest
{
PaymentMethodNonce = nonce,
CustomerId = customer.Id,
BillingAddressId = "address_id"
});
Assert.IsTrue(result.IsSuccess());
Assert.That(result.Target, Is.InstanceOf(typeof(PayPalAccount)));
Assert.IsNotNull(result.Target.ImageUrl);
var token = result.Target.Token;
var foundPaypalAccount = gateway.PayPalAccount.Find(token);
Assert.IsNotNull(foundPaypalAccount);
}
[Test]
public void Delete_DeletesCreditCard()
{
var request = new PaymentMethodRequest
{
CustomerId = gateway.Customer.Create(new CustomerRequest()).Target.Id,
PaymentMethodNonce = Nonce.Transactable
};
Result<PaymentMethod> createResult = gateway.PaymentMethod.Create(request);
Assert.IsTrue(createResult.IsSuccess());
Result<PaymentMethod> deleteResult = gateway.PaymentMethod.Delete(createResult.Target.Token);
Assert.IsTrue(deleteResult.IsSuccess());
}
[Test]
#if netcore
public async Task DeleteAsync_DeletesCreditCard()
#else
public void DeleteAsync_DeletesCreditCard()
{
Task.Run(async () =>
#endif
{
var customer = await gateway.Customer.CreateAsync(new CustomerRequest());
var request = new PaymentMethodRequest
{
CustomerId = customer.Target.Id,
PaymentMethodNonce = Nonce.Transactable
};
Result<PaymentMethod> createResult = await gateway.PaymentMethod.CreateAsync(request);
Assert.IsTrue(createResult.IsSuccess());
Result<PaymentMethod> deleteResult = await gateway.PaymentMethod.DeleteAsync(createResult.Target.Token);
Assert.IsTrue(deleteResult.IsSuccess());
}
#if net452
).GetAwaiter().GetResult();
}
#endif
[Test]
public void Delete_DeletesPayPalAccount()
{
var request = new PaymentMethodRequest
{
CustomerId = gateway.Customer.Create(new CustomerRequest()).Target.Id,
PaymentMethodNonce = Nonce.PayPalFuturePayment
};
Result<PaymentMethod> createResult = gateway.PaymentMethod.Create(request);
Assert.IsTrue(createResult.IsSuccess());
var deleteRequest = new PaymentMethodDeleteRequest { RevokeAllGrants = false};
Result<PaymentMethod> deleteResult = gateway.PaymentMethod.Delete(createResult.Target.Token, deleteRequest);
Assert.IsTrue(deleteResult.IsSuccess());
}
[Test]
public void Delete_DeletesAndroidPayAccount()
{
var request = new PaymentMethodRequest
{
CustomerId = gateway.Customer.Create(new CustomerRequest()).Target.Id,
PaymentMethodNonce = Nonce.AndroidPay
};
Result<PaymentMethod> createResult = gateway.PaymentMethod.Create(request);
Assert.IsTrue(createResult.IsSuccess());
Result<PaymentMethod> deleteResult = gateway.PaymentMethod.Delete(createResult.Target.Token);
Assert.IsTrue(deleteResult.IsSuccess());
}
[Test]
public void Delete_DeletesApplePayAccount()
{
var request = new PaymentMethodRequest
{
CustomerId = gateway.Customer.Create(new CustomerRequest()).Target.Id,
PaymentMethodNonce = Nonce.ApplePayVisa
};
Result<PaymentMethod> createResult = gateway.PaymentMethod.Create(request);
Assert.IsTrue(createResult.IsSuccess());
Result<PaymentMethod> deleteResult = gateway.PaymentMethod.Delete(createResult.Target.Token);
Assert.IsTrue(deleteResult.IsSuccess());
}
[Test]
public void Delete_RaisesNotFoundErrorWhenTokenDoesntExist()
{
Assert.Throws<NotFoundException>(() => gateway.PaymentMethod.Delete(" "));
}
[Test]
public void Find_FindsCreditCard()
{
var request = new PaymentMethodRequest
{
CustomerId = gateway.Customer.Create(new CustomerRequest()).Target.Id,
PaymentMethodNonce = Nonce.Transactable
};
Result<PaymentMethod> result = gateway.PaymentMethod.Create(request);
Assert.IsTrue(result.IsSuccess());
PaymentMethod found = gateway.PaymentMethod.Find(result.Target.Token);
Assert.AreEqual(result.Target.Token, found.Token);
}
[Test]
#if netcore
public async Task FindAsync_FindsCreditCard()
#else
public void FindAsync_FindsCreditCard()
{
Task.Run(async () =>
#endif
{
var request = new PaymentMethodRequest
{
CustomerId = gateway.Customer.Create(new CustomerRequest()).Target.Id,
PaymentMethodNonce = Nonce.Transactable
};
Result<PaymentMethod> result = await gateway.PaymentMethod.CreateAsync(request);
Assert.IsTrue(result.IsSuccess());
PaymentMethod found = await gateway.PaymentMethod.FindAsync(result.Target.Token);
Assert.AreEqual(result.Target.Token, found.Token);
}
#if net452
).GetAwaiter().GetResult();
}
#endif
[Test]
public void Find_FindsPayPalAccount()
{
var request = new PaymentMethodRequest
{
CustomerId = gateway.Customer.Create(new CustomerRequest()).Target.Id,
PaymentMethodNonce = Nonce.PayPalFuturePayment
};
Result<PaymentMethod> result = gateway.PaymentMethod.Create(request);
Assert.IsTrue(result.IsSuccess());
PaymentMethod found = gateway.PaymentMethod.Find(result.Target.Token);
Assert.AreEqual(result.Target.Token, found.Token);
}
[Test]
public void Find_FindsApplePayCard()
{
var request = new PaymentMethodRequest
{
CustomerId = gateway.Customer.Create(new CustomerRequest()).Target.Id,
PaymentMethodNonce = Nonce.ApplePayAmex
};
Result<PaymentMethod> result = gateway.PaymentMethod.Create(request);
Assert.IsTrue(result.IsSuccess());
PaymentMethod found = gateway.PaymentMethod.Find(result.Target.Token);
Assert.AreEqual(result.Target.Token, found.Token);
Assert.IsInstanceOf(typeof(ApplePayCard), found);
}
[Test]
public void Find_FindsAndroidPayCard()
{
var request = new PaymentMethodRequest
{
CustomerId = gateway.Customer.Create(new CustomerRequest()).Target.Id,
PaymentMethodNonce = Nonce.AndroidPay
};
Result<PaymentMethod> result = gateway.PaymentMethod.Create(request);
Assert.IsTrue(result.IsSuccess());
PaymentMethod found = gateway.PaymentMethod.Find(result.Target.Token);
Assert.AreEqual(result.Target.Token, found.Token);
Assert.IsInstanceOf(typeof(AndroidPayCard), found);
}
[Test]
public void Find_FindsAbstractPaymentMethod()
{
var request = new PaymentMethodRequest
{
CustomerId = gateway.Customer.Create(new CustomerRequest()).Target.Id,
PaymentMethodNonce = Nonce.AbstractTransactable
};
Result<PaymentMethod> result = gateway.PaymentMethod.Create(request);
Assert.IsTrue(result.IsSuccess());
PaymentMethod found = gateway.PaymentMethod.Find(result.Target.Token);
Assert.AreEqual(result.Target.Token, found.Token);
}
[Test]
public void Find_RaisesNotFoundErrorWhenTokenDoesntExist()
{
Assert.Throws<NotFoundException>(() => gateway.PaymentMethod.Find("missing"));
}
[Test]
public void Update_UpdatesTheCreditCard()
{
var MASTERCARD = SandboxValues.CreditCardNumber.MASTER_CARD;
var customer = gateway.Customer.Create().Target;
var creditCard = gateway.CreditCard.Create(new CreditCardRequest
{
CardholderName = "Original Holder",
CustomerId = customer.Id,
CVV = "123",
Number = SandboxValues.CreditCardNumber.VISA,
ExpirationDate = "05/2012"
}).Target;
var updateResult = gateway.PaymentMethod.Update(
creditCard.Token,
new PaymentMethodRequest
{
CardholderName = "New Holder",
CVV = "456",
Number = MASTERCARD,
ExpirationDate = "06/2013"
});
Assert.IsTrue(updateResult.IsSuccess());
Assert.That(updateResult.Target, Is.InstanceOf(typeof(CreditCard)));
var updatedCreditCard = (CreditCard)updateResult.Target;
Assert.AreEqual("New Holder", updatedCreditCard.CardholderName);
Assert.AreEqual(MASTERCARD.Substring(0, 6), updatedCreditCard.Bin);
Assert.AreEqual(MASTERCARD.Substring(MASTERCARD.Length - 4), updatedCreditCard.LastFour);
Assert.AreEqual("06/2013", updatedCreditCard.ExpirationDate);
}
[Test]
public void Update_UpdatePaymentMethodWithThreeDSecureInvalidPassThruParams()
{
var MASTERCARD = SandboxValues.CreditCardNumber.MASTER_CARD;
var customer = gateway.Customer.Create().Target;
var creditCard = gateway.CreditCard.Create(new CreditCardRequest
{
CardholderName = "Original Holder",
CustomerId = customer.Id,
CVV = "123",
Number = SandboxValues.CreditCardNumber.VISA,
ExpirationDate = "05/2012"
}).Target;
ThreeDSecurePassThruRequest passThruRequestWithoutThreeDSecureVersion = new ThreeDSecurePassThruRequest()
{
EciFlag = "05",
Cavv = "some_cavv",
Xid = "some_xid",
AuthenticationResponse = "Y",
DirectoryResponse = "Y",
CavvAlgorithm = "2",
DsTransactionId = "some_ds_transaction_id"
};
var updateResult = gateway.PaymentMethod.Update(
creditCard.Token,
new PaymentMethodRequest()
{
CardholderName = "New Holder",
CVV = "456",
Number = MASTERCARD,
ExpirationDate = "06/2013",
ThreeDSecurePassThru = passThruRequestWithoutThreeDSecureVersion,
Options = new PaymentMethodOptionsRequest()
{
VerifyCard = true
},
});
Assert.IsFalse(updateResult.IsSuccess());
Assert.AreEqual(
ValidationErrorCode.VERIFICATION_THREE_D_SECURE_THREE_D_SECURE_VERSION_IS_REQUIRED,
updateResult.Errors.ForObject("Verification").OnField("ThreeDSecureVersion")[0].Code
);
}
[Test]
public void Update_UpdatePaymentMethodWithThreeDSecurePassThruParams()
{
var MASTERCARD = SandboxValues.CreditCardNumber.MASTER_CARD;
var customer = gateway.Customer.Create().Target;
var creditCard = gateway.CreditCard.Create(new CreditCardRequest
{
CardholderName = "Original Holder",
CustomerId = customer.Id,
CVV = "123",
Number = SandboxValues.CreditCardNumber.VISA,
ExpirationDate = "05/2012"
}).Target;
ThreeDSecurePassThruRequest passThruRequestWithThreeDSecureVersion = new ThreeDSecurePassThruRequest()
{
EciFlag = "05",
Cavv = "some_cavv",
Xid = "some_xid",
ThreeDSecureVersion = "2.2.1",
AuthenticationResponse = "Y",
DirectoryResponse = "Y",
CavvAlgorithm = "2",
DsTransactionId = "some_ds_transaction_id"
};
var updateResult = gateway.PaymentMethod.Update(
creditCard.Token,
new PaymentMethodRequest()
{
CardholderName = "New Holder",
CVV = "456",
Number = MASTERCARD,
ExpirationDate = "06/2013",
ThreeDSecurePassThru = passThruRequestWithThreeDSecureVersion,
Options = new PaymentMethodOptionsRequest()
{
VerifyCard = true
},
});
Assert.IsTrue(updateResult.IsSuccess());
}
[Test]
public void UpdateWithoutSkipAdvancedFraudCheckingIncludesRiskData()
{
FraudProtectionEnterpriseSetup();
Customer customer = gateway.Customer.Create(new CustomerRequest()).Target;
CreditCardRequest request = new CreditCardRequest
{
CustomerId = customer.Id,
CardholderName = "John Doe",
CVV = "123",
Number = "4111111111111111",
ExpirationDate = "05/12",
};
CreditCard originalCreditCard = gateway.CreditCard.Create(request).Target;
PaymentMethodRequest paymentMethodUpdateRequest = new PaymentMethodRequest()
{
ExpirationDate = "05/22",
Options = new PaymentMethodOptionsRequest
{
VerifyCard = true,
SkipAdvancedFraudChecking = false
},
};
Result<PaymentMethod> paymentMethodResult = gateway.PaymentMethod.Update(originalCreditCard.Token, paymentMethodUpdateRequest);
Assert.IsTrue(paymentMethodResult.IsSuccess());
CreditCard creditCard = (CreditCard) paymentMethodResult.Target;
CreditCardVerification verification = creditCard.Verification;
Assert.IsNotNull(verification);
Assert.IsNotNull(verification.RiskData);
}
[Test]
public void UpdateWithSkipAdvancedFraudCheckingDoesNotIncludeRiskData()
{
FraudProtectionEnterpriseSetup();
Customer customer = gateway.Customer.Create(new CustomerRequest()).Target;
CreditCardRequest request = new CreditCardRequest
{
CustomerId = customer.Id,
CardholderName = "John Doe",
CVV = "123",
Number = "4111111111111111",
ExpirationDate = "05/12",
};
CreditCard originalCreditCard = gateway.CreditCard.Create(request).Target;
PaymentMethodRequest paymentMethodUpdateRequest = new PaymentMethodRequest()
{
ExpirationDate = "05/22",
Options = new PaymentMethodOptionsRequest
{
VerifyCard = true,
SkipAdvancedFraudChecking = true
},
};
Result<PaymentMethod> paymentMethodResult = gateway.PaymentMethod.Update(originalCreditCard.Token, paymentMethodUpdateRequest);
Assert.IsTrue(paymentMethodResult.IsSuccess());
CreditCard creditCard = (CreditCard) paymentMethodResult.Target;
CreditCardVerification verification = creditCard.Verification;
Assert.IsNotNull(verification);
Assert.IsNull(verification.RiskData);
}
[Test]
#if netcore
public async Task UpdateAsync_UpdatesTheCreditCard()
#else
public void UpdateAsync_UpdatesTheCreditCard()
{
Task.Run(async () =>
#endif
{
var MASTERCARD = SandboxValues.CreditCardNumber.MASTER_CARD;
var customerResult = await gateway.Customer.CreateAsync();
var customer = customerResult.Target;
var creditCardResult = await gateway.CreditCard.CreateAsync(new CreditCardRequest
{
CardholderName = "Original Holder",
CustomerId = customer.Id,
CVV = "123",
Number = SandboxValues.CreditCardNumber.VISA,
ExpirationDate = "05/2012"
});
var creditCard = creditCardResult.Target;
var updateResult = await gateway.PaymentMethod.UpdateAsync(
creditCard.Token,
new PaymentMethodRequest
{
CardholderName = "New Holder",
CVV = "456",
Number = MASTERCARD,
ExpirationDate = "06/2013"
});
Assert.IsTrue(updateResult.IsSuccess());
Assert.That(updateResult.Target, Is.InstanceOf(typeof(CreditCard)));
var updatedCreditCard = (CreditCard)updateResult.Target;
Assert.AreEqual("New Holder", updatedCreditCard.CardholderName);
Assert.AreEqual(MASTERCARD.Substring(0, 6), updatedCreditCard.Bin);
Assert.AreEqual(MASTERCARD.Substring(MASTERCARD.Length - 4), updatedCreditCard.LastFour);
Assert.AreEqual("06/2013", updatedCreditCard.ExpirationDate);
}
#if net452
).GetAwaiter().GetResult();
}
#endif
[Test]
public void Update_CreatesNewBillingAddressByDefault()
{
var customer = gateway.Customer.Create().Target;
var creditCard = gateway.CreditCard.Create(new CreditCardRequest
{
CustomerId = customer.Id,
Number = SandboxValues.CreditCardNumber.VISA,
ExpirationDate = "05/2012",
BillingAddress = new CreditCardAddressRequest
{
StreetAddress = "123 Nigeria Ave"
}
}).Target;
var updateResult = gateway.PaymentMethod.Update(
creditCard.Token,
new PaymentMethodRequest
{
BillingAddress = new PaymentMethodAddressRequest
{
Region = "IL",
}
});
Assert.IsTrue(updateResult.IsSuccess());
Assert.That(updateResult.Target, Is.InstanceOf(typeof(CreditCard)));
var updatedCreditCard = (CreditCard)updateResult.Target;
Assert.AreEqual("IL", updatedCreditCard.BillingAddress.Region);
Assert.IsNull(updatedCreditCard.BillingAddress.StreetAddress);
Assert.AreNotEqual(updatedCreditCard.BillingAddress.Id, creditCard.BillingAddress.Id);
}
[Test]
public void Update_UpdatesTheBillingAddressIfOptionIsSpecified()
{
var customer = gateway.Customer.Create().Target;
var creditCard = gateway.CreditCard.Create(new CreditCardRequest
{
CustomerId = customer.Id,
Number = SandboxValues.CreditCardNumber.VISA,
ExpirationDate = "05/2012",
BillingAddress = new CreditCardAddressRequest
{
StreetAddress = "123 Nigeria Ave"
}
}).Target;
var updateResult = gateway.PaymentMethod.Update(
creditCard.Token,
new PaymentMethodRequest
{
BillingAddress = new PaymentMethodAddressRequest
{
Region = "IL",
Options = new PaymentMethodAddressOptionsRequest
{
UpdateExisting = true
}
}
});
Assert.IsTrue(updateResult.IsSuccess());
Assert.That(updateResult.Target, Is.InstanceOf(typeof(CreditCard)));
var updatedCreditCard = (CreditCard)updateResult.Target;
Assert.AreEqual("IL", updatedCreditCard.BillingAddress.Region);
Assert.AreEqual("123 Nigeria Ave", updatedCreditCard.BillingAddress.StreetAddress);
Assert.AreEqual(updatedCreditCard.BillingAddress.Id, creditCard.BillingAddress.Id);
}
[Test]
public void Update_UpdatesCountryViaCodes()
{
var customer = gateway.Customer.Create().Target;
var creditCard = gateway.CreditCard.Create(new CreditCardRequest
{
CustomerId = customer.Id,
Number = SandboxValues.CreditCardNumber.VISA,
ExpirationDate = "05/2012",
BillingAddress = new CreditCardAddressRequest
{
StreetAddress = "123 Nigeria Ave"
}
}).Target;
var updateResult = gateway.PaymentMethod.Update(
creditCard.Token,
new PaymentMethodRequest
{
BillingAddress = new PaymentMethodAddressRequest
{
CountryName = "American Samoa",
CountryCodeAlpha2 = "AS",
CountryCodeAlpha3 = "ASM",
CountryCodeNumeric = "016",
Options = new PaymentMethodAddressOptionsRequest
{
UpdateExisting = true
}
}
});
Assert.IsTrue(updateResult.IsSuccess());
var updatedCreditCard = (CreditCard)updateResult.Target;
Assert.AreEqual("American Samoa", updatedCreditCard.BillingAddress.CountryName);
Assert.AreEqual("AS", updatedCreditCard.BillingAddress.CountryCodeAlpha2);
Assert.AreEqual("ASM", updatedCreditCard.BillingAddress.CountryCodeAlpha3);
Assert.AreEqual("016", updatedCreditCard.BillingAddress.CountryCodeNumeric);
}
[Test]
public void Update_CanPassExpirationMonthAndExpirationYear()
{
var customer = gateway.Customer.Create().Target;
var creditCard = gateway.CreditCard.Create(new CreditCardRequest
{
CustomerId = customer.Id,
Number = SandboxValues.CreditCardNumber.VISA,
ExpirationDate = "05/2012",
}).Target;
var updateResult = gateway.PaymentMethod.Update(
creditCard.Token,
new PaymentMethodRequest
{
Number = SandboxValues.CreditCardNumber.MASTER_CARD,
ExpirationMonth = "07",
ExpirationYear = "2011"
});
Assert.IsTrue(updateResult.IsSuccess());
Assert.That(updateResult.Target, Is.InstanceOf(typeof(CreditCard)));
var updatedCreditCard = (CreditCard)updateResult.Target;
Assert.AreEqual("07", updatedCreditCard.ExpirationMonth);
Assert.AreEqual("2011", updatedCreditCard.ExpirationYear);
Assert.AreEqual("07/2011", updatedCreditCard.ExpirationDate);
}
[Test]
public void Update_VerifiesTheUpdateIfOptionsVerifyCardIsTrue()
{
var customer = gateway.Customer.Create().Target;
var creditCard = gateway.CreditCard.Create(new CreditCardRequest
{
CardholderName = "Original Holder",
CustomerId = customer.Id,
CVV = "123",
Number = SandboxValues.CreditCardNumber.VISA,
ExpirationDate = "05/2012",
}).Target;
var updateResult = gateway.PaymentMethod.Update(
creditCard.Token,
new PaymentMethodRequest
{
CardholderName = "New Holder",
CVV = "456",
Number = TestUtil.CreditCardNumbers.FailsSandboxVerification.MasterCard,
ExpirationDate = "06/2013",
Options = new PaymentMethodOptionsRequest
{
VerifyCard = true
}
});
Assert.IsFalse(updateResult.IsSuccess());
Assert.IsNotNull(updateResult.CreditCardVerification);
Assert.AreEqual(VerificationStatus.PROCESSOR_DECLINED, updateResult.CreditCardVerification.Status);
Assert.IsNull(updateResult.CreditCardVerification.GatewayRejectionReason);
}
[Test]
public void Update_AllowsCustomVerificationAmount()
{
var customer = gateway.Customer.Create().Target;
var creditCard = gateway.CreditCard.Create(new CreditCardRequest
{
CardholderName = "Card Holder",
CustomerId = customer.Id,
CVV = "123",
Number = SandboxValues.CreditCardNumber.VISA,
ExpirationDate = "05/2020",
}).Target;
var updateResult = gateway.PaymentMethod.Update(
creditCard.Token,
new PaymentMethodRequest
{
PaymentMethodNonce = Nonce.ProcessorDeclinedMasterCard,
Options = new PaymentMethodOptionsRequest
{
VerifyCard = true,
VerificationAmount = "2.34"
}
});
Assert.IsFalse(updateResult.IsSuccess());
Assert.IsNotNull(updateResult.CreditCardVerification);
Assert.AreEqual(VerificationStatus.PROCESSOR_DECLINED, updateResult.CreditCardVerification.Status);
Assert.IsNull(updateResult.CreditCardVerification.GatewayRejectionReason);
}
[Test]
public void Update_CanUpdateTheBillingAddress()
{
var customer = gateway.Customer.Create().Target;
var creditCard = gateway.CreditCard.Create(new CreditCardRequest
{
CardholderName = "Original Holder",
CustomerId = customer.Id,
CVV = "123",
Number = SandboxValues.CreditCardNumber.VISA,
ExpirationDate = "05/2012",
BillingAddress = new CreditCardAddressRequest
{
FirstName = "Old First Name",
LastName = "Old Last Name",
Company = "Old Company",
StreetAddress = "123 Old St",
ExtendedAddress = "Apt Old",
Locality = "Old City",
Region = "Old State",
PostalCode = "12345",
CountryName = "Canada"
}
}).Target;
var result = gateway.PaymentMethod.Update(
creditCard.Token,
new PaymentMethodRequest
{
Options = new PaymentMethodOptionsRequest
{
VerifyCard = false
},
BillingAddress = new PaymentMethodAddressRequest
{
FirstName = "New First Name",
LastName = "New Last Name",
Company = "New Company",
StreetAddress = "123 New St",
Locality = "New City",
Region = "New State",
PostalCode = "56789",
CountryName = "United States of America"
}
});
Assert.IsTrue(result.IsSuccess());
Assert.That(result.Target, Is.InstanceOf(typeof(CreditCard)));
var address = ((CreditCard)result.Target).BillingAddress;
Assert.AreEqual("New First Name", address.FirstName);
Assert.AreEqual("New Last Name", address.LastName);
Assert.AreEqual("New Company", address.Company);
Assert.AreEqual("123 New St", address.StreetAddress);
Assert.AreEqual("New City", address.Locality);
Assert.AreEqual("New State", address.Region);
Assert.AreEqual("56789", address.PostalCode);
Assert.AreEqual("United States of America", address.CountryName);
}
[Test]
public void Update_ReturnsAnErrorResponseIfInvalid()
{
var customer = gateway.Customer.Create().Target;
var creditCard = gateway.CreditCard.Create(new CreditCardRequest
{
CardholderName = "Original Holder",
CustomerId = customer.Id,
CVV = "123",
Number = SandboxValues.CreditCardNumber.VISA,
ExpirationDate = "05/2012",
}).Target;
var result = gateway.PaymentMethod.Update(
creditCard.Token,
new PaymentMethodRequest
{
CardholderName = "New Holder",
Number = "invalid",
ExpirationDate = "05/2014"
});
Assert.IsFalse(result.IsSuccess());
Assert.AreEqual("Credit card number must be 12-19 digits.", result.Errors.ForObject("credit_card").OnField("number")[0].Message);
}
[Test]
public void Update_CanUpdateTheDefault()
{
var customer = gateway.Customer.Create().Target;
var card1 = gateway.CreditCard.Create(new CreditCardRequest
{
CustomerId = customer.Id,
Number = SandboxValues.CreditCardNumber.VISA,
ExpirationDate = "05/2009",
}).Target;
var card2 = gateway.CreditCard.Create(new CreditCardRequest
{
CustomerId = customer.Id,
Number = SandboxValues.CreditCardNumber.VISA,
ExpirationDate = "05/2009",
}).Target;
Assert.IsTrue(card1.IsDefault.Value);
Assert.IsFalse(card2.IsDefault.Value);
gateway.PaymentMethod.Update(
card2.Token,
new PaymentMethodRequest
{
Options = new PaymentMethodOptionsRequest { MakeDefault = true }
});
Assert.IsFalse(gateway.CreditCard.Find(card1.Token).IsDefault.Value);
Assert.IsTrue(gateway.CreditCard.Find(card2.Token).IsDefault.Value);
}
[Test]
public void Update_UpdatesPayPalAccountToken()
{
var customer = gateway.Customer.Create().Target;
var originalToken = $"paypal-account-{DateTime.Now.Ticks}";
var nonce = TestHelper.GetNonceForPayPalAccount(
gateway,
new Params
{
{ "consent_code", "consent-code" },
{ "token", originalToken }
});
var originalResult = gateway.PaymentMethod.Create(new PaymentMethodRequest
{
PaymentMethodNonce = nonce,
CustomerId = customer.Id
});
Assert.That(originalResult.Target, Is.InstanceOf(typeof(PayPalAccount)));
var updatedToken = $"UPDATED_TOKEN-{DateTime.Now.Ticks}";
var updatedResult = gateway.PaymentMethod.Update(
originalToken,
new PaymentMethodRequest
{
Token = updatedToken
});
Assert.IsTrue(updatedResult.IsSuccess());
var updatedPaypalAccount = gateway.PayPalAccount.Find(updatedToken);
Assert.AreEqual(((PayPalAccount)originalResult.Target).Email, updatedPaypalAccount.Email);
Exception exception = null;
try {
gateway.PayPalAccount.Find(originalToken);
} catch (Exception e) {
exception = e;
}
Assert.IsNotNull(exception);
Assert.IsInstanceOf(typeof(NotFoundException), exception);
}
[Test]
public void Update_CanMakePayPalAccountsTheDefaultPaymentMethod()
{
var customer = gateway.Customer.Create().Target;
var result = gateway.CreditCard.Create(new CreditCardRequest
{
CustomerId = customer.Id,
Number = SandboxValues.CreditCardNumber.VISA,
ExpirationDate = "05/2009",
Options = new CreditCardOptionsRequest
{
MakeDefault = true
}
});
Assert.IsTrue(result.IsSuccess());
var nonce = TestHelper.GetNonceForPayPalAccount(gateway, new Params {{ "consent_code", "consent-code" }});
var originalToken = gateway.PaymentMethod.Create(new PaymentMethodRequest
{
PaymentMethodNonce = nonce,
CustomerId = customer.Id
}).Target.Token;
var updatedResult = gateway.PaymentMethod.Update(
originalToken,
new PaymentMethodRequest { Options = new PaymentMethodOptionsRequest { MakeDefault = true }});
Assert.IsTrue(updatedResult.IsSuccess());
var updatedPaypalAccount = gateway.PayPalAccount.Find(originalToken);
Assert.IsTrue(updatedPaypalAccount.IsDefault.Value);
}
[Test]
public void Update_ReturnsAnErrorIfTokenForAccountIsUsedToAttemptUpdate()
{
var customer = gateway.Customer.Create().Target;
var firstToken = $"paypal-account-{DateTime.Now.Ticks + 1}";
var secondToken = $"paypal-account-{DateTime.Now.Ticks + 2}";
var firstNonce = TestHelper.GetNonceForPayPalAccount(
gateway,
new Params
{
{ "consent_code", "consent-code" },
{ "token", firstToken }
});
gateway.PaymentMethod.Create(new PaymentMethodRequest
{
PaymentMethodNonce = firstNonce,
CustomerId = customer.Id
});
var secondNonce = TestHelper.GetNonceForPayPalAccount(
gateway,
new Params
{
{ "consent_code", "consent-code" },
{ "token", secondToken }
});
gateway.PaymentMethod.Create(new PaymentMethodRequest
{
PaymentMethodNonce = secondNonce,
CustomerId = customer.Id
});
var updatedResult = gateway.PaymentMethod.Update(
firstToken,
new PaymentMethodRequest { Token = secondToken });
Assert.IsFalse(updatedResult.IsSuccess());
Assert.AreEqual("92906", ((int)updatedResult.Errors.DeepAll().First().Code).ToString());
}
[Test]
public void Update_UpdatesCreditCardWithAccountTypeCredit()
{
var customer = gateway.Customer.Create().Target;
var creditCard = gateway.CreditCard.Create(new CreditCardRequest
{
CardholderName = "Original Holder",
CustomerId = customer.Id,
CVV = "123",
Number = SandboxValues.CreditCardNumber.HIPER,
ExpirationDate = "05/2012"
}).Target;
var updateResult = gateway.PaymentMethod.Update(
creditCard.Token,
new PaymentMethodRequest
{
CardholderName = "New Holder",
CVV = "456",
Number = SandboxValues.CreditCardNumber.HIPER,
ExpirationDate = "06/2013",
Options = new PaymentMethodOptionsRequest()
{
VerifyCard = true,
VerificationMerchantAccountId = MerchantAccountIDs.BRAZIL_MERCHANT_ACCOUNT_ID,
VerificationAccountType = "credit",
},
});
Assert.IsTrue(updateResult.IsSuccess());
Assert.That(updateResult.Target, Is.InstanceOf(typeof(CreditCard)));
var updatedCreditCard = (CreditCard)updateResult.Target;
Assert.AreEqual("credit", updatedCreditCard.Verification.CreditCard.AccountType);
}
[Test]
public void Update_UpdatesCreditCardWithAccountTypeDebit()
{
var customer = gateway.Customer.Create().Target;
var creditCard = gateway.CreditCard.Create(new CreditCardRequest
{
CardholderName = "Original Holder",
CustomerId = customer.Id,
CVV = "123",
Number = SandboxValues.CreditCardNumber.HIPER,
ExpirationDate = "05/2012"
}).Target;
var updateResult = gateway.PaymentMethod.Update(
creditCard.Token,
new PaymentMethodRequest
{
CardholderName = "New Holder",
CVV = "456",
Number = SandboxValues.CreditCardNumber.HIPER,
ExpirationDate = "06/2013",
Options = new PaymentMethodOptionsRequest()
{
VerifyCard = true,
VerificationMerchantAccountId = MerchantAccountIDs.BRAZIL_MERCHANT_ACCOUNT_ID,
VerificationAccountType = "debit",
},
});
Assert.IsTrue(updateResult.IsSuccess());
Assert.That(updateResult.Target, Is.InstanceOf(typeof(CreditCard)));
var updatedCreditCard = (CreditCard)updateResult.Target;
Assert.AreEqual("debit", updatedCreditCard.Verification.CreditCard.AccountType);
}
[Test]
public void PaymentMethodGrantAndRevoke()
{
Result<Customer> result = partnerMerchantGateway.Customer.Create(new CustomerRequest());
var token = partnerMerchantGateway.PaymentMethod.Create(new PaymentMethodRequest
{
PaymentMethodNonce = Nonce.Transactable,
CustomerId = result.Target.Id
}).Target.Token;
string code = OAuthTestHelper.CreateGrant(oauthGateway, "integration_merchant_id", "grant_payment_method");
ResultImpl<OAuthCredentials> accessTokenResult = oauthGateway.OAuth.CreateTokenFromCode(new OAuthCredentialsRequest {
Code = code,
Scope = "grant_payment_method"
});
BraintreeGateway accessTokenGateway = new BraintreeGateway(accessTokenResult.Target.AccessToken);
PaymentMethodGrantRequest grantRequest = new PaymentMethodGrantRequest()
{
AllowVaulting = false,
IncludeBillingPostalCode = true
};
Result<PaymentMethodNonce> grantResult = accessTokenGateway.PaymentMethod.Grant(token, grantRequest);
Assert.IsTrue(grantResult.IsSuccess());
Assert.IsNotNull(grantResult.Target.Nonce);
Result<PaymentMethod> revokeResult = accessTokenGateway.PaymentMethod.Revoke(token);
Assert.IsTrue(revokeResult.IsSuccess());
}
[Test]
public void Create_CreatesWithAccountTypeCredit()
{
string nonce = TestHelper.GetNonceForNewPaymentMethod(
gateway,
new Params
{
{ "number", SandboxValues.CreditCardNumber.HIPER },
{ "expiration_date", "05/2012" }
},
isCreditCard : true
);
Result<Customer> result = gateway.Customer.Create(new CustomerRequest());
Assert.IsTrue(result.IsSuccess());
Console.WriteLine("after customer create");
var request = new PaymentMethodRequest
{
CustomerId = result.Target.Id,
PaymentMethodNonce = nonce,
Options = new PaymentMethodOptionsRequest()
{
VerifyCard = true,
VerificationMerchantAccountId = MerchantAccountIDs.BRAZIL_MERCHANT_ACCOUNT_ID,
VerificationAccountType = "credit",
},
};
Result<PaymentMethod> paymentMethodResult = gateway.PaymentMethod.Create(request);
Assert.IsTrue(paymentMethodResult.IsSuccess());
var creditCard = (CreditCard)paymentMethodResult.Target;
Assert.AreEqual("credit", creditCard.Verification.CreditCard.AccountType);
}
[Test]
public void Create_CreatesWithAccountTypeDebit()
{
string nonce = TestHelper.GetNonceForNewPaymentMethod(
gateway,
new Params
{
{ "number", SandboxValues.CreditCardNumber.HIPER },
{ "expiration_date", "05/2012" }
},
isCreditCard : true
);
Result<Customer> result = gateway.Customer.Create(new CustomerRequest());
Assert.IsTrue(result.IsSuccess());
var request = new PaymentMethodRequest
{
CustomerId = result.Target.Id,
PaymentMethodNonce = nonce,
Options = new PaymentMethodOptionsRequest()
{
VerifyCard = true,
VerificationMerchantAccountId = MerchantAccountIDs.BRAZIL_MERCHANT_ACCOUNT_ID,
VerificationAccountType = "debit",
},
};
Result<PaymentMethod> paymentMethodResult = gateway.PaymentMethod.Create(request);
Assert.IsTrue(paymentMethodResult.IsSuccess());
var creditCard = (CreditCard)paymentMethodResult.Target;
Assert.AreEqual("debit", creditCard.Verification.CreditCard.AccountType);
}
[Test]
public void Create_CreatesWithErrorAccountTypeInvalid()
{
string nonce = TestHelper.GetNonceForNewPaymentMethod(
gateway,
new Params
{
{ "number", SandboxValues.CreditCardNumber.HIPER },
{ "expiration_date", "05/2012" }
},
isCreditCard : true
);
Result<Customer> result = gateway.Customer.Create(new CustomerRequest());
Assert.IsTrue(result.IsSuccess());
var request = new PaymentMethodRequest
{
CustomerId = result.Target.Id,
PaymentMethodNonce = nonce,
Options = new PaymentMethodOptionsRequest()
{
VerifyCard = true,
VerificationMerchantAccountId = MerchantAccountIDs.BRAZIL_MERCHANT_ACCOUNT_ID,
VerificationAccountType = "ach",
},
};
Result<PaymentMethod> paymentMethodResult = gateway.PaymentMethod.Create(request);
Assert.IsFalse(paymentMethodResult.IsSuccess());
Assert.AreEqual(
ValidationErrorCode.CREDIT_CARD_OPTIONS_VERIFICATION_ACCOUNT_TYPE_IS_INVALID,
paymentMethodResult.Errors.ForObject("CreditCard").ForObject("Options").OnField("VerificationAccountType")[0].Code
);
}
[Test]
public void Create_CreatesWithErrorAccountTypeNotSupported()
{
string nonce = TestHelper.GetNonceForNewPaymentMethod(
gateway,
new Params
{
{ "number", SandboxValues.CreditCardNumber.VISA },
{ "expiration_date", "05/2012" }
},
isCreditCard : true
);
Result<Customer> result = gateway.Customer.Create(new CustomerRequest());
Assert.IsTrue(result.IsSuccess());
var request = new PaymentMethodRequest
{
CustomerId = result.Target.Id,
PaymentMethodNonce = nonce,
Options = new PaymentMethodOptionsRequest()
{
VerifyCard = true,
VerificationAccountType = "credit",
},
};
Result<PaymentMethod> paymentMethodResult = gateway.PaymentMethod.Create(request);
Assert.IsFalse(paymentMethodResult.IsSuccess());
Assert.AreEqual(
ValidationErrorCode.CREDIT_CARD_OPTIONS_VERIFICATION_ACCOUNT_TYPE_NOT_SUPPORTED,
paymentMethodResult.Errors.ForObject("CreditCard").ForObject("Options").OnField("VerificationAccountType")[0].Code
);
}
[Test]
public void Create_PaymentMethodWithNonceAndMerchantCurrencyOption()
{
string nonce = TestHelper.GenerateUnlockedNonce(gateway);
Result<Customer> result = gateway.Customer.Create(new CustomerRequest());
Assert.IsTrue(result.IsSuccess());
var request = new PaymentMethodRequest
{
CustomerId = result.Target.Id,
PaymentMethodNonce = nonce,
Options = new PaymentMethodOptionsRequest()
{
VerifyCard = true,
VerificationCurrencyIsoCode = "USD"
}
};
Result<PaymentMethod> paymentMethodResult = gateway.PaymentMethod.Create(request);
Assert.IsTrue(paymentMethodResult.IsSuccess());
Assert.IsNotNull(paymentMethodResult.Target.Token);
Assert.AreEqual(result.Target.Id, paymentMethodResult.Target.CustomerId);
Assert.IsInstanceOf(typeof(CreditCard), paymentMethodResult.Target);
}
[Test]
public void Create_PaymentMethodWithNonceAndInvalidMerchantCurrencyOption()
{
string nonce = TestHelper.GenerateUnlockedNonce(gateway);
Result<Customer> result = gateway.Customer.Create(new CustomerRequest());
Assert.IsTrue(result.IsSuccess());
var request = new PaymentMethodRequest
{
CustomerId = result.Target.Id,
PaymentMethodNonce = nonce,
Options = new PaymentMethodOptionsRequest()
{
VerifyCard = true,
VerificationCurrencyIsoCode = "GBP"
}
};
Result<PaymentMethod> paymentMethodResult = gateway.PaymentMethod.Create(request);
Assert.IsFalse(paymentMethodResult.IsSuccess());
Assert.AreEqual(
ValidationErrorCode.CREDIT_CARD_OPTIONS_VERIFICATION_INVALID_PRESENTMENT_CURRENCY,
paymentMethodResult.Errors.DeepAll()[0].Code
);
}
[Test]
public void Update_UpdatePaymentMethodWithMerchantCurrencyOption()
{
var customer = gateway.Customer.Create().Target;
var creditCard = gateway.CreditCard.Create(new CreditCardRequest
{
CardholderName = "Original Holder",
CustomerId = customer.Id,
CVV = "123",
Number = SandboxValues.CreditCardNumber.VISA,
ExpirationDate = "05/2012",
}).Target;
Result<PaymentMethod> paymentMethodResult = gateway.PaymentMethod.Update(
creditCard.Token,
new PaymentMethodRequest
{
CardholderName = "New Holder",
CVV = "456",
Number = TestUtil.CreditCardNumbers.FailsSandboxVerification.MasterCard,
ExpirationDate = "06/2013",
Options = new PaymentMethodOptionsRequest
{
VerificationCurrencyIsoCode = "USD"
}
});
Assert.IsTrue(paymentMethodResult.IsSuccess());
}
[Test]
public void Update_UpdatePaymentMethodWithInvalidMerchantCurrencyOption()
{
var customer = gateway.Customer.Create().Target;
var creditCard = gateway.CreditCard.Create(new CreditCardRequest
{
CardholderName = "Original Holder",
CustomerId = customer.Id,
CVV = "123",
Number = SandboxValues.CreditCardNumber.VISA,
ExpirationDate = "05/2012",
}).Target;
Result<PaymentMethod> paymentMethodResult = gateway.PaymentMethod.Update(
creditCard.Token,
new PaymentMethodRequest
{
CardholderName = "New Holder",
CVV = "456",
Number = TestUtil.CreditCardNumbers.FailsSandboxVerification.MasterCard,
ExpirationDate = "06/2013",
Options = new PaymentMethodOptionsRequest
{
VerifyCard = true,
VerificationCurrencyIsoCode = "GBP"
}
});
Assert.IsFalse(paymentMethodResult.IsSuccess());
Assert.AreEqual(
ValidationErrorCode.CREDIT_CARD_OPTIONS_VERIFICATION_INVALID_PRESENTMENT_CURRENCY,
paymentMethodResult.Errors.DeepAll()[0].Code
);
}
}
}
| |
// Copyright (c) DotSpatial Team. All rights reserved.
// Licensed under the MIT license. See License.txt file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using DotSpatial.Serialization;
namespace DotSpatial.Symbology
{
/// <summary>
/// LineDecoration.
/// </summary>
[Serializable]
public class LineDecoration : Descriptor, ILineDecoration
{
#region Fields
private bool _flipAll;
private bool _flipFirst;
private int _numSymbols;
private double _offset;
private int _percentualPosition;
private bool _rotateWithLine;
private IPointSymbolizer _symbol;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="LineDecoration"/> class.
/// </summary>
public LineDecoration()
{
_symbol = new PointSymbolizer(SymbologyGlobal.RandomColor(), PointShape.Triangle, 10);
_flipAll = false;
_flipFirst = true;
_rotateWithLine = true;
_numSymbols = 2;
}
#endregion
#region Properties
/// <summary>
/// Gets or sets a value indicating whether all of the symbols should be flipped.
/// </summary>
[Serialize("FlipAll")]
public bool FlipAll
{
get
{
return _flipAll;
}
set
{
_flipAll = value;
}
}
/// <summary>
/// Gets or sets a value indicating whether the first symbol in relation to the direction of the line should be flipped.
/// </summary>
[Serialize("FlipFirst")]
public bool FlipFirst
{
get
{
return _flipFirst;
}
set
{
_flipFirst = value;
}
}
/// <summary>
/// Gets or sets the number of symbols that should be drawn on each line. (not each segment).
/// </summary>
[Serialize("NumSymbols")]
public int NumSymbols
{
get
{
return _numSymbols;
}
set
{
_numSymbols = value;
}
}
/// <summary>
/// Gets or sets the offset distance measured to the left of the line in pixels.
/// </summary>
[Serialize("Offset")]
public double Offset
{
get
{
return _offset;
}
set
{
_offset = value;
}
}
/// <summary>
/// Gets or sets the percentual position between line start and end at which the single decoration gets drawn.
/// </summary>
[Serialize("PercentualPosition")]
public int PercentualPosition
{
get
{
return _percentualPosition;
}
set
{
_percentualPosition = value;
}
}
/// <summary>
/// Gets or sets a value indicating whether the symbol should be rotated according to the direction of the line. Arrows
/// at the ends, for instance, will point along the direction of the line, regardless of the direction of the line.
/// </summary>
[Serialize("RotateWithLine")]
public bool RotateWithLine
{
get
{
return _rotateWithLine;
}
set
{
_rotateWithLine = value;
}
}
/// <summary>
/// Gets or sets the decorative symbol.
/// </summary>
[Serialize("Symbol")]
public IPointSymbolizer Symbol
{
get
{
return _symbol;
}
set
{
_symbol = value;
}
}
#endregion
#region Methods
/// <summary>
/// Given the points on this line decoration, this will cycle through and handle
/// the drawing as dictated by this decoration.
/// </summary>
/// <param name="g">The graphics object used for drawing.</param>
/// <param name="path">The path of the line.</param>
/// <param name="scaleWidth">The double scale width for controling markers.</param>
public void Draw(Graphics g, GraphicsPath path, double scaleWidth)
{
if (NumSymbols == 0) return;
GraphicsPathIterator myIterator = new GraphicsPathIterator(path);
myIterator.Rewind();
int start, end;
bool isClosed;
Size2D symbolSize = _symbol.GetSize();
Bitmap symbol = new Bitmap((int)symbolSize.Width, (int)symbolSize.Height);
Graphics sg = Graphics.FromImage(symbol);
_symbol.Draw(sg, new Rectangle(0, 0, (int)symbolSize.Width, (int)symbolSize.Height));
sg.Dispose();
Matrix oldMat = g.Transform;
PointF[] points;
if (path.PointCount == 0) return;
try
{
points = path.PathPoints;
}
catch
{
return;
}
while (myIterator.NextSubpath(out start, out end, out isClosed) > 0)
{
if (NumSymbols == 1)
{
// single decoration spot
if (_percentualPosition == 0)
{
// at start of the line
DrawImage(g, points[start], points[start + 1], points[start], FlipFirst ^ FlipAll, symbol, oldMat);
}
else if (_percentualPosition == 100)
{
// at end of the line
DrawImage(g, points[end - 1], points[end], points[end], FlipFirst ^ FlipAll, symbol, oldMat);
}
else
{
// somewhere in between start and end
double totalLength = GetLength(points, start, end);
double span = totalLength * _percentualPosition / 100;
List<DecorationSpot> spot = GetPosition(points, span, start, end);
if (spot.Count > 1) DrawImage(g, spot[1].Before, spot[1].After, spot[1].Position, FlipFirst ^ FlipAll, symbol, oldMat);
}
}
else
{
// more than one decoration spot
double totalLength = GetLength(points, start, end);
double span = Math.Round(totalLength / (NumSymbols - 1), 4);
List<DecorationSpot> spots = GetPosition(points, span, start, end);
spots.Add(new DecorationSpot(points[end - 1], points[end], points[end])); // add the missing end point
for (int i = 0; i < spots.Count; i++) DrawImage(g, spots[i].Before, spots[i].After, spots[i].Position, i == 0 ? (FlipFirst ^ FlipAll) : FlipAll, symbol, oldMat);
}
}
}
/// <summary>
/// Gets the size that is needed to draw this decoration with max. 2 symbols.
/// </summary>
/// <returns>The legend symbol size.</returns>
public Size GetLegendSymbolSize()
{
Size size = _symbol.GetLegendSymbolSize();
if (NumSymbols >= 1) size.Width *= 2; // add space for the line between the decorations
return size;
}
/// <summary>
/// Handles the creation of random content for the LineDecoration.
/// </summary>
/// <param name="generator">The Random class that generates random numbers.</param>
protected override void OnRandomize(Random generator)
{
base.OnRandomize(generator);
// _symbol is randomizable so the base method already will have randomized this class
_flipAll = generator.NextBool();
_flipFirst = generator.NextBool();
_rotateWithLine = generator.NextBool();
_numSymbols = generator.Next(0, 10);
_offset = generator.NextDouble() * 10;
}
/// <summary>
/// Flips the given angle by 180 degree.
/// </summary>
/// <param name="angle">Angle, that should be flipped.</param>
private static void FlipAngle(ref float angle)
{
angle = angle + 180;
if (angle > 360) angle -= 360;
}
/// <summary>
/// Gets the angle of the line between StartPoint and EndPoint taking into account the direction of the line.
/// </summary>
/// <param name="startPoint">StartPoint of the line.</param>
/// <param name="endPoint">EndPoint of the line.</param>
/// <returns>Angle of the given line.</returns>
private static float GetAngle(PointF startPoint, PointF endPoint)
{
double deltaX = endPoint.X - startPoint.X;
double deltaY = endPoint.Y - startPoint.Y;
double angle = Math.Atan(deltaY / deltaX);
if (deltaX < 0)
{
if (deltaY <= 0) angle += Math.PI;
if (deltaY > 0) angle -= Math.PI;
}
return (float)(angle * 180.0 / Math.PI);
}
/// <summary>
/// Gets the length of the line between startpoint and endpoint.
/// </summary>
/// <param name="startPoint">Startpoint of the line.</param>
/// <param name="endPoint">Endpoint of the line.</param>
/// <returns>Length of the line.</returns>
private static double GetLength(PointF startPoint, PointF endPoint)
{
double dx = endPoint.X - startPoint.X;
double dy = endPoint.Y - startPoint.Y;
return Math.Sqrt(dx * dx + dy * dy);
}
/// <summary>
/// Gets the length of all the lines between startpoint and endpoint.
/// </summary>
/// <param name="points">Points of the lines we want to measure.</param>
/// <param name="start">Startpoint of measuring.</param>
/// <param name="end">Endpoint of measuring.</param>
/// <returns>Combined length of all lines between startpoint and endpoint.</returns>
private static double GetLength(PointF[] points, int start, int end)
{
double result = 0;
for (int i = start; i < end; i++)
{
result += GetLength(points[i], points[i + 1]);
}
return result;
}
/// <summary>
/// Get the decoration spots that result from the given line and segLength. The decoration spot needed for the endpoint is not included.
/// </summary>
/// <param name="points">Point-Array that contains the points of the line.</param>
/// <param name="segLength">Distance between two decoration spots.</param>
/// <param name="start">Index of the first point that belongs to the line.</param>
/// <param name="end">Index of the last point that belongs to the line.</param>
/// <returns>List of decoration spots that result from the given points and segLength.</returns>
private static List<DecorationSpot> GetPosition(PointF[] points, double segLength, int start, int end)
{
double coveredDistance = 0; // distance between the last decoration spot and the line end; needed to get the correct position of the next decoration spot on the next line
List<DecorationSpot> liste = new List<DecorationSpot>();
for (int i = start; i < end; i++)
{
if (coveredDistance == 0)
{
// startpoint of the first line or last segment ended on startpoint of next line
DecorationSpot result = new DecorationSpot(points[i], points[i + 1], points[i]);
liste.Add(result);
coveredDistance = 0;
if (double.IsInfinity(segLength)) return liste; // when segLength is infinit we're looking only for the first decoration spot
}
double dx = points[i + 1].X - points[i].X;
double dy = points[i + 1].Y - points[i].Y;
double lineLength = Math.Sqrt(dx * dx + dy * dy);
if (coveredDistance + lineLength <= segLength)
{
coveredDistance += lineLength;
continue; // line was shorter than segment -> does not contain any decorations
}
double offset = segLength - coveredDistance; // offset of the first decoration spot
if (dx == 0)
{
// line is parallel to y-axis
while (Math.Round(offset, 3) < Math.Round(lineLength, 3))
{
float x = points[i].X;
float y;
if (points[i].Y > points[i + 1].Y)
{
// line goes bottom up
y = (float)(points[i].Y - offset);
}
else
{
// line goes top down
y = (float)(points[i].Y + offset);
}
liste.Add(new DecorationSpot(points[i], points[i + 1], new PointF(x, y)));
offset += segLength;
}
if (Math.Round(offset, 3) > Math.Round(lineLength, 3))
{
var lastpnt = liste[liste.Count - 1];
coveredDistance = GetLength(lastpnt.Position, lastpnt.After);
}
else
{
coveredDistance = 0; // segment ends on endpoint of the current line -> reset coveredDistance to add a decoration spot at the beginning of the next line
}
}
else
{
// line is not parallel to y-axis
double slope = dy / dx;
double alpha = Math.Atan(slope);
while (Math.Round(offset, 3) < Math.Round(lineLength, 3))
{
float x, y;
if (points[i].X < points[i + 1].X)
{
// line goes right to left
x = (float)(points[i].X + Math.Cos(alpha) * offset);
y = (float)(points[i].Y + Math.Sin(alpha) * offset);
}
else
{
// line goes left to right
x = (float)(points[i].X - Math.Cos(alpha) * offset);
y = (float)(points[i].Y - Math.Sin(alpha) * offset);
}
var newPoint = new PointF(x, y);
liste.Add(new DecorationSpot(points[i], points[i + 1], newPoint));
offset += segLength;
}
if (Math.Round(offset, 3) > Math.Round(lineLength, 3))
{
var lastpnt = liste[liste.Count - 1];
coveredDistance = GetLength(lastpnt.Position, lastpnt.After);
}
else
{
coveredDistance = 0; // segment ends on endpoint of the current line -> reset coveredDistance to add a decoration spot at the beginning of the next line
}
}
}
return liste;
}
/// <summary>
/// Draws the given symbol at the position calculated from locationPoint and _offset.
/// </summary>
/// <param name="g">Graphics-object needed for drawing.</param>
/// <param name="startPoint">StartPoint of the line locationPoint belongs to. Needed for caluclating the angle and the offset of the symbol.</param>
/// <param name="stopPoint">StopPoint of the line locationPoint belongs to. Needed for caluclating the angle and the offset of the symbol.</param>
/// <param name="locationPoint">Position where the center of the image should be drawn.</param>
/// <param name="flip">Indicates whether the symbol should be flipped.</param>
/// <param name="symbol">Image that gets drawn.</param>
/// <param name="oldMat">Matrix used for rotation.</param>
private void DrawImage(Graphics g, PointF startPoint, PointF stopPoint, PointF locationPoint, bool flip, Bitmap symbol, Matrix oldMat)
{
// Move the point to the position including the offset
PointF offset = stopPoint == locationPoint ? GetOffset(startPoint, locationPoint) : GetOffset(locationPoint, stopPoint);
var point = new PointF(locationPoint.X + offset.X, locationPoint.Y + offset.Y);
// rotate it by the given angle
float angle = 0F;
if (_rotateWithLine) angle = GetAngle(startPoint, stopPoint);
if (flip) FlipAngle(ref angle);
Matrix rotated = g.Transform;
rotated.RotateAt(angle, point);
g.Transform = rotated;
// correct the position so that the symbol is drawn centered
point.X -= (float)symbol.Width / 2;
point.Y -= (float)symbol.Height / 2;
g.DrawImage(symbol, point);
g.Transform = oldMat;
}
/// <summary>
/// Calculates the offset needed to show the decoration spot of each line at the same position as it is shown for the horizontal line in the linesymbol editor window.
/// </summary>
/// <param name="point">Startpoint of the line the decoration spot belongs to.</param>
/// <param name="nextPoint">Endpoint of the line the decoration spot belongs to.</param>
/// <returns>Offset that must be added to the decoration spots locationPoint for it to be drawn with the given _offset.</returns>
private PointF GetOffset(PointF point, PointF nextPoint)
{
var dX = nextPoint.X - point.X;
var dY = nextPoint.Y - point.Y;
var alpha = Math.Atan(-dX / dY);
double x, y;
if (dX == 0 && point.Y > nextPoint.Y)
{
// line is parallel to y-axis and goes bottom up
x = Math.Cos(alpha) * -_offset;
y = Math.Sin(alpha) * _offset;
}
else if (dY != 0 && point.Y > nextPoint.Y)
{
// line goes bottom up
x = Math.Cos(alpha) * -_offset;
y = Math.Sin(alpha) * -_offset;
}
else
{
// line is parallel to x-axis or goes top down
x = Math.Cos(alpha) * _offset;
y = Math.Sin(alpha) * _offset;
}
return new PointF((float)x, (float)y);
}
#endregion
#region Classes
private struct DecorationSpot
{
/// <summary>
/// Initializes a new instance of the <see cref="DecorationSpot"/> struct.
/// </summary>
/// <param name="before">The start point of the line the decoration belongs to.</param>
/// <param name="after">The end point of the line the decoration belongs to.</param>
/// <param name="position">The position of this decoration spot.</param>
public DecorationSpot(PointF before, PointF after, PointF position)
{
After = after;
Before = before;
Position = position;
}
/// <summary>
/// Gets the end point of the line the decoration belongs to.
/// </summary>
public PointF After { get; }
/// <summary>
/// Gets the start point of the line the decoration belongs to.
/// </summary>
public PointF Before { get; }
/// <summary>
/// Gets the position of this decoration spot.
/// </summary>
public PointF Position { get; }
}
#endregion
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
[System.Serializable]
public class Knot
{
public float distanceFromStart = -1f;
public CatmullRomSpline.SubKnot[] subKnots = new CatmullRomSpline.SubKnot[CatmullRomSpline.NbSubSegmentPerSegment+1]; //[0, 1]
public Vector3 position;
public Knot(Vector3 position)
{
this.position = position;
}
public void Invalidate()
{
distanceFromStart = -1f;
}
}
public class CatmullRomSpline
{
public struct SubKnot
{
public float distanceFromStart;
public Vector3 position;
public Vector3 tangent;
}
public class Marker
{
public int segmentIndex;
public int subKnotAIndex;
public int subKnotBIndex;
public float lerpRatio;
}
public List<Knot> knots = new List<Knot>();
public const int NbSubSegmentPerSegment = 10;
private const int MinimumKnotNb = 4;
private const int FirstSegmentKnotIndex = 2;
public int NbSegments { get { return System.Math.Max(0, knots.Count - 3); } }
public Vector3 FindPositionFromDistance(float distance)
{
Vector3 tangent = Vector3.zero;
Marker result = new Marker();
bool foundSegment = PlaceMarker(result, distance);
if(foundSegment)
{
tangent = GetPosition(result);
}
return tangent;
}
public Vector3 FindTangentFromDistance(float distance)
{
Vector3 tangent = Vector3.zero;
Marker result = new Marker();
bool foundSegment = PlaceMarker(result, distance);
if(foundSegment)
{
tangent = GetTangent(result);
}
return tangent;
}
public static Vector3 ComputeBinormal(Vector3 tangent, Vector3 normal)
{
return Vector3.Cross(tangent, normal).normalized;
//Switch the orientation of the mesh - now we need the mesh normal to always look at the camera
//I think Dot Product with froward from ca,mera and normal is the solution
//return normal.normalized;
}
public float Length()
{
if(NbSegments == 0) return 0f;
//Parametrize();
return System.Math.Max(0, GetSegmentDistanceFromStart(NbSegments-1));
}
public void Clear()
{
knots.Clear();
}
public void MoveMarker(Marker marker, float distance) //in Unity units
{
PlaceMarker(marker, distance, marker);
}
public Vector3 GetPosition(Marker marker)
{
Vector3 pos = Vector3.zero;
if (NbSegments == 0) return pos;
//Debug.Log(NbSegments);
SubKnot[] subKnots = GetSegmentSubKnots(marker.segmentIndex);
pos = Vector3.Lerp(subKnots[marker.subKnotAIndex].position,
subKnots[marker.subKnotBIndex].position, marker.lerpRatio);
return pos;
}
public Vector3 GetTangent(Marker marker)
{
Vector3 tangent = Vector3.zero;
if(NbSegments == 0) return tangent;
SubKnot[] subKnots = GetSegmentSubKnots(marker.segmentIndex);
tangent = Vector3.Lerp(subKnots[marker.subKnotAIndex].tangent,
subKnots[marker.subKnotBIndex].tangent, marker.lerpRatio);
return tangent;
}
private float Epsilon { get { return 1f / NbSubSegmentPerSegment; } }
private SubKnot[] GetSegmentSubKnots(int i)
{
return knots[FirstSegmentKnotIndex+i].subKnots;
}
public float GetSegmentDistanceFromStart(int i)
{
return knots[FirstSegmentKnotIndex+i].distanceFromStart;
}
private bool IsSegmentValid(int i)
{
return knots[i].distanceFromStart != -1f && knots[i+1].distanceFromStart != -1f &&
knots[i+2].distanceFromStart != -1f && knots[i+3].distanceFromStart != -1f;
}
private bool OutOfBoundSegmentIndex(int i)
{
return i < 0 || i >= NbSegments;
}
public void Parametrize()
{
Parametrize(0, NbSegments-1);
}
public void Parametrize(int fromSegmentIndex, int toSegmentIndex)
{
if(knots.Count < MinimumKnotNb) return;
int nbSegments = System.Math.Min(toSegmentIndex+1, NbSegments);
fromSegmentIndex = System.Math.Max(0, fromSegmentIndex);
float totalDistance = 0;
if(fromSegmentIndex > 0)
{
totalDistance = GetSegmentDistanceFromStart(fromSegmentIndex-1);
}
for(int i=fromSegmentIndex; i<nbSegments; i++)
{
/*if(IsSegmentValid(i) && !force)
{
totalDistance = GetSegmentDistanceFromStart(i);
continue;
}*/
SubKnot[] subKnots = GetSegmentSubKnots(i);
//We start looping at 2 because the two first knot are at the origin - initially it was starting to loop at 0
for (int j=2; j<subKnots.Length; j++)
{
SubKnot sk = new SubKnot();
sk.distanceFromStart = totalDistance += ComputeLengthOfSegment(i, (j-1)*Epsilon, j*Epsilon);
sk.position = GetPositionOnSegment(i, j*Epsilon);
sk.tangent = GetTangentOnSegment(i, j*Epsilon);
subKnots[j] = sk;
}
knots[FirstSegmentKnotIndex+i].distanceFromStart = totalDistance;
}
}
public bool PlaceMarker(Marker result, float distance, Marker from = null)
{
//result = new Marker();
SubKnot[] subKnots;
int nbSegments = NbSegments;
if(nbSegments == 0) return false;
//Parametrize();
if(distance <= 0)
{
result.segmentIndex = 0;
result.subKnotAIndex = 0;
result.subKnotBIndex = 1;
result.lerpRatio = 0f;
return true;
}
else if(distance >= Length())
{
subKnots = GetSegmentSubKnots(nbSegments-1);
result.segmentIndex = nbSegments-1;
result.subKnotAIndex = subKnots.Length-2;
result.subKnotBIndex = subKnots.Length-1;
result.lerpRatio = 1f;
return true;
}
int fromSegmentIndex = 0;
int fromSubKnotIndex = 1;
if(from != null)
{
fromSegmentIndex = from.segmentIndex;
//fromSubKnotIndex = from.subKnotAIndex;
}
for(int i=fromSegmentIndex; i<nbSegments; i++)
{
if(distance > GetSegmentDistanceFromStart(i)) continue;
subKnots = GetSegmentSubKnots(i);
for(int j=fromSubKnotIndex; j<subKnots.Length; j++)
{
SubKnot sk = subKnots[j];
if(distance > sk.distanceFromStart) continue;
result.segmentIndex = i;
result.subKnotAIndex = j-1;
result.subKnotBIndex = j;
result.lerpRatio = 1f - ((sk.distanceFromStart - distance) /
(sk.distanceFromStart - subKnots[j-1].distanceFromStart));
break;
}
break;
}
return true;
}
private float ComputeLength()
{
if(knots.Count < 4) return 0;
float length = 0;
int nbSegments = NbSegments;
//We start looping at 3 because the two first knot are at the origin - initially it was starting to loop at 0
for (int i=3; i<nbSegments; i++)
{
length += ComputeLengthOfSegment(i, 0f, 1f);
}
return length;
}
private float ComputeLengthOfSegment(int segmentIndex, float from, float to)
{
float length = 0;
from = Mathf.Clamp01(from);
to = Mathf.Clamp01(to);
Vector3 lastPoint = GetPositionOnSegment(segmentIndex, from);
for(float j=from+Epsilon; j<to+Epsilon/2f; j+=Epsilon)
{
Vector3 point = GetPositionOnSegment(segmentIndex, j);
length += Vector3.Distance(point, lastPoint);
lastPoint = point;
}
return length;
}
public void DebugDrawEquallySpacedDots()
{
Gizmos.color = Color.red;
int nbPoints = NbSubSegmentPerSegment*NbSegments;
float length = Length();
Marker marker = new Marker();
PlaceMarker(marker, 0f);
for(int i=0; i<=nbPoints; i++)
{
MoveMarker(marker, i*(length/nbPoints));
Vector3 position = GetPosition(marker);
//Vector3 tangent = GetTangent(marker);
//Vector3 position = FindPositionFromDistance(i*(length/nbPoints));
//Vector3 tangent = FindTangentFromDistance(i*(length/nbPoints));
//Vector3 binormal = ComputeBinormal(tangent, new Vector3(0, 0, 1));
Gizmos.DrawWireSphere(position, 0.025f);
//Debug.DrawRay(position, binormal * 0.2f, Color.green);
}
}
public void DebugDrawSubKnots()
{
Gizmos.color = Color.yellow;
int nbSegments = NbSegments;
//We start looping at 3 because the two first knot are at the origin - initially it was starting to loop at 0
for (int i=3; i<nbSegments; i++)
{
SubKnot[] subKnots = GetSegmentSubKnots(i);
for(int j=0; j<subKnots.Length; j++)
{
Gizmos.DrawWireSphere(subKnots[j].position, 0.025f);
//Gizmos.DrawWireSphere(new Vector3(segments[i].subSegments[j].length, 0, 0), 0.025f);
}
}
}
public void DebugDrawSpline()
{
if (knots.Count >= 4)
{
Gizmos.color = Color.green;
Gizmos.DrawWireSphere(knots[0].position, 0.2f);
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(knots[knots.Count - 1].position, 0.2f);
Gizmos.color = Color.blue;
Gizmos.DrawWireSphere(knots[knots.Count - 2].position, 0.2f);
int nbSegments = NbSegments;
//We start looping at 3 because the two first knot are at the origin - initially it was starting to loop at 0
for (int i = 3; i < nbSegments; i++)
{
Vector3 lastPoint = GetPositionOnSegment(i, 0f);
Gizmos.DrawWireSphere(lastPoint, 0.2f);
for (float j = Epsilon; j < 1f + Epsilon / 2f; j += Epsilon)
{
Vector3 point = GetPositionOnSegment(i, j);
Debug.DrawLine(lastPoint, point, Color.green);
lastPoint = point;
}
}
}
}
private Vector3 GetPositionOnSegment(int segmentIndex, float t)
{
return FindSplinePoint(knots[segmentIndex].position, knots[segmentIndex+1].position,
knots[segmentIndex+2].position, knots[segmentIndex+3].position, t);
}
private Vector3 GetTangentOnSegment(int segmentIndex, float t)
{
return FindSplineTangent(knots[segmentIndex].position, knots[segmentIndex+1].position,
knots[segmentIndex+2].position, knots[segmentIndex+3].position, t).normalized;
}
private static Vector3 FindSplinePoint(Vector3 p0, Vector3 p1, Vector3 p2, Vector3 p3, float t)
{
Vector3 ret = new Vector3();
float t2 = t * t;
float t3 = t2 * t;
ret.x = 0.5f * ((2.0f * p1.x) +
(-p0.x + p2.x) * t +
(2.0f * p0.x - 5.0f * p1.x + 4 * p2.x - p3.x) * t2 +
(-p0.x + 3.0f * p1.x - 3.0f * p2.x + p3.x) * t3);
ret.y = 0.5f * ((2.0f * p1.y) +
(-p0.y + p2.y) * t +
(2.0f * p0.y - 5.0f * p1.y + 4 * p2.y - p3.y) * t2 +
(-p0.y + 3.0f * p1.y - 3.0f * p2.y + p3.y) * t3);
ret.z = 0.5f * ((2.0f * p1.z) +
(-p0.z + p2.z) * t +
(2.0f * p0.z - 5.0f * p1.z + 4 * p2.z - p3.z) * t2 +
(-p0.z + 3.0f * p1.z - 3.0f * p2.z + p3.z) * t3);
return ret;
}
private static Vector3 FindSplineTangent(Vector3 p0, Vector3 p1, Vector3 p2, Vector3 p3, float t)
{
Vector3 ret = new Vector3();
float t2 = t * t;
ret.x = 0.5f * (-p0.x + p2.x) +
(2.0f * p0.x - 5.0f * p1.x + 4 * p2.x - p3.x) * t +
(-p0.x + 3.0f * p1.x - 3.0f * p2.x + p3.x) * t2 * 1.5f;
ret.y = 0.5f * (-p0.y + p2.y) +
(2.0f * p0.y - 5.0f * p1.y + 4 * p2.y - p3.y) * t +
(-p0.y + 3.0f * p1.y - 3.0f * p2.y + p3.y) * t2 * 1.5f;
ret.z = 0.5f * (-p0.z + p2.z) +
(2.0f * p0.z - 5.0f * p1.z + 4 * p2.z - p3.z) * t +
(-p0.z + 3.0f * p1.z - 3.0f * p2.z + p3.z) * t2 * 1.5f;
return ret;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.