context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
#region File Description
//-----------------------------------------------------------------------------
// GameplayScreen.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Devices.Sensors;
using GameStateManagement;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Input.Touch;
using Microsoft.Devices;
using Microsoft.Xna.Framework.Audio;
#endregion
namespace MarbleMazeGame
{
class GameplayScreen : GameScreen
{
#region Fields
bool gameOver = false;
Maze maze;
Marble marble;
Camera camera;
LinkedListNode<Vector3> lastCheackpointNode;
public new bool IsActive = true;
readonly float angularVelocity = MathHelper.ToRadians(1.5f);
SpriteFont timeFont;
TimeSpan gameTime;
#endregion
#region Initializations
public GameplayScreen()
{
TransitionOnTime = TimeSpan.FromSeconds(0.0);
TransitionOffTime = TimeSpan.FromSeconds(0.0);
}
#endregion
#region Loading
/// <summary>
/// Load the game content
/// </summary>
public override void LoadContent()
{
timeFont = ScreenManager.Game.Content.Load<SpriteFont>(@"Fonts\MenuFont");
LoadAssets();
Accelerometer.Initialize();
base.LoadContent();
}
/// <summary>
/// Load all assets for the game
/// </summary>
public void LoadAssets()
{
InitializeCamera();
InitializeMaze();
InitializeMarble();
}
/// <summary>
/// Initialize the camera
/// </summary>
private void InitializeCamera()
{
// Create the camera
camera = new Camera(ScreenManager.Game, ScreenManager.GraphicsDevice);
camera.Initialize();
}
/// <summary>
/// Initialize maze
/// </summary>
private void InitializeMaze()
{
maze = new Maze(ScreenManager.Game)
{
Position = Vector3.Zero,
Camera = camera
};
maze.Initialize();
// Save the last checkpoint
lastCheackpointNode = maze.Checkpoints.First;
}
/// <summary>
/// Initialize the marble
/// </summary>
private void InitializeMarble()
{
marble = new Marble(ScreenManager.Game)
{
Position = maze.StartPoistion,
Camera = camera,
Maze = maze
};
marble.Initialize();
}
#endregion
#region Update
/// <summary>
/// Handle all the input.
/// </summary>
/// <param name="input"></param>
public override void HandleInput(InputState input)
{
if (input == null)
throw new ArgumentNullException("input");
// Rotate the maze according to accelerometer data
Vector3 currentAccelerometerState = Accelerometer.GetState().Acceleration;
if (Microsoft.Devices.Environment.DeviceType == DeviceType.Device)
{
//Change the velocity according to acceleration reading
maze.Rotation.Z = (float)Math.Round(MathHelper.ToRadians(currentAccelerometerState.Y * 30), 2);
maze.Rotation.X = -(float)Math.Round(MathHelper.ToRadians(currentAccelerometerState.X * 30), 2);
}
else if (Microsoft.Devices.Environment.DeviceType == DeviceType.Emulator)
{
Vector3 Rotation = Vector3.Zero;
if (currentAccelerometerState.X != 0)
{
if (currentAccelerometerState.X > 0)
Rotation += new Vector3(0, 0, -angularVelocity);
else
Rotation += new Vector3(0, 0, angularVelocity);
}
if (currentAccelerometerState.Y != 0)
{
if (currentAccelerometerState.Y > 0)
Rotation += new Vector3(-angularVelocity, 0, 0);
else
Rotation += new Vector3(angularVelocity, 0, 0);
}
// Limit the rotation of the maze to 30 degrees
maze.Rotation.X =
MathHelper.Clamp(maze.Rotation.X + Rotation.X,
MathHelper.ToRadians(-30), MathHelper.ToRadians(30));
maze.Rotation.Z =
MathHelper.Clamp(maze.Rotation.Z + Rotation.Z,
MathHelper.ToRadians(-30), MathHelper.ToRadians(30));
}
}
/// <summary>
/// Update all the game component
/// </summary>
/// <param name="gameTime"></param>
/// <param name="otherScreenHasFocus"></param>
/// <param name="coveredByOtherScreen"></param>
public override void Update(GameTime gameTime, bool otherScreenHasFocus, bool coveredByOtherScreen)
{
// Calculate the time from the start of the game
this.gameTime += gameTime.ElapsedGameTime;
CheckFallInPit();
UpdateLastCheackpoint();
// Update all the component of the game
maze.Update(gameTime);
marble.Update(gameTime);
camera.Update(gameTime);
CheckGameFinish();
base.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen);
}
#endregion
#region Render
/// <summary>
/// Draw all the game component
/// </summary>
/// <param name="gameTime"></param>
public override void Draw(GameTime gameTime)
{
ScreenManager.GraphicsDevice.Clear(Color.Black);
ScreenManager.SpriteBatch.Begin();
// Draw the elapsed time
ScreenManager.SpriteBatch.DrawString(timeFont,
String.Format("{0:00}:{1:00}", this.gameTime.Minutes,
this.gameTime.Seconds), new Vector2(20, 20), Color.YellowGreen);
// Drawing sprites changes some render states around, which don't play
// nicely with 3d models.
// In particular, we need to enable the depth buffer.
DepthStencilState depthStensilState =
new DepthStencilState() { DepthBufferEnable = true };
ScreenManager.GraphicsDevice.DepthStencilState = depthStensilState;
// Draw all the game components
maze.Draw(gameTime);
marble.Draw(gameTime);
ScreenManager.SpriteBatch.End();
base.Draw(gameTime);
}
#endregion
#region Private functions
/// <summary>
/// Update the last checkpoint to return to after falling in a pit.
/// </summary>
private void UpdateLastCheackpoint()
{
BoundingSphere marblePosition = marble.BoundingSphereTransformed;
var tmp = lastCheackpointNode;
while (tmp.Next != null)
{
// If the marble is close to a checkpoint save the checkpoint
if (Math.Abs(Vector3.Distance(marblePosition.Center, tmp.Next.Value))
<= marblePosition.Radius * 3)
{
lastCheackpointNode = tmp.Next;
return;
}
tmp = tmp.Next;
}
}
/// <summary>
/// If marble falls in a pit, return the marble to the last checkpoint
/// the marble passed.
/// </summary>
private void CheckFallInPit()
{
if (marble.Position.Y < -150)
{
marble.Position = lastCheackpointNode.Value;
maze.Rotation = Vector3.Zero;
marble.Acceleration = Vector3.Zero;
marble.Velocity = Vector3.Zero;
}
}
/// <summary>
/// Check if the game has ended.
/// </summary>
private void CheckGameFinish()
{
BoundingSphere marblePosition = marble.BoundingSphereTransformed;
if (Math.Abs(Vector3.Distance(marblePosition.Center, maze.End)) <= marblePosition.Radius * 3)
{
gameOver = true;
return;
}
}
#endregion
}
}
| |
//
// 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.
//
namespace NLog.Config
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml;
using NLog.Common;
using NLog.Internal;
using NLog.Layouts;
using JetBrains.Annotations;
/// <summary>
/// A class for configuring NLog through an XML configuration file
/// (App.config style or App.nlog style).
///
/// Parsing of the XML file is also implemented in this class.
/// </summary>
///<remarks>
/// - This class is thread-safe.<c>.ToList()</c> is used for that purpose.
/// - Update TemplateXSD.xml for changes outside targets
/// </remarks>
public class XmlLoggingConfiguration : LoggingConfigurationParser, IInitializeSucceeded
{
private readonly Dictionary<string, bool> _fileMustAutoReloadLookup = new Dictionary<string, bool>(StringComparer.OrdinalIgnoreCase);
private string _originalFileName;
private readonly Stack<string> _currentFilePath = new Stack<string>();
internal XmlLoggingConfiguration(LogFactory logFactory)
: base(logFactory)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class.
/// </summary>
/// <param name="fileName">Configuration file to be read.</param>
public XmlLoggingConfiguration([NotNull] string fileName)
: this(fileName, LogManager.LogFactory)
{ }
/// <summary>
/// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class.
/// </summary>
/// <param name="fileName">Configuration file to be read.</param>
/// <param name="logFactory">The <see cref="LogFactory" /> to which to apply any applicable configuration values.</param>
public XmlLoggingConfiguration([NotNull] string fileName, LogFactory logFactory)
: base(logFactory)
{
LoadFromXmlFile(fileName);
}
/// <summary>
/// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class.
/// </summary>
/// <param name="fileName">Configuration file to be read.</param>
/// <param name="ignoreErrors">Ignore any errors during configuration.</param>
[Obsolete("Constructor with parameter ignoreErrors has limited effect. Instead use LogManager.ThrowConfigExceptions. Marked obsolete in NLog 4.7")]
public XmlLoggingConfiguration([NotNull] string fileName, bool ignoreErrors)
: this(fileName, ignoreErrors, LogManager.LogFactory)
{ }
/// <summary>
/// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class.
/// </summary>
/// <param name="fileName">Configuration file to be read.</param>
/// <param name="ignoreErrors">Ignore any errors during configuration.</param>
/// <param name="logFactory">The <see cref="LogFactory" /> to which to apply any applicable configuration values.</param>
[Obsolete("Constructor with parameter ignoreErrors has limited effect. Instead use LogManager.ThrowConfigExceptions. Marked obsolete in NLog 4.7")]
public XmlLoggingConfiguration([NotNull] string fileName, bool ignoreErrors, LogFactory logFactory)
: base(logFactory)
{
using (XmlReader reader = CreateFileReader(fileName))
{
Initialize(reader, fileName, ignoreErrors);
}
}
/// <summary>
/// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class.
/// </summary>
/// <param name="reader">XML reader to read from.</param>
public XmlLoggingConfiguration([NotNull] XmlReader reader)
: this(reader, null) { }
/// <summary>
/// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class.
/// </summary>
/// <param name="reader"><see cref="XmlReader"/> containing the configuration section.</param>
/// <param name="fileName">Name of the file that contains the element (to be used as a base for including other files). <c>null</c> is allowed.</param>
public XmlLoggingConfiguration([NotNull] XmlReader reader, [CanBeNull] string fileName)
: this(reader, fileName, LogManager.LogFactory)
{ }
/// <summary>
/// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class.
/// </summary>
/// <param name="reader"><see cref="XmlReader"/> containing the configuration section.</param>
/// <param name="fileName">Name of the file that contains the element (to be used as a base for including other files). <c>null</c> is allowed.</param>
/// <param name="logFactory">The <see cref="LogFactory" /> to which to apply any applicable configuration values.</param>
public XmlLoggingConfiguration([NotNull] XmlReader reader, [CanBeNull] string fileName, LogFactory logFactory)
: base(logFactory)
{
Initialize(reader, fileName);
}
/// <summary>
/// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class.
/// </summary>
/// <param name="reader"><see cref="XmlReader"/> containing the configuration section.</param>
/// <param name="fileName">Name of the file that contains the element (to be used as a base for including other files). <c>null</c> is allowed.</param>
/// <param name="ignoreErrors">Ignore any errors during configuration.</param>
[Obsolete("Constructor with parameter ignoreErrors has limited effect. Instead use LogManager.ThrowConfigExceptions. Marked obsolete in NLog 4.7")]
public XmlLoggingConfiguration([NotNull] XmlReader reader, [CanBeNull] string fileName, bool ignoreErrors)
: this(reader, fileName, ignoreErrors, LogManager.LogFactory)
{ }
/// <summary>
/// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class.
/// </summary>
/// <param name="reader"><see cref="XmlReader"/> containing the configuration section.</param>
/// <param name="fileName">Name of the file that contains the element (to be used as a base for including other files). <c>null</c> is allowed.</param>
/// <param name="ignoreErrors">Ignore any errors during configuration.</param>
/// <param name="logFactory">The <see cref="LogFactory" /> to which to apply any applicable configuration values.</param>
[Obsolete("Constructor with parameter ignoreErrors has limited effect. Instead use LogManager.ThrowConfigExceptions. Marked obsolete in NLog 4.7")]
public XmlLoggingConfiguration([NotNull] XmlReader reader, [CanBeNull] string fileName, bool ignoreErrors, LogFactory logFactory)
: base(logFactory)
{
Initialize(reader, fileName, ignoreErrors);
}
/// <summary>
/// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class.
/// </summary>
/// <param name="xmlContents">NLog configuration as XML string.</param>
/// <param name="fileName">Name of the XML file.</param>
/// <param name="logFactory">The <see cref="LogFactory" /> to which to apply any applicable configuration values.</param>
internal XmlLoggingConfiguration([NotNull] string xmlContents, [CanBeNull] string fileName, LogFactory logFactory)
: base(logFactory)
{
LoadFromXmlContent(xmlContents, fileName);
}
/// <summary>
/// Parse XML string as NLog configuration
/// </summary>
/// <param name="xml">NLog configuration in XML to be parsed</param>
public static XmlLoggingConfiguration CreateFromXmlString(string xml)
{
return CreateFromXmlString(xml, LogManager.LogFactory);
}
/// <summary>
/// Parse XML string as NLog configuration
/// </summary>
/// <param name="xml">NLog configuration in XML to be parsed</param>
/// <param name="logFactory">NLog LogFactory</param>
public static XmlLoggingConfiguration CreateFromXmlString(string xml, LogFactory logFactory)
{
return new XmlLoggingConfiguration(xml, string.Empty, logFactory);
}
#if !NETSTANDARD
/// <summary>
/// Gets the default <see cref="LoggingConfiguration" /> object by parsing
/// the application configuration file (<c>app.exe.config</c>).
/// </summary>
public static LoggingConfiguration AppConfig
{
get
{
object o = System.Configuration.ConfigurationManager.GetSection("nlog");
return o as LoggingConfiguration;
}
}
#endif
/// <summary>
/// Did the <see cref="Initialize"/> Succeeded? <c>true</c>= success, <c>false</c>= error, <c>null</c> = initialize not started yet.
/// </summary>
public bool? InitializeSucceeded { get; private set; }
/// <summary>
/// Gets or sets a value indicating whether all of the configuration files
/// should be watched for changes and reloaded automatically when changed.
/// </summary>
public bool AutoReload
{
get
{
if (_fileMustAutoReloadLookup.Count == 0)
return false;
else
return _fileMustAutoReloadLookup.Values.All(mustAutoReload => mustAutoReload);
}
set
{
var autoReloadFiles = _fileMustAutoReloadLookup.Keys.ToList();
foreach (string nextFile in autoReloadFiles)
_fileMustAutoReloadLookup[nextFile] = value;
}
}
/// <summary>
/// Gets the collection of file names which should be watched for changes by NLog.
/// This is the list of configuration files processed.
/// If the <c>autoReload</c> attribute is not set it returns empty collection.
/// </summary>
public override IEnumerable<string> FileNamesToWatch
{
get
{
return _fileMustAutoReloadLookup.Where(entry => entry.Value).Select(entry => entry.Key);
}
}
/// <summary>
/// Re-reads the original configuration file and returns the new <see cref="LoggingConfiguration" /> object.
/// </summary>
/// <returns>The new <see cref="XmlLoggingConfiguration" /> object.</returns>
public override LoggingConfiguration Reload()
{
if (!string.IsNullOrEmpty(_originalFileName))
{
var newConfig = new XmlLoggingConfiguration(LogFactory);
newConfig.PrepareForReload(this);
newConfig.LoadFromXmlFile(_originalFileName);
return newConfig;
}
return base.Reload();
}
/// <summary>
/// Get file paths (including filename) for the possible NLog config files.
/// </summary>
/// <returns>The file paths to the possible config file</returns>
public static IEnumerable<string> GetCandidateConfigFilePaths()
{
return LogManager.LogFactory.GetCandidateConfigFilePaths();
}
/// <summary>
/// Overwrite the paths (including filename) for the possible NLog config files.
/// </summary>
/// <param name="filePaths">The file paths to the possible config file</param>
public static void SetCandidateConfigFilePaths(IEnumerable<string> filePaths)
{
LogManager.LogFactory.SetCandidateConfigFilePaths(filePaths);
}
/// <summary>
/// Clear the candidate file paths and return to the defaults.
/// </summary>
public static void ResetCandidateConfigFilePath()
{
LogManager.LogFactory.ResetCandidateConfigFilePath();
}
private void LoadFromXmlFile(string fileName)
{
using (XmlReader reader = CreateFileReader(fileName))
{
Initialize(reader, fileName);
}
}
internal void LoadFromXmlContent(string xmlContent, string fileName)
{
using (var stringReader = new StringReader(xmlContent))
{
using (XmlReader reader = XmlReader.Create(stringReader))
{
Initialize(reader, fileName);
}
}
}
/// <summary>
/// Create XML reader for (xml config) file.
/// </summary>
/// <param name="fileName">filepath</param>
/// <returns>reader or <c>null</c> if filename is empty.</returns>
private XmlReader CreateFileReader(string fileName)
{
if (!string.IsNullOrEmpty(fileName))
{
fileName = fileName.Trim();
return LogFactory.CurrentAppEnvironment.LoadXmlFile(fileName);
}
return null;
}
/// <summary>
/// Initializes the configuration.
/// </summary>
/// <param name="reader"><see cref="XmlReader"/> containing the configuration section.</param>
/// <param name="fileName">Name of the file that contains the element (to be used as a base for including other files). <c>null</c> is allowed.</param>
/// <param name="ignoreErrors">Ignore any errors during configuration.</param>
private void Initialize([NotNull] XmlReader reader, [CanBeNull] string fileName, bool ignoreErrors = false)
{
try
{
InitializeSucceeded = null;
_originalFileName = fileName;
reader.MoveToContent();
var content = new NLogXmlElement(reader);
if (!string.IsNullOrEmpty(fileName))
{
InternalLogger.Info("Configuring from an XML element in {0}...", fileName);
ParseTopLevel(content, fileName, autoReloadDefault: false);
}
else
{
ParseTopLevel(content, null, autoReloadDefault: false);
}
InitializeSucceeded = true;
}
catch (Exception exception)
{
InitializeSucceeded = false;
if (exception.MustBeRethrownImmediately())
{
throw;
}
var configurationException = new NLogConfigurationException(exception, "Exception when loading configuration {0}", fileName);
InternalLogger.Error(exception, configurationException.Message);
if (!ignoreErrors && (LogFactory.ThrowConfigExceptions ?? LogFactory.ThrowExceptions || configurationException.MustBeRethrown()))
throw configurationException;
}
}
/// <summary>
/// Add a file with configuration. Check if not already included.
/// </summary>
/// <param name="fileName"></param>
/// <param name="autoReloadDefault"></param>
private void ConfigureFromFile([NotNull] string fileName, bool autoReloadDefault)
{
if (!_fileMustAutoReloadLookup.ContainsKey(GetFileLookupKey(fileName)))
{
using (var reader = LogFactory.CurrentAppEnvironment.LoadXmlFile(fileName))
{
reader.MoveToContent();
ParseTopLevel(new NLogXmlElement(reader, false), fileName, autoReloadDefault);
}
}
}
/// <summary>
/// Parse the root
/// </summary>
/// <param name="content"></param>
/// <param name="filePath">path to config file.</param>
/// <param name="autoReloadDefault">The default value for the autoReload option.</param>
private void ParseTopLevel(NLogXmlElement content, [CanBeNull] string filePath, bool autoReloadDefault)
{
content.AssertName("nlog", "configuration");
switch (content.LocalName.ToUpperInvariant())
{
case "CONFIGURATION":
ParseConfigurationElement(content, filePath, autoReloadDefault);
break;
case "NLOG":
ParseNLogElement(content, filePath, autoReloadDefault);
break;
}
}
/// <summary>
/// Parse {configuration} xml element.
/// </summary>
/// <param name="configurationElement"></param>
/// <param name="filePath">path to config file.</param>
/// <param name="autoReloadDefault">The default value for the autoReload option.</param>
private void ParseConfigurationElement(NLogXmlElement configurationElement, [CanBeNull] string filePath, bool autoReloadDefault)
{
InternalLogger.Trace("ParseConfigurationElement");
configurationElement.AssertName("configuration");
var nlogElements = configurationElement.FilterChildren("nlog");
foreach (var nlogElement in nlogElements)
{
ParseNLogElement(nlogElement, filePath, autoReloadDefault);
}
}
/// <summary>
/// Parse {NLog} xml element.
/// </summary>
/// <param name="nlogElement"></param>
/// <param name="filePath">path to config file.</param>
/// <param name="autoReloadDefault">The default value for the autoReload option.</param>
private void ParseNLogElement(ILoggingConfigurationElement nlogElement, [CanBeNull] string filePath, bool autoReloadDefault)
{
InternalLogger.Trace("ParseNLogElement");
nlogElement.AssertName("nlog");
bool autoReload = nlogElement.GetOptionalBooleanValue("autoReload", autoReloadDefault);
try
{
string baseDirectory = null;
if (!string.IsNullOrEmpty(filePath))
{
_fileMustAutoReloadLookup[GetFileLookupKey(filePath)] = autoReload;
_currentFilePath.Push(filePath);
baseDirectory = Path.GetDirectoryName(filePath);
}
base.LoadConfig(nlogElement, baseDirectory);
}
finally
{
if (!string.IsNullOrEmpty(filePath))
_currentFilePath.Pop();
}
}
/// <summary>
/// Parses a single config section within the NLog-config
/// </summary>
/// <param name="configSection"></param>
/// <returns>Section was recognized</returns>
protected override bool ParseNLogSection(ILoggingConfigurationElement configSection)
{
if (configSection.MatchesName("include"))
{
string filePath = _currentFilePath.Peek();
bool autoLoad = !string.IsNullOrEmpty(filePath) && _fileMustAutoReloadLookup[GetFileLookupKey(filePath)];
ParseIncludeElement(configSection, !string.IsNullOrEmpty(filePath) ? Path.GetDirectoryName(filePath) : null, autoLoad);
return true;
}
else
{
return base.ParseNLogSection(configSection);
}
}
private void ParseIncludeElement(ILoggingConfigurationElement includeElement, string baseDirectory, bool autoReloadDefault)
{
includeElement.AssertName("include");
string newFileName = includeElement.GetRequiredValue("file", "nlog");
var ignoreErrors = includeElement.GetOptionalBooleanValue("ignoreErrors", false);
try
{
newFileName = ExpandSimpleVariables(newFileName);
newFileName = SimpleLayout.Evaluate(newFileName);
var fullNewFileName = newFileName;
if (baseDirectory != null)
{
fullNewFileName = Path.Combine(baseDirectory, newFileName);
}
if (File.Exists(fullNewFileName))
{
InternalLogger.Debug("Including file '{0}'", fullNewFileName);
ConfigureFromFile(fullNewFileName, autoReloadDefault);
}
else
{
//is mask?
if (newFileName.Contains("*"))
{
ConfigureFromFilesByMask(baseDirectory, newFileName, autoReloadDefault);
}
else
{
if (ignoreErrors)
{
//quick stop for performances
InternalLogger.Debug("Skipping included file '{0}' as it can't be found", fullNewFileName);
return;
}
throw new FileNotFoundException("Included file not found: " + fullNewFileName);
}
}
}
catch (Exception exception)
{
if (exception.MustBeRethrownImmediately())
{
throw;
}
var configurationException = new NLogConfigurationException(exception, "Error when including '{0}'.", newFileName);
InternalLogger.Error(exception, configurationException.Message);
if (!ignoreErrors)
throw configurationException;
}
}
/// <summary>
/// Include (multiple) files by filemask, e.g. *.nlog
/// </summary>
/// <param name="baseDirectory">base directory in case if <paramref name="fileMask"/> is relative</param>
/// <param name="fileMask">relative or absolute fileMask</param>
/// <param name="autoReloadDefault"></param>
private void ConfigureFromFilesByMask(string baseDirectory, string fileMask, bool autoReloadDefault)
{
var directory = baseDirectory;
//if absolute, split to file mask and directory.
if (Path.IsPathRooted(fileMask))
{
directory = Path.GetDirectoryName(fileMask);
if (directory is null)
{
InternalLogger.Warn("directory is empty for include of '{0}'", fileMask);
return;
}
var filename = Path.GetFileName(fileMask);
if (filename is null)
{
InternalLogger.Warn("filename is empty for include of '{0}'", fileMask);
return;
}
fileMask = filename;
}
var files = Directory.GetFiles(directory, fileMask);
foreach (var file in files)
{
//note we exclude our self in ConfigureFromFile
ConfigureFromFile(file, autoReloadDefault);
}
}
private static string GetFileLookupKey([NotNull] string fileName)
{
return Path.GetFullPath(fileName);
}
/// <inheritdoc/>
public override string ToString()
{
return $"{base.ToString()}, FilePath={_originalFileName}";
}
}
}
| |
// 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 Microsoft.Xunit.Performance;
using Xunit;
namespace System.Collections.Tests
{
public class Perf_List
{
/// <summary>
/// Creates a list containing a number of elements equal to the specified size
/// </summary>
public static List<object> CreateList(int size)
{
Random rand = new Random(24565653);
List<object> list = new List<object>();
for (int i = 0; i < size; i++)
list.Add(rand.Next());
return list;
}
[Benchmark]
[InlineData(1000)]
[InlineData(10000)]
[InlineData(100000)]
public void Add(int size)
{
List<object> list = CreateList(size);
foreach (var iteration in Benchmark.Iterations)
{
List<object> copyList = new List<object>(list);
using (iteration.StartMeasurement())
{
for (int i = 0; i < 10000; i++)
{
copyList.Add(123555); copyList.Add(123555); copyList.Add(123555); copyList.Add(123555);
copyList.Add(123555); copyList.Add(123555); copyList.Add(123555); copyList.Add(123555);
}
}
}
}
[Benchmark]
[InlineData(1000)]
[InlineData(10000)]
[InlineData(100000)]
public void AddRange(int size)
{
List<object> list = CreateList(size);
foreach (var iteration in Benchmark.Iterations)
using (iteration.StartMeasurement())
for (int i = 0; i < 5000; i++)
{
List<object> emptyList = new List<object>();
emptyList.AddRange(list);
}
}
[Benchmark]
[InlineData(1000)]
[InlineData(10000)]
[InlineData(100000)]
public void Clear(int size)
{
List<object> list = CreateList(size);
foreach (var iteration in Benchmark.Iterations)
{
// Setup lists to clear
List<object>[] listlist = new List<object>[5000];
for (int i = 0; i < 5000; i++)
listlist[i] = new List<object>(list);
// Clear the lists
using (iteration.StartMeasurement())
for (int i = 0; i < 5000; i++)
listlist[i].Clear();
}
}
[Benchmark]
[InlineData(1000)]
[InlineData(10000)]
[InlineData(100000)]
public void Contains(int size)
{
List<object> list = CreateList(size);
object contained = list[list.Count / 2];
foreach (var iteration in Benchmark.Iterations)
using (iteration.StartMeasurement())
{
for (int i = 0; i < 500; i++)
{
list.Contains(contained); list.Contains(contained); list.Contains(contained); list.Contains(contained);
list.Contains(contained); list.Contains(contained); list.Contains(contained); list.Contains(contained);
list.Contains(contained); list.Contains(contained); list.Contains(contained); list.Contains(contained);
}
}
}
[Benchmark]
public void ctor()
{
foreach (var iteration in Benchmark.Iterations)
using (iteration.StartMeasurement())
{
for (int i = 0; i < 20000; i++)
{
new List<object>(); new List<object>(); new List<object>(); new List<object>(); new List<object>();
new List<object>(); new List<object>(); new List<object>(); new List<object>(); new List<object>();
new List<object>(); new List<object>(); new List<object>(); new List<object>(); new List<object>();
}
}
}
[Benchmark]
[InlineData(1000)]
[InlineData(10000)]
[InlineData(100000)]
public void ctor_IEnumerable(int size)
{
List<object> list = CreateList(size);
var array = list.ToArray();
foreach (var iteration in Benchmark.Iterations)
using (iteration.StartMeasurement())
for (int i = 0; i < 10000; i++)
new List<object>(array);
}
[Benchmark]
[InlineData(1000)]
[InlineData(10000)]
[InlineData(100000)]
public void GetCount(int size)
{
List<object> list = CreateList(size);
int temp;
foreach (var iteration in Benchmark.Iterations)
using (iteration.StartMeasurement())
{
for (int i = 0; i < 10000; i++)
{
temp = list.Count; temp = list.Count; temp = list.Count; temp = list.Count; temp = list.Count;
temp = list.Count; temp = list.Count; temp = list.Count; temp = list.Count; temp = list.Count;
temp = list.Count; temp = list.Count; temp = list.Count; temp = list.Count; temp = list.Count;
}
}
}
[Benchmark]
[InlineData(1000)]
[InlineData(10000)]
[InlineData(100000)]
public void GetItem(int size)
{
List<object> list = CreateList(size);
object temp;
foreach (var iteration in Benchmark.Iterations)
using (iteration.StartMeasurement())
{
for (int i = 0; i < 10000; i++)
{
temp = list[50]; temp = list[50]; temp = list[50]; temp = list[50]; temp = list[50];
temp = list[50]; temp = list[50]; temp = list[50]; temp = list[50]; temp = list[50];
temp = list[50]; temp = list[50]; temp = list[50]; temp = list[50]; temp = list[50];
temp = list[50]; temp = list[50]; temp = list[50]; temp = list[50]; temp = list[50];
}
}
}
[Benchmark]
[InlineData(1000)]
[InlineData(10000)]
[InlineData(100000)]
public void Enumerator(int size)
{
List<object> list = CreateList(size);
foreach (var iteration in Benchmark.Iterations)
using (iteration.StartMeasurement())
for (int i = 0; i < 10000; i++)
foreach (var element in list) { }
}
[Benchmark]
[InlineData(1000)]
[InlineData(10000)]
[InlineData(100000)]
public void SetCapacity(int size)
{
List<object> list = CreateList(size);
foreach (var iteration in Benchmark.Iterations)
using (iteration.StartMeasurement())
for (int i = 0; i < 100; i++)
{
// Capacity set back and forth between size+1 and size+2
list.Capacity = size + (i % 2) + 1;
}
}
[Benchmark]
[InlineData(1000)]
[InlineData(10000)]
[InlineData(100000)]
public void ToArray(int size)
{
List<object> list = CreateList(size);
foreach (var iteration in Benchmark.Iterations)
using (iteration.StartMeasurement())
for (int i = 0; i < 10000; i++)
list.ToArray();
}
[Benchmark]
public static void IndexOf_ValueType()
{
List<int> collection = new List<int>();
int nonexistentItem, firstItem, middleItem, lastItem;
for (int i = 0; i < 8192; ++i)
{
collection.Add(i);
}
nonexistentItem = -1;
firstItem = 0;
middleItem = collection.Count / 2;
lastItem = collection.Count - 1;
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
collection.IndexOf(nonexistentItem);
collection.IndexOf(firstItem);
collection.IndexOf(middleItem);
collection.IndexOf(lastItem);
}
}
}
[Benchmark]
public static void IndexOf_ReferenceType()
{
List<string> collection = new List<string>();
string nonexistentItem, firstItem, middleItem, lastItem;
for (int i = 0; i < 8192; ++i)
{
collection.Add(i.ToString());
}
nonexistentItem = "foo";
firstItem = 0.ToString();
middleItem = (collection.Count / 2).ToString();
lastItem = (collection.Count - 1).ToString();
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
collection.IndexOf(nonexistentItem);
collection.IndexOf(firstItem);
collection.IndexOf(middleItem);
collection.IndexOf(lastItem);
}
}
}
private static int getSampleLength(bool largeSets)
{
if (largeSets)
return LARGE_SAMPLE_LENGTH;
else
return smallSampleLength;
}
[Benchmark]
[InlineData(true)]
[InlineData(false)]
public static void GenericList_AddRange_Int_NoCapacityIncrease(bool largeSets)
{
int sampleLength = getSampleLength(largeSets);
int[] sampleSet = new int[sampleLength];
for (int i = 0; i < sampleLength; i++)
{
sampleSet[i] = i;
}
int addLoops = LARGE_SAMPLE_LENGTH / sampleLength;
//Create an ArrayList big enough to hold 17 copies of the sample set
int startingCapacity = 17 * sampleLength * addLoops;
List<int> list = new List<int>(startingCapacity);
//Add the data to the array list.
for (int j = 0; j < addLoops; j++)
{
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
}
foreach (var iteration in Benchmark.Iterations)
{
//Clear the ArrayList without changing its capacity, so that when more data is added to the list its
//capacity will not need to increase.
list.RemoveRange(0, startingCapacity);
using (iteration.StartMeasurement())
{
for (int j = 0; j < addLoops; j++)
{
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
}
}
}
}
[Benchmark]
[InlineData(true)]
[InlineData(false)]
public static void GenericList_AddRange_Int_CapacityIncrease(bool largeSets)
{
int sampleLength = getSampleLength(largeSets);
int[] sampleSet = new int[sampleLength];
for (int i = 0; i < sampleLength; i++)
{
sampleSet[i] = i;
}
int addLoops = LARGE_SAMPLE_LENGTH / sampleLength;
foreach (var iteration in Benchmark.Iterations)
{
List<int> list = new List<int>();
using (iteration.StartMeasurement())
{
for (int j = 0; j < addLoops; j++)
{
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
}
}
}
}
[Benchmark]
[InlineData(true)]
[InlineData(false)]
public static void GenericList_AddRange_String_NoCapacityIncrease(bool largeSets)
{
int sampleLength = getSampleLength(largeSets);
string[] sampleSet = new string[sampleLength];
for (int i = 0; i < sampleLength; i++)
{
sampleSet[i] = i.ToString();
}
int addLoops = LARGE_SAMPLE_LENGTH / sampleLength;
//Create an ArrayList big enough to hold 17 copies of the sample set
int startingCapacity = 17 * sampleLength * addLoops;
List<string> list = new List<string>(startingCapacity);
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
for (int j = 0; j < addLoops; j++)
{
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
}
}
list.RemoveRange(0, startingCapacity);
}
}
[Benchmark]
[InlineData(true)]
[InlineData(false)]
public static void GenericList_AddRange_String_CapacityIncrease(bool largeSets)
{
int sampleLength = getSampleLength(largeSets);
string[] sampleSet = new string[sampleLength];
for (int i = 0; i < sampleLength; i++)
{
sampleSet[i] = i.ToString();
}
int addLoops = LARGE_SAMPLE_LENGTH / sampleLength;
foreach (var iteration in Benchmark.Iterations)
{
List<string> list = new List<string>();
using (iteration.StartMeasurement())
{
for (int j = 0; j < addLoops; j++)
{
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
list.AddRange(sampleSet);
}
}
}
}
[Benchmark]
public static void Add_ValueType()
{
foreach (var iteration in Benchmark.Iterations)
{
List<int> collection = new List<int>();
using (iteration.StartMeasurement())
{
for (int j = 0; j < 256; ++j)
{
collection.Add(j);
collection.Add(j);
collection.Add(j);
collection.Add(j);
collection.Add(j);
collection.Add(j);
collection.Add(j);
collection.Add(j);
collection.Add(j);
collection.Add(j);
}
}
}
}
[Benchmark]
public static void Add_ReferenceType()
{
string itemToAdd = "foo";
foreach (var iteration in Benchmark.Iterations)
{
List<string> collection = new List<string>();
using (iteration.StartMeasurement())
{
for (int j = 0; j < 256; ++j)
{
collection.Add(itemToAdd);
collection.Add(itemToAdd);
collection.Add(itemToAdd);
collection.Add(itemToAdd);
collection.Add(itemToAdd);
collection.Add(itemToAdd);
collection.Add(itemToAdd);
collection.Add(itemToAdd);
collection.Add(itemToAdd);
collection.Add(itemToAdd);
}
}
}
}
[Benchmark]
public static void GenericList_BinarySearch_Int()
{
int sampleLength = 10000;
int[] sampleSet = new int[sampleLength];
for (int i = 0; i < sampleLength; i++)
{
sampleSet[i] = i;
}
List<int> list = new List<int>(sampleSet);
IComparer<int> comparer = Comparer<int>.Default;
int result = 0;
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
for (int j = 0; j < sampleLength; j++)
result = list.BinarySearch(sampleSet[j], comparer);
}
}
}
[Benchmark]
public static void GenericList_BinarySearch_String()
{
int sampleLength = 1000;
string[] sampleSet = new string[sampleLength];
for (int i = 0; i < sampleLength; i++)
{
sampleSet[i] = i.ToString();
}
List<string> list = new List<string>(sampleSet);
IComparer<string> comparer = Comparer<string>.Default;
int result = 0;
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
for (int j = 0; j < sampleLength; j++)
result = list.BinarySearch(sampleSet[j], comparer);
}
}
}
[Benchmark]
public static void Contains_ValueType()
{
List<int> collection = new List<int>();
int nonexistentItem, firstItem, middleItem, lastItem;
//[] Initialize
for (int i = 0; i < 8192; ++i)
{
collection.Add(i);
}
nonexistentItem = -1;
firstItem = 0;
middleItem = collection.Count / 2;
lastItem = collection.Count - 1;
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
collection.Contains(nonexistentItem);
collection.Contains(firstItem);
collection.Contains(middleItem);
collection.Contains(lastItem);
}
}
}
[Benchmark]
public static void Contains_ReferenceType()
{
List<string> collection = new List<string>();
string nonexistentItem, firstItem, middleItem, lastItem;
//[] Initialize
for (int i = 0; i < 8192; ++i)
{
collection.Add(i.ToString());
}
nonexistentItem = "foo";
firstItem = 0.ToString();
middleItem = (collection.Count / 2).ToString();
lastItem = (collection.Count - 1).ToString();
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
collection.Contains(nonexistentItem);
collection.Contains(firstItem);
collection.Contains(middleItem);
collection.Contains(lastItem);
}
}
}
[Benchmark]
public static void ctor_ICollection_ValueType()
{
List<int> originalCollection = new List<int>();
List<int> newCollection;
//[] Initialize
for (int i = 0; i < 1024; ++i)
{
originalCollection.Add(i);
}
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
newCollection = new List<int>(originalCollection);
}
}
}
[Benchmark]
public static void ctor_ICollection_ReferenceType()
{
List<string> originalCollection = new List<string>();
List<string> newCollection;
//[] Initialize
for (int i = 0; i < 1024; ++i)
{
originalCollection.Add(i.ToString());
}
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
newCollection = new List<string>(originalCollection);
}
}
}
[Benchmark]
public static void Indexer_ValueType()
{
List<int> collection = new List<int>();
int item = 0;
//[] Initialize
for (int i = 0; i < 8192; ++i)
{
collection.Add(i);
}
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
for (int j = 0; j < 8192; ++j)
{
item = collection[j];
item = collection[j];
item = collection[j];
item = collection[j];
item = collection[j];
item = collection[j];
item = collection[j];
item = collection[j];
item = collection[j];
item = collection[j];
}
}
}
}
[Benchmark]
public static void Indexer_ReferenceType()
{
List<string> collection = new List<string>();
string item = null;
//[] Initialize
for (int i = 0; i < 8192; ++i)
{
collection.Add(i.ToString());
}
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
for (int j = 0; j < 8192; ++j)
{
item = collection[j];
item = collection[j];
item = collection[j];
item = collection[j];
item = collection[j];
item = collection[j];
item = collection[j];
item = collection[j];
item = collection[j];
item = collection[j];
}
}
}
}
[Benchmark]
public static void Sort_ValueType()
{
Random random = new Random(32829);
int size = 3000;
int[] items;
List<int> collection;
//[] Initialize
items = new int[size];
for (int i = 0; i < size; ++i)
items[i] = random.Next();
foreach (var iteration in Benchmark.Iterations)
{
collection = new List<int>(size);
for (int j = 0; j < size; ++j)
collection.Add(items[j]);
using (iteration.StartMeasurement())
collection.Sort();
}
}
[Benchmark]
public static void Sort_ReferenceType()
{
Random random = new Random(32829);
int size = 3000;
string[] items;
List<string> collection;
//[] Initialize
items = new string[size];
for (int i = 0; i < size; ++i)
{
items[i] = random.Next().ToString();
}
foreach (var iteration in Benchmark.Iterations)
{
collection = new List<string>(size);
for (int j = 0; j < size; ++j)
{
collection.Add(items[j]);
}
using (iteration.StartMeasurement())
collection.Sort();
}
}
[Benchmark]
public static void GenericList_Reverse_Int()
{
int sampleLength = 100000;
int[] sampleSet = new int[sampleLength];
for (int i = 0; i < sampleLength; i++)
{
sampleSet[i] = i;
}
List<int> list = new List<int>(sampleSet);
foreach (var iteration in Benchmark.Iterations)
using (iteration.StartMeasurement())
list.Reverse();
}
[Benchmark]
public static void GenericList_Reverse_String()
{
int sampleLength = 100000;
string[] sampleSet = new string[sampleLength];
for (int i = 0; i < sampleLength; i++)
{
sampleSet[i] = i.ToString();
}
List<string> list = new List<string>(sampleSet);
foreach (var iteration in Benchmark.Iterations)
using (iteration.StartMeasurement())
list.Reverse();
}
[Benchmark]
public static void Remove_ValueType()
{
int size = 3000;
int[] items;
List<int> collection;
int start, middle, end;
//[] Initialize
items = new int[size];
for (int i = 0; i < size; ++i)
{
items[i] = i;
}
foreach (var iteration in Benchmark.Iterations)
{
collection = new List<int>();
for (int j = 0; j < size; ++j)
{
collection.Add(items[j]);
}
start = 0;
middle = size / 3;
end = size - 1;
using (iteration.StartMeasurement())
{
for (int j = 0; j < size / 3; j++)
{
collection.Remove(-1);
collection.Remove(items[start]);
collection.Remove(items[middle]);
collection.Remove(items[end]);
++start;
++middle;
--end;
}
}
}
}
[Benchmark]
public static void Remove_ReferenceType()
{
int size = 3000;
string[] items;
List<string> collection;
int start, middle, end;
//[] Initialize
items = new string[size];
for (int i = 0; i < size; ++i)
{
items[i] = i.ToString();
}
foreach (var iteration in Benchmark.Iterations)
{
collection = new List<string>();
for (int j = 0; j < size; ++j)
{
collection.Add(items[j]);
}
start = 0;
middle = size / 3;
end = size - 1;
using (iteration.StartMeasurement())
{
for (int j = 0; j < size / 3; j++)
{
collection.Remove("-1");
collection.Remove(items[start]);
collection.Remove(items[middle]);
collection.Remove(items[end]);
++start;
++middle;
--end;
}
}
}
}
[Benchmark]
public static void Insert_ValueType()
{
List<int> collection;
collection = new List<int>();
for (int j = 0; j < 1024; ++j)
{
collection.Insert(0, j);//Insert at the begining of the list
collection.Insert(j / 2, j);//Insert in the middle of the list
collection.Insert(collection.Count, j);//Insert at the end of the list
}
foreach (var iteration in Benchmark.Iterations)
{
collection = new List<int>();
using (iteration.StartMeasurement())
{
for (int j = 0; j < 1024; ++j)
{
collection.Insert(0, j);//Insert at the begining of the list
collection.Insert(j / 2, j);//Insert in the middle of the list
collection.Insert(collection.Count, j);//Insert at the end of the list
}
}
}
}
[Benchmark]
public static void Insert_ReferenceType()
{
List<string> collection;
string itemToAdd = "foo";
foreach (var iteration in Benchmark.Iterations)
{
collection = new List<string>();
using (iteration.StartMeasurement())
{
for (int j = 0; j < 1024; ++j)
{
collection.Insert(0, itemToAdd);//Insert at the begining of the list
collection.Insert(j / 2, itemToAdd);//Insert in the middle of the list
collection.Insert(collection.Count, itemToAdd);//Insert at the end of the list
}
}
}
}
[Benchmark]
public static void Enumeration_ValueType()
{
List<int> collection = new List<int>();
int item;
//[] Initialize
for (int i = 0; i < 8192; ++i)
{
collection.Add(i);
}
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
foreach (int tempItem in collection)
{
item = tempItem;
}
}
}
}
[Benchmark]
public static void Enumeration_ReferenceType()
{
List<string> collection = new List<string>();
string item;
//[] Initialize
for (int i = 0; i < 8192; ++i)
{
collection.Add(i.ToString());
}
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
foreach (string tempItem in collection)
{
item = tempItem;
}
}
}
}
private const int LARGE_SAMPLE_LENGTH = 10000;
private const int SMALL_LOOPS = 1000;
private const int smallSampleLength = LARGE_SAMPLE_LENGTH / SMALL_LOOPS;
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Reflection;
namespace System.Management.Automation
{
/// <summary>
/// Internal wrapper for third-party adapters (PSPropertyAdapter)
/// </summary>
internal class ThirdPartyAdapter : PropertyOnlyAdapter
{
internal ThirdPartyAdapter(Type adaptedType, PSPropertyAdapter externalAdapter)
{
AdaptedType = adaptedType;
_externalAdapter = externalAdapter;
}
/// <summary>
/// The type this instance is adapting.
/// </summary>
internal Type AdaptedType { get; }
/// <summary>
/// The type of the external adapter.
/// </summary>
internal Type ExternalAdapterType
{
get
{
return _externalAdapter.GetType();
}
}
/// <summary>
/// Returns the TypeNameHierarchy out of an object.
/// </summary>
protected override IEnumerable<string> GetTypeNameHierarchy(object obj)
{
Collection<string> typeNameHierarchy = null;
try
{
typeNameHierarchy = _externalAdapter.GetTypeNameHierarchy(obj);
}
catch (Exception exception)
{
throw new ExtendedTypeSystemException(
"PSPropertyAdapter.GetTypeNameHierarchyError",
exception,
ExtendedTypeSystem.GetTypeNameHierarchyError, obj.ToString());
}
if (typeNameHierarchy == null)
{
throw new ExtendedTypeSystemException(
"PSPropertyAdapter.NullReturnValueError",
null,
ExtendedTypeSystem.NullReturnValueError, "PSPropertyAdapter.GetTypeNameHierarchy");
}
return typeNameHierarchy;
}
/// <summary>
/// Retrieves all the properties available in the object.
/// </summary>
protected override void DoAddAllProperties<T>(object obj, PSMemberInfoInternalCollection<T> members)
{
Collection<PSAdaptedProperty> properties = null;
try
{
properties = _externalAdapter.GetProperties(obj);
}
catch (Exception exception)
{
throw new ExtendedTypeSystemException(
"PSPropertyAdapter.GetProperties",
exception,
ExtendedTypeSystem.GetProperties, obj.ToString());
}
if (properties == null)
{
throw new ExtendedTypeSystemException(
"PSPropertyAdapter.NullReturnValueError",
null,
ExtendedTypeSystem.NullReturnValueError, "PSPropertyAdapter.GetProperties");
}
foreach (PSAdaptedProperty property in properties)
{
InitializeProperty(property, obj);
members.Add(property as T);
}
}
/// <summary>
/// Returns null if propertyName is not a property in the adapter or
/// the corresponding PSProperty with its adapterData set to information
/// to be used when retrieving the property.
/// </summary>
protected override PSProperty DoGetProperty(object obj, string propertyName)
{
PSAdaptedProperty property = null;
try
{
property = _externalAdapter.GetProperty(obj, propertyName);
}
catch (Exception exception)
{
throw new ExtendedTypeSystemException(
"PSPropertyAdapter.GetProperty",
exception,
ExtendedTypeSystem.GetProperty, propertyName, obj.ToString());
}
if (property != null)
{
InitializeProperty(property, obj);
}
return property;
}
/// <summary>
/// Ensures that the adapter and base object are set in the given PSAdaptedProperty.
/// </summary>
private void InitializeProperty(PSAdaptedProperty property, object baseObject)
{
if (property.adapter == null)
{
property.adapter = this;
property.baseObject = baseObject;
}
}
/// <summary>
/// Returns true if the property is settable.
/// </summary>
protected override bool PropertyIsSettable(PSProperty property)
{
PSAdaptedProperty adaptedProperty = property as PSAdaptedProperty;
Diagnostics.Assert(adaptedProperty != null, "ThirdPartyAdapter should only receive PSAdaptedProperties");
try
{
return _externalAdapter.IsSettable(adaptedProperty);
}
catch (Exception exception)
{
throw new ExtendedTypeSystemException(
"PSPropertyAdapter.PropertyIsSettableError",
exception,
ExtendedTypeSystem.PropertyIsSettableError, property.Name);
}
}
/// <summary>
/// Returns true if the property is gettable.
/// </summary>
protected override bool PropertyIsGettable(PSProperty property)
{
PSAdaptedProperty adaptedProperty = property as PSAdaptedProperty;
Diagnostics.Assert(adaptedProperty != null, "ThirdPartyAdapter should only receive PSAdaptedProperties");
try
{
return _externalAdapter.IsGettable(adaptedProperty);
}
catch (Exception exception)
{
throw new ExtendedTypeSystemException(
"PSPropertyAdapter.PropertyIsGettableError",
exception,
ExtendedTypeSystem.PropertyIsGettableError, property.Name);
}
}
/// <summary>
/// Returns the value from a property coming from a previous call to DoGetProperty.
/// </summary>
protected override object PropertyGet(PSProperty property)
{
PSAdaptedProperty adaptedProperty = property as PSAdaptedProperty;
Diagnostics.Assert(adaptedProperty != null, "ThirdPartyAdapter should only receive PSAdaptedProperties");
try
{
return _externalAdapter.GetPropertyValue(adaptedProperty);
}
catch (Exception exception)
{
throw new ExtendedTypeSystemException(
"PSPropertyAdapter.PropertyGetError",
exception,
ExtendedTypeSystem.PropertyGetError, property.Name);
}
}
/// <summary>
/// Sets the value of a property coming from a previous call to DoGetProperty.
/// </summary>
protected override void PropertySet(PSProperty property, object setValue, bool convertIfPossible)
{
PSAdaptedProperty adaptedProperty = property as PSAdaptedProperty;
Diagnostics.Assert(adaptedProperty != null, "ThirdPartyAdapter should only receive PSAdaptedProperties");
try
{
_externalAdapter.SetPropertyValue(adaptedProperty, setValue);
}
catch (SetValueException) { throw; }
catch (Exception exception)
{
throw new ExtendedTypeSystemException(
"PSPropertyAdapter.PropertySetError",
exception,
ExtendedTypeSystem.PropertySetError, property.Name);
}
}
/// <summary>
/// Returns the name of the type corresponding to the property.
/// </summary>
protected override string PropertyType(PSProperty property, bool forDisplay)
{
PSAdaptedProperty adaptedProperty = property as PSAdaptedProperty;
Diagnostics.Assert(adaptedProperty != null, "ThirdPartyAdapter should only receive PSAdaptedProperties");
string propertyTypeName = null;
try
{
propertyTypeName = _externalAdapter.GetPropertyTypeName(adaptedProperty);
}
catch (Exception exception)
{
throw new ExtendedTypeSystemException(
"PSPropertyAdapter.PropertyTypeError",
exception,
ExtendedTypeSystem.PropertyTypeError, property.Name);
}
return propertyTypeName ?? "System.Object";
}
private PSPropertyAdapter _externalAdapter;
}
/// <summary>
/// User-defined property adapter.
/// </summary>
/// <remarks>
/// This class is used to expose a simplified version of the type adapter API
/// </remarks>
public abstract class PSPropertyAdapter
{
/// <summary>
/// Returns the type hierarchy for the given object.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "object")]
public virtual Collection<string> GetTypeNameHierarchy(object baseObject)
{
if (baseObject == null)
{
throw new ArgumentNullException("baseObject");
}
Collection<string> types = new Collection<string>();
for (Type type = baseObject.GetType(); type != null; type = type.BaseType)
{
types.Add(type.FullName);
}
return types;
}
/// <summary>
/// Returns a list of the adapted properties.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "object")]
public abstract Collection<PSAdaptedProperty> GetProperties(object baseObject);
/// <summary>
/// Returns a specific property, or null if the base object does not contain the given property.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "object")]
public abstract PSAdaptedProperty GetProperty(object baseObject, string propertyName);
/// <summary>
/// Returns true if the given property is settable.
/// </summary>
public abstract bool IsSettable(PSAdaptedProperty adaptedProperty);
/// <summary>
/// Returns true if the given property is gettable.
/// </summary>
public abstract bool IsGettable(PSAdaptedProperty adaptedProperty);
/// <summary>
/// Returns the value of a given property.
/// </summary>
public abstract object GetPropertyValue(PSAdaptedProperty adaptedProperty);
/// <summary>
/// Sets the value of a given property.
/// </summary>
public abstract void SetPropertyValue(PSAdaptedProperty adaptedProperty, object value);
/// <summary>
/// Returns the type for a given property.
/// </summary>
public abstract string GetPropertyTypeName(PSAdaptedProperty adaptedProperty);
}
}
| |
namespace Trifolia.DB.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class init : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.app_securable",
c => new
{
id = c.Int(nullable: false, identity: true),
name = c.String(nullable: false, maxLength: 50),
displayName = c.String(maxLength: 255),
description = c.String(storeType: "ntext"),
})
.PrimaryKey(t => t.id);
CreateTable(
"dbo.appsecurable_role",
c => new
{
id = c.Int(nullable: false, identity: true),
appSecurableId = c.Int(nullable: false),
roleId = c.Int(nullable: false),
})
.PrimaryKey(t => t.id)
.ForeignKey("dbo.role", t => t.roleId, cascadeDelete: true)
.ForeignKey("dbo.app_securable", t => t.appSecurableId)
.Index(t => t.appSecurableId)
.Index(t => t.roleId);
CreateTable(
"dbo.role",
c => new
{
id = c.Int(nullable: false, identity: true),
name = c.String(maxLength: 50),
isDefault = c.Boolean(nullable: false),
isAdmin = c.Boolean(nullable: false),
})
.PrimaryKey(t => t.id);
CreateTable(
"dbo.role_restriction",
c => new
{
id = c.Int(nullable: false, identity: true),
roleId = c.Int(nullable: false),
organizationId = c.Int(nullable: false),
})
.PrimaryKey(t => t.id)
.ForeignKey("dbo.organization", t => t.organizationId, cascadeDelete: true)
.ForeignKey("dbo.role", t => t.roleId, cascadeDelete: true)
.Index(t => t.roleId)
.Index(t => t.organizationId);
CreateTable(
"dbo.organization",
c => new
{
id = c.Int(nullable: false, identity: true),
name = c.String(nullable: false, maxLength: 255),
contactName = c.String(maxLength: 128),
contactEmail = c.String(maxLength: 255),
contactPhone = c.String(maxLength: 50),
authProvider = c.String(maxLength: 1024),
isInternal = c.Boolean(nullable: false),
})
.PrimaryKey(t => t.id);
CreateTable(
"dbo.implementationguide",
c => new
{
id = c.Int(nullable: false, identity: true),
implementationGuideTypeId = c.Int(nullable: false),
organizationId = c.Int(),
name = c.String(nullable: false, maxLength: 255),
publishDate = c.DateTime(),
publishStatusId = c.Int(),
previousVersionImplementationGuideId = c.Int(),
version = c.Int(),
displayName = c.String(maxLength: 255, unicode: false),
accessManagerId = c.Int(),
allowAccessRequests = c.Boolean(nullable: false),
webDisplayName = c.String(maxLength: 255),
webDescription = c.String(),
webReadmeOverview = c.String(),
identifier = c.String(maxLength: 255, unicode: false),
})
.PrimaryKey(t => t.id)
.ForeignKey("dbo.user", t => t.accessManagerId)
.ForeignKey("dbo.implementationguidetype", t => t.implementationGuideTypeId)
.ForeignKey("dbo.publish_status", t => t.publishStatusId)
.ForeignKey("dbo.implementationguide", t => t.previousVersionImplementationGuideId)
.ForeignKey("dbo.organization", t => t.organizationId)
.Index(t => t.implementationGuideTypeId)
.Index(t => t.organizationId)
.Index(t => t.publishStatusId)
.Index(t => t.previousVersionImplementationGuideId)
.Index(t => t.accessManagerId);
CreateTable(
"dbo.user",
c => new
{
id = c.Int(nullable: false, identity: true),
userName = c.String(nullable: false, maxLength: 50),
firstName = c.String(nullable: false, maxLength: 125),
lastName = c.String(nullable: false, maxLength: 125),
email = c.String(nullable: false, maxLength: 255),
phone = c.String(nullable: false, maxLength: 50),
okayToContact = c.Boolean(),
externalOrganizationName = c.String(maxLength: 50),
externalOrganizationType = c.String(maxLength: 50),
apiKey = c.String(maxLength: 255),
})
.PrimaryKey(t => t.id);
CreateTable(
"dbo.user_group",
c => new
{
id = c.Int(nullable: false, identity: true),
userId = c.Int(nullable: false),
groupId = c.Int(nullable: false),
})
.PrimaryKey(t => t.id)
.ForeignKey("dbo.group", t => t.groupId, cascadeDelete: true)
.ForeignKey("dbo.user", t => t.userId)
.Index(t => t.userId)
.Index(t => t.groupId);
CreateTable(
"dbo.group",
c => new
{
id = c.Int(nullable: false, identity: true),
name = c.String(nullable: false, maxLength: 100),
description = c.String(storeType: "ntext"),
disclaimer = c.String(storeType: "ntext"),
isOpen = c.Boolean(nullable: false),
})
.PrimaryKey(t => t.id);
CreateTable(
"dbo.implementationguide_permission",
c => new
{
id = c.Int(nullable: false, identity: true),
implementationGuideId = c.Int(nullable: false),
permission = c.String(nullable: false, maxLength: 50),
type = c.String(nullable: false, maxLength: 50),
groupId = c.Int(),
userId = c.Int(),
})
.PrimaryKey(t => t.id)
.ForeignKey("dbo.group", t => t.groupId)
.ForeignKey("dbo.user", t => t.userId)
.ForeignKey("dbo.implementationguide", t => t.implementationGuideId, cascadeDelete: true)
.Index(t => t.implementationGuideId)
.Index(t => t.groupId)
.Index(t => t.userId);
CreateTable(
"dbo.group_manager",
c => new
{
id = c.Int(nullable: false, identity: true),
groupId = c.Int(nullable: false),
userId = c.Int(nullable: false),
})
.PrimaryKey(t => t.id)
.ForeignKey("dbo.group", t => t.groupId, cascadeDelete: true)
.ForeignKey("dbo.user", t => t.userId)
.Index(t => t.groupId)
.Index(t => t.userId);
CreateTable(
"dbo.user_role",
c => new
{
id = c.Int(nullable: false, identity: true),
roleId = c.Int(nullable: false),
userId = c.Int(nullable: false),
})
.PrimaryKey(t => t.id)
.ForeignKey("dbo.role", t => t.roleId, cascadeDelete: true)
.ForeignKey("dbo.user", t => t.userId, cascadeDelete: true)
.Index(t => t.roleId)
.Index(t => t.userId);
CreateTable(
"dbo.template",
c => new
{
id = c.Int(nullable: false, identity: true),
implementationGuideTypeId = c.Int(nullable: false),
templateTypeId = c.Int(nullable: false),
impliedTemplateId = c.Int(),
owningImplementationGuideId = c.Int(nullable: false),
oid = c.String(nullable: false, maxLength: 255),
isOpen = c.Boolean(nullable: false),
name = c.String(nullable: false, maxLength: 255),
bookmark = c.String(nullable: false, maxLength: 255),
description = c.String(),
primaryContext = c.String(maxLength: 255),
notes = c.String(),
lastupdated = c.DateTime(nullable: false, storeType: "date"),
authorId = c.Int(nullable: false),
previousVersionTemplateId = c.Int(),
version = c.Int(nullable: false),
primaryContextType = c.String(maxLength: 255),
statusId = c.Int(),
})
.PrimaryKey(t => t.id)
.ForeignKey("dbo.implementationguidetype", t => t.implementationGuideTypeId)
.ForeignKey("dbo.templatetype", t => t.templateTypeId)
.ForeignKey("dbo.template", t => t.impliedTemplateId)
.ForeignKey("dbo.template", t => t.previousVersionTemplateId)
.ForeignKey("dbo.publish_status", t => t.statusId)
.ForeignKey("dbo.user", t => t.authorId)
.ForeignKey("dbo.implementationguide", t => t.owningImplementationGuideId)
.Index(t => t.implementationGuideTypeId)
.Index(t => t.templateTypeId)
.Index(t => t.impliedTemplateId)
.Index(t => t.owningImplementationGuideId)
.Index(t => t.authorId)
.Index(t => t.previousVersionTemplateId)
.Index(t => t.statusId);
CreateTable(
"dbo.template_constraint",
c => new
{
id = c.Int(nullable: false, identity: true),
number = c.Int(),
templateId = c.Int(nullable: false),
parentConstraintId = c.Int(),
codeSystemId = c.Int(),
valueSetId = c.Int(),
containedTemplateId = c.Int(),
order = c.Int(nullable: false),
isBranch = c.Boolean(nullable: false),
isPrimitive = c.Boolean(nullable: false),
conformance = c.String(maxLength: 128),
cardinality = c.String(maxLength: 50),
context = c.String(maxLength: 255),
dataType = c.String(maxLength: 255),
valueConformance = c.String(maxLength: 50),
isStatic = c.Boolean(),
value = c.String(maxLength: 255),
displayName = c.String(maxLength: 255),
valueSetDate = c.DateTime(),
schematron = c.String(),
description = c.String(),
notes = c.String(),
primitiveText = c.String(),
isInheritable = c.Boolean(nullable: false),
label = c.String(storeType: "ntext"),
isBranchIdentifier = c.Boolean(nullable: false),
isSchRooted = c.Boolean(nullable: false),
isHeading = c.Boolean(nullable: false),
headingDescription = c.String(storeType: "ntext"),
category = c.String(maxLength: 255),
displayNumber = c.String(maxLength: 128),
isModifier = c.Boolean(nullable: false),
mustSupport = c.Boolean(nullable: false),
isChoice = c.Boolean(nullable: false),
})
.PrimaryKey(t => t.id)
.ForeignKey("dbo.template_constraint", t => t.parentConstraintId)
.ForeignKey("dbo.codesystem", t => t.codeSystemId)
.ForeignKey("dbo.valueset", t => t.valueSetId)
.ForeignKey("dbo.template", t => t.templateId, cascadeDelete: true)
.ForeignKey("dbo.template", t => t.containedTemplateId)
.Index(t => t.templateId)
.Index(t => t.parentConstraintId)
.Index(t => t.codeSystemId)
.Index(t => t.valueSetId)
.Index(t => t.containedTemplateId);
CreateTable(
"dbo.codesystem",
c => new
{
id = c.Int(nullable: false, identity: true),
name = c.String(nullable: false, maxLength: 255),
oid = c.String(nullable: false, maxLength: 255),
description = c.String(),
lastUpdate = c.DateTime(),
})
.PrimaryKey(t => t.id);
CreateTable(
"dbo.valueset_member",
c => new
{
id = c.Int(nullable: false, identity: true),
valueSetId = c.Int(nullable: false),
codeSystemId = c.Int(),
code = c.String(maxLength: 255),
displayName = c.String(maxLength: 1024),
status = c.String(maxLength: 255),
statusDate = c.DateTime(),
})
.PrimaryKey(t => t.id)
.ForeignKey("dbo.codesystem", t => t.codeSystemId)
.ForeignKey("dbo.valueset", t => t.valueSetId, cascadeDelete: true)
.Index(t => t.valueSetId)
.Index(t => t.codeSystemId);
CreateTable(
"dbo.valueset",
c => new
{
id = c.Int(nullable: false, identity: true),
oid = c.String(nullable: false, maxLength: 255),
name = c.String(nullable: false, maxLength: 255),
code = c.String(maxLength: 255),
description = c.String(),
intensional = c.Boolean(),
intensionalDefinition = c.String(),
lastUpdate = c.DateTime(),
source = c.String(maxLength: 1024),
isIncomplete = c.Boolean(nullable: false),
})
.PrimaryKey(t => t.id);
CreateTable(
"dbo.green_constraint",
c => new
{
id = c.Int(nullable: false, identity: true),
greenTemplateId = c.Int(nullable: false),
templateConstraintId = c.Int(nullable: false),
parentGreenConstraintId = c.Int(),
order = c.Int(),
name = c.String(nullable: false, maxLength: 255),
description = c.String(),
isEditable = c.Boolean(nullable: false),
rootXpath = c.String(maxLength: 250),
igtype_datatypeId = c.Int(),
})
.PrimaryKey(t => t.id)
.ForeignKey("dbo.green_constraint", t => t.parentGreenConstraintId)
.ForeignKey("dbo.green_template", t => t.greenTemplateId)
.ForeignKey("dbo.implementationguidetype_datatype", t => t.igtype_datatypeId)
.ForeignKey("dbo.template_constraint", t => t.templateConstraintId, cascadeDelete: true)
.Index(t => t.greenTemplateId)
.Index(t => t.templateConstraintId)
.Index(t => t.parentGreenConstraintId)
.Index(t => t.igtype_datatypeId);
CreateTable(
"dbo.green_template",
c => new
{
id = c.Int(nullable: false, identity: true),
parentGreenTemplateId = c.Int(),
templateId = c.Int(nullable: false),
order = c.Int(),
name = c.String(nullable: false, maxLength: 255),
description = c.String(),
})
.PrimaryKey(t => t.id)
.ForeignKey("dbo.green_template", t => t.parentGreenTemplateId)
.ForeignKey("dbo.template", t => t.templateId, cascadeDelete: true)
.Index(t => t.parentGreenTemplateId)
.Index(t => t.templateId);
CreateTable(
"dbo.implementationguidetype_datatype",
c => new
{
id = c.Int(nullable: false, identity: true),
implementationGuideTypeId = c.Int(nullable: false),
dataTypeName = c.String(nullable: false, maxLength: 255),
})
.PrimaryKey(t => t.id)
.ForeignKey("dbo.implementationguidetype", t => t.implementationGuideTypeId)
.Index(t => t.implementationGuideTypeId);
CreateTable(
"dbo.implementationguidetype",
c => new
{
id = c.Int(nullable: false, identity: true),
name = c.String(nullable: false, maxLength: 255),
schemaLocation = c.String(nullable: false, maxLength: 255),
schemaPrefix = c.String(nullable: false, maxLength: 255),
schemaURI = c.String(nullable: false, maxLength: 255),
})
.PrimaryKey(t => t.id);
CreateTable(
"dbo.templatetype",
c => new
{
id = c.Int(nullable: false, identity: true),
implementationGuideTypeId = c.Int(nullable: false),
name = c.String(nullable: false, maxLength: 255),
outputOrder = c.Int(nullable: false),
rootContext = c.String(maxLength: 255),
rootContextType = c.String(maxLength: 255),
})
.PrimaryKey(t => t.id)
.ForeignKey("dbo.implementationguidetype", t => t.implementationGuideTypeId, cascadeDelete: true)
.Index(t => t.implementationGuideTypeId);
CreateTable(
"dbo.implementationguide_templatetype",
c => new
{
id = c.Int(nullable: false, identity: true),
implementationGuideId = c.Int(nullable: false),
templateTypeId = c.Int(nullable: false),
name = c.String(nullable: false, maxLength: 255),
detailsText = c.String(),
})
.PrimaryKey(t => t.id)
.ForeignKey("dbo.templatetype", t => t.templateTypeId, cascadeDelete: true)
.ForeignKey("dbo.implementationguide", t => t.implementationGuideId, cascadeDelete: true)
.Index(t => t.implementationGuideId)
.Index(t => t.templateTypeId);
CreateTable(
"dbo.template_constraint_sample",
c => new
{
id = c.Int(nullable: false, identity: true),
templateConstraintId = c.Int(nullable: false),
name = c.String(nullable: false, maxLength: 255),
sampleText = c.String(nullable: false, storeType: "ntext"),
})
.PrimaryKey(t => t.id)
.ForeignKey("dbo.template_constraint", t => t.templateConstraintId, cascadeDelete: true)
.Index(t => t.templateConstraintId);
CreateTable(
"dbo.template_extension",
c => new
{
id = c.Int(nullable: false, identity: true),
templateId = c.Int(nullable: false),
identifier = c.String(nullable: false, maxLength: 255),
type = c.String(nullable: false, maxLength: 55),
value = c.String(nullable: false, maxLength: 255),
})
.PrimaryKey(t => t.id)
.ForeignKey("dbo.template", t => t.templateId, cascadeDelete: true)
.Index(t => t.templateId);
CreateTable(
"dbo.publish_status",
c => new
{
id = c.Int(nullable: false, identity: true),
status = c.String(nullable: false, maxLength: 50),
})
.PrimaryKey(t => t.id);
CreateTable(
"dbo.template_sample",
c => new
{
id = c.Int(nullable: false, identity: true),
templateId = c.Int(nullable: false),
lastUpdated = c.DateTime(nullable: false, storeType: "date"),
xmlSample = c.String(nullable: false, unicode: false, storeType: "text"),
name = c.String(nullable: false, maxLength: 255),
})
.PrimaryKey(t => t.id)
.ForeignKey("dbo.template", t => t.templateId, cascadeDelete: true)
.Index(t => t.templateId);
CreateTable(
"dbo.implementationguide_file",
c => new
{
id = c.Int(nullable: false, identity: true),
implementationGuideId = c.Int(nullable: false),
fileName = c.String(nullable: false, maxLength: 255),
mimeType = c.String(nullable: false, maxLength: 255),
contentType = c.String(nullable: false, maxLength: 255),
expectedErrorCount = c.Int(),
description = c.String(nullable: false, storeType: "ntext"),
url = c.String(maxLength: 255),
})
.PrimaryKey(t => t.id)
.ForeignKey("dbo.implementationguide", t => t.implementationGuideId, cascadeDelete: true)
.Index(t => t.implementationGuideId);
CreateTable(
"dbo.implementationguide_filedata",
c => new
{
id = c.Int(nullable: false, identity: true),
implementationGuideFileId = c.Int(nullable: false),
data = c.Binary(nullable: false, storeType: "image"),
updatedDate = c.DateTime(nullable: false),
updatedBy = c.String(nullable: false, maxLength: 255),
note = c.String(),
})
.PrimaryKey(t => t.id)
.ForeignKey("dbo.implementationguide_file", t => t.implementationGuideFileId, cascadeDelete: true)
.Index(t => t.implementationGuideFileId);
CreateTable(
"dbo.implementationguide_schpattern",
c => new
{
id = c.Int(nullable: false, identity: true),
implementationGuideId = c.Int(nullable: false),
phase = c.String(nullable: false, maxLength: 128),
patternId = c.String(nullable: false, maxLength: 255),
patternContent = c.String(nullable: false),
})
.PrimaryKey(t => t.id)
.ForeignKey("dbo.implementationguide", t => t.implementationGuideId, cascadeDelete: true)
.Index(t => t.implementationGuideId);
CreateTable(
"dbo.implementationguide_section",
c => new
{
id = c.Int(nullable: false, identity: true),
implementationGuideId = c.Int(nullable: false),
heading = c.String(nullable: false, maxLength: 255),
content = c.String(storeType: "ntext"),
order = c.Int(nullable: false),
level = c.Int(nullable: false),
})
.PrimaryKey(t => t.id)
.ForeignKey("dbo.implementationguide", t => t.implementationGuideId, cascadeDelete: true)
.Index(t => t.implementationGuideId);
CreateTable(
"dbo.implementationguide_setting",
c => new
{
id = c.Int(nullable: false, identity: true),
implementationGuideId = c.Int(nullable: false),
propertyName = c.String(nullable: false, maxLength: 255),
propertyValue = c.String(nullable: false),
})
.PrimaryKey(t => t.id)
.ForeignKey("dbo.implementationguide", t => t.implementationGuideId, cascadeDelete: true)
.Index(t => t.implementationGuideId);
CreateTable(
"dbo.audit",
c => new
{
id = c.Int(nullable: false, identity: true),
username = c.String(nullable: false, maxLength: 255),
auditDate = c.DateTime(nullable: false),
ip = c.String(nullable: false, maxLength: 50),
type = c.String(nullable: false, maxLength: 128),
implementationGuideId = c.Int(),
templateId = c.Int(),
templateConstraintId = c.Int(),
note = c.String(),
})
.PrimaryKey(t => t.id);
this.SqlResource("Trifolia.DB.Migrations.201703021923101_init_views_up.sql");
this.SqlResource("Trifolia.DB.Migrations.201703021923101_init_programmability_up.sql");
}
public override void Down()
{
this.SqlResource("Trifolia.DB.Migrations.201703021923101_init_views_down.sql");
this.SqlResource("Trifolia.DB.Migrations.201703021923101_init_programmability_down.sql");
DropForeignKey("dbo.appsecurable_role", "appSecurableId", "dbo.app_securable");
DropForeignKey("dbo.role_restriction", "roleId", "dbo.role");
DropForeignKey("dbo.role_restriction", "organizationId", "dbo.organization");
DropForeignKey("dbo.implementationguide_templatetype", "implementationGuideId", "dbo.implementationguide");
DropForeignKey("dbo.implementationguide_setting", "implementationGuideId", "dbo.implementationguide");
DropForeignKey("dbo.implementationguide_section", "implementationGuideId", "dbo.implementationguide");
DropForeignKey("dbo.implementationguide_schpattern", "implementationGuideId", "dbo.implementationguide");
DropForeignKey("dbo.implementationguide_permission", "implementationGuideId", "dbo.implementationguide");
DropForeignKey("dbo.implementationguide", "organizationId", "dbo.organization");
DropForeignKey("dbo.implementationguide", "previousVersionImplementationGuideId", "dbo.implementationguide");
DropForeignKey("dbo.implementationguide_file", "implementationGuideId", "dbo.implementationguide");
DropForeignKey("dbo.implementationguide_filedata", "implementationGuideFileId", "dbo.implementationguide_file");
DropForeignKey("dbo.template", "owningImplementationGuideId", "dbo.implementationguide");
DropForeignKey("dbo.template", "authorId", "dbo.user");
DropForeignKey("dbo.template_sample", "templateId", "dbo.template");
DropForeignKey("dbo.template", "statusId", "dbo.publish_status");
DropForeignKey("dbo.implementationguide", "publishStatusId", "dbo.publish_status");
DropForeignKey("dbo.template", "previousVersionTemplateId", "dbo.template");
DropForeignKey("dbo.template", "impliedTemplateId", "dbo.template");
DropForeignKey("dbo.template_extension", "templateId", "dbo.template");
DropForeignKey("dbo.template_constraint", "containedTemplateId", "dbo.template");
DropForeignKey("dbo.template_constraint", "templateId", "dbo.template");
DropForeignKey("dbo.template_constraint_sample", "templateConstraintId", "dbo.template_constraint");
DropForeignKey("dbo.green_constraint", "templateConstraintId", "dbo.template_constraint");
DropForeignKey("dbo.templatetype", "implementationGuideTypeId", "dbo.implementationguidetype");
DropForeignKey("dbo.template", "templateTypeId", "dbo.templatetype");
DropForeignKey("dbo.implementationguide_templatetype", "templateTypeId", "dbo.templatetype");
DropForeignKey("dbo.template", "implementationGuideTypeId", "dbo.implementationguidetype");
DropForeignKey("dbo.implementationguide", "implementationGuideTypeId", "dbo.implementationguidetype");
DropForeignKey("dbo.implementationguidetype_datatype", "implementationGuideTypeId", "dbo.implementationguidetype");
DropForeignKey("dbo.green_constraint", "igtype_datatypeId", "dbo.implementationguidetype_datatype");
DropForeignKey("dbo.green_template", "templateId", "dbo.template");
DropForeignKey("dbo.green_template", "parentGreenTemplateId", "dbo.green_template");
DropForeignKey("dbo.green_constraint", "greenTemplateId", "dbo.green_template");
DropForeignKey("dbo.green_constraint", "parentGreenConstraintId", "dbo.green_constraint");
DropForeignKey("dbo.valueset_member", "valueSetId", "dbo.valueset");
DropForeignKey("dbo.template_constraint", "valueSetId", "dbo.valueset");
DropForeignKey("dbo.valueset_member", "codeSystemId", "dbo.codesystem");
DropForeignKey("dbo.template_constraint", "codeSystemId", "dbo.codesystem");
DropForeignKey("dbo.template_constraint", "parentConstraintId", "dbo.template_constraint");
DropForeignKey("dbo.user_role", "userId", "dbo.user");
DropForeignKey("dbo.user_role", "roleId", "dbo.role");
DropForeignKey("dbo.group_manager", "userId", "dbo.user");
DropForeignKey("dbo.user_group", "userId", "dbo.user");
DropForeignKey("dbo.user_group", "groupId", "dbo.group");
DropForeignKey("dbo.group_manager", "groupId", "dbo.group");
DropForeignKey("dbo.implementationguide_permission", "userId", "dbo.user");
DropForeignKey("dbo.implementationguide_permission", "groupId", "dbo.group");
DropForeignKey("dbo.implementationguide", "accessManagerId", "dbo.user");
DropForeignKey("dbo.appsecurable_role", "roleId", "dbo.role");
DropIndex("dbo.implementationguide_setting", new[] { "implementationGuideId" });
DropIndex("dbo.implementationguide_section", new[] { "implementationGuideId" });
DropIndex("dbo.implementationguide_schpattern", new[] { "implementationGuideId" });
DropIndex("dbo.implementationguide_filedata", new[] { "implementationGuideFileId" });
DropIndex("dbo.implementationguide_file", new[] { "implementationGuideId" });
DropIndex("dbo.template_sample", new[] { "templateId" });
DropIndex("dbo.template_extension", new[] { "templateId" });
DropIndex("dbo.template_constraint_sample", new[] { "templateConstraintId" });
DropIndex("dbo.implementationguide_templatetype", new[] { "templateTypeId" });
DropIndex("dbo.implementationguide_templatetype", new[] { "implementationGuideId" });
DropIndex("dbo.templatetype", new[] { "implementationGuideTypeId" });
DropIndex("dbo.implementationguidetype_datatype", new[] { "implementationGuideTypeId" });
DropIndex("dbo.green_template", new[] { "templateId" });
DropIndex("dbo.green_template", new[] { "parentGreenTemplateId" });
DropIndex("dbo.green_constraint", new[] { "igtype_datatypeId" });
DropIndex("dbo.green_constraint", new[] { "parentGreenConstraintId" });
DropIndex("dbo.green_constraint", new[] { "templateConstraintId" });
DropIndex("dbo.green_constraint", new[] { "greenTemplateId" });
DropIndex("dbo.valueset_member", new[] { "codeSystemId" });
DropIndex("dbo.valueset_member", new[] { "valueSetId" });
DropIndex("dbo.template_constraint", new[] { "containedTemplateId" });
DropIndex("dbo.template_constraint", new[] { "valueSetId" });
DropIndex("dbo.template_constraint", new[] { "codeSystemId" });
DropIndex("dbo.template_constraint", new[] { "parentConstraintId" });
DropIndex("dbo.template_constraint", new[] { "templateId" });
DropIndex("dbo.template", new[] { "statusId" });
DropIndex("dbo.template", new[] { "previousVersionTemplateId" });
DropIndex("dbo.template", new[] { "authorId" });
DropIndex("dbo.template", new[] { "owningImplementationGuideId" });
DropIndex("dbo.template", new[] { "impliedTemplateId" });
DropIndex("dbo.template", new[] { "templateTypeId" });
DropIndex("dbo.template", new[] { "implementationGuideTypeId" });
DropIndex("dbo.user_role", new[] { "userId" });
DropIndex("dbo.user_role", new[] { "roleId" });
DropIndex("dbo.group_manager", new[] { "userId" });
DropIndex("dbo.group_manager", new[] { "groupId" });
DropIndex("dbo.implementationguide_permission", new[] { "userId" });
DropIndex("dbo.implementationguide_permission", new[] { "groupId" });
DropIndex("dbo.implementationguide_permission", new[] { "implementationGuideId" });
DropIndex("dbo.user_group", new[] { "groupId" });
DropIndex("dbo.user_group", new[] { "userId" });
DropIndex("dbo.implementationguide", new[] { "accessManagerId" });
DropIndex("dbo.implementationguide", new[] { "previousVersionImplementationGuideId" });
DropIndex("dbo.implementationguide", new[] { "publishStatusId" });
DropIndex("dbo.implementationguide", new[] { "organizationId" });
DropIndex("dbo.implementationguide", new[] { "implementationGuideTypeId" });
DropIndex("dbo.role_restriction", new[] { "organizationId" });
DropIndex("dbo.role_restriction", new[] { "roleId" });
DropIndex("dbo.appsecurable_role", new[] { "roleId" });
DropIndex("dbo.appsecurable_role", new[] { "appSecurableId" });
DropTable("dbo.audit");
DropTable("dbo.implementationguide_setting");
DropTable("dbo.implementationguide_section");
DropTable("dbo.implementationguide_schpattern");
DropTable("dbo.implementationguide_filedata");
DropTable("dbo.implementationguide_file");
DropTable("dbo.template_sample");
DropTable("dbo.publish_status");
DropTable("dbo.template_extension");
DropTable("dbo.template_constraint_sample");
DropTable("dbo.implementationguide_templatetype");
DropTable("dbo.templatetype");
DropTable("dbo.implementationguidetype");
DropTable("dbo.implementationguidetype_datatype");
DropTable("dbo.green_template");
DropTable("dbo.green_constraint");
DropTable("dbo.valueset");
DropTable("dbo.valueset_member");
DropTable("dbo.codesystem");
DropTable("dbo.template_constraint");
DropTable("dbo.template");
DropTable("dbo.user_role");
DropTable("dbo.group_manager");
DropTable("dbo.implementationguide_permission");
DropTable("dbo.group");
DropTable("dbo.user_group");
DropTable("dbo.user");
DropTable("dbo.implementationguide");
DropTable("dbo.organization");
DropTable("dbo.role_restriction");
DropTable("dbo.role");
DropTable("dbo.appsecurable_role");
DropTable("dbo.app_securable");
}
}
}
| |
// 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.Security;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
using Internal.Runtime.Augments;
namespace System.Threading
{
public delegate void TimerCallback(Object state);
//
// TimerQueue maintains a list of active timers in this AppDomain. We use a single native timer to schedule
// all managed timers in the process.
//
// Perf assumptions: We assume that timers are created and destroyed frequently, but rarely actually fire.
// There are roughly two types of timer:
//
// - timeouts for operations. These are created and destroyed very frequently, but almost never fire, because
// the whole point is that the timer only fires if something has gone wrong.
//
// - scheduled background tasks. These typically do fire, but they usually have quite long durations.
// So the impact of spending a few extra cycles to fire these is negligible.
//
// Because of this, we want to choose a data structure with very fast insert and delete times, but we can live
// with linear traversal times when firing timers.
//
// The data structure we've chosen is an unordered doubly-linked list of active timers. This gives O(1) insertion
// and removal, and O(N) traversal when finding expired timers.
//
// Note that all instance methods of this class require that the caller hold a lock on TimerQueue.Instance.
//
class TimerQueue
{
#region singleton pattern implementation
// The one-and-only TimerQueue for the AppDomain.
static TimerQueue s_queue = new TimerQueue();
public static TimerQueue Instance
{
get { return s_queue; }
}
private TimerQueue()
{
// empty private constructor to ensure we remain a singleton.
}
#endregion
#region interface to native per-AppDomain timer
//
// We need to keep our notion of time synchronized with the calls to SleepEx that drive
// the underlying native timer. In Win8, SleepEx does not count the time the machine spends
// sleeping/hibernating. Environment.TickCount (GetTickCount) *does* count that time,
// so we will get out of sync with SleepEx if we use that method.
//
// So, on Win8, we use QueryUnbiasedInterruptTime instead; this does not count time spent
// in sleep/hibernate mode.
//
private static int TickCount
{
[SecuritySafeCritical]
get
{
ulong time100ns;
bool result = Interop.mincore.QueryUnbiasedInterruptTime(out time100ns);
Contract.Assert(result);
// convert to 100ns to milliseconds, and truncate to 32 bits.
return (int)(uint)(time100ns / 10000);
}
}
Delegate m_nativeTimerCallback;
Object m_nativeTimer;
int m_currentNativeTimerStartTicks;
uint m_currentNativeTimerDuration;
[SecuritySafeCritical]
private void EnsureAppDomainTimerFiresBy(uint requestedDuration)
{
//
// The CLR VM's timer implementation does not work well for very long-duration timers.
// See kb 950807.
// So we'll limit our native timer duration to a "small" value.
// This may cause us to attempt to fire timers early, but that's ok -
// we'll just see that none of our timers has actually reached its due time,
// and schedule the native timer again.
//
const uint maxPossibleDuration = 0x0fffffff;
uint actualDuration = Math.Min(requestedDuration, maxPossibleDuration);
if (m_nativeTimer != null)
{
uint elapsed = (uint)(TickCount - m_currentNativeTimerStartTicks);
if (elapsed >= m_currentNativeTimerDuration)
return; //the timer's about to fire
uint remainingDuration = m_currentNativeTimerDuration - elapsed;
if (actualDuration >= remainingDuration)
return; //the timer will fire earlier than this request
}
#if FEATURE_LEGACYNETCFFAS
// If Pause is underway then do not schedule the timers
// A later update during resume will re-schedule
if (m_pauseTicks != 0)
{
Contract.Assert(!m_isAppDomainTimerScheduled);
Contract.Assert(m_appDomainTimer == null);
return true;
}
#endif //FEATURE_LEGACYNETCFFAS
if (m_nativeTimerCallback == null)
{
Contract.Assert(m_nativeTimer == null);
m_nativeTimerCallback = WinRTInterop.Callbacks.CreateTimerDelegate(new Action(AppDomainTimerCallback));
}
Object previousNativeTimer = m_nativeTimer;
m_nativeTimer = WinRTInterop.Callbacks.CreateTimer(m_nativeTimerCallback, TimeSpan.FromMilliseconds(actualDuration));
if (previousNativeTimer != null)
WinRTInterop.Callbacks.ReleaseTimer(previousNativeTimer, true);
m_currentNativeTimerStartTicks = TickCount;
m_currentNativeTimerDuration = actualDuration;
}
//
// The VM calls this when the native timer fires.
//
[SecuritySafeCritical]
internal static void AppDomainTimerCallback()
{
try
{
Instance.FireNextTimers();
}
catch (Exception ex)
{
RuntimeAugments.ReportUnhandledException(ex);
}
}
#endregion
#region Firing timers
//
// The list of timers
//
TimerQueueTimer m_timers;
readonly internal Lock Lock = new Lock();
#if FEATURE_LEGACYNETCFFAS
volatile int m_pauseTicks = 0; // Time when Pause was called
[SecurityCritical]
internal void Pause()
{
lock (Lock)
{
// Delete the native timer so that no timers are fired in the Pause zone
if (m_appDomainTimer != null && !m_appDomainTimer.IsInvalid)
{
m_appDomainTimer.Dispose();
m_appDomainTimer = null;
m_isAppDomainTimerScheduled = false;
m_pauseTicks = TickCount;
}
}
}
[SecurityCritical]
internal void Resume()
{
//
// Update timers to adjust their due-time to accomodate Pause/Resume
//
lock (Lock)
{
// prevent ThreadAbort while updating state
try { }
finally
{
int pauseTicks = m_pauseTicks;
m_pauseTicks = 0; // Set this to 0 so that now timers can be scheduled
int resumedTicks = TickCount;
int pauseDuration = resumedTicks - pauseTicks;
bool haveTimerToSchedule = false;
uint nextAppDomainTimerDuration = uint.MaxValue;
TimerQueueTimer timer = m_timers;
while (timer != null)
{
Contract.Assert(timer.m_dueTime != Timer.UnsignedInfiniteTimeout);
Contract.Assert(resumedTicks >= timer.m_startTicks);
uint elapsed; // How much of the timer dueTime has already elapsed
// Timers started before the paused event has to be sufficiently delayed to accomodate
// for the Pause time. However, timers started after the Paused event shouldnt be adjusted.
// E.g. ones created by the app in its Activated event should fire when it was designated.
// The Resumed event which is where this routine is executing is after this Activated and hence
// shouldn't delay this timer
if (timer.m_startTicks <= pauseTicks)
elapsed = (uint)(pauseTicks - timer.m_startTicks);
else
elapsed = (uint)(resumedTicks - timer.m_startTicks);
// Handling the corner cases where a Timer was already due by the time Resume is happening,
// We shouldn't delay those timers.
// Example is a timer started in App's Activated event with a very small duration
timer.m_dueTime = (timer.m_dueTime > elapsed) ? timer.m_dueTime - elapsed : 0; ;
timer.m_startTicks = resumedTicks; // re-baseline
if (timer.m_dueTime < nextAppDomainTimerDuration)
{
haveTimerToSchedule = true;
nextAppDomainTimerDuration = timer.m_dueTime;
}
timer = timer.m_next;
}
if (haveTimerToSchedule)
{
EnsureAppDomainTimerFiresBy(nextAppDomainTimerDuration);
}
}
}
}
#endif // FEATURE_LEGACYNETCFFAS
//
// Fire any timers that have expired, and update the native timer to schedule the rest of them.
//
private void FireNextTimers()
{
//
// we fire the first timer on this thread; any other timers that might have fired are queued
// to the ThreadPool.
//
TimerQueueTimer timerToFireOnThisThread = null;
Object previousTimer = null;
lock (Lock)
{
// prevent ThreadAbort while updating state
try { }
finally
{
//
// since we got here, that means our previous timer has fired.
//
previousTimer = m_nativeTimer;
m_nativeTimer = null;
bool haveTimerToSchedule = false;
uint nextAppDomainTimerDuration = uint.MaxValue;
int nowTicks = TickCount;
//
// Sweep through all timers. The ones that have reached their due time
// will fire. We will calculate the next native timer due time from the
// other timers.
//
TimerQueueTimer timer = m_timers;
while (timer != null)
{
Contract.Assert(timer.m_dueTime != Timer.UnsignedInfiniteTimeout);
uint elapsed = (uint)(nowTicks - timer.m_startTicks);
if (elapsed >= timer.m_dueTime)
{
//
// Remember the next timer in case we delete this one
//
TimerQueueTimer nextTimer = timer.m_next;
if (timer.m_period != Timer.UnsignedInfiniteTimeout)
{
timer.m_startTicks = nowTicks;
timer.m_dueTime = timer.m_period;
//
// This is a repeating timer; schedule it to run again.
//
if (timer.m_dueTime < nextAppDomainTimerDuration)
{
haveTimerToSchedule = true;
nextAppDomainTimerDuration = timer.m_dueTime;
}
}
else
{
//
// Not repeating; remove it from the queue
//
DeleteTimer(timer);
}
//
// If this is the first timer, we'll fire it on this thread. Otherwise, queue it
// to the ThreadPool.
//
if (timerToFireOnThisThread == null)
timerToFireOnThisThread = timer;
else
QueueTimerCompletion(timer);
timer = nextTimer;
}
else
{
//
// This timer hasn't fired yet. Just update the next time the native timer fires.
//
uint remaining = timer.m_dueTime - elapsed;
if (remaining < nextAppDomainTimerDuration)
{
haveTimerToSchedule = true;
nextAppDomainTimerDuration = remaining;
}
timer = timer.m_next;
}
}
if (haveTimerToSchedule)
EnsureAppDomainTimerFiresBy(nextAppDomainTimerDuration);
}
}
//
// Release the previous timer object outside of the lock!
//
if (previousTimer != null)
WinRTInterop.Callbacks.ReleaseTimer(previousTimer, false);
//
// Fire the user timer outside of the lock!
//
if (timerToFireOnThisThread != null)
timerToFireOnThisThread.Fire();
}
[SecuritySafeCritical]
private static void QueueTimerCompletion(TimerQueueTimer timer)
{
WaitCallback callback = s_fireQueuedTimerCompletion;
if (callback == null)
s_fireQueuedTimerCompletion = callback = new WaitCallback(FireQueuedTimerCompletion);
// Can use "unsafe" variant because we take care of capturing and restoring
// the ExecutionContext.
ThreadPool.UnsafeQueueUserWorkItem(callback, timer);
}
private static WaitCallback s_fireQueuedTimerCompletion;
private static void FireQueuedTimerCompletion(object state)
{
((TimerQueueTimer)state).Fire();
}
#endregion
#region Queue implementation
public bool UpdateTimer(TimerQueueTimer timer, uint dueTime, uint period)
{
if (timer.m_dueTime == Timer.UnsignedInfiniteTimeout)
{
// the timer is not in the list; add it (as the head of the list).
timer.m_next = m_timers;
timer.m_prev = null;
if (timer.m_next != null)
timer.m_next.m_prev = timer;
m_timers = timer;
}
timer.m_dueTime = dueTime;
timer.m_period = (period == 0) ? Timer.UnsignedInfiniteTimeout : period;
timer.m_startTicks = TickCount;
EnsureAppDomainTimerFiresBy(dueTime);
return true;
}
public void DeleteTimer(TimerQueueTimer timer)
{
if (timer.m_dueTime != Timer.UnsignedInfiniteTimeout)
{
if (timer.m_next != null)
timer.m_next.m_prev = timer.m_prev;
if (timer.m_prev != null)
timer.m_prev.m_next = timer.m_next;
if (m_timers == timer)
m_timers = timer.m_next;
timer.m_dueTime = Timer.UnsignedInfiniteTimeout;
timer.m_period = Timer.UnsignedInfiniteTimeout;
timer.m_startTicks = 0;
timer.m_prev = null;
timer.m_next = null;
}
}
#endregion
}
//
// A timer in our TimerQueue.
//
sealed class TimerQueueTimer
{
//
// All fields of this class are protected by a lock on TimerQueue.Instance.
//
// The first four fields are maintained by TimerQueue itself.
//
internal TimerQueueTimer m_next;
internal TimerQueueTimer m_prev;
//
// The time, according to TimerQueue.TickCount, when this timer's current interval started.
//
internal int m_startTicks;
//
// Timer.UnsignedInfiniteTimeout if we are not going to fire. Otherwise, the offset from m_startTime when we will fire.
//
internal uint m_dueTime;
//
// Timer.UnsignedInfiniteTimeout if we are a single-shot timer. Otherwise, the repeat interval.
//
internal uint m_period;
//
// Info about the user's callback
//
readonly TimerCallback m_timerCallback;
readonly Object m_state;
readonly ExecutionContext m_executionContext;
//
// When Timer.Dispose(WaitHandle) is used, we need to signal the wait handle only
// after all pending callbacks are complete. We set m_canceled to prevent any callbacks that
// are already queued from running. We track the number of callbacks currently executing in
// m_callbacksRunning. We set m_notifyWhenNoCallbacksRunning only when m_callbacksRunning
// reaches zero.
//
//int m_callbacksRunning;
volatile bool m_canceled;
//volatile WaitHandle m_notifyWhenNoCallbacksRunning;
[SecurityCritical]
internal TimerQueueTimer(TimerCallback timerCallback, object state, uint dueTime, uint period)
{
m_timerCallback = timerCallback;
m_state = state;
m_dueTime = Timer.UnsignedInfiniteTimeout;
m_period = Timer.UnsignedInfiniteTimeout;
m_executionContext = ExecutionContext.Capture();
//
// After the following statement, the timer may fire. No more manipulation of timer state outside of
// the lock is permitted beyond this point!
//
if (dueTime != Timer.UnsignedInfiniteTimeout)
Change(dueTime, period);
}
internal bool Change(uint dueTime, uint period)
{
bool success;
lock (TimerQueue.Instance.Lock)
{
if (m_canceled)
throw new ObjectDisposedException(null, SR.ObjectDisposed_Generic);
// prevent ThreadAbort while updating state
try { }
finally
{
m_period = period;
if (dueTime == Timer.UnsignedInfiniteTimeout)
{
TimerQueue.Instance.DeleteTimer(this);
success = true;
}
else
{
success = TimerQueue.Instance.UpdateTimer(this, dueTime, period);
}
}
}
return success;
}
public void Close()
{
lock (TimerQueue.Instance.Lock)
{
// prevent ThreadAbort while updating state
try { }
finally
{
if (!m_canceled)
{
m_canceled = true;
TimerQueue.Instance.DeleteTimer(this);
}
}
}
}
//public bool Close(WaitHandle toSignal)
//{
// bool success;
// bool shouldSignal = false;
// lock (TimerQueue.Instance.Lock)
// {
// // prevent ThreadAbort while updating state
// try { }
// finally
// {
// if (m_canceled)
// {
// success = false;
// }
// else
// {
// m_canceled = true;
// m_notifyWhenNoCallbacksRunning = toSignal;
// TimerQueue.Instance.DeleteTimer(this);
// if (m_callbacksRunning == 0)
// shouldSignal = true;
// success = true;
// }
// }
// }
// if (shouldSignal)
// SignalNoCallbacksRunning();
// return success;
//}
internal void Fire()
{
bool canceled = false;
//lock (TimerQueue.Instance.Lock)
//{
// // prevent ThreadAbort while updating state
// try { }
// finally
// {
canceled = m_canceled;
// if (!canceled)
// m_callbacksRunning++;
// }
//}
if (canceled)
return;
CallCallback();
//bool shouldSignal = false;
//lock (TimerQueue.Instance.Lock)
//{
// // prevent ThreadAbort while updating state
// try { }
// finally
// {
// m_callbacksRunning--;
// if (m_canceled && m_callbacksRunning == 0 && m_notifyWhenNoCallbacksRunning != null)
// shouldSignal = true;
// }
//}
//if (shouldSignal)
// SignalNoCallbacksRunning();
}
//[SecuritySafeCritical]
//internal void SignalNoCallbacksRunning()
//{
// SafeHandle handle = m_notifyWhenNoCallbacksRunning.SafeWaitHandle;
// handle.DangerousAddRef();
// Interop.kernel32.SetEvent(handle.DangerousGetHandle());
// handle.DangerousRelease();
//}
[SecuritySafeCritical]
internal void CallCallback()
{
ContextCallback callback = s_callCallbackInContext;
if (callback == null)
s_callCallbackInContext = callback = new ContextCallback(CallCallbackInContext);
ExecutionContext.Run(m_executionContext, callback, this);
}
[SecurityCritical]
private static ContextCallback s_callCallbackInContext;
[SecurityCritical]
private static void CallCallbackInContext(object state)
{
TimerQueueTimer t = (TimerQueueTimer)state;
t.m_timerCallback(t.m_state);
}
}
//
// TimerHolder serves as an intermediary between Timer and TimerQueueTimer, releasing the TimerQueueTimer
// if the Timer is collected.
// This is necessary because Timer itself cannot use its finalizer for this purpose. If it did,
// then users could control timer lifetimes using GC.SuppressFinalize/ReRegisterForFinalize.
// You might ask, wouldn't that be a good thing? Maybe (though it would be even better to offer this
// via first-class APIs), but Timer has never offered this, and adding it now would be a breaking
// change, because any code that happened to be suppressing finalization of Timer objects would now
// unwittingly be changing the lifetime of those timers.
//
sealed class TimerHolder
{
internal TimerQueueTimer m_timer;
public TimerHolder(TimerQueueTimer timer)
{
m_timer = timer;
}
~TimerHolder()
{
//
// If shutdown has started, another thread may be suspended while holding the timer lock.
// So we can't safely close the timer.
//
// Similarly, we should not close the timer during AD-unload's live-object finalization phase.
// A rude abort may have prevented us from releasing the lock.
//
// Note that in either case, the Timer still won't fire, because ThreadPool threads won't be
// allowed to run in this AppDomain.
//
if (Environment.HasShutdownStarted /*|| AppDomain.CurrentDomain.IsFinalizingForUnload()*/)
return;
m_timer.Close();
}
public void Close()
{
m_timer.Close();
GC.SuppressFinalize(this);
}
//public bool Close(WaitHandle notifyObject)
//{
// bool result = m_timer.Close(notifyObject);
// GC.SuppressFinalize(this);
// return result;
//}
}
public sealed class Timer : IDisposable
{
private const UInt32 MAX_SUPPORTED_TIMEOUT = (uint)0xfffffffe;
internal const uint UnsignedInfiniteTimeout = unchecked((uint)-1);
private TimerHolder m_timer;
[SecuritySafeCritical]
public Timer(TimerCallback callback,
Object state,
int dueTime,
int period)
{
if (dueTime < -1)
throw new ArgumentOutOfRangeException("dueTime", SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
if (period < -1)
throw new ArgumentOutOfRangeException("period", SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
Contract.EndContractBlock();
TimerSetup(callback, state, (UInt32)dueTime, (UInt32)period);
}
[SecuritySafeCritical]
public Timer(TimerCallback callback,
Object state,
TimeSpan dueTime,
TimeSpan period)
{
long dueTm = (long)dueTime.TotalMilliseconds;
if (dueTm < -1)
throw new ArgumentOutOfRangeException("dueTm", SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
if (dueTm > MAX_SUPPORTED_TIMEOUT)
throw new ArgumentOutOfRangeException("dueTm", SR.ArgumentOutOfRange_TimeoutTooLarge);
long periodTm = (long)period.TotalMilliseconds;
if (periodTm < -1)
throw new ArgumentOutOfRangeException("periodTm", SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
if (periodTm > MAX_SUPPORTED_TIMEOUT)
throw new ArgumentOutOfRangeException("periodTm", SR.ArgumentOutOfRange_PeriodTooLarge);
TimerSetup(callback, state, (UInt32)dueTm, (UInt32)periodTm);
}
[SecurityCritical]
private void TimerSetup(TimerCallback callback,
Object state,
UInt32 dueTime,
UInt32 period)
{
if (callback == null)
throw new ArgumentNullException("TimerCallback");
Contract.EndContractBlock();
m_timer = new TimerHolder(new TimerQueueTimer(callback, state, dueTime, period));
}
#if FEATURE_LEGACYNETCFFAS
[SecurityCritical]
internal static void Pause()
{
TimerQueue.Instance.Pause();
}
[SecurityCritical]
internal static void Resume()
{
TimerQueue.Instance.Resume();
}
#endif // FEATURE_LEGACYNETCFFAS
public bool Change(int dueTime, int period)
{
if (dueTime < -1)
throw new ArgumentOutOfRangeException("dueTime", SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
if (period < -1)
throw new ArgumentOutOfRangeException("period", SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
Contract.EndContractBlock();
return m_timer.m_timer.Change((UInt32)dueTime, (UInt32)period);
}
public bool Change(TimeSpan dueTime, TimeSpan period)
{
return Change((long)dueTime.TotalMilliseconds, (long)period.TotalMilliseconds);
}
private bool Change(long dueTime, long period)
{
if (dueTime < -1)
throw new ArgumentOutOfRangeException("dueTime", SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
if (period < -1)
throw new ArgumentOutOfRangeException("period", SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
if (dueTime > MAX_SUPPORTED_TIMEOUT)
throw new ArgumentOutOfRangeException("dueTime", SR.ArgumentOutOfRange_TimeoutTooLarge);
if (period > MAX_SUPPORTED_TIMEOUT)
throw new ArgumentOutOfRangeException("period", SR.ArgumentOutOfRange_PeriodTooLarge);
Contract.EndContractBlock();
return m_timer.m_timer.Change((UInt32)dueTime, (UInt32)period);
}
//public bool Dispose(WaitHandle notifyObject)
//{
// if (notifyObject==null)
// throw new ArgumentNullException("notifyObject");
// Contract.EndContractBlock();
// return m_timer.Close(notifyObject);
//}
public void Dispose()
{
m_timer.Close();
}
internal void KeepRootedWhileScheduled()
{
GC.SuppressFinalize(m_timer);
}
}
}
| |
#region License
//
// Copyright (c) 2007-2009, Sean Chambers <schambers80@gmail.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.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Linq;
using FluentMigrator.Builders.Create.Column;
using FluentMigrator.Expressions;
using FluentMigrator.Infrastructure;
using FluentMigrator.Model;
using FluentMigrator.Runner.Extensions;
using Moq;
using NUnit.Framework;
using NUnit.Should;
namespace FluentMigrator.Tests.Unit.Builders.Create
{
[TestFixture]
public class CreateColumnExpressionBuilderTests
{
[Test]
public void CallingOnTableSetsTableName()
{
var expressionMock = new Mock<CreateColumnExpression>();
var contextMock = new Mock<IMigrationContext>();
var builder = new CreateColumnExpressionBuilder(expressionMock.Object, contextMock.Object);
builder.OnTable("Bacon");
expressionMock.VerifySet(x => x.TableName = "Bacon");
}
[Test]
public void CallingAsAnsiStringSetsColumnDbTypeToAnsiString()
{
VerifyColumnDbType(DbType.AnsiString, b => b.AsAnsiString());
}
[Test]
public void CallingAsAnsiStringWithSizeSetsColumnDbTypeToAnsiString()
{
VerifyColumnDbType(DbType.AnsiString, b => b.AsAnsiString(42));
}
[Test]
public void CallingAsAnsiStringWithSizeSetsColumnSizeToSpecifiedValue()
{
VerifyColumnSize(42, b => b.AsAnsiString(42));
}
[Test]
public void CallingAsBinarySetsColumnDbTypeToBinary()
{
VerifyColumnDbType(DbType.Binary, b => b.AsBinary());
}
[Test]
public void CallingAsBinaryWithSizeSetsColumnDbTypeToBinary()
{
VerifyColumnDbType(DbType.Binary, b => b.AsBinary(42));
}
[Test]
public void CallingAsBinaryWithSizeSetsColumnSizeToSpecifiedValue()
{
VerifyColumnSize(42, b => b.AsBinary(42));
}
[Test]
public void CallingAsBooleanSetsColumnDbTypeToBoolean()
{
VerifyColumnDbType(DbType.Boolean, b => b.AsBoolean());
}
[Test]
public void CallingAsByteSetsColumnDbTypeToByte()
{
VerifyColumnDbType(DbType.Byte, b => b.AsByte());
}
[Test]
public void CallingAsCurrencySetsColumnDbTypeToCurrency()
{
VerifyColumnDbType(DbType.Currency, b => b.AsCurrency());
}
[Test]
public void CallingAsDateSetsColumnDbTypeToDate()
{
VerifyColumnDbType(DbType.Date, b => b.AsDate());
}
[Test]
public void CallingAsDateTimeSetsColumnDbTypeToDateTime()
{
VerifyColumnDbType(DbType.DateTime, b => b.AsDateTime());
}
[Test]
public void CallingAsDecimalSetsColumnDbTypeToDecimal()
{
VerifyColumnDbType(DbType.Decimal, b => b.AsDecimal());
}
[Test]
public void CallingAsDecimalWithSizeAndPrecisionSetsColumnDbTypeToDecimal()
{
VerifyColumnDbType(DbType.Decimal, b => b.AsDecimal(1, 2));
}
[Test]
public void CallingAsDecimalStringSetsColumnSizeToSpecifiedValue()
{
VerifyColumnSize(1, b => b.AsDecimal(1, 2));
}
[Test]
public void CallingAsDecimalStringSetsColumnPrecisionToSpecifiedValue()
{
VerifyColumnPrecision(2, b => b.AsDecimal(1, 2));
}
[Test]
public void CallingAsDoubleSetsColumnDbTypeToDouble()
{
VerifyColumnDbType(DbType.Double, b => b.AsDouble());
}
[Test]
public void CallingAsGuidSetsColumnDbTypeToGuid()
{
VerifyColumnDbType(DbType.Guid, b => b.AsGuid());
}
[Test]
public void CallingAsFixedLengthStringSetsColumnDbTypeToStringFixedLength()
{
VerifyColumnDbType(DbType.StringFixedLength, e => e.AsFixedLengthString(255));
}
[Test]
public void CallingAsFixedLengthStringSetsColumnSizeToSpecifiedValue()
{
VerifyColumnSize(255, b => b.AsFixedLengthString(255));
}
[Test]
public void CallingAsFixedLengthAnsiStringSetsColumnDbTypeToAnsiStringFixedLength()
{
VerifyColumnDbType(DbType.AnsiStringFixedLength, b => b.AsFixedLengthAnsiString(255));
}
[Test]
public void CallingAsFixedLengthAnsiStringSetsColumnSizeToSpecifiedValue()
{
VerifyColumnSize(255, b => b.AsFixedLengthAnsiString(255));
}
[Test]
public void CallingAsFloatSetsColumnDbTypeToSingle()
{
VerifyColumnDbType(DbType.Single, b => b.AsFloat());
}
[Test]
public void CallingAsInt16SetsColumnDbTypeToInt16()
{
VerifyColumnDbType(DbType.Int16, b => b.AsInt16());
}
[Test]
public void CallingAsInt32SetsColumnDbTypeToInt32()
{
VerifyColumnDbType(DbType.Int32, b => b.AsInt32());
}
[Test]
public void CallingAsInt64SetsColumnDbTypeToInt64()
{
VerifyColumnDbType(DbType.Int64, b => b.AsInt64());
}
[Test]
public void CallingAsStringSetsColumnDbTypeToString()
{
VerifyColumnDbType(DbType.String, b => b.AsString());
}
[Test]
public void CallingAsStringWithLengthSetsColumnDbTypeToString()
{
VerifyColumnDbType(DbType.String, b => b.AsString(255));
}
[Test]
public void CallingAsStringSetsColumnSizeToSpecifiedValue()
{
VerifyColumnSize(255, b => b.AsFixedLengthAnsiString(255));
}
[Test]
public void CallingAsTimeSetsColumnDbTypeToTime()
{
VerifyColumnDbType(DbType.Time, b => b.AsTime());
}
[Test]
public void CallingAsXmlSetsColumnDbTypeToXml()
{
VerifyColumnDbType(DbType.Xml, b => b.AsXml());
}
[Test]
public void CallingAsXmlWithSizeSetsColumnDbTypeToXml()
{
VerifyColumnDbType(DbType.Xml, b => b.AsXml(255));
}
[Test]
public void CallingAsXmlSetsColumnSizeToSpecifiedValue()
{
VerifyColumnSize(255, b => b.AsXml(255));
}
[Test]
public void CallingAsCustomSetsTypeToNullAndSetsCustomType()
{
VerifyColumnProperty(c => c.Type = null, b => b.AsCustom("Test"));
VerifyColumnProperty(c => c.CustomType = "Test", b => b.AsCustom("Test"));
}
[Test]
public void CallingWithDefaultValueSetsDefaultValue()
{
const int value = 42;
var columnMock = new Mock<ColumnDefinition>();
var expressionMock = new Mock<CreateColumnExpression>();
expressionMock.SetupProperty(e => e.Column);
var expression = expressionMock.Object;
expression.Column = columnMock.Object;
var contextMock = new Mock<IMigrationContext>();
var builder = new CreateColumnExpressionBuilder(expressionMock.Object, contextMock.Object);
builder.WithDefaultValue(value);
columnMock.VerifySet(c => c.DefaultValue = value);
}
[Test]
public void CallingWithDefaultSetsDefaultValue()
{
var columnMock = new Mock<ColumnDefinition>();
var expressionMock = new Mock<CreateColumnExpression>();
expressionMock.SetupProperty(e => e.Column);
var expression = expressionMock.Object;
expression.Column = columnMock.Object;
var contextMock = new Mock<IMigrationContext>();
var builder = new CreateColumnExpressionBuilder(expressionMock.Object, contextMock.Object);
builder.WithDefault(SystemMethods.NewGuid);
columnMock.VerifySet(c => c.DefaultValue = SystemMethods.NewGuid);
}
[Test]
public void CallingForeignKeySetsIsForeignKeyToTrue()
{
VerifyColumnProperty(c => c.IsForeignKey = true, b => b.ForeignKey());
}
[Test]
public void CallingIdentitySetsIsIdentityToTrue()
{
VerifyColumnProperty(c => c.IsIdentity = true, b => b.Identity());
}
[Test]
public void CallingSeededIdentitySetsAdditionalProperties()
{
var contextMock = new Mock<IMigrationContext>();
var columnMock = new Mock<ColumnDefinition>();
columnMock.SetupGet(x => x.Name).Returns("BaconId");
var expressionMock = new Mock<CreateColumnExpression>();
expressionMock.SetupGet(x => x.Column).Returns(columnMock.Object);
var builder = new CreateColumnExpressionBuilder(expressionMock.Object, contextMock.Object);
builder.Identity(23, 44);
columnMock.Object.AdditionalFeatures.ShouldContain(
new KeyValuePair<string, object>(SqlServerExtensions.IdentitySeed, 23));
columnMock.Object.AdditionalFeatures.ShouldContain(
new KeyValuePair<string, object>(SqlServerExtensions.IdentityIncrement, 44));
}
[Test]
public void CallingIndexedSetsIsIndexedToTrue()
{
VerifyColumnProperty(c => c.IsIndexed = true, b => b.Indexed());
}
[Test]
public void CallingIndexedAddsIndexExpressionToContext()
{
var collectionMock = new Mock<ICollection<IMigrationExpression>>();
var contextMock = new Mock<IMigrationContext>();
contextMock.Setup(x => x.Expressions).Returns(collectionMock.Object);
var columnMock = new Mock<ColumnDefinition>();
columnMock.SetupGet(x => x.Name).Returns("BaconId");
var expressionMock = new Mock<CreateColumnExpression>();
expressionMock.SetupGet(x => x.SchemaName).Returns("Eggs");
expressionMock.SetupGet(x => x.TableName).Returns("Bacon");
expressionMock.SetupGet(x => x.Column).Returns(columnMock.Object);
var builder = new CreateColumnExpressionBuilder(expressionMock.Object, contextMock.Object);
builder.Indexed();
collectionMock.Verify(x => x.Add(It.Is<CreateIndexExpression>(
ix => ix.Index.Name == null
&& ix.Index.TableName == "Bacon"
&& ix.Index.SchemaName == "Eggs"
&& !ix.Index.IsUnique
&& !ix.Index.IsClustered
&& ix.Index.Columns.All(c => c.Name == "BaconId")
)));
contextMock.VerifyGet(x => x.Expressions);
}
[Test]
public void CallingIndexedNamedAddsIndexExpressionToContext()
{
var collectionMock = new Mock<ICollection<IMigrationExpression>>();
var contextMock = new Mock<IMigrationContext>();
contextMock.Setup(x => x.Expressions).Returns(collectionMock.Object);
var columnMock = new Mock<ColumnDefinition>();
columnMock.SetupGet(x => x.Name).Returns("BaconId");
var expressionMock = new Mock<CreateColumnExpression>();
expressionMock.SetupGet(x => x.SchemaName).Returns("Eggs");
expressionMock.SetupGet(x => x.TableName).Returns("Bacon");
expressionMock.SetupGet(x => x.Column).Returns(columnMock.Object);
var builder = new CreateColumnExpressionBuilder(expressionMock.Object, contextMock.Object);
builder.Indexed("IX_Bacon_BaconId");
collectionMock.Verify(x => x.Add(It.Is<CreateIndexExpression>(
ix => ix.Index.Name == "IX_Bacon_BaconId"
&& ix.Index.TableName == "Bacon"
&& ix.Index.SchemaName == "Eggs"
&& !ix.Index.IsUnique
&& !ix.Index.IsClustered
&& ix.Index.Columns.All(c => c.Name == "BaconId")
)));
contextMock.VerifyGet(x => x.Expressions);
}
[Test]
public void CallingPrimaryKeySetsIsPrimaryKeyToTrue()
{
VerifyColumnProperty(c => c.IsPrimaryKey = true, b => b.PrimaryKey());
}
[Test]
public void CallingNullableSetsIsNullableToTrue()
{
VerifyColumnProperty(c => c.IsNullable = true, b => b.Nullable());
}
[Test]
public void CallingNotNullableSetsIsNullableToFalse()
{
VerifyColumnProperty(c => c.IsNullable = false, b => b.NotNullable());
}
[Test]
public void CallingUniqueSetsIsUniqueToTrue()
{
VerifyColumnProperty(c => c.IsUnique = true, b => b.Unique());
}
[Test]
public void CallingUniqueAddsIndexExpressionToContext()
{
var collectionMock = new Mock<ICollection<IMigrationExpression>>();
var contextMock = new Mock<IMigrationContext>();
contextMock.Setup(x => x.Expressions).Returns(collectionMock.Object);
var columnMock = new Mock<ColumnDefinition>();
columnMock.SetupGet(x => x.Name).Returns("BaconId");
var expressionMock = new Mock<CreateColumnExpression>();
expressionMock.SetupGet(x => x.SchemaName).Returns("Eggs");
expressionMock.SetupGet(x => x.TableName).Returns("Bacon");
expressionMock.SetupGet(x => x.Column).Returns(columnMock.Object);
var builder = new CreateColumnExpressionBuilder(expressionMock.Object, contextMock.Object);
builder.Unique();
collectionMock.Verify(x => x.Add(It.Is<CreateIndexExpression>(
ix => ix.Index.Name == null
&& ix.Index.TableName == "Bacon"
&& ix.Index.SchemaName == "Eggs"
&& ix.Index.IsUnique
&& !ix.Index.IsClustered
&& ix.Index.Columns.All(c => c.Name == "BaconId")
)));
contextMock.VerifyGet(x => x.Expressions);
}
[Test]
public void CallingUniqueNamedAddsIndexExpressionToContext()
{
var collectionMock = new Mock<ICollection<IMigrationExpression>>();
var contextMock = new Mock<IMigrationContext>();
contextMock.Setup(x => x.Expressions).Returns(collectionMock.Object);
var columnMock = new Mock<ColumnDefinition>();
columnMock.SetupGet(x => x.Name).Returns("BaconId");
var expressionMock = new Mock<CreateColumnExpression>();
expressionMock.SetupGet(x => x.SchemaName).Returns("Eggs");
expressionMock.SetupGet(x => x.TableName).Returns("Bacon");
expressionMock.SetupGet(x => x.Column).Returns(columnMock.Object);
var builder = new CreateColumnExpressionBuilder(expressionMock.Object, contextMock.Object);
builder.Unique("IX_Bacon_BaconId");
collectionMock.Verify(x => x.Add(It.Is<CreateIndexExpression>(
ix => ix.Index.Name == "IX_Bacon_BaconId"
&& ix.Index.TableName == "Bacon"
&& ix.Index.SchemaName == "Eggs"
&& ix.Index.IsUnique
&& !ix.Index.IsClustered
&& ix.Index.Columns.All(c => c.Name == "BaconId")
)));
contextMock.VerifyGet(x => x.Expressions);
}
[Test]
public void CallingReferencesAddsNewForeignKeyExpressionToContext()
{
var collectionMock = new Mock<ICollection<IMigrationExpression>>();
var contextMock = new Mock<IMigrationContext>();
contextMock.Setup(x => x.Expressions).Returns(collectionMock.Object);
var columnMock = new Mock<ColumnDefinition>();
columnMock.SetupGet(x => x.Name).Returns("BaconId");
var expressionMock = new Mock<CreateColumnExpression>();
expressionMock.SetupGet(x => x.TableName).Returns("Bacon");
expressionMock.SetupGet(x => x.Column).Returns(columnMock.Object);
var builder = new CreateColumnExpressionBuilder(expressionMock.Object, contextMock.Object);
builder.References("fk_foo", "FooTable", new[] { "BarColumn" });
collectionMock.Verify(x => x.Add(It.Is<CreateForeignKeyExpression>(
fk => fk.ForeignKey.Name == "fk_foo" &&
fk.ForeignKey.ForeignTable == "FooTable" &&
fk.ForeignKey.ForeignColumns.Contains("BarColumn") &&
fk.ForeignKey.ForeignColumns.Count == 1 &&
fk.ForeignKey.PrimaryTable == "Bacon" &&
fk.ForeignKey.PrimaryColumns.Contains("BaconId") &&
fk.ForeignKey.PrimaryColumns.Count == 1
)));
contextMock.VerifyGet(x => x.Expressions);
}
[Test]
public void CallingReferencedByAddsNewForeignKeyExpressionToContext()
{
var collectionMock = new Mock<ICollection<IMigrationExpression>>();
var contextMock = new Mock<IMigrationContext>();
contextMock.Setup(x => x.Expressions).Returns(collectionMock.Object);
var columnMock = new Mock<ColumnDefinition>();
columnMock.SetupGet(x => x.Name).Returns("BaconId");
var expressionMock = new Mock<CreateColumnExpression>();
expressionMock.SetupGet(x => x.TableName).Returns("Bacon");
expressionMock.SetupGet(x => x.Column).Returns(columnMock.Object);
var builder = new CreateColumnExpressionBuilder(expressionMock.Object, contextMock.Object);
builder.ReferencedBy("fk_foo", "FooTable", "BarColumn");
collectionMock.Verify(x => x.Add(It.Is<CreateForeignKeyExpression>(
fk => fk.ForeignKey.Name == "fk_foo" &&
fk.ForeignKey.ForeignTable == "FooTable" &&
fk.ForeignKey.ForeignColumns.Contains("BarColumn") &&
fk.ForeignKey.ForeignColumns.Count == 1 &&
fk.ForeignKey.PrimaryTable == "Bacon" &&
fk.ForeignKey.PrimaryColumns.Contains("BaconId") &&
fk.ForeignKey.PrimaryColumns.Count == 1
)));
contextMock.VerifyGet(x => x.Expressions);
}
[Test]
public void CallingForeignKeyAddsNewForeignKeyExpressionToContext()
{
var collectionMock = new Mock<ICollection<IMigrationExpression>>();
var contextMock = new Mock<IMigrationContext>();
contextMock.Setup(x => x.Expressions).Returns(collectionMock.Object);
var columnMock = new Mock<ColumnDefinition>();
columnMock.SetupGet(x => x.Name).Returns("BaconId");
var expressionMock = new Mock<CreateColumnExpression>();
expressionMock.SetupGet(x => x.TableName).Returns("Bacon");
expressionMock.SetupGet(x => x.Column).Returns(columnMock.Object);
var builder = new CreateColumnExpressionBuilder(expressionMock.Object, contextMock.Object);
builder.ForeignKey("fk_foo", "FooTable", "BarColumn");
contextMock.VerifyGet(x => x.Expressions);
collectionMock.Verify(x => x.Add(It.Is<CreateForeignKeyExpression>(
fk => fk.ForeignKey.Name == "fk_foo" &&
fk.ForeignKey.PrimaryTable == "FooTable" &&
fk.ForeignKey.PrimaryColumns.Contains("BarColumn") &&
fk.ForeignKey.PrimaryColumns.Count == 1 &&
fk.ForeignKey.ForeignTable == "Bacon" &&
fk.ForeignKey.ForeignColumns.Contains("BaconId") &&
fk.ForeignKey.ForeignColumns.Count == 1
)));
}
[TestCase(Rule.Cascade), TestCase(Rule.SetDefault), TestCase(Rule.SetNull), TestCase(Rule.None)]
public void CallingOnUpdateSetsOnUpdateOnForeignKeyExpression(Rule rule)
{
var builder = new CreateColumnExpressionBuilder(null, null) {CurrentForeignKey = new ForeignKeyDefinition()};
builder.OnUpdate(rule);
Assert.That(builder.CurrentForeignKey.OnUpdate, Is.EqualTo(rule));
Assert.That(builder.CurrentForeignKey.OnDelete, Is.EqualTo(Rule.None));
}
[TestCase(Rule.Cascade), TestCase(Rule.SetDefault), TestCase(Rule.SetNull), TestCase(Rule.None)]
public void CallingOnDeleteSetsOnDeleteOnForeignKeyExpression(Rule rule)
{
var builder = new CreateColumnExpressionBuilder(null, null) { CurrentForeignKey = new ForeignKeyDefinition() };
builder.OnDelete(rule);
Assert.That(builder.CurrentForeignKey.OnUpdate, Is.EqualTo(Rule.None));
Assert.That(builder.CurrentForeignKey.OnDelete, Is.EqualTo(rule));
}
[TestCase(Rule.Cascade), TestCase(Rule.SetDefault), TestCase(Rule.SetNull), TestCase(Rule.None)]
public void CallingOnDeleteOrUpdateSetsOnUpdateAndOnDeleteOnForeignKeyExpression(Rule rule)
{
var builder = new CreateColumnExpressionBuilder(null, null) { CurrentForeignKey = new ForeignKeyDefinition() };
builder.OnDeleteOrUpdate(rule);
Assert.That(builder.CurrentForeignKey.OnUpdate, Is.EqualTo(rule));
Assert.That(builder.CurrentForeignKey.OnDelete, Is.EqualTo(rule));
}
private void VerifyColumnProperty(Action<ColumnDefinition> columnExpression, Action<CreateColumnExpressionBuilder> callToTest)
{
var columnMock = new Mock<ColumnDefinition>();
var expressionMock = new Mock<CreateColumnExpression>();
expressionMock.SetupProperty(e => e.Column);
var expression = expressionMock.Object;
expression.Column = columnMock.Object;
var contextMock = new Mock<IMigrationContext>();
contextMock.SetupGet(mc => mc.Expressions).Returns(new Collection<IMigrationExpression>());
callToTest(new CreateColumnExpressionBuilder(expression, contextMock.Object));
columnMock.VerifySet(columnExpression);
}
private void VerifyColumnDbType(DbType expected, Action<CreateColumnExpressionBuilder> callToTest)
{
var columnMock = new Mock<ColumnDefinition>();
var expressionMock = new Mock<CreateColumnExpression>();
expressionMock.SetupProperty(e => e.Column);
var expression = expressionMock.Object;
expression.Column = columnMock.Object;
var contextMock = new Mock<IMigrationContext>();
callToTest(new CreateColumnExpressionBuilder(expression, contextMock.Object));
columnMock.VerifySet(c => c.Type = expected);
}
private void VerifyColumnSize(int expected, Action<CreateColumnExpressionBuilder> callToTest)
{
var columnMock = new Mock<ColumnDefinition>();
var expressionMock = new Mock<CreateColumnExpression>();
expressionMock.SetupProperty(e => e.Column);
var expression = expressionMock.Object;
expression.Column = columnMock.Object;
var contextMock = new Mock<IMigrationContext>();
callToTest(new CreateColumnExpressionBuilder(expression, contextMock.Object));
columnMock.VerifySet(c => c.Size = expected);
}
private void VerifyColumnPrecision(int expected, Action<CreateColumnExpressionBuilder> callToTest)
{
var columnMock = new Mock<ColumnDefinition>();
var expressionMock = new Mock<CreateColumnExpression>();
expressionMock.SetupProperty(e => e.Column);
var expression = expressionMock.Object;
expression.Column = columnMock.Object;
var contextMock = new Mock<IMigrationContext>();
callToTest(new CreateColumnExpressionBuilder(expression, contextMock.Object));
columnMock.VerifySet(c => c.Precision = expected);
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.ExceptionServices;
using Microsoft.CodeAnalysis.Collections;
using Microsoft.VisualStudio.Debugger;
using Microsoft.VisualStudio.Debugger.Clr;
using Microsoft.VisualStudio.Debugger.ComponentInterfaces;
using Microsoft.VisualStudio.Debugger.Evaluation;
using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation;
using Xunit;
using System.Collections;
namespace Microsoft.CodeAnalysis.ExpressionEvaluator
{
public abstract class ResultProviderTestBase
{
private readonly IDkmClrFormatter _formatter;
private readonly IDkmClrResultProvider _resultProvider;
internal readonly DkmInspectionContext DefaultInspectionContext;
internal ResultProviderTestBase(ResultProvider resultProvider, DkmInspectionContext defaultInspectionContext)
{
_formatter = resultProvider.Formatter;
_resultProvider = resultProvider;
this.DefaultInspectionContext = defaultInspectionContext;
}
internal DkmClrValue CreateDkmClrValue(
object value,
Type type = null,
string alias = null,
DkmEvaluationResultFlags evalFlags = DkmEvaluationResultFlags.None,
DkmClrValueFlags valueFlags = DkmClrValueFlags.None)
{
if (type == null)
{
type = value.GetType();
}
return new DkmClrValue(
value,
DkmClrValue.GetHostObjectValue((TypeImpl)type, value),
new DkmClrType((TypeImpl)type),
alias,
_formatter,
evalFlags,
valueFlags);
}
internal DkmClrValue CreateDkmClrValue(
object value,
DkmClrType type,
string alias = null,
DkmEvaluationResultFlags evalFlags = DkmEvaluationResultFlags.None,
DkmClrValueFlags valueFlags = DkmClrValueFlags.None,
ulong nativeComPointer = 0)
{
return new DkmClrValue(
value,
DkmClrValue.GetHostObjectValue(type.GetLmrType(), value),
type,
alias,
_formatter,
evalFlags,
valueFlags,
nativeComPointer: nativeComPointer);
}
internal DkmClrValue CreateErrorValue(
DkmClrType type,
string message)
{
return new DkmClrValue(
value: null,
hostObjectValue: message,
type: type,
alias: null,
formatter: _formatter,
evalFlags: DkmEvaluationResultFlags.None,
valueFlags: DkmClrValueFlags.Error);
}
#region Formatter Tests
internal string FormatNull<T>(bool useHexadecimal = false)
{
return FormatValue(null, typeof(T), useHexadecimal);
}
internal string FormatValue(object value, bool useHexadecimal = false)
{
return FormatValue(value, value.GetType(), useHexadecimal);
}
internal string FormatValue(object value, Type type, bool useHexadecimal = false)
{
var clrValue = CreateDkmClrValue(value, type);
var inspectionContext = CreateDkmInspectionContext(_formatter, DkmEvaluationFlags.None, radix: useHexadecimal ? 16u : 10u);
return clrValue.GetValueString(inspectionContext, Formatter.NoFormatSpecifiers);
}
internal bool HasUnderlyingString(object value)
{
return HasUnderlyingString(value, value.GetType());
}
internal bool HasUnderlyingString(object value, Type type)
{
var clrValue = GetValueForUnderlyingString(value, type);
return clrValue.HasUnderlyingString(DefaultInspectionContext);
}
internal string GetUnderlyingString(object value)
{
var clrValue = GetValueForUnderlyingString(value, value.GetType());
return clrValue.GetUnderlyingString(DefaultInspectionContext);
}
internal DkmClrValue GetValueForUnderlyingString(object value, Type type)
{
return CreateDkmClrValue(
value,
type,
evalFlags: DkmEvaluationResultFlags.RawString);
}
#endregion
#region ResultProvider Tests
internal DkmInspectionContext CreateDkmInspectionContext(
DkmEvaluationFlags flags = DkmEvaluationFlags.None,
uint radix = 10,
DkmRuntimeInstance runtimeInstance = null)
{
return CreateDkmInspectionContext(_formatter, flags, radix, runtimeInstance);
}
internal static DkmInspectionContext CreateDkmInspectionContext(
IDkmClrFormatter formatter,
DkmEvaluationFlags flags,
uint radix,
DkmRuntimeInstance runtimeInstance = null)
{
return new DkmInspectionContext(formatter, flags, radix, runtimeInstance);
}
internal DkmEvaluationResult FormatResult(string name, DkmClrValue value, DkmClrType declaredType = null, DkmInspectionContext inspectionContext = null)
{
return FormatResult(name, name, value, declaredType, inspectionContext: inspectionContext);
}
internal DkmEvaluationResult FormatResult(string name, string fullName, DkmClrValue value, DkmClrType declaredType = null, bool[] declaredTypeInfo = null, DkmInspectionContext inspectionContext = null)
{
DkmEvaluationResult evaluationResult = null;
var workList = new DkmWorkList();
_resultProvider.GetResult(
value,
workList,
declaredType: declaredType ?? value.Type,
customTypeInfo: new DynamicFlagsCustomTypeInfo(declaredTypeInfo == null ? null : new BitArray(declaredTypeInfo)).GetCustomTypeInfo(),
inspectionContext: inspectionContext ?? DefaultInspectionContext,
formatSpecifiers: Formatter.NoFormatSpecifiers,
resultName: name,
resultFullName: null,
completionRoutine: asyncResult => evaluationResult = asyncResult.Result);
workList.Execute();
return evaluationResult;
}
internal DkmEvaluationResult[] GetChildren(DkmEvaluationResult evalResult, DkmInspectionContext inspectionContext = null)
{
DkmEvaluationResultEnumContext enumContext;
var builder = ArrayBuilder<DkmEvaluationResult>.GetInstance();
// Request 0-3 children.
int size;
DkmEvaluationResult[] items;
for (size = 0; size < 3; size++)
{
items = GetChildren(evalResult, size, inspectionContext, out enumContext);
var totalChildCount = enumContext.Count;
Assert.InRange(totalChildCount, 0, int.MaxValue);
var expectedSize = (size < totalChildCount) ? size : totalChildCount;
Assert.Equal(expectedSize, items.Length);
}
// Request items (increasing the size of the request with each iteration).
size = 1;
items = GetChildren(evalResult, size, inspectionContext, out enumContext);
while (items.Length > 0)
{
builder.AddRange(items);
Assert.True(builder.Count <= enumContext.Count);
int offset = builder.Count;
// Request 0 items.
items = GetItems(enumContext, offset, 0);
Assert.Equal(items.Length, 0);
// Request >0 items.
size++;
items = GetItems(enumContext, offset, size);
}
Assert.Equal(builder.Count, enumContext.Count);
return builder.ToArrayAndFree();
}
internal DkmEvaluationResult[] GetChildren(DkmEvaluationResult evalResult, int initialRequestSize, DkmInspectionContext inspectionContext, out DkmEvaluationResultEnumContext enumContext)
{
DkmGetChildrenAsyncResult getChildrenResult = default(DkmGetChildrenAsyncResult);
var workList = new DkmWorkList();
_resultProvider.GetChildren(evalResult, workList, initialRequestSize, inspectionContext ?? DefaultInspectionContext, r => { getChildrenResult = r; });
workList.Execute();
var exception = getChildrenResult.Exception;
if (exception != null)
{
ExceptionDispatchInfo.Capture(exception).Throw();
}
enumContext = getChildrenResult.EnumContext;
return getChildrenResult.InitialChildren;
}
internal DkmEvaluationResult[] GetItems(DkmEvaluationResultEnumContext enumContext, int startIndex, int count)
{
DkmEvaluationEnumAsyncResult getItemsResult = default(DkmEvaluationEnumAsyncResult);
var workList = new DkmWorkList();
_resultProvider.GetItems(enumContext, workList, startIndex, count, r => { getItemsResult = r; });
workList.Execute();
var exception = getItemsResult.Exception;
if (exception != null)
{
ExceptionDispatchInfo.Capture(exception).Throw();
}
return getItemsResult.Items;
}
private const DkmEvaluationResultCategory UnspecifiedCategory = (DkmEvaluationResultCategory)(-1);
private const DkmEvaluationResultAccessType UnspecifiedAccessType = (DkmEvaluationResultAccessType)(-1);
internal static DkmEvaluationResult EvalResult(
string name,
string value,
string type,
string fullName,
DkmEvaluationResultFlags flags = DkmEvaluationResultFlags.None,
DkmEvaluationResultCategory category = UnspecifiedCategory,
DkmEvaluationResultAccessType access = UnspecifiedAccessType,
string editableValue = null,
DkmCustomUIVisualizerInfo[] customUIVisualizerInfo = null)
{
return DkmSuccessEvaluationResult.Create(
null,
null,
name,
fullName,
flags,
value,
editableValue,
type,
category,
access,
default(DkmEvaluationResultStorageType),
default(DkmEvaluationResultTypeModifierFlags),
null,
(customUIVisualizerInfo != null) ? new ReadOnlyCollection<DkmCustomUIVisualizerInfo>(customUIVisualizerInfo) : null,
null,
null);
}
internal static DkmIntermediateEvaluationResult EvalIntermediateResult(
string name,
string fullName,
string expression,
DkmLanguage language)
{
return DkmIntermediateEvaluationResult.Create(
InspectionContext: null,
StackFrame: null,
Name: name,
FullName: fullName,
Expression: expression,
IntermediateLanguage: language,
TargetRuntime: null,
DataItem: null);
}
internal static DkmEvaluationResult EvalFailedResult(
string name,
string message,
string type = null,
string fullName = null,
DkmEvaluationResultFlags flags = DkmEvaluationResultFlags.None)
{
return DkmFailedEvaluationResult.Create(
null,
null,
name,
fullName,
message,
flags,
type,
null);
}
internal static void Verify(IReadOnlyList<DkmEvaluationResult> actual, params DkmEvaluationResult[] expected)
{
try
{
int n = actual.Count;
Assert.Equal(expected.Length, n);
for (int i = 0; i < n; i++)
{
Verify(actual[i], expected[i]);
}
}
catch
{
foreach (var result in actual)
{
Console.WriteLine("{0}, ", ToString(result));
}
throw;
}
}
private static string ToString(DkmEvaluationResult result)
{
var success = result as DkmSuccessEvaluationResult;
return (success != null) ? ToString(success) : ToString((DkmFailedEvaluationResult)result);
}
private static string ToString(DkmSuccessEvaluationResult result)
{
var pooledBuilder = PooledStringBuilder.GetInstance();
var builder = pooledBuilder.Builder;
builder.Append("EvalResult(");
builder.Append(Quote(result.Name));
builder.Append(", ");
builder.Append((result.Value == null) ? "null" : Quote(Escape(result.Value)));
builder.Append(", ");
builder.Append(Quote(result.Type));
builder.Append(", ");
builder.Append((result.FullName != null) ? Quote(Escape(result.FullName)) : "null");
if (result.Flags != DkmEvaluationResultFlags.None)
{
builder.Append(", ");
builder.Append(FormatEnumValue(result.Flags));
}
if (result.Category != DkmEvaluationResultCategory.Other)
{
builder.Append(", ");
builder.Append(FormatEnumValue(result.Category));
}
if (result.Access != DkmEvaluationResultAccessType.None)
{
builder.Append(", ");
builder.Append(FormatEnumValue(result.Access));
}
if (result.EditableValue != null)
{
builder.Append(", ");
builder.Append(Quote(result.EditableValue));
}
builder.Append(")");
return pooledBuilder.ToStringAndFree();
}
private static string ToString(DkmFailedEvaluationResult result)
{
var pooledBuilder = PooledStringBuilder.GetInstance();
var builder = pooledBuilder.Builder;
builder.Append("EvalFailedResult(");
builder.Append(Quote(result.Name));
builder.Append(", ");
builder.Append(Quote(result.ErrorMessage));
if (result.Type != null)
{
builder.Append(", ");
builder.Append(Quote(result.Type));
}
if (result.FullName != null)
{
builder.Append(", ");
builder.Append(Quote(Escape(result.FullName)));
}
if (result.Flags != DkmEvaluationResultFlags.None)
{
builder.Append(", ");
builder.Append(FormatEnumValue(result.Flags));
}
builder.Append(")");
return pooledBuilder.ToStringAndFree();
}
private static string Escape(string str)
{
return str.Replace("\"", "\\\"");
}
private static string Quote(string str)
{
return '"' + str + '"';
}
private static string FormatEnumValue(Enum e)
{
var parts = e.ToString().Split(new[] { ", " }, StringSplitOptions.RemoveEmptyEntries);
var enumTypeName = e.GetType().Name;
return string.Join(" | ", parts.Select(p => enumTypeName + "." + p));
}
internal static void Verify(DkmEvaluationResult actual, DkmEvaluationResult expected)
{
Assert.Equal(expected.Name, actual.Name);
Assert.Equal(expected.FullName, actual.FullName);
var expectedSuccess = expected as DkmSuccessEvaluationResult;
var expectedIntermediate = expected as DkmIntermediateEvaluationResult;
if (expectedSuccess != null)
{
var actualSuccess = (DkmSuccessEvaluationResult)actual;
Assert.Equal(expectedSuccess.Value, actualSuccess.Value);
Assert.Equal(expectedSuccess.Type, actualSuccess.Type);
Assert.Equal(expectedSuccess.Flags, actualSuccess.Flags);
if (expectedSuccess.Category != UnspecifiedCategory)
{
Assert.Equal(expectedSuccess.Category, actualSuccess.Category);
}
if (expectedSuccess.Access != UnspecifiedAccessType)
{
Assert.Equal(expectedSuccess.Access, actualSuccess.Access);
}
Assert.Equal(expectedSuccess.EditableValue, actualSuccess.EditableValue);
Assert.True(
(expectedSuccess.CustomUIVisualizers == actualSuccess.CustomUIVisualizers) ||
(expectedSuccess.CustomUIVisualizers != null && actualSuccess.CustomUIVisualizers != null &&
expectedSuccess.CustomUIVisualizers.SequenceEqual(actualSuccess.CustomUIVisualizers, CustomUIVisualizerInfoComparer.Instance)));
}
else if (expectedIntermediate != null)
{
var actualIntermediate = (DkmIntermediateEvaluationResult)actual;
Assert.Equal(expectedIntermediate.Expression, actualIntermediate.Expression);
Assert.Equal(expectedIntermediate.IntermediateLanguage.Id.LanguageId, actualIntermediate.IntermediateLanguage.Id.LanguageId);
Assert.Equal(expectedIntermediate.IntermediateLanguage.Id.VendorId, actualIntermediate.IntermediateLanguage.Id.VendorId);
}
else
{
var actualFailed = (DkmFailedEvaluationResult)actual;
var expectedFailed = (DkmFailedEvaluationResult)expected;
Assert.Equal(expectedFailed.ErrorMessage, actualFailed.ErrorMessage);
Assert.Equal(expectedFailed.Type, actualFailed.Type);
Assert.Equal(expectedFailed.Flags, actualFailed.Flags);
}
}
#endregion
private sealed class CustomUIVisualizerInfoComparer : IEqualityComparer<DkmCustomUIVisualizerInfo>
{
internal static readonly CustomUIVisualizerInfoComparer Instance = new CustomUIVisualizerInfoComparer();
bool IEqualityComparer<DkmCustomUIVisualizerInfo>.Equals(DkmCustomUIVisualizerInfo x, DkmCustomUIVisualizerInfo y)
{
return x == y ||
(x != null && y != null &&
x.Id == y.Id &&
x.MenuName == y.MenuName &&
x.Description == y.Description &&
x.Metric == y.Metric &&
x.UISideVisualizerTypeName == y.UISideVisualizerTypeName &&
x.UISideVisualizerAssemblyName == y.UISideVisualizerAssemblyName &&
x.UISideVisualizerAssemblyLocation == y.UISideVisualizerAssemblyLocation &&
x.DebuggeeSideVisualizerTypeName == y.DebuggeeSideVisualizerTypeName &&
x.DebuggeeSideVisualizerAssemblyName == y.DebuggeeSideVisualizerAssemblyName);
}
int IEqualityComparer<DkmCustomUIVisualizerInfo>.GetHashCode(DkmCustomUIVisualizerInfo obj)
{
throw new NotImplementedException();
}
}
internal static DynamicFlagsCustomTypeInfo MakeDynamicFlagsCustomTypeInfo(params bool[] dynamicFlags)
{
return new DynamicFlagsCustomTypeInfo(dynamicFlags == null ? null : new BitArray(dynamicFlags));
}
}
}
| |
#region WatiN Copyright (C) 2006-2011 Jeroen van Menen
//Copyright 2006-2011 Jeroen van Menen
//
// 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 Copyright
using System;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Threading;
using System.Web;
using NUnit.Framework;
using NUnit.Framework.SyntaxHelpers;
using SHDocVw;
using WatiN.Core.Constraints;
using WatiN.Core.DialogHandlers;
using WatiN.Core.Exceptions;
using WatiN.Core.Native.InternetExplorer;
using WatiN.Core.Logging;
using WatiN.Core.UnitTests.TestUtils;
namespace WatiN.Core.UnitTests.IETests
{
[TestFixture]
public class IeTests : BaseWatiNTest
{
[TestFixtureSetUp]
public override void FixtureSetup()
{
base.FixtureSetup();
Logger.LogWriter = new DebugLogWriter();
}
[SetUp]
public void SetUp()
{
Settings.Reset();
}
[Test]
public void TestRunnerApartmentStateMustBeSTA()
{
Assert.IsTrue(Thread.CurrentThread.GetApartmentState() == ApartmentState.STA);
}
[Test]
public void ShouldBeAbleToGetTheMetaTags()
{
// GIVEN
using (var browser = new IE(MainURI))
{
// WHEN
var metaTags = browser.ElementsWithTag("meta");
// THEN
Assert.That(metaTags.Count, Is.EqualTo(1));
}
}
[Test]
public void CheckIEIsInheritingProperTypes()
{
using (var ie = new IE())
{
Assert.IsInstanceOfType(typeof (IE), ie, "Should be an IE instance");
Assert.IsInstanceOfType(typeof (Browser), ie, "Should be a Browser instance");
Assert.IsInstanceOfType(typeof (DomContainer), ie, "Should be a DomContainer instance");
}
}
[Test, Category("InternetConnectionNeeded")]
public void GoogleSearchWithEncodedQueryStringInConstructor()
{
var url = string.Format("http://www.google.com/search?q={0}", HttpUtility.UrlEncode("a+b"));
using (var ie = new IE(url))
{
Assert.That(ie.TextField(Find.ByName("q")).Value, Is.EqualTo("a+b"));
}
}
[Test, Ignore("Second assert fails in nunit console mode.")]
public void PressTabAndActiveElement()
{
using (var ie = new IE(MainURI))
{
ie.TextField("name").Focus();
var element = ie.ActiveElement;
Assert.AreEqual("name", element.Id);
ie.PressTab();
element = ie.ActiveElement;
Assert.AreEqual("popupid", element.Id);
}
}
[Test, Category("InternetConnectionNeeded")]
public void AddProtocolToUrlIfOmmitted()
{
using (var ie = new IE("www.google.com"))
{
Assert.That(ie.Url, Text.StartsWith("http://"));
}
}
[Test]
public void NewIeInstanceShouldTake_Settings_MakeNewIeInstanceVisible_IntoAccount()
{
Settings.MakeNewIeInstanceVisible = true;
Assert.That(Settings.MakeNewIeInstanceVisible, "Default should be true");
using (var ie = new IE())
{
Assert.That(((IWebBrowser2)ie.InternetExplorer).Visible, "IE Should be visible");
}
Settings.MakeNewIeInstanceVisible = false;
Assert.That(Settings.MakeNewIeInstanceVisible, Is.EqualTo(false), "should be false");
using (var ie = new IE())
{
Assert.That(((IWebBrowser2)ie.InternetExplorer).Visible, Is.EqualTo(false), "IE Should be visible");
}
}
// TODO: move to BrowserTests when HTMLDialogs are supported by FireFox
[Test]
public void DocumentShouldBeDisposedSoHTMLDialogGetsDisposedAndReferenceCountIsOK()
{
DialogWatcher dialogWatcher;
int ReferenceCount;
using (var ie = new IE(MainURI))
{
ReferenceCount = ie.DialogWatcher.ReferenceCount;
ie.Button("popupid").Click();
Thread.Sleep(100);
using (Document document = ie.HtmlDialog(Find.ByIndex(0)))
{
Assert.AreEqual(ReferenceCount + 1, ie.DialogWatcher.ReferenceCount, "DialogWatcher reference count");
}
dialogWatcher = ie.DialogWatcher;
}
Assert.AreEqual(ReferenceCount - 1, dialogWatcher.ReferenceCount, "DialogWatcher reference count should be zero after test");
}
[Test]
public void NewIEWithUrlAndLogonDialogHandler()
{
FailIfIEWindowExists("main", "NewIEWithUrlAndLogonDialogHandler");
var url = MainURI.AbsoluteUri;
var logon = new LogonDialogHandler("y", "z");
using (var ie = new IE(url, logon))
{
Assert.AreEqual(MainURI, new Uri(ie.Url));
Assert.IsTrue(ie.DialogWatcher.Contains(logon));
Assert.AreEqual(1, ie.DialogWatcher.Count);
using (var ie1 = new IE(url, logon))
{
Assert.AreEqual(MainURI, new Uri(ie1.Url));
Assert.IsTrue(ie.DialogWatcher.Contains(logon));
Assert.AreEqual(1, ie.DialogWatcher.Count);
}
}
Assert.IsFalse(IsIEWindowOpen("main"), "Internet Explorer should be closed by IE.Dispose");
}
[Test]
public void NewIEInSameProcess()
{
using (var ie1 = new IE())
{
using (var ie2 = new IE())
{
Assert.AreEqual(ie1.ProcessID, ie2.ProcessID);
}
}
}
[Test]
public void NewIEInNewProcess()
{
using (var ie1 = new IE())
{
using (var ie2 = new IE(true))
{
Assert.IsNotNull(ie2, "create ie in new process returned null");
Assert.AreNotEqual(ie1.ProcessID, ie2.ProcessID, "process id problem");
}
}
}
[Test]
public void NewIEWithoutUrlShouldStartAtAboutBlank()
{
using (var ie = new IE())
{
Assert.AreEqual("about:blank", ie.Url);
}
}
[Test]
public void NewIEWithUri()
{
using (var ie = new IE(MainURI))
{
Assert.AreEqual(MainURI, new Uri(ie.Url));
}
}
[Test]
public void NewIEWithUriShouldAutoClose()
{
FailIfIEWindowExists("main", "NewIEWithUriShouldAutoClose");
using (new IE(MainURI)) {}
Assert.IsFalse(IsIEWindowOpen("main"), "Internet Explorer should be closed by IE.Dispose");
}
[Test]
public void NewIEWithUriNotAutoClose()
{
FailIfIEWindowExists("main", "NewIEWithUriNotAutoClose");
using (var ie = new IE(MainURI))
{
Assert.IsTrue(ie.AutoClose);
ie.AutoClose = false;
}
Assert.IsTrue(IsIEWindowOpen("main"), "Internet Explorer should NOT be closed by IE.Dispose");
Browser.AttachTo<IE>(Find.ByTitle("main"), 3).Close();
}
[Test]
public void NewIEWithUrl()
{
FailIfIEWindowExists("main", "NewIEWithUrl");
var url = MainURI.AbsoluteUri;
using (var ie = new IE(url))
{
Assert.AreEqual(MainURI, new Uri(ie.Url));
Assert.AreEqual(0, ie.DialogWatcher.Count, "DialogWatcher count should be zero");
}
Assert.IsFalse(IsIEWindowOpen("main"), "Internet Explorer should be closed by IE.Dispose");
}
// TODO: Should this also become a multi browser test?
// Logon dialog not currently supported by FireFox implementation
[Test]
public void ReopenWithUrlAndLogonDialogHandlerInNewProcess()
{
FailIfIEWindowExists("main", "ReopenWithUrlAndLogonDialogHandler");
var logon = new LogonDialogHandler("y", "z");
using (var ie1 = new IE())
{
using (var ie2 = new IE())
{
Assert.AreEqual(ie1.ProcessID, ie2.ProcessID, "process id problem");
Assert.AreEqual("about:blank", ie2.Url);
var oldIEObj = ie2.InternetExplorer;
ie2.Reopen(MainURI, logon, true);
Assert.AreNotSame(oldIEObj, ie2.InternetExplorer, "Reopen should create a new browser.");
Assert.AreNotEqual(ie1.ProcessID, ie2.ProcessID, "process id problem");
Assert.AreEqual(MainURI, new Uri(ie2.Url));
Assert.IsTrue(ie2.DialogWatcher.Contains(logon));
Assert.AreEqual(1, ie2.DialogWatcher.Count);
}
}
Assert.IsFalse(IsIEWindowOpen("main"), "Internet Explorer should be closed by IE.Dispose");
}
[Test]
public void Should_set_and_get_cookies()
{
using (var ie = new IE())
{
// Clear all cookies.
ie.ClearCookies();
// Ensure our test cookies don't exist from a previous run.
Assert.IsNull(ie.GetCookie("http://1.watin.com/", "test-cookie"));
Assert.IsNull(ie.GetCookie("http://2.watin.com/", "test-cookie"));
// Create cookies for a pair of domains.
ie.SetCookie("http://1.watin.com/", "test-cookie=abc; expires=Wed, 01-Jan-2020 00:00:00 GMT");
Assert.AreEqual("test-cookie=abc", ie.GetCookie("http://1.watin.com/", "test-cookie"));
ie.SetCookie("http://2.watin.com/", "test-cookie=def; expires=Wed, 01-Jan-2020 00:00:00 GMT");
Assert.AreEqual("test-cookie=def", ie.GetCookie("http://2.watin.com/", "test-cookie"));
CookieCollection collection = ie.GetCookiesForUrl(new Uri("http://2.watin.com/"));
Assert.AreEqual(1, collection.Count);
Assert.AreEqual(collection[0].Name, "test-cookie");
Assert.AreEqual(collection[0].Value, "def");
}
}
[Test]
public void Should_clear_cookies()
{
using (var ie = new IE())
{
// Clear all cookies.
ie.ClearCookies();
// Ensure our test cookies don't exist from a previous run.
Assert.IsNull(ie.GetCookie("http://1.watin.com/", "test-cookie"), "Expected no cookies for 1.watin.com");
Assert.IsNull(ie.GetCookie("http://2.watin.com/", "test-cookie"), "Expected no cookies for 2.watin.com");
// Create cookies for a pair of domains.
ie.SetCookie("http://1.watin.com/", "test-cookie=abc; expires=Wed, 01-Jan-2020 00:00:00 GMT");
ie.SetCookie("http://2.watin.com/", "test-cookie=def; expires=Wed, 01-Jan-2020 00:00:00 GMT");
// Clear cookies under one subdomain.
ie.ClearCookies("http://1.watin.com/");
// Ensure just the cookie of the first subdomain was deleted.
Assert.IsNull(ie.GetCookie("http://1.watin.com/", "test-cookie"), "Expected no cookies for 1.watin.com after clear");
Assert.AreEqual("test-cookie=def", ie.GetCookie("http://2.watin.com/", "test-cookie"), "Expected cookie for 2.watin.com");
// Clear cookies under master domain.
ie.ClearCookies("http://watin.com/");
// Ensure the second subdomain's cookie was deleted this time.
Assert.IsNull(ie.GetCookie("http://2.watin.com/", "test-cookie"), "Expected no cookies for 2.watin.com after ClearCookies");
}
}
[Test, Ignore("Experiencing problems. Test fails and following tests also fail. Need to look into it")]
public void ClearCache()
{
using (var ie = new IE(GoogleUrl))
{
// Testing cache clearing directly is a little difficult because we cannot
// easily enumerate its contents without using system APIs.
// We could create a sample page that includes a nonce but says it's cacheable
// forever. Then we should only observe the change on refresh or cache clearing.
// Fortunately Google has already done it for us.
// Save the original page html.
var oldHtml = GetHtmlSource(ie);
// If we navigate to the page again, we should see identical Html.
ie.GoTo(GoogleUrl);
Assert.AreEqual(oldHtml, GetHtmlSource(ie), "HTML should be identical when pulling from the cache.");
// But after clearing the cache, things are different.
ie.ClearCache();
ie.GoTo(GoogleUrl);
Assert.AreNotEqual(oldHtml, GetHtmlSource(ie), "HTML should differ after cache has been cleared.");
}
}
private static string GetHtmlSource(Document ie)
{
var document = ((IEDocument)ie.NativeDocument).HtmlDocument;
return document.body.parentElement.outerHTML;
}
[Test]
public void IEExistsByHWND()
{
var hwnd = "0";
Assert.IsFalse(Browser.Exists<IE>(Find.By("hwnd", hwnd)), "hwnd = 0 should not be found");
using (var ie = new IE(MainURI))
{
hwnd = ie.hWnd.ToString();
Assert.IsTrue(Browser.Exists<IE>(Find.By("hwnd", hwnd)), "hwnd of ie instance should be found");
}
Assert.IsFalse(Browser.Exists<IE>(Find.By("hwnd", hwnd)), "hwnd of closed ie instance should not be found");
}
[Test]
public void IEExistsByUrl()
{
IEExistsAsserts(Find.ByUrl(MainURI));
}
[Test]
public void IEExistsByTitle()
{
IEExistsAsserts(Find.ByTitle("Ai"));
}
private static void IEExistsAsserts(Constraint findByUrl)
{
Assert.IsFalse(Browser.Exists<IE>(findByUrl));
using (new IE(MainURI))
{
Assert.IsTrue(Browser.Exists<IE>(findByUrl));
}
Assert.IsFalse(Browser.Exists<IE>(findByUrl));
}
/// <summary>
/// Attaches to IE with a zero timeout interval. Allthough the timeout
/// interval is zero the existing IE instance should be found.
/// </summary>
[Test]
public void AttachToIEWithZeroTimeout()
{
// Create a new IE instance so we can find it.
using (new IE(MainURI))
{
var startTime = DateTime.Now;
using (Browser.AttachTo<IE>(Find.ByUrl(MainURI), 0))
{
// Should return (within 1 second).
Assert.Greater(1, DateTime.Now.Subtract(startTime).TotalSeconds);
}
}
}
[Test, ExpectedException(typeof (ArgumentOutOfRangeException))]
public void AttachToIEWithNegativeTimeoutNotAllowed()
{
Browser.AttachTo<IE>(Find.ByTitle("Bogus title"), -1);
}
[Test]
public void AttachToIEByPartialTitle()
{
FailIfIEWindowExists("Ai", "AttachToIEByPartialTitle");
using (new IE(MainURI))
{
using (var ieMainByTitle = IE.AttachTo<IE>(Find.ByTitle("Ai")))
{
Assert.AreEqual(MainURI, ieMainByTitle.Uri);
}
}
}
[Test]
public void AttachToIEByUrl()
{
FailIfIEWindowExists("Ai", "AttachToIEByUrl");
using (new IE(MainURI))
{
using (var ieMainByUri = Browser.AttachTo<IE>(Find.ByUrl(MainURI)))
{
Assert.AreEqual(MainURI, ieMainByUri.Uri);
}
}
}
[Test]
public void NewIEClosedByDispose()
{
FailIfIEWindowExists("main", "IEClosedByDispose");
using (new IE(MainURI))
{
using (var ie = Browser.AttachTo<IE>(Find.ByTitle("main")))
{
Assert.AreEqual(MainURI, new Uri(ie.Url));
}
}
Assert.IsFalse(IsIEWindowOpen("main"), "Internet Explorer not closed by IE.Dispose");
}
[Test]
public void IENotFoundException()
{
var startTime = DateTime.Now;
const int timeoutTime = 5;
const string ieTitle = "Non Existing IE Title";
const string expectedMessage = "Could not find an IE window matching constraint: Attribute 'title' contains 'Non Existing IE Title' ignoring case. Search expired after '5' seconds.";
try
{
// Time out after timeoutTime seconds
startTime = DateTime.Now;
using (Browser.AttachTo<IE>(Find.ByTitle(ieTitle), timeoutTime)) {}
Assert.Fail(string.Format("Internet Explorer with title '{0}' should not be found", ieTitle));
}
catch (Exception e)
{
Assert.IsInstanceOfType(typeof (BrowserNotFoundException), e);
// add 1 second to give it some slack.
Assert.Greater(timeoutTime + 1, DateTime.Now.Subtract(startTime).TotalSeconds);
Logger.LogDebug(e.Message);
Assert.AreEqual(expectedMessage, e.Message, "Unexpected exception message");
}
}
[Test]
public void NewUriAboutBlank()
{
Assert.AreEqual("about:blank", AboutBlank.AbsoluteUri);
}
[Test]
public void CallingIEDisposeAfterIECloseShouldNotThrowAnExeption()
{
var ie = new IE();
ie.Close();
ie.Dispose();
}
[Test, ExpectedException(typeof (ObjectDisposedException))]
public void CallingIEForceCloseAfterIECloseShouldThrowAnExeption()
{
var ie = new IE();
ie.Close();
ie.ForceClose();
}
/// <summary>
/// This test addresses a problem in the IE collection where Windows Explorer
/// windows may get included in the list of shell windows which is a bit
/// problematic for methods like ForceClose since the test will timeout.
/// </summary>
[Test, Ignore("Explorer window not killed, resulting in a lot of open windows on build machine")]
public void IECollectionExcludesWindowsExplorerWindows()
{
// Bring up an Explorer window and wait for it to become visible.
var info = new ProcessStartInfo("explorer.exe") {UseShellExecute = false, CreateNoWindow = true};
var p = Process.Start(info);
try
{
Thread.Sleep(2000);
// Create an IE window so we know there's at least one of them.
new IE();
// Iterate over internet explorer windows.
// Previously this would pick up a reference to the Windows Explorer
// window which would timeout while waiting for the main document to
// become available.
Assert.GreaterOrEqual(IE.InternetExplorers().Count, 1);
foreach (var ie in IE.InternetExplorers())
ie.Close();
}
finally
{
if (p != null)
if (! p.HasExited)
p.Kill();
}
}
private static void FailIfIEWindowExists(string partialTitle, string testName)
{
if (IsIEWindowOpen(partialTitle))
{
Assert.Fail(string.Format("An Internet Explorer with '{0}' in it's title already exists. Test '{1}' can't be correctly tested. Close all IE windows and run this test again.", partialTitle, testName));
}
}
private static bool IsIEWindowOpen(string partialTitle)
{
// Give windows some time to do work before checking
Thread.Sleep(1000);
return Browser.Exists<IE>(Find.ByTitle(partialTitle));
}
[Test]
public void TestWatiNWithInjectedHTMLCode()
{
var html = "<HTML><input name=txtSomething><input type=button name=btnSomething value=Click></HTML>";
using(var ie = new IE())
{
var document = ((IEDocument)ie.NativeDocument).HtmlDocument;
document.writeln(html);
Assert.That(ie.Button(Find.ByName("btnSomething")).Exists);
}
}
[Test]
public void ProcessShouldBe_iexplore()
{
// GIVEN
using(var ie = new IE())
{
var processId = ie.ProcessID;
// WHEN
var process = Process.GetProcessById(processId);
// THEN
Assert.That(process.ProcessName, Text.Contains("iexplore"));
}
}
[Test, Category("IE8 and later"), Category("InternetConnectionNeeded")]
public void SettingNoMerge()
{
if (IE.GetMajorIEVersion() != 8) return;
// GIVEN
Settings.MakeNewIe8InstanceNoMerge = true;
// url put up by MSDN blogger, may need to add this to our files
const string testUrl = "http://www.enhanceie.com/test/sessions/";
using (var ie1 = new IE(testUrl))
{
ie1.SelectList(Find.ById("selColor")).Select("Green");
// WHEN
using (var ie2 = new IE(testUrl))
{
// THEN
var actual = ie2.Div(Find.ById("divSessStore")).InnerHtml;
StringAssert.Contains("undefined",actual,"session cookie used");
}
}
}
[Test, Ignore("Currently attaching to IE which shows PDF in Acrobat Reader is not supported")]
public void Should_find_browser_with_opened_pdf_document()
{
// GIVEN
using (var ie = new IE(@"C:\Development\watin\trunk\src\UnitTests\html\WatiN.pdf"))
{
// var ie1 = IE.AttachToIENoWait(Find.ByTitle("watin.pdf"));
Assert.That(Browser.Exists<IE>(Find.Any));
}
// WHEN
// THEN
}
[Test]
public void Should_have_dialogwatcher_set_when_instantiated_by_calling_IntenetExplorers()
{
// GIVEN
using(var ie1 = new IE())
using(var ie2 = new IE())
{
// WHEN
var internetExplorers = IE.InternetExplorers();
// THEN
Assert.That(internetExplorers.All(browser => browser.DialogWatcher != null));
}
}
}
}
| |
using System.Linq;
using Content.Server.Atmos;
using Content.Server.Atmos.EntitySystems;
using Content.Server.Disposal.Tube.Components;
using Content.Server.Disposal.Tube;
using Content.Server.Disposal.Unit.Components;
using JetBrains.Annotations;
using Robust.Shared.Containers;
using Robust.Shared.GameObjects;
using Robust.Shared.IoC;
using Robust.Shared.Map;
using Robust.Shared.Log;
using Robust.Shared.Maths;
using Robust.Shared.Physics;
namespace Content.Server.Disposal.Unit.EntitySystems
{
[UsedImplicitly]
internal sealed class DisposableSystem : EntitySystem
{
[Dependency] private readonly IMapManager _mapManager = default!;
[Dependency] private readonly DisposalUnitSystem _disposalUnitSystem = default!;
[Dependency] private readonly DisposalTubeSystem _disposalTubeSystem = default!;
public void ExitDisposals(EntityUid uid, DisposalHolderComponent? holder = null, TransformComponent? holderTransform = null)
{
if (!Resolve(uid, ref holder, ref holderTransform))
return;
if (holder.IsExitingDisposals)
{
Logger.ErrorS("c.s.disposal.holder", "Tried exiting disposals twice. This should never happen.");
return;
}
holder.IsExitingDisposals = true;
// Check for a disposal unit to throw them into and then eject them from it.
// *This ejection also makes the target not collide with the unit.*
// *This is on purpose.*
var grid = _mapManager.GetGrid(holderTransform.GridID);
var gridTileContents = grid.GetLocal(holderTransform.Coordinates);
DisposalUnitComponent? duc = null;
foreach (var contentUid in gridTileContents)
{
if (EntityManager.TryGetComponent(contentUid, out duc))
break;
}
foreach (var entity in holder.Container.ContainedEntities.ToArray())
{
if (HasComp<BeingDisposedComponent>(entity))
RemComp <BeingDisposedComponent>(entity);
if (EntityManager.TryGetComponent(entity, out IPhysBody? physics))
{
physics.CanCollide = true;
}
holder.Container.ForceRemove(entity);
if (EntityManager.GetComponent<TransformComponent>(entity).Parent == holderTransform)
{
if (duc != null)
{
// Insert into disposal unit
EntityManager.GetComponent<TransformComponent>(entity).Coordinates = new EntityCoordinates((duc).Owner, Vector2.Zero);
duc.Container.Insert(entity);
}
else
{
EntityManager.GetComponent<TransformComponent>(entity).AttachParentToContainerOrGrid();
}
}
}
if (duc != null)
{
_disposalUnitSystem.TryEjectContents(duc);
}
var atmosphereSystem = EntitySystem.Get<AtmosphereSystem>();
if (atmosphereSystem.GetTileMixture(holderTransform.Coordinates, true) is {} environment)
{
atmosphereSystem.Merge(environment, holder.Air);
holder.Air.Clear();
}
EntityManager.DeleteEntity(uid);
}
// Note: This function will cause an ExitDisposals on any failure that does not make an ExitDisposals impossible.
public bool EnterTube(EntityUid holderUid, EntityUid toUid, DisposalHolderComponent? holder = null, TransformComponent? holderTransform = null, IDisposalTubeComponent? to = null, TransformComponent? toTransform = null)
{
if (!Resolve(holderUid, ref holder, ref holderTransform))
return false;
if (holder.IsExitingDisposals)
{
Logger.ErrorS("c.s.disposal.holder", "Tried entering tube after exiting disposals. This should never happen.");
return false;
}
if (!Resolve(toUid, ref to, ref toTransform))
{
ExitDisposals(holderUid, holder, holderTransform);
return false;
}
foreach (var ent in holder.Container.ContainedEntities)
{
var comp = EnsureComp<BeingDisposedComponent>(ent);
comp.Holder = holder.Owner;
}
// Insert into next tube
holderTransform.Coordinates = new EntityCoordinates(toUid, Vector2.Zero);
if (!to.Contents.Insert(holder.Owner))
{
ExitDisposals(holderUid, holder, holderTransform);
return false;
}
if (holder.CurrentTube != null)
{
holder.PreviousTube = holder.CurrentTube;
holder.PreviousDirection = holder.CurrentDirection;
}
holderTransform.Coordinates = toTransform.Coordinates;
holder.CurrentTube = to;
holder.CurrentDirection = to.NextDirection(holder);
holder.StartingTime = 0.1f;
holder.TimeLeft = 0.1f;
// Logger.InfoS("c.s.disposal.holder", $"Disposals dir {holder.CurrentDirection}");
// Invalid direction = exit now!
if (holder.CurrentDirection == Direction.Invalid)
{
ExitDisposals(holderUid, holder, holderTransform);
return false;
}
return true;
}
public override void Update(float frameTime)
{
foreach (var comp in EntityManager.EntityQuery<DisposalHolderComponent>())
{
UpdateComp(comp, frameTime);
}
}
private void UpdateComp(DisposalHolderComponent holder, float frameTime)
{
while (frameTime > 0)
{
var time = frameTime;
if (time > holder.TimeLeft)
{
time = holder.TimeLeft;
}
holder.TimeLeft -= time;
frameTime -= time;
var currentTube = holder.CurrentTube;
if (currentTube == null || currentTube.Deleted)
{
ExitDisposals((holder).Owner);
break;
}
if (holder.TimeLeft > 0)
{
var progress = 1 - holder.TimeLeft / holder.StartingTime;
var origin = EntityManager.GetComponent<TransformComponent>(currentTube.Owner).Coordinates;
var destination = holder.CurrentDirection.ToVec();
var newPosition = destination * progress;
EntityManager.GetComponent<TransformComponent>(holder.Owner).Coordinates = origin.Offset(newPosition);
continue;
}
// Past this point, we are performing inter-tube transfer!
// Remove current tube content
currentTube.Contents.ForceRemove(holder.Owner);
// Find next tube
var nextTube = _disposalTubeSystem.NextTubeFor(currentTube.Owner, holder.CurrentDirection);
if (nextTube == null || nextTube.Deleted)
{
ExitDisposals((holder).Owner);
break;
}
// Perform remainder of entry process
if (!EnterTube((holder).Owner, nextTube.Owner, holder, null, nextTube, null))
{
break;
}
}
}
}
}
| |
/*
* REST API Documentation for the MOTI Hired Equipment Tracking System (HETS) Application
*
* The Hired Equipment Program is for owners/operators who have a dump truck, bulldozer, backhoe or other piece of equipment they want to hire out to the transportation ministry for day labour and emergency projects. The Hired Equipment Program distributes available work to local equipment owners. The program is based on seniority and is designed to deliver work to registered users fairly and efficiently through the development of local area call-out lists.
*
* OpenAPI spec version: v1
*
*
*/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using HETSAPI.Models;
using HETSAPI.ViewModels;
namespace HETSAPI.Services.Impl
{
/// <summary>
///
/// </summary>
public class OwnerService : IOwnerService
{
private readonly DbAppContext _context;
/// <summary>
/// Create a service and set the database context
/// </summary>
public OwnerService(DbAppContext context)
{
_context = context;
}
/// <summary>
///
/// </summary>
/// <param name="items"></param>
/// <response code="201">Owner created</response>
public virtual IActionResult OwnersBulkPostAsync(Owner[] items)
{
var result = "";
return new ObjectResult(result);
}
/// <summary>
///
/// </summary>
/// <response code="200">OK</response>
public virtual IActionResult OwnersGetAsync()
{
var result = "";
return new ObjectResult(result);
}
/// <summary>
///
/// </summary>
/// <remarks>Returns attachments for a particular Owner</remarks>
/// <param name="id">id of Owner to fetch attachments for</param>
/// <response code="200">OK</response>
/// <response code="404">Owner not found</response>
public virtual IActionResult OwnersIdAttachmentsGetAsync(int id)
{
var result = "";
return new ObjectResult(result);
}
/// <summary>
///
/// </summary>
/// <remarks>Gets an Owner's Contacts</remarks>
/// <param name="id">id of Owner to fetch Contacts for</param>
/// <response code="200">OK</response>
public virtual IActionResult OwnersIdContactsGetAsync(int id)
{
var result = "";
return new ObjectResult(result);
}
/// <summary>
///
/// </summary>
/// <remarks>Adds Owner Contact</remarks>
/// <param name="id">id of Owner to add a contact for</param>
/// <param name="item">Adds to Owner Contact</param>
/// <response code="200">OK</response>
public virtual IActionResult OwnersIdContactsPostAsync(int id, Contact item)
{
var result = "";
return new ObjectResult(result);
}
/// <summary>
///
/// </summary>
/// <remarks>Replaces an Owner's Contacts</remarks>
/// <param name="id">id of Owner to replace Contacts for</param>
/// <param name="item">Replacement Owner contacts.</param>
/// <response code="200">OK</response>
public virtual IActionResult OwnersIdContactsPutAsync(int id, Contact[] item)
{
var result = "";
return new ObjectResult(result);
}
/// <summary>
///
/// </summary>
/// <param name="id">id of Owner to delete</param>
/// <response code="200">OK</response>
/// <response code="404">Owner not found</response>
public virtual IActionResult OwnersIdDeletePostAsync(int id)
{
var result = "";
return new ObjectResult(result);
}
/// <summary>
///
/// </summary>
/// <remarks>Gets an Owner's Equipment</remarks>
/// <param name="id">id of Owner to fetch Equipment for</param>
/// <response code="200">OK</response>
public virtual IActionResult OwnersIdEquipmentGetAsync(int id)
{
var result = "";
return new ObjectResult(result);
}
/// <summary>
///
/// </summary>
/// <remarks>Replaces an Owner's Equipment</remarks>
/// <param name="id">id of Owner to replace Equipment for</param>
/// <param name="item">Replacement Owner Equipment.</param>
/// <response code="200">OK</response>
public virtual IActionResult OwnersIdEquipmentPutAsync(int id, Equipment[] item)
{
var result = "";
return new ObjectResult(result);
}
/// <summary>
///
/// </summary>
/// <param name="id">id of Owner to fetch</param>
/// <response code="200">OK</response>
/// <response code="404">Owner not found</response>
public virtual IActionResult OwnersIdGetAsync(int id)
{
var result = "";
return new ObjectResult(result);
}
/// <summary>
///
/// </summary>
/// <remarks>Returns History for a particular Owner</remarks>
/// <param name="id">id of Owner to fetch History for</param>
/// <param name="offset">offset for records that are returned</param>
/// <param name="limit">limits the number of records returned.</param>
/// <response code="200">OK</response>
public virtual IActionResult OwnersIdHistoryGetAsync(int id, int? offset, int? limit)
{
var result = "";
return new ObjectResult(result);
}
/// <summary>
///
/// </summary>
/// <remarks>Add a History record to the Owner</remarks>
/// <param name="id">id of Owner to add History for</param>
/// <param name="item"></param>
/// <response code="200">OK</response>
/// <response code="201">History created</response>
public virtual IActionResult OwnersIdHistoryPostAsync(int id, History item)
{
var result = "";
return new ObjectResult(result);
}
/// <summary>
///
/// </summary>
/// <param name="id">id of Owner to fetch</param>
/// <param name="item"></param>
/// <response code="200">OK</response>
/// <response code="404">Owner not found</response>
public virtual IActionResult OwnersIdPutAsync(int id, Owner item)
{
var result = "";
return new ObjectResult(result);
}
/// <summary>
///
/// </summary>
/// <param name="item"></param>
/// <response code="201">Owner created</response>
public virtual IActionResult OwnersPostAsync(Owner item)
{
var result = "";
return new ObjectResult(result);
}
/// <summary>
/// Searches Owners
/// </summary>
/// <remarks>Used for the owner search page.</remarks>
/// <param name="localareas">Local Areas (comma seperated list of id numbers)</param>
/// <param name="equipmenttypes">Equipment Types (comma seperated list of id numbers)</param>
/// <param name="owner">Id for a specific Owner</param>
/// <param name="status">Status</param>
/// <param name="hired">Hired</param>
/// <response code="200">OK</response>
public virtual IActionResult OwnersSearchGetAsync(string localareas, string equipmenttypes, int? owner, string status, bool? hired)
{
var result = "";
return new ObjectResult(result);
}
}
}
| |
//---------------------------------------------------------------------
// <copyright file="LeafCellTreeNode.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
using System.Collections.Generic;
using System.Data.Common.Utils;
using System.Data.Mapping.ViewGeneration.CqlGeneration;
using System.Data.Mapping.ViewGeneration.QueryRewriting;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Data.Metadata.Edm;
namespace System.Data.Mapping.ViewGeneration.Structures
{
// This class represents the nodes that reside at the leaves of the tree
internal class LeafCellTreeNode : CellTreeNode
{
#region Constructor
// effects: Encapsulate the cell wrapper in the node
internal LeafCellTreeNode(ViewgenContext context, LeftCellWrapper cellWrapper)
: base(context)
{
m_cellWrapper = cellWrapper;
m_leftFragmentQuery = cellWrapper.FragmentQuery;
cellWrapper.AssertHasUniqueCell();
m_rightFragmentQuery = FragmentQuery.Create(
cellWrapper.OriginalCellNumberString,
cellWrapper.CreateRoleBoolean(),
cellWrapper.RightCellQuery);
}
internal LeafCellTreeNode(ViewgenContext context, LeftCellWrapper cellWrapper, FragmentQuery rightFragmentQuery)
: base(context)
{
m_cellWrapper = cellWrapper;
m_leftFragmentQuery = cellWrapper.FragmentQuery;
m_rightFragmentQuery = rightFragmentQuery;
}
#endregion
#region Fields
internal static readonly IEqualityComparer<LeafCellTreeNode> EqualityComparer = new LeafCellTreeNodeComparer();
// The cell at the leaf level
private LeftCellWrapper m_cellWrapper;
private FragmentQuery m_leftFragmentQuery;
private FragmentQuery m_rightFragmentQuery;
#endregion
#region Properties
internal LeftCellWrapper LeftCellWrapper
{
get { return m_cellWrapper; }
}
internal override MemberDomainMap RightDomainMap
{
get { return m_cellWrapper.RightDomainMap; }
}
// effects: See CellTreeNode.FragmentQuery
internal override FragmentQuery LeftFragmentQuery { get { return m_cellWrapper.FragmentQuery; } }
internal override FragmentQuery RightFragmentQuery
{
get
{
Debug.Assert(m_rightFragmentQuery != null, "Unassigned right fragment query");
return m_rightFragmentQuery;
}
}
// effects: See CellTreeNode.Attributes
internal override Set<MemberPath> Attributes { get { return m_cellWrapper.Attributes; } }
// effects: See CellTreeNode.Children
internal override List<CellTreeNode> Children { get { return new List<CellTreeNode>(); } }
// effects: See CellTreeNode.OpType
internal override CellTreeOpType OpType { get { return CellTreeOpType.Leaf; } }
internal override int NumProjectedSlots
{
get { return LeftCellWrapper.RightCellQuery.NumProjectedSlots; }
}
internal override int NumBoolSlots
{
get { return LeftCellWrapper.RightCellQuery.NumBoolVars; }
}
#endregion
#region Methods
internal override TOutput Accept<TInput, TOutput>(CellTreeVisitor<TInput, TOutput> visitor, TInput param)
{
return visitor.VisitLeaf(this, param);
}
internal override TOutput Accept<TInput, TOutput>(SimpleCellTreeVisitor<TInput, TOutput> visitor, TInput param)
{
return visitor.VisitLeaf(this, param);
}
internal override bool IsProjectedSlot(int slot)
{
CellQuery cellQuery = LeftCellWrapper.RightCellQuery;
if (IsBoolSlot(slot))
{
return cellQuery.GetBoolVar(SlotToBoolIndex(slot)) != null;
}
else
{
return cellQuery.ProjectedSlotAt(slot) != null;
}
}
#endregion
#region Leaf CqlBlock Methods
internal override CqlBlock ToCqlBlock(bool[] requiredSlots, CqlIdentifiers identifiers, ref int blockAliasNum, ref List<WithRelationship> withRelationships)
{
// Get the projected slots and the boolean expressions
int totalSlots = requiredSlots.Length;
CellQuery cellQuery = LeftCellWrapper.RightCellQuery;
SlotInfo[] projectedSlots = new SlotInfo[totalSlots];
Debug.Assert(cellQuery.NumProjectedSlots + cellQuery.NumBoolVars == totalSlots,
"Wrong number of projected slots in node");
Debug.Assert(cellQuery.NumProjectedSlots == ProjectedSlotMap.Count,
"Different number of slots in cell query and what we have mappings for");
// Add the regular fields
for (int i = 0; i < cellQuery.NumProjectedSlots; i++)
{
ProjectedSlot slot = cellQuery.ProjectedSlotAt(i);
// If the slot is not null, we will project it
// For extents, we say that all requiredlots are the only the
// ones that are CLR non-null. Recall that "real" nulls are
// handled by having a CellConstant.Null in ConstantSlot
if (requiredSlots[i] && slot == null)
{
MemberPath memberPath = ProjectedSlotMap[i];
ConstantProjectedSlot defaultValue = new ConstantProjectedSlot(Domain.GetDefaultValueForMemberPath(memberPath, GetLeaves(), ViewgenContext.Config), memberPath);
cellQuery.FixMissingSlotAsDefaultConstant(i, defaultValue);
slot = defaultValue;
}
SlotInfo slotInfo = new SlotInfo(requiredSlots[i], slot != null,
slot, ProjectedSlotMap[i]);
projectedSlots[i] = slotInfo;
}
// Add the boolean fields
for (int boolNum = 0; boolNum < cellQuery.NumBoolVars; boolNum++)
{
BoolExpression expr = cellQuery.GetBoolVar(boolNum);
BooleanProjectedSlot boolSlot;
if (expr != null)
{
boolSlot = new BooleanProjectedSlot(expr, identifiers, boolNum);
}
else
{
boolSlot = new BooleanProjectedSlot(BoolExpression.False, identifiers, boolNum);
}
int slotIndex = BoolIndexToSlot(boolNum);
SlotInfo slotInfo = new SlotInfo(requiredSlots[slotIndex], expr != null,
boolSlot, null);
projectedSlots[slotIndex] = slotInfo;
}
// See if we are generating a query view and whether there are any colocated foreign keys for which
// we have to add With statements.
IEnumerable<SlotInfo> totalProjectedSlots = projectedSlots;
if ((cellQuery.Extent.EntityContainer.DataSpace == DataSpace.SSpace)
&& (this.m_cellWrapper.LeftExtent.BuiltInTypeKind == BuiltInTypeKind.EntitySet))
{
IEnumerable<StorageAssociationSetMapping> associationSetMaps =
this.ViewgenContext.EntityContainerMapping.GetRelationshipSetMappingsFor(this.m_cellWrapper.LeftExtent, cellQuery.Extent);
List<SlotInfo> foreignKeySlots = new List<SlotInfo>();
foreach (StorageAssociationSetMapping colocatedAssociationSetMap in associationSetMaps)
{
WithRelationship withRelationship;
if (TryGetWithRelationship(colocatedAssociationSetMap, this.m_cellWrapper.LeftExtent, cellQuery.SourceExtentMemberPath, ref foreignKeySlots, out withRelationship))
{
withRelationships.Add(withRelationship);
totalProjectedSlots = projectedSlots.Concat(foreignKeySlots);
}
}
}
ExtentCqlBlock result = new ExtentCqlBlock(cellQuery.Extent, cellQuery.SelectDistinctFlag, totalProjectedSlots.ToArray(),
cellQuery.WhereClause, identifiers, ++blockAliasNum);
return result;
}
private bool TryGetWithRelationship(StorageAssociationSetMapping colocatedAssociationSetMap,
EntitySetBase thisExtent,
MemberPath sRootNode,
ref List<SlotInfo> foreignKeySlots,
out WithRelationship withRelationship)
{
Debug.Assert(foreignKeySlots != null);
withRelationship = null;
//Get the map for foreign key end
StorageEndPropertyMapping foreignKeyEndMap = GetForeignKeyEndMapFromAssocitionMap(colocatedAssociationSetMap, thisExtent);
if (foreignKeyEndMap == null || foreignKeyEndMap.EndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many)
{
return false;
}
AssociationEndMember toEnd = (AssociationEndMember)foreignKeyEndMap.EndMember;
AssociationEndMember fromEnd = MetadataHelper.GetOtherAssociationEnd(toEnd);
EntityType toEndEntityType = (EntityType)((RefType)(toEnd.TypeUsage.EdmType)).ElementType;
EntityType fromEndEntityType = (EntityType)(((RefType)fromEnd.TypeUsage.EdmType).ElementType);
// Get the member path for AssociationSet
AssociationSet associationSet = (AssociationSet)colocatedAssociationSetMap.Set;
MemberPath prefix = new MemberPath(associationSet, toEnd);
// Collect the member paths for edm scalar properties that belong to the target entity key.
// These will be used as part of WITH RELATIONSHIP.
// Get the key properties from edm type since the query parser depends on the order of key members
IEnumerable<StorageScalarPropertyMapping> propertyMaps = foreignKeyEndMap.Properties.Cast<StorageScalarPropertyMapping>();
List<MemberPath> toEndEntityKeyMemberPaths = new List<MemberPath>();
foreach (EdmProperty edmProperty in toEndEntityType.KeyMembers)
{
IEnumerable<StorageScalarPropertyMapping> scalarPropertyMaps = propertyMaps.Where(propMap => (propMap.EdmProperty.Equals(edmProperty)));
Debug.Assert(scalarPropertyMaps.Count() == 1, "Can't Map the same column multiple times in the same end");
StorageScalarPropertyMapping scalarPropertyMap = scalarPropertyMaps.First();
// Create SlotInfo for Freign Key member that needs to be projected.
MemberProjectedSlot sSlot = new MemberProjectedSlot(new MemberPath(sRootNode, scalarPropertyMap.ColumnProperty));
MemberPath endMemberKeyPath = new MemberPath(prefix, edmProperty);
toEndEntityKeyMemberPaths.Add(endMemberKeyPath);
foreignKeySlots.Add(new SlotInfo(true, true, sSlot, endMemberKeyPath));
}
// Parent assignable from child: Ensures they are in the same hierarchy.
if (thisExtent.ElementType.IsAssignableFrom(fromEndEntityType))
{
// Now create the WITH RELATIONSHIP with all the needed info.
withRelationship = new WithRelationship(associationSet, fromEnd, fromEndEntityType, toEnd, toEndEntityType, toEndEntityKeyMemberPaths);
return true;
}
else
{
return false;
}
}
//Gets the end that is not mapped to the primary key of the table
private StorageEndPropertyMapping GetForeignKeyEndMapFromAssocitionMap(StorageAssociationSetMapping colocatedAssociationSetMap, EntitySetBase thisExtent)
{
StorageMappingFragment mapFragment = colocatedAssociationSetMap.TypeMappings.First().MappingFragments.First();
EntitySet storeEntitySet = (EntitySet)(colocatedAssociationSetMap.StoreEntitySet);
IEnumerable<EdmMember> keyProperties = storeEntitySet.ElementType.KeyMembers;
//Find the end that's mapped to primary key
foreach (StorageEndPropertyMapping endMap in mapFragment.Properties)
{
IEnumerable<EdmMember> endStoreMembers = endMap.StoreProperties;
if (endStoreMembers.SequenceEqual(keyProperties, EqualityComparer<EdmMember>.Default))
{
//Return the map for the other end since that is the foreign key end
IEnumerable<StorageEndPropertyMapping> otherEnds = mapFragment.Properties.OfType<StorageEndPropertyMapping>().Where(eMap => (!eMap.Equals(endMap)));
Debug.Assert(otherEnds.Count() == 1);
return otherEnds.First();
}
}
//This is probably defensive, but there should be no problem in falling back on the
//AssociationSetMap if colocated foreign key is not found for some reason.
return null;
}
#endregion
#region String Methods
// effects: See CellTreeNode.ToString
internal override void ToCompactString(StringBuilder stringBuilder)
{
m_cellWrapper.ToCompactString(stringBuilder);
}
#endregion
#region IEqualityComparer<LeafCellTreeNode>
// A comparer that equates leaf nodes if the wrapper is the same
private class LeafCellTreeNodeComparer : IEqualityComparer<LeafCellTreeNode>
{
public bool Equals(LeafCellTreeNode left, LeafCellTreeNode right)
{
// Quick check with references
if (object.ReferenceEquals(left, right))
{
// Gets the Null and Undefined case as well
return true;
}
// One of them is non-null at least
if (left == null || right == null)
{
return false;
}
// Both are non-null at this point
return left.m_cellWrapper.Equals(right.m_cellWrapper);
}
public int GetHashCode(LeafCellTreeNode node)
{
return node.m_cellWrapper.GetHashCode();
}
}
#endregion
}
}
| |
/*
[PLEASE DO NOT MODIFY THIS HEADER INFORMATION]---------------------
Title: Grouper
Description: A rounded groupbox with special painting features.
Date Created: December 17, 2005
Author: Adam Smith
Author Email: ibulwark@hotmail.com
Websites: http://www.ebadgeman.com | http://www.codevendor.com
Version History:
1.0a - Beta Version - Release Date: December 17, 2005
-------------------------------------------------------------------
*/
using System;
using System.Collections;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Data;
using System.Windows.Forms;
namespace CloudBox.Controller
{
/// <summary>A special custom rounding GroupBox with many painting features.</summary>
[ToolboxBitmap(typeof(Grouper), "CloudBoxUC.Resources.Grouper.bmp")]
[Designer("System.Windows.Forms.Design.ParentControlDesigner, System.Design", typeof(IDesigner))]
public class Grouper : System.Windows.Forms.UserControl
{
#region Enumerations
/// <summary>A special gradient enumeration.</summary>
public enum GroupBoxGradientMode
{
/// <summary>Specifies no gradient mode.</summary>
None = 4,
/// <summary>Specifies a gradient from upper right to lower left.</summary>
BackwardDiagonal = 3,
/// <summary>Specifies a gradient from upper left to lower right.</summary>
ForwardDiagonal = 2,
/// <summary>Specifies a gradient from left to right.</summary>
Horizontal = 0,
/// <summary>Specifies a gradient from top to bottom.</summary>
Vertical = 1
}
#endregion
#region Variables
private System.ComponentModel.Container components = null;
private int V_RoundCorners = 10;
private string V_GroupTitle = "The Grouper";
private System.Drawing.Color V_BorderColor = Color.Black;
private float V_BorderThickness = 1;
private bool V_ShadowControl = false;
private System.Drawing.Color V_BackgroundColor = Color.White;
private System.Drawing.Color V_BackgroundGradientColor = Color.White;
private GroupBoxGradientMode V_BackgroundGradientMode = GroupBoxGradientMode.None;
private System.Drawing.Color V_ShadowColor = Color.DarkGray;
private int V_ShadowThickness = 3;
private System.Drawing.Image V_GroupImage = null;
private System.Drawing.Color V_CustomGroupBoxColor = Color.White;
private bool V_PaintGroupBox = false;
private System.Drawing.Color V_BackColor = Color.Transparent;
#endregion
#region Properties
/// <summary>This feature will paint the background color of the control.</summary>
[Category("Appearance"), Description("This feature will paint the background color of the control.")]
public override System.Drawing.Color BackColor{get{return V_BackColor;} set{V_BackColor=value; this.Refresh();}}
/// <summary>This feature will paint the group title background to the specified color if PaintGroupBox is set to true.</summary>
[Category("Appearance"), Description("This feature will paint the group title background to the specified color if PaintGroupBox is set to true.")]
public System.Drawing.Color CustomGroupBoxColor{get{return V_CustomGroupBoxColor;} set{V_CustomGroupBoxColor=value; this.Refresh();}}
/// <summary>This feature will paint the group title background to the CustomGroupBoxColor.</summary>
[Category("Appearance"), Description("This feature will paint the group title background to the CustomGroupBoxColor.")]
public bool PaintGroupBox{get{return V_PaintGroupBox;} set{V_PaintGroupBox=value; this.Refresh();}}
/// <summary>This feature can add a 16 x 16 image to the group title bar.</summary>
[Category("Appearance"), Description("This feature can add a 16 x 16 image to the group title bar.")]
public System.Drawing.Image GroupImage{get{return V_GroupImage;} set{V_GroupImage=value; this.Refresh();}}
/// <summary>This feature will change the control's shadow color.</summary>
[Category("Appearance"), Description("This feature will change the control's shadow color.")]
public System.Drawing.Color ShadowColor{get{return V_ShadowColor;} set{V_ShadowColor=value; this.Refresh();}}
/// <summary>This feature will change the size of the shadow border.</summary>
[Category("Appearance"), Description("This feature will change the size of the shadow border.")]
public int ShadowThickness
{
get{return V_ShadowThickness;}
set
{
if(value>10)
{
V_ShadowThickness=10;
}
else
{
if(value<1){V_ShadowThickness=1;}
else{V_ShadowThickness=value; }
}
this.Refresh();
}
}
/// <summary>This feature will change the group control color. This color can also be used in combination with BackgroundGradientColor for a gradient paint.</summary>
[Category("Appearance"), Description("This feature will change the group control color. This color can also be used in combination with BackgroundGradientColor for a gradient paint.")]
public System.Drawing.Color BackgroundColor{get{return V_BackgroundColor;} set{V_BackgroundColor=value; this.Refresh();}}
/// <summary>This feature can be used in combination with BackgroundColor to create a gradient background.</summary>
[Category("Appearance"), Description("This feature can be used in combination with BackgroundColor to create a gradient background.")]
public System.Drawing.Color BackgroundGradientColor{get{return V_BackgroundGradientColor;} set{V_BackgroundGradientColor=value; this.Refresh();}}
/// <summary>This feature turns on background gradient painting.</summary>
[Category("Appearance"), Description("This feature turns on background gradient painting.")]
public GroupBoxGradientMode BackgroundGradientMode{get{return V_BackgroundGradientMode;} set{V_BackgroundGradientMode=value; this.Refresh();}}
/// <summary>This feature will round the corners of the control.</summary>
[Category("Appearance"), Description("This feature will round the corners of the control.")]
public int RoundCorners
{
get{return V_RoundCorners;}
set
{
if(value>25)
{
V_RoundCorners=25;
}
else
{
if(value<1){V_RoundCorners=1;}
else{V_RoundCorners=value; }
}
this.Refresh();
}
}
/// <summary>This feature will add a group title to the control.</summary>
[Category("Appearance"), Description("This feature will add a group title to the control.")]
public string GroupTitle{get{return V_GroupTitle;} set{V_GroupTitle=value; this.Refresh();}}
/// <summary>This feature will allow you to change the color of the control's border.</summary>
[Category("Appearance"), Description("This feature will allow you to change the color of the control's border.")]
public System.Drawing.Color BorderColor{get{return V_BorderColor;} set{V_BorderColor=value; this.Refresh();}}
/// <summary>This feature will allow you to set the control's border size.</summary>
[Category("Appearance"), Description("This feature will allow you to set the control's border size.")]
public float BorderThickness
{
get{return V_BorderThickness;}
set
{
if(value>3)
{
V_BorderThickness=3;
}
else
{
if(value<1){V_BorderThickness=1;}
else{V_BorderThickness=value;}
}
this.Refresh();
}
}
/// <summary>This feature will allow you to turn on control shadowing.</summary>
[Category("Appearance"), Description("This feature will allow you to turn on control shadowing.")]
public bool ShadowControl{get{return V_ShadowControl;} set{V_ShadowControl=value; this.Refresh();}}
#endregion
#region Constructor
/// <summary>This method will construct a new GroupBox control.</summary>
public Grouper()
{
InitializeStyles();
InitializeGroupBox();
}
#endregion
#region DeConstructor
/// <summary>This method will dispose of the GroupBox control.</summary>
protected override void Dispose( bool disposing )
{
if(disposing){if(components!=null){components.Dispose();}}
base.Dispose(disposing);
}
#endregion
#region Initialization
/// <summary>This method will initialize the controls custom styles.</summary>
private void InitializeStyles()
{
//Set the control styles----------------------------------
this.SetStyle(ControlStyles.DoubleBuffer, true);
this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
this.SetStyle(ControlStyles.UserPaint, true);
this.SetStyle(ControlStyles.SupportsTransparentBackColor, true);
//--------------------------------------------------------
}
/// <summary>This method will initialize the GroupBox control.</summary>
private void InitializeGroupBox()
{
components = new System.ComponentModel.Container();
this.Resize+=new EventHandler(GroupBox_Resize);
this.DockPadding.All = 20;
this.Name = "GroupBox";
this.Size = new System.Drawing.Size(368, 288);
}
#endregion
#region Protected Methods
/// <summary>Overrides the OnPaint method to paint control.</summary>
/// <param name="e">The paint event arguments.</param>
protected override void OnPaint(PaintEventArgs e)
{
PaintBack(e.Graphics);
PaintGroupText(e.Graphics);
}
#endregion
#region Private Methods
/// <summary>This method will paint the group title.</summary>
/// <param name="g">The paint event graphics object.</param>
private void PaintGroupText(System.Drawing.Graphics g)
{
//Check if string has something-------------
if(this.GroupTitle==string.Empty){return;}
//------------------------------------------
//Set Graphics smoothing mode to Anit-Alias--
g.SmoothingMode = SmoothingMode.AntiAlias;
//-------------------------------------------
//Declare Variables------------------
SizeF StringSize = g.MeasureString(this.GroupTitle, this.Font);
Size StringSize2 = StringSize.ToSize();
if(this.GroupImage!=null){StringSize2.Width+=18;}
int ArcWidth = this.RoundCorners;
int ArcHeight = this.RoundCorners;
int ArcX1 = 20;
int ArcX2 = (StringSize2.Width+34) - (ArcWidth + 1);
int ArcY1 = 0;
int ArcY2 = 24 - (ArcHeight + 1);
System.Drawing.Drawing2D.GraphicsPath path = new System.Drawing.Drawing2D.GraphicsPath();
System.Drawing.Brush BorderBrush = new SolidBrush(this.BorderColor);
System.Drawing.Pen BorderPen = new Pen(BorderBrush, this.BorderThickness);
System.Drawing.Drawing2D.LinearGradientBrush BackgroundGradientBrush = null;
System.Drawing.Brush BackgroundBrush = (this.PaintGroupBox) ? new SolidBrush(this.CustomGroupBoxColor) : new SolidBrush(this.BackgroundColor);
System.Drawing.SolidBrush TextColorBrush = new SolidBrush(this.ForeColor);
System.Drawing.SolidBrush ShadowBrush = null;
System.Drawing.Drawing2D.GraphicsPath ShadowPath = null;
//-----------------------------------
//Check if shadow is needed----------
if(this.ShadowControl)
{
ShadowBrush = new SolidBrush(this.ShadowColor);
ShadowPath = new System.Drawing.Drawing2D.GraphicsPath();
ShadowPath.AddArc(ArcX1+(this.ShadowThickness-1), ArcY1+(this.ShadowThickness-1), ArcWidth, ArcHeight, 180, GroupBoxConstants.SweepAngle); // Top Left
ShadowPath.AddArc(ArcX2+(this.ShadowThickness-1), ArcY1+(this.ShadowThickness-1), ArcWidth, ArcHeight, 270, GroupBoxConstants.SweepAngle); //Top Right
ShadowPath.AddArc(ArcX2+(this.ShadowThickness-1), ArcY2+(this.ShadowThickness-1), ArcWidth, ArcHeight, 360, GroupBoxConstants.SweepAngle); //Bottom Right
ShadowPath.AddArc(ArcX1+(this.ShadowThickness-1), ArcY2+(this.ShadowThickness-1), ArcWidth, ArcHeight, 90, GroupBoxConstants.SweepAngle); //Bottom Left
ShadowPath.CloseAllFigures();
//Paint Rounded Rectangle------------
g.FillPath(ShadowBrush, ShadowPath);
//-----------------------------------
}
//-----------------------------------
//Create Rounded Rectangle Path------
path.AddArc(ArcX1, ArcY1, ArcWidth, ArcHeight, 180, GroupBoxConstants.SweepAngle); // Top Left
path.AddArc(ArcX2, ArcY1, ArcWidth, ArcHeight, 270, GroupBoxConstants.SweepAngle); //Top Right
path.AddArc(ArcX2, ArcY2, ArcWidth, ArcHeight, 360, GroupBoxConstants.SweepAngle); //Bottom Right
path.AddArc(ArcX1, ArcY2, ArcWidth, ArcHeight, 90, GroupBoxConstants.SweepAngle); //Bottom Left
path.CloseAllFigures();
//-----------------------------------
//Check if Gradient Mode is enabled--
if(this.PaintGroupBox)
{
//Paint Rounded Rectangle------------
g.FillPath(BackgroundBrush, path);
//-----------------------------------
}
else
{
if(this.BackgroundGradientMode==GroupBoxGradientMode.None)
{
//Paint Rounded Rectangle------------
g.FillPath(BackgroundBrush, path);
//-----------------------------------
}
else
{
BackgroundGradientBrush = new LinearGradientBrush(new Rectangle(0,0,this.Width,this.Height), this.BackgroundColor, this.BackgroundGradientColor, (LinearGradientMode)this.BackgroundGradientMode);
//Paint Rounded Rectangle------------
g.FillPath(BackgroundGradientBrush, path);
//-----------------------------------
}
}
//-----------------------------------
//Paint Borded-----------------------
g.DrawPath(BorderPen, path);
//-----------------------------------
//Paint Text-------------------------
int CustomStringWidth = (this.GroupImage!=null) ? 44 : 28;
g.DrawString(this.GroupTitle, this.Font, TextColorBrush, CustomStringWidth, 5);
//-----------------------------------
//Draw GroupImage if there is one----
if(this.GroupImage!=null)
{
g.DrawImage(this.GroupImage, 28,4, 16, 16);
}
//-----------------------------------
//Destroy Graphic Objects------------
if(path!=null){path.Dispose();}
if(BorderBrush!=null){BorderBrush.Dispose();}
if(BorderPen!=null){BorderPen.Dispose();}
if(BackgroundGradientBrush!=null){BackgroundGradientBrush.Dispose();}
if(BackgroundBrush!=null){BackgroundBrush.Dispose();}
if(TextColorBrush!=null){TextColorBrush .Dispose();}
if(ShadowBrush!=null){ShadowBrush.Dispose();}
if(ShadowPath!=null){ShadowPath.Dispose();}
//-----------------------------------
}
/// <summary>This method will paint the control.</summary>
/// <param name="g">The paint event graphics object.</param>
private void PaintBack(System.Drawing.Graphics g)
{
//Set Graphics smoothing mode to Anit-Alias--
g.SmoothingMode = SmoothingMode.AntiAlias;
//-------------------------------------------
//Declare Variables------------------
int ArcWidth = this.RoundCorners * 2;
int ArcHeight = this.RoundCorners * 2;
int ArcX1 = 0;
int ArcX2 = (this.ShadowControl) ? (this.Width - (ArcWidth + 1))-this.ShadowThickness : this.Width - (ArcWidth + 1);
int ArcY1 = 10;
int ArcY2 = (this.ShadowControl) ? (this.Height - (ArcHeight + 1))-this.ShadowThickness : this.Height - (ArcHeight + 1);
System.Drawing.Drawing2D.GraphicsPath path = new System.Drawing.Drawing2D.GraphicsPath();
System.Drawing.Brush BorderBrush = new SolidBrush(this.BorderColor);
System.Drawing.Pen BorderPen = new Pen(BorderBrush, this.BorderThickness);
System.Drawing.Drawing2D.LinearGradientBrush BackgroundGradientBrush = null;
System.Drawing.Brush BackgroundBrush = new SolidBrush(this.BackgroundColor);
System.Drawing.SolidBrush ShadowBrush = null;
System.Drawing.Drawing2D.GraphicsPath ShadowPath = null;
//-----------------------------------
//Check if shadow is needed----------
if(this.ShadowControl)
{
ShadowBrush = new SolidBrush(this.ShadowColor);
ShadowPath = new System.Drawing.Drawing2D.GraphicsPath();
ShadowPath.AddArc(ArcX1+this.ShadowThickness, ArcY1+this.ShadowThickness, ArcWidth, ArcHeight, 180, GroupBoxConstants.SweepAngle); // Top Left
ShadowPath.AddArc(ArcX2+this.ShadowThickness, ArcY1+this.ShadowThickness, ArcWidth, ArcHeight, 270, GroupBoxConstants.SweepAngle); //Top Right
ShadowPath.AddArc(ArcX2+this.ShadowThickness, ArcY2+this.ShadowThickness, ArcWidth, ArcHeight, 360, GroupBoxConstants.SweepAngle); //Bottom Right
ShadowPath.AddArc(ArcX1+this.ShadowThickness, ArcY2+this.ShadowThickness, ArcWidth, ArcHeight, 90, GroupBoxConstants.SweepAngle); //Bottom Left
ShadowPath.CloseAllFigures();
//Paint Rounded Rectangle------------
g.FillPath(ShadowBrush, ShadowPath);
//-----------------------------------
}
//-----------------------------------
//Create Rounded Rectangle Path------
path.AddArc(ArcX1, ArcY1, ArcWidth, ArcHeight, 180, GroupBoxConstants.SweepAngle); // Top Left
path.AddArc(ArcX2, ArcY1, ArcWidth, ArcHeight, 270, GroupBoxConstants.SweepAngle); //Top Right
path.AddArc(ArcX2, ArcY2, ArcWidth, ArcHeight, 360, GroupBoxConstants.SweepAngle); //Bottom Right
path.AddArc(ArcX1, ArcY2, ArcWidth, ArcHeight, 90, GroupBoxConstants.SweepAngle); //Bottom Left
path.CloseAllFigures();
//-----------------------------------
//Check if Gradient Mode is enabled--
if(this.BackgroundGradientMode==GroupBoxGradientMode.None)
{
//Paint Rounded Rectangle------------
g.FillPath(BackgroundBrush, path);
//-----------------------------------
}
else
{
BackgroundGradientBrush = new LinearGradientBrush(new Rectangle(0,0,this.Width,this.Height), this.BackgroundColor, this.BackgroundGradientColor, (LinearGradientMode)this.BackgroundGradientMode);
//Paint Rounded Rectangle------------
g.FillPath(BackgroundGradientBrush, path);
//-----------------------------------
}
//-----------------------------------
//Paint Borded-----------------------
g.DrawPath(BorderPen, path);
//-----------------------------------
//Destroy Graphic Objects------------
if(path!=null){path.Dispose();}
if(BorderBrush!=null){BorderBrush.Dispose();}
if(BorderPen!=null){BorderPen.Dispose();}
if(BackgroundGradientBrush!=null){BackgroundGradientBrush.Dispose();}
if(BackgroundBrush!=null){BackgroundBrush.Dispose();}
if(ShadowBrush!=null){ShadowBrush.Dispose();}
if(ShadowPath!=null){ShadowPath.Dispose();}
//-----------------------------------
}
/// <summary>This method fires when the GroupBox resize event occurs.</summary>
/// <param name="sender">The object the sent the event.</param>
/// <param name="e">The event arguments.</param>
private void GroupBox_Resize(object sender, EventArgs e)
{
this.Refresh();
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using Premotion.Mansion.Core;
using Premotion.Mansion.Core.Collections;
using Premotion.Mansion.Core.Data;
using Premotion.Mansion.Core.Types;
using Premotion.Mansion.Repository.ElasticSearch.Querying;
using Premotion.Mansion.Repository.ElasticSearch.Responses;
using Premotion.Mansion.Repository.ElasticSearch.Responses.Facets;
namespace Premotion.Mansion.Repository.ElasticSearch.Schema.Mappings
{
/// <summary>
/// Represents the mapping of a type.
/// </summary>
[JsonConverter(typeof (TypeMappingConverter))]
public class TypeMapping
{
#region Nested type: TypeMappingConverter
/// <summary>
/// Converts <see cref="TypeMapping"/>s.
/// </summary>
private class TypeMappingConverter : BaseWriteConverter<TypeMapping>
{
#region Overrides of BaseWriteConverter<TypeMapping>
/// <summary>
/// Writes the JSON representation of the object.
/// </summary>
/// <param name="writer">The <see cref="T:Newtonsoft.Json.JsonWriter"/> to write to.</param><param name="value">The value.</param><param name="serializer">The calling serializer.</param>
protected override void DoWriteJson(JsonWriter writer, TypeMapping value, JsonSerializer serializer)
{
writer.WriteStartObject(); // root
// loop over all the mappings
writer.WritePropertyName("properties");
writer.WriteStartObject(); // properties
foreach (var mapping in value.propertyMappings.Where(candidate => !(candidate.Value is IgnoredPropertyMapping)).ToDictionary(x => x.Key, x => x.Value))
{
writer.WritePropertyName(mapping.Key);
writer.WriteStartObject(); // mapping
serializer.Serialize(writer, mapping.Value);
writer.WriteEndObject(); // mapping
}
writer.WriteEndObject(); // properties
writer.WriteEndObject(); // root
}
#endregion
}
#endregion
#region Nested type: TypeMappingDescriptor
/// <summary>
/// Represents the <see cref="TypeDescriptor"/> for elastic search types.
/// </summary>
[TypeDescriptor(Constants.DescriptorNamespaceUri, "typeMapping")]
public class TypeMappingDescriptor : TypeDescriptor
{
#region Update Methods
/// <summary>
/// Updates the given <paramref name="typeMapping"/>.
/// </summary>
/// <param name="context">The <see cref="IMansionContext"/>.</param>
/// <param name="typeMapping">The <see cref="TypeMapping"/>.</param>
/// <returns>The created <see cref="PropertyMapping"/>.</returns>
public void UpdateMapping(IMansionContext context, TypeMapping typeMapping)
{
// validate arguments
if (context == null)
throw new ArgumentNullException("context");
if (typeMapping == null)
throw new ArgumentNullException("typeMapping");
throw new NotImplementedException();
}
#endregion
}
#endregion
#region Constructors
/// <summary>
/// Constucts a type mapping for the given <paramref name="type"/>.
/// </summary>
/// <param name="type">The <see cref="ITypeDefinition"/>.</param>
/// <exception cref="ArgumentNullException">Thrown if one of the parameters is null.</exception>
public TypeMapping(ITypeDefinition type)
{
// validate arguments
if (type == null)
throw new ArgumentNullException("type");
// set values
Name = type.Name.ToLower();
}
#endregion
#region Add Methods
/// <summary>
/// Adds the given <paramref name="propertyMapping"/> to this mapping.
/// </summary>
/// <param name="propertyMapping">The <see cref="PropertyMapping"/>.</param>
/// <exception cref="ArgumentNullException">Thrown if one of the paramters is null.</exception>
public void Add(PropertyMapping propertyMapping)
{
// validate arguments
if (propertyMapping == null)
throw new ArgumentNullException("propertyMapping");
// if the property is already mapped, replace it
if (propertyMappings.ContainsKey(propertyMapping.Field))
propertyMappings.Remove(propertyMapping.Field);
// add the property mapping
propertyMappings.Add(propertyMapping.Field, propertyMapping);
}
#endregion
#region Clone Methods
/// <summary>
/// Clones this type mapping for a new <paramref name="type"/>.
/// </summary>
/// <param name="type">The <paramref name="type"/>.</param>
/// <returns>Returns the cloned type mapping.</returns>
public TypeMapping Clone(ITypeDefinition type)
{
// validate arguments
if (type == null)
throw new ArgumentNullException("type");
// create a new mapping for the type
var cloned = new TypeMapping(type);
// copy all the property mappings
foreach (var propertyMapping in propertyMappings)
cloned.propertyMappings.Add(propertyMapping.Key, propertyMapping.Value);
// return the clone
return cloned;
}
#endregion
#region Transform Methods
/// <summary>
/// Transforms the given <paramref name="source"/> into an ElasticSearch document.
/// </summary>
/// <param name="context">the <see cref="IMansionContext"/>.</param>
/// <param name="source">The <see cref="IPropertyBag"/> which to transform.</param>
/// <returns>Returns the resulting document.</returns>
/// <exception cref="ArgumentNullException">Thrown if one of the parameters is null.</exception>
public IDictionary<string, object> Transform(IMansionContext context, IPropertyBag source)
{
// validate arguments
if (context == null)
throw new ArgumentNullException("context");
if (source == null)
throw new ArgumentNullException("source");
// create a new dictionary which represents the document
var document = new Dictionary<string, object>();
// loop over all the properties, except those who start with an underscore
foreach (var property in source.Where(candidate => !candidate.Key.StartsWith("_")))
{
// ElasticSearch is case sensitive, use lower case property name
var key = property.Key.ToLower();
// check if there is mapping defined for this property
PropertyMapping mapping;
if (propertyMappings.TryGetValue(key, out mapping))
{
// allow the property mapping to transorm the value
mapping.Transform(context, source, document);
}
else
{
// just store the value in the document and let ElasticSearch figure out how to index it
document.Add(key, property.Value);
}
}
// return the transformed document
return document;
}
#endregion
#region Hit Map Methods
/// <summary>
/// Maps the given <paramref name="response"/> into a <see cref="RecordSet"/>.
/// </summary>
/// <param name="context">The <see cref="IMansionContext"/>.</param>
/// <param name="query">The <see cref="SearchQuery"/>.</param>
/// <param name="response">The <see cref="SearchResponse"/>.</param>
/// <returns>Returns the mapped record set.</returns>
public static RecordSet MapRecordSet(IMansionContext context, SearchQuery query, SearchResponse response)
{
// validate arguments
if (context == null)
throw new ArgumentNullException("context");
if (query == null)
throw new ArgumentNullException("query");
if (response == null)
throw new ArgumentNullException("response");
// map all the hits
var records = MapRecords(context, query, response.Hits.Hits);
// map the set metadata
var metaData = MapRecordSetMetaData(query, response.Hits);
// create the set
var set = new RecordSet(context, metaData, records);
// map the facets
MapFacets(context, query, response.Facets, set);
// return the set
return set;
}
/// <summary>
/// Maps the meta data of the <paramref name="hits"/>.
/// </summary>
/// <param name="query">The source <see cref="SearchQuery"/>.</param>
/// <param name="hits">The resulting <see cref="HitMetaData"/>.</param>
/// <returns>Returns a <see cref="IPropertyBag"/> containing the meta data.</returns>
private static IPropertyBag MapRecordSetMetaData(SearchQuery query, HitMetaData hits)
{
// create the meta data
var metaData = new PropertyBag
{
{"totalCount", hits.Total}
};
// set the paging options if any
if (query.From.HasValue && query.Size.HasValue && query.Size > 0)
{
metaData.Set("pageNumber", (query.From.Value + query.Size.Value)/query.Size.Value);
metaData.Set("pageSize", query.Size.Value);
}
// set the sort value, if any
var sortString = query.Sorts.Aggregate(",", (current, sort) =>
{
var s = sort.ToString();
if (String.IsNullOrEmpty(s))
return current;
return current + ',' + sort;
}).Trim(',', ' ');
if (!String.IsNullOrEmpty(sortString))
metaData.Set("sort", sortString);
// return the meta data
return metaData;
}
/// <summary>
/// Maps all the <paramref name="hits"/> into <see cref="Record"/>s.
/// </summary>
/// <param name="context">The <see cref="IMansionContext"/>.</param>
/// <param name="query">The <see cref="SearchQuery"/>.</param>
/// <param name="hits">The <see cref="Hit"/>s.</param>
/// <returns>Returns the mapped <see cref="Record"/>s.</returns>
private static IEnumerable<Record> MapRecords(IMansionContext context, SearchQuery query, IEnumerable<Hit> hits)
{
// loop over all the hits
foreach (var hit in hits)
{
// create the record
var record = new Record();
// find the type mapping
var mapping = query.IndexDefinition.FindTypeMapping(hit.Type);
// map all its properties
mapping.MapProperties(context, hit, record);
// initialize the record
record.Initialize(context);
// return the mapped record
yield return record;
}
}
/// <summary>
/// Maps the properties from <paramref name="source"/> to <paramref name="target"/>.
/// </summary>
/// <param name="context">The <see cref="IMansionContext"/>.</param>
/// <param name="source">The <see cref="Hit"/>.</param>
/// <param name="target">The <see cref="IPropertyBag"/>.</param>
private void MapProperties(IMansionContext context, Hit source, IPropertyBag target)
{
// loop over all the properties
var document = source.Source;
foreach (var property in document.Properties())
{
// find the property mapping for this property
PropertyMapping propertyMapping;
if (!Properties.TryGetValue(property.Name, out propertyMapping))
{
// just write the property without mapping
SingleValuedPropertyMapping.Map(property, target);
continue;
}
// map the value using the property mapping
propertyMapping.Map(context, source, property, target);
}
}
/// <summary>
/// Maps the given <paramref name="response"/> into a <see cref="Nodeset"/>.
/// </summary>
/// <param name="context">The <see cref="IMansionContext"/>.</param>
/// <param name="query">The <see cref="SearchQuery"/>.</param>
/// <param name="response">The <see cref="SearchResponse"/>.</param>
/// <returns>Returns the mapped record set.</returns>
public static Nodeset MapNodeset(IMansionContext context, SearchQuery query, SearchResponse response)
{
// validate arguments
if (context == null)
throw new ArgumentNullException("context");
if (query == null)
throw new ArgumentNullException("query");
if (response == null)
throw new ArgumentNullException("response");
// map all the hits
var nodes = MapNodes(context, query, response.Hits.Hits);
// map the set metadata
var metaData = MapRecordSetMetaData(query, response.Hits);
// create the set
var set = new Nodeset(context, metaData, nodes);
// map the facets
MapFacets(context, query, response.Facets, set);
// return the set
return set;
}
/// <summary>
/// Maps all the <paramref name="hits"/> into <see cref="Record"/>s.
/// </summary>
/// <param name="context">The <see cref="IMansionContext"/>.</param>
/// <param name="query">The <see cref="SearchQuery"/>.</param>
/// <param name="hits">The <see cref="Hit"/>s.</param>
/// <returns>Returns the mapped <see cref="Record"/>s.</returns>
private static IEnumerable<Node> MapNodes(IMansionContext context, SearchQuery query, IEnumerable<Hit> hits)
{
// loop over all the hits
foreach (var hit in hits)
{
// create the record
var node = new Node();
// find the type mapping
var mapping = query.IndexDefinition.FindTypeMapping(hit.Type);
// map all its properties
mapping.MapProperties(context, hit, node);
// initialize the record
node.Initialize(context);
// return the mapped record
yield return node;
}
}
/// <summary>
/// Maps the given <paramref name="facets"/>.
/// </summary>
/// <param name="context">The <see cref="IMansionContext"/>.</param>
/// <param name="query">The executed <see cref="SearchQuery"/>.</param>
/// <param name="facets">The resulting <see cref="KeyValuePair{TKey,TValue}"/> containing the facets.</param>
/// <param name="set">The <see cref="RecordSet"/> to which to add the mapped facets.</param>
private static void MapFacets(IMansionContext context, SearchQuery query, IEnumerable<KeyValuePair<string, Facet>> facets, RecordSet set)
{
// check for null
if (facets == null)
return;
// loop over all the facets
foreach (var facet in facets)
{
// find the definition
var definition = query.Facets.Single(candidate => candidate.Definition.FriendlyName.Equals(facet.Key, StringComparison.OrdinalIgnoreCase)).Definition;
// allow the facet to map itself to a facet result
var result = facet.Value.Map(context, definition);
// add the facet result to the set
set.AddFacet(result);
}
}
#endregion
#region Properties
/// <summary>
/// Gets the name of this type.
/// </summary>
public string Name { get; private set; }
/// <summary>
/// Getsthe <see cref="PropertyMapping"/>s of this mapping.
/// </summary>
public IDictionary<string, PropertyMapping> Properties
{
get { return propertyMappings; }
}
#endregion
#region Private Fields
private readonly Dictionary<string, PropertyMapping> propertyMappings = new Dictionary<string, PropertyMapping>(StringComparer.OrdinalIgnoreCase);
#endregion
}
}
| |
// 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.Runtime.CompilerServices;
using System.IO;
using System.Collections;
using System.Globalization;
using System.Text;
using System.Threading;
using Xunit;
public class DirectoryInfo_GetFileSystemInfos_str
{
public static String s_strActiveBugNums = "28509";
public static String s_strClassMethod = "Directory.GetFiles()";
public static String s_strTFName = "GetFileSystemInfos _str.cs";
public static String s_strTFPath = Directory.GetCurrentDirectory();
[Fact]
public static void runTest()
{
//////////// Global Variables used for all tests
int iCountErrors = 0;
int iCountTestcases = 0;
String strLoc = "Loc_000oo";
String strValue = String.Empty;
String dirName = Path.GetRandomFileName();
try
{
///////////////////////// START TESTS ////////////////////////////
///////////////////////////////////////////////////////////////////
DirectoryInfo dir2;
FileSystemInfo[] fsArr;
if (Directory.Exists(dirName))
Directory.Delete(dirName, true);
// [] Should throw ArgumentNullException for null argument
//-----------------------------------------------------------------
strLoc = "Loc_477g8";
dir2 = new DirectoryInfo(".");
iCountTestcases++;
try
{
dir2.GetFileSystemInfos(null);
iCountErrors++;
printerr("Error_2988b! Expected exception not thrown");
}
catch (ArgumentNullException)
{
}
catch (Exception exc)
{
iCountErrors++;
printerr("Error_0707t! Incorrect exception thrown, exc==" + exc.ToString());
}
//-----------------------------------------------------------------
// [] ArgumentException for String.Empty
//-----------------------------------------------------------------
strLoc = "Loc_4yg7b";
dir2 = new DirectoryInfo(".");
iCountTestcases++;
try
{
FileSystemInfo[] strInfos = dir2.GetFileSystemInfos(String.Empty);
if (strInfos.Length != 0)
{
iCountErrors++;
printerr("Error_8ytbm! Unexpected number of file infos returned" + strInfos.Length);
}
}
catch (Exception exc)
{
iCountErrors++;
printerr("Error_2908y! Incorrect exception thrown, exc==" + exc.ToString());
}
//-----------------------------------------------------------------
if (Interop.IsWindows) // whitespace in names and periods at ends of search patterns is acceptable on Unix
{
// [] ArgumentException for all whitespace
//-----------------------------------------------------------------
strLoc = "Loc_1190x";
dir2 = new DirectoryInfo(".");
iCountTestcases++;
try
{
dir2.GetFileSystemInfos(Path.Combine("..ab ab.. .. abc..d", "abc.."));
iCountErrors++;
printerr("Error_2198y! Expected exception not thrown");
}
catch (ArgumentException)
{
}
catch (Exception exc)
{
iCountErrors++;
printerr("Error_17888! Incorrect exception thrown, exc==" + exc.ToString());
}
//-----------------------------------------------------------------
}
// [] Should return zero length array for an empty directory
//-----------------------------------------------------------------
strLoc = "Loc_4y982";
dir2 = Directory.CreateDirectory(dirName);
fsArr = dir2.GetFileSystemInfos();
iCountTestcases++;
if (fsArr.Length != 0)
{
iCountErrors++;
printerr("Error_207v7! Incorrect number of files returned");
}
//-----------------------------------------------------------------
// [] Create a directorystructure and try different searchcriterias
//-----------------------------------------------------------------
strLoc = "Loc_2398c";
dir2.CreateSubdirectory("TestDir1");
dir2.CreateSubdirectory("TestDir2");
dir2.CreateSubdirectory("TestDir3");
dir2.CreateSubdirectory("Test1Dir1");
dir2.CreateSubdirectory("Test1Dir2");
FileStream f1 = new FileInfo(Path.Combine(dir2.FullName, "TestFile1")).Create();
FileStream f2 = new FileInfo(Path.Combine(dir2.FullName, "TestFile2")).Create();
FileStream f3 = new FileInfo(Path.Combine(dir2.FullName, "TestFile3")).Create();
FileStream f4 = new FileInfo(Path.Combine(dir2.FullName, "Test1File1")).Create();
FileStream f5 = new FileInfo(Path.Combine(dir2.FullName, "Test1File2")).Create();
// [] Search criteria ending with '*'
iCountTestcases++;
fsArr = dir2.GetFileSystemInfos("TestFile*");
iCountTestcases++;
if (fsArr.Length != 3)
{
iCountErrors++;
printerr("Error_1yt75! Incorrect number of files returned");
}
String[] names = new String[fsArr.Length];
int i = 0;
foreach (FileSystemInfo f in fsArr)
names[i++] = f.Name;
if (!Interop.IsWindows) // test is expecting sorted order as provided by Windows
{
Array.Sort(names);
}
iCountTestcases++;
if (Array.IndexOf(names, "TestFile1") < 0)
{
iCountErrors++;
printerr("Error_3y775! Incorrect name==" + fsArr[0].Name);
}
iCountTestcases++;
if (Array.IndexOf(names, "TestFile2") < 0)
{
iCountErrors++;
printerr("Error_90885! Incorrect name==" + fsArr[1].Name);
}
iCountTestcases++;
if (Array.IndexOf(names, "TestFile3") < 0)
{
iCountErrors++;
printerr("Error_879by! Incorrect name==" + fsArr[2].Name);
}
// [] Search criteria is '*'
fsArr = dir2.GetFileSystemInfos("*");
iCountTestcases++;
if (fsArr.Length != 10)
{
iCountErrors++;
printerr("Error_t5792! Incorrect number of files==" + fsArr.Length);
}
names = new String[fsArr.Length];
i = 0;
foreach (FileSystemInfo f in fsArr)
names[i++] = f.Name;
if (!Interop.IsWindows) // test is expecting sorted order as provided by Windows
{
Array.Sort(names);
}
iCountTestcases++;
if (Array.IndexOf(names, "Test1Dir1") < 0)
{
iCountErrors++;
printerr("Error_4898v! Incorrect name==" + fsArr[0].Name);
}
iCountTestcases++;
if (Array.IndexOf(names, "Test1Dir2") < 0)
{
iCountErrors++;
printerr("Error_4598c! Incorrect name==" + fsArr[1].Name);
}
iCountTestcases++;
if (Array.IndexOf(names, "TestDir1") < 0)
{
iCountErrors++;
printerr("Error_209d8! Incorrect name==" + fsArr[2].Name);
}
iCountTestcases++;
if (Array.IndexOf(names, "TestDir2") < 0)
{
iCountErrors++;
printerr("Error_10vtu! Incorrect name==" + fsArr[3].Name);
}
iCountTestcases++;
if (Array.IndexOf(names, "TestDir3") < 0)
{
iCountErrors++;
printerr("Error_190vh! Incorrect name==" + fsArr[4].Name);
}
iCountTestcases++;
if (Array.IndexOf(names, "Test1File1") < 0)
{
iCountErrors++;
printerr("Error_4898v! Incorrect name==" + fsArr[5].Name);
}
iCountTestcases++;
if (Array.IndexOf(names, "Test1File2") < 0)
{
iCountErrors++;
printerr("Error_4598c! Incorrect name==" + fsArr[6].Name);
}
iCountTestcases++;
if (Array.IndexOf(names, "TestFile1") < 0)
{
iCountErrors++;
printerr("Error_209d8! Incorrect name==" + fsArr[7].Name);
}
iCountTestcases++;
if (Array.IndexOf(names, "TestFile2") < 0)
{
iCountErrors++;
printerr("Error_10vtu! Incorrect name==" + fsArr[8].Name);
}
iCountTestcases++;
if (Array.IndexOf(names, "TestFile3") < 0)
{
iCountErrors++;
printerr("Error_190vh! Incorrect name==" + fsArr[9].Name);
}
// [] Search criteria beginning with '*'
fsArr = dir2.GetFileSystemInfos("*2");
iCountTestcases++;
if (fsArr.Length != 4)
{
iCountErrors++;
printerr("Error_8019x! Incorrect number of files==" + fsArr.Length);
}
names = new String[fsArr.Length];
i = 0;
foreach (FileSystemInfo fs in fsArr)
names[i++] = fs.Name;
iCountTestcases++;
if (Array.IndexOf(names, "Test1Dir2") < 0)
{
iCountErrors++;
printerr("Error_247yg! Incorrect name==" + fsArr[0].Name);
}
iCountTestcases++;
if (Array.IndexOf(names, "TestDir2") < 0)
{
iCountErrors++;
printerr("Error_24gy7! Incorrect name==" + fsArr[1].Name);
}
iCountTestcases++;
if (Array.IndexOf(names, "Test1File2") < 0)
{
iCountErrors++;
printerr("Error_167yb! Incorrect name==" + fsArr[2].Name);
}
iCountTestcases++;
if (Array.IndexOf(names, "TestFile2") < 0)
{
iCountErrors++;
printerr("Error_49yb7! Incorrect name==" + fsArr[3].Name);
}
fsArr = dir2.GetFileSystemInfos("*Dir2");
iCountTestcases++;
if (fsArr.Length != 2)
{
iCountErrors++;
printerr("Error_948yv! Incorrect number of files==" + fsArr.Length);
}
names = new String[fsArr.Length];
i = 0;
foreach (FileSystemInfo fs in fsArr)
names[i++] = fs.Name;
iCountTestcases++;
if (Array.IndexOf(names, "Test1Dir2") < 0)
{
iCountErrors++;
printerr("Error_247yg! Incorrect name==" + fsArr[0].Name);
}
iCountTestcases++;
if (Array.IndexOf(names, "TestDir2") < 0)
{
iCountErrors++;
printerr("Error_24gy7! Incorrect name==" + fsArr[1].Name);
}
// [] Search criteria Beginning and ending with '*'
using (new FileInfo(Path.Combine(dir2.FullName, "AAABB")).Create())
{
Directory.CreateDirectory(Path.Combine(dir2.FullName, "aaabbcc"));
fsArr = dir2.GetFileSystemInfos("*BB*");
iCountTestcases++;
if (fsArr.Length != (Interop.IsWindows ? 2 : 1))
{
iCountErrors++;
printerr("Error_4y190! Incorrect number of files==" + fsArr.Length);
}
names = new String[fsArr.Length];
i = 0;
foreach (FileSystemInfo fs in fsArr)
names[i++] = fs.Name;
if (Interop.IsWindows)
{
iCountTestcases++;
if (Array.IndexOf(names, "aaabbcc") < 0)
{
iCountErrors++;
printerr("Error_956yb! Incorrect name==" + fsArr[0]);
foreach (FileSystemInfo s in fsArr)
Console.WriteLine(s.Name);
}
}
if (Array.IndexOf(names, "AAABB") < 0)
{
iCountErrors++;
printerr("Error_48yg7! Incorrect name==" + fsArr[1]);
foreach (FileSystemInfo s in fsArr)
Console.WriteLine(s.Name);
}
strLoc = "Loc_0001";
}
// [] Should not search on fullpath
// [] Search Criteria without match should return empty array
fsArr = dir2.GetFileSystemInfos("Directory");
if (fsArr.Length != 0)
{
iCountErrors++;
printerr("Error_209v7! Incorrect number of files==" + fsArr.Length);
}
using (new FileInfo(Path.Combine(dir2.FullName, "TestDir1", "Test.tmp")).Create())
{
fsArr = dir2.GetFileSystemInfos(Path.Combine("TestDir1", "*"));
if (fsArr.Length != 1)
{
printerr("Error_28gyb! Incorrect number of files");
}
}
f1.Dispose();
f2.Dispose();
f3.Dispose();
f4.Dispose();
f5.Dispose();
}
catch (Exception exc_general)
{
++iCountErrors;
Console.WriteLine("Error Err_8888yyy! strLoc==" + strLoc + ", exc_general==" + exc_general.ToString());
}
//// Finish Diagnostics
if (iCountErrors != 0)
{
Console.WriteLine("FAiL! " + s_strTFName + " ,iCountErrors==" + iCountErrors.ToString());
}
FailSafeDirectoryOperations.DeleteDirectory(dirName, true);
Assert.Equal(0, iCountErrors);
}
public static void printerr(String err, [CallerMemberName] string memberName = "", [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNumber = 0)
{
Console.WriteLine("ERROR: ({0}, {1}, {2}) {3}", memberName, filePath, lineNumber, err);
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="SettingsDialog.cs" company="None">
// Copyright (c) Brandon Wallace and Jesse Calhoun. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace TQVaultAE.GUI
{
using Properties;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Globalization;
using System.Windows.Forms;
using TQVaultData;
/// <summary>
/// Class for the Settings/Configuration Dialog
/// </summary>
internal partial class SettingsDialog : VaultForm
{
/// <summary>
/// Indicates whether the title screen will be skipped on startup
/// </summary>
private bool skipTitle;
/// <summary>
/// Save path for the vault files
/// </summary>
private string vaultPath;
/// <summary>
/// Indicates whether item copying is allowed
/// </summary>
private bool allowItemCopy;
/// <summary>
/// Indicates whether item editing is allowed
/// </summary>
private bool allowItemEdit;
/// <summary>
/// Indicates whether the last opened character will be loaded at startup
/// </summary>
private bool loadLastCharacter;
/// <summary>
/// Indicates whether the last opened vault will be loaded at startup
/// </summary>
private bool loadLastVault;
/// <summary>
/// Indicates whether the language will be auto detected
/// </summary>
private bool detectLanguage;
/// <summary>
/// The language we will be using.
/// </summary>
private string titanQuestLanguage;
/// <summary>
/// Indicates whether the game paths will be auto detected
/// </summary>
private bool detectGamePath;
/// <summary>
/// Titan Quest game path
/// </summary>
private string titanQuestPath;
/// <summary>
/// Immortal Throne game path
/// </summary>
private string immortalThronePath;
/// <summary>
/// Indicates whether custom maps have been enabled
/// </summary>
private bool enableMods;
/// <summary>
/// Current custom map
/// </summary>
private string customMap;
/// <summary>
/// Indicates whether we are loading all data files on startup
/// </summary>
private bool loadAllFiles;
/// <summary>
/// Indicates whether warning messages are suppressed
/// </summary>
private bool suppressWarnings;
/// <summary>
/// Indicates whether player items will be readonly.
/// </summary>
private bool playerReadonly;
/// <summary>
/// Indicates whether the vault path has been changed
/// </summary>
private bool vaultPathChanged;
/// <summary>
/// Indicates whether the play list filter has been changed
/// </summary>
private bool playerFilterChanged;
/// <summary>
/// Indicates that any configuration item has been changed
/// </summary>
private bool configurationChanged;
/// <summary>
/// Indicates that the UI setting has changed.
/// </summary>
private bool uiSettingChanged;
/// <summary>
/// Indicates that the settings have been loaded
/// </summary>
private bool settingsLoaded;
/// <summary>
/// Indicates that the language setting has been changed
/// </summary>
private bool languageChanged;
/// <summary>
/// Indicates that the game language has been changed
/// </summary>
private bool gamePathChanged;
/// <summary>
/// Indicates that the custom map selection has changed
/// </summary>
private bool customMapsChanged;
/// <summary>
/// Initializes a new instance of the SettingsDialog class.
/// </summary>
public SettingsDialog()
{
this.InitializeComponent();
this.vaultPathLabel.Text = Resources.SettingsLabel1;
this.languageLabel.Text = Resources.SettingsLabel2;
this.titanQuestPathLabel.Text = Resources.SettingsLabel3;
this.immortalThronePathLabel.Text = Resources.SettingsLabel4;
this.customMapLabel.Text = Resources.SettingsLabel5;
this.detectGamePathsCheckBox.Text = Resources.SettingsDetectGamePath;
this.detectLanguageCheckBox.Text = Resources.SettingsDetectLanguage;
this.enableCustomMapsCheckBox.Text = Resources.SettingsEnableMod;
this.toolTip.SetToolTip(this.enableCustomMapsCheckBox, Resources.SettingsEnableModTT);
this.skipTitleCheckBox.Text = Resources.SettingsSkipTitle;
this.toolTip.SetToolTip(this.skipTitleCheckBox, Resources.SettingsSkipTitleTT);
this.allowItemCopyCheckBox.Text = Resources.SettingsAllowCopy;
this.toolTip.SetToolTip(this.allowItemCopyCheckBox, Resources.SettingsAllowCopyTT);
this.allowItemEditCheckBox.Text = Resources.SettingsAllowEdit;
this.toolTip.SetToolTip(this.allowItemEditCheckBox, Resources.SettingsAllowEditTT);
this.loadLastCharacterCheckBox.Text = Resources.SettingsLoadChar;
this.toolTip.SetToolTip(this.loadLastCharacterCheckBox, Resources.SettingsLoadCharTT);
this.loadLastVaultCheckBox.Text = Resources.SettingsLoadVault;
this.toolTip.SetToolTip(this.loadLastVaultCheckBox, Resources.SettingsLoadVaultTT);
this.loadAllFilesCheckBox.Text = Resources.SettingsPreLoad;
this.toolTip.SetToolTip(this.loadAllFilesCheckBox, Resources.SettingsPreLoadTT);
this.suppressWarningsCheckBox.Text = Resources.SettingsNoWarning;
this.toolTip.SetToolTip(this.suppressWarningsCheckBox, Resources.SettingsNoWarningTT);
this.playerReadonlyCheckbox.Text = Resources.SettingsPlayerReadonly;
this.toolTip.SetToolTip(this.playerReadonlyCheckbox, Resources.SettingsPlayerReadonlyTT);
this.resetButton.Text = Resources.SettingsReset;
this.toolTip.SetToolTip(this.resetButton, Resources.SettingsResetTT);
this.cancelButton.Text = Resources.GlobalCancel;
this.okayButton.Text = Resources.GlobalOK;
this.Text = Resources.SettingsTitle;
this.DrawCustomBorder = true;
this.mapListComboBox.Items.Clear();
this.mapListComboBox.Items.Add(string.Empty);
string[] maps = TQData.GetCustomMapList(TQData.IsITInstalled);
if (maps != null && maps.Length > 0)
{
this.mapListComboBox.Items.AddRange(maps);
}
if (!IniProperties.ShowEditingCopyFeatures)
{
this.allowItemEditCheckBox.Visible = false;
this.allowItemCopyCheckBox.Visible = false;
}
}
/// <summary>
/// Gets a value indicating whether the game path has been changed
/// </summary>
public bool GamePathChanged
{
get
{
return this.gamePathChanged;
}
}
/// <summary>
/// Gets a value indicating whether the language setting has been changed
/// </summary>
public bool LanguageChanged
{
get
{
return this.languageChanged;
}
}
/// <summary>
/// Gets a value indicating whether the UI setting was changed.
/// </summary>
public bool UISettingChanged
{
get
{
return this.uiSettingChanged;
}
}
/// <summary>
/// Gets a value indicating whether the custom map selection has changed
/// </summary>
public bool CustomMapsChanged
{
get
{
return this.customMapsChanged;
}
}
/// <summary>
/// Gets a value indicating whether any configuration item has been changed
/// </summary>
public bool ConfigurationChanged
{
get
{
return this.configurationChanged;
}
}
/// <summary>
/// Gets a value indicating whether the vault save path has been changed
/// </summary>
public bool VaultPathChanged
{
get
{
return this.vaultPathChanged;
}
}
/// <summary>
/// Gets a value indicating whether the player list filter has been changed
/// </summary>
public bool PlayerFilterChanged
{
get
{
return this.playerFilterChanged;
}
}
/// <summary>
/// Gets the vault save path
/// </summary>
public string VaultPath
{
get
{
return this.vaultPath;
}
}
/// <summary>
/// Override of ScaleControl which supports font scaling.
/// </summary>
/// <param name="factor">SizeF for the scale factor</param>
/// <param name="specified">BoundsSpecified value.</param>
protected override void ScaleControl(SizeF factor, BoundsSpecified specified)
{
this.Font = new Font(this.Font.Name, this.Font.SizeInPoints * factor.Height, this.Font.Style);
base.ScaleControl(factor, specified);
}
/// <summary>
/// Handler for clicking the vault path browse button
/// </summary>
/// <param name="sender">sender object</param>
/// <param name="e">EventArgs data</param>
private void VaultPathBrowseButtonClick(object sender, EventArgs e)
{
this.folderBrowserDialog.Description = Resources.SettingsBrowseVault;
this.folderBrowserDialog.RootFolder = Environment.SpecialFolder.Desktop;
this.folderBrowserDialog.SelectedPath = this.vaultPath;
this.folderBrowserDialog.ShowDialog();
if (this.folderBrowserDialog.SelectedPath.Trim().ToUpperInvariant() != this.vaultPath.Trim().ToUpperInvariant())
{
this.vaultPath = this.folderBrowserDialog.SelectedPath.Trim().ToUpperInvariant();
this.vaultPathTextBox.Text = this.vaultPath.Trim().ToUpperInvariant();
this.vaultPathTextBox.Invalidate();
this.configurationChanged = true;
this.vaultPathChanged = true;
}
}
/// <summary>
/// Handler for clicking the reset button
/// </summary>
/// <param name="sender">sender object</param>
/// <param name="e">EventArgs data</param>
private void ResetButtonClick(object sender, EventArgs e)
{
if (this.configurationChanged)
{
this.LoadSettings();
this.UpdateDialogSettings();
this.Invalidate();
}
}
/// <summary>
/// Handler for clicking the skip title check box
/// </summary>
/// <param name="sender">sender object</param>
/// <param name="e">EventArgs data</param>
private void SkipTitleCheckBoxCheckedChanged(object sender, EventArgs e)
{
if (this.skipTitleCheckBox.Checked)
{
if (this.skipTitle == false)
{
this.skipTitle = true;
this.configurationChanged = true;
}
}
else
{
if (this.skipTitle == true)
{
this.skipTitle = false;
this.configurationChanged = true;
}
}
}
/// <summary>
/// Handler for loading this dialog box
/// </summary>
/// <param name="sender">sender object</param>
/// <param name="e">EventArgs data</param>
private void SettingsDialogLoad(object sender, EventArgs e)
{
this.settingsLoaded = false;
this.LoadSettings();
this.UpdateDialogSettings();
}
/// <summary>
/// Loads the settings from the config file
/// </summary>
private void LoadSettings()
{
this.skipTitle = Settings.Default.SkipTitle;
this.vaultPath = Settings.Default.VaultPath;
this.allowItemCopy = Settings.Default.AllowItemCopy;
this.allowItemEdit = Settings.Default.AllowItemEdit;
this.loadLastCharacter = Settings.Default.LoadLastCharacter;
this.loadLastVault = Settings.Default.LoadLastVault;
this.detectLanguage = Settings.Default.AutoDetectLanguage;
// Force English since there was some issue with getting the proper language setting.
if (Database.DB.GameLanguage == null)
{
this.titanQuestLanguage = "English";
}
else
{
this.titanQuestLanguage = Database.DB.GameLanguage;
}
this.detectGamePath = Settings.Default.AutoDetectGamePath;
this.titanQuestPath = TQData.TQPath;
this.immortalThronePath = TQData.ImmortalThronePath;
this.enableMods = Settings.Default.ModEnabled;
this.customMap = Settings.Default.CustomMap;
this.loadAllFiles = Settings.Default.LoadAllFiles;
this.suppressWarnings = Settings.Default.SuppressWarnings;
this.playerReadonly = Settings.Default.PlayerReadonly;
this.settingsLoaded = true;
this.configurationChanged = false;
this.vaultPathChanged = false;
this.playerFilterChanged = false;
this.languageChanged = false;
this.gamePathChanged = false;
this.uiSettingChanged = false;
}
/// <summary>
/// Updates the dialog settings display
/// </summary>
private void UpdateDialogSettings()
{
// Check to see that we can update things
if (!this.settingsLoaded)
{
return;
}
// Build language combo box
char delim = ',';
this.languageComboBox.Items.Clear();
// Read the languages from the config file
string val = Settings.Default.GameLanguages;
if (val.Length > 2)
{
string[] languages = val.Split(delim);
if (languages.Length > 0)
{
List<string> languageName = new List<string>();
foreach (string langCode in languages)
{
CultureInfo ci = new CultureInfo(langCode.ToUpperInvariant(), false);
languageName.Add(ci.DisplayName.ToString());
}
string[] listLanguages = new string[languageName.Count];
languageName.CopyTo(listLanguages);
Array.Sort(listLanguages);
this.languageComboBox.Items.AddRange(listLanguages);
}
else
{
// Reading failed so we default to English
this.languageComboBox.Items.Add("English");
}
}
this.vaultPathTextBox.Text = this.vaultPath;
this.skipTitleCheckBox.Checked = this.skipTitle;
this.allowItemEditCheckBox.Checked = this.allowItemEdit;
this.allowItemCopyCheckBox.Checked = this.allowItemCopy;
this.loadLastCharacterCheckBox.Checked = this.loadLastCharacter;
this.loadLastVaultCheckBox.Checked = this.loadLastVault;
this.detectLanguageCheckBox.Checked = this.detectLanguage;
this.detectGamePathsCheckBox.Checked = this.detectGamePath;
this.immortalThronePathTextBox.Text = this.immortalThronePath;
this.immortalThronePathTextBox.Enabled = !this.detectGamePath;
this.immortalThronePathBrowseButton.Enabled = !this.detectGamePath;
this.titanQuestPathTextBox.Text = this.titanQuestPath;
this.titanQuestPathTextBox.Enabled = !this.detectGamePath;
this.titanQuestPathBrowseButton.Enabled = !this.detectGamePath;
this.loadAllFilesCheckBox.Checked = this.loadAllFiles;
this.suppressWarningsCheckBox.Checked = this.suppressWarnings;
this.playerReadonlyCheckbox.Checked = this.playerReadonly;
this.enableCustomMapsCheckBox.Checked = this.enableMods;
int ind = this.mapListComboBox.FindStringExact(this.customMap);
if (ind != -1)
{
this.mapListComboBox.SelectedIndex = ind;
}
this.mapListComboBox.Enabled = this.enableMods;
ind = this.languageComboBox.FindString(this.titanQuestLanguage);
if (ind != -1)
{
this.languageComboBox.SelectedIndex = ind;
}
this.languageComboBox.Enabled = !this.detectLanguage;
}
/// <summary>
/// Handler for clicking the OK button
/// </summary>
/// <param name="sender">sender object</param>
/// <param name="e">EventArgs data</param>
private void OkayButtonClick(object sender, EventArgs e)
{
if (this.configurationChanged)
{
Settings.Default.SkipTitle = this.skipTitle;
Settings.Default.VaultPath = this.vaultPath;
Settings.Default.AllowItemCopy = this.allowItemCopy;
Settings.Default.AllowItemEdit = this.allowItemEdit;
Settings.Default.LoadLastCharacter = this.loadLastCharacter;
Settings.Default.LoadLastVault = this.loadLastVault;
Settings.Default.AutoDetectLanguage = this.detectLanguage;
Settings.Default.TQLanguage = this.titanQuestLanguage;
Settings.Default.AutoDetectGamePath = this.detectGamePath;
Settings.Default.TQITPath = this.immortalThronePath;
Settings.Default.TQPath = this.titanQuestPath;
Settings.Default.ModEnabled = this.enableMods;
Settings.Default.CustomMap = this.customMap;
Settings.Default.LoadAllFiles = this.loadAllFiles;
Settings.Default.SuppressWarnings = this.suppressWarnings;
Settings.Default.PlayerReadonly = this.playerReadonly;
}
}
/// <summary>
/// Handler for clicking the allow item editing check box
/// </summary>
/// <param name="sender">sender object</param>
/// <param name="e">EventArgs data</param>
private void AllowItemEditCheckBoxCheckedChanged(object sender, EventArgs e)
{
if (this.allowItemEditCheckBox.Checked)
{
if (this.allowItemEdit == false)
{
this.allowItemEdit = true;
this.configurationChanged = true;
}
}
else
{
if (this.allowItemEdit == true)
{
this.allowItemEdit = false;
this.configurationChanged = true;
}
}
}
/// <summary>
/// Handler for clicking the allow item copy check box
/// </summary>
/// <param name="sender">sender object</param>
/// <param name="e">EventArgs data</param>
private void AllowItemCopyCheckBoxCheckedChanged(object sender, EventArgs e)
{
if (this.allowItemCopyCheckBox.Checked)
{
if (this.allowItemCopy == false)
{
this.allowItemCopy = true;
this.configurationChanged = true;
}
}
else
{
if (this.allowItemCopy == true)
{
this.allowItemCopy = false;
this.configurationChanged = true;
}
}
}
/// <summary>
/// Handler for clicking the load last character check box
/// </summary>
/// <param name="sender">sender object</param>
/// <param name="e">EventArgs data</param>
private void LoadLastCharacterCheckBoxCheckedChanged(object sender, EventArgs e)
{
if (this.loadLastCharacterCheckBox.Checked)
{
if (this.loadLastCharacter == false)
{
this.loadLastCharacter = true;
this.configurationChanged = true;
}
}
else
{
if (this.loadLastCharacter == true)
{
this.loadLastCharacter = false;
this.configurationChanged = true;
}
}
}
/// <summary>
/// Handler for clicking the load last vault check box
/// </summary>
/// <param name="sender">sender object</param>
/// <param name="e">EventArgs data</param>
private void LoadLastVaultCheckBoxCheckedChanged(object sender, EventArgs e)
{
if (this.loadLastVaultCheckBox.Checked)
{
if (this.loadLastVault == false)
{
this.loadLastVault = true;
this.configurationChanged = true;
}
}
else
{
if (this.loadLastVault == true)
{
this.loadLastVault = false;
this.configurationChanged = true;
}
}
}
/// <summary>
/// Handler for clicking the detect language check box
/// </summary>
/// <param name="sender">sender object</param>
/// <param name="e">EventArgs data</param>
private void DetectLanguageCheckBoxCheckedChanged(object sender, EventArgs e)
{
if (this.detectLanguageCheckBox.Checked)
{
if (this.detectLanguage == false)
{
this.detectLanguage = true;
this.languageComboBox.Enabled = false;
this.configurationChanged = true;
// Force TQVault to restart to autodetect the language
this.languageChanged = true;
}
}
else
{
if (this.detectLanguage == true)
{
this.detectLanguage = false;
this.languageComboBox.Enabled = true;
this.configurationChanged = true;
}
}
}
/// <summary>
/// Handler for clicking the detect game paths check box
/// </summary>
/// <param name="sender">sender object</param>
/// <param name="e">EventArgs data</param>
private void DetectGamePathsCheckBoxCheckedChanged(object sender, EventArgs e)
{
if (this.detectGamePathsCheckBox.Checked)
{
if (this.detectGamePath == false)
{
this.detectGamePath = true;
this.immortalThronePathTextBox.Enabled = false;
this.titanQuestPathTextBox.Enabled = false;
this.titanQuestPathBrowseButton.Enabled = false;
this.immortalThronePathBrowseButton.Enabled = false;
this.configurationChanged = true;
// Force TQVault to restart to autodetect the game path
this.gamePathChanged = true;
}
}
else
{
if (this.detectGamePath == true)
{
this.detectGamePath = false;
this.immortalThronePathTextBox.Enabled = true;
this.titanQuestPathTextBox.Enabled = true;
this.titanQuestPathBrowseButton.Enabled = true;
this.immortalThronePathBrowseButton.Enabled = true;
this.configurationChanged = true;
}
}
}
/// <summary>
/// Handler for changing the language selection
/// </summary>
/// <param name="sender">sender object</param>
/// <param name="e">EventArgs data</param>
private void LanguageComboBoxSelectedIndexChanged(object sender, EventArgs e)
{
// There was some problem getting the game language so we ignore changing it.
if (Database.DB.GameLanguage == null)
{
return;
}
this.titanQuestLanguage = this.languageComboBox.SelectedItem.ToString();
if (this.titanQuestLanguage.ToUpperInvariant() != Database.DB.GameLanguage.ToUpperInvariant())
{
this.languageChanged = true;
}
this.configurationChanged = true;
}
/// <summary>
/// Handler for leaving the vault text box
/// </summary>
/// <param name="sender">sender object</param>
/// <param name="e">EventArgs data</param>
private void VaultPathTextBoxLeave(object sender, EventArgs e)
{
if (this.vaultPath.ToUpperInvariant() != this.vaultPathTextBox.Text.Trim().ToUpperInvariant())
{
this.vaultPath = this.vaultPathTextBox.Text.Trim();
this.vaultPathTextBox.Invalidate();
this.configurationChanged = true;
this.vaultPathChanged = true;
}
}
/// <summary>
/// Handler for leaving the Titan Quest game path text box
/// </summary>
/// <param name="sender">sender object</param>
/// <param name="e">EventArgs data</param>
private void TitanQuestPathTextBoxLeave(object sender, EventArgs e)
{
if (this.titanQuestPath.ToUpperInvariant() != this.titanQuestPathTextBox.Text.Trim().ToUpperInvariant())
{
this.titanQuestPath = this.titanQuestPathTextBox.Text.Trim();
this.titanQuestPathTextBox.Invalidate();
this.configurationChanged = true;
this.gamePathChanged = true;
}
}
/// <summary>
/// Handler for leaving the Immortal Throne game path text box
/// </summary>
/// <param name="sender">sender object</param>
/// <param name="e">EventArgs data</param>
private void ImmortalThronePathTextBoxLeave(object sender, EventArgs e)
{
if (this.immortalThronePath.ToUpperInvariant() != this.immortalThronePathTextBox.Text.Trim().ToUpperInvariant())
{
this.immortalThronePath = this.immortalThronePathTextBox.Text.Trim();
this.immortalThronePathTextBox.Invalidate();
this.configurationChanged = true;
this.gamePathChanged = true;
}
}
/// <summary>
/// Handler for clicking the Titan Quest game path browse button
/// </summary>
/// <param name="sender">sender object</param>
/// <param name="e">EventArgs data</param>
private void TitanQuestPathBrowseButtonClick(object sender, EventArgs e)
{
this.folderBrowserDialog.Description = Resources.SettingsBrowseTQ;
this.folderBrowserDialog.RootFolder = Environment.SpecialFolder.MyComputer;
this.folderBrowserDialog.SelectedPath = this.titanQuestPath;
this.folderBrowserDialog.ShowDialog();
if (this.folderBrowserDialog.SelectedPath.Trim().ToUpperInvariant() != this.titanQuestPath.Trim().ToUpperInvariant())
{
this.titanQuestPath = this.folderBrowserDialog.SelectedPath.Trim().ToUpperInvariant();
this.titanQuestPathTextBox.Text = this.titanQuestPath.Trim().ToUpperInvariant();
this.titanQuestPathTextBox.Invalidate();
this.configurationChanged = true;
this.gamePathChanged = true;
}
}
/// <summary>
/// Handler for clicking the Immortal Throne game path browse button
/// </summary>
/// <param name="sender">sender object</param>
/// <param name="e">EventArgs data</param>
private void ImmortalThronePathBrowseButtonClick(object sender, EventArgs e)
{
this.folderBrowserDialog.Description = Resources.SettingsBrowseIT;
this.folderBrowserDialog.RootFolder = Environment.SpecialFolder.MyComputer;
this.folderBrowserDialog.SelectedPath = this.immortalThronePath;
this.folderBrowserDialog.ShowDialog();
if (this.folderBrowserDialog.SelectedPath.Trim().ToUpperInvariant() != this.immortalThronePath.Trim().ToUpperInvariant())
{
this.immortalThronePath = this.folderBrowserDialog.SelectedPath.Trim().ToUpperInvariant();
this.immortalThronePathTextBox.Text = this.immortalThronePath.Trim().ToUpperInvariant();
this.immortalThronePathTextBox.Invalidate();
this.configurationChanged = true;
this.gamePathChanged = true;
}
}
/// <summary>
/// Handler for clicking enable custom maps
/// </summary>
/// <param name="sender">sender object</param>
/// <param name="e">EventArgs data</param>
private void EnableCustomMapsCheckBoxCheckedChanged(object sender, EventArgs e)
{
if (this.enableCustomMapsCheckBox.Checked)
{
if (this.enableMods == false)
{
this.enableMods = true;
this.configurationChanged = true;
this.customMapsChanged = true;
this.mapListComboBox.Enabled = true;
}
}
else
{
if (this.enableMods == true)
{
this.enableMods = false;
this.configurationChanged = true;
this.customMapsChanged = true;
this.mapListComboBox.Enabled = false;
}
}
}
/// <summary>
/// Handler for changing the selected custom map
/// </summary>
/// <param name="sender">sender object</param>
/// <param name="e">EventArgs data</param>
private void MapListComboBoxSelectedIndexChanged(object sender, EventArgs e)
{
if (!this.settingsLoaded)
{
return;
}
if (this.mapListComboBox.SelectedItem.ToString() != Settings.Default.CustomMap)
{
this.customMap = this.mapListComboBox.SelectedItem.ToString();
this.configurationChanged = true;
this.customMapsChanged = true;
}
}
/// <summary>
/// Handler for clicking the load all files check box
/// </summary>
/// <param name="sender">sender object</param>
/// <param name="e">EventArgs data</param>
private void LoadAllFilesCheckBoxCheckedChanged(object sender, EventArgs e)
{
if (this.loadAllFilesCheckBox.Checked)
{
if (this.loadAllFiles == false)
{
this.loadAllFiles = true;
this.configurationChanged = true;
}
}
else
{
if (this.loadAllFiles == true)
{
this.loadAllFiles = false;
this.configurationChanged = true;
}
}
}
/// <summary>
/// Handler for clicking the suppress warnings check box
/// </summary>
/// <param name="sender">sender object</param>
/// <param name="e">EventArgs data</param>
private void SuppressWarningsCheckBoxCheckedChanged(object sender, EventArgs e)
{
if (this.suppressWarningsCheckBox.Checked)
{
if (this.suppressWarnings == false)
{
this.suppressWarnings = true;
this.configurationChanged = true;
}
}
else
{
if (this.suppressWarnings == true)
{
this.suppressWarnings = false;
this.configurationChanged = true;
}
}
}
private void PlayerReadonlyCheckboxCheckedChanged(object sender, EventArgs e)
{
if (this.playerReadonlyCheckbox.Checked)
{
if (this.playerReadonly == false)
{
this.playerReadonly = true;
this.configurationChanged = true;
}
}
else
{
if (this.playerReadonly == true)
{
this.playerReadonly = false;
this.configurationChanged = true;
}
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.Azure.Devices.Client
{
using System;
using System.ComponentModel;
using System.Security;
using System.Threading;
using Microsoft.Win32.SafeHandles;
// IOThreadTimer has several characterstics that are important for performance:
// - Timers that expire benefit from being scheduled to run on IO threads using IOThreadScheduler.Schedule.
// - The timer "waiter" thread thread is only allocated if there are set timers.
// - The timer waiter thread itself is an IO thread, which allows it to go away if there is no need for it,
// and allows it to be reused for other purposes.
// - After the timer count goes to zero, the timer waiter thread remains active for a bounded amount
// of time to wait for additional timers to be set.
// - Timers are stored in an array-based priority queue to reduce the amount of time spent in updates, and
// to always provide O(1) access to the minimum timer (the first one that will expire).
// - The standard textbook priority queue data structure is extended to allow efficient Delete in addition to
// DeleteMin for efficient handling of canceled timers.
// - Timers that are typically set, then immediately canceled (such as a retry timer,
// or a flush timer), are tracked separately from more stable timers, to avoid having
// to update the waitable timer in the typical case when a timer is canceled. Whether
// a timer instance follows this pattern is specified when the timer is constructed.
// - Extending a timer by a configurable time delta (maxSkew) does not involve updating the
// waitable timer, or taking a lock.
// - Timer instances are relatively cheap. They share "heavy" resources like the waiter thread and
// waitable timer handle.
// - Setting or canceling a timer does not typically involve any allocations.
class IOThreadTimer
{
const int maxSkewInMillisecondsDefault = 100;
static long systemTimeResolutionTicks = -1;
Action<object> callback;
object callbackState;
long dueTime;
int index;
long maxSkew;
TimerGroup timerGroup;
public IOThreadTimer(Action<object> callback, object callbackState, bool isTypicallyCanceledShortlyAfterBeingSet)
: this(callback, callbackState, isTypicallyCanceledShortlyAfterBeingSet, maxSkewInMillisecondsDefault)
{
}
public IOThreadTimer(Action<object> callback, object callbackState, bool isTypicallyCanceledShortlyAfterBeingSet, int maxSkewInMilliseconds)
{
this.callback = callback;
this.callbackState = callbackState;
this.maxSkew = Ticks.FromMilliseconds(maxSkewInMilliseconds);
this.timerGroup =
(isTypicallyCanceledShortlyAfterBeingSet ? TimerManager.Value.VolatileTimerGroup : TimerManager.Value.StableTimerGroup);
}
public static long SystemTimeResolutionTicks
{
get
{
if (IOThreadTimer.systemTimeResolutionTicks == -1)
{
IOThreadTimer.systemTimeResolutionTicks = GetSystemTimeResolution();
}
return IOThreadTimer.systemTimeResolutionTicks;
}
}
[Fx.Tag.SecurityNote(Critical = "Calls critical method GetSystemTimeAdjustment", Safe = "method is a SafeNativeMethod")]
static long GetSystemTimeResolution()
{
int dummyAdjustment;
uint increment;
uint dummyAdjustmentDisabled;
if (UnsafeNativeMethods.GetSystemTimeAdjustment(out dummyAdjustment, out increment, out dummyAdjustmentDisabled) != 0)
{
return (long)increment;
}
// Assume the default, which is around 15 milliseconds.
return 15 * TimeSpan.TicksPerMillisecond;
}
public bool Cancel()
{
return TimerManager.Value.Cancel(this);
}
public void SetIfValid(TimeSpan timeFromNow)
{
if (TimeSpan.Zero < timeFromNow && timeFromNow < TimeSpan.MaxValue)
{
this.Set(timeFromNow);
}
}
public void Set(TimeSpan timeFromNow)
{
if (timeFromNow == TimeSpan.MaxValue)
{
throw Fx.Exception.Argument("timeFromNow", CommonResources.IOThreadTimerCannotAcceptMaxTimeSpan);
}
SetAt(Ticks.Add(Ticks.Now, Ticks.FromTimeSpan(timeFromNow)));
}
public void Set(int millisecondsFromNow)
{
SetAt(Ticks.Add(Ticks.Now, Ticks.FromMilliseconds(millisecondsFromNow)));
}
public void SetAt(long newDueTimeInTicks)
{
if (newDueTimeInTicks >= TimeSpan.MaxValue.Ticks || newDueTimeInTicks < 0)
{
throw Fx.Exception.ArgumentOutOfRange(
"newDueTime",
newDueTimeInTicks,
CommonResources.GetString(CommonResources.ArgumentOutOfRange, 0, TimeSpan.MaxValue.Ticks - 1));
}
TimerManager.Value.Set(this, newDueTimeInTicks);
}
[Fx.Tag.SynchronizationObject(Blocking = false, Scope = Fx.Tag.Strings.AppDomain)]
class TimerManager : IDisposable
{
const long maxTimeToWaitForMoreTimers = 1000 * TimeSpan.TicksPerMillisecond;
[Fx.Tag.Queue(typeof(IOThreadTimer), Scope = Fx.Tag.Strings.AppDomain, StaleElementsRemovedImmediately = true)]
static TimerManager value = new TimerManager();
Action<object> onWaitCallback;
TimerGroup stableTimerGroup;
TimerGroup volatileTimerGroup;
[Fx.Tag.SynchronizationObject(Blocking = false)]
WaitableTimer[] waitableTimers;
bool waitScheduled;
public TimerManager()
{
this.onWaitCallback = new Action<object>(OnWaitCallback);
this.stableTimerGroup = new TimerGroup();
this.volatileTimerGroup = new TimerGroup();
this.waitableTimers = new WaitableTimer[] { this.stableTimerGroup.WaitableTimer, this.volatileTimerGroup.WaitableTimer };
}
object ThisLock
{
get { return this; }
}
public static TimerManager Value
{
get
{
return TimerManager.value;
}
}
public TimerGroup StableTimerGroup
{
get
{
return this.stableTimerGroup;
}
}
public TimerGroup VolatileTimerGroup
{
get
{
return this.volatileTimerGroup;
}
}
public void Set(IOThreadTimer timer, long dueTime)
{
long timeDiff = dueTime - timer.dueTime;
if (timeDiff < 0)
{
timeDiff = -timeDiff;
}
if (timeDiff > timer.maxSkew)
{
lock (ThisLock)
{
TimerGroup timerGroup = timer.timerGroup;
TimerQueue timerQueue = timerGroup.TimerQueue;
if (timer.index > 0)
{
if (timerQueue.UpdateTimer(timer, dueTime))
{
UpdateWaitableTimer(timerGroup);
}
}
else
{
if (timerQueue.InsertTimer(timer, dueTime))
{
UpdateWaitableTimer(timerGroup);
if (timerQueue.Count == 1)
{
EnsureWaitScheduled();
}
}
}
}
}
}
public bool Cancel(IOThreadTimer timer)
{
lock (ThisLock)
{
if (timer.index > 0)
{
TimerGroup timerGroup = timer.timerGroup;
TimerQueue timerQueue = timerGroup.TimerQueue;
timerQueue.DeleteTimer(timer);
if (timerQueue.Count > 0)
{
UpdateWaitableTimer(timerGroup);
}
else
{
TimerGroup otherTimerGroup = GetOtherTimerGroup(timerGroup);
if (otherTimerGroup.TimerQueue.Count == 0)
{
long now = Ticks.Now;
long thisGroupRemainingTime = timerGroup.WaitableTimer.DueTime - now;
long otherGroupRemainingTime = otherTimerGroup.WaitableTimer.DueTime - now;
if (thisGroupRemainingTime > maxTimeToWaitForMoreTimers &&
otherGroupRemainingTime > maxTimeToWaitForMoreTimers)
{
timerGroup.WaitableTimer.Set(Ticks.Add(now, maxTimeToWaitForMoreTimers));
}
}
}
return true;
}
else
{
return false;
}
}
}
void EnsureWaitScheduled()
{
if (!this.waitScheduled)
{
ScheduleWait();
}
}
TimerGroup GetOtherTimerGroup(TimerGroup timerGroup)
{
if (object.ReferenceEquals(timerGroup, this.volatileTimerGroup))
{
return this.stableTimerGroup;
}
else
{
return this.volatileTimerGroup;
}
}
void OnWaitCallback(object state)
{
WaitHandle.WaitAny(this.waitableTimers);
long now = Ticks.Now;
lock (ThisLock)
{
this.waitScheduled = false;
ScheduleElapsedTimers(now);
ReactivateWaitableTimers();
ScheduleWaitIfAnyTimersLeft();
}
}
void ReactivateWaitableTimers()
{
ReactivateWaitableTimer(this.stableTimerGroup);
ReactivateWaitableTimer(this.volatileTimerGroup);
}
static void ReactivateWaitableTimer(TimerGroup timerGroup)
{
TimerQueue timerQueue = timerGroup.TimerQueue;
if (timerQueue.Count > 0)
{
timerGroup.WaitableTimer.Set(timerQueue.MinTimer.dueTime);
}
else
{
timerGroup.WaitableTimer.Set(long.MaxValue);
}
}
void ScheduleElapsedTimers(long now)
{
ScheduleElapsedTimers(this.stableTimerGroup, now);
ScheduleElapsedTimers(this.volatileTimerGroup, now);
}
static void ScheduleElapsedTimers(TimerGroup timerGroup, long now)
{
TimerQueue timerQueue = timerGroup.TimerQueue;
while (timerQueue.Count > 0)
{
IOThreadTimer timer = timerQueue.MinTimer;
long timeDiff = timer.dueTime - now;
if (timeDiff <= timer.maxSkew)
{
timerQueue.DeleteMinTimer();
ActionItem.Schedule(timer.callback, timer.callbackState);
}
else
{
break;
}
}
}
void ScheduleWait()
{
ActionItem.Schedule(this.onWaitCallback, null);
this.waitScheduled = true;
}
void ScheduleWaitIfAnyTimersLeft()
{
if (this.stableTimerGroup.TimerQueue.Count > 0 ||
this.volatileTimerGroup.TimerQueue.Count > 0)
{
ScheduleWait();
}
}
static void UpdateWaitableTimer(TimerGroup timerGroup)
{
WaitableTimer waitableTimer = timerGroup.WaitableTimer;
IOThreadTimer minTimer = timerGroup.TimerQueue.MinTimer;
long timeDiff = waitableTimer.DueTime - minTimer.dueTime;
if (timeDiff < 0)
{
timeDiff = -timeDiff;
}
if (timeDiff > minTimer.maxSkew)
{
waitableTimer.Set(minTimer.dueTime);
}
}
public void Dispose()
{
this.stableTimerGroup.Dispose();
this.volatileTimerGroup.Dispose();
GC.SuppressFinalize(this);
}
}
class TimerGroup : IDisposable
{
TimerQueue timerQueue;
WaitableTimer waitableTimer;
public TimerGroup()
{
this.waitableTimer = new WaitableTimer();
this.waitableTimer.Set(long.MaxValue);
this.timerQueue = new TimerQueue();
}
public TimerQueue TimerQueue
{
get
{
return this.timerQueue;
}
}
public WaitableTimer WaitableTimer
{
get
{
return this.waitableTimer;
}
}
public void Dispose()
{
this.waitableTimer.Dispose();
GC.SuppressFinalize(this);
}
}
class TimerQueue
{
int count;
IOThreadTimer[] timers;
public TimerQueue()
{
this.timers = new IOThreadTimer[4];
}
public int Count
{
get { return count; }
}
public IOThreadTimer MinTimer
{
get
{
Fx.Assert(this.count > 0, "Should have at least one timer in our queue.");
return timers[1];
}
}
public void DeleteMinTimer()
{
IOThreadTimer minTimer = this.MinTimer;
DeleteMinTimerCore();
minTimer.index = 0;
minTimer.dueTime = 0;
}
public void DeleteTimer(IOThreadTimer timer)
{
int index = timer.index;
Fx.Assert(index > 0, "");
Fx.Assert(index <= this.count, "");
IOThreadTimer[] tempTimers = this.timers;
for (; ; )
{
int parentIndex = index / 2;
if (parentIndex >= 1)
{
IOThreadTimer parentTimer = tempTimers[parentIndex];
tempTimers[index] = parentTimer;
parentTimer.index = index;
}
else
{
break;
}
index = parentIndex;
}
timer.index = 0;
timer.dueTime = 0;
tempTimers[1] = null;
DeleteMinTimerCore();
}
public bool InsertTimer(IOThreadTimer timer, long dueTime)
{
Fx.Assert(timer.index == 0, "Timer should not have an index.");
IOThreadTimer[] tempTimers = this.timers;
int index = this.count + 1;
if (index == tempTimers.Length)
{
tempTimers = new IOThreadTimer[tempTimers.Length * 2];
Array.Copy(this.timers, tempTimers, this.timers.Length);
this.timers = tempTimers;
}
this.count = index;
if (index > 1)
{
for (; ; )
{
int parentIndex = index / 2;
if (parentIndex == 0)
{
break;
}
IOThreadTimer parent = tempTimers[parentIndex];
if (parent.dueTime > dueTime)
{
tempTimers[index] = parent;
parent.index = index;
index = parentIndex;
}
else
{
break;
}
}
}
tempTimers[index] = timer;
timer.index = index;
timer.dueTime = dueTime;
return index == 1;
}
public bool UpdateTimer(IOThreadTimer timer, long newDueTime)
{
int index = timer.index;
IOThreadTimer[] tempTimers = this.timers;
int tempCount = this.count;
Fx.Assert(index > 0, "");
Fx.Assert(index <= tempCount, "");
int parentIndex = index / 2;
if (parentIndex == 0 ||
tempTimers[parentIndex].dueTime <= newDueTime)
{
int leftChildIndex = index * 2;
if (leftChildIndex > tempCount ||
tempTimers[leftChildIndex].dueTime >= newDueTime)
{
int rightChildIndex = leftChildIndex + 1;
if (rightChildIndex > tempCount ||
tempTimers[rightChildIndex].dueTime >= newDueTime)
{
timer.dueTime = newDueTime;
return index == 1;
}
}
}
DeleteTimer(timer);
InsertTimer(timer, newDueTime);
return true;
}
void DeleteMinTimerCore()
{
int currentCount = this.count;
if (currentCount == 1)
{
this.count = 0;
this.timers[1] = null;
}
else
{
IOThreadTimer[] tempTimers = this.timers;
IOThreadTimer lastTimer = tempTimers[currentCount];
this.count = --currentCount;
int index = 1;
for (; ; )
{
int leftChildIndex = index * 2;
if (leftChildIndex > currentCount)
{
break;
}
int childIndex;
IOThreadTimer child;
if (leftChildIndex < currentCount)
{
IOThreadTimer leftChild = tempTimers[leftChildIndex];
int rightChildIndex = leftChildIndex + 1;
IOThreadTimer rightChild = tempTimers[rightChildIndex];
if (rightChild.dueTime < leftChild.dueTime)
{
child = rightChild;
childIndex = rightChildIndex;
}
else
{
child = leftChild;
childIndex = leftChildIndex;
}
}
else
{
childIndex = leftChildIndex;
child = tempTimers[childIndex];
}
if (lastTimer.dueTime > child.dueTime)
{
tempTimers[index] = child;
child.index = index;
}
else
{
break;
}
index = childIndex;
if (leftChildIndex >= currentCount)
{
break;
}
}
tempTimers[index] = lastTimer;
lastTimer.index = index;
tempTimers[currentCount + 1] = null;
}
}
}
[Fx.Tag.SynchronizationPrimitive(Fx.Tag.BlocksUsing.NonBlocking)]
class WaitableTimer : WaitHandle
{
long dueTime;
[Fx.Tag.SecurityNote(Critical = "Call the critical CreateWaitableTimer method in TimerHelper",
Safe = "Doesn't leak information or resources")]
public WaitableTimer()
{
#if WINDOWS_UWP
dueTime = 0;
throw new NotImplementedException();
#else
this.SafeWaitHandle = TimerHelper.CreateWaitableTimer();
#endif
}
public long DueTime
{
get { return this.dueTime; }
}
[Fx.Tag.SecurityNote(Critical = "Call the critical Set method in TimerHelper",
Safe = "Doesn't leak information or resources")]
public void Set(long newDueTime)
{
this.dueTime = TimerHelper.Set(this.SafeWaitHandle, newDueTime);
}
[Fx.Tag.SecurityNote(Critical = "Provides a set of unsafe methods used to work with the WaitableTimer")]
[SecurityCritical]
static class TimerHelper
{
public static unsafe SafeWaitHandle CreateWaitableTimer()
{
SafeWaitHandle handle = UnsafeNativeMethods.CreateWaitableTimer(IntPtr.Zero, false, null);
if (handle.IsInvalid)
{
Exception exception = new Win32Exception();
handle.SetHandleAsInvalid();
throw Fx.Exception.AsError(exception);
}
return handle;
}
public static unsafe long Set(SafeWaitHandle timer, long dueTime)
{
if (!UnsafeNativeMethods.SetWaitableTimer(timer, ref dueTime, 0, IntPtr.Zero, IntPtr.Zero, false))
{
throw Fx.Exception.AsError(new Win32Exception());
}
return dueTime;
}
}
}
}
}
| |
/*-
* Copyright (c) 2009, 2020 Oracle and/or its affiliates. All rights reserved.
*
* See the file LICENSE for license information.
*
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;
using BerkeleyDB;
using NUnit.Framework;
namespace CsharpAPITest
{
public class Configuration
{
public static Random random = new Random();
/*
* Configure the value with data in xml and return true or
* false to indicate if the value is configured. If there
* is no testing data and it is optional, return false. If
* there is no testing data in xml and it is compulsory,
* ConfigNotFoundException will be thrown. If any testing
* data is provided, the value will be set by the testing
* data and true will be returned.
*/
#region Config
public static void ConfigAckPolicy(XmlElement xmlElem,
string name, ref AckPolicy ackPolicy, bool compulsory)
{
XmlNode xmlNode = XMLReader.GetNode(xmlElem,
name);
if (xmlNode == null && compulsory == true)
throw new ConfigNotFoundException(name);
else if (xmlNode != null)
{
string policy = xmlNode.InnerText;
if (policy == "ALL")
ackPolicy = AckPolicy.ALL;
else if (policy == "ALL_PEERS")
ackPolicy = AckPolicy.ALL_PEERS;
else if (policy == "NONE")
ackPolicy = AckPolicy.NONE;
else if (policy == "ONE")
ackPolicy = AckPolicy.ONE;
else if (policy == "ONE_PEER")
ackPolicy = AckPolicy.ONE_PEER;
else if (policy == "QUORUM")
ackPolicy = AckPolicy.QUORUM;
else
throw new InvalidConfigException(name);
}
}
public static bool ConfigBool(XmlElement xmlElem,
string name, ref bool value, bool compulsory)
{
XmlNode xmlNode;
xmlNode = XMLReader.GetNode(xmlElem, name);
if (xmlNode == null && compulsory == false)
return false;
else if (xmlNode == null && compulsory == true)
throw new ConfigNotFoundException(name);
value = bool.Parse(xmlNode.InnerText);
return true;
}
public static bool ConfigByteOrder(XmlElement xmlElem,
string name, ref ByteOrder byteOrder, bool compulsory)
{
XmlNode xmlNode;
xmlNode = XMLReader.GetNode(xmlElem, name);
if (xmlNode == null && compulsory == false)
return false;
else if (xmlNode == null && compulsory == true)
throw new ConfigNotFoundException(name);
byteOrder = ByteOrder.FromConst(
int.Parse(xmlNode.InnerText));
return true;
}
public static bool ConfigByteMatrix(XmlElement xmlElem,
string name, ref byte[,] byteMatrix, bool compulsory)
{
int i, j, matrixLen;
XmlNode xmlNode = XMLReader.GetNode(xmlElem, name);
if (xmlNode == null && compulsory == false)
return false;
else if (xmlNode == null && compulsory == true)
throw new ConfigNotFoundException(name);
matrixLen = xmlNode.ChildNodes.Count;
byte[,] matrix = new byte[matrixLen, matrixLen];
for (i = 0; i < matrixLen; i++)
{
if (xmlNode.ChildNodes[i].ChildNodes.Count != matrixLen)
throw new ConfigNotFoundException(name);
for (j = 0; j < matrixLen; j++)
{
matrix[i, j] = byte.Parse(
xmlNode.ChildNodes[i].ChildNodes[j].InnerText);
}
}
byteMatrix = matrix;
return true;
}
public static bool ConfigCacheInfo(XmlElement xmlElem,
string name, ref CacheInfo cacheSize, bool compulsory)
{
XmlNode xmlNode;
XmlNode xmlChildNode;
uint bytes;
uint gigabytes;
int nCaches;
xmlNode = XMLReader.GetNode(xmlElem, name);
if (xmlNode == null && compulsory == true)
throw new ConfigNotFoundException(name);
else if (xmlNode != null)
{
if ((xmlChildNode = XMLReader.GetNode(
(XmlElement)xmlNode, "Bytes")) != null)
{
bytes = uint.Parse(xmlChildNode.InnerText);
if ((xmlChildNode = XMLReader.GetNode(
(XmlElement)xmlNode, "Gigabytes")) != null)
{
gigabytes = uint.Parse(xmlChildNode.InnerText);
if ((xmlChildNode = XMLReader.GetNode(
(XmlElement)xmlNode, "NCaches")) != null)
{
nCaches = int.Parse(xmlChildNode.InnerText);
cacheSize = new CacheInfo(gigabytes,bytes,nCaches);
return true;
}
}
}
}
return false;
}
public static bool ConfigCachePriority(XmlElement xmlElem,
string name, ref CachePriority cachePriority, bool compulsory)
{
XmlNode xmlNode;
string priority;
xmlNode = XMLReader.GetNode(xmlElem, name);
if (xmlNode == null && compulsory == false)
return false;
else if (xmlNode == null && compulsory == true)
throw new ConfigNotFoundException(name);
priority = xmlNode.InnerText;
if (priority == "DEFAULT")
cachePriority = CachePriority.DEFAULT;
else if (priority == "HIGH")
cachePriority = CachePriority.HIGH;
else if (priority == "LOW")
cachePriority = CachePriority.LOW;
else if (priority == "VERY_HIGH")
cachePriority = CachePriority.VERY_HIGH;
else if (priority == "VERY_LOW")
cachePriority = CachePriority.VERY_LOW;
else
throw new InvalidConfigException(name);
return true;
}
public static bool ConfigCreatePolicy(XmlElement xmlElem,
string name, ref CreatePolicy createPolicy, bool compulsory)
{
XmlNode xmlNode;
xmlNode = XMLReader.GetNode(xmlElem, name);
if (xmlNode == null && compulsory == false)
return false;
else if (xmlNode == null && compulsory == true)
throw new ConfigNotFoundException(name);
if (xmlNode.InnerText == "ALWAYS")
createPolicy = CreatePolicy.ALWAYS;
else if (xmlNode.InnerText == "IF_NEEDED")
createPolicy = CreatePolicy.IF_NEEDED;
else if (xmlNode.InnerText == "NEVER")
createPolicy = CreatePolicy.NEVER;
else
throw new InvalidConfigException(name);
return true;
}
public static bool ConfigDuplicatesPolicy(XmlElement xmlElem,
string name, ref DuplicatesPolicy duplicatePolicy,bool compulsory)
{
XmlNode xmlNode;
xmlNode = XMLReader.GetNode(xmlElem, name);
if (xmlNode == null && compulsory == false)
return false;
else if (xmlNode == null && compulsory == true)
throw new ConfigNotFoundException(name);
if (xmlNode.InnerText == "NONE")
duplicatePolicy = DuplicatesPolicy.NONE;
else if (xmlNode.InnerText == "SORTED")
duplicatePolicy = DuplicatesPolicy.SORTED;
else if (xmlNode.InnerText == "UNSORTED")
duplicatePolicy = DuplicatesPolicy.UNSORTED;
else
throw new InvalidConfigException(name);
return true;
}
public static bool ConfigDateTime(XmlElement xmlElem,
string name, ref DateTime time, bool compulsory)
{
XmlNode xmlNode;
xmlNode = XMLReader.GetNode(xmlElem, name);
if (xmlNode == null && compulsory == false)
return false;
else if (xmlNode == null && compulsory == true)
throw new ConfigNotFoundException(name);
time = DateTime.Parse(xmlNode.InnerText);
return true;
}
public static bool ConfigDeadlockPolicy(XmlElement xmlElem,
string name, ref DeadlockPolicy deadlockPolicy, bool compulsory)
{
XmlNode xmlNode = XMLReader.GetNode(xmlElem, name);
if (xmlNode == null && compulsory == false)
return false;
else if (xmlNode == null && compulsory == true)
throw new ConfigNotFoundException(name);
string policy = xmlNode.InnerText;
if (policy == "DEFAULT")
deadlockPolicy = DeadlockPolicy.DEFAULT;
else if (policy == "EXPIRE")
deadlockPolicy = DeadlockPolicy.EXPIRE;
else if (policy == "MAX_LOCKS")
deadlockPolicy = DeadlockPolicy.MAX_LOCKS;
else if (policy == "MAX_WRITE")
deadlockPolicy = DeadlockPolicy.MAX_WRITE;
else if (policy == "MIN_LOCKS")
deadlockPolicy = DeadlockPolicy.MIN_LOCKS;
else if (policy == "MIN_WRITE")
deadlockPolicy = DeadlockPolicy.MIN_WRITE;
else if (policy == "OLDEST")
deadlockPolicy = DeadlockPolicy.OLDEST;
else if (policy == "RANDOM")
deadlockPolicy = DeadlockPolicy.RANDOM;
else if (policy == "YOUNGEST")
deadlockPolicy = DeadlockPolicy.YOUNGEST;
else
throw new InvalidConfigException(name);
return true;
}
public static bool ConfigEncryption(XmlElement xmlElem,
string name, DatabaseConfig dbConfig, bool compulsory)
{
EncryptionAlgorithm alg;
XmlNode xmlNode;
string tmp, password;
xmlNode = XMLReader.GetNode(xmlElem, name);
if (xmlNode == null && compulsory == false)
return false;
else if (xmlNode == null && compulsory == true)
throw new ConfigNotFoundException(name);
password = XMLReader.GetNode((XmlElement)xmlNode,
"password").InnerText;
tmp = XMLReader.GetNode((XmlElement)xmlNode, "algorithm").InnerText;
if (tmp == "AES")
alg = EncryptionAlgorithm.AES;
else
alg = EncryptionAlgorithm.DEFAULT;
dbConfig.SetEncryption(password, alg);
return true;
}
public static bool ConfigInt(XmlElement xmlElem,
string name, ref int value, bool compulsory)
{
XmlNode xmlNode;
xmlNode = XMLReader.GetNode(xmlElem, name);
if (xmlNode == null && compulsory == false)
return false;
else if (xmlNode == null && compulsory == true)
throw new ConfigNotFoundException(name);
value = int.Parse(xmlNode.InnerText);
return true;
}
public static bool ConfigIsolation(XmlElement xmlElem,
string name, ref Isolation value, bool compulsory)
{
XmlNode xmlNode;
int isolationDegree;
xmlNode = XMLReader.GetNode(xmlElem, name);
if (xmlNode == null && compulsory == false)
return false;
else if (xmlNode == null && compulsory == true)
throw new ConfigNotFoundException(name);
isolationDegree = int.Parse(xmlNode.InnerText);
if (isolationDegree == 1)
value = Isolation.DEGREE_ONE;
else if (isolationDegree == 2)
value = Isolation.DEGREE_TWO;
else if (isolationDegree == 3)
value = Isolation.DEGREE_THREE;
else
throw new InvalidConfigException(name);
return true;
}
public static bool ConfigLogFlush(XmlElement xmlElem,
string name, ref TransactionConfig.LogFlush value,
bool compulsory)
{
XmlNode xmlNode;
string logFlush;
xmlNode = XMLReader.GetNode(xmlElem, name);
if (xmlNode == null && compulsory == false)
return false;
else if (xmlNode == null && compulsory == true)
throw new ConfigNotFoundException(name);
logFlush = xmlNode.InnerText;
if (logFlush == "DEFAULT")
value = TransactionConfig.LogFlush.DEFAULT;
else if (logFlush == "NOSYNC")
value = TransactionConfig.LogFlush.NOSYNC;
else if (logFlush == "WRITE_NOSYNC")
value = TransactionConfig.LogFlush.WRITE_NOSYNC;
else if (logFlush == "SYNC")
value = TransactionConfig.LogFlush.SYNC;
else
throw new InvalidConfigException(name);
return true;
}
public static bool ConfigLong(XmlElement xmlElem,
string name, ref long value, bool compulsory)
{
XmlNode xmlNode;
xmlNode = XMLReader.GetNode(xmlElem, name);
if (xmlNode == null && compulsory == false)
return false;
else if (xmlNode == null && compulsory == true)
throw new ConfigNotFoundException(name);
value = long.Parse(xmlNode.InnerText);
return true;
}
public static bool ConfigMaxSequentialWrites(
XmlElement xmlElem, string name,
MPoolConfig mpoolConfig, bool compulsory)
{
XmlNode xmlNode;
uint pause;
int writes;
xmlNode = XMLReader.GetNode(xmlElem, name);
if (xmlNode == null && compulsory == false)
return false;
else if (xmlNode == null && compulsory == true)
throw new ConfigNotFoundException(name);
pause = uint.Parse(XMLReader.GetNode(
(XmlElement)xmlNode, "pause").InnerText);
writes = int.Parse(XMLReader.GetNode(
(XmlElement)xmlNode,"maxWrites").InnerText);
mpoolConfig.SetMaxSequentialWrites(writes, pause);
return true;
}
public static bool ConfigReplicationHostAddress(
XmlElement xmlElem, string name,
ref DbSiteConfig siteConfig, bool compulsory)
{
XmlNode xmlNode = XMLReader.GetNode(
xmlElem, name);
if (xmlNode == null && compulsory == false)
return false;
else if (xmlNode == null && compulsory == true)
throw new ConfigNotFoundException(name);
siteConfig.Host = XMLReader.GetNode(
(XmlElement)xmlNode, "Host").InnerText;
siteConfig.Port = uint.Parse(XMLReader.GetNode(
(XmlElement)xmlNode, "Port").InnerText);
return true;
}
public static bool ConfigString(XmlElement xmlElem,
string name, ref string valChar, bool compulsory)
{
XmlNode xmlNode;
xmlNode = XMLReader.GetNode(xmlElem, name);
if (xmlNode == null && compulsory == false)
return false;
else if (xmlNode == null && compulsory == true)
throw new ConfigNotFoundException(name);
valChar = xmlNode.InnerText;
return true;
}
public static bool ConfigStringList(XmlElement xmlElem,
string name, ref List<string> strings, bool compulsory)
{
XmlNode xmlNode;
xmlNode = XMLReader.GetNode(xmlElem, name);
if (xmlNode == null && compulsory == false)
return false;
else if (xmlNode == null && compulsory == true)
throw new ConfigNotFoundException(name);
XmlNodeList list = xmlNode.ChildNodes;
for (int i = 0; i < list.Count; i++)
strings.Add(list[i].InnerText);
return true;
}
public static bool ConfigUint(XmlElement xmlElem,
string name, ref uint value, bool compulsory)
{
XmlNode xmlNode;
xmlNode = XMLReader.GetNode(xmlElem, name);
if (xmlNode == null && compulsory == false)
return false;
else if (xmlNode == null && compulsory == true)
throw new ConfigNotFoundException(name);
value = uint.Parse(xmlNode.InnerText);
return true;
}
public static bool ConfigVerboseMessages(
XmlElement xmlElem, string name,
ref VerboseMessages verbose, bool compulsory)
{
XmlNode xmlNode = XMLReader.GetNode(xmlElem,
name);
if (xmlNode == null && compulsory == false)
return false;
else if (xmlNode == null && compulsory == true)
throw new ConfigNotFoundException(name);
ConfigBool((XmlElement)xmlNode, "AllFileOps",
ref verbose.AllFileOps, compulsory);
ConfigBool((XmlElement)xmlNode, "Deadlock",
ref verbose.Deadlock, compulsory);
ConfigBool((XmlElement)xmlNode, "FileOps",
ref verbose.FileOps, compulsory);
ConfigBool((XmlElement)xmlNode, "Recovery",
ref verbose.Recovery, compulsory);
ConfigBool((XmlElement)xmlNode, "Register",
ref verbose.Register, compulsory);
ConfigBool((XmlElement)xmlNode, "Replication",
ref verbose.Replication, compulsory);
ConfigBool((XmlElement)xmlNode, "ReplicationElection",
ref verbose.ReplicationElection, compulsory);
ConfigBool((XmlElement)xmlNode, "ReplicationLease",
ref verbose.ReplicationLease, compulsory);
ConfigBool((XmlElement)xmlNode, "ReplicationMessages",
ref verbose.ReplicationMessages, compulsory);
ConfigBool((XmlElement)xmlNode, "ReplicationMisc",
ref verbose.ReplicationMisc, compulsory);
ConfigBool((XmlElement)xmlNode, "ReplicationSync",
ref verbose.ReplicationSync, compulsory);
ConfigBool((XmlElement)xmlNode, "RepMgrConnectionFailure",
ref verbose.RepMgrConnectionFailure, compulsory);
ConfigBool((XmlElement)xmlNode, "RepMgrMisc",
ref verbose.RepMgrMisc, compulsory);
ConfigBool((XmlElement)xmlNode, "WaitsForTable",
ref verbose.WaitsForTable, compulsory);
return true;
}
#endregion Config
/*
* Confirm that the given value is the same with that in
* xml. If there is no testing data in xml and it is
* compulsory, the ConfigNotFoundException will be thrown.
* If there is no testing data and it is optional, nothing
* will be done. If any testing data is provided, the value
* will be checked.
*/
#region Confirm
public static void ConfirmAckPolicy(XmlElement xmlElem,
string name, AckPolicy ackPolicy, bool compulsory)
{
XmlNode xmlNode = XMLReader.GetNode(xmlElem,
name);
if (xmlNode == null && compulsory == true)
throw new ConfigNotFoundException(name);
else if (xmlNode != null)
{
string policy = xmlNode.InnerText;
if (policy == "ALL")
Assert.AreEqual(AckPolicy.ALL,
ackPolicy);
else if (policy == "ALL_PEERS")
Assert.AreEqual(AckPolicy.ALL_PEERS,
ackPolicy);
else if (policy == "NONE")
Assert.AreEqual(AckPolicy.NONE,
ackPolicy);
else if (policy == "ONE")
Assert.AreEqual(AckPolicy.ONE,
ackPolicy);
else if (policy == "ONE_PEER")
Assert.AreEqual(AckPolicy.ONE_PEER,
ackPolicy);
else if (policy == "QUORUM")
Assert.AreEqual(AckPolicy.QUORUM,
ackPolicy);
else
throw new InvalidConfigException(name);
}
}
public static void ConfirmBool(XmlElement xmlElem,
string name, bool value, bool compulsory)
{
XmlNode xmlNode;
bool expected;
xmlNode = XMLReader.GetNode(xmlElem,
name);
if (xmlNode == null && compulsory == true)
throw new ConfigNotFoundException(name);
else if (xmlNode != null)
{
if (xmlNode.ChildNodes.Count > 1)
{
expected = bool.Parse(
xmlNode.FirstChild.NextSibling.InnerText);
Assert.AreEqual(expected, value);
}
}
}
/*
* If configure MACHINE, the ByteOrder in database will
* switch to LITTLE_ENDIAN or BIG_ENDIAN according to the
* current machine.
*/
public static void ConfirmByteOrder(XmlElement xmlElem,
string name, ByteOrder byteOrder, bool compulsory)
{
XmlNode xmlNode;
ByteOrder specOrder;
xmlNode = XMLReader.GetNode(xmlElem, name);
if (xmlNode == null && compulsory == true)
throw new ConfigNotFoundException(name);
else if (xmlNode != null)
{
specOrder = ByteOrder.FromConst(int.Parse(
xmlNode.InnerText));
if (specOrder == ByteOrder.MACHINE)
Assert.AreNotEqual(specOrder, byteOrder);
else
Assert.AreEqual(specOrder, byteOrder);
}
}
public static void ConfirmByteMatrix(XmlElement xmlElem,
string name, byte[,] byteMatrix, bool compulsory)
{
int i, j, matrixLen;
XmlNode xmlNode = XMLReader.GetNode(xmlElem, name);
if (xmlNode == null && compulsory == true)
throw new ConfigNotFoundException(name);
else if (xmlNode != null)
{
/*
* If the length of the 2 matrixes are not
* the same, the matrixes are definately
* not equal.
*/
matrixLen = xmlNode.ChildNodes.Count;
Assert.AreEqual(matrixLen * matrixLen,byteMatrix.Length);
/*
* Go over every element in the matrix to
* see if the same with the given xml data.
*/
for (i = 0; i < matrixLen; i++)
{
if (xmlNode.ChildNodes[i].ChildNodes.Count != matrixLen)
throw new ConfigNotFoundException(name);
for (j = 0; j < matrixLen; j++)
Assert.AreEqual(
byte.Parse(xmlNode.ChildNodes[i].ChildNodes[j].InnerText),
byteMatrix[i, j]);
}
}
}
public static void ConfirmCachePriority(XmlElement xmlElem,
string name, CachePriority priority, bool compulsory)
{
XmlNode xmlNode;
xmlNode = XMLReader.GetNode(xmlElem, name);
if (xmlNode == null && compulsory == true)
throw new ConfigNotFoundException(name);
else if (xmlNode != null)
{
if (xmlNode.InnerText == "DEFAULT")
Assert.AreEqual(CachePriority.DEFAULT, priority);
else if (xmlNode.InnerText == "HIGH")
Assert.AreEqual(CachePriority.HIGH, priority);
else if (xmlNode.InnerText == "LOW")
Assert.AreEqual(CachePriority.LOW, priority);
else if (xmlNode.InnerText == "VERY_HIGH")
Assert.AreEqual(CachePriority.VERY_HIGH, priority);
else if (xmlNode.InnerText == "VERY_LOW")
Assert.AreEqual(CachePriority.VERY_LOW, priority);
}
}
public static void ConfirmCacheSize(XmlElement xmlElem,
string name, CacheInfo cache, bool compulsory)
{
uint bytes;
uint gigabytes;
int nCaches;
XmlNode xmlNode;
XmlNode xmlChildNode;
xmlNode = XMLReader.GetNode(xmlElem, name);
if (xmlNode == null && compulsory == true)
throw new ConfigNotFoundException(name);
else if (xmlNode != null)
{
if ((xmlChildNode = XMLReader.GetNode(
(XmlElement)xmlNode, "Bytes")) != null)
{
bytes = uint.Parse(xmlChildNode.InnerText);
if ((xmlChildNode = XMLReader.GetNode(
(XmlElement)xmlNode, "Gigabytes")) != null)
{
gigabytes = uint.Parse(xmlChildNode.InnerText);
if ((xmlChildNode = XMLReader.GetNode(
(XmlElement)xmlNode,
"NCaches")) != null)
{
nCaches = int.Parse(xmlChildNode.InnerText);
Assert.LessOrEqual(bytes, cache.Bytes);
Assert.AreEqual(gigabytes, cache.Gigabytes);
Assert.AreEqual(nCaches, cache.NCaches);
}
}
}
}
}
/*
* If bytes in CacheSize is assigned, the bytes in cachesize
* couldn't be the default one.
*/
public static void ConfirmCacheSize(XmlElement xmlElem,
string name, CacheInfo cache, uint defaultCache,
bool compulsory)
{
uint bytes;
uint gigabytes;
int nCaches;
XmlNode xmlNode;
XmlNode xmlChildNode;
xmlNode = XMLReader.GetNode(xmlElem, name);
if (xmlNode == null && compulsory == true)
throw new ConfigNotFoundException(name);
else if (xmlNode != null)
{
if ((xmlChildNode = XMLReader.GetNode(
(XmlElement)xmlNode, "Bytes")) != null)
{
bytes = defaultCache;
if ((xmlChildNode = XMLReader.GetNode(
(XmlElement)xmlNode, "Gigabytes")) != null)
{
gigabytes = uint.Parse(xmlChildNode.InnerText);
if ((xmlChildNode = XMLReader.GetNode(
(XmlElement)xmlNode, "NCaches")) != null)
{
nCaches = int.Parse(xmlChildNode.InnerText);
Assert.AreNotEqual(bytes, cache.Bytes);
Assert.AreEqual(gigabytes, cache.Gigabytes);
Assert.AreEqual(nCaches, cache.NCaches);
}
}
}
}
}
public static void ConfirmCreatePolicy(XmlElement xmlElem,
string name, CreatePolicy createPolicy, bool compulsory)
{
XmlNode xmlNode;
xmlNode = XMLReader.GetNode(xmlElem, name);
if (xmlNode == null && compulsory == true)
throw new ConfigNotFoundException(name);
else if (xmlNode != null)
{
if (xmlNode.InnerText == "ALWAYS")
Assert.IsTrue(createPolicy.Equals(CreatePolicy.ALWAYS));
else if (xmlNode.InnerText == "IF_NEEDED")
Assert.IsTrue(createPolicy.Equals(CreatePolicy.IF_NEEDED));
else if (xmlNode.InnerText == "NEVER")
Assert.IsTrue(createPolicy.Equals(CreatePolicy.NEVER));
}
}
public static void ConfirmDataBaseType(XmlElement xmlElem,
string name, DatabaseType dbType, bool compulsory)
{
XmlNode xmlNode;
xmlNode = XMLReader.GetNode(xmlElem, name);
if (xmlNode == null && compulsory == true)
throw new ConfigNotFoundException(name);
else if (xmlNode != null)
{
if (xmlNode.InnerText == "BTREE")
Assert.AreEqual(dbType, DatabaseType.BTREE);
else if (xmlNode.InnerText == "HASH")
Assert.AreEqual(dbType, DatabaseType.HASH);
else if (xmlNode.InnerText == "QUEUE")
Assert.AreEqual(dbType, DatabaseType.QUEUE);
else if (xmlNode.InnerText == "RECNO")
Assert.AreEqual(dbType, DatabaseType.RECNO);
else if (xmlNode.InnerText == "UNKNOWN")
Assert.AreEqual(dbType, DatabaseType.UNKNOWN);
}
}
public static void ConfirmDateTime(XmlElement xmlElem,
string name, DateTime time, bool compulsory)
{
XmlNode xmlNode;
xmlNode = XMLReader.GetNode(xmlElem, name);
if (xmlNode == null && compulsory == true)
throw new ConfigNotFoundException(name);
else if (xmlNode != null)
Assert.AreEqual(DateTime.Parse(
xmlNode.InnerText), time);
}
public static void ConfirmDeadlockPolicy(XmlElement xmlElem,
string name, DeadlockPolicy deadlockPolicy, bool compulsory)
{
XmlNode xmlNode = XMLReader.GetNode(xmlElem, name);
if (xmlNode == null && compulsory == true)
throw new ConfigNotFoundException(name);
else if (xmlNode != null)
{
string policy = xmlNode.InnerText;
if (policy == "DEFAULT")
Assert.AreEqual(DeadlockPolicy.DEFAULT, deadlockPolicy);
else if (policy == "EXPIRE")
Assert.AreEqual(DeadlockPolicy.EXPIRE, deadlockPolicy);
else if (policy == "MAX_LOCKS")
Assert.AreEqual(DeadlockPolicy.MAX_LOCKS, deadlockPolicy);
else if (policy == "MAX_WRITE")
Assert.AreEqual(DeadlockPolicy.MAX_WRITE, deadlockPolicy);
else if (policy == "MIN_LOCKS")
Assert.AreEqual(DeadlockPolicy.MIN_LOCKS, deadlockPolicy);
else if (policy == "MIN_WRITE")
Assert.AreEqual(DeadlockPolicy.MIN_WRITE, deadlockPolicy);
else if (policy == "OLDEST")
Assert.AreEqual(DeadlockPolicy.OLDEST, deadlockPolicy);
else if (policy == "RANDOM")
Assert.AreEqual(DeadlockPolicy.RANDOM, deadlockPolicy);
else if (policy == "YOUNGEST")
Assert.AreEqual(DeadlockPolicy.YOUNGEST, deadlockPolicy);
else
throw new InvalidConfigException(name);
}
}
public static void ConfirmDuplicatesPolicy(
XmlElement xmlElem, string name,
DuplicatesPolicy duplicatedPolicy, bool compulsory)
{
XmlNode xmlNode;
xmlNode = XMLReader.GetNode(xmlElem, name);
if (xmlNode == null && compulsory == true)
throw new ConfigNotFoundException(name);
else if (xmlNode != null)
{
if (xmlNode.InnerText == "NONE")
Assert.AreEqual(duplicatedPolicy, DuplicatesPolicy.NONE);
else if (xmlNode.InnerText == "SORTED")
Assert.AreEqual(duplicatedPolicy, DuplicatesPolicy.SORTED);
else if (xmlNode.InnerText == "UNSORTED")
Assert.AreEqual(duplicatedPolicy, DuplicatesPolicy.UNSORTED);
}
}
public static void ConfirmEncryption(XmlElement xmlElem,
string name, string dPwd, EncryptionAlgorithm dAlg, bool compulsory)
{
EncryptionAlgorithm alg;
XmlNode xmlNode = XMLReader.GetNode(xmlElem,
name);
if (xmlNode == null && compulsory == true)
throw new ConfigNotFoundException(name);
else if (xmlNode != null)
{
string password = XMLReader.GetNode(
(XmlElement)xmlNode, "password").InnerText;
string tmp = XMLReader.GetNode(
(XmlElement)xmlNode, "algorithm").InnerText;
if (tmp == "AES")
alg = EncryptionAlgorithm.AES;
else
alg = EncryptionAlgorithm.DEFAULT;
Assert.AreEqual(dAlg, alg);
Assert.AreEqual(dPwd, dPwd);
}
}
public static void ConfirmInt(XmlElement xmlElem,
string name, int value, bool compulsory)
{
XmlNode xmlNode;
xmlNode = XMLReader.GetNode(xmlElem, name);
if (xmlNode == null && compulsory == true)
throw new ConfigNotFoundException(name);
else if (xmlNode != null)
Assert.AreEqual(int.Parse(xmlNode.InnerText), value);
}
public static void ConfirmIsolation(XmlElement xmlElem,
string name, Isolation value, bool compulsory)
{
XmlNode xmlNode;
int isolationDegree;
xmlNode = XMLReader.GetNode(xmlElem, name);
if (xmlNode == null && compulsory == true)
throw new ConfigNotFoundException(name);
else if (xmlNode != null)
{
isolationDegree = int.Parse(xmlNode.InnerText);
if (isolationDegree == 1)
Assert.AreEqual(Isolation.DEGREE_ONE, value);
else if (isolationDegree == 2)
Assert.AreEqual(Isolation.DEGREE_TWO, value);
else if (isolationDegree == 3)
Assert.AreEqual(Isolation.DEGREE_THREE, value);
else
throw new InvalidConfigException(name);
}
}
public static void ConfirmLogFlush(XmlElement xmlElem,
string name, TransactionConfig.LogFlush value,
bool compulsory)
{
XmlNode xmlNode;
string logFlush;
xmlNode = XMLReader.GetNode(xmlElem, name);
if (xmlNode == null && compulsory == true)
throw new ConfigNotFoundException(name);
else if (xmlNode != null)
{
logFlush = xmlNode.InnerText;
if (logFlush == "DEFAULT")
Assert.AreEqual(TransactionConfig.LogFlush.DEFAULT, value);
else if (logFlush == "NOSYNC")
Assert.AreEqual(TransactionConfig.LogFlush.NOSYNC, value);
else if (logFlush == "WRITE_NOSYNC")
Assert.AreEqual(TransactionConfig.LogFlush.WRITE_NOSYNC, value);
else if (logFlush == "SYNC")
Assert.AreEqual(TransactionConfig.LogFlush.SYNC, value);
else
throw new InvalidConfigException(name);
}
}
public static void ConfirmLong(XmlElement xmlElem,
string name, long value, bool compulsory)
{
XmlNode xmlNode;
xmlNode = XMLReader.GetNode(xmlElem, name);
if (xmlNode == null && compulsory == true)
throw new ConfigNotFoundException(name);
else if (xmlNode != null)
Assert.AreEqual(long.Parse(xmlNode.InnerText), value);
}
public static void ConfirmMaxSequentialWrites(
XmlElement xmlElem, string name,
uint mPause, int mWrites, bool compulsory)
{
XmlNode xmlNode;
uint pause;
int writes;
xmlNode = XMLReader.GetNode(xmlElem, name);
if (xmlNode == null && compulsory == true)
throw new ConfigNotFoundException(name);
else if (xmlNode != null)
{
writes = int.Parse(XMLReader.GetNode(
(XmlElement)xmlNode, "maxWrites").InnerText);
pause = uint.Parse(XMLReader.GetNode(
(XmlElement)xmlNode, "pause").InnerText);
Assert.AreEqual(mPause, pause);
Assert.AreEqual(mWrites, writes);
}
}
public static void ConfirmReplicationHostAddress(
XmlElement xmlElem, string name,
DbSiteConfig siteConfig, bool compulsory)
{
XmlNode xmlNode = XMLReader.GetNode(xmlElem, name);
if (xmlNode == null && compulsory == true)
throw new ConfigNotFoundException(name);
else if (xmlNode != null)
{
string host = XMLReader.GetNode(
(XmlElement)xmlNode, "Host").InnerText;
uint port = uint.Parse(XMLReader.GetNode(
(XmlElement)xmlNode, "Port").InnerText);
Assert.AreEqual(host, siteConfig.Host);
Assert.AreEqual(port, siteConfig.Port);
}
}
public static void ConfirmString(XmlElement xmlElem,
string name, string str, bool compulsory)
{
XmlNode xmlNode;
if (str != null)
{
xmlNode = XMLReader.GetNode(xmlElem, name);
if (xmlNode == null && compulsory == true)
throw new ConfigNotFoundException(name);
else if (xmlNode != null)
{
if (xmlNode.HasChildNodes)
Assert.AreEqual(
xmlNode.FirstChild.InnerText, str);
}
}
}
public static void ConfirmStringList(XmlElement xmlElem,
string name, List<string> strings, bool compulsory)
{
XmlNode xmlNode;
if (strings != null)
{
xmlNode = XMLReader.GetNode(xmlElem, name);
if (xmlNode == null && compulsory == true)
throw new ConfigNotFoundException(name);
else if (xmlNode != null)
{
if (xmlNode.HasChildNodes)
{
XmlNodeList list = xmlNode.ChildNodes;
for (int i = 0; i < xmlNode.ChildNodes.Count;i++)
Assert.IsTrue(
strings.Contains(list[i].InnerText));
}
}
}
}
public static void ConfirmUint(XmlElement xmlElem,
string name, uint value, bool compulsory)
{
XmlNode xmlNode;
xmlNode = XMLReader.GetNode(xmlElem, name);
if (xmlNode == null && compulsory == true)
throw new ConfigNotFoundException(name);
else if (xmlNode != null)
Assert.AreEqual(uint.Parse(xmlNode.InnerText), value);
}
public static void ConfirmVerboseMessages(
XmlElement xmlElem, string name,
VerboseMessages verbose, bool compulsory)
{
XmlNode xmlNode = XMLReader.GetNode(xmlElem, name);
if (xmlNode == null && compulsory == true)
throw new ConfigNotFoundException(name);
else if (xmlNode != null)
{
ConfirmBool((XmlElement)xmlNode, "AllFileOps",
verbose.AllFileOps, compulsory);
ConfirmBool((XmlElement)xmlNode, "Deadlock",
verbose.Deadlock, compulsory);
ConfirmBool((XmlElement)xmlNode, "FileOps",
verbose.FileOps, compulsory);
ConfirmBool((XmlElement)xmlNode, "Recovery",
verbose.Recovery, compulsory);
ConfirmBool((XmlElement)xmlNode, "Register",
verbose.Register, compulsory);
ConfirmBool((XmlElement)xmlNode, "Replication",
verbose.Replication, compulsory);
ConfirmBool((XmlElement)xmlNode, "ReplicationElection",
verbose.ReplicationElection, compulsory);
ConfirmBool((XmlElement)xmlNode, "ReplicationLease",
verbose.ReplicationLease, compulsory);
ConfirmBool((XmlElement)xmlNode, "ReplicationMessages",
verbose.ReplicationMessages, compulsory);
ConfirmBool((XmlElement)xmlNode, "ReplicationMisc",
verbose.ReplicationMisc, compulsory);
ConfirmBool((XmlElement)xmlNode, "ReplicationSync",
verbose.ReplicationSync, compulsory);
ConfirmBool((XmlElement)xmlNode, "RepMgrConnectionFailure",
verbose.RepMgrConnectionFailure, compulsory);
ConfirmBool((XmlElement)xmlNode, "RepMgrMisc",
verbose.RepMgrMisc, compulsory);
ConfirmBool((XmlElement)xmlNode,"WaitsForTable",
verbose.WaitsForTable, compulsory);
}
}
#endregion Confirm
public static void dbtFromString(DatabaseEntry dbt, string s)
{
dbt.Data = System.Text.Encoding.ASCII.GetBytes(s);
}
public static string strFromDBT(DatabaseEntry dbt)
{
System.Text.ASCIIEncoding decode = new ASCIIEncoding();
return decode.GetString(dbt.Data);
}
/*
* Reading params successfully returns true. Unless returns
* false. The retrieved Xml fragment is returning in xmlElem.
*/
public static XmlElement TestSetUp(string testFixtureName, string testName)
{
XMLReader xmlReader = new XMLReader("../../../AllTestData.xml");
XmlElement xmlElem = xmlReader.GetXmlElement(testFixtureName, testName);
if (xmlElem == null)
throw new ConfigNotFoundException(testFixtureName + ":" + testName);
else
return xmlElem;
}
/*
* Delete existing test output directory and its files,
* then create a new one.
*/
public static void ClearDir(string testDir)
{
if (Directory.Exists(testDir))
Directory.Delete(testDir, true);
Directory.CreateDirectory(testDir);
}
public static string RandomString(int max) {
string text = "";
int len = random.Next(max);
for (int i = 0; i < len; i++)
text += "a";
return text;
}
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using QuantConnect.Logging;
using QuantConnect.Util;
using System;
using System.IO;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace QuantConnect.Brokerages
{
/// <summary>
/// Wrapper for System.Net.Websockets.ClientWebSocket to enhance testability
/// </summary>
public class WebSocketClientWrapper : IWebSocket
{
private const int ReceiveBufferSize = 8192;
private string _url;
private string _sessionToken;
private CancellationTokenSource _cts;
private ClientWebSocket _client;
private Task _taskConnect;
private readonly object _locker = new object();
/// <summary>
/// Wraps constructor
/// </summary>
/// <param name="url">The target websocket url</param>
/// <param name="sessionToken">The websocket session token</param>
public void Initialize(string url, string sessionToken = null)
{
_url = url;
_sessionToken = sessionToken;
}
/// <summary>
/// Wraps send method
/// </summary>
/// <param name="data"></param>
public void Send(string data)
{
lock (_locker)
{
var buffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes(data));
_client.SendAsync(buffer, WebSocketMessageType.Text, true, _cts.Token).SynchronouslyAwaitTask();
}
}
/// <summary>
/// Wraps Connect method
/// </summary>
public void Connect()
{
lock (_locker)
{
if (_cts == null)
{
_cts = new CancellationTokenSource();
_client = null;
_taskConnect = Task.Factory.StartNew(
() =>
{
Log.Trace($"WebSocketClientWrapper connection task started: {_url}");
try
{
HandleConnection();
}
catch (Exception e)
{
Log.Error(e, $"Error in WebSocketClientWrapper connection task: {_url}: ");
}
Log.Trace($"WebSocketClientWrapper connection task ended: {_url}");
},
_cts.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default);
var count = 0;
do
{
// wait for _client to be not null
if (_client != null || _cts.Token.WaitHandle.WaitOne(50))
{
break;
}
}
while (++count < 100);
}
}
}
/// <summary>
/// Wraps Close method
/// </summary>
public void Close()
{
lock (_locker)
{
try
{
try
{
_client?.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "", _cts.Token).SynchronouslyAwaitTask();
}
catch
{
// ignored
}
_cts?.Cancel();
_taskConnect?.Wait(TimeSpan.FromSeconds(5));
_cts.DisposeSafely();
}
catch (Exception e)
{
Log.Error($"WebSocketClientWrapper.Close({_url}): {e}");
}
_cts = null;
}
if (_client != null)
{
OnClose(new WebSocketCloseData(0, string.Empty, true));
}
}
/// <summary>
/// Wraps IsAlive
/// </summary>
public bool IsOpen => _client?.State == WebSocketState.Open;
/// <summary>
/// Wraps message event
/// </summary>
public event EventHandler<WebSocketMessage> Message;
/// <summary>
/// Wraps error event
/// </summary>
public event EventHandler<WebSocketError> Error;
/// <summary>
/// Wraps open method
/// </summary>
public event EventHandler Open;
/// <summary>
/// Wraps close method
/// </summary>
public event EventHandler<WebSocketCloseData> Closed;
/// <summary>
/// Event invocator for the <see cref="Message"/> event
/// </summary>
protected virtual void OnMessage(WebSocketMessage e)
{
//Logging.Log.Trace("WebSocketWrapper.OnMessage(): " + e.Message);
Message?.Invoke(this, e);
}
/// <summary>
/// Event invocator for the <see cref="Error"/> event
/// </summary>
/// <param name="e"></param>
protected virtual void OnError(WebSocketError e)
{
Log.Error(e.Exception, $"WebSocketClientWrapper.OnError(): (IsOpen:{IsOpen}, State:{_client.State}): {_url}: {e.Message}");
Error?.Invoke(this, e);
}
/// <summary>
/// Event invocator for the <see cref="Open"/> event
/// </summary>
protected virtual void OnOpen()
{
Log.Trace($"WebSocketClientWrapper.OnOpen(): Connection opened (IsOpen:{IsOpen}, State:{_client.State}): {_url}");
Open?.Invoke(this, EventArgs.Empty);
}
/// <summary>
/// Event invocator for the <see cref="Close"/> event
/// </summary>
protected virtual void OnClose(WebSocketCloseData e)
{
Log.Trace($"WebSocketClientWrapper.OnClose(): Connection closed (IsOpen:{IsOpen}, State:{_client.State}): {_url}");
Closed?.Invoke(this, e);
}
private void HandleConnection()
{
var receiveBuffer = new byte[ReceiveBufferSize];
while (_cts is { IsCancellationRequested: false })
{
Log.Trace($"WebSocketClientWrapper.HandleConnection({_url}): Connecting...");
using (var connectionCts = CancellationTokenSource.CreateLinkedTokenSource(_cts.Token))
{
try
{
lock (_locker)
{
_client.DisposeSafely();
_client = new ClientWebSocket();
if (_sessionToken != null)
{
_client.Options.SetRequestHeader("x-session-token", _sessionToken);
}
_client.ConnectAsync(new Uri(_url), connectionCts.Token).SynchronouslyAwaitTask();
}
OnOpen();
while ((_client.State == WebSocketState.Open || _client.State == WebSocketState.CloseSent) &&
!connectionCts.IsCancellationRequested)
{
var messageData = ReceiveMessage(_client, connectionCts.Token, receiveBuffer);
if (messageData == null)
{
break;
}
OnMessage(new WebSocketMessage(this, messageData));
}
}
catch (OperationCanceledException) { }
catch (WebSocketException ex)
{
OnError(new WebSocketError(ex.Message, ex));
connectionCts.Token.WaitHandle.WaitOne(2000);
}
catch (Exception ex)
{
OnError(new WebSocketError(ex.Message, ex));
}
connectionCts.Cancel();
}
}
}
private MessageData ReceiveMessage(
WebSocket webSocket,
CancellationToken ct,
byte[] receiveBuffer,
long maxSize = long.MaxValue)
{
var buffer = new ArraySegment<byte>(receiveBuffer);
using (var ms = new MemoryStream())
{
WebSocketReceiveResult result;
do
{
result = webSocket.ReceiveAsync(buffer, ct).SynchronouslyAwaitTask();
ms.Write(buffer.Array, buffer.Offset, result.Count);
if (ms.Length > maxSize)
{
throw new InvalidOperationException($"Maximum size of the message was exceeded: {_url}");
}
}
while (!result.EndOfMessage);
if (result.MessageType == WebSocketMessageType.Binary)
{
return new BinaryMessage
{
Data = ms.ToArray(),
Count = result.Count,
};
}
else if (result.MessageType == WebSocketMessageType.Text)
{
return new TextMessage
{
Message = Encoding.UTF8.GetString(ms.GetBuffer(), 0, (int)ms.Length),
};
}
else if (result.MessageType == WebSocketMessageType.Close)
{
Log.Trace($"WebSocketClientWrapper.HandleConnection({_url}): WebSocketMessageType.Close - Data: {Encoding.UTF8.GetString(ms.GetBuffer(), 0, (int)ms.Length)}");
return null;
}
}
return null;
}
/// <summary>
/// Defines a message of websocket data
/// </summary>
public abstract class MessageData
{
/// <summary>
/// Type of message
/// </summary>
public WebSocketMessageType MessageType { get; set; }
}
/// <summary>
/// Defines a text-Type message of websocket data
/// </summary>
public class TextMessage : MessageData
{
/// <summary>
/// Data contained in message
/// </summary>
public string Message { get; set; }
/// <summary>
/// Constructs default instance of the TextMessage
/// </summary>
public TextMessage()
{
MessageType = WebSocketMessageType.Text;
}
}
/// <summary>
/// Defines a byte-Type message of websocket data
/// </summary>
public class BinaryMessage : MessageData
{
/// <summary>
/// Data contained in message
/// </summary>
public byte[] Data { get; set; }
/// <summary>
/// Count of message
/// </summary>
public int Count { get; set; }
/// <summary>
/// Constructs default instance of the BinaryMessage
/// </summary>
public BinaryMessage()
{
MessageType = WebSocketMessageType.Binary;
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Network
{
using Azure;
using Management;
using Rest;
using Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// VirtualNetworkPeeringsOperations operations.
/// </summary>
public partial interface IVirtualNetworkPeeringsOperations
{
/// <summary>
/// Deletes the specified virtual network peering.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='virtualNetworkPeeringName'>
/// The name of the virtual network peering.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string virtualNetworkPeeringName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the specified virtual network peering.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='virtualNetworkPeeringName'>
/// The name of the virtual network peering.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<VirtualNetworkPeering>> GetWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string virtualNetworkPeeringName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates a peering in the specified virtual network.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='virtualNetworkPeeringName'>
/// The name of the peering.
/// </param>
/// <param name='virtualNetworkPeeringParameters'>
/// Parameters supplied to the create or update virtual network peering
/// operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<VirtualNetworkPeering>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string virtualNetworkPeeringName, VirtualNetworkPeering virtualNetworkPeeringParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all virtual network peerings in a virtual network.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<VirtualNetworkPeering>>> ListWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes the specified virtual network peering.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='virtualNetworkPeeringName'>
/// The name of the virtual network peering.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string virtualNetworkPeeringName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates a peering in the specified virtual network.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='virtualNetworkPeeringName'>
/// The name of the peering.
/// </param>
/// <param name='virtualNetworkPeeringParameters'>
/// Parameters supplied to the create or update virtual network peering
/// operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<VirtualNetworkPeering>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string virtualNetworkPeeringName, VirtualNetworkPeering virtualNetworkPeeringParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all virtual network peerings in a virtual network.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<VirtualNetworkPeering>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
/*
nwitsml Copyright 2010 Setiri LLC
Derived from the jwitsml project, Copyright 2010 Statoil ASA
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
namespace witsmllib.v120
{
/**
* Version specific implementation of the WitsmlRig type.
*
* @author <a href="mailto:info@nwitsml.org">NWitsml</a>
*/
using System;
using witsmllib.util;
using System.Xml.Linq;
sealed class WitsmlRig : witsmllib.WitsmlRig
{
/**
* Create a new WITSML rig instance.
*
* @param server Server this instance lives within. Non-null.
* @param id ID of instance. May be null.
* @param name Name of instance. May be null.
* @param parent Parent of instance. May be null.
* @param parentId ID of parent instance. May be null.
*/
private WitsmlRig(WitsmlServer server, String id, String name,
WitsmlObject parent, String parentId)
:base(server, id, name, parent, parentId)
{}
/**
* Factory method for this type.
*
* @param server Server the new instance lives within. Non-null.
* @param parent Parent instance. May be null.
* @param element XML element to create instance from. Non-null.
* @return New WITSML rig instance. Never null.
*/
static WitsmlObject newInstance(WitsmlServer server, WitsmlObject parent, XElement element)
{
//Debug.Assert(server != null : "server cannot be null";
//Debug.Assert(element != null : "element cannot be null";
String id = element.Attribute("uidRig").Value ;
String parentId = element.Attribute("uidWellbore").Value;
String name = element.Element(element.Name.Namespace + "nameRig").Value.Trim(); //, element.getNamespace());
WitsmlRig rig = new WitsmlRig(server, id, name, parent, parentId);
rig.update(element);
return rig;
}
/**
* Return complete XML query for this type.
*
* @param id ID of instance to get. May be empty to indicate all.
* Non-null.
* @param parentId Parent IDs. Closest first. May be empty if instances
* are accessed from the root. Non-null.
* @return XML query. Never null.
*/
static String getQuery(String id, params String[] parentId)
{
//Debug.Assert(id != null : "id cannot be null";
//Debug.Assert(parentId != null : "parentId cannot be null";
String uidWellbore = parentId.Length > 0 ? parentId[0] : "";
String uidWell = parentId.Length > 1 ? parentId[1] : "";
String query = "<rigs xmlns=\"" + WitsmlVersion.VERSION_1_2_0.getNamespace() + "\">" +
" <rig uidWell =\"" + uidWell + "\"" +
" uidWellbore = \"" + uidWellbore + "\"" +
" uidRig = \"" + id + "\">" +
" <nameRig/>" +
" <owner/>" +
" <typeRig/>" +
" <manufacturer/>" +
" <yearEntService/>" +
" <classRig/>" +
" <approvals/>" +
" <registration/>" +
" <telNumber/>" +
" <faxNumber/>" +
" <emailAddress/>" +
" <nameContact/>" +
" <ratingDrillDepth uom=\"" + WitsmlServer.distUom + "\"/>" +
" <isOffshore/>" +
" <dtmRefToDtmPerm uom=\"" + WitsmlServer.distUom+"\"/>" +
" <airGap uom=\"" + WitsmlServer.distUom+"\"/>" +
" <dtmReference/>" +
" <dTimStartOp/>" +
" <dTimEndOp/>" +
" <bop>" +
" </bop>" +
" <pits>" +
" <indexPit/>" +
" <dTimInstall/>" +
" <dTimRemove/>" +
" <capMx uom=\"" + WitsmlServer.volUom+"\"/>" +
" <owner/>" +
" <type/>" +
" <isActive/>" +
" </pits>" +
" <pumps>" +
" <indexPump/>" +
" <manufacturer/>" +
" <model/>" +
" <dTimInstall/>" +
" <dTimRemove/>" +
" <owner/>" +
" <typePump/>" +
" <numCyl/>" +
" <odRod uom=\"" + WitsmlServer.distUom+"\"/>" +
" <idLiner uom=\"" + WitsmlServer.distUom+"\"/>" +
" <pumpAction/>" +
" <eff/>" +
" <lenStroke uom=\"" + WitsmlServer.distUom+"\"/>" +
" <presMx/>" +
" <powHydMx/>" +
" <spmMx/>" +
" <displacement uom=\"" + WitsmlServer.volUom+"\"/>" +
" <presDamp/>" +
" <volDamp uom=\"" + WitsmlServer.volUom+"\"/>" +
" <powMechMx/>" +
" </pumps>" +
" <shakers>" + // TODO
" </shakers>" +
" <centrifuge>" + // TODO
" </centrifuge>" +
" <hydroclone>" + // TODO
" </hydroclone>" +
" <degasser>" + // TODO
" </degasser>" +
" <surfaceEquipment>" + // TODO
" </surfaceEquipment>" +
" <numDerricks/>" +
" <typeDerrick/>" +
" <ratingDerrick/>" +
" <htDerrick uom=\"" + WitsmlServer.distUom+"\"/>" +
" <ratingHkld/>" +
" <capWindDerrick/>" +
" <wtBlock/>" +
" <ratingBlock/>" +
" <numBlockLines/>" +
" <typeHook/>" +
" <ratingHook/>" +
" <sizeDrillLine uom=\"" + WitsmlServer.distUom+"\"/>" +
" <typeDrawWorks/>" +
" <powerDrawWorks/>" +
" <ratingDrawWorks/>" +
" <motorDrawWorks/>" +
" <descBrake/>" +
" <typeSwivel/>" +
" <ratingSwivel/>" +
" <rotSystem/>" +
" <descRotSystem/>" +
" <ratingTqRotSys/>" +
" <rotSizeOpening uom=\"" + WitsmlServer.distUom+"\"/>" +
" <ratingRotSystem/>" +
" <scrSystem/>" +
" <pipeHandlingSystem/>" +
" <capBulkMud uom=\"" + WitsmlServer.volUom+"\"/>" +
" <capLiquidMud uom=\"" + WitsmlServer.volUom+"\"/>" +
" <capDrillWater uom=\"" + WitsmlServer.volUom+"\"/>" +
" <capPotableWater uom=\"" + WitsmlServer.volUom+"\"/>" +
" <capFuel uom=\"" + WitsmlServer.volUom+"\"/>" +
" <capBulkCement uom=\"" + WitsmlServer.volUom+"\"/>" +
" <mainEngine/>" +
" <generator/>" +
" <cementUnit/>" +
" <numBunks/>" +
" <bunksPerRoom/>" +
" <numCranes/>" +
" <numAnch/>" +
" <moorType/>" +
" <numGuideTens/>" +
" <numRiserTens/>" +
" <varDeckLdMx uom=\"" + WitsmlServer.forceUom+"\"/>" +
" <vdlStorm uom=\"" + WitsmlServer.forceUom+"\"/>" +
" <numThrusters/>" +
" <azimuthing/>" +
" <motionCompensationMn uom=\"" + WitsmlServer.forceUom+"\"/>" +
" <motionCompensationMx uom=\"" + WitsmlServer.forceUom+"\"/>" +
" <strokeMotionCompensation uom=\"" + WitsmlServer.distUom+"\"/>" +
" <riserAngleLimit uom=\"rad\"/>" +
" <heaveMx uom=\"" + WitsmlServer.distUom+"\"/>" +
" <gantry/>" +
" <flares/>" +
WitsmlCommonData.getQuery() +
" </rig>" +
"</rigs>";
return query;
}
/**
* Parse the specified DOM element and instantiate the properties
* of this instance.
*
* @param element XML element to parse. Non-null.
*/
void update(XElement element)
{
//Debug.Assert(element != null : "element cannot be null";
owner = XmlUtil.update(element, "owner", owner);
rigType = XmlUtil.update(element, "typeRig", rigType);
manufacturer = XmlUtil.update(element, "manufacturer", manufacturer);
startYear = XmlUtil.update(element, "yearEntService", startYear);
rigClass = XmlUtil.update(element, "classRig", rigClass);
approvals = XmlUtil.update(element, "approvals", approvals);
registrationLocation = XmlUtil.update(element, "registration", registrationLocation);
phoneNumber = XmlUtil.update(element, "telNumber", phoneNumber);
faxNumber = XmlUtil.update(element, "faxNumber", faxNumber);
emailAddress = XmlUtil.update(element, "emailAddress", emailAddress);
contactName = XmlUtil.update(element, "nameContact", contactName);
drillDepthRating = XmlUtil.update(element, "ratingDrillDepth", drillDepthRating);
waterDepthRating = XmlUtil.update(element, "ratingWaterDepth", waterDepthRating);
_isOffshore = XmlUtil.update(element, "isOffshore", _isOffshore);
drillingDatumToPermanentDatumDistance = XmlUtil.update(element, "dtmRefToDtmPerm", drillingDatumToPermanentDatumDistance);
airGap = XmlUtil.update(element, "airGap", airGap);
datum = XmlUtil.update(element, "dtmReference", datum);
operationStartTime = XmlUtil.update(element, "dTimStartOp", operationStartTime);
operationEndTime = XmlUtil.update(element, "dTimEndOp", operationEndTime);
XElement commonDataElement = element.Element(element.Name.Namespace + "commonData");//, element.getNamespace());
if (commonDataElement != null)
commonData = new WitsmlCommonData(commonDataElement);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using Pulsar4X.Entities;
using Pulsar4X.Entities.Components;
using System.ComponentModel;
/// <summary>
/// This is a duplicate of the Aurora armor system: Ships are basically spheres with a volume of HullSize.
/// Armor is coated around these spheres in ever increasing amounts per armor depth. likewise armor has to cover itself, as well as the ship sphere.
/// ShipOnDamage(or its equivilant) will touch on this, though I have yet to figure that out.
/// This is certainly up for updating/revision. - NathanH.
/// </summary>
namespace Pulsar4X.Entities.Components
{
/// <summary>
/// Ship Class armor definition. each copy of a ship will point to their shipclass, which points to this for important and hopefully static data.
/// </summary>
public class ArmorDefTN : ComponentDefTN
{
/// <summary>
/// Armor coverage of surface area of the ship per HullSpace(50.0 ton increment). This will vary with techlevel and can be updated. CalcArmor requires this.
/// </summary>
private ushort m_oArmorPerHS;
public ushort armorPerHS
{
get { return m_oArmorPerHS; }
}
/// <summary>
/// Number of armor layers, CalcArmor needs to know this as well.
/// </summary>
private ushort m_oDepth;
public ushort depth
{
get { return m_oDepth; }
}
/// <summary>
/// Area coverage of the armor, Cost and column # both require this.
/// </summary>
private double m_oArea;
public double area
{
get { return m_oArea; }
}
/// <summary>
/// Strength of Armor, purely needed for display.
/// </summary>
private double m_oStrength;
public double strength
{
get { return m_oStrength; }
}
/// <summary>
/// Column number counts how many columns of armor this ship can have, and hence how well protected it is from normal damage.
/// This is determined by taking the overall strength requirement divided by the depth of the armor.
/// </summary>
private ushort m_oCNum;
public ushort cNum
{
get { return m_oCNum; }
}
/// <summary>
/// Just an empty constructor. I don't really need this, the main show is in CalcArmor.
/// </summary>
public ArmorDefTN(string Title)
{
Name = Title;
size = 0.0f;
cost = 0.0m;
m_oArea = 0.0;
htk = 1;
/// <summary>
/// Unused parts of componentDefTN
/// </summary>
crew = 0;
isObsolete = false;
isMilitary = false;
isSalvaged = false;
isDivisible = false;
componentType = ComponentTypeTN.Armor;
minerialsCost = new decimal[(int)Constants.Minerals.MinerialNames.MinerialCount];
for (int mineralIterator = 0; mineralIterator < (int)Constants.Minerals.MinerialNames.MinerialCount; mineralIterator++)
{
minerialsCost[mineralIterator] = 0.0m;
}
}
/// <summary>
/// CalcArmor takes the size of the craft, as well as armor tech level and requested depth, and calculates how big the armor must be to cover the ship.
/// this is an iterative process, each layer of armor has to be placed on top of the old layer. Aurora updates this every time a change is made to the ship,
/// and I have written this function to work in the same manner.
/// </summary>
/// <param name="armorPerHS"> armor Per Unit of Hull Space </param>
/// <param name="sizeOfCraft"> In HullSpace increments </param>
/// <param name="armorDepth"> Armor Layers </param>
public void CalcArmor(string Title, ushort armorPerHS, double sizeOfCraft, ushort armorDepth)
{
/// <summary>
/// Bounds checking as armorDepth is a short, but then so is the value passed...
/// well armor can't be 0 layers atleast.
/// </summary>
if (armorDepth < 1)
armorDepth = 1;
if (armorDepth > 65535)
armorDepth = 65535;
Name = Title;
m_oArmorPerHS = armorPerHS;
m_oDepth = armorDepth;
/// <summary>
/// Armor calculation is as follows:
/// First Volume of a sphere: V = 4/3 * pi * r^3 r^3 = 3V/4pi. Hullsize is the value for volume. radius is what needs to be determined
/// From radius the armor area can be derived: A = 4 * pi * r^2
/// Area / 4.0 is the required strength area that needs to be covered.
/// </summary>
bool done;
int ArmourLayer;
double volume, radius3, radius2, radius, area = 0.0, strengthReq = 0.0, lastPro;
double areaF;
double temp1 = 1.0 / 3.0;
double pi = 3.14159654;
/// <summary>
/// Size must be initialized to 0.0 for this
/// Armor is being totally recalculated every time this is run, the previous result is thrown out.
/// </summary>
size = 0.0f;
/// <summary>
/// For each layer of Depth.
/// </summary>
for (ArmourLayer = 0; ArmourLayer < m_oDepth; ArmourLayer++)
{
done = false;
lastPro = -1;
volume = Math.Ceiling(sizeOfCraft + (double)size);
/// <summary>
/// While Armor does not yet fully cover the ship and itself.
/// </summary>
while (done == false)
{
radius3 = (3.0 * volume) / (4.0 * pi);
radius = Math.Pow(radius3, temp1);
radius2 = Math.Pow(radius, 2.0);
area = (4.0 * pi) * radius2;
/// <summary>
/// This wonky multiply by 10 then divide by 10 is to get the same behavior as in Aurora.
/// </summary>
areaF = Math.Floor(area * 10.0) / 10.0;
area = (Math.Round(area * 10.0)) / 10.0;
area *= (double)(ArmourLayer + 1);
strengthReq = area / 4.0;
size = (float)Math.Ceiling((strengthReq / (double)m_oArmorPerHS) * 10.0) / 10.0f;
volume = Math.Ceiling(sizeOfCraft + (double)size);
if (size == lastPro)
done = true;
lastPro = size;
}
}
m_oStrength = strengthReq;
m_oArea = area / m_oDepth;
cost = (decimal)m_oArea;
/// <summary>
/// This is a kludge to find the armor type and calculate the armor cost in minerals because I wrote ArmorDefTN first and did not put the tech as a member of ArmorDefTN and don't
/// feel like fixing it.
/// </summary>
for (int ArmorIterator = 0; ArmorIterator < Constants.MagazineTN.MagArmor.Count(); ArmorIterator++)
{
if (m_oArmorPerHS == Constants.MagazineTN.MagArmor[ArmorIterator])
{
/// <summary>
/// do duranium/neutronium split here.
/// </summary>
//0-1.0 1-1.0 2-1.0 3- D:9/10 N:1/10 ... 12 - D:1/10 N:9/10
int fraction = 13 - ArmorIterator;
//13 12 11 10 9 8 7 6 5 4 3 2 1
float DuraniumFraction = (float)fraction / 10.0f;
//1.3 1.2 1.1 1.0 .9 .8 .7 .6 .5 .4 .3 .2 .1
float NeutroniumFraction = (10.0f - (float)fraction) / 10.0f;
//-.3 -.2 -.1 0 .1 .2 .3 .4 .5 .6 .7 .8 .9
if (DuraniumFraction >= 1.0)
{
minerialsCost[(int)Constants.Minerals.MinerialNames.Duranium] = cost;
}
else
{
minerialsCost[(int)Constants.Minerals.MinerialNames.Duranium] = cost * (decimal)DuraniumFraction;
minerialsCost[(int)Constants.Minerals.MinerialNames.Neutronium] = cost * (decimal)NeutroniumFraction;
}
break;
}
}
m_oCNum = (ushort)Math.Floor(strengthReq / (double)m_oDepth);
double Tonnage = Math.Ceiling(size + sizeOfCraft);
if (m_oCNum > (ushort)Math.Floor((Tonnage) / 2.0))
{
m_oCNum = (ushort)Math.Floor((Tonnage) / 2.0);
}
}
/// <summary>
/// End of Function CalcArmor
/// </summary>
}
/// <summary>
/// End of Class ArmorDefTN
/// </summary>
/// <summary>
/// Armor contains ship data itself. each ship will have its own copy of this.
/// </summary>
public class ArmorTN : ComponentTN
{
/// <summary>
/// isDamaged controls whether or not armorColumns has been populated yet.
/// </summary>
private bool m_oIsDamaged;
public bool isDamaged
{
get { return m_oIsDamaged; }
}
/// <summary>
/// armorColumns contains the actual data that will need to be looked up
/// </summary>
private BindingList<ushort> m_lArmorColumns;
public BindingList<ushort> armorColumns
{
get { return m_lArmorColumns; }
}
/// <summary>
/// armorDamage is an easily stored listing of the damage that the ship has taken
/// Column # is the key, and value is how much damage has been done to that column( DepthValue to Zero ).
/// </summary>
private Dictionary<ushort, ushort> m_lArmorDamage;
public Dictionary<ushort, ushort> armorDamage
{
get { return m_lArmorDamage; }
}
/// <summary>
/// ArmorDef contains the definitions for this component
/// </summary>
private ArmorDefTN m_oArmorDef;
public ArmorDefTN armorDef
{
get { return m_oArmorDef; }
}
/// <summary>
/// the actual ship armor constructor does nothing with armorColumns or armorDamage yet.
/// </summary>
public ArmorTN(ArmorDefTN protectionDef)
{
m_oIsDamaged = false;
m_lArmorColumns = new BindingList<ushort>();
m_lArmorDamage = new Dictionary<ushort, ushort>();
m_oArmorDef = protectionDef;
Name = protectionDef.Name;
/// <summary>
/// This won't be used but will be set in any event.
/// </summary>
isDestroyed = false;
}
/// <summary>
/// SetDamage puts (CurrentDepth-DamageValue) damage into a specific column.
/// </summary>
/// <param name="ColumnCount">Total Columns, ship will have access to ship class which has armorDef.</param>
/// <param name="Depth">Full and pristine armor Depth.</param>
/// <param name="Column">The specific column to be damaged.</param>
/// <param name="DamageValue">How much damage has been done.</param>
/// <returns>Damage that passes through to internal components.</returns>
public int SetDamage(ushort ColumnCount, ushort Depth, ushort Column, ushort DamageValue)
{
int RemainingDamage = 0;
int newDepth;
if (m_oIsDamaged == false)
{
for (ushort loop = 0; loop < ColumnCount; loop++)
{
if (loop != Column)
{
m_lArmorColumns.Add(Depth);
}
else
{
newDepth = Depth - DamageValue;
if (newDepth < 0)
{
RemainingDamage = newDepth * -1;
newDepth = 0;
}
m_lArmorColumns.Add((ushort)newDepth);
m_lArmorDamage.Add(Column, (ushort)newDepth);
}
}
/// <summary>
/// end for ColumnCount
/// </summary>
m_oIsDamaged = true;
}
/// <summary>
/// end if isDamaged = false
/// </summary>
else
{
if (m_lArmorColumns[Column] == 0)
return DamageValue;
newDepth = m_lArmorColumns[Column] - DamageValue;
if (newDepth < 0)
{
RemainingDamage = newDepth * -1;
newDepth = 0;
}
m_lArmorColumns[Column] = (ushort)newDepth;
if (m_lArmorDamage.ContainsKey(Column) == true)
{
m_lArmorDamage[Column] = (ushort)newDepth;
}
else
{
m_lArmorDamage.Add(Column, (ushort)newDepth);
}
}
/// <summary>
/// end else if isDamaged = true
/// </summary>
return RemainingDamage;
}
/// <summary>
/// RepairSingleBlock undoes one point of damage from the worst damaged column.
/// If this totally fixes the column all damage to that column is repaired and it is removed from the list.
/// If all damage overall is repaired isDamaged is set to false, and the armorColumn is depopulated.
/// </summary>
/// <param name="Depth">Armor Depth, this will be called from ship which will have access to ship class and therefore this number</param>
public void RepairSingleBlock(ushort Depth)
{
ushort mostDamaged = m_lArmorDamage.Min().Key;
ushort repair = (ushort)(m_lArmorDamage.Min().Value + 1);
m_lArmorDamage[mostDamaged] = repair;
m_lArmorColumns[mostDamaged] = repair;
if (m_lArmorDamage[mostDamaged] == Depth)
{
m_lArmorDamage.Remove(mostDamaged);
if (m_lArmorDamage.Count == 0)
{
RepairAllArmor();
}
}
}
/// <summary>
/// When the armor of a ship is repaired at a shipyard all damage is cleared.
/// Also convienently called from RepairSingleBlock if a hangar manages to complete all repairs.
/// </summary>
public void RepairAllArmor()
{
m_oIsDamaged = false;
m_lArmorDamage.Clear();
m_lArmorColumns.Clear();
}
}
/// <summary>
/// End of Class ArmorTN
/// </summary>
/// <summary>
/// Armor rules for newtonian, feel free to rename.
/// </summary>
public class ArmorDefNA : BasicNewtonian
{
/// <summary>
/// Area of armor coverage.
/// </summary>
private float m_oArea;
public float area
{
get { return m_oArea; }
}
/// <summary>
/// # of armor layers
/// </summary>
private ushort m_oDepth;
public ushort depth
{
get { return m_oDepth; }
}
/// <summary>
/// ColumnNumber is 2*diameter, one row for each side of the ship. this is different from TN's calculation.
/// </summary>
private ushort m_oColumnNumber;
public ushort columnNumber
{
get { return m_oColumnNumber; }
}
/// <summary>
/// Cost of the armor layering.
/// </summary>
private decimal m_oCost;
public decimal cost
{
get { return m_oCost; }
}
/// <summary>
/// This constructor initializes armor statistics for CalcArmor.
/// </summary>
/// <param name="MJBox">Megajoules per armor box, how resistant to damage each part of the armor is</param>
public ArmorDefNA(string Title, ushort MJBox)
{
Name = Title;
m_oUnitMass = 0;
m_oArea = 0.0f;
m_oCost = 0.0m;
m_oIntegrity = MJBox;
m_oType = NewtonianType.Other;
}
/// <summary>
/// Since MJ per box is not part of CalcArmor in the way that HSPerArmor is for TN rules I need a new function to update Armor for NA.
/// </summary>
/// <param name="MJBox">New megajoules per box stat</param>
public void UpdateArmorType(ushort MJBox)
{
m_oIntegrity = MJBox;
}
/// <summary>
/// CalcArmor is mostly a copy of the function in TN, but it is a simpler one due to not having a varying amount of armor per HS.
/// </summary>
/// <param name="SizeInTonsOfShip">Each ton of the ship is equal to 10m^3 of volume for this calculation.</param>
/// <param name="depth">The number of armor layers desired.</param>
public void CalcArmor(int SizeInTonsOfShip, ushort depth)
{
if (depth < 1)
depth = 1;
m_oDepth = depth;
/// <summary>
/// Armor calculation is as follows:
/// First Volume of a sphere: V = 4/3 * pi * r^3 r^3 = 3V/4pi. Hullsize is the value for volume. radius is what needs to be determined
/// Actually, Volume is now ship tonnage * 10.
/// From radius the armor area can be derived: A = 4 * pi * r^2
/// Area / 4.0 is the required strength area that needs to be covered.
/// </summary>
int loop;
double volume, radius3, radius2, radius = 0.0, area = 0.0;
double temp1 = 1.0 / 3.0;
double pi = 3.14159654;
/// <summary>
/// Size must be initialized to 0.0 for this
/// Armor is being totally recalculated every time this is run, the previous result is thrown out.
/// </summary>
m_oUnitMass = 0;
/// <summary>
/// For each layer of Depth.
/// </summary>
for (loop = 0; loop < m_oDepth; loop++)
{
volume = Math.Ceiling((double)(SizeInTonsOfShip + m_oUnitMass));
volume = volume * 10;
radius3 = (3.0 * volume) / (4.0 * pi);
radius = Math.Pow(radius3, temp1);
radius2 = Math.Pow(radius, 2.0);
area = (4.0 * pi) * radius2;
m_oUnitMass = m_oUnitMass + (int)Math.Round((double)(area / 100.0));
}
m_oArea = (float)area;
m_oCost = (decimal)m_oArea;
/// <summary>
/// ColumnNumber = Diameter * 2 = radius * 2 * 2.
/// </summary>
m_oColumnNumber = (ushort)(radius * 4.0);
}
}
/// <summary>
/// End of ArmorDefNA
/// </summary>
/// <summary>
/// Armor contains ship data itself. each ship will have its own copy of this.
/// </summary>
public class ArmorNA
{
/// <summary>
/// isDamaged controls whether or not armorColumns has been populated yet.
/// </summary>
private bool m_oIsDamaged;
public bool isDamaged
{
get { return m_oIsDamaged; }
}
/// <summary>
/// armorColumns contains the actual data that will need to be looked up
/// </summary>
private BindingList<ushort> m_lArmorColumns;
public BindingList<ushort> armorColumns
{
get { return m_lArmorColumns; }
}
/// <summary>
/// armorDamage is an easily stored listing of the damage that the ship has taken
/// Column # is the key, and value is how much damage has been done to that column( DepthValue to Zero ).
/// </summary>
private Dictionary<ushort, ushort> m_lArmorDamage;
public Dictionary<ushort, ushort> armorDamage
{
get { return m_lArmorDamage; }
}
/// <summary>
/// ArmorDef contains the definitions for this component
/// </summary>
private ArmorDefNA m_oArmorDef;
public ArmorDefNA armorDef
{
get { return m_oArmorDef; }
}
/// <summary>
/// the actual ship armor constructor does nothing with armorColumns or armorDamage yet.
/// </summary>
public ArmorNA(ArmorDefNA protectionDef)
{
m_oIsDamaged = false;
m_lArmorColumns = new BindingList<ushort>();
m_lArmorDamage = new Dictionary<ushort, ushort>();
m_oArmorDef = protectionDef;
}
/// <summary>
/// SetDamage puts (CurrentDepth-DamageValue) damage into a specific column.
/// </summary>
/// <param name="ColumnCount">Total Columns, ship will have access to ship class which has armorDef.</param>
/// <param name="Depth">Full and pristine armor Depth.</param>
/// <param name="Column">The specific column to be damaged.</param>
/// <param name="DamageValue">How much damage has been done.</param>
/// <returns>Remaining damage that passes through to internals.</returns>
public int SetDamage(ushort ColumnCount, ushort Depth, ushort Column, ushort DamageValue)
{
int RemainingDamage = 0;
int newDepth;
if (m_oIsDamaged == false)
{
for (ushort loop = 0; loop < ColumnCount; loop++)
{
if (loop != Column)
{
m_lArmorColumns.Add(Depth);
}
else
{
/// <summary>
/// I have to type cast this subtraction of a short from a short into a short with a short.
/// </summary>
newDepth = Depth - DamageValue;
if (newDepth < 0)
{
RemainingDamage = newDepth * -1;
newDepth = 0;
}
m_lArmorColumns.Add((ushort)newDepth);
m_lArmorDamage.Add(Column, (ushort)newDepth);
}
}
/// <summary>
/// end for ColumnCount
/// </summary>
m_oIsDamaged = true;
}
/// <summary>
/// end if isDamaged = false
/// </summary>
else
{
if (m_lArmorColumns[Column] == 0)
return DamageValue;
newDepth = m_lArmorColumns[Column] - DamageValue;
if (newDepth < 0)
{
RemainingDamage = newDepth * -1;
newDepth = 0;
}
m_lArmorColumns[Column] = (ushort)newDepth;
if (m_lArmorDamage.ContainsKey(Column) == true)
{
m_lArmorDamage[Column] = (ushort)newDepth;
}
else
{
m_lArmorDamage.Add(Column, (ushort)newDepth);
}
}
/// <summary>
/// end else if isDamaged = true
/// </summary>
return RemainingDamage;
}
/// <summary>
/// RepairSingleBlock undoes one point of damage from the worst damaged column.
/// If this totally fixes the column all damage to that column is repaired and it is removed from the list.
/// If all damage overall is repaired isDamaged is set to false, and the armorColumn is depopulated.
/// </summary>
/// <param name="Depth">Armor Depth, this will be called from ship which will have access to ship class and therefore this number</param>
public void RepairSingleBlock(ushort Depth)
{
ushort mostDamaged = m_lArmorDamage.Min().Key;
ushort repair = (ushort)(m_lArmorDamage.Min().Value + 1);
m_lArmorDamage[mostDamaged] = repair;
m_lArmorColumns[mostDamaged] = repair;
if (m_lArmorDamage[mostDamaged] == Depth)
{
m_lArmorDamage.Remove(mostDamaged);
if (m_lArmorDamage.Count == 0)
{
RepairAllArmor();
}
}
}
/// <summary>
/// When the armor of a ship is repaired at a shipyard all damage is cleared.
/// Also convienently called from RepairSingleBlock if a hangar manages to complete all repairs.
/// </summary>
public void RepairAllArmor()
{
m_oIsDamaged = false;
m_lArmorDamage.Clear();
m_lArmorColumns.Clear();
}
}
/// <summary>
/// End of Class ArmorNA
/// </summary>
}
/// <summary>
/// End of Namespace Pulsar4X.Entites.Components
/// </summary>
| |
/// Refly License
///
/// Copyright (c) 2004 Jonathan de Halleux, http://www.dotnetwiki.org
///
/// 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.
using System;
using System.Reflection;
using System.Diagnostics;
using System.Xml.Serialization;
namespace Refly.CodeDom
{
/// <summary>
/// Helper static class for Type related tasks
/// </summary>
/// <include file="GUnit.CodeDom.Doc.xml" path="doc/remarkss/remarks[@name='TypeHelper']"/>
public sealed class TypeHelper
{
internal TypeHelper()
{}
public static ConstructorInfo GetConstructor(Type t, params Type[] args)
{
if (t==null)
throw new ArgumentNullException("t");
ConstructorInfo ci = t.GetConstructor(args);
if (ci==null)
throw new ArgumentNullException("constructor for " + t.FullName +" not found");
return ci;
}
public static ConstructorInfo GetDefaultConstructor(Type t)
{
if (t==null)
throw new ArgumentNullException("t");
ConstructorInfo ci = t.GetConstructor(Type.EmptyTypes);
if (ci==null)
throw new ArgumentNullException("no default constructor for " + t.FullName );
return ci;
}
public static bool IsXmlNullable(FieldInfo f)
{
if (f.FieldType.IsValueType)
return false;
if (!HasCustomAttribute(f,typeof(XmlElementAttribute)))
return true;
XmlElementAttribute attr =
(XmlElementAttribute)GetFirstCustomAttribute(f,typeof(XmlElementAttribute));
return attr.IsNullable;
}
/// <summary>
/// Gets a value indicating if the type <paramref name="t"/> is tagged
/// by a <paramref name="customAttributeType"/> instance.
/// </summary>
/// <param name="t">type to test</param>
/// <param name="customAttributeType">custom attribute type to search</param>
/// <returns>
/// true if <param name="t"/> is tagged by a <paramref name="customAttributeType"/>
/// attribute, false otherwise.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="t"/> or <paramref name="customAttributeType"/>
/// is a null reference
/// </exception>
/// <remarks>
/// You can use this method to check that a type is tagged by an attribute.
/// </remarks>
public static bool HasCustomAttribute(Type t,Type customAttributeType)
{
if (t==null)
throw new ArgumentNullException("t");
if (customAttributeType==null)
throw new ArgumentNullException("customAttributeType");
return t.GetCustomAttributes(customAttributeType,true).Length != 0;
}
/// <summary>
/// Gets a value indicating if the property info <paramref name="t"/> is tagged
/// by a <paramref name="customAttributeType"/> instance.
/// </summary>
/// <param name="t">property to test</param>
/// <param name="customAttributeType">custom attribute type to search</param>
/// <returns>
/// true if <param name="t"/> is tagged by a <paramref name="customAttributeType"/>
/// attribute, false otherwise.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="t"/> or <paramref name="customAttributeType"/>
/// is a null reference
/// </exception>
/// <remarks>
/// You can use this property to check that a method is tagged by a
/// specified attribute.
/// </remarks>
public static bool HasCustomAttribute(PropertyInfo t,Type customAttributeType)
{
if (t==null)
throw new ArgumentNullException("t");
if (customAttributeType==null)
throw new ArgumentNullException("customAttributeType");
return t.GetCustomAttributes(customAttributeType,true).Length != 0;
}
public static bool HasCustomAttribute(FieldInfo t,Type customAttributeType)
{
if (t==null)
throw new ArgumentNullException("t");
if (customAttributeType==null)
throw new ArgumentNullException("customAttributeType");
return t.GetCustomAttributes(customAttributeType,true).Length != 0;
}
/// <summary>
/// Gets the first instance of <paramref name="customAttributeType"/>
/// from the type <paramref name="t"/> custom attributes.
/// </summary>
/// <param name="t">type to test</param>
/// <param name="customAttributeType">custom attribute type to search</param>
/// <returns>
/// First instance of <paramref name="customAttributeTyp"/>
/// from the type <paramref name="t"/> custom attributes.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="t"/> or <paramref name="customAttributeType"/>
/// is a null reference
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="t"/> is not tagged by an attribute of type
/// <paramref name="customAttributeType"/>
/// </exception>
/// <remarks>
/// You can use this method to retreive a specified attribute
/// instance
/// </remarks>
public static Object GetFirstCustomAttribute(Type t, Type customAttributeType)
{
if (t==null)
throw new ArgumentNullException("t");
if (customAttributeType==null)
throw new ArgumentNullException("customAttributeType");
Object[] attrs = t.GetCustomAttributes(customAttributeType,true);
if (attrs.Length==0)
throw new ArgumentException("type does not have custom attribute");
return attrs[0];
}
/// <summary>
/// Gets the first instance of <paramref name="customAttributeType"/>
/// from the property <paramref name="mi"/> custom attributes.
/// </summary>
/// <param name="mi">property to test</param>
/// <param name="customAttributeType">custom attribute type to search</param>
/// <returns>
/// First instance of <paramref name="customAttributeTyp"/>
/// from the property <paramref name="mi"/> custom attributes.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="mi"/> or <paramref name="customAttributeType"/>
/// is a null reference
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="mi"/> is not tagged by an attribute of type
/// <paramref name="customAttributeType"/>
/// </exception>
/// <remarks>
/// You can use this property to retreive a specified attribute
/// instance of a method.
/// </remarks>
public static Object GetFirstCustomAttribute(PropertyInfo mi, Type customAttributeType)
{
if (mi==null)
throw new ArgumentNullException("mi");
if (customAttributeType==null)
throw new ArgumentNullException("customAttributeType");
Object[] attrs = mi.GetCustomAttributes(customAttributeType,true);
if (attrs.Length==0)
throw new ArgumentException("type does not have custom attribute");
return attrs[0];
}
public static Object GetFirstCustomAttribute(FieldInfo mi, Type customAttributeType)
{
if (mi==null)
throw new ArgumentNullException("mi");
if (customAttributeType==null)
throw new ArgumentNullException("customAttributeType");
Object[] attrs = mi.GetCustomAttributes(customAttributeType,true);
if (attrs.Length==0)
throw new ArgumentException("type does not have custom attribute");
return attrs[0];
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using Signum.Engine.Maps;
using Signum.Entities;
using Signum.Entities.Basics;
using Signum.Entities.Reflection;
using Signum.Utilities;
using Signum.Utilities.ExpressionTrees;
namespace Signum.Engine.CodeGeneration
{
public class ReactCodeGenerator
{
public string SolutionName = null!;
public string SolutionFolder = null!;
public Schema CurrentSchema = null!;
public virtual void GenerateReactFromEntities()
{
CurrentSchema = Schema.Current;
GetSolutionInfo(out SolutionFolder, out SolutionName);
string projectFolder = GetProjectFolder();
if (!Directory.Exists(projectFolder))
throw new InvalidOperationException("{0} not found. Override GetProjectFolder".FormatWith(projectFolder));
bool? overwriteFiles = null;
foreach (var mod in GetModules())
{
if (Directory.Exists(BaseFileName(mod)))
{
var clientFile = GetClientFile(mod);
if(File.Exists(clientFile))
{
var lines = File.ReadAllLines(clientFile).ToList();
var index = lines.FindLastIndex(s => s.Contains("Navigator.addSettings(new EntitySettings")).NotFoundToNull() ??
lines.FindLastIndex(s => s.Contains("export function start")).NotFoundToNull() ?? 0;
lines.Insert(index + 1, WritetEntitySettings(mod).Trim().Indent(2));
File.WriteAllLines(clientFile, lines);
}
else
{
WriteFile(() => WriteClientFile(mod), () => GetClientFile(mod), ref overwriteFiles);
}
foreach (var t in mod.Types)
{
WriteFile(() => WriteEntityComponentFile(t), () => GetViewFileName(mod, t), ref overwriteFiles);
}
}
else
{
WriteFile(() => WriteClientFile(mod), () => GetClientFile(mod), ref overwriteFiles);
WriteFile(() => WriteTypingsFile(mod), () => GetTypingsFile(mod), ref overwriteFiles);
foreach (var t in mod.Types)
{
WriteFile(() => WriteEntityComponentFile(t), () => GetViewFileName(mod, t), ref overwriteFiles);
}
WriteFile(() => WriteServerFile(mod), () => ServerFileName(mod), ref overwriteFiles);
WriteFile(() => WriteControllerFile(mod), () => ControllerFileName(mod), ref overwriteFiles);
}
}
}
protected virtual void WriteFile(Func<string?> getContent, Func<string> getFileName, ref bool? overwriteFiles)
{
var content = getContent();
if (content == null)
return;
var fileName = getFileName();
FileTools.CreateParentDirectory(fileName);
if (!File.Exists(fileName) || SafeConsole.Ask(ref overwriteFiles, "Overwrite {0}?".FormatWith(fileName)))
File.WriteAllText(fileName, content, Encoding.UTF8);
}
protected virtual string GetProjectFolder()
{
return Path.Combine(SolutionFolder, SolutionName + ".React");
}
protected virtual void GetSolutionInfo(out string solutionFolder, out string solutionName)
{
CodeGenerator.GetSolutionInfo(out solutionFolder, out solutionName);
}
protected virtual string ServerFileName(Module m)
{
return BaseFileName(m) + m.ModuleName + "Server.cs";
}
protected virtual string GetViewFileName(Module m, Type t)
{
return BaseFileName(m) + "Templates\\" + GetComponentName(t) + ".tsx";
}
protected virtual string ControllerFileName(Module m)
{
return BaseFileName(m) + m.ModuleName + "Controller.cs";
}
protected virtual string GetClientFile(Module m)
{
return BaseFileName(m) + m.ModuleName + "Client.tsx";
}
protected virtual string GetTypingsFile(Module m)
{
return BaseFileName(m) + m.Types.First().Namespace + ".t4s";
}
protected virtual string BaseFileName(Module m)
{
return Path.Combine(GetProjectFolder(), "App\\" + m.ModuleName + "\\");
}
protected virtual IEnumerable<Module> GetModules()
{
Dictionary<Type, bool> types = CandidateTypes().ToDictionary(a => a, Schema.Current.Tables.ContainsKey);
return ReactGetModules(types, this.SolutionName);
}
public IEnumerable<Module> ReactGetModules(Dictionary<Type, bool> types, string solutionName)
{
while (true)
{
var typesToShow = types.Keys.OrderBy(a => types[a]).ThenBy(a => a.FullName).ToList();
var selectedTypes = new ConsoleSwitch<int, Type>("Chose types for a new Logic module:")
.Load(typesToShow, t => (types[t] ? "-" : " ") + t.FullName)
.ChooseMultiple();
if (selectedTypes.IsNullOrEmpty())
yield break;
var directories = Directory.GetDirectories(GetProjectFolder(), "App\\").Select(a => Path.GetFileName(a)!);
string? moduleName;
if (directories.IsEmpty())
{
moduleName = AskModuleName(solutionName, selectedTypes);
}
else
{
var selectedName = directories.And("[New Module]").ChooseConsole(message: "Select a Module");
if (selectedName == "[New Module]")
moduleName = AskModuleName(solutionName, selectedTypes);
else
moduleName = selectedName;
}
if (!moduleName.HasText())
yield break;
yield return new Module(moduleName, selectedTypes.ToList());
types.SetRange(selectedTypes, a => a, a => true);
}
}
private static string AskModuleName(string solutionName, Type[] selected)
{
string? moduleName = CodeGenerator.GetDefaultModuleName(selected, solutionName);
SafeConsole.WriteColor(ConsoleColor.Gray, $"Module name? ([Enter] for '{moduleName}'):");
moduleName = Console.ReadLine().DefaultText(moduleName!);
return moduleName;
}
protected virtual List<Type> CandidateTypes()
{
var assembly = Assembly.Load(Assembly.GetEntryAssembly()!.GetReferencedAssemblies().Single(a => a.Name == this.SolutionName + ".Entities"));
return assembly.GetTypes().Where(t => t.IsModifiableEntity() && !t.IsAbstract && !typeof(MixinEntity).IsAssignableFrom(t)).ToList();
}
protected virtual string? WriteServerFile(Module mod)
{
if (!ShouldWriteServerFile(mod))
return null;
StringBuilder sb = new StringBuilder();
foreach (var item in GetServerUsingNamespaces(mod))
sb.AppendLine("using {0};".FormatWith(item));
sb.AppendLine();
sb.AppendLine("namespace " + GetServerNamespace(mod));
sb.AppendLine("{");
sb.Append(WriteServerClass(mod).Indent(2));
sb.AppendLine("}");
return sb.ToString();
}
protected virtual bool ShouldWriteServerFile(Module mod)
{
return SafeConsole.Ask($"Write Server File for {mod.ModuleName}?");
}
protected virtual string GetServerNamespace(Module mod)
{
return SolutionName + ".React." + mod.ModuleName;
}
protected virtual string WriteServerClass(Module mod)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("public static class " + mod.ModuleName + "Server");
sb.AppendLine("{");
sb.AppendLine();
sb.Append(WriteServerStartMethod(mod).Indent(2));
sb.AppendLine("}");
return sb.ToString();
}
protected virtual string WriteServerStartMethod(Module mod)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("public static void Start()");
sb.AppendLine("{");
sb.AppendLine("}");
return sb.ToString();
}
protected virtual string? WriteControllerFile(Module mod)
{
if (!ShouldWriteControllerFile(mod))
return null;
StringBuilder sb = new StringBuilder();
foreach (var item in GetServerUsingNamespaces(mod))
sb.AppendLine("using {0};".FormatWith(item));
sb.AppendLine();
sb.AppendLine("namespace " + GetServerNamespace(mod));
sb.AppendLine("{");
sb.Append(WriteControllerClass(mod).Indent(2));
sb.AppendLine("}");
return sb.ToString();
}
protected virtual bool ShouldWriteControllerFile(Module mod)
{
return SafeConsole.Ask($"Write Controller File for {mod.ModuleName}?");
}
protected virtual string WriteControllerClass(Module mod)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("public class " + mod.ModuleName + "Controller : ControllerBase");
sb.AppendLine("{");
sb.AppendLine();
sb.Append(WriteControllerExampleMethod(mod).Indent(2));
sb.AppendLine("}");
return sb.ToString();
}
protected virtual string WriteControllerExampleMethod(Module mod)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine($"//[Route(\"api/{mod.ModuleName.ToLower()}/login\"), HttpPost]");
sb.AppendLine(@"//public MyResponse Login([Required, FromBody]MyRequest data)");
sb.AppendLine(@"//{");
sb.AppendLine(@"//}");
return sb.ToString();
}
protected virtual List<string> GetServerUsingNamespaces(Module mod)
{
var result = new List<string>()
{
"System",
"System.Collections.Generic",
"System.Linq",
"System.Text",
"System.Reflection",
"System.Web.Http",
"Signum.Utilities",
"Signum.Entities",
"Signum.Engine",
"Signum.Engine.Operations",
"Signum.React",
};
result.AddRange(mod.Types.Select(t => t.Namespace!).Distinct());
return result;
}
protected virtual string WriteClientFile(Module mod)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("import * as React from 'react'");
sb.AppendLine("import { Route } from 'react-router'");
sb.AppendLine("import { ajaxPost, ajaxGet } from '@framework/Services';");
sb.AppendLine("import { EntitySettings, ViewPromise } from '@framework/Navigator'");
sb.AppendLine("import * as Navigator from '@framework/Navigator'");
sb.AppendLine("import { EntityOperationSettings } from '@framework/Operations'");
sb.AppendLine("import * as Operations from '@framework/Operations'");
foreach (var gr in mod.Types.GroupBy(a => a.Namespace))
{
sb.AppendLine("import { "
+ gr.Select(t => t.Name).GroupsOf(5).ToString(a => a.ToString(", "), ",\r\n")
+ " } from './" + gr.Key + "'");
}
sb.AppendLine();
sb.AppendLine(WriteClientStartMethod(mod));
return sb.ToString();
}
protected virtual string WriteTypingsFile(Module mod)
{
return "";
}
private static string[] GetTypingsImports()
{
return new[] { "Files", "Mailing", "SMS", "Processes", "Basics", "Scheduler" };
}
protected virtual string WriteClientStartMethod(Module mod)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("export function start(options: { routes: JSX.Element[] }) {");
sb.AppendLine("");
string entitySettings = WritetEntitySettings(mod);
if (entitySettings != null)
sb.Append(entitySettings.Indent(2));
sb.AppendLine();
string operationSettings = WriteOperationSettings(mod);
if (operationSettings != null)
sb.Append(operationSettings.Indent(2));
sb.AppendLine("}");
return sb.ToString();
}
protected virtual string WritetEntitySettings(Module mod)
{
StringBuilder sb = new StringBuilder();
foreach (var t in mod.Types)
{
string es = GetEntitySetting(t);
if (es != null)
sb.AppendLine(es);
}
return sb.ToString();
}
protected virtual string GetEntitySetting(Type type)
{
var v = GetVarName(type);
return "Navigator.addSettings(new EntitySettings({0}, {1} => import('./Templates/{2}')));".FormatWith(
type.Name, v, GetComponentName(type));
}
protected virtual string GetVarName(Type type)
{
return type.Name.Substring(0, 1).ToLower();
}
protected virtual string WriteOperationSettings(Module mod)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("//Operations.addSettings(new EntityOperationSettings(MyEntityOperations.Save, {}));");
return sb.ToString();
}
protected virtual string GetComponentName(Type type)
{
return Reflector.CleanTypeName(type);
}
protected virtual string WriteEntityComponentFile(Type type)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("import * as React from 'react'");
sb.AppendLine("import { " + type.Name + " } from '../" + type.Namespace + "'");
sb.AppendLine("import { TypeContext, ValueLine, EntityLine, EntityCombo, EntityList, EntityDetail, EntityStrip, EntityRepeater, EntityTable, FormGroup } from '@framework/Lines'");
sb.AppendLine("import { SearchControl, ValueSearchControl, FilterOperation, OrderType, PaginationMode } from '@framework/Search'");
var v = GetVarName(type);
if (this.GenerateFunctionalComponent(type))
{
sb.AppendLine();
sb.AppendLine("export default function {0}(p: {{ ctx: TypeContext<{1}> }}) {{".FormatWith(GetComponentName(type), type.Name));
sb.AppendLine("");
sb.AppendLine(" var ctx = p.ctx;");
sb.AppendLine(" return (");
sb.AppendLine(" <div>");
foreach (var pi in GetProperties(type))
{
string? prop = WriteProperty(pi, v);
if (prop != null)
sb.AppendLine(prop.Indent(6));
}
sb.AppendLine(" </div>");
sb.AppendLine(" );");
sb.AppendLine("}");
}
else
{
sb.AppendLine();
sb.AppendLine("export default class {0} extends React.Component<{{ ctx: TypeContext<{1}> }}> {{".FormatWith(GetComponentName(type), type.Name));
sb.AppendLine("");
sb.AppendLine(" render() {");
sb.AppendLine(" var ctx = this.props.ctx;");
sb.AppendLine(" return (");
sb.AppendLine(" <div>");
foreach (var pi in GetProperties(type))
{
string? prop = WriteProperty(pi, v);
if (prop != null)
sb.AppendLine(prop.Indent(8));
}
sb.AppendLine(" </div>");
sb.AppendLine(" );");
sb.AppendLine(" }");
sb.AppendLine("}");
}
return sb.ToString();
}
protected virtual bool GenerateFunctionalComponent(Type type)
{
return true;
}
protected virtual string? WriteProperty(PropertyInfo pi, string v)
{
if (pi.PropertyType.IsLite() || pi.PropertyType.IsIEntity())
return WriteEntityProperty(pi, v);
if (pi.PropertyType.IsEmbeddedEntity())
return WriteEmbeddedProperty(pi, v);
if (pi.PropertyType.IsMList())
return WriteMListProperty(pi, v);
if (IsValue(pi.PropertyType))
return WriteValueLine(pi, v);
return null;
}
protected virtual string WriteMListProperty(PropertyInfo pi, string v)
{
var elementType = pi.PropertyType.ElementType()!.CleanType();
if (!(elementType.IsLite() || elementType.IsModifiableEntity()))
return $"{{ /* {pi.PropertyType.TypeName()} not supported */ }}";
var eka = elementType.GetCustomAttribute<EntityKindAttribute>();
if (elementType.IsEmbeddedEntity() || (eka!.EntityKind == EntityKind.Part || eka!.EntityKind == EntityKind.SharedPart))
if (pi.GetCustomAttribute<ImplementedByAttribute>()?.ImplementedTypes.Length > 1)
return "<EntityRepeater ctx={{ctx.subCtx({0} => {0}.{1})}} />".FormatWith(v, pi.Name.FirstLower());
else
return "<EntityTable ctx={{ctx.subCtx({0} => {0}.{1})}} />".FormatWith(v, pi.Name.FirstLower());
return "<EntityStrip ctx={{ctx.subCtx({0} => {0}.{1})}} />".FormatWith(v, pi.Name.FirstLower());
}
protected virtual string WriteEmbeddedProperty(PropertyInfo pi, string v)
{
return "<EntityDetail ctx={{ctx.subCtx({0} => {0}.{1})}} />".FormatWith(v, pi.Name.FirstLower());
}
protected virtual string WriteEntityProperty(PropertyInfo pi, string v)
{
Type type = pi.PropertyType.CleanType();
var eka = type.GetCustomAttribute<EntityKindAttribute>();
if (eka == null)
return "<EntityLine ctx={{ctx.subCtx({0} => {0}.{1})}} />".FormatWith(v, pi.Name.FirstLower());
if (eka.EntityKind == EntityKind.Part || eka.EntityKind == EntityKind.SharedPart)
return "<EntityDetail ctx={{ctx.subCtx({0} => {0}.{1})}} />".FormatWith(v, pi.Name.FirstLower());
if (eka.IsLowPopulation)
return "<EntityCombo ctx={{ctx.subCtx({0} => {0}.{1})}} />".FormatWith(v, pi.Name.FirstLower());
return "<EntityLine ctx={{ctx.subCtx({0} => {0}.{1})}} />".FormatWith(v, pi.Name.FirstLower());
}
protected virtual bool IsValue(Type type)
{
type = type.UnNullify();
if (type.IsEnum || type == typeof(TimeSpan) || type == typeof(ColorEmbedded))
return true;
TypeCode tc = Type.GetTypeCode(type);
return tc != TypeCode.DBNull &&
tc != TypeCode.Empty &&
tc != TypeCode.Object;
}
protected virtual string WriteValueLine(PropertyInfo pi, string v)
{
return "<ValueLine ctx={{ctx.subCtx({0} => {0}.{1})}} />".FormatWith(v, pi.Name.FirstLower());
}
protected virtual IEnumerable<PropertyInfo> GetProperties(Type type)
{
return Reflector.PublicInstanceDeclaredPropertiesInOrder(type).Where(pi =>
{
var ts = pi.GetCustomAttribute<InTypeScriptAttribute>();
if (ts != null)
{
var inTS = ts.GetInTypeScript();
if (inTS != null)
return inTS.Value;
}
if (pi.HasAttribute<HiddenPropertyAttribute>() || pi.HasAttribute<ExpressionFieldAttribute>())
return false;
return true;
});
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Diagnostics;
using System.Runtime.CompilerServices;
namespace System.Threading.Tasks
{
/// <summary>
/// Provides a set of static (Shared in Visual Basic) methods for working with specific kinds of
/// <see cref="System.Threading.Tasks.Task"/> instances.
/// </summary>
public static class TaskExtensions
{
/// <summary>
/// Creates a proxy <see cref="System.Threading.Tasks.Task">Task</see> that represents the
/// asynchronous operation of a Task{Task}.
/// </summary>
/// <remarks>
/// It is often useful to be able to return a Task from a <see cref="System.Threading.Tasks.Task{TResult}">
/// Task{TResult}</see>, where the inner Task represents work done as part of the outer Task{TResult}. However,
/// doing so results in a Task{Task}, which, if not dealt with carefully, could produce unexpected behavior. Unwrap
/// solves this problem by creating a proxy Task that represents the entire asynchronous operation of such a Task{Task}.
/// </remarks>
/// <param name="task">The Task{Task} to unwrap.</param>
/// <exception cref="T:System.ArgumentNullException">The exception that is thrown if the
/// <paramref name="task"/> argument is null.</exception>
/// <returns>A Task that represents the asynchronous operation of the provided Task{Task}.</returns>
public static Task Unwrap(this Task<Task> task)
{
if (task == null)
throw new ArgumentNullException("task");
// Fast path for an already successfully completed outer task: just return the inner one.
// As in the subsequent slower path, a null inner task is special-cased to mean cancellation.
if (task.Status == TaskStatus.RanToCompletion && (task.CreationOptions & TaskCreationOptions.AttachedToParent) == 0)
{
return task.Result ?? Task.FromCanceled(new CancellationToken(true));
}
// Create a new Task to serve as a proxy for the actual inner task. Attach it
// to the parent if the original was attached to the parent.
var tcs = new TaskCompletionSource<VoidResult>(task.CreationOptions & TaskCreationOptions.AttachedToParent);
TransferAsynchronously(tcs, task);
return tcs.Task;
}
/// <summary>
/// Creates a proxy <see cref="System.Threading.Tasks.Task{TResult}">Task{TResult}</see> that represents the
/// asynchronous operation of a Task{Task{TResult}}.
/// </summary>
/// <remarks>
/// It is often useful to be able to return a Task{TResult} from a Task{TResult}, where the inner Task{TResult}
/// represents work done as part of the outer Task{TResult}. However, doing so results in a Task{Task{TResult}},
/// which, if not dealt with carefully, could produce unexpected behavior. Unwrap solves this problem by
/// creating a proxy Task{TResult} that represents the entire asynchronous operation of such a Task{Task{TResult}}.
/// </remarks>
/// <param name="task">The Task{Task{TResult}} to unwrap.</param>
/// <exception cref="T:System.ArgumentNullException">The exception that is thrown if the
/// <paramref name="task"/> argument is null.</exception>
/// <returns>A Task{TResult} that represents the asynchronous operation of the provided Task{Task{TResult}}.</returns>
public static Task<TResult> Unwrap<TResult>(this Task<Task<TResult>> task)
{
if (task == null)
throw new ArgumentNullException("task");
// Fast path for an already successfully completed outer task: just return the inner one.
// As in the subsequent slower path, a null inner task is special-cased to mean cancellation.
if (task.Status == TaskStatus.RanToCompletion && (task.CreationOptions & TaskCreationOptions.AttachedToParent) == 0)
{
return task.Result ?? Task.FromCanceled<TResult>(new CancellationToken(true));
}
// Create a new Task to serve as a proxy for the actual inner task. Attach it
// to the parent if the original was attached to the parent.
var tcs = new TaskCompletionSource<TResult>(task.CreationOptions & TaskCreationOptions.AttachedToParent);
TransferAsynchronously(tcs, task);
return tcs.Task;
}
/// <summary>
/// Transfer the results of the <paramref name="outer"/> task's inner task to the <paramref name="completionSource"/>.
/// </summary>
/// <param name="completionSource">The completion source to which results should be transfered.</param>
/// <param name="outer">
/// The outer task that when completed will yield an inner task whose results we want marshaled to the <paramref name="completionSource"/>.
/// </param>
private static void TransferAsynchronously<TResult, TInner>(TaskCompletionSource<TResult> completionSource, Task<TInner> outer) where TInner : Task
{
Action callback = null;
// Create a continuation delegate. For performance reasons, we reuse the same delegate/closure across multiple
// continuations; by using .ConfigureAwait(false).GetAwaiter().UnsafeOnComplete(action), in most cases
// this delegate can be stored directly into the Task's continuation field, eliminating the need for additional
// allocations. Thus, this whole Unwrap operation generally results in four allocations: one for the TaskCompletionSource,
// one for the returned task, one for the delegate, and one for the closure. Since the delegate is used
// across multiple continuations, we use the callback variable as well to indicate which continuation we're in:
// if the callback is non-null, then we're processing the continuation for the outer task and use the callback
// object as the continuation off of the inner task; if the callback is null, then we're processing the
// inner task.
callback = delegate
{
Debug.Assert(outer.IsCompleted);
if (callback != null)
{
// Process the outer task's completion
// Clear out the callback field to indicate that any future invocations should
// be for processing the inner task, but store away a local copy in case we need
// to use it as the continuation off of the outer task.
Action innerCallback = callback;
callback = null;
bool result = true;
switch (outer.Status)
{
case TaskStatus.Canceled:
case TaskStatus.Faulted:
// The outer task has completed as canceled or faulted; transfer that
// status to the completion source, and we're done.
result = completionSource.TrySetFromTask(outer);
break;
case TaskStatus.RanToCompletion:
Task inner = outer.Result;
if (inner == null)
{
// The outer task completed successfully, but with a null inner task;
// cancel the completionSource, and we're done.
result = completionSource.TrySetCanceled();
}
else if (inner.IsCompleted)
{
// The inner task also completed! Transfer the results, and we're done.
result = completionSource.TrySetFromTask(inner);
}
else
{
// Run this delegate again once the inner task has completed.
inner.ConfigureAwait(false).GetAwaiter().UnsafeOnCompleted(innerCallback);
}
break;
}
Debug.Assert(result);
}
else
{
// Process the inner task's completion. All we need to do is transfer its results
// to the completion source.
Debug.Assert(outer.Status == TaskStatus.RanToCompletion);
Debug.Assert(outer.Result.IsCompleted);
completionSource.TrySetFromTask(outer.Result);
}
};
// Kick things off by hooking up the callback as the task's continuation
outer.ConfigureAwait(false).GetAwaiter().UnsafeOnCompleted(callback);
}
/// <summary>Copies that ending state information from <paramref name="task"/> to <paramref name="completionSource"/>.</summary>
private static bool TrySetFromTask<TResult>(this TaskCompletionSource<TResult> completionSource, Task task)
{
Debug.Assert(task.IsCompleted);
// Before transferring the results, check to make sure we're not too deep on the stack. Calling TrySet*
// will cause any synchronous continuations to be invoked, which is fine unless we're so deep that doing
// so overflows. ContinueWith has built-in support for avoiding such stack dives, but that support is not
// (yet) part of await's infrastructure, so until it is we mimic it manually. This matches the behavior
// employed by the Unwrap implementation in mscorlib. (If TryEnsureSufficientExecutionStack is made public
// in the future, switch to using it to avoid the try/catch block and exception.)
try
{
RuntimeHelpers.EnsureSufficientExecutionStack();
}
catch (InsufficientExecutionStackException)
{
// This is very rare. We're too deep to safely invoke
// TrySet* synchronously, so do so asynchronously instead.
Task.Factory.StartNew(s =>
{
var t = (Tuple<TaskCompletionSource<TResult>, Task>)s;
TrySetFromTask(t.Item1, t.Item2);
}, Tuple.Create(completionSource, task), CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default);
return true;
}
// Transfer the results from the supplied Task to the TaskCompletionSource.
bool result = false;
switch(task.Status)
{
case TaskStatus.Canceled:
result = completionSource.TrySetCanceled(ExtractCancellationToken(task));
break;
case TaskStatus.Faulted:
result = completionSource.TrySetException(task.Exception.InnerExceptions);
break;
case TaskStatus.RanToCompletion:
Task<TResult> resultTask = task as Task<TResult>;
result = resultTask != null ?
completionSource.TrySetResult(resultTask.Result) :
completionSource.TrySetResult(default(TResult));
break;
}
return result;
}
/// <summary>Gets the CancellationToken associated with a canceled task.</summary>
private static CancellationToken ExtractCancellationToken(Task task)
{
// With the public Task APIs as of .NET 4.6, the only way to extract a CancellationToken
// that was associated with a Task is by await'ing it, catching the resulting
// OperationCanceledException, and getting the token from the OCE.
Debug.Assert(task.IsCanceled);
try
{
task.GetAwaiter().GetResult();
}
catch (OperationCanceledException oce)
{
CancellationToken ct = oce.CancellationToken;
if (ct.IsCancellationRequested)
return ct;
}
return new CancellationToken(true);
}
/// <summary>Dummy type to use as a void TResult.</summary>
private struct VoidResult { }
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Dynamic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Massive
{
public static class ObjectExtensions
{
/// <summary>
/// Extension method for adding in a bunch of parameters
/// </summary>
public static void AddParams(this SqlCommand cmd, params object[] args)
{
foreach (var item in args)
{
AddParam(cmd, item);
}
}
/// <summary>
/// Extension for adding single parameter
/// </summary>
public static void AddParam(this SqlCommand cmd, object item)
{
var p = cmd.CreateParameter();
p.ParameterName = string.Format("@{0}", cmd.Parameters.Count);
if (item == null)
{
p.Value = DBNull.Value;
}
else
{
if (item is Guid)
{
p.Value = item;
p.SqlDbType = SqlDbType.UniqueIdentifier;
}
else if (item is ExpandoObject)
{
var d = (IDictionary<string, object>) item;
p.Value = d.Values.FirstOrDefault();
}
else
{
p.Value = item;
}
if (item is string)
p.Size = ((string) item).Length > 4000 ? -1 : 4000;
}
cmd.Parameters.Add(p);
}
/// <summary>
/// Turns an IDataReader to a Dynamic list of things
/// </summary>
public static List<dynamic> ToExpandoList(this IDataReader rdr)
{
var result = new List<dynamic>();
while (rdr.Read())
{
result.Add(rdr.RecordToExpando());
}
return result;
}
public static dynamic RecordToExpando(this IDataReader rdr)
{
dynamic e = new ExpandoObject();
var d = e as IDictionary<string, object>;
for (int i = 0; i < rdr.FieldCount; i++)
d.Add(rdr.GetName(i), DBNull.Value.Equals(rdr[i]) ? null : rdr[i]);
return e;
}
/// <summary>
/// Turns the object into an ExpandoObject
/// </summary>
public static dynamic ToExpando(this object o)
{
var result = new ExpandoObject();
var d = result as IDictionary<string, object>; //work with the Expando as a Dictionary
if (o is ExpandoObject) return o; //shouldn't have to... but just in case
if (o.GetType() == typeof (NameValueCollection) || o.GetType().IsSubclassOf(typeof (NameValueCollection)))
{
var nv = (NameValueCollection) o;
foreach (string i in nv) d.Add(i, nv[i]);
}
else
{
var props = o.GetType().GetProperties();
foreach (var item in props)
{
d.Add(item.Name, item.GetValue(o, null));
}
}
return result;
}
/// <summary>
/// Turns the object into a Dictionary
/// </summary>
public static IDictionary<string, object> ToDictionary(this object thingy)
{
return (IDictionary<string, object>) thingy.ToExpando();
}
}
/// <summary>
/// Convenience class for opening/executing data
/// </summary>
public static class DB
{
public static DynamicModel Current
{
get
{
if (ConfigurationManager.ConnectionStrings.Count > 1)
{
return new DynamicModel(ConfigurationManager.ConnectionStrings[1].Name);
}
throw new InvalidOperationException("Need a connection string name - can't determine what it is");
}
}
}
/// <summary>
/// A class that wraps your database table in Dynamic Funtime
/// </summary>
public class DynamicModel : DynamicObject
{
private readonly DbProviderFactory _factory;
private readonly string _connectionString;
public static DynamicModel Open(string connectionStringName)
{
dynamic dm = new DynamicModel(connectionStringName);
return dm;
}
public DynamicModel(string connectionStringName, string tableName = "", string primaryKeyField = "", string descriptorField = "", bool primaryKeyIsIdentity = false)
{
TableName = tableName == "" ? this.GetType().Name : tableName;
PrimaryKeyField = string.IsNullOrEmpty(primaryKeyField) ? "ID" : primaryKeyField;
DescriptorField = descriptorField;
PrimaryKeyIsIdentity = primaryKeyIsIdentity;
var _providerName = "System.Data.SqlClient";
if (ConfigurationManager.ConnectionStrings[connectionStringName].ProviderName != null)
_providerName = ConfigurationManager.ConnectionStrings[connectionStringName].ProviderName;
_factory = DbProviderFactories.GetFactory(_providerName);
_connectionString = ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString;
}
/// <summary>
/// Creates a new Expando from a Form POST - white listed against the columns in the DB
/// </summary>
public dynamic CreateFrom(NameValueCollection coll)
{
dynamic result = new ExpandoObject();
var dc = (IDictionary<string, object>) result;
var schema = Schema;
//loop the collection, setting only what's in the Schema
foreach (var item in coll.Keys)
{
var exists = schema.Any(x => x.COLUMN_NAME.ToLower() == item.ToString().ToLower());
if (exists)
{
var key = item.ToString();
var val = coll[key];
dc.Add(key, val);
}
}
return result;
}
/// <summary>
/// Gets a default value for the column
/// </summary>
public dynamic DefaultValue(dynamic column)
{
dynamic result;
string def = column.COLUMN_DEFAULT;
if (String.IsNullOrEmpty(def))
{
result = null;
}
else if (def == "getdate()" || def == "(getdate())")
{
result = DateTime.Now.ToShortDateString();
}
else if (def == "newid()" || def == "(newid())")
{
result = Guid.NewGuid().ToString();
}
else
{
result = def.Replace("(", "").Replace(")", "");
}
return result;
}
/// <summary>
/// Creates an empty Expando set with defaults from the DB
/// </summary>
public dynamic Prototype
{
get
{
dynamic result = new ExpandoObject();
var schema = Schema;
foreach (dynamic column in schema)
{
var dc = (IDictionary<string, object>) result;
dc.Add(column.COLUMN_NAME, DefaultValue(column));
}
result._Table = this;
return result;
}
}
public string DescriptorField { get; private set; }
/// <summary>
/// List out all the schema bits for use with ... whatever
/// </summary>
private IEnumerable<dynamic> _schema;
public IEnumerable<dynamic> Schema
{
get { return _schema ?? (_schema = Query("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @0", TableName)); }
}
/// <summary>
/// Enumerates the reader yielding the result - thanks to Jeroen Haegebaert
/// </summary>
public virtual IEnumerable<dynamic> Query(string sql, params object[] args)
{
using (var conn = OpenConnection())
{
var rdr = CreateCommand(sql, conn, args).ExecuteReader();
while (rdr.Read())
{
yield return rdr.RecordToExpando();
}
}
}
public virtual IEnumerable<dynamic> Query(string sql, SqlConnection connection, params object[] args)
{
using (var rdr = CreateCommand(sql, connection, args).ExecuteReader())
{
while (rdr.Read())
{
yield return rdr.RecordToExpando();
}
}
}
/// <summary>
/// Executes the reader using SQL async API - thanks to Damian Edwards
/// </summary>
public void QueryAsync(string sql, Action<List<dynamic>> callback, params object[] args)
{
var conn = new SqlConnection(_connectionString);
using (var cmd = new SqlCommand(sql, conn))
{
cmd.AddParams(args);
try
{
conn.Open();
var task = Task.Factory.FromAsync<IDataReader>(cmd.BeginExecuteReader, cmd.EndExecuteReader, null);
task.ContinueWith(x =>
{
var result = x.Result.ToExpandoList();
conn.Dispose();
callback.Invoke(result);
});
}
catch (DbException)
{
if (conn.State == ConnectionState.Open)
conn.Close();
throw;
}
}
}
/// <summary>
/// Returns a single result
/// </summary>
public virtual object Scalar(string sql, params object[] args)
{
object result;
using (var conn = OpenConnection())
{
result = CreateCommand(sql, conn, args).ExecuteScalar();
}
return result;
}
/// <summary>
/// Creates a SqlCommand that you can use for loving your database.
/// </summary>
private SqlCommand CreateCommand(string sql, SqlConnection conn, params object[] args)
{
var result = _factory.CreateCommand() as SqlCommand;
if (result != null)
{
result.Connection = conn;
result.CommandText = sql;
if (args.Length > 0)
result.AddParams(args);
return result;
}
throw new Exception("Can not create database connection");
}
/// <summary>
/// Returns and OpenConnection
/// </summary>
public virtual SqlConnection OpenConnection()
{
var result = _factory.CreateConnection() as SqlConnection;
if (result != null)
{
result.ConnectionString = _connectionString;
result.Open();
return result;
}
throw new Exception("Cannot create database connection");
}
/// <summary>
/// Builds a set of Insert and Update commands based on the passed-on objects.
/// These objects can be POCOs, Anonymous, NameValueCollections, or Expandos. Objects
/// With a PK property (whatever PrimaryKeyField is set to) will be created at UPDATEs
/// </summary>
public virtual List<SqlCommand> BuildCommands(params object[] things)
{
return things.Select(item => HasPrimaryKey(item) ? CreateUpdateCommand(item, GetPrimaryKey(item)) : CreateInsertCommand(item)).ToList();
}
public virtual int Execute(SqlCommand command)
{
return Execute(new[] {command});
}
public virtual int Execute(string sql, params object[] args)
{
return Execute(CreateCommand(sql, null, args));
}
/// <summary>
/// Executes a series of SqlCommand in a transaction
/// </summary>
public virtual int Execute(IEnumerable<SqlCommand> commands)
{
var result = 0;
using (var conn = OpenConnection())
{
using (var tx = conn.BeginTransaction())
{
foreach (var cmd in commands)
{
cmd.Connection = conn;
cmd.Transaction = tx;
result += cmd.ExecuteNonQuery();
}
tx.Commit();
}
}
return result;
}
public virtual string PrimaryKeyField { get; set; }
/// <summary>
/// Conventionally introspects the object passed in for a field that
/// looks like a PK. If you've named your PrimaryKeyField, this becomes easy
/// </summary>
public virtual bool HasPrimaryKey(object o)
{
return o.ToDictionary().ContainsKey(PrimaryKeyField);
}
/// <summary>
/// If the object passed in has a property with the same name as your PrimaryKeyField
/// it is returned here.
/// </summary>
public virtual object GetPrimaryKey(object o)
{
object result;
o.ToDictionary().TryGetValue(PrimaryKeyField, out result);
return result;
}
public virtual string TableName { get; set; }
public virtual bool PrimaryKeyIsIdentity { get; set; }
/// <summary>
/// Returns all records complying with the passed-in WHERE clause and arguments,
/// ordered as specified, limited (TOP) by limit.
/// </summary>
public virtual IEnumerable<dynamic> All(string where = "", string orderBy = "", int limit = 0, string columns = "*", params object[] args)
{
string sql = BuildSelect(where, orderBy, limit);
return Query(string.Format(sql, columns, TableName), args);
}
private static string BuildSelect(string where, string orderBy, int limit)
{
string sql = limit > 0 ? "SELECT TOP " + limit + " {0} FROM {1} " : "SELECT {0} FROM {1} ";
if (!string.IsNullOrEmpty(where))
sql += where.Trim().StartsWith("where", StringComparison.OrdinalIgnoreCase) ? where : "WHERE " + where;
if (!String.IsNullOrEmpty(orderBy))
sql += orderBy.Trim().StartsWith("order by", StringComparison.OrdinalIgnoreCase) ? orderBy : " ORDER BY " + orderBy;
return sql;
}
/// <summary>
/// Returns a dynamic PagedResult. Result properties are Items, TotalPages, and TotalRecords.
/// </summary>
public virtual dynamic Paged(string where = "", string orderBy = "", string columns = "*", int pageSize = 20, int currentPage = 1, params object[] args)
{
return BuildPagedResult(where: where, orderBy: orderBy, columns: columns, pageSize: pageSize, currentPage: currentPage, args: args);
}
public virtual dynamic Paged(string sql, string primaryKey, string where = "", string orderBy = "", string columns = "*", int pageSize = 20, int currentPage = 1, params object[] args)
{
return BuildPagedResult(sql, primaryKey, where, orderBy, columns, pageSize, currentPage, args);
}
private dynamic BuildPagedResult(string sql = "", string primaryKeyField = "", string where = "", string orderBy = "", string columns = "*", int pageSize = 20, int currentPage = 1, params object[] args)
{
dynamic result = new ExpandoObject();
var countSQL = !string.IsNullOrEmpty(sql)
? string.Format("SELECT COUNT({0}) FROM ({1}) AS PagedTable", primaryKeyField, sql)
: string.Format("SELECT COUNT({0}) FROM {1}", PrimaryKeyField, TableName);
if (String.IsNullOrEmpty(orderBy))
{
orderBy = string.IsNullOrEmpty(primaryKeyField) ? PrimaryKeyField : primaryKeyField;
}
if (!string.IsNullOrEmpty(where))
{
if (!where.Trim().StartsWith("where", StringComparison.CurrentCultureIgnoreCase))
{
where = "WHERE " + where;
}
}
string query = !string.IsNullOrEmpty(sql)
? string.Format(
"SELECT {0} FROM (SELECT ROW_NUMBER() OVER (ORDER BY {1}) AS Row, {0} FROM ({2}) AS PagedTable {3}) AS Paged ",
columns, orderBy, sql, where)
: string.Format(
"SELECT {0} FROM (SELECT ROW_NUMBER() OVER (ORDER BY {1}) AS Row, {0} FROM {2} {3}) AS Paged ",
columns, orderBy, TableName, where);
var pageStart = (currentPage - 1)*pageSize;
query += string.Format(" WHERE Row > {0} AND Row <={1}", pageStart, (pageStart + pageSize));
countSQL += where;
result.TotalRecords = Scalar(countSQL, args);
result.TotalPages = result.TotalRecords/pageSize;
if (result.TotalRecords%pageSize > 0)
result.TotalPages += 1;
result.Items = Query(string.Format(query, columns, TableName), args);
return result;
}
/// <summary>
/// Returns a single row from the database
/// </summary>
public virtual dynamic Single(string where, string columns = "*", params object[] args)
{
var sql = string.Format("SELECT {0} FROM {1} WHERE {2}", columns, TableName, where);
return Query(sql, args).FirstOrDefault();
}
/// <summary>
/// Returns a single row from the database
/// </summary>
public virtual dynamic Single(object key, string columns = "*")
{
var sql = string.Format("SELECT {0} FROM {1} WHERE {2} = @0", columns, TableName, PrimaryKeyField);
return Query(sql, key).FirstOrDefault();
}
/// <summary>
/// This will return a string/object dictionary for dropdowns etc
/// </summary>
public virtual IDictionary<string, object> KeyValues(string orderBy = "")
{
if (String.IsNullOrEmpty(DescriptorField))
throw new InvalidOperationException("There's no DescriptorField set - do this in your constructor to describe the text value you want to see");
var sql = string.Format("SELECT {0},{1} FROM {2} ", PrimaryKeyField, DescriptorField, TableName);
if (!String.IsNullOrEmpty(orderBy))
sql += "ORDER BY " + orderBy;
return (IDictionary<string, object>) Query(sql);
}
/// <summary>
/// This will return an Expando as a Dictionary
/// </summary>
public virtual IDictionary<string, object> ItemAsDictionary(ExpandoObject item)
{
return item;
}
//Checks to see if a key is present based on the passed-in value
public virtual bool ItemContainsKey(string key, ExpandoObject item)
{
var dc = ItemAsDictionary(item);
return dc.ContainsKey(key);
}
/// <summary>
/// Executes a set of objects as Insert or Update commands based on their property settings, within a transaction.
/// These objects can be POCOs, Anonymous, NameValueCollections, or Expandos. Objects
/// With a PK property (whatever PrimaryKeyField is set to) will be created at UPDATEs
/// </summary>
public virtual int Save(params object[] things)
{
if (things.Any(item => !IsValid(item)))
{
throw new InvalidOperationException("Can't save this item: " + String.Join("; ", Errors.ToArray()));
}
var commands = BuildCommands(things);
return Execute(commands);
}
public virtual SqlCommand CreateInsertCommand(dynamic expando)
{
var settings = (IDictionary<string, object>) expando;
var sbKeys = new StringBuilder();
var sbVals = new StringBuilder();
const string stub = "INSERT INTO {0} ({1}) \r\n VALUES ({2})";
var result = CreateCommand(stub, null);
int counter = 0;
foreach (var item in settings.Where(x => x.Value != null && !(PrimaryKeyIsIdentity && x.Key.Equals(PrimaryKeyField))))
{
sbKeys.AppendFormat("{0},", item.Key);
sbVals.AppendFormat("@{0},", counter);
result.AddParam(item.Value);
counter++;
}
if (counter > 0)
{
var keys = sbKeys.ToString().Substring(0, sbKeys.Length - 1);
var vals = sbVals.ToString().Substring(0, sbVals.Length - 1);
var sql = string.Format(stub, TableName, keys, vals);
result.CommandText = sql;
}
else throw new InvalidOperationException("Can't parse this object to the database - there are no properties set");
return result;
}
/// <summary>
/// Creates a command for use with transactions - internal stuff mostly, but here for you to play with
/// </summary>
public virtual SqlCommand CreateUpdateCommand(dynamic expando, object key)
{
var settings = (IDictionary<string, object>) expando;
var sbKeys = new StringBuilder();
const string stub = "UPDATE {0} SET {1} WHERE {2} = @{3}";
var result = CreateCommand(stub, null);
int counter = 0;
foreach (var item in settings)
{
var val = item.Value;
if (!item.Key.Equals(PrimaryKeyField, StringComparison.OrdinalIgnoreCase))
{
result.AddParam(val);
sbKeys.AppendFormat("{0} = @{1}, \r\n", item.Key, counter);
counter++;
}
}
if (counter > 0)
{
//add the key
result.AddParam(key);
//strip the last commas
var keys = sbKeys.ToString().Substring(0, sbKeys.Length - 4);
result.CommandText = string.Format(stub, TableName, keys, PrimaryKeyField, counter);
}
else throw new InvalidOperationException("No parsable object was sent in - could not divine any name/value pairs");
return result;
}
/// <summary>
/// Removes one or more records from the DB according to the passed-in WHERE
/// </summary>
public virtual SqlCommand CreateDeleteCommand(string where = "", object key = null, params object[] args)
{
var sql = string.Format("DELETE FROM {0} ", TableName);
if (key != null)
{
sql += string.Format("WHERE {0}=@0", PrimaryKeyField);
args = new[] {key};
}
else if (!string.IsNullOrEmpty(where))
{
sql += where.Trim().StartsWith("where", StringComparison.OrdinalIgnoreCase) ? where : "WHERE " + where;
}
return CreateCommand(sql, null, args);
}
public bool IsValid(dynamic item)
{
Errors.Clear();
Validate(item);
return Errors.Count == 0;
}
//Temporary holder for error messages
public IList<string> Errors = new List<string>();
/// <summary>
/// Adds a record to the database. You can pass in an Anonymous object, an ExpandoObject,
/// A regular old POCO, or a NameValueColletion from a Request.Form or Request.QueryString
/// </summary>
public virtual dynamic Insert(object o)
{
var ex = o.ToExpando();
if (!IsValid(ex))
{
throw new InvalidOperationException("Can't insert: " + String.Join("; ", Errors.ToArray()));
}
if (BeforeSave(ex))
{
using (dynamic conn = OpenConnection())
{
var cmd = CreateInsertCommand(ex);
cmd.Connection = conn;
cmd.ExecuteNonQuery();
cmd.CommandText = "SELECT @@IDENTITY as newID";
ex.ID = cmd.ExecuteScalar();
Inserted(ex);
}
return ex;
}
return null;
}
/// <summary>
/// Updates a record in the database. You can pass in an Anonymous object, an ExpandoObject,
/// A regular old POCO, or a NameValueCollection from a Request.Form or Request.QueryString
/// </summary>
public virtual int Update(object o, object key = null)
{
var ex = o.ToExpando() as IDictionary<string, object>;
if (!IsValid(ex))
{
throw new InvalidOperationException("Can't Update: " + String.Join("; ", Errors.ToArray()));
}
var result = 0;
if (BeforeSave(ex))
{
result = Execute(CreateUpdateCommand(ex, key ?? GetPrimaryKey(o)));
Updated(ex);
}
return result;
}
/// <summary>
/// Removes one or more records from the DB according to the passed-in WHERE
/// </summary>
public int Delete(object key = null, string where = "", params object[] args)
{
var deleted = this.Single(key);
var result = 0;
if (BeforeDelete(deleted))
{
result = Execute(CreateDeleteCommand(where, key, args));
Deleted(deleted);
}
return result;
}
public void DefaultTo(string key, object value, dynamic item)
{
if (!ItemContainsKey(key, item))
{
var dc = (IDictionary<string, object>) item;
dc[key] = value;
}
}
//Hooks
public virtual void Validate(dynamic item)
{}
public virtual void Inserted(dynamic item)
{}
public virtual void Updated(dynamic item)
{}
public virtual void Deleted(dynamic item)
{}
public virtual bool BeforeDelete(dynamic item)
{
return true;
}
public virtual bool BeforeSave(dynamic item)
{
return true;
}
//validation methods
public virtual void ValidatesPresenceOf(object value, string message = "Required")
{
if (value == null)
Errors.Add(message);
else if (String.IsNullOrEmpty(value.ToString()))
Errors.Add(message);
}
//fun methods
public virtual void ValidatesNumericalityOf(object value, string message = "Should be a number")
{
var type = value.GetType().Name;
var numerics = new[] {"Int32", "Int16", "Int64", "Decimal", "Double", "Single", "Float"};
if (!numerics.Contains(type))
{
Errors.Add(message);
}
}
public virtual void ValidateIsCurrency(object value, string message = "Should be money")
{
if (value == null)
Errors.Add(message);
else
{
decimal val;
decimal.TryParse(value.ToString(), out val);
if (val == decimal.MinValue)
Errors.Add(message);
}
}
public int Count()
{
return Count(TableName);
}
public int Count(string tableName, string where = "")
{
return (int) Scalar("SELECT COUNT(*) FROM " + tableName + " " + where);
}
/// <summary>
/// A helpful query tool
/// </summary>
public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
{
//parse the method
var constraints = new List<string>();
var counter = 0;
var info = binder.CallInfo;
// accepting named args only... SKEET!
if (info.ArgumentNames.Count != args.Length)
{
throw new InvalidOperationException("Please use named arguments for this type of query - the column name, orderby, columns, etc");
}
//first should be "FindBy, Last, Single, First"
var op = binder.Name;
var columns = " * ";
string orderBy = string.Format(" ORDER BY {0}", PrimaryKeyField);
string where = "";
var whereArgs = new List<object>();
//loop the named args - see if we have order, columns and constraints
if (info.ArgumentNames.Count > 0)
{
for (int i = 0; i < args.Length; i++)
{
var name = info.ArgumentNames[i].ToLower();
switch (name)
{
case "orderby":
orderBy = " ORDER BY " + args[i];
break;
case "columns":
columns = args[i].ToString();
break;
default:
constraints.Add(string.Format(" {0} = @{1}", name, counter));
whereArgs.Add(args[i]);
counter++;
break;
}
}
}
//Build the WHERE bits
if (constraints.Count > 0)
{
where = " WHERE " + string.Join(" AND ", constraints.ToArray());
}
//probably a bit much here but... yeah this whole thing needs to be refactored...
if (op.ToLower() == "count")
{
result = Scalar("SELECT COUNT(*) FROM " + TableName + where, whereArgs.ToArray());
}
else if (op.ToLower() == "sum")
{
result = Scalar("SELECT SUM(" + columns + ") FROM " + TableName + where, whereArgs.ToArray());
}
else if (op.ToLower() == "max")
{
result = Scalar("SELECT MAX(" + columns + ") FROM " + TableName + where, whereArgs.ToArray());
}
else if (op.ToLower() == "min")
{
result = Scalar("SELECT MIN(" + columns + ") FROM " + TableName + where, whereArgs.ToArray());
}
else if (op.ToLower() == "avg")
{
result = Scalar("SELECT AVG(" + columns + ") FROM " + TableName + where, whereArgs.ToArray());
}
else
{
//build the SQL
string sql = "SELECT TOP 1 " + columns + " FROM " + TableName + where;
var justOne = op.StartsWith("First") || op.StartsWith("Last") || op.StartsWith("Get") || op.StartsWith("Single");
//Be sure to sort by DESC on the PK (PK Sort is the default)
if (op.StartsWith("Last"))
{
orderBy = orderBy + " DESC ";
}
else
{
//default to multiple
sql = "SELECT " + columns + " FROM " + TableName + where;
}
result = justOne ? Query(sql + orderBy, whereArgs.ToArray()).FirstOrDefault() : Query(sql + orderBy, whereArgs.ToArray());
}
return true;
}
}
}
| |
/*
* TestMarshal.cs - Test the "Marshal" class.
*
* Copyright (C) 2003 Southern Storm Software, Pty Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
using CSUnit;
using System;
using System.Reflection;
using System.Runtime.InteropServices;
public class TestMarshal : TestCase
{
// Test values.
private static readonly byte[] foobar =
{(byte)'f', (byte)'o', (byte)'o', (byte)'b', (byte)'a', (byte)'r'};
private static readonly long[] numbers =
{1, 2, 3, 4, 5, 6};
// Constructor.
public TestMarshal(String name)
: base(name)
{
// Nothing to do here.
}
// Set up for the tests.
protected override void Setup()
{
// Nothing to do here.
}
// Clean up after the tests.
protected override void Cleanup()
{
// Nothing to do here.
}
// Test HGlobal memory allocation and reallocation.
public void TestMarshalHGlobal()
{
int size = 16384;
int size2 = size + 1024;
IntPtr ptr;
int posn;
// Allocate a 16k block of memory.
ptr = Marshal.AllocHGlobal(size);
Assert("NullCheck (1)", (ptr != IntPtr.Zero));
// Verify that the block is all-zeroes.
for(posn = 0; posn < size; ++posn)
{
if(Marshal.ReadByte(ptr, posn) != 0)
{
Fail("ZeroCheck (" + posn.ToString() + ")");
}
}
// Fill the block with 0xDD.
for(posn = 0; posn < size; ++posn)
{
Marshal.WriteByte(ptr, posn, (byte)0xDD);
}
// Verify that the block is now all-0xDD.
for(posn = 0; posn < size; ++posn)
{
if(Marshal.ReadByte(ptr, posn) != 0xDD)
{
Fail("SetCheck (" + posn.ToString() + ")");
}
}
// Re-allocate the block to a larger size.
ptr = Marshal.ReAllocHGlobal(ptr, new IntPtr(size2));
Assert("NullCheck (2)", (ptr != IntPtr.Zero));
// Verify that the bottom part of the block is still all-0xDD.
for(posn = 0; posn < size; ++posn)
{
if(Marshal.ReadByte(ptr, posn) != 0xDD)
{
Fail("SetCheck2 (" + posn.ToString() + ")");
}
}
// Fill from the mid-point to the end with 0xAA.
for(posn = size / 2; posn < size2; ++posn)
{
Marshal.WriteByte(ptr, posn, (byte)0xAA);
}
// Re-validate the block's contents.
for(posn = 0; posn < size / 2; ++posn)
{
if(Marshal.ReadByte(ptr, posn) != 0xDD)
{
Fail("SetCheck3 (" + posn.ToString() + ")");
}
}
for(posn = size / 2; posn < size2; ++posn)
{
if(Marshal.ReadByte(ptr, posn) != 0xAA)
{
Fail("SetCheck4 (" + posn.ToString() + ")");
}
}
// Re-allocate the block to a smaller size.
size2 = size * 3 / 4;
ptr = Marshal.ReAllocHGlobal(ptr, new IntPtr(size2));
Assert("NullCheck (3)", (ptr != IntPtr.Zero));
// Make sure the block's contents are still correct.
for(posn = 0; posn < size / 2; ++posn)
{
if(Marshal.ReadByte(ptr, posn) != 0xDD)
{
Fail("SetCheck5 (" + posn.ToString() + ")");
}
}
for(posn = size / 2; posn < size2; ++posn)
{
if(Marshal.ReadByte(ptr, posn) != 0xAA)
{
Fail("SetCheck6 (" + posn.ToString() + ")");
}
}
// Free the block.
Marshal.FreeHGlobal(ptr);
}
// Test copies from managed to unmanaged.
public unsafe void TestMarshalCopyToUnmanaged()
{
// Check exception conditions.
try
{
Marshal.Copy((byte[])null, 0, new IntPtr(3), 0);
Fail("NullCheck (1)");
}
catch(ArgumentNullException)
{
// Success.
}
try
{
Marshal.Copy(new int [3], 0, IntPtr.Zero, 0);
Fail("NullCheck (2)");
}
catch(ArgumentNullException)
{
// Success.
}
try
{
Marshal.Copy(new long [3], -1, new IntPtr(3), 0);
Fail("RangeCheck (3)");
}
catch(ArgumentOutOfRangeException)
{
// Success.
}
try
{
Marshal.Copy(new byte [3], 0, new IntPtr(3), 4);
Fail("RangeCheck (4)");
}
catch(ArgumentOutOfRangeException)
{
// Success.
}
try
{
Marshal.Copy(new byte [3], 3, new IntPtr(3), 1);
Fail("RangeCheck (5)");
}
catch(ArgumentOutOfRangeException)
{
// Success.
}
// Allocate a block and copy "foobar" into it.
IntPtr ptr = Marshal.AllocHGlobal(6);
Marshal.Copy(foobar, 0, ptr, 6);
// Check that the block does indeed contain "foobar".
int posn;
for(posn = 0; posn < 6; ++posn)
{
if(Marshal.ReadByte(ptr, posn) != foobar[posn])
{
Fail("SetCheck1 (" + posn.ToString() + ")");
}
}
Marshal.FreeHGlobal(ptr);
// Allocate another block and copy numbers into it.
ptr = Marshal.AllocHGlobal(6 * sizeof(long));
Marshal.Copy(numbers, 0, ptr, 6);
// Check that the block does indeed contain the numbers.
for(posn = 0; posn < 6; ++posn)
{
if(Marshal.ReadInt64(ptr, posn * 8) != numbers[posn])
{
Fail("SetCheck2 (" + posn.ToString() + ")");
}
}
Marshal.FreeHGlobal(ptr);
}
// Test copies from unmanaged to managed.
public unsafe void TestMarshalCopyToManaged()
{
// Check exception conditions.
try
{
Marshal.Copy(new IntPtr(3), (byte[])null, 0, 0);
Fail("NullCheck (1)");
}
catch(ArgumentNullException)
{
// Success.
}
try
{
Marshal.Copy(IntPtr.Zero, new int [3], 0, 0);
Fail("NullCheck (2)");
}
catch(ArgumentNullException)
{
// Success.
}
try
{
Marshal.Copy(new IntPtr(3), new long [3], -1, 0);
Fail("RangeCheck (3)");
}
catch(ArgumentOutOfRangeException)
{
// Success.
}
try
{
Marshal.Copy(new IntPtr(3), new byte [3], 0, 4);
Fail("RangeCheck (4)");
}
catch(ArgumentOutOfRangeException)
{
// Success.
}
try
{
Marshal.Copy(new IntPtr(3), new byte [3], 3, 1);
Fail("RangeCheck (5)");
}
catch(ArgumentOutOfRangeException)
{
// Success.
}
// Allocate a block and copy "foobar" into it.
IntPtr ptr = Marshal.AllocHGlobal(6);
int posn;
for(posn = 0; posn < 6; ++posn)
{
Marshal.WriteByte(ptr, posn, foobar[posn]);
}
// Copy the data out into a byte buffer.
byte[] buffer = new byte [6];
Marshal.Copy(ptr, buffer, 0, 6);
// Check that the buffer does indeed contain "foobar".
for(posn = 0; posn < 6; ++posn)
{
if(buffer[posn] != foobar[posn])
{
Fail("SetCheck1 (" + posn.ToString() + ")");
}
}
Marshal.FreeHGlobal(ptr);
// Allocate another block and copy numbers into it.
ptr = Marshal.AllocHGlobal(6 * sizeof(long));
for(posn = 0; posn < 6; ++posn)
{
Marshal.WriteInt64(ptr, posn * 8, numbers[posn]);
}
// Copy the data out into a long buffer.
long[] lbuffer = new long [6];
Marshal.Copy(ptr, lbuffer, 0, 6);
// Check that the buffer does indeed contain the numbers.
for(posn = 0; posn < 6; ++posn)
{
if(lbuffer[posn] != numbers[posn])
{
Fail("SetCheck2 (" + posn.ToString() + ")");
}
}
Marshal.FreeHGlobal(ptr);
}
// Test structure for "OffsetOf" and "SizeOf".
private struct OffsetStruct
{
public int x;
public int y;
};
// Test the "OffsetOf" method.
public void TestMarshalOffsetOf()
{
// Simple tests that should succeed.
AssertEquals("OffsetOf (1)", IntPtr.Zero,
Marshal.OffsetOf(typeof(OffsetStruct), "x"));
AssertEquals("OffsetOf (2)", new IntPtr(4),
Marshal.OffsetOf(typeof(OffsetStruct), "y"));
// Test exception cases.
try
{
Marshal.OffsetOf(null, "x");
Fail("OffsetOf (3)");
}
catch(ArgumentNullException)
{
// Success.
}
try
{
Marshal.OffsetOf(typeof(OffsetStruct), null);
Fail("OffsetOf (4)");
}
catch(ArgumentNullException)
{
// Success.
}
#if CONFIG_REFLECTION && !ECMA_COMPAT
try
{
// TypeDelegator is not a runtime type.
Marshal.OffsetOf(new TypeDelegator(typeof(int)), "value_");
Fail("OffsetOf (5)");
}
catch(ArgumentException)
{
// Success.
}
#endif
try
{
Marshal.OffsetOf(typeof(OffsetStruct), "z");
Fail("OffsetOf (6)");
}
catch(ArgumentException)
{
// Success.
}
}
// Test the "SizeOf" method.
public void TestMarshalSizeOf()
{
// Simple tests that should succeed.
Assert("SizeOf (1)",
(Marshal.SizeOf(typeof(OffsetStruct)) >= 8));
AssertEquals("SizeOf (2)", 4, Marshal.SizeOf((Object)3));
// Test exception cases.
try
{
Marshal.SizeOf((Type)null);
Fail("SizeOf (3)");
}
catch(ArgumentNullException)
{
// Success.
}
#if CONFIG_REFLECTION && !ECMA_COMPAT
try
{
Marshal.SizeOf(new TypeDelegator(typeof(int)));
Fail("SizeOf (4)");
}
catch(ArgumentException)
{
// Success.
}
#endif
try
{
Marshal.SizeOf((Object)null);
Fail("SizeOf (5)");
}
catch(ArgumentNullException)
{
// Success.
}
}
}; // class TestMarshal
| |
namespace Palantir.Numeric.UnitTests
{
using System;
using System.Collections.Generic;
using System.Linq;
using Xunit;
using FluentAssertions;
using Palantir.Numeric;
public class UnitsOfMeasureTests
{
[Fact]
public void CreateSimpleUnit_ShouldSetProperties()
{
var g = new Unit("g", "Gram");
g.Abbreviation.Should().Be("g");
g.Name.Should().Be("Gram");
}
[Fact]
public void AddUnitConversion_ShouldEnableConversion()
{
var kg = new Unit("kg", "Kilogram");
var g = new Unit("g", "Gram");
kg.AddConversion(g, x => x * 1000);
kg.CanConvertTo(g).Should().BeTrue();
}
[Fact]
public void CreateSimpleMeasure_ShouldSetProperties()
{
var kg = new Unit("kg");
var weight = new Measure(110, kg);
weight.Value.Should().Be(110);
weight.Unit.Should().Be(kg);
}
[Fact]
public void MeasureConvertUnit_WhenConvertible_ShouldProduceResult()
{
var kg = new Unit("kg");
var g = new Unit("g");
kg.AddConversion(g, x => x * 1000);
var weight = new Measure(110, kg);
var result = weight.ConvertTo(g);
result.Value.Should().Be(110000);
result.Unit.Should().Be(g);
}
[Fact]
public void MeasureConvertUnit_WhenNotConvertible_ShouldError()
{
var kg = new Unit("kg");
var g = new Unit("g");
var weight = new Measure(110, kg);
Action action = () => weight.ConvertTo(g);
action.ShouldThrow<IncompatibleUnitException>();
}
[Fact]
public void MeasureAddition_WithSameUnit_ShouldProduceResult()
{
var kg = new Unit("kg");
var weight1 = new Measure(110, kg);
var weight2 = new Measure(10, kg);
var result = weight1 + weight2;
result.Value.Should().Be(120);
result.Unit.Should().Be(kg);
}
[Fact]
public void MeasureAddition_WithOrthogonalUnit_ShouldError()
{
var kg = new Unit("kg");
var kph = new Unit("kph");
var weight = new Measure(110, kg);
var speed = new Measure(10, kph);
Action action = () => Add(weight, speed);
action.ShouldThrow<IncompatibleUnitException>()
.WithMessage("Cannot add 'kg' and 'kph' units");
}
[Fact]
public void MeasureAddition_WithConvertibleUnit_ShouldProduceResult()
{
var kg = new Unit("kg");
var g = new Unit("g");
kg.AddConversion(g, x => x * 1000);
var weight1 = new Measure(110, kg);
var weight2 = new Measure(100, g);
var result = weight1 + weight2;
result.Value.Should().Be(110100);
result.Unit.Should().Be(g);
}
[Fact]
public void MeasureAddition_WithReverseConvertibleUnit_ShouldProduceResult()
{
var kg = new Unit("kg");
var g = new Unit("g");
g.AddConversion(kg, x => x / 1000);
var weight1 = new Measure(110, kg);
var weight2 = new Measure(100, g);
var result = weight1 + weight2;
result.Value.Should().Be(110.1M);
result.Unit.Should().Be(kg);
}
private Measure Add(Measure lhs, Measure rhs)
{
return lhs + rhs;
}
private Measure Subtract(Measure lhs, Measure rhs)
{
return lhs - rhs;
}
private Measure Divide(Measure lhs, Measure rhs)
{
return lhs / rhs;
}
private Measure Multiply(Measure lhs, Measure rhs)
{
return lhs * rhs;
}
[Fact]
public void MeasureSubtraction_WithSameUnit_ShouldProduceResult()
{
var kg = new Unit("kg");
var weight1 = new Measure(110, kg);
var weight2 = new Measure(10, kg);
var result = weight1 - weight2;
result.Value.Should().Be(100);
result.Unit.Should().Be(kg);
}
[Fact]
public void MeasureSubtraction_WithOrthogonalUnit_ShouldError()
{
var kg = new Unit("kg");
var kph = new Unit("kph");
var weight = new Measure(110, kg);
var speed = new Measure(10, kph);
Action action = () => Subtract(weight, speed);
action.ShouldThrow<IncompatibleUnitException>()
.WithMessage("Cannot subtract 'kg' and 'kph' units");
}
[Fact]
public void MeasureSubtraction_WithConvertibleUnit_ShouldProduceResult()
{
var kg = new Unit("kg");
var g = new Unit("g");
kg.AddConversion(g, x => x * 1000);
var weight1 = new Measure(110, kg);
var weight2 = new Measure(100, g);
var result = weight1 - weight2;
result.Value.Should().Be(109900);
result.Unit.Should().Be(g);
}
[Fact]
public void MeasureSubtraction_WithReverseConvertibleUnit_ShouldProduceResult()
{
var kg = new Unit("kg");
var g = new Unit("g");
g.AddConversion(kg, x => x / 1000);
var weight1 = new Measure(110, kg);
var weight2 = new Measure(100, g);
var result = weight1 - weight2;
result.Value.Should().Be(109.9M);
result.Unit.Should().Be(kg);
}
[Fact]
public void MeasureDivision_WithSameUnit_ShouldProduceResult()
{
var kg = new Unit("kg");
var weight1 = new Measure(110, kg);
var weight2 = new Measure(10, kg);
var result = weight1 / weight2;
result.Value.Should().Be(11);
result.Unit.Should().Be(kg);
}
[Fact]
public void MeasureDivision_WithOrthogonalUnit_ShouldError()
{
var kg = new Unit("kg");
var kph = new Unit("kph");
var weight = new Measure(110, kg);
var speed = new Measure(10, kph);
Action action = () => Divide(weight, speed);
action.ShouldThrow<IncompatibleUnitException>()
.WithMessage("Cannot divide 'kg' and 'kph' units");
}
[Fact]
public void MeasureDivision_WithConvertibleUnit_ShouldProduceResult()
{
var kg = new Unit("kg");
var g = new Unit("g");
kg.AddConversion(g, x => x * 1000);
var weight1 = new Measure(110, kg);
var weight2 = new Measure(100, g);
var result = weight1 / weight2;
result.Value.Should().Be(1100);
result.Unit.Should().Be(g);
}
[Fact]
public void MeasureDivision_WithReverseConvertibleUnit_ShouldProduceResult()
{
var kg = new Unit("kg");
var g = new Unit("g");
g.AddConversion(kg, x => x / 1000);
var weight1 = new Measure(110, kg);
var weight2 = new Measure(100, g);
var result = weight1 / weight2;
result.Value.Should().Be(1100);
result.Unit.Should().Be(kg);
}
[Fact]
public void MeasureMultiplication_WithSameUnit_ShouldProduceResult()
{
var kg = new Unit("kg");
var weight1 = new Measure(110, kg);
var weight2 = new Measure(10, kg);
var result = weight1 * weight2;
result.Value.Should().Be(1100);
result.Unit.Should().Be(kg);
}
[Fact]
public void MeasureMultiplication_WithOrthogonalUnit_ShouldError()
{
var kg = new Unit("kg");
var kph = new Unit("kph");
var weight = new Measure(110, kg);
var speed = new Measure(10, kph);
Action action = () => Multiply(weight, speed);
action.ShouldThrow<IncompatibleUnitException>()
.WithMessage("Cannot multiply 'kg' and 'kph' units");
}
[Fact]
public void MeasureMultiplication_WithConvertibleUnit_ShouldProduceResult()
{
var kg = new Unit("kg");
var g = new Unit("g");
kg.AddConversion(g, x => x * 1000);
var weight1 = new Measure(110, kg);
var weight2 = new Measure(100, g);
var result = weight1 * weight2;
result.Value.Should().Be(11000000);
result.Unit.Should().Be(g);
}
[Fact]
public void MeasureMultiplication_WithReverseConvertibleUnit_ShouldProduceResult()
{
var kg = new Unit("kg");
var g = new Unit("g");
g.AddConversion(kg, x => x / 1000);
var weight1 = new Measure(110, kg);
var weight2 = new Measure(100, g);
var result = weight1 * weight2;
result.Value.Should().Be(11);
result.Unit.Should().Be(kg);
}
}
}
| |
/*
* 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;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Xml;
using Nini.Config;
using OpenMetaverse;
using Aurora.Framework;
using Aurora.Framework.Capabilities;
using Aurora.Simulation.Base;
using OpenSim.Services.Interfaces;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
using FriendInfo = OpenSim.Services.Interfaces.FriendInfo;
using Aurora.DataManager;
namespace OpenSim.Services.LLLoginService
{
public class LLLoginService : ILoginService, IService
{
private static bool Initialized = false;
// Global Textures
private const string sunTexture = "cce0f112-878f-4586-a2e2-a8f104bba271";
private const string cloudTexture = "dc4b9f0b-d008-45c6-96a4-01dd947ac621";
private const string moonTexture = "ec4b9f0b-d008-45c6-96a4-01dd947ac621";
protected IUserAccountService m_UserAccountService;
protected IAgentInfoService m_agentInfoService;
protected IAuthenticationService m_AuthenticationService;
protected IInventoryService m_InventoryService;
protected IGridService m_GridService;
protected ISimulationService m_SimulationService;
protected ILibraryService m_LibraryService;
protected IFriendsService m_FriendsService;
protected IAvatarService m_AvatarService;
protected IAssetService m_AssetService;
protected ICapsService m_CapsService;
protected IAvatarAppearanceArchiver m_ArchiveService;
protected IRegistryCore m_registry;
protected string m_DefaultRegionName;
protected string m_WelcomeMessage;
protected string m_WelcomeMessageURL;
protected bool m_RequireInventory;
protected int m_MinLoginLevel;
protected bool m_AllowRemoteSetLoginLevel;
protected IConfig m_loginServerConfig;
protected IConfigSource m_config;
protected bool m_AllowAnonymousLogin = false;
protected bool m_AllowDuplicateLogin = false;
protected string m_DefaultUserAvatarArchive = "DefaultAvatar.aa";
protected string m_DefaultHomeRegion = "";
protected ArrayList eventCategories = new ArrayList();
protected ArrayList classifiedCategories = new ArrayList();
protected List<ILoginModule> LoginModules = new List<ILoginModule>();
private string m_forceUserToWearFolderName;
private string m_forceUserToWearFolderOwnerUUID;
public int MinLoginLevel
{
get { return m_MinLoginLevel; }
}
public void Initialize(IConfigSource config, IRegistryCore registry)
{
m_config = config;
m_loginServerConfig = config.Configs["LoginService"];
if (m_loginServerConfig == null)
return;
m_forceUserToWearFolderName = m_loginServerConfig.GetString("forceUserToWearFolderName", "");
m_forceUserToWearFolderOwnerUUID = m_loginServerConfig.GetString("forceUserToWearFolderOwner", "");
m_DefaultHomeRegion = m_loginServerConfig.GetString("DefaultHomeRegion", "");
m_DefaultUserAvatarArchive = m_loginServerConfig.GetString("DefaultAvatarArchiveForNewUser", m_DefaultUserAvatarArchive);
m_AllowAnonymousLogin = m_loginServerConfig.GetBoolean("AllowAnonymousLogin", false);
m_AllowDuplicateLogin = m_loginServerConfig.GetBoolean("AllowDuplicateLogin", false);
LLLoginResponseRegister.RegisterValue("AllowFirstLife", m_loginServerConfig.GetBoolean("AllowFirstLifeInProfile", true) ? "Y" : "N");
LLLoginResponseRegister.RegisterValue("TutorialURL", m_loginServerConfig.GetString("TutorialURL", ""));
LLLoginResponseRegister.RegisterValue("OpenIDURL", m_loginServerConfig.GetString("OpenIDURL", ""));
LLLoginResponseRegister.RegisterValue("SnapshotConfigURL", m_loginServerConfig.GetString("SnapshotConfigURL", ""));
LLLoginResponseRegister.RegisterValue("MaxAgentGroups", m_loginServerConfig.GetInt("MaxAgentGroups", 100));
LLLoginResponseRegister.RegisterValue("HelpURL", m_loginServerConfig.GetString("HelpURL", ""));
LLLoginResponseRegister.RegisterValue("VoiceServerType", m_loginServerConfig.GetString("VoiceServerType", "vivox"));
ReadEventValues(m_loginServerConfig);
ReadClassifiedValues(m_loginServerConfig);
LLLoginResponseRegister.RegisterValue("AllowExportPermission", m_loginServerConfig.GetBoolean("AllowUsageOfExportPermissions", true));
m_DefaultRegionName = m_loginServerConfig.GetString("DefaultRegion", String.Empty);
m_WelcomeMessage = m_loginServerConfig.GetString("WelcomeMessage", "");
m_WelcomeMessage = m_WelcomeMessage.Replace("\\n", "\n");
m_WelcomeMessageURL = m_loginServerConfig.GetString("CustomizedMessageURL", "");
if (m_WelcomeMessageURL != "")
{
WebClient client = new WebClient();
m_WelcomeMessage = client.DownloadString(m_WelcomeMessageURL);
}
LLLoginResponseRegister.RegisterValue("Message", m_WelcomeMessage);
m_RequireInventory = m_loginServerConfig.GetBoolean("RequireInventory", true);
m_AllowRemoteSetLoginLevel = m_loginServerConfig.GetBoolean("AllowRemoteSetLoginLevel", false);
m_MinLoginLevel = m_loginServerConfig.GetInt("MinLoginLevel", 0);
LLLoginResponseRegister.RegisterValue("MapTileURL", m_loginServerConfig.GetString("MapTileURL", string.Empty));
LLLoginResponseRegister.RegisterValue("WebProfileURL", m_loginServerConfig.GetString("WebProfileURL", string.Empty));
LLLoginResponseRegister.RegisterValue("SearchURL", m_loginServerConfig.GetString("SearchURL", string.Empty));
// if [LoginService] doesn't have the Search URL, try to get it from [GridInfoService]
if (LLLoginResponseRegister.GetValue("SearchURL").ToString() == string.Empty)
{
IConfig gridInfo = config.Configs["GridInfoService"];
LLLoginResponseRegister.RegisterValue("SearchURL", gridInfo.GetString("search", string.Empty));
}
LLLoginResponseRegister.RegisterValue("DestinationURL", m_loginServerConfig.GetString("DestinationURL", string.Empty));
LLLoginResponseRegister.RegisterValue("MarketPlaceURL", m_loginServerConfig.GetString("MarketPlaceURL", string.Empty));
LLLoginResponseRegister.RegisterValue("SunTexture", m_loginServerConfig.GetString("SunTexture", sunTexture));
LLLoginResponseRegister.RegisterValue("MoonTexture", m_loginServerConfig.GetString("MoonTexture", moonTexture));
LLLoginResponseRegister.RegisterValue("CloudTexture", m_loginServerConfig.GetString("CloudTexture", cloudTexture));
registry.RegisterModuleInterface<ILoginService>(this);
m_registry = registry;
}
public void Start(IConfigSource config, IRegistryCore registry)
{
m_UserAccountService = registry.RequestModuleInterface<IUserAccountService>().InnerService;
m_agentInfoService = registry.RequestModuleInterface<IAgentInfoService>().InnerService;
m_AuthenticationService = registry.RequestModuleInterface<IAuthenticationService>();
m_InventoryService = registry.RequestModuleInterface<IInventoryService>();
m_GridService = registry.RequestModuleInterface<IGridService>();
m_AvatarService = registry.RequestModuleInterface<IAvatarService>().InnerService;
m_FriendsService = registry.RequestModuleInterface<IFriendsService>();
m_SimulationService = registry.RequestModuleInterface<ISimulationService>();
m_AssetService = registry.RequestModuleInterface<IAssetService>().InnerService;
m_LibraryService = registry.RequestModuleInterface<ILibraryService>();
m_CapsService = registry.RequestModuleInterface<ICapsService>();
m_ArchiveService = registry.RequestModuleInterface<IAvatarAppearanceArchiver>();
if (!Initialized)
{
Initialized = true;
RegisterCommands();
}
LoginModules = AuroraModuleLoader.PickupModules<ILoginModule>();
foreach (ILoginModule module in LoginModules)
{
module.Initialize(this, m_config, registry);
}
MainConsole.Instance.DebugFormat("[LLOGIN SERVICE]: Starting...");
}
public void FinishedStartup()
{
}
public void ReadEventValues(IConfig config)
{
SetEventCategories((Int32)DirectoryManager.EventCategories.Discussion, "Discussion");
SetEventCategories((Int32)DirectoryManager.EventCategories.Sports, "Sports");
SetEventCategories((Int32)DirectoryManager.EventCategories.LiveMusic, "Live Music");
SetEventCategories((Int32)DirectoryManager.EventCategories.Commercial, "Commercial");
SetEventCategories((Int32)DirectoryManager.EventCategories.Nightlife, "Nightlife/Entertainment");
SetEventCategories((Int32)DirectoryManager.EventCategories.Games, "Games/Contests");
SetEventCategories((Int32)DirectoryManager.EventCategories.Pageants, "Pageants");
SetEventCategories((Int32)DirectoryManager.EventCategories.Education, "Education");
SetEventCategories((Int32)DirectoryManager.EventCategories.Arts, "Arts and Culture");
SetEventCategories((Int32)DirectoryManager.EventCategories.Charity, "Charity/Support Groups");
SetEventCategories((Int32)DirectoryManager.EventCategories.Miscellaneous, "Miscellaneous");
}
public void ReadClassifiedValues(IConfig config)
{
AddClassifiedCategory((Int32)DirectoryManager.ClassifiedCategories.Shopping, "Shopping");
AddClassifiedCategory((Int32)DirectoryManager.ClassifiedCategories.LandRental, "Land Rental");
AddClassifiedCategory((Int32)DirectoryManager.ClassifiedCategories.PropertyRental, "Property Rental");
AddClassifiedCategory((Int32)DirectoryManager.ClassifiedCategories.SpecialAttraction, "Special Attraction");
AddClassifiedCategory((Int32)DirectoryManager.ClassifiedCategories.NewProducts, "New Products");
AddClassifiedCategory((Int32)DirectoryManager.ClassifiedCategories.Employment, "Employment");
AddClassifiedCategory((Int32)DirectoryManager.ClassifiedCategories.Wanted, "Wanted");
AddClassifiedCategory((Int32)DirectoryManager.ClassifiedCategories.Service, "Service");
AddClassifiedCategory((Int32)DirectoryManager.ClassifiedCategories.Personal, "Personal");
}
public void SetEventCategories(Int32 value, string categoryName)
{
Hashtable hash = new Hashtable();
hash["category_name"] = categoryName;
hash["category_id"] = value;
eventCategories.Add(hash);
}
public void AddClassifiedCategory(Int32 ID, string categoryName)
{
Hashtable hash = new Hashtable();
hash["category_name"] = categoryName;
hash["category_id"] = ID;
classifiedCategories.Add(hash);
}
public Hashtable SetLevel(string firstName, string lastName, string passwd, int level, IPEndPoint clientIP)
{
Hashtable response = new Hashtable();
response["success"] = "false";
if (!m_AllowRemoteSetLoginLevel)
return response;
try
{
UserAccount account = m_UserAccountService.GetUserAccount(UUID.Zero, firstName, lastName);
if (account == null)
{
MainConsole.Instance.InfoFormat("[LLOGIN SERVICE]: Set Level failed, user {0} {1} not found", firstName, lastName);
return response;
}
if (account.UserLevel < 200)
{
MainConsole.Instance.InfoFormat("[LLOGIN SERVICE]: Set Level failed, reason: user level too low");
return response;
}
//
// Authenticate this user
//
// We don't support clear passwords here
//
string token = m_AuthenticationService.Authenticate(account.PrincipalID, "UserAccount", passwd, 30);
UUID secureSession = UUID.Zero;
if ((token == string.Empty) || (token != string.Empty && !UUID.TryParse(token, out secureSession)))
{
MainConsole.Instance.InfoFormat("[LLOGIN SERVICE]: SetLevel failed, reason: authentication failed");
return response;
}
}
catch (Exception e)
{
MainConsole.Instance.Error("[LLOGIN SERVICE]: SetLevel failed, exception " + e);
return response;
}
m_MinLoginLevel = level;
MainConsole.Instance.InfoFormat("[LLOGIN SERVICE]: Login level set to {0} by {1} {2}", level, firstName, lastName);
response["success"] = true;
return response;
}
public bool VerifyClient(UUID AgentID, string name, string authType, string passwd, UUID scopeID)
{
MainConsole.Instance.InfoFormat("[LLOGIN SERVICE]: Login verification request for {0}", AgentID);
//
// Get the account and check that it exists
//
UserAccount account = m_UserAccountService.GetUserAccount(scopeID, AgentID);
if (account == null)
{
return false;
}
IAgentInfo agent = null;
IAgentConnector agentData = DataManager.RequestPlugin<IAgentConnector>();
if (agentData != null)
{
agent = agentData.GetAgent(account.PrincipalID);
}
if (agent == null)
{
agentData.CreateNewAgent(account.PrincipalID);
agent = agentData.GetAgent(account.PrincipalID);
}
foreach (ILoginModule module in LoginModules)
{
object data;
if (module.Login(null, account, agent, authType, passwd, out data) != null)
{
return false;
}
}
return true;
}
public LoginResponse Login(UUID AgentID, string Name, string authType, string passwd, string startLocation, UUID scopeID,
string clientVersion, string channel, string mac, string id0, IPEndPoint clientIP, Hashtable requestData)
{
LoginResponse response;
UUID session = UUID.Random();
UUID secureSession = UUID.Zero;
UserAccount account = AgentID != UUID.Zero ? m_UserAccountService.GetUserAccount(scopeID, AgentID) : m_UserAccountService.GetUserAccount(scopeID, Name);
if (account == null)
return LLFailedLoginResponse.AccountProblem;
if (account.UserLevel < m_MinLoginLevel)
{
MainConsole.Instance.InfoFormat("[LLOGIN SERVICE]: Login failed for user {1}, reason: login is blocked for user level {0}", account.UserLevel, account.Name);
return LLFailedLoginResponse.LoginBlockedProblem;
}
if (account.UserLevel < 0)//No allowing anyone less than 0
return LLFailedLoginResponse.PermanentBannedProblem;
IAgentInfo agent = null;
IAgentConnector agentData = DataManager.RequestPlugin<IAgentConnector>();
if (agentData != null)
agent = agentData.GetAgent(account.PrincipalID);
if (agent == null)
{
agentData.CreateNewAgent(account.PrincipalID);
agent = agentData.GetAgent(account.PrincipalID);
}
requestData["ip"] = clientIP.ToString();
foreach (ILoginModule module in LoginModules)
{
object data;
if ((response = module.Login(requestData, account, agent, authType, passwd, out data)) != null)
return response;
if (data != null)
secureSession = (UUID)data;//TODO: NEED TO FIND BETTER WAY TO GET THIS DATA
}
MainConsole.Instance.InfoFormat("[LLOGIN SERVICE]: Login request for {0} from {1} with user agent {2} starting in {3}",
Name, clientIP.Address, clientVersion, startLocation);
try
{
string DisplayName = account.Name;
IProfileConnector profileData = DataManager.RequestPlugin<IProfileConnector>();
//
// Get the user's inventory
//
if (m_RequireInventory && m_InventoryService == null)
{
MainConsole.Instance.WarnFormat("[LLOGIN SERVICE]: Login failed for user {0}, reason: inventory service not set up", account.Name);
return LLFailedLoginResponse.InventoryProblem;
}
List<InventoryFolderBase> inventorySkel = m_InventoryService.GetInventorySkeleton(account.PrincipalID);
if (m_RequireInventory && ((inventorySkel == null) || (inventorySkel.Count == 0)))
{
m_InventoryService.CreateUserInventory(account.PrincipalID, m_DefaultUserAvatarArchive == "");
inventorySkel = m_InventoryService.GetInventorySkeleton(account.PrincipalID);
if (m_RequireInventory && ((inventorySkel == null) || (inventorySkel.Count == 0)))
{
MainConsole.Instance.InfoFormat("[LLOGIN SERVICE]: Login failed for user {0}, reason: unable to retrieve user inventory", account.Name);
return LLFailedLoginResponse.InventoryProblem;
}
}
m_InventoryService.CreateUserRootFolder(account.PrincipalID);
if (profileData != null)
{
IUserProfileInfo UPI = profileData.GetUserProfile(account.PrincipalID);
if (UPI == null)
{
profileData.CreateNewProfile(account.PrincipalID);
UPI = profileData.GetUserProfile(account.PrincipalID);
UPI.AArchiveName = m_DefaultUserAvatarArchive;
UPI.IsNewUser = true;
//profileData.UpdateUserProfile(UPI); //It gets hit later by the next thing
}
//Find which is set, if any
string archiveName = (UPI.AArchiveName != "" && UPI.AArchiveName != " ") ? UPI.AArchiveName : m_DefaultUserAvatarArchive;
if (UPI.IsNewUser && archiveName != "")
{
AvatarAppearance appearance = m_ArchiveService.LoadAvatarArchive(archiveName, account.Name);
UPI.AArchiveName = "";
AvatarData adata = new AvatarData(appearance);
m_AvatarService.SetAppearance(account.PrincipalID, appearance);
}
if (UPI.IsNewUser)
{
UPI.IsNewUser = false;
profileData.UpdateUserProfile(UPI);
}
if (UPI.DisplayName != "")
DisplayName = UPI.DisplayName;
}
// Get active gestures
List<InventoryItemBase> gestures = m_InventoryService.GetActiveGestures(account.PrincipalID);
//MainConsole.Instance.DebugFormat("[LLOGIN SERVICE]: {0} active gestures", gestures.Count);
//Reset logged in to true if the user was crashed, but don't fire the logged in event yet
m_agentInfoService.SetLoggedIn(account.PrincipalID.ToString(), true, false, UUID.Zero);
//Lock it as well
m_agentInfoService.LockLoggedInStatus(account.PrincipalID.ToString(), true);
//Now get the logged in status, then below make sure to kill the previous agent if we crashed before
UserInfo guinfo = m_agentInfoService.GetUserInfo(account.PrincipalID.ToString());
//
// Clear out any existing CAPS the user may have
//
if (m_CapsService != null)
{
IAgentProcessing agentProcessor = m_registry.RequestModuleInterface<IAgentProcessing>();
if (agentProcessor != null)
{
IClientCapsService clientCaps = m_CapsService.GetClientCapsService(account.PrincipalID);
if (clientCaps != null)
{
IRegionClientCapsService rootRegionCaps = clientCaps.GetRootCapsService();
if (rootRegionCaps != null)
agentProcessor.LogoutAgent(rootRegionCaps, !m_AllowDuplicateLogin);
}
}
else
m_CapsService.RemoveCAPS(account.PrincipalID);
}
//
// Change Online status and get the home region
//
GridRegion home = null;
if (guinfo != null && (guinfo.HomeRegionID != UUID.Zero) && m_GridService != null)
{
home = m_GridService.GetRegionByUUID(scopeID, guinfo.HomeRegionID);
}
bool GridUserInfoFound = true;
if (guinfo == null)
{
GridUserInfoFound = false;
// something went wrong, make something up, so that we don't have to test this anywhere else
guinfo = new UserInfo { UserID = account.PrincipalID.ToString() };
guinfo.CurrentPosition = guinfo.HomePosition = new Vector3(128, 128, 30);
}
if (!GridUserInfoFound || guinfo.HomeRegionID == UUID.Zero) //Give them a default home and last
{
if (m_GridService != null)
{
if (m_DefaultHomeRegion != "")
{
GridRegion newHomeRegion = m_GridService.GetRegionByName(account.ScopeID, m_DefaultHomeRegion);
if (newHomeRegion != null)
guinfo.HomeRegionID = guinfo.CurrentRegionID = newHomeRegion.RegionID;
}
if (guinfo.HomeRegionID == UUID.Zero)
{
List<GridRegion> DefaultRegions = m_GridService.GetDefaultRegions(account.ScopeID);
GridRegion DefaultRegion = null;
DefaultRegion = DefaultRegions.Count == 0 ? null : DefaultRegions[0];
if (DefaultRegion != null)
guinfo.HomeRegionID = guinfo.CurrentRegionID = DefaultRegion.RegionID;
}
}
//Z = 0 so that it fixes it on the region server and puts it on the ground
guinfo.CurrentPosition = guinfo.HomePosition = new Vector3(128, 128, 25);
guinfo.HomeLookAt = guinfo.CurrentLookAt = new Vector3(0, 0, 0);
m_agentInfoService.SetLastPosition(guinfo.UserID, guinfo.CurrentRegionID, guinfo.CurrentPosition, guinfo.CurrentLookAt);
m_agentInfoService.SetHomePosition(guinfo.UserID, guinfo.HomeRegionID, guinfo.HomePosition, guinfo.HomeLookAt);
}
//
// Find the destination region/grid
//
string where = string.Empty;
Vector3 position = Vector3.Zero;
Vector3 lookAt = Vector3.Zero;
TeleportFlags tpFlags = TeleportFlags.ViaLogin;
GridRegion destination = FindDestination(account, scopeID, guinfo, session, startLocation, home, out tpFlags, out where, out position, out lookAt);
if (destination == null)
{
MainConsole.Instance.InfoFormat("[LLOGIN SERVICE]: Login failed for user {0}, reason: destination not found", account.Name);
return LLFailedLoginResponse.DeadRegionProblem;
}
//
// Get the avatar
//
AvatarAppearance avappearance;
if (m_AvatarService != null)
{
avappearance = m_AvatarService.GetAppearance(account.PrincipalID);
if (avappearance == null)
{
//Create an appearance for the user if one doesn't exist
if (m_DefaultUserAvatarArchive != "")
{
MainConsole.Instance.Error("[LLoginService]: Cannot find an appearance for user " + account.Name +
", loading the default avatar from " + m_DefaultUserAvatarArchive + ".");
m_ArchiveService.LoadAvatarArchive(m_DefaultUserAvatarArchive, account.Name);
}
else
{
MainConsole.Instance.Error("[LLoginService]: Cannot find an appearance for user " + account.Name + ", setting to the default avatar.");
AvatarAppearance appearance = new AvatarAppearance(account.PrincipalID);
m_AvatarService.SetAvatar(account.PrincipalID, new AvatarData(appearance));
}
avappearance = m_AvatarService.GetAppearance(account.PrincipalID);
}
else
{
//Verify that all assets exist now
for (int i = 0; i < avappearance.Wearables.Length; i++)
{
bool messedUp = false;
foreach (KeyValuePair<UUID, UUID> item in avappearance.Wearables[i].GetItems())
{
AssetBase asset = m_AssetService.Get(item.Value.ToString());
if (asset == null)
{
InventoryItemBase invItem = m_InventoryService.GetItem(new InventoryItemBase(item.Value));
if (invItem == null)
{
MainConsole.Instance.Warn("[LLOGIN SERVICE]: Missing avatar appearance asset for user " + account.Name + " for item " + item.Value + ", asset should be " + item.Key + "!");
messedUp = true;
}
}
}
if (messedUp)
avappearance.Wearables[i] = AvatarWearable.DefaultWearables[i];
}
//Also verify that all baked texture indices exist
foreach (byte BakedTextureIndex in AvatarAppearance.BAKE_INDICES)
{
if (BakedTextureIndex == 19) //Skirt isn't used unless you have a skirt
continue;
if (avappearance.Texture.GetFace(BakedTextureIndex).TextureID == AppearanceManager.DEFAULT_AVATAR_TEXTURE)
{
MainConsole.Instance.Warn("[LLOGIN SERVICE]: Bad texture index for user " + account.Name + " for " + BakedTextureIndex + "!");
avappearance = new AvatarAppearance(account.PrincipalID);
m_AvatarService.SetAvatar(account.PrincipalID, new AvatarData(avappearance));
break;
}
}
}
}
else
avappearance = new AvatarAppearance(account.PrincipalID);
if ((m_forceUserToWearFolderName != "") && (m_forceUserToWearFolderOwnerUUID.Length == 36))
{
UUID userThatOwnersFolder;
if (UUID.TryParse(m_forceUserToWearFolderOwnerUUID, out userThatOwnersFolder))
{
avappearance = WearFolder(avappearance, account.PrincipalID, userThatOwnersFolder);
}
}
avappearance = FixCurrentOutFitFolder(account.PrincipalID, avappearance);
inventorySkel = m_InventoryService.GetInventorySkeleton(account.PrincipalID);
//
// Instantiate/get the simulation interface and launch an agent at the destination
//
string reason = string.Empty;
AgentCircuitData aCircuit = LaunchAgentAtGrid(destination, tpFlags, account, avappearance, session, secureSession, position, where,
clientIP, out where, out reason, out destination);
if (aCircuit == null)
{
MainConsole.Instance.InfoFormat("[LLOGIN SERVICE]: Login failed for user {1}, reason: {0}", reason, account.Name);
return new LLFailedLoginResponse(LoginResponseEnum.InternalError, reason, false);
}
// Get Friends list
List<FriendInfo> friendsList = new List<FriendInfo>();
if (m_FriendsService != null)
{
friendsList = m_FriendsService.GetFriends(account.PrincipalID);
//MainConsole.Instance.DebugFormat("[LLOGIN SERVICE]: Retrieved {0} friends", friendsList.Length);
}
//Set them as logged in now, they are ready, and fire the logged in event now, as we're all done
m_agentInfoService.SetLastPosition(account.PrincipalID.ToString(), destination.RegionID, position, lookAt);
m_agentInfoService.LockLoggedInStatus(account.PrincipalID.ToString(), false); //Unlock it now
m_agentInfoService.SetLoggedIn(account.PrincipalID.ToString(), true, true, destination.RegionID);
//
// Finally, fill out the response and return it
//
string MaturityRating = "A";
string MaxMaturity = "A";
if (agent != null)
{
if (agent.MaturityRating == 0)
MaturityRating = "P";
else if (agent.MaturityRating == 1)
MaturityRating = "M";
else if (agent.MaturityRating == 2)
MaturityRating = "A";
if (agent.MaxMaturity == 0)
MaxMaturity = "P";
else if (agent.MaxMaturity == 1)
MaxMaturity = "M";
else if (agent.MaxMaturity == 2)
MaxMaturity = "A";
}
response = new LLLoginResponse(account, aCircuit, guinfo, destination, inventorySkel, friendsList.ToArray(), m_InventoryService, m_LibraryService,
where, startLocation, position, lookAt, gestures, home, clientIP, MaxMaturity, MaturityRating,
eventCategories, classifiedCategories, FillOutSeedCap(aCircuit, destination, clientIP, account.PrincipalID), m_config, DisplayName, m_registry);
MainConsole.Instance.InfoFormat("[LLOGIN SERVICE]: All clear. Sending login response to client to login to region " + destination.RegionName + ", tried to login to " + startLocation + " at " + position.ToString() + ".");
AddLoginSuccessNotification(account);
return response;
}
catch (Exception e)
{
MainConsole.Instance.WarnFormat("[LLOGIN SERVICE]: Exception processing login for {0} : {1}", Name, e);
if (account != null)
{
//Revert their logged in status if we got that far
m_agentInfoService.LockLoggedInStatus(account.PrincipalID.ToString(), false); //Unlock it now
m_agentInfoService.SetLoggedIn(account.PrincipalID.ToString(), false, false, UUID.Zero);
}
return LLFailedLoginResponse.InternalError;
}
}
private void AddLoginSuccessNotification(UserAccount account)
{
if (MainConsole.NotificationService == null)
return;
MainConsole.NotificationService.AddNotification(AlertLevel.Low, account.Name + " has logged in successfully.", "LLLoginService",
(messages) =>
{
return messages.Count + " users have logged in successfully.";
});
}
protected string FillOutSeedCap(AgentCircuitData aCircuit, GridRegion destination, IPEndPoint ipepClient, UUID AgentID)
{
if (m_CapsService != null)
{
//Remove any previous users
string CapsBase = CapsUtil.GetRandomCapsObjectPath();
return m_CapsService.CreateCAPS(AgentID, CapsUtil.GetCapsSeedPath(CapsBase), destination.RegionHandle, true, aCircuit);
}
return "";
}
protected GridRegion FindDestination(UserAccount account, UUID scopeID, UserInfo pinfo, UUID sessionID, string startLocation, GridRegion home, out TeleportFlags tpFlags, out string where, out Vector3 position, out Vector3 lookAt)
{
where = "home";
position = new Vector3(128, 128, 25);
lookAt = new Vector3(0, 1, 0);
tpFlags = TeleportFlags.ViaLogin;
if (m_GridService == null)
return null;
if (startLocation.Equals("home"))
{
tpFlags |= TeleportFlags.ViaLandmark;
// logging into home region
if (pinfo == null)
return null;
GridRegion region = null;
bool tryDefaults = false;
if (home == null)
{
MainConsole.Instance.WarnFormat(
"[LLOGIN SERVICE]: User {0} {1} tried to login to a 'home' start location but they have none set",
account.FirstName, account.LastName);
tryDefaults = true;
}
else
{
region = home;
position = pinfo.HomePosition;
lookAt = pinfo.HomeLookAt;
}
if (tryDefaults)
{
tpFlags &= ~TeleportFlags.ViaLandmark;
List<GridRegion> defaults = m_GridService.GetDefaultRegions(scopeID);
if (defaults != null && defaults.Count > 0)
{
region = defaults[0];
where = "safe";
}
else
{
List<GridRegion> fallbacks = m_GridService.GetFallbackRegions(account.ScopeID, 0, 0);
if (fallbacks != null && fallbacks.Count > 0)
{
region = fallbacks[0];
where = "safe";
}
else
{
//Try to find any safe region
List<GridRegion> safeRegions = m_GridService.GetSafeRegions(account.ScopeID, 0, 0);
if (safeRegions != null && safeRegions.Count > 0)
{
region = safeRegions[0];
where = "safe";
}
else
{
MainConsole.Instance.WarnFormat("[LLOGIN SERVICE]: User {0} {1} does not have a valid home and this grid does not have default locations. Attempting to find random region",
account.FirstName, account.LastName);
defaults = m_GridService.GetRegionsByName(scopeID, "", 1);
if (defaults != null && defaults.Count > 0)
{
region = defaults[0];
where = "safe";
}
}
}
}
}
return region;
}
if (startLocation.Equals("last"))
{
tpFlags |= TeleportFlags.ViaLandmark;
// logging into last visited region
where = "last";
if (pinfo == null)
return null;
GridRegion region = null;
if (pinfo.CurrentRegionID.Equals(UUID.Zero) || (region = m_GridService.GetRegionByUUID(scopeID, pinfo.CurrentRegionID)) == null)
{
tpFlags &= ~TeleportFlags.ViaLandmark;
List<GridRegion> defaults = m_GridService.GetDefaultRegions(scopeID);
if (defaults != null && defaults.Count > 0)
{
region = defaults[0];
where = "safe";
}
else
{
defaults = m_GridService.GetFallbackRegions(scopeID, 0, 0);
if (defaults != null && defaults.Count > 0)
{
region = defaults[0];
where = "safe";
}
else
{
defaults = m_GridService.GetSafeRegions(scopeID, 0, 0);
if (defaults != null && defaults.Count > 0)
{
region = defaults[0];
where = "safe";
}
}
}
}
else
{
position = pinfo.CurrentPosition;
if (position.X < 0)
position.X = 0;
if (position.Y < 0)
position.Y = 0;
if (position.Z < 0)
position.Z = 0;
if (position.X > region.RegionSizeX)
position.X = region.RegionSizeX;
if (position.Y > region.RegionSizeY)
position.Y = region.RegionSizeY;
lookAt = pinfo.CurrentLookAt;
}
return region;
}
else
{
// free uri form
// e.g. New Moon&135&46 New Moon@osgrid.org:8002&153&34
where = "url";
Regex reURI = new Regex(@"^uri:(?<region>[^&]+)&(?<x>\d+)&(?<y>\d+)&(?<z>\d+)$");
Match uriMatch = reURI.Match(startLocation);
position = new Vector3(float.Parse(uriMatch.Groups["x"].Value, Culture.NumberFormatInfo),
float.Parse(uriMatch.Groups["y"].Value, Culture.NumberFormatInfo),
float.Parse(uriMatch.Groups["z"].Value, Culture.NumberFormatInfo));
string regionName = uriMatch.Groups["region"].ToString();
if (!regionName.Contains("@"))
{
List<GridRegion> regions = m_GridService.GetRegionsByName(scopeID, regionName, 1);
if ((regions == null) || (regions.Count == 0))
{
MainConsole.Instance.InfoFormat(
"[LLLOGIN SERVICE]: Got Custom Login URI {0}, can't locate region {1}. Trying defaults.",
startLocation, regionName);
regions = m_GridService.GetDefaultRegions(scopeID);
if (regions != null && regions.Count > 0)
{
where = "safe";
return regions[0];
}
List<GridRegion> fallbacks = m_GridService.GetFallbackRegions(account.ScopeID, 0, 0);
if (fallbacks != null && fallbacks.Count > 0)
{
where = "safe";
return fallbacks[0];
}
//Try to find any safe region
List<GridRegion> safeRegions = m_GridService.GetSafeRegions(account.ScopeID, 0, 0);
if (safeRegions != null && safeRegions.Count > 0)
{
where = "safe";
return safeRegions[0];
}
MainConsole.Instance.InfoFormat(
"[LLLOGIN SERVICE]: Got Custom Login URI {0}, Grid does not have any available regions.",
startLocation);
return null;
}
return regions[0];
}
//This is so that you can login to other grids via IWC (or HG), example"RegionTest@testingserver.com:8002". All this really needs to do is inform the other grid that we have a user who wants to connect. IWC allows users to login by default to other regions (without the host names), but if one is provided and we don't have a link, we need to create one here.
string[] parts = regionName.Split(new char[] { '@' });
if (parts.Length < 2)
{
MainConsole.Instance.InfoFormat("[LLLOGIN SERVICE]: Got Custom Login URI {0}, can't locate region {1}",
startLocation, regionName);
return null;
}
// Valid specification of a remote grid
regionName = parts[0];
string domainLocator = parts[1];
//Try now that we removed the domain locator
GridRegion region = m_GridService.GetRegionByName(scopeID, regionName);
if (region != null && region.RegionName == regionName)
//Make sure the region name is right too... it could just be a similar name
return region;
ICommunicationService service = m_registry.RequestModuleInterface<ICommunicationService>();
if (service != null)
{
region = service.GetRegionForGrid(regionName, domainLocator);
if (region != null)
return region;
}
List<GridRegion> defaults = m_GridService.GetDefaultRegions(scopeID);
if (defaults != null && defaults.Count > 0)
{
where = "safe";
return defaults[0];
}
else
{
List<GridRegion> fallbacks = m_GridService.GetFallbackRegions(account.ScopeID, 0, 0);
if (fallbacks != null && fallbacks.Count > 0)
{
where = "safe";
return fallbacks[0];
}
else
{
//Try to find any safe region
List<GridRegion> safeRegions = m_GridService.GetSafeRegions(account.ScopeID, 0, 0);
if (safeRegions != null && safeRegions.Count > 0)
{
where = "safe";
return safeRegions[0];
}
MainConsole.Instance.InfoFormat(
"[LLLOGIN SERVICE]: Got Custom Login URI {0}, Grid does not have any available regions.",
startLocation);
return null;
}
}
}
}
protected AgentCircuitData LaunchAgentAtGrid(GridRegion destination, TeleportFlags tpFlags, UserAccount account, AvatarAppearance appearance,
UUID session, UUID secureSession, Vector3 position, string currentWhere,
IPEndPoint clientIP, out string where, out string reason, out GridRegion dest)
{
where = currentWhere;
reason = string.Empty;
uint circuitCode = 0;
AgentCircuitData aCircuit = null;
dest = destination;
bool success = false;
#region Launch Agent
circuitCode = (uint)Util.RandomClass.Next();
aCircuit = MakeAgent(destination, account, appearance, session, secureSession, circuitCode, position, clientIP);
aCircuit.teleportFlags = (uint)tpFlags;
success = LaunchAgentDirectly(destination, ref aCircuit, out reason);
if (!success && m_GridService != null)
{
//Remove the landmark flag (landmark is used for ignoring the landing points in the region)
aCircuit.teleportFlags &= ~(uint)TeleportFlags.ViaLandmark;
m_GridService.SetRegionUnsafe(destination.RegionID);
// Make sure the client knows this isn't where they wanted to land
where = "safe";
// Try the default regions
List<GridRegion> defaultRegions = m_GridService.GetDefaultRegions(account.ScopeID);
if (defaultRegions != null)
{
success = TryFindGridRegionForAgentLogin(defaultRegions, account,
appearance, session, secureSession, circuitCode, position,
clientIP, aCircuit, out dest);
}
if (!success)
{
// Try the fallback regions
List<GridRegion> fallbacks = m_GridService.GetFallbackRegions(account.ScopeID, destination.RegionLocX, destination.RegionLocY);
if (fallbacks != null)
{
success = TryFindGridRegionForAgentLogin(fallbacks, account,
appearance, session, secureSession, circuitCode, position,
clientIP, aCircuit, out dest);
}
if (!success)
{
//Try to find any safe region
List<GridRegion> safeRegions = m_GridService.GetSafeRegions(account.ScopeID, destination.RegionLocX, destination.RegionLocY);
if (safeRegions != null)
{
success = TryFindGridRegionForAgentLogin(safeRegions, account,
appearance, session, secureSession, circuitCode, position,
clientIP, aCircuit, out dest);
if (!success)
reason = "No Region Found";
}
}
}
}
#endregion
if (success)
{
//Set the region to safe since we got there
m_GridService.SetRegionSafe(destination.RegionID);
return aCircuit;
}
return null;
}
protected bool TryFindGridRegionForAgentLogin(List<GridRegion> regions, UserAccount account,
AvatarAppearance appearance, UUID session, UUID secureSession, uint circuitCode, Vector3 position,
IPEndPoint clientIP, AgentCircuitData aCircuit, out GridRegion destination)
{
foreach (GridRegion r in regions)
{
string reason;
bool success = LaunchAgentDirectly(r, ref aCircuit, out reason);
if (success)
{
aCircuit = MakeAgent(r, account, appearance, session, secureSession, circuitCode, position, clientIP);
destination = r;
return true;
}
m_GridService.SetRegionUnsafe(r.RegionID);
}
destination = null;
return false;
}
protected AgentCircuitData MakeAgent(GridRegion region, UserAccount account,
AvatarAppearance appearance, UUID session, UUID secureSession, uint circuit, Vector3 position,
IPEndPoint clientIP)
{
AgentCircuitData aCircuit = new AgentCircuitData
{
AgentID = account.PrincipalID,
Appearance = appearance ?? new AvatarAppearance(account.PrincipalID),
CapsPath = CapsUtil.GetRandomCapsObjectPath(),
child = false,
circuitcode = circuit,
SecureSessionID = secureSession,
SessionID = session,
startpos = position,
IPAddress = clientIP.Address.ToString(),
ClientIPEndPoint = clientIP
};
// the first login agent is root
return aCircuit;
}
protected bool LaunchAgentDirectly(GridRegion region, ref AgentCircuitData aCircuit, out string reason)
{
return m_registry.RequestModuleInterface<IAgentProcessing>().LoginAgent(region, ref aCircuit, out reason);
}
#region Console Commands
protected void RegisterCommands()
{
if (MainConsole.Instance == null)
return;
MainConsole.Instance.Commands.AddCommand("login level",
"login level <level>",
"Set the minimum user level to log in", HandleLoginCommand);
MainConsole.Instance.Commands.AddCommand("login reset",
"login reset",
"Reset the login level to allow all users",
HandleLoginCommand);
MainConsole.Instance.Commands.AddCommand("login text",
"login text <text>",
"Set the text users will see on login", HandleLoginCommand);
}
protected void HandleLoginCommand(string[] cmd)
{
string subcommand = cmd[1];
switch (subcommand)
{
case "level":
// Set the minimum level to allow login
// Useful to allow grid update without worrying about users.
// or fixing critical issues
//
if (cmd.Length > 2)
Int32.TryParse(cmd[2], out m_MinLoginLevel);
break;
case "reset":
m_MinLoginLevel = 0;
break;
case "text":
if (cmd.Length > 2)
m_WelcomeMessage = cmd[2];
break;
}
}
#endregion
#region Force Wear
public AvatarAppearance WearFolder(AvatarAppearance avappearance, UUID user, UUID folderOwnerID)
{
InventoryFolderBase Folder2Wear = m_InventoryService.GetFolderByOwnerAndName(folderOwnerID, m_forceUserToWearFolderName);
if (Folder2Wear != null)
{
List<InventoryItemBase> itemsInFolder = m_InventoryService.GetFolderItems(UUID.Zero, Folder2Wear.ID);
InventoryFolderBase appearanceFolder = m_InventoryService.GetFolderForType(user, InventoryType.Wearable,
AssetType.Clothing);
InventoryFolderBase folderForAppearance = new InventoryFolderBase(UUID.Random(), "GridWear", user, -1,
appearanceFolder.ID, 1);
List<InventoryFolderBase> userFolders = m_InventoryService.GetFolderFolders(user, appearanceFolder.ID);
bool alreadyThere = false;
List<UUID> items2RemoveFromAppearence = new List<UUID>();
List<UUID> toDelete = new List<UUID>();
foreach (InventoryFolderBase folder in userFolders)
{
if (folder.Name == folderForAppearance.Name)
{
List<InventoryItemBase> itemsInCurrentFolder = m_InventoryService.GetFolderItems(UUID.Zero,
folder.ID);
foreach (InventoryItemBase itemBase in itemsInCurrentFolder)
{
items2RemoveFromAppearence.Add(itemBase.AssetID);
items2RemoveFromAppearence.Add(itemBase.ID);
toDelete.Add(itemBase.ID);
}
folderForAppearance = folder;
alreadyThere = true;
m_InventoryService.DeleteItems(user, toDelete);
break;
}
}
if (!alreadyThere)
m_InventoryService.AddFolder(folderForAppearance);
else
{
// we have to remove all the old items if they are currently wearing them
for (int i = 0; i < avappearance.Wearables.Length; i++)
{
AvatarWearable wearable = avappearance.Wearables[i];
for (int ii = 0; ii < wearable.Count; ii++)
{
if (items2RemoveFromAppearence.Contains(wearable[ii].ItemID))
{
avappearance.Wearables[i] = AvatarWearable.DefaultWearables[i];
break;
}
}
}
List<AvatarAttachment> attachments = avappearance.GetAttachments();
foreach (AvatarAttachment attachment in attachments)
{
if ((items2RemoveFromAppearence.Contains(attachment.AssetID)) ||
(items2RemoveFromAppearence.Contains(attachment.ItemID)))
{
avappearance.DetachAttachment(attachment.ItemID);
}
}
}
// ok, now we have a empty folder, lets add the items
foreach (InventoryItemBase itemBase in itemsInFolder)
{
InventoryItemBase newcopy = (InventoryItemBase) itemBase.Clone();
newcopy.ID = UUID.Random();
newcopy.Folder = folderForAppearance.ID;
newcopy.Owner = user;
m_InventoryService.AddItem(newcopy);
if (newcopy.InvType == (int) InventoryType.Object)
{
AssetBase attobj = m_AssetService.Get(newcopy.AssetID.ToString());
if (attobj != null)
{
string xmlData = Utils.BytesToString(attobj.Data);
XmlDocument doc = new XmlDocument();
try
{
doc.LoadXml(xmlData);
}
catch
{
continue;
}
if (doc.FirstChild.OuterXml.StartsWith("<groups>") ||
(doc.FirstChild.NextSibling != null &&
doc.FirstChild.NextSibling.OuterXml.StartsWith("<groups>")))
continue;
string xml = "";
if ((doc.FirstChild.NodeType == XmlNodeType.XmlDeclaration) &&
(doc.FirstChild.NextSibling != null))
xml = doc.FirstChild.NextSibling.OuterXml;
else
xml = doc.FirstChild.OuterXml;
doc.LoadXml(xml);
if (doc.DocumentElement == null) continue;
XmlNodeList xmlNodeList = doc.DocumentElement.SelectNodes("//State");
int attchspot;
if ((xmlNodeList != null) && (int.TryParse(xmlNodeList[0].InnerText, out attchspot)))
{
AvatarAttachment a = new AvatarAttachment(attchspot, newcopy.ID, newcopy.AssetID);
Dictionary<int, List<AvatarAttachment>> ac = avappearance.Attachments;
if (!ac.ContainsKey(attchspot))
ac[attchspot] = new List<AvatarAttachment>();
ac[attchspot].Add(a);
avappearance.Attachments = ac;
}
}
}
}
}
return avappearance;
}
public AvatarAppearance FixCurrentOutFitFolder(UUID user, AvatarAppearance avappearance)
{
InventoryFolderBase CurrentOutFitFolder = m_InventoryService.GetFolderForType(user, 0, AssetType.CurrentOutfitFolder);
if (CurrentOutFitFolder == null) return avappearance;
List<InventoryItemBase> ic = m_InventoryService.GetFolderItems(user, CurrentOutFitFolder.ID);
List<UUID> brokenLinks = new List<UUID>();
List<UUID> OtherStuff = new List<UUID>();
foreach (var i in ic)
{
InventoryItemBase linkedItem = null;
if ((linkedItem = m_InventoryService.GetItem(new InventoryItemBase(i.AssetID))) == null)
{
brokenLinks.Add(i.ID);
}
else if (linkedItem.ID == AvatarWearable.DEFAULT_EYES_ITEM ||
linkedItem.ID == AvatarWearable.DEFAULT_BODY_ITEM ||
linkedItem.ID == AvatarWearable.DEFAULT_HAIR_ITEM ||
linkedItem.ID == AvatarWearable.DEFAULT_PANTS_ITEM ||
linkedItem.ID == AvatarWearable.DEFAULT_SHIRT_ITEM ||
linkedItem.ID == AvatarWearable.DEFAULT_SKIN_ITEM)
brokenLinks.Add(i.ID); //Default item link, needs removed
else if (!OtherStuff.Contains(i.AssetID))
OtherStuff.Add(i.AssetID);
}
for (int i = 0; i < avappearance.Wearables.Length; i++)
{
AvatarWearable wearable = avappearance.Wearables[i];
for (int ii = 0; ii < wearable.Count; ii++)
{
if (!OtherStuff.Contains(wearable[ii].ItemID))
{
InventoryItemBase linkedItem2 = null;
if ((linkedItem2 = m_InventoryService.GetItem(new InventoryItemBase(wearable[ii].ItemID))) != null)
{
InventoryItemBase linkedItem3 = (InventoryItemBase)linkedItem2.Clone();
linkedItem3.AssetID = linkedItem2.ID;
linkedItem3.AssetType = 24;
linkedItem3.ID = UUID.Random();
linkedItem3.CurrentPermissions = linkedItem2.NextPermissions;
linkedItem3.EveryOnePermissions = linkedItem2.NextPermissions;
linkedItem3.Folder = CurrentOutFitFolder.ID;
m_InventoryService.AddItem(linkedItem3);
}
else
{
avappearance.Wearables[i] = AvatarWearable.DefaultWearables[i];
}
}
}
}
List<AvatarAttachment> attachments = avappearance.GetAttachments();
List<UUID> items2UnAttach = new List<UUID>();
foreach (KeyValuePair<int, List<AvatarAttachment>> attachmentSpot in avappearance.Attachments)
{
foreach (AvatarAttachment attachment in attachmentSpot.Value)
{
if (!OtherStuff.Contains(attachment.ItemID))
{
InventoryItemBase linkedItem2 = null;
if ((linkedItem2 = m_InventoryService.GetItem(new InventoryItemBase(attachment.ItemID))) != null)
{
InventoryItemBase linkedItem3 = (InventoryItemBase)linkedItem2.Clone();
linkedItem3.AssetID = linkedItem2.ID;
linkedItem3.AssetType = 24;
linkedItem3.ID = UUID.Random();
linkedItem3.CurrentPermissions = linkedItem2.NextPermissions;
linkedItem3.EveryOnePermissions = linkedItem2.NextPermissions;
linkedItem3.Folder = CurrentOutFitFolder.ID;
m_InventoryService.AddItem(linkedItem3);
}
else
items2UnAttach.Add(attachment.ItemID);
}
}
}
foreach (UUID uuid in items2UnAttach)
{
avappearance.DetachAttachment(uuid);
}
if (brokenLinks.Count != 0)
m_InventoryService.DeleteItems(user, brokenLinks);
return avappearance;
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace NxtTipbot
{
public interface ISlackConnector
{
string SelfId { get; }
string SelfName { get; }
Task SendMessage(string channelId, string message, bool unfurl_links = true);
Task<string> GetInstantMessageId(string userId);
SlackUser GetUser(string userId);
}
public class SlackConnector : ISlackConnector
{
private readonly string apiToken;
private readonly ILogger logger;
private readonly ISlackHandler slackHandler;
public string SelfId { get; private set; }
public string SelfName { get; private set; }
private List<SlackChannelSession> channelSessions;
private List<SlackUser> slackUsers;
private List<SlackIMSession> imSessions;
private ClientWebSocket webSocket;
private readonly UTF8Encoding encoder = new UTF8Encoding();
public SlackConnector(string apiToken, ILogger logger, ISlackHandler slackHandler)
{
this.logger = logger;
this.apiToken = apiToken;
this.slackHandler = slackHandler;
}
public async Task Run()
{
var lastConnectTry = DateTime.MinValue;
while (DateTime.Compare(lastConnectTry.AddMinutes(1), DateTime.UtcNow) < 0)
{
try
{
string websocketUri = string.Empty;
List<SlackChannelSession> groupSessions;
List<SlackChannelSession> mpimSessions;
using (var httpClient = new HttpClient())
using (var response = await httpClient.GetAsync($"https://slack.com/api/rtm.start?token={apiToken}&simple_latest=true&no_unreads=true&mpim_aware=true"))
using (var content = response.Content)
{
var json = await content.ReadAsStringAsync();
logger.LogTrace($"Initial handshake reply with rtm.start: {json}");
var jObject = JObject.Parse(json);
websocketUri = (string)jObject["url"];
SelfId = (string)jObject["self"]["id"];
SelfName = (string)jObject["self"]["name"];
channelSessions = JsonConvert.DeserializeObject<List<SlackChannelSession>>(jObject["channels"].ToString());
groupSessions = JsonConvert.DeserializeObject<List<SlackChannelSession>>(jObject["groups"].ToString());
mpimSessions = JsonConvert.DeserializeObject<List<SlackChannelSession>>(jObject["mpims"].ToString());
slackUsers = JsonConvert.DeserializeObject<List<SlackUser>>(jObject["users"].ToString());
imSessions = JsonConvert.DeserializeObject<List<SlackIMSession>>(jObject["ims"].ToString());
}
var channels = string.Join(", ", channelSessions.Where(s => s.IsMember).Select(s => s.Name));
var groups = string.Join(", ", groupSessions.Where(s => s.IsMember).Select(s => s.Name));
var mpims = string.Join(", ", mpimSessions.Where(s => s.IsMember).Select(s => s.Name));
channelSessions.AddRange(groupSessions.Union(mpimSessions));
logger.LogTrace($"I'm currently in these channels: {channels}");
logger.LogTrace($"I'm currently in these private channels: {groups}");
logger.LogTrace($"I'm currently in these Multiparty IM's: {mpims}");
webSocket = new ClientWebSocket();
lastConnectTry = DateTime.UtcNow;
await webSocket.ConnectAsync(new Uri(websocketUri), CancellationToken.None);
await Recieve();
}
catch (Exception e)
{
logger.LogCritical($"Unhandled exception: {e.ToString()}\n{e.Message}\n{e.StackTrace}\nAttempting to reconnect..");
}
}
}
private async Task Recieve()
{
WebSocketReceiveResult result;
var buffer = new byte[8192];
while (webSocket.State == WebSocketState.Open)
{
string json = string.Empty;
do
{
result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
if (result.MessageType == WebSocketMessageType.Close)
{
logger.LogInformation("MessageType.Close recieved, closing connection to Slack.");
await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
return;
}
json += encoder.GetString(buffer, 0, result.Count);
} while (result.Count == buffer.Length || !json.TrimEnd().EndsWith("}"));
JObject jObject = null;
try
{
jObject = JObject.Parse(json);
}
catch (Exception)
{
logger.LogCritical($"Error when parsing json, length: {json.Length}, json text: {json}");
throw;
}
var type = (string)jObject["type"];
switch (type)
{
case "presence_change":// ignore these
case "reconnect_url":
case "user_typing":
case "hello":
case "reaction_removed":
case "file_shared":
case "file_public":
case "dnd_updated_user":
case "pin_added":
case "pin_removed":
case "desktop_notification":
break;
case "reaction_added": await HandleReactionAdded(json);
break;
case "message": await HandleMessage(json);
break;
case "im_created": HandleIMSessionCreated(jObject);
break;
case "channel_created": HandleChannelCreated(jObject);
break;
case "team_join": HandleTeamJoin(jObject);
break;
case "user_change": HandleUserChange(jObject);
break;
case null: HandleNullType(jObject, json);
break;
default: logger.LogTrace($"Data recieved: {json}");
break;
}
}
}
private async Task HandleReactionAdded(string json)
{
var reaction = JsonConvert.DeserializeObject<SlackReaction>(json);
var slackUser = slackUsers.SingleOrDefault(u => u.Id == reaction.UserId);
var recipientSlackUser = slackUsers.SingleOrDefault(u => u.Id == reaction.ItemUserId);
var channel = channelSessions.SingleOrDefault(c => c.Id == reaction.Item.ChannelId);
if (slackUser != null && recipientSlackUser != null && slackUser.Id != SelfId && channel != null)
{
await slackHandler.TipBotReactionCommand(reaction, slackUser, recipientSlackUser, channel);
}
}
private async Task HandleMessage(string json)
{
var message = JsonConvert.DeserializeObject<SlackMessage>(json);
var slackUser = slackUsers.SingleOrDefault(u => u.Id == message.UserId);
var channel = channelSessions.SingleOrDefault(c => c.Id == message.ChannelId);
var instantMessage = imSessions.SingleOrDefault(im => im.Id == message.ChannelId);
if (slackUser != null && slackUser.Id != SelfId)
{
if (channel != null && message.Text.StartsWith(SelfName, StringComparison.OrdinalIgnoreCase) || message.Text.StartsWith($"<@{SelfId}>"))
{
await slackHandler.TipBotChannelCommand(message, slackUser, channel);
}
else if (instantMessage != null)
{
logger.LogTrace($"Recieved IM from: {slackUser.Name} ({slackUser.Id}), message: {message.Text}");
await slackHandler.InstantMessageCommand(message.Text, slackUser, instantMessage);
}
}
}
private void HandleIMSessionCreated(JObject jObject)
{
var imSession = new SlackIMSession
{
Id = (string)jObject["channel"]["id"],
UserId = (string)jObject["user"]
};
if (imSessions.All(im => im.Id != imSession.Id))
{
imSessions.Add(imSession);
var slackUser = slackUsers.Single(u => u.Id == imSession.UserId);
logger.LogTrace($"IM session with user {slackUser.Name} was created.");
}
}
private void HandleChannelCreated(JObject jObject)
{
var channelSession = JsonConvert.DeserializeObject<SlackChannelSession>(jObject["channel"].ToString());
channelSessions.Add(channelSession);
logger.LogTrace($"#{channelSession.Name} was created.");
}
private void HandleTeamJoin(JObject jObject)
{
var slackUser = JsonConvert.DeserializeObject<SlackUser>(jObject["user"].ToString());
logger.LogTrace($"User {slackUser.Name} has joined the team (id: {slackUser.Id}).");
slackUsers.Add(slackUser);
}
private void HandleUserChange(JObject jObject)
{
var slackUser = JsonConvert.DeserializeObject<SlackUser>(jObject["user"].ToString());
var oldSlackUser = slackUsers.Single(u => u.Id == slackUser.Id);
if (!string.Equals(oldSlackUser.Name, slackUser.Name))
{
logger.LogTrace($"User {oldSlackUser.Name} changed his username to {slackUser.Name} (id: {slackUser.Id})");
oldSlackUser.Name = slackUser.Name;
}
}
private void HandleNullType(JObject jObject, string json)
{
if ((string)jObject["reply_to"] == null)
logger.LogTrace(json);
}
public async Task SendMessage(string channelId, string message, bool unfurl_links = true)
{
var debugTarget = channelSessions.SingleOrDefault(s => s.Id == channelId)?.Name ??
slackUsers.Single(u => u.Id == imSessions.Single(s => s.Id == channelId).UserId).Name;
message = message.Replace("&", "%26amp;");
logger.LogTrace($"Sending chat.postMessage to: {debugTarget} ({channelId}), message: {message}");
using (var httpClient = new HttpClient())
using (var response = await httpClient.GetAsync($"https://slack.com/api/chat.postMessage?token={apiToken}&channel={channelId}&text={message}&unfurl_links={unfurl_links}&as_user=true"))
using (var content = response.Content)
{
var json = await content.ReadAsStringAsync();
//logger.LogTrace($"Reply from request to chat.postMessage: {json}");
}
}
public async Task<string> GetInstantMessageId(string userId)
{
if (userId == SelfId)
{
throw new ArgumentException("Cannot instant message with yourself", nameof(userId));
}
var id = imSessions.SingleOrDefault(im => im.UserId == userId)?.Id;
if (id == null)
{
var userName = slackUsers.Single(u => u.Id == userId).Name;
logger.LogTrace($"Requesting im.open with user {userName} ({userId})");
using (var httpClient = new HttpClient())
using (var response = await httpClient.GetAsync($"https://slack.com/api/im.open?token={apiToken}&user={userId}&as_user=true"))
using (var content = response.Content)
{
var json = await content.ReadAsStringAsync();
logger.LogTrace($"Reply from request to im.open: {json}");
var jObject = JObject.Parse(json);
id = (string)jObject["channel"]["id"];
imSessions.Add(new SlackIMSession {Id = id, UserId = userId});
}
}
return id;
}
public SlackUser GetUser(string userId)
{
return slackUsers.SingleOrDefault(u => u.Id == userId);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using Server;
using Server.Mobiles;
using Server.Network;
using Server.Spells;
namespace Server.Items
{
public class Teleporter : Item
{
private bool m_Active, m_Creatures, m_CombatCheck, m_CriminalCheck;
private Point3D m_PointDest;
private Map m_MapDest;
private bool m_SourceEffect;
private bool m_DestEffect;
private int m_SoundID;
private TimeSpan m_Delay;
[CommandProperty(AccessLevel.GameMaster)]
public bool SourceEffect
{
get { return m_SourceEffect; }
set { m_SourceEffect = value; InvalidateProperties(); }
}
[CommandProperty(AccessLevel.GameMaster)]
public bool DestEffect
{
get { return m_DestEffect; }
set { m_DestEffect = value; InvalidateProperties(); }
}
[CommandProperty(AccessLevel.GameMaster)]
public int SoundID
{
get { return m_SoundID; }
set { m_SoundID = value; InvalidateProperties(); }
}
[CommandProperty(AccessLevel.GameMaster)]
public TimeSpan Delay
{
get { return m_Delay; }
set { m_Delay = value; InvalidateProperties(); }
}
[CommandProperty(AccessLevel.GameMaster)]
public bool Active
{
get { return m_Active; }
set { m_Active = value; InvalidateProperties(); }
}
[CommandProperty(AccessLevel.GameMaster)]
public Point3D PointDest
{
get { return m_PointDest; }
set { m_PointDest = value; InvalidateProperties(); }
}
[CommandProperty(AccessLevel.GameMaster)]
public Map MapDest
{
get { return m_MapDest; }
set { m_MapDest = value; InvalidateProperties(); }
}
[CommandProperty(AccessLevel.GameMaster)]
public bool Creatures
{
get { return m_Creatures; }
set { m_Creatures = value; InvalidateProperties(); }
}
[CommandProperty(AccessLevel.GameMaster)]
public bool CombatCheck
{
get { return m_CombatCheck; }
set { m_CombatCheck = value; InvalidateProperties(); }
}
[CommandProperty(AccessLevel.GameMaster)]
public bool CriminalCheck
{
get { return m_CriminalCheck; }
set { m_CriminalCheck = value; InvalidateProperties(); }
}
public override int LabelNumber { get { return 1026095; } } // teleporter
[Constructable]
public Teleporter()
: this(new Point3D(0, 0, 0), null, false)
{
}
[Constructable]
public Teleporter(Point3D pointDest, Map mapDest)
: this(pointDest, mapDest, false)
{
}
[Constructable]
public Teleporter(Point3D pointDest, Map mapDest, bool creatures)
: base(0x1BC3)
{
Movable = false;
Visible = false;
m_Active = true;
m_PointDest = pointDest;
m_MapDest = mapDest;
m_Creatures = creatures;
m_CombatCheck = false;
m_CriminalCheck = false;
}
public override void GetProperties(ObjectPropertyList list)
{
base.GetProperties(list);
if (m_Active)
list.Add(1060742); // active
else
list.Add(1060743); // inactive
if (m_MapDest != null)
list.Add(1060658, "Map\t{0}", m_MapDest);
if (m_PointDest != Point3D.Zero)
list.Add(1060659, "Coords\t{0}", m_PointDest);
list.Add(1060660, "Creatures\t{0}", m_Creatures ? "Yes" : "No");
}
public override void OnSingleClick(Mobile from)
{
base.OnSingleClick(from);
if (m_Active)
{
if (m_MapDest != null && m_PointDest != Point3D.Zero)
LabelTo(from, "{0} [{1}]", m_PointDest, m_MapDest);
else if (m_MapDest != null)
LabelTo(from, "[{0}]", m_MapDest);
else if (m_PointDest != Point3D.Zero)
LabelTo(from, m_PointDest.ToString());
}
else
{
LabelTo(from, "(inactive)");
}
}
public virtual bool CanTeleport(Mobile m)
{
if (!m_Creatures && !m.Player)
{
return false;
}
else if (m_CriminalCheck && m.Criminal)
{
m.SendLocalizedMessage(1005561, "", 0x22); // Thou'rt a criminal and cannot escape so easily.
return false;
}
else if (m_CombatCheck && SpellHelper.CheckCombat(m))
{
m.SendLocalizedMessage(1005564, "", 0x22); // Wouldst thou flee during the heat of battle??
return false;
}
return true;
}
public virtual void StartTeleport(Mobile m)
{
if (m_Delay == TimeSpan.Zero)
DoTeleport(m);
else
Timer.DelayCall<Mobile>(m_Delay, DoTeleport, m);
}
public virtual void DoTeleport(Mobile m)
{
Map map = m_MapDest;
if (map == null || map == Map.Internal)
map = m.Map;
Point3D p = m_PointDest;
if (p == Point3D.Zero)
p = m.Location;
Server.Mobiles.BaseCreature.TeleportPets(m, p, map);
bool sendEffect = (!m.Hidden || m.AccessLevel == AccessLevel.Player);
if (m_SourceEffect && sendEffect)
Effects.SendLocationEffect(m.Location, m.Map, 0x3728, 10, 10);
m.MoveToWorld(p, map);
if (m_DestEffect && sendEffect)
Effects.SendLocationEffect(m.Location, m.Map, 0x3728, 10, 10);
if (m_SoundID > 0 && sendEffect)
Effects.PlaySound(m.Location, m.Map, m_SoundID);
}
public override bool OnMoveOver(Mobile m)
{
if (m_Active && CanTeleport(m))
{
StartTeleport(m);
return false;
}
return true;
}
public Teleporter(Serial serial)
: base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)4); // version
writer.Write((bool)m_CriminalCheck);
writer.Write((bool)m_CombatCheck);
writer.Write((bool)m_SourceEffect);
writer.Write((bool)m_DestEffect);
writer.Write((TimeSpan)m_Delay);
writer.WriteEncodedInt((int)m_SoundID);
writer.Write(m_Creatures);
writer.Write(m_Active);
writer.Write(m_PointDest);
writer.Write(m_MapDest);
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
switch (version)
{
case 4:
{
m_CriminalCheck = reader.ReadBool();
goto case 3;
}
case 3:
{
m_CombatCheck = reader.ReadBool();
goto case 2;
}
case 2:
{
m_SourceEffect = reader.ReadBool();
m_DestEffect = reader.ReadBool();
m_Delay = reader.ReadTimeSpan();
m_SoundID = reader.ReadEncodedInt();
goto case 1;
}
case 1:
{
m_Creatures = reader.ReadBool();
goto case 0;
}
case 0:
{
m_Active = reader.ReadBool();
m_PointDest = reader.ReadPoint3D();
m_MapDest = reader.ReadMap();
break;
}
}
}
}
public class SkillTeleporter : Teleporter
{
private SkillName m_Skill;
private double m_Required;
private string m_MessageString;
private int m_MessageNumber;
[CommandProperty(AccessLevel.GameMaster)]
public SkillName Skill
{
get { return m_Skill; }
set { m_Skill = value; InvalidateProperties(); }
}
[CommandProperty(AccessLevel.GameMaster)]
public double Required
{
get { return m_Required; }
set { m_Required = value; InvalidateProperties(); }
}
[CommandProperty(AccessLevel.GameMaster)]
public string MessageString
{
get { return m_MessageString; }
set { m_MessageString = value; InvalidateProperties(); }
}
[CommandProperty(AccessLevel.GameMaster)]
public int MessageNumber
{
get { return m_MessageNumber; }
set { m_MessageNumber = value; InvalidateProperties(); }
}
private void EndMessageLock(object state)
{
((Mobile)state).EndAction(this);
}
public override bool CanTeleport(Mobile m)
{
if (!base.CanTeleport(m))
return false;
Skill sk = m.Skills[m_Skill];
if (sk == null || sk.Base < m_Required)
{
if (m.BeginAction(this))
{
if (m_MessageString != null)
m.Send(new UnicodeMessage(Serial, ItemID, MessageType.Regular, 0x3B2, 3, "ENU", null, m_MessageString));
else if (m_MessageNumber != 0)
m.Send(new MessageLocalized(Serial, ItemID, MessageType.Regular, 0x3B2, 3, m_MessageNumber, null, ""));
Timer.DelayCall(TimeSpan.FromSeconds(5.0), new TimerStateCallback(EndMessageLock), m);
}
return false;
}
return true;
}
public override void GetProperties(ObjectPropertyList list)
{
base.GetProperties(list);
int skillIndex = (int)m_Skill;
string skillName;
if (skillIndex >= 0 && skillIndex < SkillInfo.Table.Length)
skillName = SkillInfo.Table[skillIndex].Name;
else
skillName = "(Invalid)";
list.Add(1060661, "{0}\t{1:F1}", skillName, m_Required);
if (m_MessageString != null)
list.Add(1060662, "Message\t{0}", m_MessageString);
else if (m_MessageNumber != 0)
list.Add(1060662, "Message\t#{0}", m_MessageNumber);
}
[Constructable]
public SkillTeleporter()
{
}
public SkillTeleporter(Serial serial)
: base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
writer.Write((int)m_Skill);
writer.Write((double)m_Required);
writer.Write((string)m_MessageString);
writer.Write((int)m_MessageNumber);
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
switch (version)
{
case 0:
{
m_Skill = (SkillName)reader.ReadInt();
m_Required = reader.ReadDouble();
m_MessageString = reader.ReadString();
m_MessageNumber = reader.ReadInt();
break;
}
}
}
}
public class KeywordTeleporter : Teleporter
{
private string m_Substring;
private int m_Keyword;
private int m_Range;
[CommandProperty(AccessLevel.GameMaster)]
public string Substring
{
get { return m_Substring; }
set { m_Substring = value; InvalidateProperties(); }
}
[CommandProperty(AccessLevel.GameMaster)]
public int Keyword
{
get { return m_Keyword; }
set { m_Keyword = value; InvalidateProperties(); }
}
[CommandProperty(AccessLevel.GameMaster)]
public int Range
{
get { return m_Range; }
set { m_Range = value; InvalidateProperties(); }
}
public override bool HandlesOnSpeech { get { return true; } }
public override void OnSpeech(SpeechEventArgs e)
{
if (!e.Handled && Active)
{
Mobile m = e.Mobile;
if (!m.InRange(GetWorldLocation(), m_Range))
return;
bool isMatch = false;
if (m_Keyword >= 0 && e.HasKeyword(m_Keyword))
isMatch = true;
else if (m_Substring != null && e.Speech.ToLower().IndexOf(m_Substring.ToLower()) >= 0)
isMatch = true;
if (!isMatch || !CanTeleport(m))
return;
e.Handled = true;
StartTeleport(m);
}
}
public override void DoTeleport(Mobile m)
{
if (!m.InRange(GetWorldLocation(), m_Range) || m.Map != Map)
return;
base.DoTeleport(m);
}
public override bool OnMoveOver(Mobile m)
{
return true;
}
public override void GetProperties(ObjectPropertyList list)
{
base.GetProperties(list);
list.Add(1060661, "Range\t{0}", m_Range);
if (m_Keyword >= 0)
list.Add(1060662, "Keyword\t{0}", m_Keyword);
if (m_Substring != null)
list.Add(1060663, "Substring\t{0}", m_Substring);
}
[Constructable]
public KeywordTeleporter()
{
m_Keyword = -1;
m_Substring = null;
}
public KeywordTeleporter(Serial serial)
: base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
writer.Write(m_Substring);
writer.Write(m_Keyword);
writer.Write(m_Range);
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
switch (version)
{
case 0:
{
m_Substring = reader.ReadString();
m_Keyword = reader.ReadInt();
m_Range = reader.ReadInt();
break;
}
}
}
}
public class WaitTeleporter : KeywordTeleporter
{
private static Dictionary<Mobile, TeleportingInfo> m_Table;
public static void Initialize()
{
m_Table = new Dictionary<Mobile, TeleportingInfo>();
EventSink.Logout += new LogoutEventHandler(EventSink_Logout);
}
public static void EventSink_Logout(LogoutEventArgs e)
{
Mobile from = e.Mobile;
TeleportingInfo info;
if (from == null || !m_Table.TryGetValue(from, out info))
return;
info.Timer.Stop();
m_Table.Remove(from);
}
private int m_StartNumber;
private string m_StartMessage;
private int m_ProgressNumber;
private string m_ProgressMessage;
private bool m_ShowTimeRemaining;
[CommandProperty(AccessLevel.GameMaster)]
public int StartNumber
{
get { return m_StartNumber; }
set { m_StartNumber = value; }
}
[CommandProperty(AccessLevel.GameMaster)]
public string StartMessage
{
get { return m_StartMessage; }
set { m_StartMessage = value; }
}
[CommandProperty(AccessLevel.GameMaster)]
public int ProgressNumber
{
get { return m_ProgressNumber; }
set { m_ProgressNumber = value; }
}
[CommandProperty(AccessLevel.GameMaster)]
public string ProgressMessage
{
get { return m_ProgressMessage; }
set { m_ProgressMessage = value; }
}
[CommandProperty(AccessLevel.GameMaster)]
public bool ShowTimeRemaining
{
get { return m_ShowTimeRemaining; }
set { m_ShowTimeRemaining = value; }
}
[Constructable]
public WaitTeleporter()
{
}
public static string FormatTime(TimeSpan ts)
{
if (ts.TotalHours >= 1)
{
int h = (int)Math.Round(ts.TotalHours);
return String.Format("{0} hour{1}", h, (h == 1) ? "" : "s");
}
else if (ts.TotalMinutes >= 1)
{
int m = (int)Math.Round(ts.TotalMinutes);
return String.Format("{0} minute{1}", m, (m == 1) ? "" : "s");
}
int s = Math.Max((int)Math.Round(ts.TotalSeconds), 0);
return String.Format("{0} second{1}", s, (s == 1) ? "" : "s");
}
private void EndLock(Mobile m)
{
m.EndAction(this);
}
public override void StartTeleport(Mobile m)
{
TeleportingInfo info;
if (m_Table.TryGetValue(m, out info))
{
if (info.Teleporter == this)
{
if (m.BeginAction(this))
{
if (m_ProgressMessage != null)
m.SendMessage(m_ProgressMessage);
else if (m_ProgressNumber != 0)
m.SendLocalizedMessage(m_ProgressNumber);
if (m_ShowTimeRemaining)
m.SendMessage("Time remaining: {0}", FormatTime(m_Table[m].Timer.Next - DateTime.Now));
Timer.DelayCall<Mobile>(TimeSpan.FromSeconds(5), EndLock, m);
}
return;
}
else
{
info.Timer.Stop();
}
}
if (m_StartMessage != null)
m.SendMessage(m_StartMessage);
else if (m_StartNumber != 0)
m.SendLocalizedMessage(m_StartNumber);
if (Delay == TimeSpan.Zero)
DoTeleport(m);
else
m_Table[m] = new TeleportingInfo(this, Timer.DelayCall<Mobile>(Delay, DoTeleport, m));
}
public override void DoTeleport(Mobile m)
{
m_Table.Remove(m);
base.DoTeleport(m);
}
public WaitTeleporter(Serial serial)
: base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
writer.Write(m_StartNumber);
writer.Write(m_StartMessage);
writer.Write(m_ProgressNumber);
writer.Write(m_ProgressMessage);
writer.Write(m_ShowTimeRemaining);
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
m_StartNumber = reader.ReadInt();
m_StartMessage = reader.ReadString();
m_ProgressNumber = reader.ReadInt();
m_ProgressMessage = reader.ReadString();
m_ShowTimeRemaining = reader.ReadBool();
}
private class TeleportingInfo
{
private WaitTeleporter m_Teleporter;
private Timer m_Timer;
public WaitTeleporter Teleporter { get { return m_Teleporter; } }
public Timer Timer { get { return m_Timer; } }
public TeleportingInfo(WaitTeleporter tele, Timer t)
{
m_Teleporter = tele;
m_Timer = t;
}
}
}
public class TimeoutTeleporter : Teleporter
{
private TimeSpan m_TimeoutDelay;
private Dictionary<Mobile, Timer> m_Teleporting;
[CommandProperty(AccessLevel.GameMaster)]
public TimeSpan TimeoutDelay
{
get { return m_TimeoutDelay; }
set { m_TimeoutDelay = value; }
}
[Constructable]
public TimeoutTeleporter()
: this(new Point3D(0, 0, 0), null, false)
{
}
[Constructable]
public TimeoutTeleporter(Point3D pointDest, Map mapDest)
: this(pointDest, mapDest, false)
{
}
[Constructable]
public TimeoutTeleporter(Point3D pointDest, Map mapDest, bool creatures)
: base(pointDest, mapDest, creatures)
{
m_Teleporting = new Dictionary<Mobile, Timer>();
}
public void StartTimer(Mobile m)
{
StartTimer(m, m_TimeoutDelay);
}
private void StartTimer(Mobile m, TimeSpan delay)
{
Timer t;
if (m_Teleporting.TryGetValue(m, out t))
t.Stop();
m_Teleporting[m] = Timer.DelayCall<Mobile>(delay, StartTeleport, m);
}
public void StopTimer(Mobile m)
{
Timer t;
if (m_Teleporting.TryGetValue(m, out t))
{
t.Stop();
m_Teleporting.Remove(m);
}
}
public override void DoTeleport(Mobile m)
{
m_Teleporting.Remove(m);
base.DoTeleport(m);
}
public override bool OnMoveOver(Mobile m)
{
if (Active)
{
if (!CanTeleport(m))
return false;
StartTimer(m);
}
return true;
}
public TimeoutTeleporter(Serial serial)
: base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
writer.Write(m_TimeoutDelay);
writer.Write(m_Teleporting.Count);
foreach (KeyValuePair<Mobile, Timer> kvp in m_Teleporting)
{
writer.Write(kvp.Key);
writer.Write(kvp.Value.Next);
}
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
m_TimeoutDelay = reader.ReadTimeSpan();
m_Teleporting = new Dictionary<Mobile, Timer>();
int count = reader.ReadInt();
for (int i = 0; i < count; ++i)
{
Mobile m = reader.ReadMobile();
DateTime end = reader.ReadDateTime();
StartTimer(m, end - DateTime.Now);
}
}
}
public class TimeoutGoal : Item
{
private TimeoutTeleporter m_Teleporter;
[CommandProperty(AccessLevel.GameMaster)]
public TimeoutTeleporter Teleporter
{
get { return m_Teleporter; }
set { m_Teleporter = value; }
}
[Constructable]
public TimeoutGoal()
: base(0x1822)
{
Movable = false;
Visible = false;
Hue = 1154;
}
public override bool OnMoveOver(Mobile m)
{
if (m_Teleporter != null)
m_Teleporter.StopTimer(m);
return true;
}
public override string DefaultName
{
get { return "timeout teleporter goal"; }
}
public TimeoutGoal(Serial serial)
: base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
writer.WriteItem<TimeoutTeleporter>(m_Teleporter);
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
m_Teleporter = reader.ReadItem<TimeoutTeleporter>();
}
}
public class ConditionTeleporter : Teleporter
{
[Flags]
protected enum ConditionFlag
{
None = 0x000,
DenyMounted = 0x001,
DenyFollowers = 0x002,
DenyPackContents = 0x004,
DenyHolding = 0x008,
DenyEquipment = 0x010,
DenyTransformed = 0x020,
StaffOnly = 0x040,
DenyPackEthereals = 0x080,
DeadOnly = 0x100
}
private ConditionFlag m_Flags;
[CommandProperty(AccessLevel.GameMaster)]
public bool DenyMounted
{
get { return GetFlag(ConditionFlag.DenyMounted); }
set { SetFlag(ConditionFlag.DenyMounted, value); InvalidateProperties(); }
}
[CommandProperty(AccessLevel.GameMaster)]
public bool DenyFollowers
{
get { return GetFlag(ConditionFlag.DenyFollowers); }
set { SetFlag(ConditionFlag.DenyFollowers, value); InvalidateProperties(); }
}
[CommandProperty(AccessLevel.GameMaster)]
public bool DenyPackContents
{
get { return GetFlag(ConditionFlag.DenyPackContents); }
set { SetFlag(ConditionFlag.DenyPackContents, value); InvalidateProperties(); }
}
[CommandProperty(AccessLevel.GameMaster)]
public bool DenyHolding
{
get { return GetFlag(ConditionFlag.DenyHolding); }
set { SetFlag(ConditionFlag.DenyHolding, value); InvalidateProperties(); }
}
[CommandProperty(AccessLevel.GameMaster)]
public bool DenyEquipment
{
get { return GetFlag(ConditionFlag.DenyEquipment); }
set { SetFlag(ConditionFlag.DenyEquipment, value); InvalidateProperties(); }
}
[CommandProperty(AccessLevel.GameMaster)]
public bool DenyTransformed
{
get { return GetFlag(ConditionFlag.DenyTransformed); }
set { SetFlag(ConditionFlag.DenyTransformed, value); InvalidateProperties(); }
}
[CommandProperty( AccessLevel.GameMaster )]
public bool StaffOnly
{
get{ return GetFlag( ConditionFlag.StaffOnly ); }
set{ SetFlag( ConditionFlag.StaffOnly, value ); InvalidateProperties(); }
}
[CommandProperty(AccessLevel.GameMaster)]
public bool DenyPackEthereals
{
get { return GetFlag(ConditionFlag.DenyPackEthereals); }
set { SetFlag(ConditionFlag.DenyPackEthereals, value); InvalidateProperties(); }
}
[CommandProperty(AccessLevel.GameMaster)]
public bool DeadOnly
{
get { return GetFlag(ConditionFlag.DeadOnly); }
set { SetFlag(ConditionFlag.DeadOnly, value); InvalidateProperties(); }
}
public override bool CanTeleport(Mobile m)
{
if (!base.CanTeleport(m))
return false;
if (GetFlag(ConditionFlag.StaffOnly) && m.AccessLevel < AccessLevel.Counselor)
return false;
if (GetFlag(ConditionFlag.DenyMounted) && m.Mounted)
{
m.SendLocalizedMessage(1077252); // You must dismount before proceeding.
return false;
}
if (GetFlag(ConditionFlag.DenyFollowers) && (m.Followers != 0 || (m is PlayerMobile && ((PlayerMobile)m).AutoStabled.Count != 0)))
{
m.SendLocalizedMessage(1077250); // No pets permitted beyond this point.
return false;
}
Container pack = m.Backpack;
if (pack != null)
{
if (GetFlag(ConditionFlag.DenyPackContents) && pack.TotalItems != 0)
{
m.SendMessage("You must empty your backpack before proceeding.");
return false;
}
if (GetFlag(ConditionFlag.DenyPackEthereals) && (pack.FindItemByType(typeof(EtherealMount)) != null || pack.FindItemByType(typeof(BaseImprisonedMobile)) != null))
{
m.SendMessage("You must empty your backpack of ethereal mounts before proceeding.");
return false;
}
}
if (GetFlag(ConditionFlag.DenyHolding) && m.Holding != null)
{
m.SendMessage("You must let go of what you are holding before proceeding.");
return false;
}
if (GetFlag(ConditionFlag.DenyEquipment))
{
foreach (Item item in m.Items)
{
switch (item.Layer)
{
case Layer.Hair:
case Layer.FacialHair:
case Layer.Backpack:
case Layer.Mount:
case Layer.Bank:
{
continue; // ignore
}
default:
{
m.SendMessage("You must remove all of your equipment before proceeding.");
return false;
}
}
}
}
if (GetFlag(ConditionFlag.DenyTransformed) && m.IsBodyMod)
{
m.SendMessage("You cannot go there in this form.");
return false;
}
if (GetFlag(ConditionFlag.DeadOnly) && m.Alive)
{
m.SendLocalizedMessage(1060014); // Only the dead may pass.
return false;
}
return true;
}
[Constructable]
public ConditionTeleporter()
{
}
public override void GetProperties(ObjectPropertyList list)
{
base.GetProperties(list);
StringBuilder props = new StringBuilder();
if (GetFlag(ConditionFlag.DenyMounted))
props.Append("<BR>Deny Mounted");
if (GetFlag(ConditionFlag.DenyFollowers))
props.Append("<BR>Deny Followers");
if (GetFlag(ConditionFlag.DenyPackContents))
props.Append("<BR>Deny Pack Contents");
if (GetFlag(ConditionFlag.DenyPackEthereals))
props.Append("<BR>Deny Pack Ethereals");
if (GetFlag(ConditionFlag.DenyHolding))
props.Append("<BR>Deny Holding");
if (GetFlag(ConditionFlag.DenyEquipment))
props.Append("<BR>Deny Equipment");
if (GetFlag(ConditionFlag.DenyTransformed))
props.Append("<BR>Deny Transformed");
if (GetFlag(ConditionFlag.StaffOnly))
props.Append("<BR>Staff Only");
if (GetFlag(ConditionFlag.DeadOnly))
props.Append("<BR>Dead Only");
if (props.Length != 0)
{
props.Remove(0, 4);
list.Add(props.ToString());
}
}
public ConditionTeleporter(Serial serial)
: base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
writer.Write((int)m_Flags);
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
m_Flags = (ConditionFlag)reader.ReadInt();
}
protected bool GetFlag(ConditionFlag flag)
{
return ((m_Flags & flag) != 0);
}
protected void SetFlag(ConditionFlag flag, bool value)
{
if (value)
m_Flags |= flag;
else
m_Flags &= ~flag;
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2009-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.
// ***********************************************************************
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Linq;
using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal;
using NUnit.TestData.TestCaseSourceAttributeFixture;
using NUnit.TestUtilities;
namespace NUnit.Framework.Attributes
{
[TestFixture]
public class TestCaseSourceTests : TestSourceMayBeInherited
{
#region Tests With Static and Instance Members as Source
[Test, TestCaseSource("StaticProperty")]
public void SourceCanBeStaticProperty(string source)
{
Assert.AreEqual("StaticProperty", source);
}
[Test, TestCaseSource("InheritedStaticProperty")]
public void TestSourceCanBeInheritedStaticProperty(bool source)
{
Assert.AreEqual(true, source);
}
static IEnumerable StaticProperty
{
get { return new object[] { new object[] { "StaticProperty" } }; }
}
[Test]
public void SourceUsingInstancePropertyIsNotRunnable()
{
var result = TestBuilder.RunParameterizedMethodSuite(typeof(TestCaseSourceAttributeFixture), "MethodWithInstancePropertyAsSource");
Assert.AreEqual(result.Children.ToArray()[0].ResultState, ResultState.NotRunnable);
}
[Test, TestCaseSource("StaticMethod")]
public void SourceCanBeStaticMethod(string source)
{
Assert.AreEqual("StaticMethod", source);
}
static IEnumerable StaticMethod()
{
return new object[] { new object[] { "StaticMethod" } };
}
[Test]
public void SourceUsingInstanceMethodIsNotRunnable()
{
var result = TestBuilder.RunParameterizedMethodSuite(typeof(TestCaseSourceAttributeFixture), "MethodWithInstanceMethodAsSource");
Assert.AreEqual(result.Children.ToArray()[0].ResultState, ResultState.NotRunnable);
}
IEnumerable InstanceMethod()
{
return new object[] { new object[] { "InstanceMethod" } };
}
[Test, TestCaseSource("StaticField")]
public void SourceCanBeStaticField(string source)
{
Assert.AreEqual("StaticField", source);
}
static object[] StaticField =
{ new object[] { "StaticField" } };
[Test]
public void SourceUsingInstanceFieldIsNotRunnable()
{
var result = TestBuilder.RunParameterizedMethodSuite(typeof(TestCaseSourceAttributeFixture), "MethodWithInstanceFieldAsSource");
Assert.AreEqual(result.Children.ToArray()[0].ResultState, ResultState.NotRunnable);
}
#endregion
#region Test With IEnumerable Class as Source
[Test, TestCaseSource(typeof(DataSourceClass))]
public void SourceCanBeInstanceOfIEnumerable(string source)
{
Assert.AreEqual("DataSourceClass", source);
}
class DataSourceClass : IEnumerable
{
public DataSourceClass()
{
}
public IEnumerator GetEnumerator()
{
yield return "DataSourceClass";
}
}
#endregion
[Test, TestCaseSource("MyData")]
public void SourceMayReturnArgumentsAsObjectArray(int n, int d, int q)
{
Assert.AreEqual(q, n / d);
}
[TestCaseSource("MyData")]
public void TestAttributeIsOptional(int n, int d, int q)
{
Assert.AreEqual(q, n / d);
}
[Test, TestCaseSource("MyIntData")]
public void SourceMayReturnArgumentsAsIntArray(int n, int d, int q)
{
Assert.AreEqual(q, n / d);
}
[Test, TestCaseSource("MyArrayData")]
public void SourceMayReturnArrayForArray(int[] array)
{
Assert.That(true);
}
[Test, TestCaseSource("EvenNumbers")]
public void SourceMayReturnSinglePrimitiveArgumentAlone(int n)
{
Assert.AreEqual(0, n % 2);
}
[Test, TestCaseSource("Params")]
public int SourceMayReturnArgumentsAsParamSet(int n, int d)
{
return n / d;
}
[Test]
[TestCaseSource("MyData")]
[TestCaseSource("MoreData", Category = "Extra")]
[TestCase(12, 2, 6)]
public void TestMayUseMultipleSourceAttributes(int n, int d, int q)
{
Assert.AreEqual(q, n / d);
}
[Test, TestCaseSource("FourArgs")]
public void TestWithFourArguments(int n, int d, int q, int r)
{
Assert.AreEqual(q, n / d);
Assert.AreEqual(r, n % d);
}
[Test, Category("Top"), TestCaseSource(typeof(DivideDataProvider), "HereIsTheData")]
public void SourceMayBeInAnotherClass(int n, int d, int q)
{
Assert.AreEqual(q, n / d);
}
[Test, Category("Top"), TestCaseSource(typeof(DivideDataProvider), "HereIsTheDataWithParameters", new object[] { 100, 4, 25 })]
public void SourceInAnotherClassPassingSomeDataToConstructor(int n, int d, int q)
{
Assert.AreEqual(q, n / d);
}
[Test, Category("Top"), TestCaseSource("StaticMethodDataWithParameters", new object[] { 8000, 8, 1000 })]
public void SourceCanBeStaticMethodPassingSomeDataToConstructor(int n, int d, int q)
{
Assert.AreEqual(q, n / d);
}
[Test]
public void SourceInAnotherClassPassingParamsToField()
{
var testMethod = (TestMethod)TestBuilder.MakeParameterizedMethodSuite(
typeof(TestCaseSourceAttributeFixture), "SourceInAnotherClassPassingParamsToField").Tests[0];
Assert.AreEqual(RunState.NotRunnable, testMethod.RunState);
ITestResult result = TestBuilder.RunTest(testMethod, null);
Assert.AreEqual(ResultState.NotRunnable, result.ResultState);
Assert.AreEqual("You have specified a data source field but also given a set of parameters. Fields cannot take parameters, " +
"please revise the 3rd parameter passed to the TestCaseSourceAttribute and either remove " +
"it or specify a method.", result.Message);
}
[Test]
public void SourceInAnotherClassPassingParamsToProperty()
{
var testMethod = (TestMethod)TestBuilder.MakeParameterizedMethodSuite(
typeof(TestCaseSourceAttributeFixture), "SourceInAnotherClassPassingParamsToProperty").Tests[0];
Assert.AreEqual(RunState.NotRunnable, testMethod.RunState);
ITestResult result = TestBuilder.RunTest(testMethod, null);
Assert.AreEqual(ResultState.NotRunnable, result.ResultState);
Assert.AreEqual("You have specified a data source property but also given a set of parameters. " +
"Properties cannot take parameters, please revise the 3rd parameter passed to the " +
"TestCaseSource attribute and either remove it or specify a method.", result.Message);
}
[Test]
public void SourceInAnotherClassPassingSomeDataToConstructorWrongNumberParam()
{
var testMethod = (TestMethod)TestBuilder.MakeParameterizedMethodSuite(
typeof(TestCaseSourceAttributeFixture), "SourceInAnotherClassPassingSomeDataToConstructorWrongNumberParam").Tests[0];
Assert.AreEqual(RunState.NotRunnable, testMethod.RunState);
ITestResult result = TestBuilder.RunTest(testMethod, null);
Assert.AreEqual(ResultState.NotRunnable, result.ResultState);
Assert.AreEqual("You have given the wrong number of arguments to the method in the TestCaseSourceAttribute" +
", please check the number of parameters passed in the object is correct in the 3rd parameter for the " +
"TestCaseSourceAttribute and this matches the number of parameters in the target method and try again.", result.Message);
}
[Test, TestCaseSource(typeof(DivideDataProviderWithReturnValue), "TestCases")]
public int SourceMayBeInAnotherClassWithReturn(int n, int d)
{
return n / d;
}
[Test]
public void IgnoreTakesPrecedenceOverExpectedException()
{
var result = TestBuilder.RunParameterizedMethodSuite(
typeof(TestCaseSourceAttributeFixture), "MethodCallsIgnore").Children.ToArray()[0];
Assert.AreEqual(ResultState.Ignored, result.ResultState);
Assert.AreEqual("Ignore this", result.Message);
}
[Test]
public void CanIgnoreIndividualTestCases()
{
TestSuite suite = TestBuilder.MakeParameterizedMethodSuite(
typeof(TestCaseSourceAttributeFixture), "MethodWithIgnoredTestCases");
Test testCase = TestFinder.Find("MethodWithIgnoredTestCases(1)", suite, false);
Assert.That(testCase.RunState, Is.EqualTo(RunState.Runnable));
testCase = TestFinder.Find("MethodWithIgnoredTestCases(2)", suite, false);
Assert.That(testCase.RunState, Is.EqualTo(RunState.Ignored));
Assert.That(testCase.Properties.Get(PropertyNames.SkipReason), Is.EqualTo("Don't Run Me!"));
}
[Test]
public void CanMarkIndividualTestCasesExplicit()
{
TestSuite suite = TestBuilder.MakeParameterizedMethodSuite(
typeof(TestCaseSourceAttributeFixture), "MethodWithExplicitTestCases");
Test testCase = TestFinder.Find("MethodWithExplicitTestCases(1)", suite, false);
Assert.That(testCase.RunState, Is.EqualTo(RunState.Runnable));
testCase = TestFinder.Find("MethodWithExplicitTestCases(2)", suite, false);
Assert.That(testCase.RunState, Is.EqualTo(RunState.Explicit));
testCase = TestFinder.Find("MethodWithExplicitTestCases(3)", suite, false);
Assert.That(testCase.RunState, Is.EqualTo(RunState.Explicit));
Assert.That(testCase.Properties.Get(PropertyNames.SkipReason), Is.EqualTo("Connection failing"));
}
[Test]
public void HandlesExceptionInTestCaseSource()
{
var testMethod = (TestMethod)TestBuilder.MakeParameterizedMethodSuite(
typeof(TestCaseSourceAttributeFixture), "MethodWithSourceThrowingException").Tests[0];
Assert.AreEqual(RunState.NotRunnable, testMethod.RunState);
ITestResult result = TestBuilder.RunTest(testMethod, null);
Assert.AreEqual(ResultState.NotRunnable, result.ResultState);
Assert.AreEqual("System.Exception : my message", result.Message);
}
[TestCaseSource("exception_source"), Explicit("Used for GUI tests")]
public void HandlesExceptionInTestCaseSource_GuiDisplay(string lhs, string rhs)
{
Assert.AreEqual(lhs, rhs);
}
private static IEnumerable<TestCaseData> ZeroTestCasesSource() => Enumerable.Empty<TestCaseData>();
[TestCaseSource("ZeroTestCasesSource")]
public void TestWithZeroTestSourceCasesShouldPassWithoutRequiringArguments(int requiredParameter)
{
}
[Test]
public void TestMethodIsNotRunnableWhenSourceDoesNotExist()
{
TestSuite suiteToTest = TestBuilder.MakeParameterizedMethodSuite(typeof(TestCaseSourceAttributeFixture), "MethodWithNonExistingSource");
Assert.That(suiteToTest.Tests.Count == 1);
Assert.AreEqual(RunState.NotRunnable, suiteToTest.Tests[0].RunState);
}
static object[] testCases =
{
new TestCaseData(
new string[] { "A" },
new string[] { "B" })
};
[Test, TestCaseSource("testCases")]
public void MethodTakingTwoStringArrays(string[] a, string[] b)
{
Assert.That(a, Is.TypeOf(typeof(string[])));
Assert.That(b, Is.TypeOf(typeof(string[])));
}
[TestCaseSource("SingleMemberArrayAsArgument")]
public void Issue1337SingleMemberArrayAsArgument(string[] args)
{
Assert.That(args.Length == 1 && args[0] == "1");
}
static string[][] SingleMemberArrayAsArgument = { new[] { "1" } };
#region Sources used by the tests
static object[] MyData = new object[] {
new object[] { 12, 3, 4 },
new object[] { 12, 4, 3 },
new object[] { 12, 6, 2 } };
static object[] MyIntData = new object[] {
new int[] { 12, 3, 4 },
new int[] { 12, 4, 3 },
new int[] { 12, 6, 2 } };
static object[] MyArrayData = new object[]
{
new int[] { 12 },
new int[] { 12, 4 },
new int[] { 12, 6, 2 }
};
public static IEnumerable StaticMethodDataWithParameters(int inject1, int inject2, int inject3)
{
yield return new object[] { inject1, inject2, inject3 };
}
static object[] FourArgs = new object[] {
new TestCaseData( 12, 3, 4, 0 ),
new TestCaseData( 12, 4, 3, 0 ),
new TestCaseData( 12, 5, 2, 2 ) };
static int[] EvenNumbers = new int[] { 2, 4, 6, 8 };
static object[] MoreData = new object[] {
new object[] { 12, 1, 12 },
new object[] { 12, 2, 6 } };
static object[] Params = new object[] {
new TestCaseData(24, 3).Returns(8),
new TestCaseData(24, 2).Returns(12) };
private class DivideDataProvider
{
#pragma warning disable 0169 // x is never assigned
private static object[] myObject;
#pragma warning restore 0169
public static IEnumerable HereIsTheDataWithParameters(int inject1, int inject2, int inject3)
{
yield return new object[] { inject1, inject2, inject3 };
}
public static IEnumerable HereIsTheData
{
get
{
yield return new object[] { 100, 20, 5 };
yield return new object[] { 100, 4, 25 };
}
}
}
public class DivideDataProviderWithReturnValue
{
public static IEnumerable TestCases
{
get
{
return new object[] {
new TestCaseData(12, 3).Returns(4).SetName("TC1"),
new TestCaseData(12, 2).Returns(6).SetName("TC2"),
new TestCaseData(12, 4).Returns(3).SetName("TC3")
};
}
}
}
private static IEnumerable exception_source
{
get
{
yield return new TestCaseData("a", "a");
yield return new TestCaseData("b", "b");
throw new System.Exception("my message");
}
}
#endregion
}
public class TestSourceMayBeInherited
{
protected static IEnumerable<bool> InheritedStaticProperty
{
get { yield return true; }
}
}
}
| |
/* Generated SBE (Simple Binary Encoding) message codec */
using System;
using System.Text;
using System.Collections.Generic;
using Adaptive.Agrona;
namespace Adaptive.Cluster.Codecs {
public class TerminationAckDecoder
{
public const ushort BLOCK_LENGTH = 20;
public const ushort TEMPLATE_ID = 76;
public const ushort SCHEMA_ID = 111;
public const ushort SCHEMA_VERSION = 7;
private TerminationAckDecoder _parentMessage;
private IDirectBuffer _buffer;
protected int _offset;
protected int _limit;
protected int _actingBlockLength;
protected int _actingVersion;
public TerminationAckDecoder()
{
_parentMessage = this;
}
public ushort SbeBlockLength()
{
return BLOCK_LENGTH;
}
public ushort SbeTemplateId()
{
return TEMPLATE_ID;
}
public ushort SbeSchemaId()
{
return SCHEMA_ID;
}
public ushort SbeSchemaVersion()
{
return SCHEMA_VERSION;
}
public string SbeSemanticType()
{
return "";
}
public IDirectBuffer Buffer()
{
return _buffer;
}
public int Offset()
{
return _offset;
}
public TerminationAckDecoder Wrap(
IDirectBuffer buffer, int offset, int actingBlockLength, int actingVersion)
{
this._buffer = buffer;
this._offset = offset;
this._actingBlockLength = actingBlockLength;
this._actingVersion = actingVersion;
Limit(offset + actingBlockLength);
return this;
}
public int EncodedLength()
{
return _limit - _offset;
}
public int Limit()
{
return _limit;
}
public void Limit(int limit)
{
this._limit = limit;
}
public static int LeadershipTermIdId()
{
return 1;
}
public static int LeadershipTermIdSinceVersion()
{
return 0;
}
public static int LeadershipTermIdEncodingOffset()
{
return 0;
}
public static int LeadershipTermIdEncodingLength()
{
return 8;
}
public static string LeadershipTermIdMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static long LeadershipTermIdNullValue()
{
return -9223372036854775808L;
}
public static long LeadershipTermIdMinValue()
{
return -9223372036854775807L;
}
public static long LeadershipTermIdMaxValue()
{
return 9223372036854775807L;
}
public long LeadershipTermId()
{
return _buffer.GetLong(_offset + 0, ByteOrder.LittleEndian);
}
public static int LogPositionId()
{
return 2;
}
public static int LogPositionSinceVersion()
{
return 0;
}
public static int LogPositionEncodingOffset()
{
return 8;
}
public static int LogPositionEncodingLength()
{
return 8;
}
public static string LogPositionMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static long LogPositionNullValue()
{
return -9223372036854775808L;
}
public static long LogPositionMinValue()
{
return -9223372036854775807L;
}
public static long LogPositionMaxValue()
{
return 9223372036854775807L;
}
public long LogPosition()
{
return _buffer.GetLong(_offset + 8, ByteOrder.LittleEndian);
}
public static int MemberIdId()
{
return 3;
}
public static int MemberIdSinceVersion()
{
return 0;
}
public static int MemberIdEncodingOffset()
{
return 16;
}
public static int MemberIdEncodingLength()
{
return 4;
}
public static string MemberIdMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static int MemberIdNullValue()
{
return -2147483648;
}
public static int MemberIdMinValue()
{
return -2147483647;
}
public static int MemberIdMaxValue()
{
return 2147483647;
}
public int MemberId()
{
return _buffer.GetInt(_offset + 16, ByteOrder.LittleEndian);
}
public override string ToString()
{
return AppendTo(new StringBuilder(100)).ToString();
}
public StringBuilder AppendTo(StringBuilder builder)
{
int originalLimit = Limit();
Limit(_offset + _actingBlockLength);
builder.Append("[TerminationAck](sbeTemplateId=");
builder.Append(TEMPLATE_ID);
builder.Append("|sbeSchemaId=");
builder.Append(SCHEMA_ID);
builder.Append("|sbeSchemaVersion=");
if (_parentMessage._actingVersion != SCHEMA_VERSION)
{
builder.Append(_parentMessage._actingVersion);
builder.Append('/');
}
builder.Append(SCHEMA_VERSION);
builder.Append("|sbeBlockLength=");
if (_actingBlockLength != BLOCK_LENGTH)
{
builder.Append(_actingBlockLength);
builder.Append('/');
}
builder.Append(BLOCK_LENGTH);
builder.Append("):");
//Token{signal=BEGIN_FIELD, name='leadershipTermId', referencedName='null', description='null', id=1, version=0, deprecated=0, encodedLength=0, offset=0, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=0, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("LeadershipTermId=");
builder.Append(LeadershipTermId());
builder.Append('|');
//Token{signal=BEGIN_FIELD, name='logPosition', referencedName='null', description='null', id=2, version=0, deprecated=0, encodedLength=0, offset=8, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=8, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("LogPosition=");
builder.Append(LogPosition());
builder.Append('|');
//Token{signal=BEGIN_FIELD, name='memberId', referencedName='null', description='null', id=3, version=0, deprecated=0, encodedLength=0, offset=16, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='int32', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=4, offset=16, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT32, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("MemberId=");
builder.Append(MemberId());
Limit(originalLimit);
return builder;
}
}
}
| |
#region Apache License
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to you under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
// .NET Compact Framework 1.0 has no support for System.Runtime.Remoting
#if !NETCF
using System;
using System.Collections;
using System.Threading;
using System.Runtime.Remoting.Messaging;
using log4net.Layout;
using log4net.Core;
using log4net.Util;
namespace log4net.Appender
{
/// <summary>
/// Delivers logging events to a remote logging sink.
/// </summary>
/// <remarks>
/// <para>
/// This Appender is designed to deliver events to a remote sink.
/// That is any object that implements the <see cref="IRemoteLoggingSink"/>
/// interface. It delivers the events using .NET remoting. The
/// object to deliver events to is specified by setting the
/// appenders <see cref="RemotingAppender.Sink"/> property.</para>
/// <para>
/// The RemotingAppender buffers events before sending them. This allows it to
/// make more efficient use of the remoting infrastructure.</para>
/// <para>
/// Once the buffer is full the events are still not sent immediately.
/// They are scheduled to be sent using a pool thread. The effect is that
/// the send occurs asynchronously. This is very important for a
/// number of non obvious reasons. The remoting infrastructure will
/// flow thread local variables (stored in the <see cref="CallContext"/>),
/// if they are marked as <see cref="ILogicalThreadAffinative"/>, across the
/// remoting boundary. If the server is not contactable then
/// the remoting infrastructure will clear the <see cref="ILogicalThreadAffinative"/>
/// objects from the <see cref="CallContext"/>. To prevent a logging failure from
/// having side effects on the calling application the remoting call must be made
/// from a separate thread to the one used by the application. A <see cref="ThreadPool"/>
/// thread is used for this. If no <see cref="ThreadPool"/> thread is available then
/// the events will block in the thread pool manager until a thread is available.</para>
/// <para>
/// Because the events are sent asynchronously using pool threads it is possible to close
/// this appender before all the queued events have been sent.
/// When closing the appender attempts to wait until all the queued events have been sent, but
/// this will timeout after 30 seconds regardless.</para>
/// <para>
/// If this appender is being closed because the <see cref="AppDomain.ProcessExit"/>
/// event has fired it may not be possible to send all the queued events. During process
/// exit the runtime limits the time that a <see cref="AppDomain.ProcessExit"/>
/// event handler is allowed to run for. If the runtime terminates the threads before
/// the queued events have been sent then they will be lost. To ensure that all events
/// are sent the appender must be closed before the application exits. See
/// <see cref="log4net.Core.LoggerManager.Shutdown"/> for details on how to shutdown
/// log4net programmatically.</para>
/// </remarks>
/// <seealso cref="IRemoteLoggingSink" />
/// <author>Nicko Cadell</author>
/// <author>Gert Driesen</author>
/// <author>Daniel Cazzulino</author>
public class RemotingAppender : BufferingAppenderSkeleton
{
#region Public Instance Constructors
/// <summary>
/// Initializes a new instance of the <see cref="RemotingAppender" /> class.
/// </summary>
/// <remarks>
/// <para>
/// Default constructor.
/// </para>
/// </remarks>
public RemotingAppender()
{
}
#endregion Public Instance Constructors
#region Public Instance Properties
/// <summary>
/// Gets or sets the URL of the well-known object that will accept
/// the logging events.
/// </summary>
/// <value>
/// The well-known URL of the remote sink.
/// </value>
/// <remarks>
/// <para>
/// The URL of the remoting sink that will accept logging events.
/// The sink must implement the <see cref="IRemoteLoggingSink"/>
/// interface.
/// </para>
/// </remarks>
public string Sink
{
get { return m_sinkUrl; }
set { m_sinkUrl = value; }
}
#endregion Public Instance Properties
#region Implementation of IOptionHandler
/// <summary>
/// Initialize the appender based on the options set
/// </summary>
/// <remarks>
/// <para>
/// This is part of the <see cref="IOptionHandler"/> delayed object
/// activation scheme. The <see cref="ActivateOptions"/> method must
/// be called on this object after the configuration properties have
/// been set. Until <see cref="ActivateOptions"/> is called this
/// object is in an undefined state and must not be used.
/// </para>
/// <para>
/// If any of the configuration properties are modified then
/// <see cref="ActivateOptions"/> must be called again.
/// </para>
/// </remarks>
#if NET_4_0 || MONO_4_0
[System.Security.SecuritySafeCritical]
#endif
override public void ActivateOptions()
{
base.ActivateOptions();
IDictionary channelProperties = new Hashtable();
channelProperties["typeFilterLevel"] = "Full";
m_sinkObj = (IRemoteLoggingSink)Activator.GetObject(typeof(IRemoteLoggingSink), m_sinkUrl, channelProperties);
}
#endregion
#region Override implementation of BufferingAppenderSkeleton
/// <summary>
/// Send the contents of the buffer to the remote sink.
/// </summary>
/// <remarks>
/// The events are not sent immediately. They are scheduled to be sent
/// using a pool thread. The effect is that the send occurs asynchronously.
/// This is very important for a number of non obvious reasons. The remoting
/// infrastructure will flow thread local variables (stored in the <see cref="CallContext"/>),
/// if they are marked as <see cref="ILogicalThreadAffinative"/>, across the
/// remoting boundary. If the server is not contactable then
/// the remoting infrastructure will clear the <see cref="ILogicalThreadAffinative"/>
/// objects from the <see cref="CallContext"/>. To prevent a logging failure from
/// having side effects on the calling application the remoting call must be made
/// from a separate thread to the one used by the application. A <see cref="ThreadPool"/>
/// thread is used for this. If no <see cref="ThreadPool"/> thread is available then
/// the events will block in the thread pool manager until a thread is available.
/// </remarks>
/// <param name="events">The events to send.</param>
override protected void SendBuffer(LoggingEvent[] events)
{
// Setup for an async send
BeginAsyncSend();
// Send the events
if (!ThreadPool.QueueUserWorkItem(new WaitCallback(SendBufferCallback), events))
{
// Cancel the async send
EndAsyncSend();
ErrorHandler.Error("RemotingAppender ["+Name+"] failed to ThreadPool.QueueUserWorkItem logging events in SendBuffer.");
}
}
/// <summary>
/// Override base class close.
/// </summary>
/// <remarks>
/// <para>
/// This method waits while there are queued work items. The events are
/// sent asynchronously using <see cref="ThreadPool"/> work items. These items
/// will be sent once a thread pool thread is available to send them, therefore
/// it is possible to close the appender before all the queued events have been
/// sent.</para>
/// <para>
/// This method attempts to wait until all the queued events have been sent, but this
/// method will timeout after 30 seconds regardless.</para>
/// <para>
/// If the appender is being closed because the <see cref="AppDomain.ProcessExit"/>
/// event has fired it may not be possible to send all the queued events. During process
/// exit the runtime limits the time that a <see cref="AppDomain.ProcessExit"/>
/// event handler is allowed to run for.</para>
/// </remarks>
override protected void OnClose()
{
base.OnClose();
// Wait for the work queue to become empty before closing, timeout 30 seconds
if (!m_workQueueEmptyEvent.WaitOne(30 * 1000, false))
{
ErrorHandler.Error("RemotingAppender ["+Name+"] failed to send all queued events before close, in OnClose.");
}
}
/// <summary>
/// Flushes any buffered log data.
/// </summary>
/// <param name="millisecondsTimeout">The maximum time to wait for logging events to be flushed.</param>
/// <returns><c>True</c> if all logging events were flushed successfully, else <c>false</c>.</returns>
public override bool Flush(int millisecondsTimeout)
{
base.Flush();
return m_workQueueEmptyEvent.WaitOne(millisecondsTimeout, false);
}
#endregion
/// <summary>
/// A work item is being queued into the thread pool
/// </summary>
private void BeginAsyncSend()
{
// The work queue is not empty
m_workQueueEmptyEvent.Reset();
// Increment the queued count
Interlocked.Increment(ref m_queuedCallbackCount);
}
/// <summary>
/// A work item from the thread pool has completed
/// </summary>
private void EndAsyncSend()
{
// Decrement the queued count
if (Interlocked.Decrement(ref m_queuedCallbackCount) <= 0)
{
// If the work queue is empty then set the event
m_workQueueEmptyEvent.Set();
}
}
/// <summary>
/// Send the contents of the buffer to the remote sink.
/// </summary>
/// <remarks>
/// This method is designed to be used with the <see cref="ThreadPool"/>.
/// This method expects to be passed an array of <see cref="LoggingEvent"/>
/// objects in the state param.
/// </remarks>
/// <param name="state">the logging events to send</param>
private void SendBufferCallback(object state)
{
try
{
LoggingEvent[] events = (LoggingEvent[])state;
// Send the events
m_sinkObj.LogEvents(events);
}
catch(Exception ex)
{
ErrorHandler.Error("Failed in SendBufferCallback", ex);
}
finally
{
EndAsyncSend();
}
}
#region Private Instance Fields
/// <summary>
/// The URL of the remote sink.
/// </summary>
private string m_sinkUrl;
/// <summary>
/// The local proxy (.NET remoting) for the remote logging sink.
/// </summary>
private IRemoteLoggingSink m_sinkObj;
/// <summary>
/// The number of queued callbacks currently waiting or executing
/// </summary>
private int m_queuedCallbackCount = 0;
/// <summary>
/// Event used to signal when there are no queued work items
/// </summary>
/// <remarks>
/// This event is set when there are no queued work items. In this
/// state it is safe to close the appender.
/// </remarks>
private ManualResetEvent m_workQueueEmptyEvent = new ManualResetEvent(true);
#endregion Private Instance Fields
/// <summary>
/// Interface used to deliver <see cref="LoggingEvent"/> objects to a remote sink.
/// </summary>
/// <remarks>
/// This interface must be implemented by a remoting sink
/// if the <see cref="RemotingAppender"/> is to be used
/// to deliver logging events to the sink.
/// </remarks>
public interface IRemoteLoggingSink
{
/// <summary>
/// Delivers logging events to the remote sink
/// </summary>
/// <param name="events">Array of events to log.</param>
/// <remarks>
/// <para>
/// Delivers logging events to the remote sink
/// </para>
/// </remarks>
void LogEvents(LoggingEvent[] events);
}
}
}
#endif // !NETCF
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Win32.SafeHandles;
using System.Security;
namespace System.IO.MemoryMappedFiles
{
public partial class MemoryMappedFile
{
/// <summary>
/// Used by the 2 Create factory method groups. A null fileHandle specifies that the
/// memory mapped file should not be associated with an existing file on disk (i.e. start
/// out empty).
/// </summary>
[SecurityCritical]
private static unsafe SafeMemoryMappedFileHandle CreateCore(
FileStream fileStream, string mapName,
HandleInheritability inheritability, MemoryMappedFileAccess access,
MemoryMappedFileOptions options, long capacity)
{
if (mapName != null)
{
// Named maps are not supported in our Unix implementation. We could support named maps on Linux using
// shared memory segments (shmget/shmat/shmdt/shmctl/etc.), but that doesn't work on OSX by default due
// to very low default limits on OSX for the size of such objects; it also doesn't support behaviors
// like copy-on-write or the ability to control handle inheritability, and reliably cleaning them up
// relies on some non-conforming behaviors around shared memory IDs remaining valid even after they've
// been marked for deletion (IPC_RMID). We could also support named maps using the current implementation
// by not unlinking after creating the backing store, but then the backing stores would remain around
// and accessible even after process exit, with no good way to appropriately clean them up.
// (File-backed maps may still be used for cross-process communication.)
throw CreateNamedMapsNotSupportedException();
}
bool ownsFileStream = false;
if (fileStream != null)
{
// This map is backed by a file. Make sure the file's size is increased to be
// at least as big as the requested capacity of the map.
if (fileStream.Length < capacity)
{
try
{
fileStream.SetLength(capacity);
}
catch (ArgumentException exc)
{
// If the capacity is too large, we'll get an ArgumentException from SetLength,
// but on Windows this same condition is represented by an IOException.
throw new IOException(exc.Message, exc);
}
}
}
else
{
// This map is backed by memory-only. With files, multiple views over the same map
// will end up being able to share data through the same file-based backing store;
// for anonymous maps, we need a similar backing store, or else multiple views would logically
// each be their own map and wouldn't share any data. To achieve this, we create a backing object
// (either memory or on disk, depending on the system) and use its file descriptor as the file handle.
// However, we only do this when the permission is more than read-only. We can't change the size
// of an object that has read-only permissions, but we also don't need to worry about sharing
// views over a read-only, anonymous, memory-backed map, because the data will never change, so all views
// will always see zero and can't change that. In that case, we just use the built-in anonymous support of
// the map by leaving fileStream as null.
Interop.Sys.MemoryMappedProtections protections = MemoryMappedView.GetProtections(access, forVerification: false);
if ((protections & Interop.Sys.MemoryMappedProtections.PROT_WRITE) != 0 && capacity > 0)
{
ownsFileStream = true;
fileStream = CreateSharedBackingObject(protections, capacity);
// If the MMF handle should not be inherited, mark the backing object fd as O_CLOEXEC.
if (inheritability == HandleInheritability.None)
{
Interop.CheckIo(Interop.Sys.Fcntl.SetCloseOnExec(fileStream.SafeFileHandle));
}
}
}
return new SafeMemoryMappedFileHandle(fileStream, ownsFileStream, inheritability, access, options, capacity);
}
/// <summary>
/// Used by the CreateOrOpen factory method groups.
/// </summary>
[SecurityCritical]
private static SafeMemoryMappedFileHandle CreateOrOpenCore(
string mapName,
HandleInheritability inheritability, MemoryMappedFileAccess access,
MemoryMappedFileOptions options, long capacity)
{
// Since we don't support mapName != null, CreateOrOpenCore can't
// be used to Open an existing map, and thus is identical to CreateCore.
return CreateCore(null, mapName, inheritability, access, options, capacity);
}
/// <summary>
/// Used by the OpenExisting factory method group and by CreateOrOpen if access is write.
/// We'll throw an ArgumentException if the file mapping object didn't exist and the
/// caller used CreateOrOpen since Create isn't valid with Write access
/// </summary>
[SecurityCritical]
private static SafeMemoryMappedFileHandle OpenCore(
string mapName, HandleInheritability inheritability, MemoryMappedFileAccess access, bool createOrOpen)
{
throw CreateNamedMapsNotSupportedException();
}
/// <summary>
/// Used by the OpenExisting factory method group and by CreateOrOpen if access is write.
/// We'll throw an ArgumentException if the file mapping object didn't exist and the
/// caller used CreateOrOpen since Create isn't valid with Write access
/// </summary>
[SecurityCritical]
private static SafeMemoryMappedFileHandle OpenCore(
string mapName, HandleInheritability inheritability, MemoryMappedFileRights rights, bool createOrOpen)
{
throw CreateNamedMapsNotSupportedException();
}
// -----------------------------
// ---- PAL layer ends here ----
// -----------------------------
/// <summary>Gets an exception indicating that named maps are not supported on this platform.</summary>
private static Exception CreateNamedMapsNotSupportedException()
{
return new PlatformNotSupportedException(SR.PlatformNotSupported_NamedMaps);
}
private static FileAccess TranslateProtectionsToFileAccess(Interop.Sys.MemoryMappedProtections protections)
{
return
(protections & (Interop.Sys.MemoryMappedProtections.PROT_READ | Interop.Sys.MemoryMappedProtections.PROT_WRITE)) != 0 ? FileAccess.ReadWrite :
(protections & (Interop.Sys.MemoryMappedProtections.PROT_WRITE)) != 0 ? FileAccess.Write :
FileAccess.Read;
}
private static FileStream CreateSharedBackingObject(Interop.Sys.MemoryMappedProtections protections, long capacity)
{
return CreateSharedBackingObjectUsingMemory(protections, capacity)
?? CreateSharedBackingObjectUsingFile(protections, capacity);
}
// -----------------------------
// ---- PAL layer ends here ----
// -----------------------------
private static FileStream CreateSharedBackingObjectUsingMemory(
Interop.Sys.MemoryMappedProtections protections, long capacity)
{
// The POSIX shared memory object name must begin with '/'. After that we just want something short and unique.
string mapName = "/corefx_map_" + Guid.NewGuid().ToString("N");
// Determine the flags to use when creating the shared memory object
Interop.Sys.OpenFlags flags = (protections & Interop.Sys.MemoryMappedProtections.PROT_WRITE) != 0 ?
Interop.Sys.OpenFlags.O_RDWR :
Interop.Sys.OpenFlags.O_RDONLY;
flags |= Interop.Sys.OpenFlags.O_CREAT | Interop.Sys.OpenFlags.O_EXCL; // CreateNew
// Determine the permissions with which to create the file
Interop.Sys.Permissions perms = default(Interop.Sys.Permissions);
if ((protections & Interop.Sys.MemoryMappedProtections.PROT_READ) != 0)
perms |= Interop.Sys.Permissions.S_IRUSR;
if ((protections & Interop.Sys.MemoryMappedProtections.PROT_WRITE) != 0)
perms |= Interop.Sys.Permissions.S_IWUSR;
if ((protections & Interop.Sys.MemoryMappedProtections.PROT_EXEC) != 0)
perms |= Interop.Sys.Permissions.S_IXUSR;
// Create the shared memory object.
SafeFileHandle fd = Interop.Sys.ShmOpen(mapName, flags, (int)perms);
if (fd.IsInvalid)
{
Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();
if (errorInfo.Error == Interop.Error.ENOTSUP)
{
// If ShmOpen is not supported, fall back to file backing object.
// Note that the System.Native shim will force this failure on platforms where
// the result of native shm_open does not work well with our subsequent call
// to mmap.
return null;
}
throw Interop.GetExceptionForIoErrno(errorInfo);
}
try
{
// Unlink the shared memory object immediately so that it'll go away once all handles
// to it are closed (as with opened then unlinked files, it'll remain usable via
// the open handles even though it's unlinked and can't be opened anew via its name).
Interop.CheckIo(Interop.Sys.ShmUnlink(mapName));
// Give it the right capacity. We do this directly with ftruncate rather
// than via FileStream.SetLength after the FileStream is created because, on some systems,
// lseek fails on shared memory objects, causing the FileStream to think it's unseekable,
// causing it to preemptively throw from SetLength.
Interop.CheckIo(Interop.Sys.FTruncate(fd, capacity));
// Wrap the file descriptor in a stream and return it.
return new FileStream(fd, TranslateProtectionsToFileAccess(protections));
}
catch
{
fd.Dispose();
throw;
}
}
private static FileStream CreateSharedBackingObjectUsingFile(Interop.Sys.MemoryMappedProtections protections, long capacity)
{
// We create a temporary backing file in TMPDIR. We don't bother putting it into subdirectories as the file exists
// extremely briefly: it's opened/created and then immediately unlinked.
string path = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N"));
FileAccess access =
(protections & (Interop.Sys.MemoryMappedProtections.PROT_READ | Interop.Sys.MemoryMappedProtections.PROT_WRITE)) != 0 ? FileAccess.ReadWrite :
(protections & (Interop.Sys.MemoryMappedProtections.PROT_WRITE)) != 0 ? FileAccess.Write :
FileAccess.Read;
// Create the backing file, then immediately unlink it so that it'll be cleaned up when no longer in use.
// Then enlarge it to the requested capacity.
const int DefaultBufferSize = 0x1000;
var fs = new FileStream(path, FileMode.CreateNew, TranslateProtectionsToFileAccess(protections), FileShare.ReadWrite, DefaultBufferSize);
try
{
Interop.CheckIo(Interop.Sys.Unlink(path));
fs.SetLength(capacity);
}
catch
{
fs.Dispose();
throw;
}
return fs;
}
}
}
| |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache Lic se, Version 2.0. A
* copy of the license can be found in the License.txt file at the root of this distribution.
*
* You must not remove this notice, or any other, from this software.
*
* ***************************************************************************/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using MSBuild = Microsoft.Build.Evaluation;
using MSBuildExecution = Microsoft.Build.Execution;
namespace Microsoft.VisualStudio.Project
{
/// <summary>
/// Allows projects to group outputs according to usage.
/// </summary>
[CLSCompliant(false), ComVisible(true)]
public class OutputGroup : IVsOutputGroup2
{
#region fields
private readonly ProjectConfig _projectCfg;
private readonly ProjectNode _project;
private readonly List<Output> _outputs = new List<Output>();
private readonly string _name;
private readonly string _targetName;
private Output _keyOutput;
#endregion
/// <summary>
/// Constructor for IVSOutputGroup2 implementation
/// </summary>
/// <param name="outputName">Name of the output group. See VS_OUTPUTGROUP_CNAME_Build in vsshell.idl for the list of standard values</param>
/// <param name="msBuildTargetName">MSBuild target name</param>
/// <param name="projectManager">Project that produce this output</param>
/// <param name="configuration">Configuration that produce this output</param>
protected internal OutputGroup(string outputName, string msBuildTargetName, ProjectNode projectManager, ProjectConfig configuration)
{
Utilities.ArgumentNotNull("outputName", outputName);
Utilities.ArgumentNotNull("msBuildTargetName", msBuildTargetName);
Utilities.ArgumentNotNull("projectManager", projectManager);
Utilities.ArgumentNotNull("configuration", configuration);
_name = outputName;
_targetName = msBuildTargetName;
_project = projectManager;
_projectCfg = configuration;
}
#region properties
/// <summary>
/// Get the project configuration object associated with this output group
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Cfg")]
protected ProjectConfig ProjectCfg
{
get { return _projectCfg; }
}
/// <summary>
/// Get the project object that produces this output group.
/// </summary>
protected internal ProjectNode Project
{
get { return _project; }
}
/// <summary>
/// Gets the msbuild target name which is assciated to the outputgroup.
/// ProjectNode defines a static collection of output group names and their associated MsBuild target
/// </summary>
protected internal string TargetName
{
get { return _targetName; }
}
/// <summary>
/// Easy access to the canonical name of the group.
/// </summary>
protected internal string Name
{
get {
string canonicalName;
ThreadHelper.ThrowIfNotOnUIThread();
ErrorHandler.ThrowOnFailure(get_CanonicalName(out canonicalName));
return canonicalName;
}
}
#endregion
#region virtual methods
protected virtual void Refresh()
{
// Let MSBuild know which configuration we are working with
ThreadHelper.ThrowIfNotOnUIThread();
_project.SetConfiguration(_projectCfg.ConfigCanonicalName);
// Generate dependencies if such a task exist
if (_project.ProjectInstance.Targets.ContainsKey(ProjectFileConstants.AllProjectOutputGroups))
{
bool succeeded = false;
_project.BuildTarget(ProjectFileConstants.AllProjectOutputGroups, out succeeded);
// The next line triggers an exception for a customer that works with JetBrains.
//Debug.Assert(succeeded, "Failed to build target: " + ProjectFileConstants.AllProjectOutputGroups);
}
// Rebuild the content of our list of output
string outputType = _targetName + "Output";
this._outputs.Clear();
foreach (MSBuildExecution.ProjectItemInstance assembly in MSBuildProjectInstance.GetItems(_project.ProjectInstance, outputType))
{
Output output = new Output(_project, assembly);
this._outputs.Add(output);
// See if it is our key output
if (String.Compare(MSBuildItem.GetMetadataValue(assembly, "IsKeyOutput"), true.ToString(), StringComparison.OrdinalIgnoreCase) == 0)
_keyOutput = output;
}
_project.SetCurrentConfiguration();
// Now that the group is built we have to check if it is invalidated by a property
// change on the project.
_project.OnProjectPropertyChanged += new EventHandler<ProjectPropertyChangedArgs>(OnProjectPropertyChanged);
}
public virtual void InvalidateGroup()
{
// Set keyOutput to null so that a refresh will be performed the next time
// a property getter is called.
if (null != _keyOutput)
{
// Once the group is invalidated there is no more reason to listen for events.
_project.OnProjectPropertyChanged -= new EventHandler<ProjectPropertyChangedArgs>(OnProjectPropertyChanged);
}
_keyOutput = null;
}
#endregion
#region event handlers
public void OnProjectPropertyChanged(object sender, ProjectPropertyChangedArgs args)
{
// In theory here we should decide if we have to invalidate the group according with the kind of property
// that is changed.
InvalidateGroup();
}
#endregion
#region IVsOutputGroup2 Members
public virtual int get_CanonicalName(out string pbstrCanonicalName)
{
pbstrCanonicalName = this._name;
return VSConstants.S_OK;
}
public virtual int get_DeployDependencies(uint celt, IVsDeployDependency[] rgpdpd, uint[] pcActual)
{
return VSConstants.E_NOTIMPL;
}
public virtual int get_Description(out string pbstrDescription)
{
pbstrDescription = null;
string description;
ThreadHelper.ThrowIfNotOnUIThread();
int hr = this.get_CanonicalName(out description);
if(ErrorHandler.Succeeded(hr))
pbstrDescription = this.Project.GetOutputGroupDescription(description);
return hr;
}
public virtual int get_DisplayName(out string pbstrDisplayName)
{
pbstrDisplayName = null;
string displayName;
ThreadHelper.ThrowIfNotOnUIThread();
int hr = this.get_CanonicalName(out displayName);
if(ErrorHandler.Succeeded(hr))
pbstrDisplayName = this.Project.GetOutputGroupDisplayName(displayName);
return hr;
}
public virtual int get_KeyOutput(out string pbstrCanonicalName)
{
pbstrCanonicalName = null;
if(_keyOutput == null)
Refresh();
if(_keyOutput == null)
{
pbstrCanonicalName = String.Empty;
return VSConstants.S_FALSE;
}
ThreadHelper.ThrowIfNotOnUIThread();
return _keyOutput.get_CanonicalName(out pbstrCanonicalName);
}
public virtual int get_KeyOutputObject(out IVsOutput2 ppKeyOutput)
{
ThreadHelper.ThrowIfNotOnUIThread();
if (_keyOutput == null)
{
Refresh();
if (_keyOutput == null)
{
// horrible hack: we don't really have outputs but the WPF designer insists
// that we have an output so it can figure out our output assembly name. So we
// lie here, and then lie again to give a path in Output.get_Property
_keyOutput = new Output(_project, null);
}
}
ppKeyOutput = _keyOutput;
if(ppKeyOutput == null)
return VSConstants.S_FALSE;
return VSConstants.S_OK;
}
public virtual int get_Outputs(uint celt, IVsOutput2[] rgpcfg, uint[] pcActual)
{
// Ensure that we are refreshed. This is somewhat of a hack that enables project to
// project reference scenarios to work. Normally, output groups are populated as part
// of build. However, in the project to project reference case, what ends up happening
// is that the referencing projects requests the referenced project's output group
// before a build is done on the referenced project.
//
// Furthermore, the project auto toolbox manager requires output groups to be populated
// on project reopen as well...
//
// In the end, this is probably the right thing to do, though -- as it keeps the output
// groups always up to date.
ThreadHelper.ThrowIfNotOnUIThread();
Refresh();
// See if only the caller only wants to know the count
if(celt == 0 || rgpcfg == null)
{
if(pcActual != null && pcActual.Length > 0)
pcActual[0] = (uint)_outputs.Count;
return VSConstants.S_OK;
}
// Fill the array with our outputs
uint count = 0;
foreach(Output output in _outputs)
{
if(rgpcfg.Length > count && celt > count && output != null)
{
rgpcfg[count] = output;
++count;
}
}
if(pcActual != null && pcActual.Length > 0)
pcActual[0] = count;
// If the number asked for does not match the number returned, return S_FALSE
return (count == celt) ? VSConstants.S_OK : VSConstants.S_FALSE;
}
public virtual int get_ProjectCfg(out IVsProjectCfg2 ppIVsProjectCfg2)
{
ThreadHelper.ThrowIfNotOnUIThread();
ppIVsProjectCfg2 = (IVsProjectCfg2)this._projectCfg;
return VSConstants.S_OK;
}
public virtual int get_Property(string pszProperty, out object pvar)
{
ThreadHelper.ThrowIfNotOnUIThread();
pvar = _project.GetProjectProperty(pszProperty);
return VSConstants.S_OK;
}
#endregion
protected internal List<Output> Outputs => _outputs;
protected internal Output KeyOutput
{
get
{
return _keyOutput;
}
set { _keyOutput = value; }
}
}
}
| |
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
namespace WeifenLuo.WinFormsUI.Docking
{
internal class VS2012LightAutoHideStrip : AutoHideStripBase
{
private class TabVS2012Light : Tab
{
internal TabVS2012Light(IDockContent content)
: base(content)
{
}
private int m_tabX = 0;
public int TabX
{
get { return m_tabX; }
set { m_tabX = value; }
}
private int m_tabWidth = 0;
public int TabWidth
{
get { return m_tabWidth; }
set { m_tabWidth = value; }
}
public bool IsMouseOver { get; set; }
}
private const int _ImageHeight = 16;
private const int _ImageWidth = 0;
private const int _ImageGapTop = 2;
private const int _ImageGapLeft = 4;
private const int _ImageGapRight = 2;
private const int _ImageGapBottom = 2;
private const int _TextGapLeft = 0;
private const int _TextGapRight = 0;
private const int _TabGapTop = 3;
private const int _TabGapBottom = 8;
private const int _TabGapLeft = 4;
private const int _TabGapBetween = 10;
#region Customizable Properties
public Font TextFont
{
get { return DockPanel.Skin.AutoHideStripSkin.TextFont; }
}
private static StringFormat _stringFormatTabHorizontal;
private StringFormat StringFormatTabHorizontal
{
get
{
if (_stringFormatTabHorizontal == null)
{
_stringFormatTabHorizontal = new StringFormat();
_stringFormatTabHorizontal.Alignment = StringAlignment.Near;
_stringFormatTabHorizontal.LineAlignment = StringAlignment.Center;
_stringFormatTabHorizontal.FormatFlags = StringFormatFlags.NoWrap;
_stringFormatTabHorizontal.Trimming = StringTrimming.None;
}
if (RightToLeft == RightToLeft.Yes)
_stringFormatTabHorizontal.FormatFlags |= StringFormatFlags.DirectionRightToLeft;
else
_stringFormatTabHorizontal.FormatFlags &= ~StringFormatFlags.DirectionRightToLeft;
return _stringFormatTabHorizontal;
}
}
private static StringFormat _stringFormatTabVertical;
private StringFormat StringFormatTabVertical
{
get
{
if (_stringFormatTabVertical == null)
{
_stringFormatTabVertical = new StringFormat();
_stringFormatTabVertical.Alignment = StringAlignment.Near;
_stringFormatTabVertical.LineAlignment = StringAlignment.Center;
_stringFormatTabVertical.FormatFlags = StringFormatFlags.NoWrap | StringFormatFlags.DirectionVertical;
_stringFormatTabVertical.Trimming = StringTrimming.None;
}
if (RightToLeft == RightToLeft.Yes)
_stringFormatTabVertical.FormatFlags |= StringFormatFlags.DirectionRightToLeft;
else
_stringFormatTabVertical.FormatFlags &= ~StringFormatFlags.DirectionRightToLeft;
return _stringFormatTabVertical;
}
}
private static int ImageHeight
{
get { return _ImageHeight; }
}
private static int ImageWidth
{
get { return _ImageWidth; }
}
private static int ImageGapTop
{
get { return _ImageGapTop; }
}
private static int ImageGapLeft
{
get { return _ImageGapLeft; }
}
private static int ImageGapRight
{
get { return _ImageGapRight; }
}
private static int ImageGapBottom
{
get { return _ImageGapBottom; }
}
private static int TextGapLeft
{
get { return _TextGapLeft; }
}
private static int TextGapRight
{
get { return _TextGapRight; }
}
private static int TabGapTop
{
get { return _TabGapTop; }
}
private static int TabGapBottom
{
get { return _TabGapBottom; }
}
private static int TabGapLeft
{
get { return _TabGapLeft; }
}
private static int TabGapBetween
{
get { return _TabGapBetween; }
}
private static Pen PenTabBorder
{
get { return SystemPens.GrayText; }
}
#endregion
private static Matrix _matrixIdentity = new Matrix();
private static Matrix MatrixIdentity
{
get { return _matrixIdentity; }
}
private static DockState[] _dockStates;
private static DockState[] DockStates
{
get
{
if (_dockStates == null)
{
_dockStates = new DockState[4];
_dockStates[0] = DockState.DockLeftAutoHide;
_dockStates[1] = DockState.DockRightAutoHide;
_dockStates[2] = DockState.DockTopAutoHide;
_dockStates[3] = DockState.DockBottomAutoHide;
}
return _dockStates;
}
}
private static GraphicsPath _graphicsPath;
internal static GraphicsPath GraphicsPath
{
get
{
if (_graphicsPath == null)
_graphicsPath = new GraphicsPath();
return _graphicsPath;
}
}
public VS2012LightAutoHideStrip(DockPanel panel)
: base(panel)
{
SetStyle(ControlStyles.ResizeRedraw |
ControlStyles.UserPaint |
ControlStyles.AllPaintingInWmPaint |
ControlStyles.OptimizedDoubleBuffer, true);
BackColor = SystemColors.ControlLight;
}
protected override void OnPaint(PaintEventArgs e)
{
Graphics g = e.Graphics;
g.FillRectangle(SystemBrushes.Control, ClientRectangle);
DrawTabStrip(g);
}
protected override void OnLayout(LayoutEventArgs levent)
{
CalculateTabs();
base.OnLayout(levent);
}
private void DrawTabStrip(Graphics g)
{
DrawTabStrip(g, DockState.DockTopAutoHide);
DrawTabStrip(g, DockState.DockBottomAutoHide);
DrawTabStrip(g, DockState.DockLeftAutoHide);
DrawTabStrip(g, DockState.DockRightAutoHide);
}
private void DrawTabStrip(Graphics g, DockState dockState)
{
Rectangle rectTabStrip = GetLogicalTabStripRectangle(dockState);
if (rectTabStrip.IsEmpty)
return;
Matrix matrixIdentity = g.Transform;
if (dockState == DockState.DockLeftAutoHide || dockState == DockState.DockRightAutoHide)
{
Matrix matrixRotated = new Matrix();
matrixRotated.RotateAt(90, new PointF((float)rectTabStrip.X + (float)rectTabStrip.Height / 2,
(float)rectTabStrip.Y + (float)rectTabStrip.Height / 2));
g.Transform = matrixRotated;
}
foreach (Pane pane in GetPanes(dockState))
{
foreach (TabVS2012Light tab in pane.AutoHideTabs)
DrawTab(g, tab);
}
g.Transform = matrixIdentity;
}
private void CalculateTabs()
{
CalculateTabs(DockState.DockTopAutoHide);
CalculateTabs(DockState.DockBottomAutoHide);
CalculateTabs(DockState.DockLeftAutoHide);
CalculateTabs(DockState.DockRightAutoHide);
}
private void CalculateTabs(DockState dockState)
{
Rectangle rectTabStrip = GetLogicalTabStripRectangle(dockState);
int imageHeight = rectTabStrip.Height - ImageGapTop - ImageGapBottom;
int imageWidth = ImageWidth;
if (imageHeight > ImageHeight)
imageWidth = ImageWidth * (imageHeight / ImageHeight);
int x = TabGapLeft + rectTabStrip.X;
foreach (Pane pane in GetPanes(dockState))
{
foreach (TabVS2012Light tab in pane.AutoHideTabs)
{
int width = imageWidth + ImageGapLeft + ImageGapRight +
TextRenderer.MeasureText(tab.Content.DockHandler.TabText, TextFont).Width +
TextGapLeft + TextGapRight;
tab.TabX = x;
tab.TabWidth = width;
x += width;
}
x += TabGapBetween;
}
}
private Rectangle RtlTransform(Rectangle rect, DockState dockState)
{
Rectangle rectTransformed;
if (dockState == DockState.DockLeftAutoHide || dockState == DockState.DockRightAutoHide)
rectTransformed = rect;
else
rectTransformed = DrawHelper.RtlTransform(this, rect);
return rectTransformed;
}
private GraphicsPath GetTabOutline(TabVS2012Light tab, bool transformed, bool rtlTransform)
{
DockState dockState = tab.Content.DockHandler.DockState;
Rectangle rectTab = GetTabRectangle(tab, transformed);
if (rtlTransform)
rectTab = RtlTransform(rectTab, dockState);
if (GraphicsPath != null)
{
GraphicsPath.Reset();
GraphicsPath.AddRectangle(rectTab);
}
return GraphicsPath;
}
private void DrawTab(Graphics g, TabVS2012Light tab)
{
Rectangle rectTabOrigin = GetTabRectangle(tab);
if (rectTabOrigin.IsEmpty)
return;
DockState dockState = tab.Content.DockHandler.DockState;
IDockContent content = tab.Content;
Color textColor;
if (tab.Content.DockHandler.IsActivated || tab.IsMouseOver)
textColor = DockPanel.Skin.AutoHideStripSkin.DockStripGradient.StartColor;
else
textColor = DockPanel.Skin.AutoHideStripSkin.DockStripGradient.EndColor;
Rectangle rectThickLine = rectTabOrigin;
rectThickLine.X += _TabGapLeft + _TextGapLeft + _ImageGapLeft + _ImageWidth;
rectThickLine.Width = TextRenderer.MeasureText(tab.Content.DockHandler.TabText, TextFont).Width - 8;
rectThickLine.Height = Measures.AutoHideTabLineWidth;
if (dockState == DockState.DockBottomAutoHide || dockState == DockState.DockLeftAutoHide)
rectThickLine.Y += rectTabOrigin.Height - Measures.AutoHideTabLineWidth;
else
if (dockState == DockState.DockTopAutoHide || dockState == DockState.DockRightAutoHide)
rectThickLine.Y += 0;
g.FillRectangle(new SolidBrush(textColor), rectThickLine);
//Set no rotate for drawing icon and text
Matrix matrixRotate = g.Transform;
g.Transform = MatrixIdentity;
// High-DPI display of auto-hide icons is not implemented!
//// Draw the icon
//Rectangle rectImage = rectTabOrigin;
//rectImage.X += ImageGapLeft;
//rectImage.Y += ImageGapTop;
//int imageHeight = rectTabOrigin.Height - ImageGapTop - ImageGapBottom;
//int imageWidth = ImageWidth;
//if (imageHeight > ImageHeight)
// imageWidth = ImageWidth * (imageHeight / ImageHeight);
//rectImage.Height = imageHeight;
//rectImage.Width = imageWidth;
//rectImage = GetTransformedRectangle(dockState, rectImage);
//
//if (dockState == DockState.DockLeftAutoHide || dockState == DockState.DockRightAutoHide)
//{
// // The DockState is DockLeftAutoHide or DockRightAutoHide, so rotate the image 90 degrees to the right.
// Rectangle rectTransform = RtlTransform(rectImage, dockState);
// Point[] rotationPoints =
// {
// new Point(rectTransform.X + rectTransform.Width, rectTransform.Y),
// new Point(rectTransform.X + rectTransform.Width, rectTransform.Y + rectTransform.Height),
// new Point(rectTransform.X, rectTransform.Y)
// };
//
// using (Icon rotatedIcon = new Icon(((Form)content).Icon, 16, 16)) {
// g.DrawImage(rotatedIcon.ToBitmap(), rotationPoints);
// }
//}
//else
//{
// // Draw the icon normally without any rotation.
// g.DrawIcon(((Form)content).Icon, RtlTransform(rectImage, dockState));
//}
// Draw the text
Rectangle rectText = rectTabOrigin;
rectText.X += ImageGapLeft + /*imageWidth +*/ ImageGapRight + TextGapLeft;
rectText.Width -= ImageGapLeft + /*imageWidth +*/ ImageGapRight + TextGapLeft;
rectText = RtlTransform(GetTransformedRectangle(dockState, rectText), dockState);
if (DockPanel.ActiveContent == content || tab.IsMouseOver)
textColor = DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.TextColor;
else
textColor = DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveTabGradient.TextColor;
if (dockState == DockState.DockLeftAutoHide || dockState == DockState.DockRightAutoHide)
g.DrawString(content.DockHandler.TabText, TextFont, new SolidBrush(textColor), rectText, StringFormatTabVertical);
else
g.DrawString(content.DockHandler.TabText, TextFont, new SolidBrush(textColor), rectText, StringFormatTabHorizontal);
// Set rotate back
g.Transform = matrixRotate;
}
private Rectangle GetLogicalTabStripRectangle(DockState dockState)
{
return GetLogicalTabStripRectangle(dockState, false);
}
private Rectangle GetLogicalTabStripRectangle(DockState dockState, bool transformed)
{
if (!DockHelper.IsDockStateAutoHide(dockState))
return Rectangle.Empty;
int leftPanes = GetPanes(DockState.DockLeftAutoHide).Count;
int rightPanes = GetPanes(DockState.DockRightAutoHide).Count;
int topPanes = GetPanes(DockState.DockTopAutoHide).Count;
int bottomPanes = GetPanes(DockState.DockBottomAutoHide).Count;
int x, y, width, height;
height = MeasureHeight();
if (dockState == DockState.DockLeftAutoHide && leftPanes > 0)
{
x = 0;
y = (topPanes == 0) ? 0 : height;
width = Height - (topPanes == 0 ? 0 : height) - (bottomPanes == 0 ? 0 : height);
}
else if (dockState == DockState.DockRightAutoHide && rightPanes > 0)
{
x = Width - height;
if (leftPanes != 0 && x < height)
x = height;
y = (topPanes == 0) ? 0 : height;
width = Height - (topPanes == 0 ? 0 : height) - (bottomPanes == 0 ? 0 : height);
}
else if (dockState == DockState.DockTopAutoHide && topPanes > 0)
{
x = leftPanes == 0 ? 0 : height;
y = 0;
width = Width - (leftPanes == 0 ? 0 : height) - (rightPanes == 0 ? 0 : height);
}
else if (dockState == DockState.DockBottomAutoHide && bottomPanes > 0)
{
x = leftPanes == 0 ? 0 : height;
y = Height - height;
if (topPanes != 0 && y < height)
y = height;
width = Width - (leftPanes == 0 ? 0 : height) - (rightPanes == 0 ? 0 : height);
}
else
return Rectangle.Empty;
if (width == 0 || height == 0)
{
return Rectangle.Empty;
}
var rect = new Rectangle(x, y, width, height);
return transformed ? GetTransformedRectangle(dockState, rect) : rect;
}
private Rectangle GetTabRectangle(TabVS2012Light tab)
{
return GetTabRectangle(tab, false);
}
private Rectangle GetTabRectangle(TabVS2012Light tab, bool transformed)
{
DockState dockState = tab.Content.DockHandler.DockState;
Rectangle rectTabStrip = GetLogicalTabStripRectangle(dockState);
if (rectTabStrip.IsEmpty)
return Rectangle.Empty;
int x = tab.TabX;
int y = rectTabStrip.Y +
(dockState == DockState.DockTopAutoHide || dockState == DockState.DockRightAutoHide ?
0 : TabGapTop);
int width = tab.TabWidth;
int height = rectTabStrip.Height - TabGapTop;
if (!transformed)
return new Rectangle(x, y, width, height);
else
return GetTransformedRectangle(dockState, new Rectangle(x, y, width, height));
}
private Rectangle GetTransformedRectangle(DockState dockState, Rectangle rect)
{
if (dockState != DockState.DockLeftAutoHide && dockState != DockState.DockRightAutoHide)
return rect;
PointF[] pts = new PointF[1];
// the center of the rectangle
pts[0].X = (float)rect.X + (float)rect.Width / 2;
pts[0].Y = (float)rect.Y + (float)rect.Height / 2;
Rectangle rectTabStrip = GetLogicalTabStripRectangle(dockState);
using (var matrix = new Matrix())
{
matrix.RotateAt(90, new PointF((float)rectTabStrip.X + (float)rectTabStrip.Height / 2,
(float)rectTabStrip.Y + (float)rectTabStrip.Height / 2));
matrix.TransformPoints(pts);
}
return new Rectangle((int)(pts[0].X - (float)rect.Height / 2 + .5F),
(int)(pts[0].Y - (float)rect.Width / 2 + .5F),
rect.Height, rect.Width);
}
protected override IDockContent HitTest(Point point)
{
Tab tab = TabHitTest(point);
if (tab != null)
return tab.Content;
else
return null;
}
protected override Rectangle GetTabBounds(Tab tab)
{
GraphicsPath path = GetTabOutline((TabVS2012Light)tab, true, true);
RectangleF bounds = path.GetBounds();
return new Rectangle((int)bounds.Left, (int)bounds.Top, (int)bounds.Width, (int)bounds.Height);
}
protected Tab TabHitTest(Point ptMouse)
{
foreach (DockState state in DockStates)
{
Rectangle rectTabStrip = GetLogicalTabStripRectangle(state, true);
if (!rectTabStrip.Contains(ptMouse))
continue;
foreach (Pane pane in GetPanes(state))
{
foreach (TabVS2012Light tab in pane.AutoHideTabs)
{
GraphicsPath path = GetTabOutline(tab, true, true);
if (path.IsVisible(ptMouse))
return tab;
}
}
}
return null;
}
private TabVS2012Light lastSelectedTab = null;
protected override void OnMouseHover(EventArgs e)
{
var tab = (TabVS2012Light)TabHitTest(PointToClient(MousePosition));
if (tab != null)
{
tab.IsMouseOver = true;
Invalidate();
}
if (lastSelectedTab != tab)
{
if (lastSelectedTab != null)
lastSelectedTab.IsMouseOver = false;
lastSelectedTab = tab;
}
base.OnMouseHover(e);
}
protected override void OnMouseLeave(EventArgs e)
{
base.OnMouseLeave(e);
if (lastSelectedTab != null)
lastSelectedTab.IsMouseOver = false;
Invalidate();
}
protected override int MeasureHeight()
{
return Math.Max(ImageGapBottom +
ImageGapTop + ImageHeight,
TextFont.Height) + TabGapTop + TabGapBottom;
}
protected override void OnRefreshChanges()
{
CalculateTabs();
Invalidate();
}
protected override AutoHideStripBase.Tab CreateTab(IDockContent content)
{
return new TabVS2012Light(content);
}
}
}
| |
using System;
using System.Diagnostics;
using Lucene.Net.Documents;
using Lucene.Net.Support;
using NUnit.Framework;
using Console = Lucene.Net.Support.SystemConsole;
namespace Lucene.Net.Search
{
using AtomicReaderContext = Lucene.Net.Index.AtomicReaderContext;
using BytesRef = Lucene.Net.Util.BytesRef;
using Directory = Lucene.Net.Store.Directory;
using DirectoryReader = Lucene.Net.Index.DirectoryReader;
using Document = Documents.Document;
using Field = Field;
using FieldType = FieldType;
using SingleField = SingleField;
using IndexReader = Lucene.Net.Index.IndexReader;
using Int32Field = Int32Field;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer;
using MultiFields = Lucene.Net.Index.MultiFields;
using NumericUtils = Lucene.Net.Util.NumericUtils;
using RandomIndexWriter = Lucene.Net.Index.RandomIndexWriter;
using SlowCompositeReaderWrapper = Lucene.Net.Index.SlowCompositeReaderWrapper;
using Terms = Lucene.Net.Index.Terms;
using TermsEnum = Lucene.Net.Index.TermsEnum;
using TestNumericUtils = Lucene.Net.Util.TestNumericUtils; // NaN arrays
using TestUtil = Lucene.Net.Util.TestUtil;
[TestFixture]
public class TestNumericRangeQuery32 : LuceneTestCase
{
// distance of entries
private static int Distance;
// shift the starting of the values to the left, to also have negative values:
private static readonly int StartOffset = -1 << 15;
// number of docs to generate for testing
private static int NoDocs;
private static Directory Directory = null;
private static IndexReader Reader = null;
private static IndexSearcher Searcher = null;
/// <summary>
/// LUCENENET specific
/// Is non-static because NewIndexWriterConfig is no longer static.
/// </summary>
[OneTimeSetUp]
public override void BeforeClass()
{
base.BeforeClass();
NoDocs = AtLeast(4096);
Distance = (1 << 30) / NoDocs;
Directory = NewDirectory();
RandomIndexWriter writer = new RandomIndexWriter(Random(), Directory, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetMaxBufferedDocs(TestUtil.NextInt(Random(), 100, 1000)).SetMergePolicy(NewLogMergePolicy()));
FieldType storedInt = new FieldType(Int32Field.TYPE_NOT_STORED);
storedInt.IsStored = true;
storedInt.Freeze();
FieldType storedInt8 = new FieldType(storedInt);
storedInt8.NumericPrecisionStep = 8;
FieldType storedInt4 = new FieldType(storedInt);
storedInt4.NumericPrecisionStep = 4;
FieldType storedInt2 = new FieldType(storedInt);
storedInt2.NumericPrecisionStep = 2;
FieldType storedIntNone = new FieldType(storedInt);
storedIntNone.NumericPrecisionStep = int.MaxValue;
FieldType unstoredInt = Int32Field.TYPE_NOT_STORED;
FieldType unstoredInt8 = new FieldType(unstoredInt);
unstoredInt8.NumericPrecisionStep = 8;
FieldType unstoredInt4 = new FieldType(unstoredInt);
unstoredInt4.NumericPrecisionStep = 4;
FieldType unstoredInt2 = new FieldType(unstoredInt);
unstoredInt2.NumericPrecisionStep = 2;
Int32Field field8 = new Int32Field("field8", 0, storedInt8), field4 = new Int32Field("field4", 0, storedInt4), field2 = new Int32Field("field2", 0, storedInt2), fieldNoTrie = new Int32Field("field" + int.MaxValue, 0, storedIntNone), ascfield8 = new Int32Field("ascfield8", 0, unstoredInt8), ascfield4 = new Int32Field("ascfield4", 0, unstoredInt4), ascfield2 = new Int32Field("ascfield2", 0, unstoredInt2);
Document doc = new Document();
// add fields, that have a distance to test general functionality
doc.Add(field8);
doc.Add(field4);
doc.Add(field2);
doc.Add(fieldNoTrie);
// add ascending fields with a distance of 1, beginning at -noDocs/2 to test the correct splitting of range and inclusive/exclusive
doc.Add(ascfield8);
doc.Add(ascfield4);
doc.Add(ascfield2);
// Add a series of noDocs docs with increasing int values
for (int l = 0; l < NoDocs; l++)
{
int val = Distance * l + StartOffset;
field8.SetInt32Value(val);
field4.SetInt32Value(val);
field2.SetInt32Value(val);
fieldNoTrie.SetInt32Value(val);
val = l - (NoDocs / 2);
ascfield8.SetInt32Value(val);
ascfield4.SetInt32Value(val);
ascfield2.SetInt32Value(val);
writer.AddDocument(doc);
}
Reader = writer.Reader;
Searcher = NewSearcher(Reader);
writer.Dispose();
}
[OneTimeTearDown]
public override void AfterClass()
{
Searcher = null;
Reader.Dispose();
Reader = null;
Directory.Dispose();
Directory = null;
base.AfterClass();
}
[SetUp]
public override void SetUp()
{
base.SetUp();
// set the theoretical maximum term count for 8bit (see docs for the number)
// super.tearDown will restore the default
BooleanQuery.MaxClauseCount = 3 * 255 * 2 + 255;
}
/// <summary>
/// test for both constant score and boolean query, the other tests only use the constant score mode </summary>
private void TestRange(int precisionStep)
{
string field = "field" + precisionStep;
int count = 3000;
int lower = (Distance * 3 / 2) + StartOffset, upper = lower + count * Distance + (Distance / 3);
NumericRangeQuery<int> q = NumericRangeQuery.NewInt32Range(field, precisionStep, lower, upper, true, true);
NumericRangeFilter<int> f = NumericRangeFilter.NewInt32Range(field, precisionStep, lower, upper, true, true);
for (sbyte i = 0; i < 3; i++)
{
TopDocs topDocs;
string type;
switch (i)
{
case 0:
type = " (constant score filter rewrite)";
q.MultiTermRewriteMethod = MultiTermQuery.CONSTANT_SCORE_FILTER_REWRITE;
topDocs = Searcher.Search(q, null, NoDocs, Sort.INDEXORDER);
break;
case 1:
type = " (constant score boolean rewrite)";
q.MultiTermRewriteMethod = MultiTermQuery.CONSTANT_SCORE_BOOLEAN_QUERY_REWRITE;
topDocs = Searcher.Search(q, null, NoDocs, Sort.INDEXORDER);
break;
case 2:
type = " (filter)";
topDocs = Searcher.Search(new MatchAllDocsQuery(), f, NoDocs, Sort.INDEXORDER);
break;
default:
return;
}
ScoreDoc[] sd = topDocs.ScoreDocs;
Assert.IsNotNull(sd);
Assert.AreEqual(count, sd.Length, "Score doc count" + type);
Document doc = Searcher.Doc(sd[0].Doc);
Assert.AreEqual(2 * Distance + StartOffset, doc.GetField(field).GetInt32Value().Value, "First doc" + type);
doc = Searcher.Doc(sd[sd.Length - 1].Doc);
Assert.AreEqual((1 + count) * Distance + StartOffset, doc.GetField(field).GetInt32Value().Value, "Last doc" + type);
}
}
[Test]
public virtual void TestRange_8bit()
{
TestRange(8);
}
[Test]
public virtual void TestRange_4bit()
{
TestRange(4);
}
[Test]
public virtual void TestRange_2bit()
{
TestRange(2);
}
[Test]
public virtual void TestInverseRange()
{
AtomicReaderContext context = (AtomicReaderContext)SlowCompositeReaderWrapper.Wrap(Reader).Context;
NumericRangeFilter<int> f = NumericRangeFilter.NewInt32Range("field8", 8, 1000, -1000, true, true);
Assert.IsNull(f.GetDocIdSet(context, (context.AtomicReader).LiveDocs), "A inverse range should return the null instance");
f = NumericRangeFilter.NewInt32Range("field8", 8, int.MaxValue, null, false, false);
Assert.IsNull(f.GetDocIdSet(context, (context.AtomicReader).LiveDocs), "A exclusive range starting with Integer.MAX_VALUE should return the null instance");
f = NumericRangeFilter.NewInt32Range("field8", 8, null, int.MinValue, false, false);
Assert.IsNull(f.GetDocIdSet(context, (context.AtomicReader).LiveDocs), "A exclusive range ending with Integer.MIN_VALUE should return the null instance");
}
[Test]
public virtual void TestOneMatchQuery()
{
NumericRangeQuery<int> q = NumericRangeQuery.NewInt32Range("ascfield8", 8, 1000, 1000, true, true);
TopDocs topDocs = Searcher.Search(q, NoDocs);
ScoreDoc[] sd = topDocs.ScoreDocs;
Assert.IsNotNull(sd);
Assert.AreEqual(1, sd.Length, "Score doc count");
}
private void TestLeftOpenRange(int precisionStep)
{
string field = "field" + precisionStep;
int count = 3000;
int upper = (count - 1) * Distance + (Distance / 3) + StartOffset;
NumericRangeQuery<int> q = NumericRangeQuery.NewInt32Range(field, precisionStep, null, upper, true, true);
TopDocs topDocs = Searcher.Search(q, null, NoDocs, Sort.INDEXORDER);
ScoreDoc[] sd = topDocs.ScoreDocs;
Assert.IsNotNull(sd);
Assert.AreEqual(count, sd.Length, "Score doc count");
Document doc = Searcher.Doc(sd[0].Doc);
Assert.AreEqual(StartOffset, doc.GetField(field).GetInt32Value().Value, "First doc");
doc = Searcher.Doc(sd[sd.Length - 1].Doc);
Assert.AreEqual((count - 1) * Distance + StartOffset, doc.GetField(field).GetInt32Value().Value, "Last doc");
q = NumericRangeQuery.NewInt32Range(field, precisionStep, null, upper, false, true);
topDocs = Searcher.Search(q, null, NoDocs, Sort.INDEXORDER);
sd = topDocs.ScoreDocs;
Assert.IsNotNull(sd);
Assert.AreEqual(count, sd.Length, "Score doc count");
doc = Searcher.Doc(sd[0].Doc);
Assert.AreEqual(StartOffset, doc.GetField(field).GetInt32Value().Value, "First doc");
doc = Searcher.Doc(sd[sd.Length - 1].Doc);
Assert.AreEqual((count - 1) * Distance + StartOffset, doc.GetField(field).GetInt32Value().Value, "Last doc");
}
[Test]
public virtual void TestLeftOpenRange_8bit()
{
TestLeftOpenRange(8);
}
[Test]
public virtual void TestLeftOpenRange_4bit()
{
TestLeftOpenRange(4);
}
[Test]
public virtual void TestLeftOpenRange_2bit()
{
TestLeftOpenRange(2);
}
private void TestRightOpenRange(int precisionStep)
{
string field = "field" + precisionStep;
int count = 3000;
int lower = (count - 1) * Distance + (Distance / 3) + StartOffset;
NumericRangeQuery<int> q = NumericRangeQuery.NewInt32Range(field, precisionStep, lower, null, true, true);
TopDocs topDocs = Searcher.Search(q, null, NoDocs, Sort.INDEXORDER);
ScoreDoc[] sd = topDocs.ScoreDocs;
Assert.IsNotNull(sd);
Assert.AreEqual(NoDocs - count, sd.Length, "Score doc count");
Document doc = Searcher.Doc(sd[0].Doc);
Assert.AreEqual(count * Distance + StartOffset, doc.GetField(field).GetInt32Value().Value, "First doc");
doc = Searcher.Doc(sd[sd.Length - 1].Doc);
Assert.AreEqual((NoDocs - 1) * Distance + StartOffset, doc.GetField(field).GetInt32Value().Value, "Last doc");
q = NumericRangeQuery.NewInt32Range(field, precisionStep, lower, null, true, false);
topDocs = Searcher.Search(q, null, NoDocs, Sort.INDEXORDER);
sd = topDocs.ScoreDocs;
Assert.IsNotNull(sd);
Assert.AreEqual(NoDocs - count, sd.Length, "Score doc count");
doc = Searcher.Doc(sd[0].Doc);
Assert.AreEqual(count * Distance + StartOffset, doc.GetField(field).GetInt32Value().Value, "First doc");
doc = Searcher.Doc(sd[sd.Length - 1].Doc);
Assert.AreEqual((NoDocs - 1) * Distance + StartOffset, doc.GetField(field).GetInt32Value().Value, "Last doc");
}
[Test]
public virtual void TestRightOpenRange_8bit()
{
TestRightOpenRange(8);
}
[Test]
public virtual void TestRightOpenRange_4bit()
{
TestRightOpenRange(4);
}
[Test]
public virtual void TestRightOpenRange_2bit()
{
TestRightOpenRange(2);
}
[Test]
public virtual void TestInfiniteValues()
{
Directory dir = NewDirectory();
RandomIndexWriter writer = new RandomIndexWriter(Random(), dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())));
Document doc = new Document();
doc.Add(new SingleField("float", float.NegativeInfinity, Field.Store.NO));
doc.Add(new Int32Field("int", int.MinValue, Field.Store.NO));
writer.AddDocument(doc);
doc = new Document();
doc.Add(new SingleField("float", float.PositiveInfinity, Field.Store.NO));
doc.Add(new Int32Field("int", int.MaxValue, Field.Store.NO));
writer.AddDocument(doc);
doc = new Document();
doc.Add(new SingleField("float", 0.0f, Field.Store.NO));
doc.Add(new Int32Field("int", 0, Field.Store.NO));
writer.AddDocument(doc);
foreach (float f in TestNumericUtils.FLOAT_NANs)
{
doc = new Document();
doc.Add(new SingleField("float", f, Field.Store.NO));
writer.AddDocument(doc);
}
writer.Dispose();
IndexReader r = DirectoryReader.Open(dir);
IndexSearcher s = NewSearcher(r);
Query q = NumericRangeQuery.NewInt32Range("int", null, null, true, true);
TopDocs topDocs = s.Search(q, 10);
Assert.AreEqual(3, topDocs.ScoreDocs.Length, "Score doc count");
q = NumericRangeQuery.NewInt32Range("int", null, null, false, false);
topDocs = s.Search(q, 10);
Assert.AreEqual(3, topDocs.ScoreDocs.Length, "Score doc count");
q = NumericRangeQuery.NewInt32Range("int", int.MinValue, int.MaxValue, true, true);
topDocs = s.Search(q, 10);
Assert.AreEqual(3, topDocs.ScoreDocs.Length, "Score doc count");
q = NumericRangeQuery.NewInt32Range("int", int.MinValue, int.MaxValue, false, false);
topDocs = s.Search(q, 10);
Assert.AreEqual(1, topDocs.ScoreDocs.Length, "Score doc count");
q = NumericRangeQuery.NewSingleRange("float", null, null, true, true);
topDocs = s.Search(q, 10);
Assert.AreEqual(3, topDocs.ScoreDocs.Length, "Score doc count");
q = NumericRangeQuery.NewSingleRange("float", null, null, false, false);
topDocs = s.Search(q, 10);
Assert.AreEqual(3, topDocs.ScoreDocs.Length, "Score doc count");
q = NumericRangeQuery.NewSingleRange("float", float.NegativeInfinity, float.PositiveInfinity, true, true);
topDocs = s.Search(q, 10);
Assert.AreEqual(3, topDocs.ScoreDocs.Length, "Score doc count");
q = NumericRangeQuery.NewSingleRange("float", float.NegativeInfinity, float.PositiveInfinity, false, false);
topDocs = s.Search(q, 10);
Assert.AreEqual(1, topDocs.ScoreDocs.Length, "Score doc count");
q = NumericRangeQuery.NewSingleRange("float", float.NaN, float.NaN, true, true);
topDocs = s.Search(q, 10);
Assert.AreEqual(TestNumericUtils.FLOAT_NANs.Length, topDocs.ScoreDocs.Length, "Score doc count");
r.Dispose();
dir.Dispose();
}
private void TestRandomTrieAndClassicRangeQuery(int precisionStep)
{
string field = "field" + precisionStep;
int totalTermCountT = 0, totalTermCountC = 0, termCountT, termCountC;
int num = TestUtil.NextInt(Random(), 10, 20);
for (int i = 0; i < num; i++)
{
int lower = (int)(Random().NextDouble() * NoDocs * Distance) + StartOffset;
int upper = (int)(Random().NextDouble() * NoDocs * Distance) + StartOffset;
if (lower > upper)
{
int a = lower;
lower = upper;
upper = a;
}
BytesRef lowerBytes = new BytesRef(NumericUtils.BUF_SIZE_INT32), upperBytes = new BytesRef(NumericUtils.BUF_SIZE_INT32);
NumericUtils.Int32ToPrefixCodedBytes(lower, 0, lowerBytes);
NumericUtils.Int32ToPrefixCodedBytes(upper, 0, upperBytes);
// test inclusive range
NumericRangeQuery<int> tq = NumericRangeQuery.NewInt32Range(field, precisionStep, lower, upper, true, true);
TermRangeQuery cq = new TermRangeQuery(field, lowerBytes, upperBytes, true, true);
TopDocs tTopDocs = Searcher.Search(tq, 1);
TopDocs cTopDocs = Searcher.Search(cq, 1);
Assert.AreEqual(cTopDocs.TotalHits, tTopDocs.TotalHits, "Returned count for NumericRangeQuery and TermRangeQuery must be equal");
totalTermCountT += termCountT = CountTerms(tq);
totalTermCountC += termCountC = CountTerms(cq);
CheckTermCounts(precisionStep, termCountT, termCountC);
// test exclusive range
tq = NumericRangeQuery.NewInt32Range(field, precisionStep, lower, upper, false, false);
cq = new TermRangeQuery(field, lowerBytes, upperBytes, false, false);
tTopDocs = Searcher.Search(tq, 1);
cTopDocs = Searcher.Search(cq, 1);
Assert.AreEqual(cTopDocs.TotalHits, tTopDocs.TotalHits, "Returned count for NumericRangeQuery and TermRangeQuery must be equal");
totalTermCountT += termCountT = CountTerms(tq);
totalTermCountC += termCountC = CountTerms(cq);
CheckTermCounts(precisionStep, termCountT, termCountC);
// test left exclusive range
tq = NumericRangeQuery.NewInt32Range(field, precisionStep, lower, upper, false, true);
cq = new TermRangeQuery(field, lowerBytes, upperBytes, false, true);
tTopDocs = Searcher.Search(tq, 1);
cTopDocs = Searcher.Search(cq, 1);
Assert.AreEqual(cTopDocs.TotalHits, tTopDocs.TotalHits, "Returned count for NumericRangeQuery and TermRangeQuery must be equal");
totalTermCountT += termCountT = CountTerms(tq);
totalTermCountC += termCountC = CountTerms(cq);
CheckTermCounts(precisionStep, termCountT, termCountC);
// test right exclusive range
tq = NumericRangeQuery.NewInt32Range(field, precisionStep, lower, upper, true, false);
cq = new TermRangeQuery(field, lowerBytes, upperBytes, true, false);
tTopDocs = Searcher.Search(tq, 1);
cTopDocs = Searcher.Search(cq, 1);
Assert.AreEqual(cTopDocs.TotalHits, tTopDocs.TotalHits, "Returned count for NumericRangeQuery and TermRangeQuery must be equal");
totalTermCountT += termCountT = CountTerms(tq);
totalTermCountC += termCountC = CountTerms(cq);
CheckTermCounts(precisionStep, termCountT, termCountC);
}
CheckTermCounts(precisionStep, totalTermCountT, totalTermCountC);
if (VERBOSE && precisionStep != int.MaxValue)
{
Console.WriteLine("Average number of terms during random search on '" + field + "':");
Console.WriteLine(" Numeric query: " + (((double)totalTermCountT) / (num * 4)));
Console.WriteLine(" Classical query: " + (((double)totalTermCountC) / (num * 4)));
}
}
[Test]
public virtual void TestEmptyEnums()
{
int count = 3000;
int lower = (Distance * 3 / 2) + StartOffset, upper = lower + count * Distance + (Distance / 3);
// test empty enum
Debug.Assert(lower < upper);
Assert.IsTrue(0 < CountTerms(NumericRangeQuery.NewInt32Range("field4", 4, lower, upper, true, true)));
Assert.AreEqual(0, CountTerms(NumericRangeQuery.NewInt32Range("field4", 4, upper, lower, true, true)));
// test empty enum outside of bounds
lower = Distance * NoDocs + StartOffset;
upper = 2 * lower;
Debug.Assert(lower < upper);
Assert.AreEqual(0, CountTerms(NumericRangeQuery.NewInt32Range("field4", 4, lower, upper, true, true)));
}
private int CountTerms(MultiTermQuery q)
{
Terms terms = MultiFields.GetTerms(Reader, q.Field);
if (terms == null)
{
return 0;
}
TermsEnum termEnum = q.GetTermsEnum(terms);
Assert.IsNotNull(termEnum);
int count = 0;
BytesRef cur, last = null;
while ((cur = termEnum.Next()) != null)
{
count++;
if (last != null)
{
Assert.IsTrue(last.CompareTo(cur) < 0);
}
last = BytesRef.DeepCopyOf(cur);
}
// LUCENE-3314: the results after next() already returned null are undefined,
// Assert.IsNull(termEnum.Next());
return count;
}
private void CheckTermCounts(int precisionStep, int termCountT, int termCountC)
{
if (precisionStep == int.MaxValue)
{
Assert.AreEqual(termCountC, termCountT, "Number of terms should be equal for unlimited precStep");
}
else
{
Assert.IsTrue(termCountT <= termCountC, "Number of terms for NRQ should be <= compared to classical TRQ");
}
}
[Test]
public virtual void TestRandomTrieAndClassicRangeQuery_8bit()
{
TestRandomTrieAndClassicRangeQuery(8);
}
[Test]
public virtual void TestRandomTrieAndClassicRangeQuery_4bit()
{
TestRandomTrieAndClassicRangeQuery(4);
}
[Test]
public virtual void TestRandomTrieAndClassicRangeQuery_2bit()
{
TestRandomTrieAndClassicRangeQuery(2);
}
[Test]
public virtual void TestRandomTrieAndClassicRangeQuery_NoTrie()
{
TestRandomTrieAndClassicRangeQuery(int.MaxValue);
}
private void TestRangeSplit(int precisionStep)
{
string field = "ascfield" + precisionStep;
// 10 random tests
int num = TestUtil.NextInt(Random(), 10, 20);
for (int i = 0; i < num; i++)
{
int lower = (int)(Random().NextDouble() * NoDocs - NoDocs / 2);
int upper = (int)(Random().NextDouble() * NoDocs - NoDocs / 2);
if (lower > upper)
{
int a = lower;
lower = upper;
upper = a;
}
// test inclusive range
Query tq = NumericRangeQuery.NewInt32Range(field, precisionStep, lower, upper, true, true);
TopDocs tTopDocs = Searcher.Search(tq, 1);
Assert.AreEqual(upper - lower + 1, tTopDocs.TotalHits, "Returned count of range query must be equal to inclusive range length");
// test exclusive range
tq = NumericRangeQuery.NewInt32Range(field, precisionStep, lower, upper, false, false);
tTopDocs = Searcher.Search(tq, 1);
Assert.AreEqual(Math.Max(upper - lower - 1, 0), tTopDocs.TotalHits, "Returned count of range query must be equal to exclusive range length");
// test left exclusive range
tq = NumericRangeQuery.NewInt32Range(field, precisionStep, lower, upper, false, true);
tTopDocs = Searcher.Search(tq, 1);
Assert.AreEqual(upper - lower, tTopDocs.TotalHits, "Returned count of range query must be equal to half exclusive range length");
// test right exclusive range
tq = NumericRangeQuery.NewInt32Range(field, precisionStep, lower, upper, true, false);
tTopDocs = Searcher.Search(tq, 1);
Assert.AreEqual(upper - lower, tTopDocs.TotalHits, "Returned count of range query must be equal to half exclusive range length");
}
}
[Test]
public virtual void TestRangeSplit_8bit()
{
TestRangeSplit(8);
}
[Test]
public virtual void TestRangeSplit_4bit()
{
TestRangeSplit(4);
}
[Test]
public virtual void TestRangeSplit_2bit()
{
TestRangeSplit(2);
}
/// <summary>
/// we fake a float test using int2float conversion of NumericUtils </summary>
private void TestFloatRange(int precisionStep)
{
string field = "ascfield" + precisionStep;
const int lower = -1000, upper = +2000;
Query tq = NumericRangeQuery.NewSingleRange(field, precisionStep, NumericUtils.SortableInt32ToSingle(lower), NumericUtils.SortableInt32ToSingle(upper), true, true);
TopDocs tTopDocs = Searcher.Search(tq, 1);
Assert.AreEqual(upper - lower + 1, tTopDocs.TotalHits, "Returned count of range query must be equal to inclusive range length");
Filter tf = NumericRangeFilter.NewSingleRange(field, precisionStep, NumericUtils.SortableInt32ToSingle(lower), NumericUtils.SortableInt32ToSingle(upper), true, true);
tTopDocs = Searcher.Search(new MatchAllDocsQuery(), tf, 1);
Assert.AreEqual(upper - lower + 1, tTopDocs.TotalHits, "Returned count of range filter must be equal to inclusive range length");
}
[Test]
public virtual void TestFloatRange_8bit()
{
TestFloatRange(8);
}
[Test]
public virtual void TestFloatRange_4bit()
{
TestFloatRange(4);
}
[Test]
public virtual void TestFloatRange_2bit()
{
TestFloatRange(2);
}
private void TestSorting(int precisionStep)
{
string field = "field" + precisionStep;
// 10 random tests, the index order is ascending,
// so using a reverse sort field should retun descending documents
int num = TestUtil.NextInt(Random(), 10, 20);
for (int i = 0; i < num; i++)
{
int lower = (int)(Random().NextDouble() * NoDocs * Distance) + StartOffset;
int upper = (int)(Random().NextDouble() * NoDocs * Distance) + StartOffset;
if (lower > upper)
{
int a = lower;
lower = upper;
upper = a;
}
Query tq = NumericRangeQuery.NewInt32Range(field, precisionStep, lower, upper, true, true);
TopDocs topDocs = Searcher.Search(tq, null, NoDocs, new Sort(new SortField(field, SortFieldType.INT32, true)));
if (topDocs.TotalHits == 0)
{
continue;
}
ScoreDoc[] sd = topDocs.ScoreDocs;
Assert.IsNotNull(sd);
int last = Searcher.Doc(sd[0].Doc).GetField(field).GetInt32Value().Value;
for (int j = 1; j < sd.Length; j++)
{
int act = Searcher.Doc(sd[j].Doc).GetField(field).GetInt32Value().Value;
Assert.IsTrue(last > act, "Docs should be sorted backwards");
last = act;
}
}
}
[Test]
public virtual void TestSorting_8bit()
{
TestSorting(8);
}
[Test]
public virtual void TestSorting_4bit()
{
TestSorting(4);
}
[Test]
public virtual void TestSorting_2bit()
{
TestSorting(2);
}
[Test]
public virtual void TestEqualsAndHash()
{
QueryUtils.CheckHashEquals(NumericRangeQuery.NewInt32Range("test1", 4, 10, 20, true, true));
QueryUtils.CheckHashEquals(NumericRangeQuery.NewInt32Range("test2", 4, 10, 20, false, true));
QueryUtils.CheckHashEquals(NumericRangeQuery.NewInt32Range("test3", 4, 10, 20, true, false));
QueryUtils.CheckHashEquals(NumericRangeQuery.NewInt32Range("test4", 4, 10, 20, false, false));
QueryUtils.CheckHashEquals(NumericRangeQuery.NewInt32Range("test5", 4, 10, null, true, true));
QueryUtils.CheckHashEquals(NumericRangeQuery.NewInt32Range("test6", 4, null, 20, true, true));
QueryUtils.CheckHashEquals(NumericRangeQuery.NewInt32Range("test7", 4, null, null, true, true));
QueryUtils.CheckEqual(NumericRangeQuery.NewInt32Range("test8", 4, 10, 20, true, true), NumericRangeQuery.NewInt32Range("test8", 4, 10, 20, true, true));
QueryUtils.CheckUnequal(NumericRangeQuery.NewInt32Range("test9", 4, 10, 20, true, true), NumericRangeQuery.NewInt32Range("test9", 8, 10, 20, true, true));
QueryUtils.CheckUnequal(NumericRangeQuery.NewInt32Range("test10a", 4, 10, 20, true, true), NumericRangeQuery.NewInt32Range("test10b", 4, 10, 20, true, true));
QueryUtils.CheckUnequal(NumericRangeQuery.NewInt32Range("test11", 4, 10, 20, true, true), NumericRangeQuery.NewInt32Range("test11", 4, 20, 10, true, true));
QueryUtils.CheckUnequal(NumericRangeQuery.NewInt32Range("test12", 4, 10, 20, true, true), NumericRangeQuery.NewInt32Range("test12", 4, 10, 20, false, true));
QueryUtils.CheckUnequal(NumericRangeQuery.NewInt32Range("test13", 4, 10, 20, true, true), NumericRangeQuery.NewSingleRange("test13", 4, 10f, 20f, true, true));
// the following produces a hash collision, because Long and Integer have the same hashcode, so only test equality:
Query q1 = NumericRangeQuery.NewInt32Range("test14", 4, 10, 20, true, true);
Query q2 = NumericRangeQuery.NewInt64Range("test14", 4, 10L, 20L, true, true);
Assert.IsFalse(q1.Equals(q2));
Assert.IsFalse(q2.Equals(q1));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEngine;
namespace UnityTest
{
[Serializable]
public partial class UnitTestView : EditorWindow, IHasCustomMenu
{
private static UnitTestView s_Instance;
private static readonly IUnitTestEngine k_TestEngine = new NUnitTestEngine();
[SerializeField] private List<UnitTestResult> m_ResultList = new List<UnitTestResult>();
[SerializeField] private List<string> m_FoldMarkers = new List<string>();
[SerializeField] private List<UnitTestRendererLine> m_SelectedLines = new List<UnitTestRendererLine>();
UnitTestRendererLine m_TestLines;
private TestFilterSettings m_FilterSettings;
#region runner steering vars
private Vector2 m_TestListScroll, m_TestInfoScroll;
private float m_HorizontalSplitBarPosition = 200;
private float m_VerticalSplitBarPosition = 300;
#endregion
private UnitTestsRunnerSettings m_Settings;
#region GUI Contents
private readonly GUIContent m_GUIRunSelectedTestsIcon = new GUIContent("Run Selected", "Run selected tests");
private readonly GUIContent m_GUIRunAllTestsIcon = new GUIContent("Run All", "Run all tests");
private readonly GUIContent m_GUIRerunFailedTestsIcon = new GUIContent("Rerun Failed", "Rerun failed tests");
private readonly GUIContent m_GUIRunOnRecompile = new GUIContent("Run on recompile", "Run all tests after recompilation");
private readonly GUIContent m_GUIShowDetailsBelowTests = new GUIContent("Show details below tests", "Show run details below test list");
private readonly GUIContent m_GUIRunTestsOnNewScene = new GUIContent("Run tests on a new scene", "Run tests on a new scene");
private readonly GUIContent m_GUIAutoSaveSceneBeforeRun = new GUIContent("Autosave scene", "The runner will automatically save the current scene changes before it starts");
#endregion
public UnitTestView()
{
m_ResultList.Clear();
}
public void OnEnable()
{
title = "Unit Tests";
s_Instance = this;
m_Settings = ProjectSettingsBase.Load<UnitTestsRunnerSettings>();
m_FilterSettings = new TestFilterSettings("UnityTest.UnitTestView");
RefreshTests();
EnableBackgroundRunner(m_Settings.runOnRecompilation);
}
public void OnDestroy()
{
s_Instance = null;
EnableBackgroundRunner(false);
}
public void OnGUI()
{
EditorGUILayout.BeginVertical();
EditorGUILayout.BeginHorizontal(EditorStyles.toolbar);
if (GUILayout.Button(m_GUIRunAllTestsIcon, EditorStyles.toolbarButton))
{
RunTests();
GUIUtility.ExitGUI();
}
EditorGUI.BeginDisabledGroup(!m_TestLines.IsAnySelected);
if (GUILayout.Button(m_GUIRunSelectedTestsIcon, EditorStyles.toolbarButton))
{
m_TestLines.RunSelectedTests();
}
EditorGUI.EndDisabledGroup();
if (GUILayout.Button(m_GUIRerunFailedTestsIcon, EditorStyles.toolbarButton))
{
m_TestLines.RunTests(m_ResultList.Where(result => result.IsFailure || result.IsError).Select(l => l.FullName).ToArray());
}
GUILayout.FlexibleSpace();
m_FilterSettings.OnGUI ();
EditorGUILayout.EndHorizontal();
if (m_Settings.horizontalSplit)
EditorGUILayout.BeginVertical();
else
EditorGUILayout.BeginHorizontal(GUILayout.ExpandWidth(true));
RenderTestList();
RenderTestInfo();
if (m_Settings.horizontalSplit)
EditorGUILayout.EndVertical();
else
EditorGUILayout.EndHorizontal();
EditorGUILayout.EndVertical();
}
private void RenderTestList()
{
EditorGUILayout.BeginVertical(Styles.testList);
m_TestListScroll = EditorGUILayout.BeginScrollView(m_TestListScroll,
GUILayout.ExpandWidth(true),
GUILayout.MaxWidth(2000));
if (m_TestLines != null)
{
if (m_TestLines.Render(m_FilterSettings.BuildRenderingOptions())) Repaint();
}
EditorGUILayout.EndScrollView();
EditorGUILayout.EndVertical();
}
private void RenderTestInfo()
{
var ctrlId = GUIUtility.GetControlID(FocusType.Passive);
var rect = GUILayoutUtility.GetLastRect();
if (m_Settings.horizontalSplit)
{
rect.y = rect.height + rect.y - 1;
rect.height = 3;
}
else
{
rect.x = rect.width + rect.x - 1;
rect.width = 3;
}
EditorGUIUtility.AddCursorRect(rect, m_Settings.horizontalSplit ? MouseCursor.ResizeVertical : MouseCursor.ResizeHorizontal);
var e = Event.current;
switch (e.type)
{
case EventType.MouseDown:
if (GUIUtility.hotControl == 0 && rect.Contains(e.mousePosition))
GUIUtility.hotControl = ctrlId;
break;
case EventType.MouseDrag:
if (GUIUtility.hotControl == ctrlId)
{
m_HorizontalSplitBarPosition -= e.delta.y;
if (m_HorizontalSplitBarPosition < 20) m_HorizontalSplitBarPosition = 20;
m_VerticalSplitBarPosition -= e.delta.x;
if (m_VerticalSplitBarPosition < 20) m_VerticalSplitBarPosition = 20;
Repaint();
}
break;
case EventType.MouseUp:
if (GUIUtility.hotControl == ctrlId)
GUIUtility.hotControl = 0;
break;
}
m_TestInfoScroll = EditorGUILayout.BeginScrollView(m_TestInfoScroll, m_Settings.horizontalSplit
? GUILayout.MinHeight(m_HorizontalSplitBarPosition)
: GUILayout.Width(m_VerticalSplitBarPosition));
var text = "";
if (m_SelectedLines.Any())
{
text = m_SelectedLines.First().GetResultText();
}
EditorGUILayout.TextArea(text, Styles.info);
EditorGUILayout.EndScrollView();
}
private void ToggleRunOnRecompilation()
{
m_Settings.runOnRecompilation = !m_Settings.runOnRecompilation;
EnableBackgroundRunner(m_Settings.runOnRecompilation);
}
public void AddItemsToMenu (GenericMenu menu)
{
menu.AddItem(m_GUIRunOnRecompile, m_Settings.runOnRecompilation, ToggleRunOnRecompilation);
menu.AddItem(m_GUIRunTestsOnNewScene, m_Settings.runTestOnANewScene, m_Settings.ToggleRunTestOnANewScene);
if(!m_Settings.runTestOnANewScene)
menu.AddDisabledItem(m_GUIAutoSaveSceneBeforeRun);
else
menu.AddItem(m_GUIAutoSaveSceneBeforeRun, m_Settings.autoSaveSceneBeforeRun, m_Settings.ToggleAutoSaveSceneBeforeRun);
menu.AddItem(m_GUIShowDetailsBelowTests, m_Settings.horizontalSplit, m_Settings.ToggleHorizontalSplit);
}
private void RefreshTests()
{
UnitTestResult[] newResults;
m_TestLines = k_TestEngine.GetTests(out newResults, out m_FilterSettings.AvailableCategories);
foreach (var newResult in newResults)
{
var result = m_ResultList.Where(t => t.Test == newResult.Test && t.FullName == newResult.FullName).ToArray();
if (result.Count() != 1) continue;
newResult.Update(result.Single(), true);
}
UnitTestRendererLine.SelectedLines = m_SelectedLines;
UnitTestRendererLine.RunTest = RunTests;
GroupLine.FoldMarkers = m_FoldMarkers;
TestLine.GetUnitTestResult = FindTestResult;
m_ResultList = new List<UnitTestResult>(newResults);
m_FilterSettings.UpdateCounters(m_ResultList.Cast<ITestResult>());
Repaint();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.Graphics;
using Android.Graphics.Drawables;
using Android.Animation;
using Android.Util;
using Android.Content.Res;
using Android.Views.Animations;
namespace Sino.Droid.MaterialRipple
{
public class MaterialRippleLayout : FrameLayout
{
private const int DEFAULT_DURATION = 350;
private const int DEFAULT_FADE_DURATION = 75;
private const float DEFAULT_DIAMETER_DP = 35;
private const float DEFAULT_ALPHA = 0.2f;
private static Color DEFAULT_COLOR = Color.Black;
private static Color DEFAULT_BACKGROUND = Color.Transparent;
private const bool DEFAULT_HOVER = true;
private const bool DEFAULT_DELAY_CLICK = true;
private const bool DEFAULT_PERSISTENT = false;
private const bool DEFAULT_SEARCH_ADAPTER = false;
private const bool DEFAULT_RIPPLE_OVERLAY = false;
private const int DEFAULT_ROUNDED_CORNERS = 0;
private const int FADE_EXTRA_DELAY = 50;
private const long HOVER_DURATION = 2500;
private Paint paint = new Paint(PaintFlags.AntiAlias);
private Rect bounds = new Rect();
private Color rippleColor;
private bool rippleOverlay;
private bool rippleHover;
private int rippleDiameter;
private int rippleDuration;
private int rippleAlpha;
private bool rippleDelayClick;
private int rippleFadeDuration;
private bool ripplePersistent;
private Drawable rippleBackground;
private bool rippleInAdapter;
private float rippleRoundedCorners;
private float radius;
private AdapterView parentAdapter;
private View childView;
private AnimatorSet rippleAnimator;
private ObjectAnimator hoverAnimator;
private Point currentCoords = new Point();
private Point previousCoords = new Point();
private LayerType layerType;
private bool eventCancelled;
private bool prepressed;
private int positionInAdapter;
private GestureDetector gestureDetector;
private PerformClickEvent pendingClickEvent;
private PressedEvent pendingPressEvent;
public static RippleBuilder On(View view)
{
return new RippleBuilder(view);
}
public MaterialRippleLayout(Context context)
: this(context, null, 0) { }
public MaterialRippleLayout(Context context, IAttributeSet attrs)
: this(context, attrs, 0) { }
public MaterialRippleLayout(Context context, IAttributeSet attrs, int defStyle)
: base(context, attrs, defStyle)
{
longClickListener = new LongClickListener
{
LongPress = (e) =>
{
hasPerformedLongPress = childView.PerformLongClick();
if (hasPerformedLongPress)
{
if (rippleHover)
{
StartRipple(null);
}
CancelPressedEvent();
}
},
Down = (x) =>
{
hasPerformedLongPress = false;
}
};
SetWillNotDraw(false);
gestureDetector = new GestureDetector(context, longClickListener);
TypedArray a = context.ObtainStyledAttributes(attrs,Resource.Styleable.MaterialRippleLayout);
rippleColor = a.GetColor(Resource.Styleable.MaterialRippleLayout_sino_droid_mrl_rippleColor, DEFAULT_COLOR);
rippleDiameter = a.GetDimensionPixelSize(
Resource.Styleable.MaterialRippleLayout_sino_droid_mrl_rippleDimension,
(int)dpToPx(Resources, DEFAULT_DIAMETER_DP)
);
rippleOverlay = a.GetBoolean(Resource.Styleable.MaterialRippleLayout_sino_droid_mrl_rippleOverlay, DEFAULT_RIPPLE_OVERLAY);
rippleHover = a.GetBoolean(Resource.Styleable.MaterialRippleLayout_sino_droid_mrl_rippleHover, DEFAULT_HOVER);
rippleDuration = a.GetInt(Resource.Styleable.MaterialRippleLayout_sino_droid_mrl_rippleDuration, DEFAULT_DURATION);
rippleAlpha = (int)(255 * a.GetFloat(Resource.Styleable.MaterialRippleLayout_sino_droid_mrl_rippleAlpha, DEFAULT_ALPHA));
rippleDelayClick = a.GetBoolean(Resource.Styleable.MaterialRippleLayout_sino_droid_mrl_rippleDelayClick, DEFAULT_DELAY_CLICK);
rippleFadeDuration = a.GetInteger(Resource.Styleable.MaterialRippleLayout_sino_droid_mrl_rippleFadeDuration, DEFAULT_FADE_DURATION);
rippleBackground = new ColorDrawable(a.GetColor(Resource.Styleable.MaterialRippleLayout_sino_droid_mrl_rippleBackground, DEFAULT_BACKGROUND));
ripplePersistent = a.GetBoolean(Resource.Styleable.MaterialRippleLayout_sino_droid_mrl_ripplePersistent, DEFAULT_PERSISTENT);
rippleInAdapter = a.GetBoolean(Resource.Styleable.MaterialRippleLayout_sino_droid_mrl_rippleInAdapter, DEFAULT_SEARCH_ADAPTER);
rippleRoundedCorners = a.GetDimensionPixelSize(Resource.Styleable.MaterialRippleLayout_sino_droid_mrl_rippleRoundedCorners, DEFAULT_ROUNDED_CORNERS);
a.Recycle();
paint.Color = rippleColor;
paint.Alpha = rippleAlpha;
enableClipPathSupportIfNecessary();
}
public T GetChildView<T>() where T : View
{
return (T)childView;
}
public override void AddView(View child, int index, ViewGroup.LayoutParams param)
{
if (ChildCount > 0)
{
throw new InvalidOperationException("MaterialRippleLayout can host only one child");
}
childView = child;
base.AddView(child, index, param);
}
public override void SetOnClickListener(IOnClickListener onClickListener)
{
if (childView == null)
{
throw new InvalidOperationException("MaterialRippleLayout must have a child view to handle clicks");
}
childView.SetOnClickListener(onClickListener);
}
public new event EventHandler Click
{
add
{
childView.Click += value;
}
remove
{
childView.Click -= value;
}
}
public override void SetOnLongClickListener(IOnLongClickListener onClickListener)
{
if (childView == null)
{
throw new InvalidOperationException("MaterialRippleLayout must have a child view to handle clicks");
}
childView.SetOnLongClickListener(onClickListener);
}
public new event EventHandler<View.LongClickEventArgs> LongClick
{
add
{
childView.LongClick += value;
}
remove
{
childView.LongClick -= value;
}
}
public override bool OnInterceptTouchEvent(MotionEvent e)
{
return !FindClickableViewInChild(childView, (int)e.GetX(), (int)e.GetY());
}
public override bool OnTouchEvent(MotionEvent e)
{
bool superOnTouchEvent = base.OnTouchEvent(e);
if (!Enabled || !childView.Enabled) return superOnTouchEvent;
bool isEventInBounds = bounds.Contains((int)e.GetX(), (int)e.GetY());
if (isEventInBounds)
{
previousCoords.Set(currentCoords.X, currentCoords.Y);
currentCoords.Set((int)e.GetX(), (int)e.GetY());
}
bool gestureResult = gestureDetector.OnTouchEvent(e);
if (gestureResult || hasPerformedLongPress)
{
return true;
}
else
{
var action = e.ActionMasked;
switch (action)
{
case MotionEventActions.Up:
pendingClickEvent = new PerformClickEvent
{
ClickAdapterView = (x) =>
{
int position = x.GetPositionForView(this);
long itemId = x.GetItemIdAtPosition(position);
if(position != AdapterView.InvalidPosition)
{
x.PerformItemClick(this, position, itemId);
}
},
RunDelegate = () =>
{
if (hasPerformedLongPress) return;
if(Parent is AdapterView)
{
pendingClickEvent.ClickAdapterView((AdapterView)Parent);
}
else if(rippleInAdapter)
{
pendingClickEvent.ClickAdapterView(FindParentAdapterView());
}
else
{
childView.PerformClick();
}
}
};
if (prepressed)
{
childView.Pressed = true;
PostDelayed(() =>
{
childView.Pressed = false;
}, ViewConfiguration.PressedStateDuration);
}
if (isEventInBounds)
{
StartRipple(pendingClickEvent);
}
else if (!rippleHover)
{
SetRadius(0);
}
if (!rippleDelayClick && isEventInBounds)
{
pendingClickEvent.Run();
}
CancelPressedEvent();
break;
case MotionEventActions.Down:
SetPositionInAdapter();
eventCancelled = false;
pendingPressEvent = new PressedEvent(e)
{
RunDelegate = (x) =>
{
prepressed = false;
childView.LongClickable = false;
childView.OnTouchEvent(x);
childView.Pressed = true;
if (rippleHover)
{
StartHover();
}
}
};
if (IsInScrollingContainer())
{
CancelPressedEvent();
prepressed = true;
PostDelayed(pendingPressEvent, ViewConfiguration.TapTimeout);
}
else
{
pendingPressEvent.Run();
}
break;
case MotionEventActions.Cancel:
if (rippleInAdapter)
{
currentCoords.Set(previousCoords.X, previousCoords.Y);
previousCoords = new Point();
}
childView.OnTouchEvent(e);
if (rippleHover)
{
if (!prepressed)
{
StartRipple(null);
}
}
else
{
childView.Pressed = false;
}
CancelPressedEvent();
break;
case MotionEventActions.Move:
if (rippleHover)
{
if (isEventInBounds && !eventCancelled)
{
Invalidate();
}
else if (!isEventInBounds)
{
StartRipple(null);
}
}
if (!isEventInBounds)
{
CancelPressedEvent();
if (hoverAnimator != null)
{
hoverAnimator.Cancel();
}
childView.OnTouchEvent(e);
eventCancelled = true;
}
break;
}
return true;
}
}
private void CancelPressedEvent()
{
if (pendingPressEvent != null)
{
RemoveCallbacks(pendingPressEvent);
prepressed = false;
}
}
private bool hasPerformedLongPress;
private GestureDetector.SimpleOnGestureListener longClickListener;
private void StartHover()
{
if (eventCancelled) return;
if (hoverAnimator != null)
{
hoverAnimator.Cancel();
}
float radius = (float)(Math.Sqrt(Math.Pow(Width, 2) + Math.Pow(Height, 2)) * 1.2f);
hoverAnimator = ObjectAnimator.OfFloat(this, radiusProperty, rippleDiameter, radius);
hoverAnimator.SetDuration(HOVER_DURATION);
hoverAnimator.SetInterpolator(new LinearInterpolator());
hoverAnimator.Start();
}
private void StartRipple(Java.Lang.IRunnable animationEndRunnable)
{
if (eventCancelled) return;
float endRadius = GetEndRadius();
CancelAnimations();
rippleAnimator = new AnimatorSet();
rippleAnimator.AddListener(new RippleAnimatorListenerAdapter
{
AnimationEnd = (x) =>
{
if (!ripplePersistent)
{
SetRadius(0);
SetAlpha(rippleAlpha);
}
if (animationEndRunnable != null && rippleDelayClick)
{
animationEndRunnable.Run();
}
childView.Pressed = false;
}
});
ObjectAnimator ripple = ObjectAnimator.OfFloat(this, radiusProperty, radius, endRadius);
ripple.SetDuration(rippleDuration);
ripple.SetInterpolator(new DecelerateInterpolator());
ObjectAnimator fade = ObjectAnimator.OfInt(this, circleAlphaProperty, rippleAlpha, 0);
fade.SetDuration(rippleFadeDuration);
fade.SetInterpolator(new AccelerateInterpolator());
fade.StartDelay = rippleDuration - rippleFadeDuration - FADE_EXTRA_DELAY;
if (ripplePersistent)
{
rippleAnimator.Play(ripple);
}
else if (GetRadius() > endRadius)
{
fade.StartDelay = 0;
rippleAnimator.Play(fade);
}
else
{
rippleAnimator.PlayTogether(ripple, fade);
}
rippleAnimator.Start();
}
private void CancelAnimations()
{
if (rippleAnimator != null)
{
rippleAnimator.Cancel();
rippleAnimator.RemoveAllListeners();
}
if (hoverAnimator != null)
{
hoverAnimator.Cancel();
}
}
private float GetEndRadius()
{
int width = Width;
int height = Height;
int halfWidth = width / 2;
int halfHeight = height / 2;
float radiusX = halfWidth > currentCoords.X ? width - currentCoords.X : currentCoords.X;
float radiusY = halfHeight > currentCoords.Y ? height - currentCoords.Y : currentCoords.Y;
return (float)Math.Sqrt(Math.Pow(radiusX, 2) + Math.Pow(radiusY, 2)) * 1.2f;
}
private bool IsInScrollingContainer()
{
IViewParent p = Parent;
while (p != null && p is ViewGroup)
{
if (((ViewGroup)p).ShouldDelayChildPressedState())
{
return true;
}
p = p.Parent;
}
return false;
}
private AdapterView FindParentAdapterView()
{
if (parentAdapter != null)
{
return parentAdapter;
}
IViewParent current = Parent;
while (true)
{
if (current is AdapterView)
{
parentAdapter = (AdapterView)current;
return parentAdapter;
}
else
{
current = current.Parent;
}
}
}
private void SetPositionInAdapter()
{
if (rippleInAdapter)
{
positionInAdapter = FindParentAdapterView().GetPositionForView(this);
}
}
private bool AdapterPositionChanged()
{
if (rippleInAdapter)
{
int newPosition = FindParentAdapterView().GetPositionForView(this);
bool changed = newPosition != positionInAdapter;
positionInAdapter = newPosition;
if (changed)
{
CancelPressedEvent();
CancelAnimations();
childView.Pressed = false;
SetRadius(0);
}
return changed;
}
return false;
}
private bool FindClickableViewInChild(View view, int x, int y)
{
if (view is ViewGroup)
{
ViewGroup viewGroup = (ViewGroup)view;
for (int i = 0; i < viewGroup.ChildCount; i++)
{
View child = viewGroup.GetChildAt(i);
Rect rect = new Rect();
child.GetHitRect(rect);
bool contains = rect.Contains(x, y);
if (contains)
{
return FindClickableViewInChild(child, x - rect.Left, y - rect.Top);
}
}
}
else if (view != childView)
{
return (view.Enabled && (view.Clickable || view.LongClickable || view.FocusableInTouchMode));
}
return view.FocusableInTouchMode;
}
protected override void OnSizeChanged(int w, int h, int oldw, int oldh)
{
base.OnSizeChanged(w, h, oldw, oldh);
bounds.Set(0, 0, w, h);
rippleBackground.Bounds = bounds;
}
public override bool IsInEditMode
{
get
{
return true;
}
}
public override void Draw(Canvas canvas)
{
bool positionChanged = AdapterPositionChanged();
if (rippleOverlay)
{
if (!positionChanged)
{
rippleBackground.Draw(canvas);
}
base.Draw(canvas);
if (!positionChanged)
{
if (rippleRoundedCorners != 0)
{
Path clipPath = new Path();
RectF rect = new RectF(0, 0, canvas.Width, canvas.Height);
clipPath.AddRoundRect(rect, rippleRoundedCorners, rippleRoundedCorners, Path.Direction.Cw);
canvas.ClipPath(clipPath);
}
canvas.DrawCircle(currentCoords.X, currentCoords.Y, radius, paint);
}
}
else
{
if (!positionChanged)
{
rippleBackground.Draw(canvas);
canvas.DrawCircle(currentCoords.X, currentCoords.Y, radius, paint);
}
base.Draw(canvas);
}
}
public class RadiusProperty : Property
{
public RadiusProperty()
: base(Java.Lang.Class.FromType(typeof(Java.Lang.Float)), "radius")
{
}
public override Java.Lang.Object Get(Java.Lang.Object @object)
{
return ((MaterialRippleLayout)@object).GetRadius();
}
public override void Set(Java.Lang.Object @object, Java.Lang.Object value)
{
((MaterialRippleLayout)@object).SetRadius((float)value);
}
}
private Property radiusProperty = new RadiusProperty();
private float GetRadius()
{
return radius;
}
public void SetRadius(float radius)
{
this.radius = radius;
Invalidate();
}
private class CircleAlphaProperty : Property
{
public CircleAlphaProperty()
: base(Java.Lang.Class.FromType(typeof(Java.Lang.Integer)), "rippleAlpha")
{
}
public override Java.Lang.Object Get(Java.Lang.Object @object)
{
return ((MaterialRippleLayout)@object).GetAlpha();
}
public override void Set(Java.Lang.Object @object, Java.Lang.Object value)
{
((MaterialRippleLayout)@object).SetAlpha((int)value);
}
}
private CircleAlphaProperty circleAlphaProperty = new CircleAlphaProperty();
public int GetAlpha()
{
return paint.Alpha;
}
public void SetAlpha(int rippleAlpha)
{
paint.Alpha = rippleAlpha;
Invalidate();
}
public void SetColor(Color rippleColor)
{
this.rippleColor = rippleColor;
paint.Color = rippleColor;
paint.Alpha = rippleAlpha;
Invalidate();
}
public void SetOverlay(bool rippleOverlay)
{
this.rippleOverlay = rippleOverlay;
}
public void SetDiameter(int rippleDiameter)
{
this.rippleDiameter = rippleDiameter;
}
public void SetDuration(int rippleDuration)
{
this.rippleDuration = rippleDuration;
}
public void SetBackground(Color color)
{
rippleBackground = new ColorDrawable(color);
rippleBackground.Bounds = bounds;
Invalidate();
}
public void SetHover(bool rippleHover)
{
this.rippleHover = rippleHover;
}
public void SetDelayClick(bool rippleDelayClick)
{
this.rippleDelayClick = rippleDelayClick;
}
public void SetFadeDuration(int rippleFadeDuration)
{
this.rippleFadeDuration = rippleFadeDuration;
}
public void SetPersistent(bool ripplePersistent)
{
this.ripplePersistent = ripplePersistent;
}
public void SetInAdapter(bool rippleInAdapter)
{
this.rippleInAdapter = rippleInAdapter;
}
public void SetRoundedCorners(int rippleRoundedCorner)
{
this.rippleRoundedCorners = rippleRoundedCorner;
enableClipPathSupportIfNecessary();
}
public void SetDefaultAlpha(int alpha)
{
this.rippleAlpha = alpha;
paint.Alpha = alpha;
Invalidate();
}
public void PerformRipple()
{
currentCoords = new Point(Width / 2, Height / 2);
StartRipple(null);
}
public void PerformRipple(Point anchor)
{
currentCoords = new Point(anchor.X, anchor.Y);
StartRipple(null);
}
private void enableClipPathSupportIfNecessary()
{
if (Build.VERSION.SdkInt <= BuildVersionCodes.JellyBeanMr1)
{
if (rippleRoundedCorners != 0)
{
layerType = LayerType;
SetLayerType(Android.Views.LayerType.Software, null);
}
else
{
SetLayerType(layerType, null);
}
}
}
private class PerformClickEvent : Java.Lang.Object, Java.Lang.IRunnable
{
public Action<AdapterView> ClickAdapterView { get; set; }
public Action RunDelegate { get; set; }
public void Run()
{
if (RunDelegate != null)
{
RunDelegate();
}
}
}
private class PressedEvent : Java.Lang.Object, Java.Lang.IRunnable
{
public Action<MotionEvent> RunDelegate { get; set; }
private MotionEvent e;
public PressedEvent(MotionEvent e)
{
this.e = e;
}
public void Run()
{
if (RunDelegate != null)
{
RunDelegate(e);
}
}
}
public static float dpToPx(Resources resources, float dp)
{
return TypedValue.ApplyDimension(ComplexUnitType.Dip, dp, resources.DisplayMetrics);
}
public class RippleBuilder
{
private Context context;
private View child;
private Color rippleColor = DEFAULT_COLOR;
private bool rippleOverlay = DEFAULT_RIPPLE_OVERLAY;
private bool rippleHover = DEFAULT_HOVER;
private float rippleDiameter = DEFAULT_DIAMETER_DP;
private int rippleDuration = DEFAULT_DURATION;
private float rippleAlpha = DEFAULT_ALPHA;
private bool rippleDelayClick = DEFAULT_DELAY_CLICK;
private int rippleFadeDuration = DEFAULT_FADE_DURATION;
private bool ripplePersistent = DEFAULT_PERSISTENT;
private Color rippleBackground = DEFAULT_BACKGROUND;
private bool rippleSearchAdapter = DEFAULT_SEARCH_ADAPTER;
private float rippleRoundedCorner = DEFAULT_ROUNDED_CORNERS;
public RippleBuilder(View child)
{
this.child = child;
this.context = child.Context;
}
public RippleBuilder SetColor(Color color)
{
this.rippleColor = color;
return this;
}
public RippleBuilder SetOverlay(bool overlay)
{
this.rippleOverlay = overlay;
return this;
}
public RippleBuilder SetHover(bool hover)
{
this.rippleHover = hover;
return this;
}
public RippleBuilder SetDiameterDp(int diameterDp)
{
this.rippleDiameter = diameterDp;
return this;
}
public RippleBuilder SetDuration(int duration)
{
this.rippleDuration = duration;
return this;
}
public RippleBuilder SetAlpha(float alpha)
{
this.rippleAlpha = 255 * alpha;
return this;
}
public RippleBuilder SetDelayClick(bool delayClick)
{
this.rippleDelayClick = delayClick;
return this;
}
public RippleBuilder SetFadeDuration(int fadeDuration)
{
this.rippleFadeDuration = fadeDuration;
return this;
}
public RippleBuilder SetPersistent(bool persistent)
{
this.ripplePersistent = persistent;
return this;
}
public RippleBuilder SetBackground(Color color)
{
this.rippleBackground = color;
return this;
}
public RippleBuilder SetInAdapter(bool inAdapter)
{
this.rippleSearchAdapter = inAdapter;
return this;
}
public RippleBuilder SetRoundedCorners(int radiusDp)
{
this.rippleRoundedCorner = radiusDp;
return this;
}
public MaterialRippleLayout Create()
{
MaterialRippleLayout layout = new MaterialRippleLayout(context);
layout.SetColor(rippleColor);
layout.SetDefaultAlpha((int)rippleAlpha);
layout.SetDelayClick(rippleDelayClick);
layout.SetDiameter((int)dpToPx(context.Resources, rippleDiameter));
layout.SetDuration(rippleDuration);
layout.SetFadeDuration(rippleFadeDuration);
layout.SetHover(rippleHover);
layout.SetPersistent(ripplePersistent);
layout.SetOverlay(rippleOverlay);
layout.SetBackground(rippleBackground);
layout.SetInAdapter(rippleSearchAdapter);
layout.SetRoundedCorners((int)dpToPx(context.Resources, rippleRoundedCorner));
ViewGroup.LayoutParams param = child.LayoutParameters;
ViewGroup parent = (ViewGroup)child.Parent;
int index = 0;
if (parent != null && parent is MaterialRippleLayout)
{
throw new InvalidOperationException("MaterialRippleLayout could not be created: parent of the view already is a MaterialRippleLayout");
}
if (parent != null)
{
index = parent.IndexOfChild(child);
parent.RemoveView(child);
}
layout.AddView(child, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent));
if (parent != null)
{
parent.AddView(layout, index, param);
}
return layout;
}
}
}
}
| |
// Copyright 2005-2012 Moonfire Games
// Released under the MIT license
// http://mfgames.com/mfgames-cil/license
using System;
using System.Collections.Generic;
using MfGames.HierarchicalPaths;
namespace MfGames.Extensions.System.Collections.Generic
{
/// <summary>
/// Extends IList-derived classes with additional extensions.
/// </summary>
public static class SystemCollectionsGenericListExtensions
{
#region Methods
/// <summary>
/// Gets the last item in the list.
/// </summary>
/// <param name="list">The list.</param>
/// <returns></returns>
public static TItem GetLast<TItem>(this IList<TItem> list)
{
if (list.Count == 0)
{
return default(TItem);
}
return list[list.Count - 1];
}
/// <summary>
/// Chooses a random item from the list using the random from RandomManager.
/// </summary>
public static TItem GetRandom<TItem>(this IList<TItem> list)
{
return GetRandom(list, RandomManager.Random);
}
/// <summary>
/// Chooses a random item from the list using the given random.
/// </summary>
public static TItem GetRandom<TItem>(
this IList<TItem> list,
Random random)
{
// If we have an empty list, then we can't return anything.
if (list.Count == 0)
{
throw new InvalidOperationException(
"Cannot randomly select if there are no items in the list.");
}
// Pick a random item from the list.
int index = random.Next(0, list.Count);
return list[index];
}
/// <summary>
/// Shuffles the contents of the list so that each HierarchicalPath is
/// followed directly by the items underneath it, but still retain the
/// relative order elements that aren't in the hierarchicy.
///
/// For example, given "/z/a", "/z", and "/b", it would sort them into
/// "/z", "/z/a", "/b".
/// </summary>
/// <typeparam name="TItem">The type of the item.</typeparam>
/// <param name="list">The list.</param>
public static void OrderByHierarchicalPath<TItem>(this IList<TItem> list)
where TItem: IHierarchicalPathContainer
{
// If the list is empty or has a single time, we don't have to do
// anything.
int count = list.Count;
if (count <= 1)
{
return;
}
// For the first path, go through the list and perform a bubble
// sort to reorder the elements so that parent elements will be
// before the child ones.
for (int startIndex = 0;
startIndex < count - 1;
startIndex++)
{
// Pull out the path at this index.
HierarchicalPath startPath = list[startIndex].HierarchicalPath;
bool startOver = false;
// Go through all the items after the start index.
for (int testIndex = startIndex + 1;
testIndex < count;
testIndex++)
{
// Pull out the test path for comparison.
HierarchicalPath testPath = list[testIndex].HierarchicalPath;
// Check for equal levels since we don't swap equal-level
// elements.
if (startPath.Count == testPath.Count)
{
continue;
}
// Check to see which one has the least number of elements
// since that will be "higher" on the list.
if (startPath.StartsWith(testPath))
{
// We have to insert the parent before the current start
// index, then start processing again.
TItem item = list[testIndex];
list.RemoveAt(testIndex);
list.Insert(startIndex, item);
// Decrement the start index to start again.
startOver = true;
break;
}
}
// If we are starting over, we shift the index back slight and
// start the outer loop again.
if (startOver)
{
startIndex--;
break;
}
}
// The second pass involves grouping the related items together.
// This is a 2-loop process. The first loop is the item we are
// comparing against. The second looks for items that are underneath
// the test path and brings them before items that are not.
for (int startIndex = 0;
startIndex < count - 1;
startIndex++)
{
// Pull out the path at this index.
HierarchicalPath startPath = list[startIndex].HierarchicalPath;
// Go through all the items after the start index.
int lastChildIndex = startIndex;
bool foundNonChild = false;
for (int testIndex = startIndex + 1;
testIndex < count;
testIndex++)
{
// Pull out the test path for comparison.
HierarchicalPath testPath = list[testIndex].HierarchicalPath;
// Check to see if testPath is underneath the startPath.
if (testPath.StartsWith(startPath))
{
// Check to see if we have a non-child between the last
// child path and this one.
if (foundNonChild)
{
// Increment the last child index since we'll be
// inserting this new item there.
lastChildIndex++;
// Remove the item from the test position and insert
// it into the updated child index.
TItem item = list[testIndex];
list.RemoveAt(testIndex);
list.Insert(lastChildIndex, item);
// Move the index back to it (and a bit more to
// handle the for() loop incrementer.
testIndex = lastChildIndex - 1;
// Clear out the non child flag.
foundNonChild = false;
}
else
{
// This is a child item, just mark it and continue.
lastChildIndex = testIndex;
}
}
else
{
// This isn't a child path
foundNonChild = true;
}
}
}
}
/// <summary>
/// Pops the first item off the specified list.
/// </summary>
/// <typeparam name="TItem">The type of the item.</typeparam>
/// <param name="list">The list.</param>
/// <returns>The first item in the list.</returns>
public static TItem Pop<TItem>(this IList<TItem> list)
{
TItem first = list[0];
list.RemoveAt(0);
return first;
}
/// <summary>
/// Pushes the specified item into the beginning of the list.
/// </summary>
/// <typeparam name="TItem">The type of the item.</typeparam>
/// <param name="list">The list.</param>
/// <param name="item">The item.</param>
public static void Push<TItem>(
this IList<TItem> list,
TItem item)
{
list.Insert(0, item);
}
/// <summary>
/// Removes the last item in the list.
/// </summary>
/// <typeparam name="TItem">The type of the item.</typeparam>
/// <param name="list">The list.</param>
/// <returns></returns>
public static TItem RemoveLast<TItem>(this IList<TItem> list)
{
if (list.Count == 0)
{
return default(TItem);
}
TItem last = list[list.Count - 1];
list.RemoveAt(list.Count - 1);
return last;
}
#endregion
}
}
| |
//
// https://github.com/mythz/ServiceStack.Redis
// ServiceStack.Redis: ECMA CLI Binding to the Redis key-value storage system
//
// Authors:
// Demis Bellot (demis.bellot@gmail.com)
//
// Copyright 2010 Liquidbit Ltd.
//
// Licensed under the same terms of Redis and ServiceStack: new BSD license.
//
using System;
using System.Collections.Generic;
using System.Linq;
using ServiceStack.DesignPatterns.Model;
using ServiceStack.Redis.Support;
using ServiceStack.Text;
namespace ServiceStack.Redis
{
public partial class RedisClient : IRedisClient
{
public IHasNamed<IRedisSortedSet> SortedSets { get; set; }
internal class RedisClientSortedSets
: IHasNamed<IRedisSortedSet>
{
private readonly RedisClient client;
public RedisClientSortedSets(RedisClient client)
{
this.client = client;
}
public IRedisSortedSet this[string setId]
{
get
{
return new RedisClientSortedSet(client, setId);
}
set
{
var col = this[setId];
col.Clear();
col.CopyTo(value.ToArray(), 0);
}
}
}
public static double GetLexicalScore(string value)
{
if (string.IsNullOrEmpty(value))
return 0;
var lexicalValue = 0;
if (value.Length >= 1)
lexicalValue += value[0] * (int)Math.Pow(256, 3);
if (value.Length >= 2)
lexicalValue += value[1] * (int)Math.Pow(256, 2);
if (value.Length >= 3)
lexicalValue += value[2] * (int)Math.Pow(256, 1);
if (value.Length >= 4)
lexicalValue += value[3];
return lexicalValue;
}
public bool AddItemToSortedSet(string setId, string value)
{
return AddItemToSortedSet(setId, value, GetLexicalScore(value));
}
public bool AddItemToSortedSet(string setId, string value, double score)
{
return base.ZAdd(setId, score, value.ToUtf8Bytes()) == Success;
}
public bool AddRangeToSortedSet(string setId, List<string> values, double score)
{
var pipeline = CreatePipelineCommand();
var uSetId = setId.ToUtf8Bytes();
var uScore = score.ToUtf8Bytes();
foreach (var value in values)
{
pipeline.WriteCommand(Commands.ZAdd, uSetId, uScore, value.ToUtf8Bytes());
}
pipeline.Flush();
var success = pipeline.ReadAllAsIntsHaveSuccess();
return success;
}
public bool RemoveItemFromSortedSet(string setId, string value)
{
return base.ZRem(setId, value.ToUtf8Bytes()) == Success;
}
public string PopItemWithLowestScoreFromSortedSet(string setId)
{
//TODO: this should be atomic
var topScoreItemBytes = base.ZRange(setId, FirstElement, 1);
if (topScoreItemBytes.Length == 0) return null;
base.ZRem(setId, topScoreItemBytes[0]);
return topScoreItemBytes[0].FromUtf8Bytes();
}
public string PopItemWithHighestScoreFromSortedSet(string setId)
{
//TODO: this should be atomic
var topScoreItemBytes = base.ZRevRange(setId, FirstElement, 1);
if (topScoreItemBytes.Length == 0) return null;
base.ZRem(setId, topScoreItemBytes[0]);
return topScoreItemBytes[0].FromUtf8Bytes();
}
public bool SortedSetContainsItem(string setId, string value)
{
return base.ZRank(setId, value.ToUtf8Bytes()) != -1;
}
public double IncrementItemInSortedSet(string setId, string value, double incrementBy)
{
return base.ZIncrBy(setId, incrementBy, value.ToUtf8Bytes());
}
public int GetItemIndexInSortedSet(string setId, string value)
{
return base.ZRank(setId, value.ToUtf8Bytes());
}
public int GetItemIndexInSortedSetDesc(string setId, string value)
{
return base.ZRevRank(setId, value.ToUtf8Bytes());
}
public List<string> GetAllItemsFromSortedSet(string setId)
{
var multiDataList = base.ZRange(setId, FirstElement, LastElement);
return multiDataList.ToStringList();
}
public List<string> GetAllItemsFromSortedSetDesc(string setId)
{
var multiDataList = base.ZRevRange(setId, FirstElement, LastElement);
return multiDataList.ToStringList();
}
public List<string> GetRangeFromSortedSet(string setId, int fromRank, int toRank)
{
var multiDataList = base.ZRange(setId, fromRank, toRank);
return multiDataList.ToStringList();
}
public List<string> GetRangeFromSortedSetDesc(string setId, int fromRank, int toRank)
{
var multiDataList = base.ZRevRange(setId, fromRank, toRank);
return multiDataList.ToStringList();
}
public IDictionary<string, double> GetAllWithScoresFromSortedSet(string setId)
{
var multiDataList = base.ZRangeWithScores(setId, FirstElement, LastElement);
return CreateSortedScoreMap(multiDataList);
}
public IDictionary<string, double> GetRangeWithScoresFromSortedSet(string setId, int fromRank, int toRank)
{
var multiDataList = base.ZRangeWithScores(setId, fromRank, toRank);
return CreateSortedScoreMap(multiDataList);
}
public IDictionary<string, double> GetRangeWithScoresFromSortedSetDesc(string setId, int fromRank, int toRank)
{
var multiDataList = base.ZRevRangeWithScores(setId, fromRank, toRank);
return CreateSortedScoreMap(multiDataList);
}
private static IDictionary<string, double> CreateSortedScoreMap(byte[][] multiDataList)
{
var map = new OrderedDictionary<string, double>();
for (var i = 0; i < multiDataList.Length; i += 2)
{
var key = multiDataList[i].FromUtf8Bytes();
double value;
double.TryParse(multiDataList[i + 1].FromUtf8Bytes(), out value);
map[key] = value;
}
return map;
}
public List<string> GetRangeFromSortedSetByLowestScore(string setId, string fromStringScore, string toStringScore)
{
return GetRangeFromSortedSetByLowestScore(setId, fromStringScore, toStringScore, null, null);
}
public List<string> GetRangeFromSortedSetByLowestScore(string setId, string fromStringScore, string toStringScore, int? skip, int? take)
{
var fromScore = GetLexicalScore(fromStringScore);
var toScore = GetLexicalScore(toStringScore);
return GetRangeFromSortedSetByLowestScore(setId, fromScore, toScore, skip, take);
}
public List<string> GetRangeFromSortedSetByLowestScore(string setId, double fromScore, double toScore)
{
return GetRangeFromSortedSetByLowestScore(setId, fromScore, toScore, null, null);
}
public List<string> GetRangeFromSortedSetByLowestScore(string setId, double fromScore, double toScore, int? skip, int? take)
{
var multiDataList = base.ZRangeByScore(setId, fromScore, toScore, skip, take);
return multiDataList.ToStringList();
}
public IDictionary<string, double> GetRangeWithScoresFromSortedSetByLowestScore(string setId, string fromStringScore, string toStringScore)
{
return GetRangeWithScoresFromSortedSetByLowestScore(setId, fromStringScore, toStringScore, null, null);
}
public IDictionary<string, double> GetRangeWithScoresFromSortedSetByLowestScore(string setId, string fromStringScore, string toStringScore, int? skip, int? take)
{
var fromScore = GetLexicalScore(fromStringScore);
var toScore = GetLexicalScore(toStringScore);
return GetRangeWithScoresFromSortedSetByLowestScore(setId, fromScore, toScore, skip, take);
}
public IDictionary<string, double> GetRangeWithScoresFromSortedSetByLowestScore(string setId, double fromScore, double toScore)
{
return GetRangeWithScoresFromSortedSetByLowestScore(setId, fromScore, toScore, null, null);
}
public IDictionary<string, double> GetRangeWithScoresFromSortedSetByLowestScore(string setId, double fromScore, double toScore, int? skip, int? take)
{
var multiDataList = base.ZRangeByScoreWithScores(setId, fromScore, toScore, skip, take);
return CreateSortedScoreMap(multiDataList);
}
public List<string> GetRangeFromSortedSetByHighestScore(string setId, string fromStringScore, string toStringScore)
{
return GetRangeFromSortedSetByHighestScore(setId, fromStringScore, toStringScore, null, null);
}
public List<string> GetRangeFromSortedSetByHighestScore(string setId, string fromStringScore, string toStringScore, int? skip, int? take)
{
var fromScore = GetLexicalScore(fromStringScore);
var toScore = GetLexicalScore(toStringScore);
return GetRangeFromSortedSetByHighestScore(setId, fromScore, toScore, skip, take);
}
public List<string> GetRangeFromSortedSetByHighestScore(string setId, double fromScore, double toScore)
{
return GetRangeFromSortedSetByHighestScore(setId, fromScore, toScore, null, null);
}
public List<string> GetRangeFromSortedSetByHighestScore(string setId, double fromScore, double toScore, int? skip, int? take)
{
var multiDataList = base.ZRevRangeByScore(setId, fromScore, toScore, skip, take);
return multiDataList.ToStringList();
}
public IDictionary<string, double> GetRangeWithScoresFromSortedSetByHighestScore(string setId, string fromStringScore, string toStringScore)
{
return GetRangeWithScoresFromSortedSetByHighestScore(setId, fromStringScore, toStringScore, null, null);
}
public IDictionary<string, double> GetRangeWithScoresFromSortedSetByHighestScore(string setId, string fromStringScore, string toStringScore, int? skip, int? take)
{
var fromScore = GetLexicalScore(fromStringScore);
var toScore = GetLexicalScore(toStringScore);
return GetRangeWithScoresFromSortedSetByHighestScore(setId, fromScore, toScore, skip, take);
}
public IDictionary<string, double> GetRangeWithScoresFromSortedSetByHighestScore(string setId, double fromScore, double toScore)
{
return GetRangeWithScoresFromSortedSetByHighestScore(setId, fromScore, toScore, null, null);
}
public IDictionary<string, double> GetRangeWithScoresFromSortedSetByHighestScore(string setId, double fromScore, double toScore, int? skip, int? take)
{
var multiDataList = base.ZRevRangeByScoreWithScores(setId, fromScore, toScore, skip, take);
return CreateSortedScoreMap(multiDataList);
}
public int RemoveRangeFromSortedSet(string setId, int minRank, int maxRank)
{
return base.ZRemRangeByRank(setId, minRank, maxRank);
}
public int RemoveRangeFromSortedSetByScore(string setId, double fromScore, double toScore)
{
return base.ZRemRangeByScore(setId, fromScore, toScore);
}
public int GetSortedSetCount(string setId)
{
return base.ZCard(setId);
}
public double GetItemScoreInSortedSet(string setId, string value)
{
return base.ZScore(setId, value.ToUtf8Bytes());
}
public int StoreIntersectFromSortedSets(string intoSetId, params string[] setIds)
{
return base.ZInterStore(intoSetId, setIds);
}
public int StoreUnionFromSortedSets(string intoSetId, params string[] setIds)
{
return base.ZUnionStore(intoSetId, setIds);
}
}
}
| |
// 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.IO;
using System.Diagnostics;
using System.Xml.XPath;
using System.Xml.Schema;
using System.Collections;
using System.Threading.Tasks;
namespace System.Xml
{
/// <summary>
/// Implementations of XmlRawWriter are intended to be wrapped by the XmlWellFormedWriter. The
/// well-formed writer performs many checks in behalf of the raw writer, and keeps state that the
/// raw writer otherwise would have to keep. Therefore, the well-formed writer will call the
/// XmlRawWriter using the following rules, in order to make raw writers easier to implement:
///
/// 1. The well-formed writer keeps a stack of element names, and always calls
/// WriteEndElement(string, string, string) instead of WriteEndElement().
/// 2. The well-formed writer tracks namespaces, and will pass himself in via the
/// WellformedWriter property. It is used in the XmlRawWriter's implementation of IXmlNamespaceResolver.
/// Thus, LookupPrefix does not have to be implemented.
/// 3. The well-formed writer tracks write states, so the raw writer doesn't need to.
/// 4. The well-formed writer will always call StartElementContent.
/// 5. The well-formed writer will always call WriteNamespaceDeclaration for namespace nodes,
/// rather than calling WriteStartAttribute(). If the writer is supporting namespace declarations in chunks
/// (SupportsNamespaceDeclarationInChunks is true), the XmlWellFormedWriter will call WriteStartNamespaceDeclaration,
/// then any method that can be used to write out a value of an attribute (WriteString, WriteChars, WriteRaw, WriteCharEntity...)
/// and then WriteEndNamespaceDeclaration - instead of just a single WriteNamespaceDeclaration call. This feature will be
/// supported by raw writers serializing to text that wish to preserve the attribute value escaping etc.
/// 6. The well-formed writer guarantees a well-formed document, including correct call sequences,
/// correct namespaces, and correct document rule enforcement.
/// 7. All element and attribute names will be fully resolved and validated. Null will never be
/// passed for any of the name parts.
/// 8. The well-formed writer keeps track of xml:space and xml:lang.
/// 9. The well-formed writer verifies NmToken, Name, and QName values and calls WriteString().
/// </summary>
internal abstract partial class XmlRawWriter : XmlWriter
{
//
// XmlWriter implementation
//
// Raw writers do not have to track whether this is a well-formed document.
public override Task WriteStartDocumentAsync()
{
throw new InvalidOperationException(SR.Xml_InvalidOperation);
}
public override Task WriteStartDocumentAsync(bool standalone)
{
throw new InvalidOperationException(SR.Xml_InvalidOperation);
}
public override Task WriteEndDocumentAsync()
{
throw new InvalidOperationException(SR.Xml_InvalidOperation);
}
public override Task WriteDocTypeAsync(string name, string pubid, string sysid, string subset)
{
return Task.CompletedTask;
}
// Raw writers do not have to keep a stack of element names.
public override Task WriteEndElementAsync()
{
throw new InvalidOperationException(SR.Xml_InvalidOperation);
}
// Raw writers do not have to keep a stack of element names.
public override Task WriteFullEndElementAsync()
{
throw new InvalidOperationException(SR.Xml_InvalidOperation);
}
// By default, convert base64 value to string and call WriteString.
public override Task WriteBase64Async(byte[] buffer, int index, int count)
{
if (base64Encoder == null)
{
base64Encoder = new XmlRawWriterBase64Encoder(this);
}
// Encode will call WriteRaw to write out the encoded characters
return base64Encoder.EncodeAsync(buffer, index, count);
}
// Raw writers do not have to verify NmToken values.
public override Task WriteNmTokenAsync(string name)
{
throw new InvalidOperationException(SR.Xml_InvalidOperation);
}
// Raw writers do not have to verify Name values.
public override Task WriteNameAsync(string name)
{
throw new InvalidOperationException(SR.Xml_InvalidOperation);
}
// Raw writers do not have to verify QName values.
public override Task WriteQualifiedNameAsync(string localName, string ns)
{
throw new InvalidOperationException(SR.Xml_InvalidOperation);
}
// Forward call to WriteString(string).
public override Task WriteCDataAsync(string text)
{
return WriteStringAsync(text);
}
// Forward call to WriteString(string).
public override Task WriteCharEntityAsync(char ch)
{
return WriteStringAsync(new string(new char[] { ch }));
}
// Forward call to WriteString(string).
public override Task WriteSurrogateCharEntityAsync(char lowChar, char highChar)
{
return WriteStringAsync(new string(new char[] { lowChar, highChar }));
}
// Forward call to WriteString(string).
public override Task WriteWhitespaceAsync(string ws)
{
return WriteStringAsync(ws);
}
// Forward call to WriteString(string).
public override Task WriteCharsAsync(char[] buffer, int index, int count)
{
return WriteStringAsync(new string(buffer, index, count));
}
// Forward call to WriteString(string).
public override Task WriteRawAsync(char[] buffer, int index, int count)
{
return WriteStringAsync(new string(buffer, index, count));
}
// Forward call to WriteString(string).
public override Task WriteRawAsync(string data)
{
return WriteStringAsync(data);
}
// Copying to XmlRawWriter is not currently supported.
public override Task WriteAttributesAsync(XmlReader reader, bool defattr)
{
throw new InvalidOperationException(SR.Xml_InvalidOperation);
}
public override Task WriteNodeAsync(XmlReader reader, bool defattr)
{
throw new InvalidOperationException(SR.Xml_InvalidOperation);
}
public override Task WriteNodeAsync(System.Xml.XPath.XPathNavigator navigator, bool defattr)
{
throw new InvalidOperationException(SR.Xml_InvalidOperation);
}
//
// XmlRawWriter methods and properties
//
// Write the xml declaration. This must be the first call.
internal virtual Task WriteXmlDeclarationAsync(XmlStandalone standalone)
{
return Task.CompletedTask;
}
internal virtual Task WriteXmlDeclarationAsync(string xmldecl)
{
return Task.CompletedTask;
}
// Called after an element's attributes have been enumerated, but before any children have been
// enumerated. This method must always be called, even for empty elements.
internal virtual Task StartElementContentAsync()
{
throw new NotImplementedException();
}
// WriteEndElement() and WriteFullEndElement() overloads, in which caller gives the full name of the
// element, so that raw writers do not need to keep a stack of element names. This method should
// always be called instead of WriteEndElement() or WriteFullEndElement() without parameters.
internal virtual Task WriteEndElementAsync(string prefix, string localName, string ns)
{
throw new NotImplementedException();
}
internal virtual Task WriteFullEndElementAsync(string prefix, string localName, string ns)
{
return WriteEndElementAsync(prefix, localName, ns);
}
internal virtual async Task WriteQualifiedNameAsync(string prefix, string localName, string ns)
{
if (prefix.Length != 0)
{
await WriteStringAsync(prefix).ConfigureAwait(false);
await WriteStringAsync(":").ConfigureAwait(false);
}
await WriteStringAsync(localName).ConfigureAwait(false);
}
// This method must be called instead of WriteStartAttribute() for namespaces.
internal virtual Task WriteNamespaceDeclarationAsync(string prefix, string ns)
{
throw new NotImplementedException();
}
internal virtual Task WriteStartNamespaceDeclarationAsync(string prefix)
{
throw new NotSupportedException();
}
internal virtual Task WriteEndNamespaceDeclarationAsync()
{
throw new NotSupportedException();
}
// This is called when the remainder of a base64 value should be output.
internal virtual Task WriteEndBase64Async()
{
// The Flush will call WriteRaw to write out the rest of the encoded characters
return base64Encoder.FlushAsync();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using GongSolutions.Wpf.DragDrop;
using log4net;
using MoreLinq;
using POESKillTree.Common;
using POESKillTree.Common.ViewModels;
using POESKillTree.Localization;
using POESKillTree.Model;
using POESKillTree.Model.Builds;
using POESKillTree.Model.Serialization;
using POESKillTree.SkillTreeFiles;
using POESKillTree.Utils;
using POESKillTree.Utils.Extensions;
using POESKillTree.Utils.Wpf;
using POESKillTree.Controls.Dialogs;
using Newtonsoft.Json;
using System.Text;
namespace POESKillTree.ViewModels.Builds
{
public class ClassFilterItem
{
public string CharacterClass { get; }
public string AscendancyClass { get; }
public ClassFilterItem(string characterClass, string ascendancyClass)
{
CharacterClass = characterClass;
AscendancyClass = ascendancyClass;
}
public override string ToString()
{
return CharacterClass + " " + AscendancyClass;
}
}
public class BuildsViewModelProxy : BindingProxy<BuildsControlViewModel>
{
}
/// <summary>
/// View model providing access to and operations on builds.
/// </summary>
public class BuildsControlViewModel : Notifier
{
private static readonly ILog Log = LogManager.GetLogger(typeof(BuildsControlViewModel));
private static readonly ClassFilterItem NoFilterItem = new ClassFilterItem(L10n.Message("All"), null);
private readonly IExtendedDialogCoordinator _dialogCoordinator;
private readonly BuildValidator _buildValidator;
private readonly FileSystemWatcher _fileSystemWatcher;
private readonly SynchronizationContext _synchronizationContext = SynchronizationContext.Current;
private readonly SimpleMonitor _changingFileSystemMonitor = new SimpleMonitor();
private int _changingFileSystemCounter;
/// <summary>
/// Gets the root folder of the build folder tree.
/// </summary>
public IBuildFolderViewModel BuildRoot { get; }
/// <summary>
/// Gets the drop handler that handles drag and drop for the build tree.
/// </summary>
public IDropTarget DropHandler { get; }
public ICommand NewFolderCommand { get; }
public ICommand NewBuildCommand { get; }
public ICommand DeleteCommand { get; }
public ICommand OpenBuildCommand { get; }
public ICommand SaveBuildCommand { get; }
public ICommand SaveBuildAsCommand { get; }
public ICommand SaveAllBuildsCommand { get; }
public ICommand RevertBuildCommand { get; }
public ICommand MoveUpCommand { get; }
public ICommand MoveDownCommand { get; }
public ICommand EditCommand { get; }
public ICommand CutCommand { get; }
public ICommand CopyCommand { get; }
public ICommand PasteCommand { get; }
public ICommand ReloadCommand { get; }
public ICommand OpenBuildsSavePathCommand { get; }
public ICommand ExpandAllCommand { get; }
public ICommand CollapseAllCommand { get; }
public ICommand ExportCurrentToClipboardCommand { get; }
public ICommand ImportCurrentFromClipboardCommand { get; }
public ICommand ExportGGGBuildFile { get; }
public ICommand ImportGGGBuildFile { get; }
public IPersistentData PersistentData { get; }
private BuildViewModel _currentBuild;
/// <summary>
/// Gets or sets the currently opened build.
/// </summary>
public BuildViewModel CurrentBuild
{
get { return _currentBuild; }
set
{
SetProperty(ref _currentBuild, value, () =>
{
if (CurrentBuild != null)
CurrentBuild.CurrentlyOpen = true;
PersistentData.CurrentBuild = CurrentBuild?.Build;
}, b =>
{
if (CurrentBuild != null)
CurrentBuild.CurrentlyOpen = false;
});
}
}
private IBuildViewModel _selectedBuild;
/// <summary>
/// Gets or sets the currently selected build.
/// </summary>
public IBuildViewModel SelectedBuild
{
get { return _selectedBuild; }
set
{
SetProperty(ref _selectedBuild, value, () =>
{
if (SelectedBuild != null)
SelectedBuild.IsSelected = true;
PersistentData.SelectedBuild = SelectedBuild?.Build;
}, b =>
{
if (SelectedBuild != null)
SelectedBuild.IsSelected = false;
});
}
}
private ClassFilterItem _classFilter;
/// <summary>
/// Gets or sets the class builds must be of to be visible
/// (L10n("All") shows everything).
/// </summary>
public ClassFilterItem ClassFilter
{
get { return _classFilter; }
set { SetProperty(ref _classFilter, value, () => BuildRoot.ApplyFilter()); }
}
private string _textFilter;
/// <summary>
/// Gets or sets a string build names must contain to be visible.
/// </summary>
public string TextFilter
{
get { return _textFilter; }
set { SetProperty(ref _textFilter, value, () => BuildRoot.ApplyFilter()); }
}
private IBuildViewModel _buildClipboard;
private bool _clipboardIsCopy;
private ISkillTree _skillTree;
/// <summary>
/// Sets the <see cref="ISkillTree"/> instance.
/// </summary>
public ISkillTree SkillTree
{
private get { return _skillTree; }
set { SetProperty(ref _skillTree, value, () => BuildRoot.SkillTree = SkillTree); }
}
public IReadOnlyList<ClassFilterItem> ClassFilterItems { get; }
public BuildsControlViewModel(IExtendedDialogCoordinator dialogCoordinator, IPersistentData persistentData, ISkillTree skillTree)
{
_dialogCoordinator = dialogCoordinator;
PersistentData = persistentData;
DropHandler = new CustomDropHandler(this);
_buildValidator = new BuildValidator(PersistentData.Options);
BuildRoot = new BuildFolderViewModel(persistentData.RootBuild, Filter, BuildOnCollectionChanged);
_fileSystemWatcher = new FileSystemWatcher
{
Path = PersistentData.Options.BuildsSavePath,
IncludeSubdirectories = true,
NotifyFilter = NotifyFilters.DirectoryName | NotifyFilters.FileName | NotifyFilters.LastWrite
};
_fileSystemWatcher.Error += FileSystemWatcherOnError;
_fileSystemWatcher.Changed += FileSystemWatcherOnChanged;
_fileSystemWatcher.Created += FileSystemWatcherOnChanged;
_fileSystemWatcher.Deleted += FileSystemWatcherOnChanged;
_fileSystemWatcher.Renamed += FileSystemWatcherOnChanged;
_fileSystemWatcher.EnableRaisingEvents = true;
// The monitor alone is not enough because delays are necessary and those shouldn't block other save
// operations, which would happen if delays are awaited directly in the save method.
// It could be done awaited with .ConfigureAwait(false) if SimpleMonitor would be thread safe.
_changingFileSystemMonitor.Entered += (sender, args) => _changingFileSystemCounter++;
_changingFileSystemMonitor.Freed += async (sender, args) =>
{
// Wait because FileSystemWatcherOnChanged calls are delayed a bit.
await Task.Delay(2000);
// This is a counter and not boolean because other save operations may happen while waiting on delay.
_changingFileSystemCounter--;
};
CurrentBuild = TreeFindBuildViewModel(PersistentData.CurrentBuild);
SelectedBuild = TreeFindBuildViewModel(PersistentData.SelectedBuild);
PersistentData.PropertyChanged += PersistentDataOnPropertyChanged;
PersistentData.Options.PropertyChanged += OptionsOnPropertyChanged;
NewFolderCommand = new AsyncRelayCommand<IBuildFolderViewModel>(
NewFolder,
vm => vm != null && _buildValidator.CanHaveSubfolder(vm));
NewBuildCommand = new RelayCommand<IBuildFolderViewModel>(NewBuild);
DeleteCommand = new AsyncRelayCommand<IBuildViewModel>(
Delete,
o => o != BuildRoot);
OpenBuildCommand = new AsyncRelayCommand<BuildViewModel>(
OpenBuild,
b => b != null && (b != CurrentBuild || b.Build.IsDirty));
SaveBuildCommand = new AsyncRelayCommand<BuildViewModel>(
SaveBuild,
b => b != null && b.Build.IsDirty);
SaveBuildAsCommand = new AsyncRelayCommand<BuildViewModel>(SaveBuildAs);
SaveAllBuildsCommand = new AsyncRelayCommand(
SaveAllBuilds,
() => TreeFind<BuildViewModel>(b => b.Build.IsDirty, BuildRoot) != null);
RevertBuildCommand = new RelayCommand<BuildViewModel>(
build => build.Build.RevertChanges(),
b => b != null && b.Build.IsDirty && b.Build.CanRevert);
MoveUpCommand = new RelayCommand<IBuildViewModel>(
MoveUp,
o => o != BuildRoot && o.Parent.Children.IndexOf(o) > 0);
MoveDownCommand = new RelayCommand<IBuildViewModel>(
MoveDown,
o => o != BuildRoot && o.Parent.Children.IndexOf(o) < o.Parent.Children.Count - 1);
EditCommand = new AsyncRelayCommand<IBuildViewModel>(Edit);
CutCommand = new AsyncRelayCommand<IBuildViewModel>(
Cut,
b => b != BuildRoot && b != CurrentBuild);
CopyCommand = new RelayCommand<IBuildViewModel<PoEBuild>>(Copy);
PasteCommand = new AsyncRelayCommand<IBuildViewModel>(Paste, CanPaste);
ReloadCommand = new AsyncRelayCommand(Reload);
OpenBuildsSavePathCommand = new RelayCommand(() => Process.Start(PersistentData.Options.BuildsSavePath));
ExpandAllCommand = new RelayCommand(ExpandAll);
CollapseAllCommand = new RelayCommand(CollapseAll);
ExportCurrentToClipboardCommand = new RelayCommand(() => CopyToClipboard(CurrentBuild.Build));
ImportCurrentFromClipboardCommand = new AsyncRelayCommand(ImportCurrentFromClipboard, CanPasteFromClipboard);
ExportGGGBuildFile = new RelayCommand<IBuildFolderViewModel>(ExportGGGBuild);
ImportGGGBuildFile = new RelayCommand(() => ImportGGGBuild());
SkillTree = skillTree;
ClassFilterItems = GenerateAscendancyClassItems(SkillTree.AscendancyClasses).ToList();
ClassFilter = NoFilterItem;
}
#region GGG Builds File Export/Import
private async void ExportGGGBuild(IBuildFolderViewModel target)
{
var build = new GGGBuild()
{
Name = target.Build.Name,
Version = Properties.Version.GGGPatchVersion,
Parts = new List<GGGBuildPart>()
};
foreach (var c in target.Children)
if (!c.GetType().Equals(typeof(BuildFolderViewModel)))
build.Parts.Add(new GGGBuildPart() { Label = c.Build.Name, Link = ((PoEBuild)c.Build).TreeUrl });
var dialogSettings = new FileSelectorDialogSettings
{
DefaultPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
IsFolderPicker = true,
};
var path = await _dialogCoordinator.ShowFileSelectorAsync(this,
L10n.Message("Select save directory"),
L10n.Message("Select the directory where you want to export this build structure."),
dialogSettings);
if (path == null)
return;
path = Path.Combine(path, $"{SerializationUtils.EncodeFileName(build.Name)}.build");
byte[] jsonEncodedText = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(build));
using (FileStream stream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None, bufferSize: jsonEncodedText.Length, useAsync: true))
{
await stream.WriteAsync(jsonEncodedText, 0, jsonEncodedText.Length);
}
}
private void ImportGGGBuild()
{
throw new NotImplementedException();
}
#endregion
private IEnumerable<ClassFilterItem> GenerateAscendancyClassItems(IAscendancyClasses ascendancyClasses)
{
yield return NoFilterItem;
foreach (var nameToContent in CharacterNames.NameToContent)
{
var charClass = nameToContent.Value;
yield return new ClassFilterItem(charClass, null);
foreach (var ascClass in ascendancyClasses.AscendancyClassesForCharacter(charClass))
{
yield return new ClassFilterItem(charClass, ascClass);
}
}
}
#region Event handlers
private void PersistentDataOnPropertyChanged(object sender, PropertyChangedEventArgs args)
{
switch (args.PropertyName)
{
case nameof(IPersistentData.CurrentBuild):
if (CurrentBuild?.Build == PersistentData.CurrentBuild)
return;
CurrentBuild = PersistentData.CurrentBuild == null
? null
: TreeFindBuildViewModel(PersistentData.CurrentBuild);
break;
case nameof(IPersistentData.SelectedBuild):
if (SelectedBuild?.Build == PersistentData.SelectedBuild)
return;
SelectedBuild = PersistentData.SelectedBuild == null
? null
: TreeFindBuildViewModel(PersistentData.SelectedBuild);
break;
}
}
private void OptionsOnPropertyChanged(object sender, PropertyChangedEventArgs args)
{
switch (args.PropertyName)
{
case nameof(Options.BuildsSavePath):
Directory.CreateDirectory(PersistentData.Options.BuildsSavePath);
_fileSystemWatcher.Path = PersistentData.Options.BuildsSavePath;
break;
}
}
private void FileSystemWatcherOnError(object sender, ErrorEventArgs errorEventArgs)
{
Log.Error($"File system watcher for {_fileSystemWatcher.Path} stopped working",
errorEventArgs.GetException());
}
private void FileSystemWatcherOnChanged(object sender, EventArgs fileSystemEventArgs)
{
// Only continue if all operations done by ourselves and the delay periods after them are finished.
if (_changingFileSystemCounter > 0)
return;
_synchronizationContext.Post(async _ => await FileSystemWatcherOnChanged(), null);
}
private async Task FileSystemWatcherOnChanged()
{
// There might be multiple changes, only react to the first one.
// Events for changes that take some time should occur before they are reenabled.
_fileSystemWatcher.EnableRaisingEvents = false;
var message = L10n.Message("Files in your build save directory have been changed.\n" +
"Do you want to reload all builds from the file system?");
if (GetDirtyBuilds().Any())
{
message += L10n.Message("\nAll unsaved changes will be lost.");
}
message += L10n.Message("\n\nYou can also reload through the 'File' menu.");
var result =
await _dialogCoordinator.ShowQuestionAsync(this, message, title: L10n.Message("Builds changed"));
if (result == MessageBoxResult.Yes)
{
await PersistentData.ReloadBuildsAsync();
}
_fileSystemWatcher.EnableRaisingEvents = true;
}
#endregion
#region Command methods
private async Task NewFolder(IBuildFolderViewModel folder)
{
var name = await _dialogCoordinator.ShowValidatingInputDialogAsync(this,
L10n.Message("New Folder"),
L10n.Message("Enter the name of the new folder."),
"",
s => _buildValidator.ValidateNewFolderName(s, folder));
if (string.IsNullOrWhiteSpace(name))
return;
var newFolder = new BuildFolderViewModel(new BuildFolder {Name = name}, Filter, BuildOnCollectionChanged);
folder.Children.Add(newFolder);
await SaveBuildToFile(newFolder);
}
public void NewBuild(IBuildFolderViewModel folder)
{
var name = Util.FindDistinctName(SerializationConstants.DefaultBuildName,
folder.Children.Select(b => b.Build.Name));
var build = new BuildViewModel(new PoEBuild { Name = name }, Filter);
folder.Children.Add(build);
CurrentBuild = build;
}
private async Task Delete(IBuildViewModel build)
{
if (build == null)
return;
if (TreeFind<BuildViewModel>(b => b == CurrentBuild, build) != null)
{
await _dialogCoordinator.ShowInfoAsync(this,
L10n.Message("The currently opened build can not be deleted."));
return;
}
if (build is IBuildFolderViewModel)
{
var result = await _dialogCoordinator.ShowQuestionAsync(this,
string.Format(L10n.Message("This will delete the build folder \"{0}\" and all its contents.\n"),
build.Build.Name) + L10n.Message("Do you want to continue?"));
if (result != MessageBoxResult.Yes)
return;
}
build.IsSelected = false;
build.Parent.IsSelected = true;
build.Parent.Children.Remove(build);
await DeleteBuildFile(build);
}
private async Task OpenBuild(BuildViewModel build)
{
if (build != CurrentBuild)
{
CurrentBuild = build;
return;
}
if (!build.Build.IsDirty || !build.Build.CanRevert)
return;
var result = await _dialogCoordinator.ShowQuestionAsync(this,
L10n.Message("This build is currently opened but has unsaved changes.\n")
+ L10n.Message("Do you want to discard all changes made to it since your last save?"),
title: L10n.Message("Discard changes?"));
if (result == MessageBoxResult.Yes)
{
CurrentBuild.Build.RevertChanges();
}
}
private async Task SaveBuild(BuildViewModel build)
{
var poeBuild = build.Build;
if (!poeBuild.CanRevert && poeBuild.IsDirty)
{
// Build was created in this program run and was not yet saved.
// Thus it needs a name.
var name = await _dialogCoordinator.ShowValidatingInputDialogAsync(this,
L10n.Message("Saving new Build"),
L10n.Message("Enter the name of the build."),
poeBuild.Name,
s => _buildValidator.ValidateExistingFileName(s, build));
if (string.IsNullOrEmpty(name))
return;
poeBuild.Name = name;
}
poeBuild.LastUpdated = DateTime.Now;
await SaveBuildToFile(build);
// Save parent folder to retain ordering information when renaming
await SaveBuildToFile(build.Parent);
}
private async Task SaveBuildAs(BuildViewModel vm)
{
var build = vm.Build;
var name = await _dialogCoordinator.ShowValidatingInputDialogAsync(this, L10n.Message("Save as"),
L10n.Message("Enter the new name of the build"), build.Name, s => _buildValidator.ValidateNewBuildName(s, vm.Parent));
if (string.IsNullOrWhiteSpace(name))
return;
var newBuild = build.DeepClone();
newBuild.Name = name;
var newVm = new BuildViewModel(newBuild, Filter);
var builds = vm.Parent.Children;
if (build.CanRevert)
{
// The original build exists in the file system.
build.RevertChanges();
builds.Insert(builds.IndexOf(vm), newVm);
}
else
{
// The original build does not exist in the file system
// It will be replaced by the new one.
var i = builds.IndexOf(vm);
builds.RemoveAt(i);
builds.Insert(i, newVm);
}
CurrentBuild = newVm;
await SaveBuild(newVm);
}
private async Task SaveAllBuilds()
{
await TreeTraverseAsync<BuildViewModel>(async build =>
{
if (build.Build.IsDirty)
await SaveBuild(build);
}, BuildRoot);
}
private void MoveUp(IBuildViewModel build)
{
var list = build.Parent.Children;
var i = list.IndexOf(build);
list.Move(i, i - 1);
}
private void MoveDown(IBuildViewModel build)
{
var list = build.Parent.Children;
var i = list.IndexOf(build);
list.Move(i, i + 1);
}
private async Task Cut(IBuildViewModel build)
{
build.IsSelected = false;
build.Parent.IsSelected = true;
build.Parent.Children.Remove(build);
await DeleteBuildFile(build);
_buildClipboard = build;
_clipboardIsCopy = false;
var poeBuild = build.Build as PoEBuild;
if (poeBuild != null)
{
CopyToClipboard(poeBuild);
}
}
private void Copy(IBuildViewModel<PoEBuild> build)
{
_buildClipboard = build;
_clipboardIsCopy = true;
CopyToClipboard(build.Build);
}
private bool CanPaste(IBuildViewModel target)
{
return CanPasteFromClipboard() || CanPasteNonClipboard(target);
}
private bool CanPasteNonClipboard(IBuildViewModel target)
{
if (target == null || _buildClipboard == null)
return false;
var targetFolder = target as IBuildFolderViewModel ?? target.Parent;
return _buildValidator.CanMoveTo(_buildClipboard, targetFolder);
}
private async Task Paste(IBuildViewModel target)
{
var targetFolder = target as IBuildFolderViewModel ?? target.Parent;
IBuildViewModel pasted;
if (CanPasteFromClipboard() && !CanPasteNonClipboard(target))
{
var b = await PasteFromClipboard(BuildRoot);
if (b == null)
return;
pasted = new BuildViewModel(b, Filter);
}
else if (_clipboardIsCopy)
{
if (!(_buildClipboard.Build is PoEBuild oldBuild))
throw new InvalidOperationException("Can only copy builds, not folders.");
var newName = Util.FindDistinctName(oldBuild.Name, targetFolder.Children.Select(b => b.Build.Name));
var newBuild = PoEBuild.CreateNotRevertableCopy(oldBuild, newName);
pasted = new BuildViewModel(newBuild, Filter);
}
else
{
pasted = _buildClipboard;
_buildClipboard = null;
}
targetFolder.Children.Add(pasted);
// Folders and non-dirty builds need to be saved to create the new file.
var build = pasted.Build as PoEBuild;
if (build == null || !build.IsDirty)
{
await SaveBuildToFile(pasted);
}
}
private async Task Edit(IBuildViewModel build)
{
var nameBefore = build.Build.Name;
var buildVm = build as IBuildViewModel<PoEBuild>;
var folderVm = build as IBuildViewModel<BuildFolder>;
if (buildVm != null)
{
await _dialogCoordinator.EditBuildAsync(this, buildVm, _buildValidator);
}
else if (folderVm != null)
{
var name = await _dialogCoordinator.ShowValidatingInputDialogAsync(this,
L10n.Message("Edit Folder"),
L10n.Message("Enter the new name for this folder below."),
folderVm.Build.Name,
s => _buildValidator.ValidateExistingFolderName(s, folderVm));
if (!string.IsNullOrWhiteSpace(name))
{
folderVm.Build.Name = name;
await SaveBuildToFile(build);
}
}
else
{
throw new ArgumentException("Argument's IBuild implementation is not supported");
}
if (build.Build.Name != nameBefore)
{
await SaveBuildToFile(build.Parent);
}
}
private async Task Reload()
{
if (GetDirtyBuilds().Any())
{
var result = await _dialogCoordinator.ShowQuestionAsync(this,
L10n.Message("Any unsaved changes will be lost.\nAre you sure?"));
if (result != MessageBoxResult.Yes)
return;
}
await PersistentData.ReloadBuildsAsync();
}
private void ExpandAll()
{
TreeTraverse<IBuildFolderViewModel>(b => b.Build.IsExpanded = true, BuildRoot);
}
private void CollapseAll()
{
TreeTraverse<IBuildFolderViewModel>(b => b.Build.IsExpanded = false, BuildRoot);
}
private void CopyToClipboard(PoEBuild build)
{
Clipboard.SetText(PersistentData.ExportBuild(build));
}
private static bool CanPasteFromClipboard()
{
if (!Clipboard.ContainsText())
{
return false;
}
var str = Clipboard.GetText();
return str.StartsWith("<?xml ") && str.Contains("<PoEBuild ") && str.Contains("</PoEBuild>");
}
private async Task<PoEBuild> PasteFromClipboard(IBuildFolderViewModel targetFolder)
{
var str = Clipboard.GetText();
var newBuild = await PersistentData.ImportBuildAsync(str);
if (newBuild == null)
return null;
newBuild.Name = Util.FindDistinctName(newBuild.Name, targetFolder.Children.Select(b => b.Build.Name));
return newBuild;
}
private async Task ImportCurrentFromClipboard()
{
var pasted = await PasteFromClipboard(BuildRoot);
if (pasted == null)
return;
var build = new BuildViewModel(pasted, Filter);
BuildRoot.Children.Add(build);
CurrentBuild = build;
}
#endregion
private bool Filter(IBuildViewModel b)
{
if (ClassFilter == null)
return true;
var build = b as BuildViewModel;
if (build == null)
return true;
if (ClassFilter != NoFilterItem)
{
if (ClassFilter.CharacterClass != build.CharacterClass)
return false;
if (ClassFilter.AscendancyClass != null
&& ClassFilter.AscendancyClass != build.AscendancyClass)
{
return false;
}
}
return string.IsNullOrEmpty(TextFilter)
|| build.Build.Name.Contains(TextFilter, StringComparison.InvariantCultureIgnoreCase);
}
#region Traverse helper methods
private BuildViewModel TreeFindBuildViewModel(PoEBuild build)
{
return TreeFind<BuildViewModel>(b => b.Build == build, BuildRoot);
}
private IBuildViewModel<T> TreeFindBuildViewModel<T>(T build)
where T : class, IBuild
{
return TreeFind<IBuildViewModel<T>>(b => b.Build == build, BuildRoot);
}
private static T TreeFind<T>(Predicate<T> predicate, IBuildViewModel current) where T : class, IBuildViewModel
{
var t = current as T;
if (t != null && predicate(t))
{
return t;
}
var folder = current as BuildFolderViewModel;
return folder?.Children.Select(build => TreeFind(predicate, build)).FirstOrDefault(r => r != null);
}
private static async Task TreeTraverseAsync<T>(Func<T, Task> action, IBuildViewModel current) where T : class, IBuildViewModel
{
var t = current as T;
if (t != null)
await action(t);
var folder = current as BuildFolderViewModel;
if (folder == null)
return;
foreach (var build in folder.Children)
{
await TreeTraverseAsync(action, build);
}
}
private static void TreeTraverse<T>(Action<T> action, IBuildViewModel current) where T : class, IBuildViewModel
{
var t = current as T;
if (t != null)
action(t);
var folder = current as BuildFolderViewModel;
folder?.Children.ForEach(b => TreeTraverse(action, b));
}
#endregion
#region Saving and related methods
private async void BuildOnCollectionChanged(IBuildFolderViewModel build)
{
await SaveBuildToFile(build);
// It's ok that this method doesn't return Task as it is used like an event handler and the
// async action in SaveBuildToFile does not require to be waited upon.
}
private async Task SaveBuildToFile(IBuildViewModel build)
{
try
{
using (_changingFileSystemMonitor.Enter())
{
PersistentData.SaveBuild(build.Build);
}
}
catch (Exception e)
{
Log.Error($"Build save failed for '{build.Build.Name}'", e);
await _dialogCoordinator.ShowErrorAsync(this,
L10n.Message("An error occurred during a save operation."), e.Message);
}
}
private async Task DeleteBuildFile(IBuildViewModel build)
{
try
{
using (_changingFileSystemMonitor.Enter())
{
PersistentData.DeleteBuild(build.Build);
}
}
catch (Exception e)
{
Log.Error($"Build deletion failed for '{build.Build.Name}'", e);
await _dialogCoordinator.ShowErrorAsync(this,
L10n.Message("An error occurred during a delete operation."), e.Message);
}
}
/// <summary>
/// If there are any unsaved builds the user will be asked if they should be saved. They will be saved if
/// the user wants to.
/// </summary>
/// <param name="message">The message the dialog will show.</param>
/// <param name="revertWhenUnsaved">True if dirty builds should be reverted to their saved state when the user
/// doesn't want to save.</param>
/// <returns>False if the dialog was canceled by the user, true if he clicked Yes or No.</returns>
public async Task<bool> HandleUnsavedBuilds(string message, bool revertWhenUnsaved)
{
var dirtyBuilds = GetDirtyBuilds().ToList();
if (!dirtyBuilds.Any())
return true;
var title = L10n.Message("Unsaved Builds");
var details = L10n.Message("These builds are not saved:\n");
foreach (var build in dirtyBuilds)
{
details += "\n - " + build.Build.Name;
}
var result = await _dialogCoordinator.ShowQuestionAsync(this, message, details, title, MessageBoxButton.YesNoCancel);
switch (result)
{
case MessageBoxResult.Yes:
foreach (var build in dirtyBuilds)
{
await SaveBuild(build);
}
return true;
case MessageBoxResult.No:
if (revertWhenUnsaved)
{
dirtyBuilds.Where(b => b.Build.CanRevert)
.ForEach(b => b.Build.RevertChanges());
}
return true;
default:
return false;
}
}
private IEnumerable<BuildViewModel> GetDirtyBuilds()
{
var dirty = new List<BuildViewModel>();
TreeTraverse<BuildViewModel>(vm =>
{
if (vm.Build.IsDirty)
dirty.Add(vm);
}, BuildRoot);
return dirty;
}
#endregion
private class CustomDropHandler : DefaultDropHandler
{
private readonly BuildsControlViewModel _outer;
public CustomDropHandler(BuildsControlViewModel outer)
{
_outer = outer;
}
public override void DragOver(IDropInfo dropInfo)
{
base.DragOver(dropInfo);
// Highlight: insert at TargetItem
// Insert: insert at TargetItem's parent
var isHighlight = dropInfo.DropTargetAdorner == DropTargetAdorners.Highlight;
// Can't drop onto builds
if (dropInfo.TargetItem is BuildViewModel && isHighlight)
{
dropInfo.Effects = DragDropEffects.None;
}
// Ask BuildValidator if drop is possible
var source = dropInfo.Data as IBuildViewModel;
if (source == null)
return;
IBuildFolderViewModel target;
if (isHighlight)
{
target = dropInfo.TargetItem as IBuildFolderViewModel;
}
else
{
var targetChild = dropInfo.TargetItem as IBuildViewModel;
if (targetChild == null)
return;
target = targetChild.Parent;
}
if (target == null)
return;
if (!_outer._buildValidator.CanMoveTo(source, target))
{
dropInfo.Effects = DragDropEffects.None;
}
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.Win32.SafeHandles;
using System.ComponentModel;
using System.Globalization;
using System.Net.Security;
using System.Runtime.InteropServices;
using System.Security.Authentication;
using System.Security.Authentication.ExtendedProtection;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
namespace System.Net
{
// For SSL connections:
internal partial class SSPISecureChannelType : SSPIInterface
{
public const string MSSecurityPackage = "Microsoft Unified Security Protocol Provider";
public const Interop.Secur32.ContextFlags RequiredFlags = Interop.Secur32.ContextFlags.ReplayDetect | Interop.Secur32.ContextFlags.SequenceDetect |
Interop.Secur32.ContextFlags.Confidentiality | Interop.Secur32.ContextFlags.AllocateMemory;
public const Interop.Secur32.ContextFlags ServerRequiredFlags = RequiredFlags | Interop.Secur32.ContextFlags.AcceptStream;
private static volatile SecurityPackageInfoClass[] s_securityPackages;
public void VerifyPackageInfo()
{
bool found = false;
EnumerateSecurityPackages();
if (s_securityPackages != null)
{
foreach (var package in s_securityPackages)
{
if (string.Compare(package.Name, MSSecurityPackage, StringComparison.OrdinalIgnoreCase) == 0)
{
found = true;
break;
}
}
}
if (!found)
{
if (Logging.On)
{
Logging.PrintInfo(Logging.Web, SR.Format(SR.net_log_sspi_security_package_not_found, MSSecurityPackage));
}
throw new NotSupportedException(SR.net_securitypackagesupport);
}
}
public Exception GetException(SecurityStatus status)
{
return new Win32Exception((int)status);
}
public SecurityStatus AcceptSecurityContext(ref SafeFreeCredentials credential, ref SafeDeleteContext context, SecurityBuffer inputBuffer, SecurityBuffer outputBuffer, bool remoteCertRequired)
{
Interop.Secur32.ContextFlags outFlags = Interop.Secur32.ContextFlags.Zero;
var retStatus = SafeDeleteContext.AcceptSecurityContext(
ref credential,
ref context,
ServerRequiredFlags | (remoteCertRequired ? Interop.Secur32.ContextFlags.MutualAuth : Interop.Secur32.ContextFlags.Zero),
Interop.Secur32.Endianness.Native,
inputBuffer,
null,
outputBuffer,
ref outFlags
);
return MapToSecurityStatus((Interop.SecurityStatus)retStatus);
}
public SecurityStatus InitializeSecurityContext(ref SafeFreeCredentials credential, ref SafeDeleteContext context, string targetName, SecurityBuffer inputBuffer, SecurityBuffer outputBuffer)
{
Interop.Secur32.ContextFlags outFlags = Interop.Secur32.ContextFlags.Zero;
var retStatus = (SecurityStatus)SafeDeleteContext.InitializeSecurityContext(ref credential, ref context, targetName, RequiredFlags | Interop.Secur32.ContextFlags.InitManualCredValidation, Interop.Secur32.Endianness.Native, inputBuffer, null, outputBuffer, ref outFlags);
return MapToSecurityStatus((Interop.SecurityStatus)retStatus);
}
public SecurityStatus InitializeSecurityContext(SafeFreeCredentials credential, ref SafeDeleteContext context, string targetName, SecurityBuffer[] inputBuffers, SecurityBuffer outputBuffer)
{
Interop.Secur32.ContextFlags outFlags = Interop.Secur32.ContextFlags.Zero;
var retStatus = (SecurityStatus)SafeDeleteContext.InitializeSecurityContext(ref credential, ref context, targetName, RequiredFlags | Interop.Secur32.ContextFlags.InitManualCredValidation, Interop.Secur32.Endianness.Native, null, inputBuffers, outputBuffer, ref outFlags);
return MapToSecurityStatus((Interop.SecurityStatus)retStatus);
}
public SafeFreeCredentials AcquireCredentialsHandle(X509Certificate certificate, SslProtocols protocols, EncryptionPolicy policy, bool isServer)
{
Interop.Secur32.SecureCredential secureCredential = CreateSecureCredential(Interop.Secur32.SecureCredential.CurrentVersion, certificate, protocols, policy, isServer);
// First try without impersonation, if it fails, then try the process account.
// I.E. We don't know which account the certificate context was created under.
try
{
//
// For app-compat we want to ensure the credential are accessed under >>process<< acount.
//
return WindowsIdentity.RunImpersonated<SafeFreeCredentials>(SafeAccessTokenHandle.InvalidHandle, () =>
{
return AcquireCredentialsHandle(MSSecurityPackage, isServer, secureCredential);
});
}
catch
{
return AcquireCredentialsHandle(MSSecurityPackage, isServer, secureCredential);
}
}
public SecurityStatus EncryptMessage(SafeDeleteContext securityContext, byte[] buffer, int size, int headerSize, int trailerSize, out int resultSize)
{
resultSize = 0;
// Encryption using SCHANNEL requires 4 buffers: header, payload, trailer, empty.
SecurityBuffer[] securityBuffer = new SecurityBuffer[4];
securityBuffer[0] = new SecurityBuffer(buffer, 0, headerSize, SecurityBufferType.Header);
securityBuffer[1] = new SecurityBuffer(buffer, headerSize, size, SecurityBufferType.Data);
securityBuffer[2] = new SecurityBuffer(buffer, headerSize + size, trailerSize, SecurityBufferType.Trailer);
securityBuffer[3] = new SecurityBuffer(null, SecurityBufferType.Empty);
SecurityStatus secStatus = EncryptDecryptHelper(OP.Encrypt, securityContext, securityBuffer, 0);
if (secStatus == 0)
{
// The full buffer may not be used.
resultSize = securityBuffer[0].size + securityBuffer[1].size + securityBuffer[2].size;
GlobalLog.Leave("SecureChannel#" + Logging.HashString(this) + "::Encrypt OK", "data size:" + resultSize.ToString());
}
return secStatus;
}
public SecurityStatus DecryptMessage(SafeDeleteContext securityContext, byte[] buffer, ref int offset, ref int count)
{
// Decryption using SCHANNEL requires four buffers.
SecurityBuffer[] decspc = new SecurityBuffer[4];
decspc[0] = new SecurityBuffer(buffer, offset, count, SecurityBufferType.Data);
decspc[1] = new SecurityBuffer(null, SecurityBufferType.Empty);
decspc[2] = new SecurityBuffer(null, SecurityBufferType.Empty);
decspc[3] = new SecurityBuffer(null, SecurityBufferType.Empty);
SecurityStatus secStatus = EncryptDecryptHelper(OP.Decrypt, securityContext, decspc, 0);
count = 0;
for (int i = 0; i < decspc.Length; i++)
{
// Successfully decoded data and placed it at the following position in the buffer,
if ((secStatus == SecurityStatus.OK && decspc[i].type == SecurityBufferType.Data)
// or we failed to decode the data, here is the encoded data.
|| (secStatus != SecurityStatus.OK && decspc[i].type == SecurityBufferType.Extra))
{
offset = decspc[i].offset;
count = decspc[i].size;
break;
}
}
return secStatus;
}
public unsafe int QueryContextChannelBinding(SafeDeleteContext phContext, ChannelBindingKind attribute, out SafeFreeContextBufferChannelBinding refHandle)
{
refHandle = SafeFreeContextBufferChannelBinding.CreateEmptyHandle();
// Bindings is on the stack, so there's no need for a fixed block.
Bindings bindings = new Bindings();
int errorCode = SafeFreeContextBufferChannelBinding.QueryContextChannelBinding(phContext, (Interop.Secur32.ContextAttribute)attribute, &bindings, refHandle);
if (errorCode != 0)
{
GlobalLog.Leave("QueryContextChannelBinding", "ERROR = " + ErrorDescription(errorCode));
refHandle = null;
}
return errorCode;
}
public int QueryContextStreamSizes(SafeDeleteContext securityContext, out StreamSizes streamSizes)
{
int errorCode;
streamSizes = QueryContextAttributes(securityContext, Interop.Secur32.ContextAttribute.StreamSizes, out errorCode) as StreamSizes;
return errorCode;
}
public int QueryContextConnectionInfo(SafeDeleteContext securityContext, out SslConnectionInfo connectionInfo)
{
int errorCode;
connectionInfo = QueryContextAttributes(securityContext, Interop.Secur32.ContextAttribute.ConnectionInfo, out errorCode) as SslConnectionInfo;
return errorCode;
}
public int QueryContextRemoteCertificate(SafeDeleteContext securityContext, out SafeFreeCertContext remoteCert)
{
int errorCode;
remoteCert = QueryContextAttributes(securityContext, Interop.Secur32.ContextAttribute.RemoteCertificate, out errorCode) as SafeFreeCertContext;
return errorCode;
}
public int QueryContextIssuerList(SafeDeleteContext securityContext, out Object issuerList)
{
int errorCode;
issuerList = QueryContextAttributes(securityContext, Interop.Secur32.ContextAttribute.IssuerListInfoEx, out errorCode);
return errorCode;
}
#region Private Methods
private enum OP
{
Encrypt = 1,
Decrypt
}
private SecurityStatus MapToSecurityStatus(Interop.SecurityStatus secStatus)
{
SecurityStatus retStatus;
if (SecurityStatus.TryParse(secStatus.ToString(), out retStatus))
{
return retStatus;
}
else
{
throw new Win32Exception("Coulbd not map from Interop.SecurityStatus to SecurityStatus. Interop.SecurityStatus value:" + secStatus.ToString());
}
}
private void EnumerateSecurityPackages()
{
GlobalLog.Enter("EnumerateSecurityPackages");
if (s_securityPackages == null)
{
lock (this)
{
if (s_securityPackages == null)
{
int moduleCount = 0;
SafeFreeContextBuffer arrayBaseHandle = null;
try
{
int errorCode = SafeFreeContextBuffer.EnumeratePackages(out moduleCount, out arrayBaseHandle);
GlobalLog.Print("SSPIWrapper::arrayBase: " + (arrayBaseHandle.DangerousGetHandle().ToString("x")));
if (errorCode != 0)
{
throw new Win32Exception(errorCode);
}
SecurityPackageInfoClass[] securityPackagesList = new SecurityPackageInfoClass[moduleCount];
if (Logging.On)
{
Logging.PrintInfo(Logging.Web, SR.net_log_sspi_enumerating_security_packages);
}
for (int i = 0; i < moduleCount; i++)
{
securityPackagesList[i] = new SecurityPackageInfoClass(arrayBaseHandle, i);
if (Logging.On)
{
Logging.PrintInfo(Logging.Web, " " + securityPackagesList[i].Name);
}
}
s_securityPackages = securityPackagesList;
}
finally
{
if (arrayBaseHandle != null)
{
arrayBaseHandle.Dispose();
}
}
}
}
}
GlobalLog.Leave("EnumerateSecurityPackages");
}
private SafeFreeCredentials AcquireCredentialsHandle(string package, bool isServer, Interop.Secur32.SecureCredential scc)
{
GlobalLog.Print("SSPIWrapper::AcquireCredentialsHandle#3(): using " + package);
if (Logging.On)
{
Logging.PrintInfo(Logging.Web,
"AcquireCredentialsHandle(" +
"package = " + package + ", " +
"IsInBoundCred = " + isServer + ", " +
"scc = " + scc + ")");
}
SafeFreeCredentials outCredential = null;
int errorCode = AcquireCredentialsHandle(
package,
isServer,
ref scc,
out outCredential
);
if (errorCode != 0)
{
#if TRACE_VERBOSE
GlobalLog.Print("SSPIWrapper::AcquireCredentialsHandle#3(): error " + Interop.MapSecurityStatus((uint)errorCode));
#endif
if (Logging.On) Logging.PrintError(Logging.Web, SR.Format(SR.net_log_operation_failed_with_error, "AcquireCredentialsHandle()", String.Format(CultureInfo.CurrentCulture, "0X{0:X}", errorCode)));
throw new Win32Exception(errorCode);
}
#if TRACE_VERBOSE
GlobalLog.Print("SSPIWrapper::AcquireCredentialsHandle#3(): cred handle = " + outCredential.ToString());
#endif
return outCredential;
}
private int AcquireCredentialsHandle(string moduleName, bool IsInBoundCred, ref Interop.Secur32.SecureCredential authdata, out SafeFreeCredentials outCredential)
{
Interop.Secur32.CredentialUse intent = IsInBoundCred ? Interop.Secur32.CredentialUse.Inbound : Interop.Secur32.CredentialUse.Outbound;
return SafeFreeCredentials.AcquireCredentialsHandle(moduleName, intent, ref authdata, out outCredential);
}
private Interop.Secur32.SecureCredential CreateSecureCredential(int version, X509Certificate certificate, SslProtocols protocols, EncryptionPolicy policy, bool isServer)
{
Interop.Secur32.SecureCredential.Flags flags = Interop.Secur32.SecureCredential.Flags.Zero;
if (!isServer)
{
flags = Interop.Secur32.SecureCredential.Flags.ValidateManual | Interop.Secur32.SecureCredential.Flags.NoDefaultCred;
if ((protocols.HasFlag(SslProtocols.Tls) || protocols.HasFlag(SslProtocols.Tls11) || protocols.HasFlag(SslProtocols.Tls12))
&& (policy != EncryptionPolicy.AllowNoEncryption) && (policy != EncryptionPolicy.NoEncryption))
{
flags |= Interop.Secur32.SecureCredential.Flags.UseStrongCrypto;
}
}
var credential = new Interop.Secur32.SecureCredential()
{
rootStore = IntPtr.Zero,
phMappers = IntPtr.Zero,
palgSupportedAlgs = IntPtr.Zero,
certContextArray = IntPtr.Zero,
cCreds = 0,
cMappers = 0,
cSupportedAlgs = 0,
dwSessionLifespan = 0,
reserved = 0
};
if (policy == EncryptionPolicy.RequireEncryption)
{
// Prohibit null encryption cipher.
credential.dwMinimumCipherStrength = 0;
credential.dwMaximumCipherStrength = 0;
}
else if (policy == EncryptionPolicy.AllowNoEncryption)
{
// Allow null encryption cipher in addition to other ciphers.
credential.dwMinimumCipherStrength = -1;
credential.dwMaximumCipherStrength = 0;
}
else if (policy == EncryptionPolicy.NoEncryption)
{
// Suppress all encryption and require null encryption cipher only
credential.dwMinimumCipherStrength = -1;
credential.dwMaximumCipherStrength = -1;
}
else
{
throw new ArgumentException(SR.Format(SR.net_invalid_enum, "EncryptionPolicy"), "policy");
}
int _protocolFlags = 0;
if (isServer)
{
_protocolFlags = ((int)protocols & Interop.SChannel.ServerProtocolMask);
}
else
{
_protocolFlags = ((int)protocols & Interop.SChannel.ClientProtocolMask);
}
credential.version = version;
credential.dwFlags = flags;
credential.grbitEnabledProtocols = _protocolFlags;
if (certificate != null)
{
credential.certContextArray = certificate.Handle;
credential.cCreds = 1;
}
return credential;
}
private unsafe SecurityStatus EncryptDecryptHelper(OP op, SafeDeleteContext context, SecurityBuffer[] input, uint sequenceNumber)
{
Interop.Secur32.SecurityBufferDescriptor sdcInOut = new Interop.Secur32.SecurityBufferDescriptor(input.Length);
var unmanagedBuffer = new Interop.Secur32.SecurityBufferStruct[input.Length];
fixed (Interop.Secur32.SecurityBufferStruct* unmanagedBufferPtr = unmanagedBuffer)
{
sdcInOut.UnmanagedPointer = unmanagedBufferPtr;
GCHandle[] pinnedBuffers = new GCHandle[input.Length];
byte[][] buffers = new byte[input.Length][];
try
{
for (int i = 0; i < input.Length; i++)
{
SecurityBuffer iBuffer = input[i];
unmanagedBuffer[i].count = iBuffer.size;
unmanagedBuffer[i].type = iBuffer.type;
if (iBuffer.token == null || iBuffer.token.Length == 0)
{
unmanagedBuffer[i].token = IntPtr.Zero;
}
else
{
pinnedBuffers[i] = GCHandle.Alloc(iBuffer.token, GCHandleType.Pinned);
unmanagedBuffer[i].token = Marshal.UnsafeAddrOfPinnedArrayElement(iBuffer.token, iBuffer.offset);
buffers[i] = iBuffer.token;
}
}
// The result is written in the input Buffer passed as type=BufferType.Data.
int errorCode;
switch (op)
{
case OP.Encrypt:
errorCode = EncryptMessage(context, sdcInOut, sequenceNumber);
break;
case OP.Decrypt:
errorCode = DecryptMessage(context, sdcInOut, sequenceNumber);
break;
default: throw NotImplemented.ByDesignWithMessage(SR.net_MethodNotImplementedException);
}
// Marshalling back returned sizes / data.
for (int i = 0; i < input.Length; i++)
{
SecurityBuffer iBuffer = input[i];
iBuffer.size = unmanagedBuffer[i].count;
iBuffer.type = unmanagedBuffer[i].type;
if (iBuffer.size == 0)
{
iBuffer.offset = 0;
iBuffer.token = null;
}
else
checked
{
// Find the buffer this is inside of. Usually they all point inside buffer 0.
int j;
for (j = 0; j < input.Length; j++)
{
if (buffers[j] == null)
{
continue;
}
byte* bufferAddress = (byte*)Marshal.UnsafeAddrOfPinnedArrayElement(buffers[j], 0);
if ((byte*)unmanagedBuffer[i].token >= bufferAddress &&
(byte*)unmanagedBuffer[i].token + iBuffer.size <= bufferAddress + buffers[j].Length)
{
iBuffer.offset = (int)((byte*)unmanagedBuffer[i].token - bufferAddress);
iBuffer.token = buffers[j];
break;
}
}
if (j >= input.Length)
{
GlobalLog.Assert("SSPIWrapper::EncryptDecryptHelper", "Output buffer out of range.");
iBuffer.size = 0;
iBuffer.offset = 0;
iBuffer.token = null;
}
}
// Backup validate the new sizes.
GlobalLog.Assert(iBuffer.offset >= 0 && iBuffer.offset <= (iBuffer.token == null ? 0 : iBuffer.token.Length), "SSPIWrapper::EncryptDecryptHelper|'offset' out of range. [{0}]", iBuffer.offset);
GlobalLog.Assert(iBuffer.size >= 0 && iBuffer.size <= (iBuffer.token == null ? 0 : iBuffer.token.Length - iBuffer.offset), "SSPIWrapper::EncryptDecryptHelper|'size' out of range. [{0}]", iBuffer.size);
}
if (errorCode != 0 && Logging.On)
{
if (errorCode == 0x90321)
{
Logging.PrintError(Logging.Web, SR.Format(SR.net_log_operation_returned_something, op, "SEC_I_RENEGOTIATE"));
}
else
{
Logging.PrintError(Logging.Web, SR.Format(SR.net_log_operation_failed_with_error, op, String.Format(CultureInfo.CurrentCulture, "0X{0:X}", errorCode)));
}
}
return MapToSecurityStatus((Interop.SecurityStatus)errorCode);
}
finally
{
for (int i = 0; i < pinnedBuffers.Length; ++i)
{
if (pinnedBuffers[i].IsAllocated)
{
pinnedBuffers[i].Free();
}
}
}
}
}
private int EncryptMessage(SafeDeleteContext context, Interop.Secur32.SecurityBufferDescriptor inputOutput, uint sequenceNumber)
{
int status = (int)Interop.SecurityStatus.InvalidHandle;
try
{
bool ignore = false;
context.DangerousAddRef(ref ignore);
status = Interop.Secur32.EncryptMessage(ref context._handle, 0, inputOutput, sequenceNumber);
return status;
}
finally
{
context.DangerousRelease();
}
}
private unsafe int DecryptMessage(SafeDeleteContext context, Interop.Secur32.SecurityBufferDescriptor inputOutput,
uint sequenceNumber)
{
int status = (int)Interop.SecurityStatus.InvalidHandle;
try
{
bool ignore = false;
context.DangerousAddRef(ref ignore);
status = Interop.Secur32.DecryptMessage(ref context._handle, inputOutput, sequenceNumber, null);
return status;
}
finally
{
context.DangerousRelease();
}
}
private object QueryContextAttributes(SafeDeleteContext securityContext, Interop.Secur32.ContextAttribute contextAttribute, out int errorCode)
{
GlobalLog.Enter("QueryContextAttributes", contextAttribute.ToString());
int nativeBlockSize = IntPtr.Size;
Type handleType = null;
switch (contextAttribute)
{
case Interop.Secur32.ContextAttribute.Sizes:
nativeBlockSize = SecSizes.SizeOf;
break;
case Interop.Secur32.ContextAttribute.StreamSizes:
nativeBlockSize = StreamSizes.SizeOf;
break;
case Interop.Secur32.ContextAttribute.Names:
handleType = typeof(SafeFreeContextBuffer);
break;
case Interop.Secur32.ContextAttribute.PackageInfo:
handleType = typeof(SafeFreeContextBuffer);
break;
case Interop.Secur32.ContextAttribute.NegotiationInfo:
handleType = typeof(SafeFreeContextBuffer);
nativeBlockSize = Marshal.SizeOf<NegotiationInfo>();
break;
case Interop.Secur32.ContextAttribute.ClientSpecifiedSpn:
handleType = typeof(SafeFreeContextBuffer);
break;
case Interop.Secur32.ContextAttribute.RemoteCertificate:
handleType = typeof(SafeFreeCertContext);
break;
case Interop.Secur32.ContextAttribute.LocalCertificate:
handleType = typeof(SafeFreeCertContext);
break;
case Interop.Secur32.ContextAttribute.IssuerListInfoEx:
nativeBlockSize = Marshal.SizeOf<Interop.Secur32.IssuerListInfoEx>();
handleType = typeof(SafeFreeContextBuffer);
break;
case Interop.Secur32.ContextAttribute.ConnectionInfo:
nativeBlockSize = Marshal.SizeOf<SslConnectionInfo>();
break;
default:
throw new ArgumentException(SR.Format(SR.net_invalid_enum, "ContextAttribute"), "contextAttribute");
}
SafeHandle SspiHandle = null;
object attribute = null;
try
{
byte[] nativeBuffer = new byte[nativeBlockSize];
errorCode = QueryContextAttributes(securityContext, contextAttribute, nativeBuffer, handleType, out SspiHandle);
if (errorCode != 0)
{
GlobalLog.Leave("Win32:QueryContextAttributes", "ERROR = " + ErrorDescription(errorCode));
return null;
}
switch (contextAttribute)
{
case Interop.Secur32.ContextAttribute.Sizes:
attribute = new SecSizes(nativeBuffer);
break;
case Interop.Secur32.ContextAttribute.StreamSizes:
attribute = new StreamSizes(nativeBuffer);
break;
case Interop.Secur32.ContextAttribute.Names:
attribute = Marshal.PtrToStringUni(SspiHandle.DangerousGetHandle());
break;
case Interop.Secur32.ContextAttribute.PackageInfo:
attribute = new SecurityPackageInfoClass(SspiHandle, 0);
break;
case Interop.Secur32.ContextAttribute.NegotiationInfo:
unsafe
{
fixed (void* ptr = nativeBuffer)
{
attribute = new NegotiationInfoClass(SspiHandle, Marshal.ReadInt32(new IntPtr(ptr), NegotiationInfo.NegotiationStateOffest));
}
}
break;
case Interop.Secur32.ContextAttribute.ClientSpecifiedSpn:
attribute = Marshal.PtrToStringUni(SspiHandle.DangerousGetHandle());
break;
case Interop.Secur32.ContextAttribute.LocalCertificate:
goto case Interop.Secur32.ContextAttribute.RemoteCertificate;
case Interop.Secur32.ContextAttribute.RemoteCertificate:
attribute = SspiHandle;
SspiHandle = null;
break;
case Interop.Secur32.ContextAttribute.IssuerListInfoEx:
attribute = new Interop.Secur32.IssuerListInfoEx(SspiHandle, nativeBuffer);
SspiHandle = null;
break;
case Interop.Secur32.ContextAttribute.ConnectionInfo:
attribute = new SslConnectionInfo(nativeBuffer);
break;
default:
// Will return null.
break;
}
}
finally
{
if (SspiHandle != null)
{
SspiHandle.Dispose();
}
}
GlobalLog.Leave("QueryContextAttributes", Logging.ObjectToString(attribute));
return attribute;
}
private unsafe int QueryContextAttributes(SafeDeleteContext phContext, Interop.Secur32.ContextAttribute attribute, byte[] buffer, Type handleType, out SafeHandle refHandle)
{
refHandle = null;
if (handleType != null)
{
if (handleType == typeof(SafeFreeContextBuffer))
{
refHandle = SafeFreeContextBuffer.CreateEmptyHandle();
}
else if (handleType == typeof(SafeFreeCertContext))
{
refHandle = new SafeFreeCertContext();
}
else
{
throw new ArgumentException(SR.Format(SR.SSPIInvalidHandleType, handleType.FullName), "handleType");
}
}
fixed (byte* bufferPtr = buffer)
{
return SafeFreeContextBuffer.QueryContextAttributes(phContext, attribute, bufferPtr, refHandle);
}
}
private string ErrorDescription(int errorCode)
{
if (errorCode == -1)
{
return "An exception when invoking Win32 API";
}
switch ((Interop.SecurityStatus)errorCode)
{
case Interop.SecurityStatus.InvalidHandle:
return "Invalid handle";
case Interop.SecurityStatus.InvalidToken:
return "Invalid token";
case Interop.SecurityStatus.ContinueNeeded:
return "Continue needed";
case Interop.SecurityStatus.IncompleteMessage:
return "Message incomplete";
case Interop.SecurityStatus.WrongPrincipal:
return "Wrong principal";
case Interop.SecurityStatus.TargetUnknown:
return "Target unknown";
case Interop.SecurityStatus.PackageNotFound:
return "Package not found";
case Interop.SecurityStatus.BufferNotEnough:
return "Buffer not enough";
case Interop.SecurityStatus.MessageAltered:
return "Message altered";
case Interop.SecurityStatus.UntrustedRoot:
return "Untrusted root";
default:
return "0x" + errorCode.ToString("x", NumberFormatInfo.InvariantInfo);
}
}
#endregion
}
#region structures
[StructLayout(LayoutKind.Sequential)]
internal struct SecurityPackageInfo
{
// see SecPkgInfoW in <sspi.h>
internal int Capabilities;
internal short Version;
internal short RPCID;
internal int MaxToken;
internal IntPtr Name;
internal IntPtr Comment;
internal static readonly int Size = Marshal.SizeOf<SecurityPackageInfo>();
internal static readonly int NameOffest = (int)Marshal.OffsetOf<SecurityPackageInfo>("Name");
}
[StructLayout(LayoutKind.Sequential)]
internal struct Bindings
{
// see SecPkgContext_Bindings in <sspi.h>
internal int BindingsLength;
internal IntPtr pBindings;
}
[StructLayout(LayoutKind.Sequential)]
internal struct NegotiationInfo
{
// see SecPkgContext_NegotiationInfoW in <sspi.h>
// [MarshalAs(UnmanagedType.LPStruct)] internal SecurityPackageInfo PackageInfo;
internal IntPtr PackageInfo;
internal uint NegotiationState;
internal static readonly int Size = Marshal.SizeOf<NegotiationInfo>();
internal static readonly int NegotiationStateOffest = (int)Marshal.OffsetOf<NegotiationInfo>("NegotiationState");
}
#endregion
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
namespace OpenSim.Region.CoreModules.World.Terrain.PaintBrushes
{
/// <summary>
/// Hydraulic Erosion Brush
/// </summary>
public class ErodeSphere : ITerrainPaintableEffect
{
private const double rainHeight = 0.2;
private const int rounds = 10;
private const NeighbourSystem type = NeighbourSystem.Moore;
private const double waterSaturation = 0.30;
#region Supporting Functions
private static int[] Neighbours(NeighbourSystem neighbourType, int index)
{
int[] coord = new int[2];
index++;
switch (neighbourType)
{
case NeighbourSystem.Moore:
switch (index)
{
case 1:
coord[0] = -1;
coord[1] = -1;
break;
case 2:
coord[0] = -0;
coord[1] = -1;
break;
case 3:
coord[0] = +1;
coord[1] = -1;
break;
case 4:
coord[0] = -1;
coord[1] = -0;
break;
case 5:
coord[0] = -0;
coord[1] = -0;
break;
case 6:
coord[0] = +1;
coord[1] = -0;
break;
case 7:
coord[0] = -1;
coord[1] = +1;
break;
case 8:
coord[0] = -0;
coord[1] = +1;
break;
case 9:
coord[0] = +1;
coord[1] = +1;
break;
default:
break;
}
break;
case NeighbourSystem.VonNeumann:
switch (index)
{
case 1:
coord[0] = 0;
coord[1] = -1;
break;
case 2:
coord[0] = -1;
coord[1] = 0;
break;
case 3:
coord[0] = +1;
coord[1] = 0;
break;
case 4:
coord[0] = 0;
coord[1] = +1;
break;
case 5:
coord[0] = -0;
coord[1] = -0;
break;
default:
break;
}
break;
}
return coord;
}
private enum NeighbourSystem
{
Moore,
VonNeumann
} ;
#endregion
#region ITerrainPaintableEffect Members
public void PaintEffect(ITerrainChannel map, bool[,] mask, double rx, double ry, double rz,
double strength, double duration, int startX, int endX, int startY, int endY)
{
strength = TerrainUtil.MetersToSphericalStrength(strength);
int x, y;
// Using one 'rain' round for this, so skipping a useless loop
// Will need to adapt back in for the Flood brush
ITerrainChannel water = new TerrainChannel(map.Width, map.Height);
ITerrainChannel sediment = new TerrainChannel(map.Width, map.Height);
// Fill with rain
for (x = startX; x <= endX; x++)
{
for (y = startY; y <= endY; y++)
{
if (mask[x, y])
water[x, y] = Math.Max(0.0, TerrainUtil.SphericalFactor(x, y, rx, ry, strength) * rainHeight * duration);
}
}
for (int i = 0; i < rounds; i++)
{
// Erode underlying terrain
for (x = startX; x <= endX; x++)
{
for (y = startY; y <= endY; y++)
{
if (mask[x, y])
{
const double solConst = (1.0 / rounds);
double sedDelta = water[x, y] * solConst;
map[x, y] -= sedDelta;
sediment[x, y] += sedDelta;
}
}
}
// Move water
for (x = startX; x <= endX; x++)
{
for (y = startY; y <= endY; y++)
{
if (water[x, y] <= 0)
continue;
// Step 1. Calculate average of neighbours
int neighbours = 0;
double altitudeTotal = 0.0;
double altitudeMe = map[x, y] + water[x, y];
const int NEIGHBOUR_ME = 4;
const int NEIGHBOUR_MAX = 9;
for (int j = 0; j < NEIGHBOUR_MAX; j++)
{
if (j != NEIGHBOUR_ME)
{
int[] coords = Neighbours(type, j);
coords[0] += x;
coords[1] += y;
if (coords[0] > map.Width - 1)
continue;
if (coords[1] > map.Height - 1)
continue;
if (coords[0] < 0)
continue;
if (coords[1] < 0)
continue;
// Calculate total height of this neighbour
double altitudeNeighbour = water[coords[0], coords[1]] + map[coords[0], coords[1]];
// If it's greater than me...
if (altitudeNeighbour - altitudeMe < 0)
{
// Add it to our calculations
neighbours++;
altitudeTotal += altitudeNeighbour;
}
}
}
if (neighbours == 0)
continue;
double altitudeAvg = altitudeTotal / neighbours;
// Step 2. Allocate water to neighbours.
for (int j = 0; j < NEIGHBOUR_MAX; j++)
{
if (j != NEIGHBOUR_ME)
{
int[] coords = Neighbours(type, j);
coords[0] += x;
coords[1] += y;
if (coords[0] > map.Width - 1)
continue;
if (coords[1] > map.Height - 1)
continue;
if (coords[0] < 0)
continue;
if (coords[1] < 0)
continue;
// Skip if we dont have water to begin with.
if (water[x, y] < 0)
continue;
// Calculate our delta average
double altitudeDelta = altitudeMe - altitudeAvg;
if (altitudeDelta < 0)
continue;
// Calculate how much water we can move
double waterMin = Math.Min(water[x, y], altitudeDelta);
double waterDelta = waterMin * ((water[coords[0], coords[1]] + map[coords[0], coords[1]])
/ altitudeTotal);
double sedimentDelta = sediment[x, y] * (waterDelta / water[x, y]);
if (sedimentDelta > 0)
{
sediment[x, y] -= sedimentDelta;
sediment[coords[0], coords[1]] += sedimentDelta;
}
}
}
}
}
// Evaporate
for (x = 0; x < water.Width; x++)
{
for (y = 0; y < water.Height; y++)
{
water[x, y] *= 1.0 - (rainHeight / rounds);
double waterCapacity = waterSaturation * water[x, y];
double sedimentDeposit = sediment[x, y] - waterCapacity;
if (sedimentDeposit > 0)
{
if (mask[x, y])
{
sediment[x, y] -= sedimentDeposit;
map[x, y] += sedimentDeposit;
}
}
}
}
}
// Deposit any remainder (should be minimal)
for (x = 0; x < water.Width; x++)
for (y = 0; y < water.Height; y++)
if (mask[x, y] && sediment[x, y] > 0)
map[x, y] += sediment[x, y];
}
#endregion
}
}
| |
/*
* 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 glacier-2012-06-01.normal.json service model.
*/
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using Amazon.Glacier.Model;
namespace Amazon.Glacier
{
/// <summary>
/// Interface for accessing Glacier
///
/// Amazon Glacier is a storage solution for "cold data."
///
///
/// <para>
/// Amazon Glacier is an extremely low-cost storage service that provides secure, durable,
/// and easy-to-use storage for data backup and archival. With Amazon Glacier, customers
/// can store their data cost effectively for months, years, or decades. Amazon Glacier
/// also enables customers to offload the administrative burdens of operating and scaling
/// storage to AWS, so they don't have to worry about capacity planning, hardware provisioning,
/// data replication, hardware failure and recovery, or time-consuming hardware migrations.
/// </para>
///
/// <para>
/// Amazon Glacier is a great storage choice when low storage cost is paramount, your
/// data is rarely retrieved, and retrieval latency of several hours is acceptable. If
/// your application requires fast or frequent access to your data, consider using Amazon
/// S3. For more information, go to <a href="http://aws.amazon.com/s3/">Amazon Simple
/// Storage Service (Amazon S3)</a>.
/// </para>
///
/// <para>
/// You can store any kind of data in any format. There is no maximum limit on the total
/// amount of data you can store in Amazon Glacier.
/// </para>
///
/// <para>
/// If you are a first-time user of Amazon Glacier, we recommend that you begin by reading
/// the following sections in the <i>Amazon Glacier Developer Guide</i>:
/// </para>
/// <ul> <li>
/// <para>
/// <a href="http://docs.aws.amazon.com/amazonglacier/latest/dev/introduction.html">What
/// is Amazon Glacier</a> - This section of the Developer Guide describes the underlying
/// data model, the operations it supports, and the AWS SDKs that you can use to interact
/// with the service.
/// </para>
/// </li> <li>
/// <para>
/// <a href="http://docs.aws.amazon.com/amazonglacier/latest/dev/amazon-glacier-getting-started.html">Getting
/// Started with Amazon Glacier</a> - The Getting Started section walks you through the
/// process of creating a vault, uploading archives, creating jobs to download archives,
/// retrieving the job output, and deleting archives.
/// </para>
/// </li> </ul>
/// </summary>
public partial interface IAmazonGlacier : IDisposable
{
#region AbortMultipartUpload
/// <summary>
/// Initiates the asynchronous execution of the AbortMultipartUpload operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the AbortMultipartUpload operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<AbortMultipartUploadResponse> AbortMultipartUploadAsync(AbortMultipartUploadRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region AbortVaultLock
/// <summary>
/// Initiates the asynchronous execution of the AbortVaultLock operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the AbortVaultLock operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<AbortVaultLockResponse> AbortVaultLockAsync(AbortVaultLockRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region AddTagsToVault
/// <summary>
/// Initiates the asynchronous execution of the AddTagsToVault operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the AddTagsToVault operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<AddTagsToVaultResponse> AddTagsToVaultAsync(AddTagsToVaultRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region CompleteMultipartUpload
/// <summary>
/// Initiates the asynchronous execution of the CompleteMultipartUpload operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the CompleteMultipartUpload operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<CompleteMultipartUploadResponse> CompleteMultipartUploadAsync(CompleteMultipartUploadRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region CompleteVaultLock
/// <summary>
/// Initiates the asynchronous execution of the CompleteVaultLock operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the CompleteVaultLock operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<CompleteVaultLockResponse> CompleteVaultLockAsync(CompleteVaultLockRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region CreateVault
/// <summary>
/// Initiates the asynchronous execution of the CreateVault operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the CreateVault operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<CreateVaultResponse> CreateVaultAsync(CreateVaultRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region DeleteArchive
/// <summary>
/// Initiates the asynchronous execution of the DeleteArchive operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DeleteArchive operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<DeleteArchiveResponse> DeleteArchiveAsync(DeleteArchiveRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region DeleteVault
/// <summary>
/// Initiates the asynchronous execution of the DeleteVault operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DeleteVault operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<DeleteVaultResponse> DeleteVaultAsync(DeleteVaultRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region DeleteVaultAccessPolicy
/// <summary>
/// Initiates the asynchronous execution of the DeleteVaultAccessPolicy operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DeleteVaultAccessPolicy operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<DeleteVaultAccessPolicyResponse> DeleteVaultAccessPolicyAsync(DeleteVaultAccessPolicyRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region DeleteVaultNotifications
/// <summary>
/// Initiates the asynchronous execution of the DeleteVaultNotifications operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DeleteVaultNotifications operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<DeleteVaultNotificationsResponse> DeleteVaultNotificationsAsync(DeleteVaultNotificationsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region DescribeJob
/// <summary>
/// Initiates the asynchronous execution of the DescribeJob operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DescribeJob operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<DescribeJobResponse> DescribeJobAsync(DescribeJobRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region DescribeVault
/// <summary>
/// Initiates the asynchronous execution of the DescribeVault operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DescribeVault operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<DescribeVaultResponse> DescribeVaultAsync(DescribeVaultRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region GetDataRetrievalPolicy
/// <summary>
/// Initiates the asynchronous execution of the GetDataRetrievalPolicy operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetDataRetrievalPolicy operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<GetDataRetrievalPolicyResponse> GetDataRetrievalPolicyAsync(GetDataRetrievalPolicyRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region GetJobOutput
/// <summary>
/// Initiates the asynchronous execution of the GetJobOutput operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetJobOutput operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<GetJobOutputResponse> GetJobOutputAsync(GetJobOutputRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region GetVaultAccessPolicy
/// <summary>
/// Initiates the asynchronous execution of the GetVaultAccessPolicy operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetVaultAccessPolicy operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<GetVaultAccessPolicyResponse> GetVaultAccessPolicyAsync(GetVaultAccessPolicyRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region GetVaultLock
/// <summary>
/// Initiates the asynchronous execution of the GetVaultLock operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetVaultLock operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<GetVaultLockResponse> GetVaultLockAsync(GetVaultLockRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region GetVaultNotifications
/// <summary>
/// Initiates the asynchronous execution of the GetVaultNotifications operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetVaultNotifications operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<GetVaultNotificationsResponse> GetVaultNotificationsAsync(GetVaultNotificationsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region InitiateJob
/// <summary>
/// Initiates the asynchronous execution of the InitiateJob operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the InitiateJob operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<InitiateJobResponse> InitiateJobAsync(InitiateJobRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region InitiateMultipartUpload
/// <summary>
/// Initiates the asynchronous execution of the InitiateMultipartUpload operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the InitiateMultipartUpload operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<InitiateMultipartUploadResponse> InitiateMultipartUploadAsync(InitiateMultipartUploadRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region InitiateVaultLock
/// <summary>
/// Initiates the asynchronous execution of the InitiateVaultLock operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the InitiateVaultLock operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<InitiateVaultLockResponse> InitiateVaultLockAsync(InitiateVaultLockRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region ListJobs
/// <summary>
/// Initiates the asynchronous execution of the ListJobs operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListJobs operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<ListJobsResponse> ListJobsAsync(ListJobsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region ListMultipartUploads
/// <summary>
/// Initiates the asynchronous execution of the ListMultipartUploads operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListMultipartUploads operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<ListMultipartUploadsResponse> ListMultipartUploadsAsync(ListMultipartUploadsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region ListParts
/// <summary>
/// Initiates the asynchronous execution of the ListParts operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListParts operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<ListPartsResponse> ListPartsAsync(ListPartsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region ListTagsForVault
/// <summary>
/// Initiates the asynchronous execution of the ListTagsForVault operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListTagsForVault operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<ListTagsForVaultResponse> ListTagsForVaultAsync(ListTagsForVaultRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region ListVaults
/// <summary>
/// This operation lists all vaults owned by the calling user's account. The list returned
/// in the response is ASCII-sorted by vault name.
///
///
/// <para>
/// By default, this operation returns up to 1,000 items. If there are more vaults to
/// list, the response <code class="code">marker</code> field contains the vault Amazon
/// Resource Name (ARN) at which to continue the list with a new List Vaults request;
/// otherwise, the <code class="code">marker</code> field is <code class="code">null</code>.
/// To return a list of vaults that begins at a specific vault, set the <code class="code">marker</code>
/// request parameter to the vault ARN you obtained from a previous List Vaults request.
/// You can also limit the number of vaults returned in the response by specifying the
/// <code class="code">limit</code> parameter in the request.
/// </para>
///
/// <para>
/// An AWS account has full permission to perform all operations (actions). However, AWS
/// Identity and Access Management (IAM) users don't have any permissions by default.
/// You must grant them explicit permission to perform specific actions. For more information,
/// see <a href="http://docs.aws.amazon.com/amazonglacier/latest/dev/using-iam-with-amazon-glacier.html">Access
/// Control Using AWS Identity and Access Management (IAM)</a>.
/// </para>
///
/// <para>
/// For conceptual information and underlying REST API, go to <a href="http://docs.aws.amazon.com/amazonglacier/latest/dev/retrieving-vault-info.html">Retrieving
/// Vault Metadata in Amazon Glacier</a> and <a href="http://docs.aws.amazon.com/amazonglacier/latest/dev/api-vaults-get.html">List
/// Vaults </a> in the <i>Amazon Glacier Developer Guide</i>.
/// </para>
/// </summary>
/// <param name="cancellationToken"> ttd1
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the ListVaults service method, as returned by Glacier.</returns>
/// <exception cref="Amazon.Glacier.Model.InvalidParameterValueException">
/// Returned if a parameter of the request is incorrectly specified.
/// </exception>
/// <exception cref="Amazon.Glacier.Model.MissingParameterValueException">
/// Returned if a required header or parameter is missing from the request.
/// </exception>
/// <exception cref="Amazon.Glacier.Model.ResourceNotFoundException">
/// Returned if the specified resource, such as a vault, upload ID, or job ID, does not
/// exist.
/// </exception>
/// <exception cref="Amazon.Glacier.Model.ServiceUnavailableException">
/// Returned if the service cannot complete the request.
/// </exception>
Task<ListVaultsResponse> ListVaultsAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Initiates the asynchronous execution of the ListVaults operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListVaults operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<ListVaultsResponse> ListVaultsAsync(ListVaultsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region RemoveTagsFromVault
/// <summary>
/// Initiates the asynchronous execution of the RemoveTagsFromVault operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the RemoveTagsFromVault operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<RemoveTagsFromVaultResponse> RemoveTagsFromVaultAsync(RemoveTagsFromVaultRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region SetDataRetrievalPolicy
/// <summary>
/// Initiates the asynchronous execution of the SetDataRetrievalPolicy operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the SetDataRetrievalPolicy operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<SetDataRetrievalPolicyResponse> SetDataRetrievalPolicyAsync(SetDataRetrievalPolicyRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region SetVaultAccessPolicy
/// <summary>
/// Initiates the asynchronous execution of the SetVaultAccessPolicy operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the SetVaultAccessPolicy operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<SetVaultAccessPolicyResponse> SetVaultAccessPolicyAsync(SetVaultAccessPolicyRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region SetVaultNotifications
/// <summary>
/// Initiates the asynchronous execution of the SetVaultNotifications operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the SetVaultNotifications operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<SetVaultNotificationsResponse> SetVaultNotificationsAsync(SetVaultNotificationsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region UploadArchive
/// <summary>
/// Initiates the asynchronous execution of the UploadArchive operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the UploadArchive operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<UploadArchiveResponse> UploadArchiveAsync(UploadArchiveRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region UploadMultipartPart
/// <summary>
/// Initiates the asynchronous execution of the UploadMultipartPart operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the UploadMultipartPart operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<UploadMultipartPartResponse> UploadMultipartPartAsync(UploadMultipartPartRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#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.IO;
using System.Runtime.Serialization;
namespace System.Xml
{
public interface IXmlBinaryReaderInitializer
{
void SetInput(byte[] buffer, int offset, int count,
IXmlDictionary dictionary,
XmlDictionaryReaderQuotas quotas,
XmlBinaryReaderSession session,
OnXmlDictionaryReaderClose onClose);
void SetInput(Stream stream,
IXmlDictionary dictionary,
XmlDictionaryReaderQuotas quotas,
XmlBinaryReaderSession session,
OnXmlDictionaryReaderClose onClose);
}
internal class XmlBinaryReader : XmlBaseReader, IXmlBinaryReaderInitializer
{
private bool _isTextWithEndElement;
private bool _buffered;
private ArrayState _arrayState;
private int _arrayCount;
private int _maxBytesPerRead;
private XmlBinaryNodeType _arrayNodeType;
public XmlBinaryReader()
{
}
public void SetInput(byte[] buffer, int offset, int count,
IXmlDictionary dictionary,
XmlDictionaryReaderQuotas quotas,
XmlBinaryReaderSession session,
OnXmlDictionaryReaderClose onClose)
{
if (buffer == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(buffer));
if (offset < 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.Format(SR.ValueMustBeNonNegative)));
if (offset > buffer.Length)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.Format(SR.OffsetExceedsBufferSize, buffer.Length)));
if (count < 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.ValueMustBeNonNegative)));
if (count > buffer.Length - offset)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.SizeExceedsRemainingBufferSpace, buffer.Length - offset)));
MoveToInitial(quotas, session, null);
BufferReader.SetBuffer(buffer, offset, count, dictionary, session);
_buffered = true;
}
public void SetInput(Stream stream,
IXmlDictionary dictionary,
XmlDictionaryReaderQuotas quotas,
XmlBinaryReaderSession session,
OnXmlDictionaryReaderClose onClose)
{
if (stream == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(stream));
MoveToInitial(quotas, session, null);
BufferReader.SetBuffer(stream, dictionary, session);
_buffered = false;
}
private void MoveToInitial(XmlDictionaryReaderQuotas quotas, XmlBinaryReaderSession session, OnXmlDictionaryReaderClose onClose)
{
MoveToInitial(quotas);
_maxBytesPerRead = quotas.MaxBytesPerRead;
_arrayState = ArrayState.None;
_isTextWithEndElement = false;
}
public override void Close()
{
base.Close();
}
public override string ReadElementContentAsString()
{
if (this.Node.NodeType != XmlNodeType.Element)
MoveToStartElement();
if (!CanOptimizeReadElementContent())
return base.ReadElementContentAsString();
string value;
switch (GetNodeType())
{
case XmlBinaryNodeType.Chars8TextWithEndElement:
SkipNodeType();
value = BufferReader.ReadUTF8String(ReadUInt8());
ReadTextWithEndElement();
break;
case XmlBinaryNodeType.DictionaryTextWithEndElement:
SkipNodeType();
value = BufferReader.GetDictionaryString(ReadDictionaryKey()).Value;
ReadTextWithEndElement();
break;
default:
value = base.ReadElementContentAsString();
break;
}
if (value.Length > Quotas.MaxStringContentLength)
XmlExceptionHelper.ThrowMaxStringContentLengthExceeded(this, Quotas.MaxStringContentLength);
return value;
}
public override bool ReadElementContentAsBoolean()
{
if (this.Node.NodeType != XmlNodeType.Element)
MoveToStartElement();
if (!CanOptimizeReadElementContent())
return base.ReadElementContentAsBoolean();
bool value;
switch (GetNodeType())
{
case XmlBinaryNodeType.TrueTextWithEndElement:
SkipNodeType();
value = true;
ReadTextWithEndElement();
break;
case XmlBinaryNodeType.FalseTextWithEndElement:
SkipNodeType();
value = false;
ReadTextWithEndElement();
break;
case XmlBinaryNodeType.BoolTextWithEndElement:
SkipNodeType();
value = (BufferReader.ReadUInt8() != 0);
ReadTextWithEndElement();
break;
default:
value = base.ReadElementContentAsBoolean();
break;
}
return value;
}
public override int ReadElementContentAsInt()
{
if (this.Node.NodeType != XmlNodeType.Element)
MoveToStartElement();
if (!CanOptimizeReadElementContent())
return base.ReadElementContentAsInt();
int value;
switch (GetNodeType())
{
case XmlBinaryNodeType.ZeroTextWithEndElement:
SkipNodeType();
value = 0;
ReadTextWithEndElement();
break;
case XmlBinaryNodeType.OneTextWithEndElement:
SkipNodeType();
value = 1;
ReadTextWithEndElement();
break;
case XmlBinaryNodeType.Int8TextWithEndElement:
SkipNodeType();
value = BufferReader.ReadInt8();
ReadTextWithEndElement();
break;
case XmlBinaryNodeType.Int16TextWithEndElement:
SkipNodeType();
value = BufferReader.ReadInt16();
ReadTextWithEndElement();
break;
case XmlBinaryNodeType.Int32TextWithEndElement:
SkipNodeType();
value = BufferReader.ReadInt32();
ReadTextWithEndElement();
break;
default:
value = base.ReadElementContentAsInt();
break;
}
return value;
}
private bool CanOptimizeReadElementContent()
{
return (_arrayState == ArrayState.None && !Signing);
}
public override float ReadElementContentAsFloat()
{
if (this.Node.NodeType != XmlNodeType.Element)
MoveToStartElement();
if (CanOptimizeReadElementContent() && GetNodeType() == XmlBinaryNodeType.FloatTextWithEndElement)
{
SkipNodeType();
float value = BufferReader.ReadSingle();
ReadTextWithEndElement();
return value;
}
return base.ReadElementContentAsFloat();
}
public override double ReadElementContentAsDouble()
{
if (this.Node.NodeType != XmlNodeType.Element)
MoveToStartElement();
if (CanOptimizeReadElementContent() && GetNodeType() == XmlBinaryNodeType.DoubleTextWithEndElement)
{
SkipNodeType();
double value = BufferReader.ReadDouble();
ReadTextWithEndElement();
return value;
}
return base.ReadElementContentAsDouble();
}
public override decimal ReadElementContentAsDecimal()
{
if (this.Node.NodeType != XmlNodeType.Element)
MoveToStartElement();
if (CanOptimizeReadElementContent() && GetNodeType() == XmlBinaryNodeType.DecimalTextWithEndElement)
{
SkipNodeType();
decimal value = BufferReader.ReadDecimal();
ReadTextWithEndElement();
return value;
}
return base.ReadElementContentAsDecimal();
}
public override DateTime ReadElementContentAsDateTime()
{
if (this.Node.NodeType != XmlNodeType.Element)
MoveToStartElement();
if (CanOptimizeReadElementContent() && GetNodeType() == XmlBinaryNodeType.DateTimeTextWithEndElement)
{
SkipNodeType();
DateTime value = BufferReader.ReadDateTime();
ReadTextWithEndElement();
return value;
}
return base.ReadElementContentAsDateTime();
}
public override TimeSpan ReadElementContentAsTimeSpan()
{
if (this.Node.NodeType != XmlNodeType.Element)
MoveToStartElement();
if (CanOptimizeReadElementContent() && GetNodeType() == XmlBinaryNodeType.TimeSpanTextWithEndElement)
{
SkipNodeType();
TimeSpan value = BufferReader.ReadTimeSpan();
ReadTextWithEndElement();
return value;
}
return base.ReadElementContentAsTimeSpan();
}
public override Guid ReadElementContentAsGuid()
{
if (this.Node.NodeType != XmlNodeType.Element)
MoveToStartElement();
if (CanOptimizeReadElementContent() && GetNodeType() == XmlBinaryNodeType.GuidTextWithEndElement)
{
SkipNodeType();
Guid value = BufferReader.ReadGuid();
ReadTextWithEndElement();
return value;
}
return base.ReadElementContentAsGuid();
}
public override UniqueId ReadElementContentAsUniqueId()
{
if (this.Node.NodeType != XmlNodeType.Element)
MoveToStartElement();
if (CanOptimizeReadElementContent() && GetNodeType() == XmlBinaryNodeType.UniqueIdTextWithEndElement)
{
SkipNodeType();
UniqueId value = BufferReader.ReadUniqueId();
ReadTextWithEndElement();
return value;
}
return base.ReadElementContentAsUniqueId();
}
public override bool TryGetBase64ContentLength(out int length)
{
length = 0;
if (!_buffered)
return false;
if (_arrayState != ArrayState.None)
return false;
int totalLength;
if (!this.Node.Value.TryGetByteArrayLength(out totalLength))
return false;
int offset = BufferReader.Offset;
try
{
bool done = false;
while (!done && !BufferReader.EndOfFile)
{
XmlBinaryNodeType nodeType = GetNodeType();
SkipNodeType();
int actual;
switch (nodeType)
{
case XmlBinaryNodeType.Bytes8TextWithEndElement:
actual = BufferReader.ReadUInt8();
done = true;
break;
case XmlBinaryNodeType.Bytes16TextWithEndElement:
actual = BufferReader.ReadUInt16();
done = true;
break;
case XmlBinaryNodeType.Bytes32TextWithEndElement:
actual = BufferReader.ReadUInt31();
done = true;
break;
case XmlBinaryNodeType.EndElement:
actual = 0;
done = true;
break;
case XmlBinaryNodeType.Bytes8Text:
actual = BufferReader.ReadUInt8();
break;
case XmlBinaryNodeType.Bytes16Text:
actual = BufferReader.ReadUInt16();
break;
case XmlBinaryNodeType.Bytes32Text:
actual = BufferReader.ReadUInt31();
break;
default:
// Non-optimal or unexpected node - fallback
return false;
}
BufferReader.Advance(actual);
if (totalLength > int.MaxValue - actual)
return false;
totalLength += actual;
}
length = totalLength;
return true;
}
finally
{
BufferReader.Offset = offset;
}
}
private void ReadTextWithEndElement()
{
ExitScope();
ReadNode();
}
private XmlAtomicTextNode MoveToAtomicTextWithEndElement()
{
_isTextWithEndElement = true;
return MoveToAtomicText();
}
public override bool Read()
{
if (this.Node.ReadState == ReadState.Closed)
return false;
SignNode();
if (_isTextWithEndElement)
{
_isTextWithEndElement = false;
MoveToEndElement();
return true;
}
if (_arrayState == ArrayState.Content)
{
if (_arrayCount != 0)
{
MoveToArrayElement();
return true;
}
_arrayState = ArrayState.None;
}
if (this.Node.ExitScope)
{
ExitScope();
}
return ReadNode();
}
private bool ReadNode()
{
if (!_buffered)
BufferReader.SetWindow(ElementNode.BufferOffset, _maxBytesPerRead);
if (BufferReader.EndOfFile)
{
MoveToEndOfFile();
return false;
}
XmlBinaryNodeType nodeType;
if (_arrayState == ArrayState.None)
{
nodeType = GetNodeType();
SkipNodeType();
}
else
{
DiagnosticUtility.DebugAssert(_arrayState == ArrayState.Element, "");
nodeType = _arrayNodeType;
_arrayCount--;
_arrayState = ArrayState.Content;
}
XmlElementNode elementNode;
PrefixHandleType prefix;
switch (nodeType)
{
case XmlBinaryNodeType.ShortElement:
elementNode = EnterScope();
elementNode.Prefix.SetValue(PrefixHandleType.Empty);
ReadName(elementNode.LocalName);
ReadAttributes();
elementNode.Namespace = LookupNamespace(PrefixHandleType.Empty);
elementNode.BufferOffset = BufferReader.Offset;
return true;
case XmlBinaryNodeType.Element:
elementNode = EnterScope();
ReadName(elementNode.Prefix);
ReadName(elementNode.LocalName);
ReadAttributes();
elementNode.Namespace = LookupNamespace(elementNode.Prefix);
elementNode.BufferOffset = BufferReader.Offset;
return true;
case XmlBinaryNodeType.ShortDictionaryElement:
elementNode = EnterScope();
elementNode.Prefix.SetValue(PrefixHandleType.Empty);
ReadDictionaryName(elementNode.LocalName);
ReadAttributes();
elementNode.Namespace = LookupNamespace(PrefixHandleType.Empty);
elementNode.BufferOffset = BufferReader.Offset;
return true;
case XmlBinaryNodeType.DictionaryElement:
elementNode = EnterScope();
ReadName(elementNode.Prefix);
ReadDictionaryName(elementNode.LocalName);
ReadAttributes();
elementNode.Namespace = LookupNamespace(elementNode.Prefix);
elementNode.BufferOffset = BufferReader.Offset;
return true;
case XmlBinaryNodeType.PrefixElementA:
case XmlBinaryNodeType.PrefixElementB:
case XmlBinaryNodeType.PrefixElementC:
case XmlBinaryNodeType.PrefixElementD:
case XmlBinaryNodeType.PrefixElementE:
case XmlBinaryNodeType.PrefixElementF:
case XmlBinaryNodeType.PrefixElementG:
case XmlBinaryNodeType.PrefixElementH:
case XmlBinaryNodeType.PrefixElementI:
case XmlBinaryNodeType.PrefixElementJ:
case XmlBinaryNodeType.PrefixElementK:
case XmlBinaryNodeType.PrefixElementL:
case XmlBinaryNodeType.PrefixElementM:
case XmlBinaryNodeType.PrefixElementN:
case XmlBinaryNodeType.PrefixElementO:
case XmlBinaryNodeType.PrefixElementP:
case XmlBinaryNodeType.PrefixElementQ:
case XmlBinaryNodeType.PrefixElementR:
case XmlBinaryNodeType.PrefixElementS:
case XmlBinaryNodeType.PrefixElementT:
case XmlBinaryNodeType.PrefixElementU:
case XmlBinaryNodeType.PrefixElementV:
case XmlBinaryNodeType.PrefixElementW:
case XmlBinaryNodeType.PrefixElementX:
case XmlBinaryNodeType.PrefixElementY:
case XmlBinaryNodeType.PrefixElementZ:
elementNode = EnterScope();
prefix = PrefixHandle.GetAlphaPrefix((int)nodeType - (int)XmlBinaryNodeType.PrefixElementA);
elementNode.Prefix.SetValue(prefix);
ReadName(elementNode.LocalName);
ReadAttributes();
elementNode.Namespace = LookupNamespace(prefix);
elementNode.BufferOffset = BufferReader.Offset;
return true;
case XmlBinaryNodeType.PrefixDictionaryElementA:
case XmlBinaryNodeType.PrefixDictionaryElementB:
case XmlBinaryNodeType.PrefixDictionaryElementC:
case XmlBinaryNodeType.PrefixDictionaryElementD:
case XmlBinaryNodeType.PrefixDictionaryElementE:
case XmlBinaryNodeType.PrefixDictionaryElementF:
case XmlBinaryNodeType.PrefixDictionaryElementG:
case XmlBinaryNodeType.PrefixDictionaryElementH:
case XmlBinaryNodeType.PrefixDictionaryElementI:
case XmlBinaryNodeType.PrefixDictionaryElementJ:
case XmlBinaryNodeType.PrefixDictionaryElementK:
case XmlBinaryNodeType.PrefixDictionaryElementL:
case XmlBinaryNodeType.PrefixDictionaryElementM:
case XmlBinaryNodeType.PrefixDictionaryElementN:
case XmlBinaryNodeType.PrefixDictionaryElementO:
case XmlBinaryNodeType.PrefixDictionaryElementP:
case XmlBinaryNodeType.PrefixDictionaryElementQ:
case XmlBinaryNodeType.PrefixDictionaryElementR:
case XmlBinaryNodeType.PrefixDictionaryElementS:
case XmlBinaryNodeType.PrefixDictionaryElementT:
case XmlBinaryNodeType.PrefixDictionaryElementU:
case XmlBinaryNodeType.PrefixDictionaryElementV:
case XmlBinaryNodeType.PrefixDictionaryElementW:
case XmlBinaryNodeType.PrefixDictionaryElementX:
case XmlBinaryNodeType.PrefixDictionaryElementY:
case XmlBinaryNodeType.PrefixDictionaryElementZ:
elementNode = EnterScope();
prefix = PrefixHandle.GetAlphaPrefix((int)nodeType - (int)XmlBinaryNodeType.PrefixDictionaryElementA);
elementNode.Prefix.SetValue(prefix);
ReadDictionaryName(elementNode.LocalName);
ReadAttributes();
elementNode.Namespace = LookupNamespace(prefix);
elementNode.BufferOffset = BufferReader.Offset;
return true;
case XmlBinaryNodeType.EndElement:
MoveToEndElement();
return true;
case XmlBinaryNodeType.Comment:
ReadName(MoveToComment().Value);
return true;
case XmlBinaryNodeType.EmptyTextWithEndElement:
MoveToAtomicTextWithEndElement().Value.SetValue(ValueHandleType.Empty);
if (this.OutsideRootElement)
VerifyWhitespace();
return true;
case XmlBinaryNodeType.ZeroTextWithEndElement:
MoveToAtomicTextWithEndElement().Value.SetValue(ValueHandleType.Zero);
if (this.OutsideRootElement)
VerifyWhitespace();
return true;
case XmlBinaryNodeType.OneTextWithEndElement:
MoveToAtomicTextWithEndElement().Value.SetValue(ValueHandleType.One);
if (this.OutsideRootElement)
VerifyWhitespace();
return true;
case XmlBinaryNodeType.TrueTextWithEndElement:
MoveToAtomicTextWithEndElement().Value.SetValue(ValueHandleType.True);
if (this.OutsideRootElement)
VerifyWhitespace();
return true;
case XmlBinaryNodeType.FalseTextWithEndElement:
MoveToAtomicTextWithEndElement().Value.SetValue(ValueHandleType.False);
if (this.OutsideRootElement)
VerifyWhitespace();
return true;
case XmlBinaryNodeType.BoolTextWithEndElement:
MoveToAtomicTextWithEndElement().Value.SetValue(ReadUInt8() != 0 ? ValueHandleType.True : ValueHandleType.False);
if (this.OutsideRootElement)
VerifyWhitespace();
return true;
case XmlBinaryNodeType.Chars8TextWithEndElement:
if (_buffered)
ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.UTF8, ReadUInt8());
else
ReadPartialUTF8Text(true, ReadUInt8());
return true;
case XmlBinaryNodeType.Chars8Text:
if (_buffered)
ReadText(MoveToComplexText(), ValueHandleType.UTF8, ReadUInt8());
else
ReadPartialUTF8Text(false, ReadUInt8());
return true;
case XmlBinaryNodeType.Chars16TextWithEndElement:
if (_buffered)
ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.UTF8, ReadUInt16());
else
ReadPartialUTF8Text(true, ReadUInt16());
return true;
case XmlBinaryNodeType.Chars16Text:
if (_buffered)
ReadText(MoveToComplexText(), ValueHandleType.UTF8, ReadUInt16());
else
ReadPartialUTF8Text(false, ReadUInt16());
return true;
case XmlBinaryNodeType.Chars32TextWithEndElement:
if (_buffered)
ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.UTF8, ReadUInt31());
else
ReadPartialUTF8Text(true, ReadUInt31());
return true;
case XmlBinaryNodeType.Chars32Text:
if (_buffered)
ReadText(MoveToComplexText(), ValueHandleType.UTF8, ReadUInt31());
else
ReadPartialUTF8Text(false, ReadUInt31());
return true;
case XmlBinaryNodeType.UnicodeChars8TextWithEndElement:
ReadUnicodeText(true, ReadUInt8());
return true;
case XmlBinaryNodeType.UnicodeChars8Text:
ReadUnicodeText(false, ReadUInt8());
return true;
case XmlBinaryNodeType.UnicodeChars16TextWithEndElement:
ReadUnicodeText(true, ReadUInt16());
return true;
case XmlBinaryNodeType.UnicodeChars16Text:
ReadUnicodeText(false, ReadUInt16());
return true;
case XmlBinaryNodeType.UnicodeChars32TextWithEndElement:
ReadUnicodeText(true, ReadUInt31());
return true;
case XmlBinaryNodeType.UnicodeChars32Text:
ReadUnicodeText(false, ReadUInt31());
return true;
case XmlBinaryNodeType.Bytes8TextWithEndElement:
if (_buffered)
ReadBinaryText(MoveToAtomicTextWithEndElement(), ReadUInt8());
else
ReadPartialBinaryText(true, ReadUInt8());
return true;
case XmlBinaryNodeType.Bytes8Text:
if (_buffered)
ReadBinaryText(MoveToComplexText(), ReadUInt8());
else
ReadPartialBinaryText(false, ReadUInt8());
return true;
case XmlBinaryNodeType.Bytes16TextWithEndElement:
if (_buffered)
ReadBinaryText(MoveToAtomicTextWithEndElement(), ReadUInt16());
else
ReadPartialBinaryText(true, ReadUInt16());
return true;
case XmlBinaryNodeType.Bytes16Text:
if (_buffered)
ReadBinaryText(MoveToComplexText(), ReadUInt16());
else
ReadPartialBinaryText(false, ReadUInt16());
return true;
case XmlBinaryNodeType.Bytes32TextWithEndElement:
if (_buffered)
ReadBinaryText(MoveToAtomicTextWithEndElement(), ReadUInt31());
else
ReadPartialBinaryText(true, ReadUInt31());
return true;
case XmlBinaryNodeType.Bytes32Text:
if (_buffered)
ReadBinaryText(MoveToComplexText(), ReadUInt31());
else
ReadPartialBinaryText(false, ReadUInt31());
return true;
case XmlBinaryNodeType.DictionaryTextWithEndElement:
MoveToAtomicTextWithEndElement().Value.SetDictionaryValue(ReadDictionaryKey());
return true;
case XmlBinaryNodeType.UniqueIdTextWithEndElement:
ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.UniqueId, ValueHandleLength.UniqueId);
return true;
case XmlBinaryNodeType.GuidTextWithEndElement:
ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.Guid, ValueHandleLength.Guid);
return true;
case XmlBinaryNodeType.DecimalTextWithEndElement:
ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.Decimal, ValueHandleLength.Decimal);
return true;
case XmlBinaryNodeType.Int8TextWithEndElement:
ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.Int8, ValueHandleLength.Int8);
return true;
case XmlBinaryNodeType.Int16TextWithEndElement:
ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.Int16, ValueHandleLength.Int16);
return true;
case XmlBinaryNodeType.Int32TextWithEndElement:
ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.Int32, ValueHandleLength.Int32);
return true;
case XmlBinaryNodeType.Int64TextWithEndElement:
ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.Int64, ValueHandleLength.Int64);
return true;
case XmlBinaryNodeType.UInt64TextWithEndElement:
ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.UInt64, ValueHandleLength.UInt64);
return true;
case XmlBinaryNodeType.FloatTextWithEndElement:
ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.Single, ValueHandleLength.Single);
return true;
case XmlBinaryNodeType.DoubleTextWithEndElement:
ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.Double, ValueHandleLength.Double);
return true;
case XmlBinaryNodeType.TimeSpanTextWithEndElement:
ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.TimeSpan, ValueHandleLength.TimeSpan);
return true;
case XmlBinaryNodeType.DateTimeTextWithEndElement:
ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.DateTime, ValueHandleLength.DateTime);
return true;
case XmlBinaryNodeType.QNameDictionaryTextWithEndElement:
BufferReader.ReadQName(MoveToAtomicTextWithEndElement().Value);
return true;
case XmlBinaryNodeType.Array:
ReadArray();
return true;
default:
BufferReader.ReadValue(nodeType, MoveToComplexText().Value);
return true;
}
}
private void VerifyWhitespace()
{
if (!this.Node.Value.IsWhitespace())
XmlExceptionHelper.ThrowInvalidBinaryFormat(this);
}
private void ReadAttributes()
{
XmlBinaryNodeType nodeType = GetNodeType();
if (nodeType < XmlBinaryNodeType.MinAttribute || nodeType > XmlBinaryNodeType.MaxAttribute)
return;
ReadAttributes2();
}
private void ReadAttributes2()
{
int startOffset = 0;
if (_buffered)
startOffset = BufferReader.Offset;
while (true)
{
XmlAttributeNode attributeNode;
Namespace nameSpace;
PrefixHandleType prefix;
XmlBinaryNodeType nodeType = GetNodeType();
switch (nodeType)
{
case XmlBinaryNodeType.ShortAttribute:
SkipNodeType();
attributeNode = AddAttribute();
attributeNode.Prefix.SetValue(PrefixHandleType.Empty);
ReadName(attributeNode.LocalName);
ReadAttributeText(attributeNode.AttributeText);
break;
case XmlBinaryNodeType.Attribute:
SkipNodeType();
attributeNode = AddAttribute();
ReadName(attributeNode.Prefix);
ReadName(attributeNode.LocalName);
ReadAttributeText(attributeNode.AttributeText);
FixXmlAttribute(attributeNode);
break;
case XmlBinaryNodeType.ShortDictionaryAttribute:
SkipNodeType();
attributeNode = AddAttribute();
attributeNode.Prefix.SetValue(PrefixHandleType.Empty);
ReadDictionaryName(attributeNode.LocalName);
ReadAttributeText(attributeNode.AttributeText);
break;
case XmlBinaryNodeType.DictionaryAttribute:
SkipNodeType();
attributeNode = AddAttribute();
ReadName(attributeNode.Prefix);
ReadDictionaryName(attributeNode.LocalName);
ReadAttributeText(attributeNode.AttributeText);
break;
case XmlBinaryNodeType.XmlnsAttribute:
SkipNodeType();
nameSpace = AddNamespace();
ReadName(nameSpace.Prefix);
ReadName(nameSpace.Uri);
attributeNode = AddXmlnsAttribute(nameSpace);
break;
case XmlBinaryNodeType.ShortXmlnsAttribute:
SkipNodeType();
nameSpace = AddNamespace();
nameSpace.Prefix.SetValue(PrefixHandleType.Empty);
ReadName(nameSpace.Uri);
attributeNode = AddXmlnsAttribute(nameSpace);
break;
case XmlBinaryNodeType.ShortDictionaryXmlnsAttribute:
SkipNodeType();
nameSpace = AddNamespace();
nameSpace.Prefix.SetValue(PrefixHandleType.Empty);
ReadDictionaryName(nameSpace.Uri);
attributeNode = AddXmlnsAttribute(nameSpace);
break;
case XmlBinaryNodeType.DictionaryXmlnsAttribute:
SkipNodeType();
nameSpace = AddNamespace();
ReadName(nameSpace.Prefix);
ReadDictionaryName(nameSpace.Uri);
attributeNode = AddXmlnsAttribute(nameSpace);
break;
case XmlBinaryNodeType.PrefixDictionaryAttributeA:
case XmlBinaryNodeType.PrefixDictionaryAttributeB:
case XmlBinaryNodeType.PrefixDictionaryAttributeC:
case XmlBinaryNodeType.PrefixDictionaryAttributeD:
case XmlBinaryNodeType.PrefixDictionaryAttributeE:
case XmlBinaryNodeType.PrefixDictionaryAttributeF:
case XmlBinaryNodeType.PrefixDictionaryAttributeG:
case XmlBinaryNodeType.PrefixDictionaryAttributeH:
case XmlBinaryNodeType.PrefixDictionaryAttributeI:
case XmlBinaryNodeType.PrefixDictionaryAttributeJ:
case XmlBinaryNodeType.PrefixDictionaryAttributeK:
case XmlBinaryNodeType.PrefixDictionaryAttributeL:
case XmlBinaryNodeType.PrefixDictionaryAttributeM:
case XmlBinaryNodeType.PrefixDictionaryAttributeN:
case XmlBinaryNodeType.PrefixDictionaryAttributeO:
case XmlBinaryNodeType.PrefixDictionaryAttributeP:
case XmlBinaryNodeType.PrefixDictionaryAttributeQ:
case XmlBinaryNodeType.PrefixDictionaryAttributeR:
case XmlBinaryNodeType.PrefixDictionaryAttributeS:
case XmlBinaryNodeType.PrefixDictionaryAttributeT:
case XmlBinaryNodeType.PrefixDictionaryAttributeU:
case XmlBinaryNodeType.PrefixDictionaryAttributeV:
case XmlBinaryNodeType.PrefixDictionaryAttributeW:
case XmlBinaryNodeType.PrefixDictionaryAttributeX:
case XmlBinaryNodeType.PrefixDictionaryAttributeY:
case XmlBinaryNodeType.PrefixDictionaryAttributeZ:
SkipNodeType();
attributeNode = AddAttribute();
prefix = PrefixHandle.GetAlphaPrefix((int)nodeType - (int)XmlBinaryNodeType.PrefixDictionaryAttributeA);
attributeNode.Prefix.SetValue(prefix);
ReadDictionaryName(attributeNode.LocalName);
ReadAttributeText(attributeNode.AttributeText);
break;
case XmlBinaryNodeType.PrefixAttributeA:
case XmlBinaryNodeType.PrefixAttributeB:
case XmlBinaryNodeType.PrefixAttributeC:
case XmlBinaryNodeType.PrefixAttributeD:
case XmlBinaryNodeType.PrefixAttributeE:
case XmlBinaryNodeType.PrefixAttributeF:
case XmlBinaryNodeType.PrefixAttributeG:
case XmlBinaryNodeType.PrefixAttributeH:
case XmlBinaryNodeType.PrefixAttributeI:
case XmlBinaryNodeType.PrefixAttributeJ:
case XmlBinaryNodeType.PrefixAttributeK:
case XmlBinaryNodeType.PrefixAttributeL:
case XmlBinaryNodeType.PrefixAttributeM:
case XmlBinaryNodeType.PrefixAttributeN:
case XmlBinaryNodeType.PrefixAttributeO:
case XmlBinaryNodeType.PrefixAttributeP:
case XmlBinaryNodeType.PrefixAttributeQ:
case XmlBinaryNodeType.PrefixAttributeR:
case XmlBinaryNodeType.PrefixAttributeS:
case XmlBinaryNodeType.PrefixAttributeT:
case XmlBinaryNodeType.PrefixAttributeU:
case XmlBinaryNodeType.PrefixAttributeV:
case XmlBinaryNodeType.PrefixAttributeW:
case XmlBinaryNodeType.PrefixAttributeX:
case XmlBinaryNodeType.PrefixAttributeY:
case XmlBinaryNodeType.PrefixAttributeZ:
SkipNodeType();
attributeNode = AddAttribute();
prefix = PrefixHandle.GetAlphaPrefix((int)nodeType - (int)XmlBinaryNodeType.PrefixAttributeA);
attributeNode.Prefix.SetValue(prefix);
ReadName(attributeNode.LocalName);
ReadAttributeText(attributeNode.AttributeText);
break;
default:
ProcessAttributes();
return;
}
}
}
private void ReadText(XmlTextNode textNode, ValueHandleType type, int length)
{
int offset = BufferReader.ReadBytes(length);
textNode.Value.SetValue(type, offset, length);
if (this.OutsideRootElement)
VerifyWhitespace();
}
private void ReadBinaryText(XmlTextNode textNode, int length)
{
ReadText(textNode, ValueHandleType.Base64, length);
}
private void ReadPartialUTF8Text(bool withEndElement, int length)
{
// The maxBytesPerRead includes the quota for the XmlBinaryNodeType.TextNode, so we need
// to account for that.
const int maxTextNodeLength = 5;
int maxLength = Math.Max(_maxBytesPerRead - maxTextNodeLength, 0);
if (length <= maxLength)
{
if (withEndElement)
ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.UTF8, length);
else
ReadText(MoveToComplexText(), ValueHandleType.UTF8, length);
}
else
{
// We also need to make sure we have enough room to insert a new XmlBinaryNodeType.TextNode
// for the split data.
int actual = Math.Max(maxLength - maxTextNodeLength, 0);
int offset = BufferReader.ReadBytes(actual);
// We need to make sure we don't split a utf8 character, so scan backwards for a
// character boundary. We'll actually always push off at least one character since
// although we find the character boundary, we don't bother to figure out if we have
// all the bytes that comprise the character.
int i;
for (i = offset + actual - 1; i >= offset; i--)
{
byte b = BufferReader.GetByte(i);
// The first byte of UTF8 character sequence has either the high bit off, or the
// two high bits set.
if ((b & 0x80) == 0 || (b & 0xC0) == 0xC0)
break;
}
// Move any split characters so we can insert the node
int byteCount = (offset + actual - i);
// Include the split characters in the count
BufferReader.Offset = BufferReader.Offset - byteCount;
actual -= byteCount;
MoveToComplexText().Value.SetValue(ValueHandleType.UTF8, offset, actual);
if (this.OutsideRootElement)
VerifyWhitespace();
XmlBinaryNodeType nodeType = (withEndElement ? XmlBinaryNodeType.Chars32TextWithEndElement : XmlBinaryNodeType.Chars32Text);
InsertNode(nodeType, length - actual);
}
}
private void ReadUnicodeText(bool withEndElement, int length)
{
if ((length & 1) != 0)
XmlExceptionHelper.ThrowInvalidBinaryFormat(this);
if (_buffered)
{
if (withEndElement)
{
ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.Unicode, length);
}
else
{
ReadText(MoveToComplexText(), ValueHandleType.Unicode, length);
}
}
else
{
ReadPartialUnicodeText(withEndElement, length);
}
}
private void ReadPartialUnicodeText(bool withEndElement, int length)
{
// The maxBytesPerRead includes the quota for the XmlBinaryNodeType.TextNode, so we need
// to account for that.
const int maxTextNodeLength = 5;
int maxLength = Math.Max(_maxBytesPerRead - maxTextNodeLength, 0);
if (length <= maxLength)
{
if (withEndElement)
ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.Unicode, length);
else
ReadText(MoveToComplexText(), ValueHandleType.Unicode, length);
}
else
{
// We also need to make sure we have enough room to insert a new XmlBinaryNodeType.TextNode
// for the split data.
int actual = Math.Max(maxLength - maxTextNodeLength, 0);
// Make sure we break on a char boundary
if ((actual & 1) != 0)
actual--;
int offset = BufferReader.ReadBytes(actual);
// We need to make sure we don't split a Unicode surrogate character
int byteCount = 0;
char ch = (char)BufferReader.GetInt16(offset + actual - sizeof(char));
// If the last char is a high surrogate char, then move back
if (ch >= 0xD800 && ch < 0xDC00)
byteCount = sizeof(char);
// Include the split characters in the count
BufferReader.Offset = BufferReader.Offset - byteCount;
actual -= byteCount;
MoveToComplexText().Value.SetValue(ValueHandleType.Unicode, offset, actual);
if (this.OutsideRootElement)
VerifyWhitespace();
XmlBinaryNodeType nodeType = (withEndElement ? XmlBinaryNodeType.UnicodeChars32TextWithEndElement : XmlBinaryNodeType.UnicodeChars32Text);
InsertNode(nodeType, length - actual);
}
}
private void ReadPartialBinaryText(bool withEndElement, int length)
{
const int nodeLength = 5;
int maxBytesPerRead = Math.Max(_maxBytesPerRead - nodeLength, 0);
if (length <= maxBytesPerRead)
{
if (withEndElement)
ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.Base64, length);
else
ReadText(MoveToComplexText(), ValueHandleType.Base64, length);
}
else
{
int actual = maxBytesPerRead;
if (actual > 3)
actual -= (actual % 3);
ReadText(MoveToComplexText(), ValueHandleType.Base64, actual);
XmlBinaryNodeType nodeType = (withEndElement ? XmlBinaryNodeType.Bytes32TextWithEndElement : XmlBinaryNodeType.Bytes32Text);
InsertNode(nodeType, length - actual);
}
}
private void InsertNode(XmlBinaryNodeType nodeType, int length)
{
byte[] buffer = new byte[5];
buffer[0] = (byte)nodeType;
unchecked
{
buffer[1] = (byte)length;
length >>= 8;
buffer[2] = (byte)length;
length >>= 8;
buffer[3] = (byte)length;
}
length >>= 8;
buffer[4] = (byte)length;
BufferReader.InsertBytes(buffer, 0, buffer.Length);
}
private void ReadAttributeText(XmlAttributeTextNode textNode)
{
XmlBinaryNodeType nodeType = GetNodeType();
SkipNodeType();
BufferReader.ReadValue(nodeType, textNode.Value);
}
private void ReadName(ValueHandle value)
{
int length = ReadMultiByteUInt31();
int offset = BufferReader.ReadBytes(length);
value.SetValue(ValueHandleType.UTF8, offset, length);
}
private void ReadName(StringHandle handle)
{
int length = ReadMultiByteUInt31();
int offset = BufferReader.ReadBytes(length);
handle.SetValue(offset, length);
}
private void ReadName(PrefixHandle prefix)
{
int length = ReadMultiByteUInt31();
int offset = BufferReader.ReadBytes(length);
prefix.SetValue(offset, length);
}
private void ReadDictionaryName(StringHandle s)
{
int key = ReadDictionaryKey();
s.SetValue(key);
}
private XmlBinaryNodeType GetNodeType()
{
return BufferReader.GetNodeType();
}
private void SkipNodeType()
{
BufferReader.SkipNodeType();
}
private int ReadDictionaryKey()
{
return BufferReader.ReadDictionaryKey();
}
private int ReadMultiByteUInt31()
{
return BufferReader.ReadMultiByteUInt31();
}
private int ReadUInt8()
{
return BufferReader.ReadUInt8();
}
private int ReadUInt16()
{
return BufferReader.ReadUInt16();
}
private int ReadUInt31()
{
return BufferReader.ReadUInt31();
}
private bool IsValidArrayType(XmlBinaryNodeType nodeType)
{
switch (nodeType)
{
case XmlBinaryNodeType.BoolTextWithEndElement:
case XmlBinaryNodeType.Int16TextWithEndElement:
case XmlBinaryNodeType.Int32TextWithEndElement:
case XmlBinaryNodeType.Int64TextWithEndElement:
case XmlBinaryNodeType.FloatTextWithEndElement:
case XmlBinaryNodeType.DoubleTextWithEndElement:
case XmlBinaryNodeType.DecimalTextWithEndElement:
case XmlBinaryNodeType.DateTimeTextWithEndElement:
case XmlBinaryNodeType.TimeSpanTextWithEndElement:
case XmlBinaryNodeType.GuidTextWithEndElement:
return true;
default:
return false;
}
}
private void ReadArray()
{
if (GetNodeType() == XmlBinaryNodeType.Array) // Prevent recursion
XmlExceptionHelper.ThrowInvalidBinaryFormat(this);
ReadNode(); // ReadStartElement
if (this.Node.NodeType != XmlNodeType.Element)
XmlExceptionHelper.ThrowInvalidBinaryFormat(this);
if (GetNodeType() == XmlBinaryNodeType.Array) // Prevent recursion
XmlExceptionHelper.ThrowInvalidBinaryFormat(this);
ReadNode(); // ReadEndElement
if (this.Node.NodeType != XmlNodeType.EndElement)
XmlExceptionHelper.ThrowInvalidBinaryFormat(this);
_arrayState = ArrayState.Element;
_arrayNodeType = GetNodeType();
if (!IsValidArrayType(_arrayNodeType))
XmlExceptionHelper.ThrowInvalidBinaryFormat(this);
SkipNodeType();
_arrayCount = ReadMultiByteUInt31();
if (_arrayCount == 0)
XmlExceptionHelper.ThrowInvalidBinaryFormat(this);
MoveToArrayElement();
}
private void MoveToArrayElement()
{
_arrayState = ArrayState.Element;
MoveToNode(ElementNode);
}
private void SkipArrayElements(int count)
{
_arrayCount -= count;
if (_arrayCount == 0)
{
_arrayState = ArrayState.None;
ExitScope();
ReadNode();
}
}
public override bool IsStartArray(out Type type)
{
type = null;
if (_arrayState != ArrayState.Element)
return false;
switch (_arrayNodeType)
{
case XmlBinaryNodeType.BoolTextWithEndElement:
type = typeof(bool);
break;
case XmlBinaryNodeType.Int16TextWithEndElement:
type = typeof(short);
break;
case XmlBinaryNodeType.Int32TextWithEndElement:
type = typeof(int);
break;
case XmlBinaryNodeType.Int64TextWithEndElement:
type = typeof(long);
break;
case XmlBinaryNodeType.FloatTextWithEndElement:
type = typeof(float);
break;
case XmlBinaryNodeType.DoubleTextWithEndElement:
type = typeof(double);
break;
case XmlBinaryNodeType.DecimalTextWithEndElement:
type = typeof(decimal);
break;
case XmlBinaryNodeType.DateTimeTextWithEndElement:
type = typeof(DateTime);
break;
case XmlBinaryNodeType.GuidTextWithEndElement:
type = typeof(Guid);
break;
case XmlBinaryNodeType.TimeSpanTextWithEndElement:
type = typeof(TimeSpan);
break;
case XmlBinaryNodeType.UniqueIdTextWithEndElement:
type = typeof(UniqueId);
break;
default:
return false;
}
return true;
}
public override bool TryGetArrayLength(out int count)
{
count = 0;
if (!_buffered)
return false;
if (_arrayState != ArrayState.Element)
return false;
count = _arrayCount;
return true;
}
private bool IsStartArray(string localName, string namespaceUri, XmlBinaryNodeType nodeType)
{
return IsStartElement(localName, namespaceUri) && _arrayState == ArrayState.Element && _arrayNodeType == nodeType && !Signing;
}
private bool IsStartArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, XmlBinaryNodeType nodeType)
{
return IsStartElement(localName, namespaceUri) && _arrayState == ArrayState.Element && _arrayNodeType == nodeType && !Signing;
}
private void CheckArray(Array array, int offset, int count)
{
if (array == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(array)));
if (offset < 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.Format(SR.ValueMustBeNonNegative)));
if (offset > array.Length)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.Format(SR.OffsetExceedsBufferSize, array.Length)));
if (count < 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.ValueMustBeNonNegative)));
if (count > array.Length - offset)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.SizeExceedsRemainingBufferSpace, array.Length - offset)));
}
private unsafe int ReadArray(bool[] array, int offset, int count)
{
CheckArray(array, offset, count);
int actual = Math.Min(count, _arrayCount);
fixed (bool* items = &array[offset])
{
BufferReader.UnsafeReadArray((byte*)items, (byte*)&items[actual]);
}
SkipArrayElements(actual);
return actual;
}
public override int ReadArray(string localName, string namespaceUri, bool[] array, int offset, int count)
{
if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.BoolTextWithEndElement))
return ReadArray(array, offset, count);
return base.ReadArray(localName, namespaceUri, array, offset, count);
}
public override int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, bool[] array, int offset, int count)
{
if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.BoolTextWithEndElement))
return ReadArray(array, offset, count);
return base.ReadArray(localName, namespaceUri, array, offset, count);
}
private unsafe int ReadArray(short[] array, int offset, int count)
{
CheckArray(array, offset, count);
int actual = Math.Min(count, _arrayCount);
fixed (short* items = &array[offset])
{
BufferReader.UnsafeReadArray((byte*)items, (byte*)&items[actual]);
}
SkipArrayElements(actual);
return actual;
}
public override int ReadArray(string localName, string namespaceUri, short[] array, int offset, int count)
{
if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.Int16TextWithEndElement) && BitConverter.IsLittleEndian)
return ReadArray(array, offset, count);
return base.ReadArray(localName, namespaceUri, array, offset, count);
}
public override int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, short[] array, int offset, int count)
{
if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.Int16TextWithEndElement) && BitConverter.IsLittleEndian)
return ReadArray(array, offset, count);
return base.ReadArray(localName, namespaceUri, array, offset, count);
}
private unsafe int ReadArray(int[] array, int offset, int count)
{
CheckArray(array, offset, count);
int actual = Math.Min(count, _arrayCount);
fixed (int* items = &array[offset])
{
BufferReader.UnsafeReadArray((byte*)items, (byte*)&items[actual]);
}
SkipArrayElements(actual);
return actual;
}
public override int ReadArray(string localName, string namespaceUri, int[] array, int offset, int count)
{
if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.Int32TextWithEndElement) && BitConverter.IsLittleEndian)
return ReadArray(array, offset, count);
return base.ReadArray(localName, namespaceUri, array, offset, count);
}
public override int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, int[] array, int offset, int count)
{
if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.Int32TextWithEndElement) && BitConverter.IsLittleEndian)
return ReadArray(array, offset, count);
return base.ReadArray(localName, namespaceUri, array, offset, count);
}
private unsafe int ReadArray(long[] array, int offset, int count)
{
CheckArray(array, offset, count);
int actual = Math.Min(count, _arrayCount);
fixed (long* items = &array[offset])
{
BufferReader.UnsafeReadArray((byte*)items, (byte*)&items[actual]);
}
SkipArrayElements(actual);
return actual;
}
public override int ReadArray(string localName, string namespaceUri, long[] array, int offset, int count)
{
if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.Int64TextWithEndElement) && BitConverter.IsLittleEndian)
return ReadArray(array, offset, count);
return base.ReadArray(localName, namespaceUri, array, offset, count);
}
public override int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, long[] array, int offset, int count)
{
if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.Int64TextWithEndElement) && BitConverter.IsLittleEndian)
return ReadArray(array, offset, count);
return base.ReadArray(localName, namespaceUri, array, offset, count);
}
private unsafe int ReadArray(float[] array, int offset, int count)
{
CheckArray(array, offset, count);
int actual = Math.Min(count, _arrayCount);
fixed (float* items = &array[offset])
{
BufferReader.UnsafeReadArray((byte*)items, (byte*)&items[actual]);
}
SkipArrayElements(actual);
return actual;
}
public override int ReadArray(string localName, string namespaceUri, float[] array, int offset, int count)
{
if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.FloatTextWithEndElement))
return ReadArray(array, offset, count);
return base.ReadArray(localName, namespaceUri, array, offset, count);
}
public override int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, float[] array, int offset, int count)
{
if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.FloatTextWithEndElement))
return ReadArray(array, offset, count);
return base.ReadArray(localName, namespaceUri, array, offset, count);
}
private unsafe int ReadArray(double[] array, int offset, int count)
{
CheckArray(array, offset, count);
int actual = Math.Min(count, _arrayCount);
fixed (double* items = &array[offset])
{
BufferReader.UnsafeReadArray((byte*)items, (byte*)&items[actual]);
}
SkipArrayElements(actual);
return actual;
}
public override int ReadArray(string localName, string namespaceUri, double[] array, int offset, int count)
{
if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.DoubleTextWithEndElement))
return ReadArray(array, offset, count);
return base.ReadArray(localName, namespaceUri, array, offset, count);
}
public override int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, double[] array, int offset, int count)
{
if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.DoubleTextWithEndElement))
return ReadArray(array, offset, count);
return base.ReadArray(localName, namespaceUri, array, offset, count);
}
private unsafe int ReadArray(decimal[] array, int offset, int count)
{
CheckArray(array, offset, count);
int actual = Math.Min(count, _arrayCount);
fixed (decimal* items = &array[offset])
{
BufferReader.UnsafeReadArray((byte*)items, (byte*)&items[actual]);
}
SkipArrayElements(actual);
return actual;
}
public override int ReadArray(string localName, string namespaceUri, decimal[] array, int offset, int count)
{
if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.DecimalTextWithEndElement))
return ReadArray(array, offset, count);
return base.ReadArray(localName, namespaceUri, array, offset, count);
}
public override int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, decimal[] array, int offset, int count)
{
if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.DecimalTextWithEndElement))
return ReadArray(array, offset, count);
return base.ReadArray(localName, namespaceUri, array, offset, count);
}
// DateTime
private int ReadArray(DateTime[] array, int offset, int count)
{
CheckArray(array, offset, count);
int actual = Math.Min(count, _arrayCount);
for (int i = 0; i < actual; i++)
{
array[offset + i] = BufferReader.ReadDateTime();
}
SkipArrayElements(actual);
return actual;
}
public override int ReadArray(string localName, string namespaceUri, DateTime[] array, int offset, int count)
{
if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.DateTimeTextWithEndElement))
return ReadArray(array, offset, count);
return base.ReadArray(localName, namespaceUri, array, offset, count);
}
public override int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, DateTime[] array, int offset, int count)
{
if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.DateTimeTextWithEndElement))
return ReadArray(array, offset, count);
return base.ReadArray(localName, namespaceUri, array, offset, count);
}
// Guid
private int ReadArray(Guid[] array, int offset, int count)
{
CheckArray(array, offset, count);
int actual = Math.Min(count, _arrayCount);
for (int i = 0; i < actual; i++)
{
array[offset + i] = BufferReader.ReadGuid();
}
SkipArrayElements(actual);
return actual;
}
public override int ReadArray(string localName, string namespaceUri, Guid[] array, int offset, int count)
{
if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.GuidTextWithEndElement))
return ReadArray(array, offset, count);
return base.ReadArray(localName, namespaceUri, array, offset, count);
}
public override int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, Guid[] array, int offset, int count)
{
if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.GuidTextWithEndElement))
return ReadArray(array, offset, count);
return base.ReadArray(localName, namespaceUri, array, offset, count);
}
// TimeSpan
private int ReadArray(TimeSpan[] array, int offset, int count)
{
CheckArray(array, offset, count);
int actual = Math.Min(count, _arrayCount);
for (int i = 0; i < actual; i++)
{
array[offset + i] = BufferReader.ReadTimeSpan();
}
SkipArrayElements(actual);
return actual;
}
public override int ReadArray(string localName, string namespaceUri, TimeSpan[] array, int offset, int count)
{
if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.TimeSpanTextWithEndElement))
return ReadArray(array, offset, count);
return base.ReadArray(localName, namespaceUri, array, offset, count);
}
public override int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, TimeSpan[] array, int offset, int count)
{
if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.TimeSpanTextWithEndElement))
return ReadArray(array, offset, count);
return base.ReadArray(localName, namespaceUri, array, offset, count);
}
private enum ArrayState
{
None,
Element,
Content
}
protected override XmlSigningNodeWriter CreateSigningNodeWriter()
{
return new XmlSigningNodeWriter(false);
}
}
}
| |
using Facepunch.Network.Raknet;
using Microsoft.Win32;
using Newtonsoft.Json;
using SilentOrbit.ProtocolBuffers;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace Rust_Interceptor {
public class RustInterceptor {
public bool ClientPackets = false;
public bool RememberPackets = false;
public bool RememberFilteredOnly = false;
public string CommandPrefix = "RI.";
internal bool isAlive;
public bool IsAlive {
get {
return isAlive;
}
}
public int RememberedPacketCount {
get {
return remeberedPackets.Count;
}
}
internal static Packet serverPacket;
internal static Packet clientPacket;
internal static List<Packet> remeberedPackets;
internal static List<Packet.Rust> packetFilter;
internal string serverIP;
internal int serverPort;
internal int listenPort;
internal Queue<Packet> packetQueue;
internal RakNetPeer clientPeer;
internal RakNetPeer serverPeer;
internal readonly Thread backgroundThread;
internal Action<Packet> packetHandlerCallback = null;
internal Action<string> commandCallback = null;
public RustInterceptor(string server = "127.0.0.1", int port = 28015, int listenPort = 5678) {
StringPool.Fill();
serverIP = server;
serverPort = port;
this.listenPort = listenPort;
serverPacket = new Packet();
clientPacket = new Packet();
backgroundThread = new Thread(BackgroundThread);
packetQueue = new Queue<Packet>();
remeberedPackets = new List<Packet>();
packetFilter = new List<Packet.Rust>();
}
public void RegisterCallback(Action<Packet> handler) {
packetHandlerCallback = handler;
}
public static ulong serverGUID {
get { return serverPacket.incomingGUID; }
}
public static ulong clientGUID {
get { return clientPacket.incomingGUID; }
}
public void AddPacketsToFilter(params Packet.Rust[] packetTypes) {
foreach (Packet.Rust type in packetTypes) {
if (!packetFilter.Contains(type))
packetFilter.Add(type);
}
}
internal bool IsFiltered(Packet p) {
if (p.type != Packet.PacketType.RUST) return false;
if (packetFilter.Count == 0)
return true;
else
return packetFilter.Contains((Packet.Rust)p.packetID);
}
public void Start() {
isAlive = true;
backgroundThread.Start();
}
public void Stop() {
isAlive = false;
while (backgroundThread.IsAlive) Thread.Sleep(1);
}
public bool HasPacket() {
return packetQueue.Count > 0;
}
public Packet[] LoadPackets(string filename = "packets.json") {
var json = File.ReadAllText(filename);
return JsonConvert.DeserializeObject<Packet[]>(json);
}
public void SavePackets(Packet[] packet, string filename = "packets.json", Formatting formatting = Formatting.Indented, bool informative = true) {
Serializer.informativeDump = informative;
JsonWriter jsonWriter = new JsonTextWriter(new StreamWriter(File.Create(filename)));
jsonWriter.Formatting = formatting;
jsonWriter.WriteStartArray();
foreach (Packet p in packet) {
Serializer.Serialize(jsonWriter, p);
}
jsonWriter.WriteEndArray();
jsonWriter.Close();
}
public void SavePackets(List<Packet> packets, string filename = "packets.json", Formatting formatting = Formatting.Indented, bool informative = true) {
SavePackets(packets.ToArray(), filename, formatting, informative);
}
public void SavePackets(string filename = "packets.json", Formatting formatting = Formatting.Indented, bool informative = true) {
if (!RememberPackets) {
Console.WriteLine("There are no packets to save. Set 'RememberPackets' before you start or pass in packets to this function");
return;
}
SavePackets(remeberedPackets.ToArray(), filename, formatting, informative);
}
public void GetPacket(out Packet packet) {
while (packetQueue.Count < 1) Thread.Sleep(1);
lock (packetQueue) {
packet = packetQueue.Dequeue();
}
}
internal void BackgroundThread() {
Thread thread = new Thread(() => Clipboard.SetText(string.Format("connect 127.0.0.1:{0}", listenPort)));
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
thread.Join();
Console.WriteLine("Server address copied to Clipboard (F1 -> Paste -> Enter)");
Console.WriteLine("Listening on {0}", listenPort);
clientPeer = RakNetPeer.CreateServer("0.0.0.0", listenPort, 1);
var emptyPacket = false;
var hasClientPacket = false;
var hasServerPacket = false;
while (isAlive) {
hasClientPacket = clientPeer.Receive();
hasServerPacket = (serverPeer == null ? false : serverPeer.Receive());
if (!hasClientPacket && !hasServerPacket) {
Thread.Sleep(1);
continue;
}
if (hasClientPacket) {
var ticks = DateTime.Now.Ticks;
clientPacket.Receive(clientPeer);
var packet = clientPacket.Clone();
if (packet.Length == packet.Position) {
emptyPacket = true;
}
if (packet.type == Packet.PacketType.RAKNET) {
switch ((Packet.RakNet)packet.packetID) {
case Packet.RakNet.NEW_INCOMING_CONNECTION:
Console.Write("Starting Proxy: ");
serverPeer = RakNetPeer.CreateConnection(serverIP, serverPort, 32, 100, 1000);
while (!serverPeer.Receive()) Thread.Sleep(10);
serverPacket.Receive(serverPeer);
serverPacket.Send(clientPeer, clientGUID);
serverPacket.Clear();
Console.WriteLine("Started");
break;
case Packet.RakNet.CONNECTION_LOST:
isAlive = false;
Console.WriteLine("Client Disconnected");
break;
}
if (!isAlive) break;
} else {
bool shouldDrop = false;
if (clientPacket.type == Packet.PacketType.RUST && commandCallback != null)
if (clientPacket.rustID == Packet.Rust.ConsoleCommand) {
string command = clientPacket.String();
if (command.StartsWith(CommandPrefix, StringComparison.OrdinalIgnoreCase)) {
commandCallback(command.Substring(CommandPrefix.Length));
shouldDrop = true;
}
}
if (!shouldDrop) {
if (ClientPackets && !emptyPacket && IsFiltered(packet)) {
if (packetHandlerCallback != null) {
packetHandlerCallback(packet);
} else
lock (packetQueue) {
packetQueue.Enqueue(packet);
}
}
clientPacket.Send(serverPeer, serverGUID);
clientPacket.Clear();
packet.delay = (DateTime.Now.Ticks - ticks);
if (RememberFilteredOnly && !IsFiltered(packet) && !ClientPackets) continue;
if (RememberPackets)
lock (remeberedPackets) {
remeberedPackets.Add(packet);
}
}
}
}
if (hasServerPacket) {
var ticks = DateTime.Now.Ticks;
serverPacket.Receive(serverPeer);
var packet = serverPacket.Clone();
emptyPacket = false;
if (packet.Position == packet.Length) {
emptyPacket = true;
}
if (IsFiltered(packet) && !emptyPacket) {
if (packetHandlerCallback != null) {
packetHandlerCallback(packet);
} else
lock (packetQueue) {
packetQueue.Enqueue(packet);
}
}
serverPacket.Send(clientPeer, clientGUID);
serverPacket.Clear();
packet.delay = (DateTime.Now.Ticks - ticks);
if (RememberFilteredOnly && !IsFiltered(packet)) continue;
if (RememberPackets)
lock (remeberedPackets) {
remeberedPackets.Add(packet);
}
}
}
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2014 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 NUnit.Framework.Constraints;
using NUnit.Framework.Internal;
namespace NUnit.Framework
{
public partial class Assert
{
#region ThrowsAsync
/// <summary>
/// Verifies that an async delegate throws a particular exception when called.
/// </summary>
/// <param name="expression">A constraint to be satisfied by the exception</param>
/// <param name="code">A TestSnippet delegate</param>
/// <param name="message">The message that will be displayed on failure</param>
/// <param name="args">Arguments to be used in formatting the message</param>
public static Exception ThrowsAsync(IResolveConstraint expression, AsyncTestDelegate code, string message, params object[] args)
{
Exception caughtException = null;
try
{
AsyncToSyncAdapter.Await(code.Invoke);
}
catch (Exception e)
{
caughtException = e;
}
Assert.That(caughtException, expression, message, args);
return caughtException;
}
/// <summary>
/// Verifies that an async delegate throws a particular exception when called.
/// </summary>
/// <param name="expression">A constraint to be satisfied by the exception</param>
/// <param name="code">A TestSnippet delegate</param>
public static Exception ThrowsAsync(IResolveConstraint expression, AsyncTestDelegate code)
{
return ThrowsAsync(expression, code, string.Empty, null);
}
/// <summary>
/// Verifies that an async delegate throws a particular exception when called.
/// </summary>
/// <param name="expectedExceptionType">The exception Type expected</param>
/// <param name="code">A TestDelegate</param>
/// <param name="message">The message that will be displayed on failure</param>
/// <param name="args">Arguments to be used in formatting the message</param>
public static Exception ThrowsAsync(Type expectedExceptionType, AsyncTestDelegate code, string message, params object[] args)
{
return ThrowsAsync(new ExceptionTypeConstraint(expectedExceptionType), code, message, args);
}
/// <summary>
/// Verifies that an async delegate throws a particular exception when called.
/// </summary>
/// <param name="expectedExceptionType">The exception Type expected</param>
/// <param name="code">A TestDelegate</param>
public static Exception ThrowsAsync(Type expectedExceptionType, AsyncTestDelegate code)
{
return ThrowsAsync(new ExceptionTypeConstraint(expectedExceptionType), code, string.Empty, null);
}
#endregion
#region ThrowsAsync<TActual>
/// <summary>
/// Verifies that an async delegate throws a particular exception when called.
/// </summary>
/// <typeparam name="TActual">Type of the expected exception</typeparam>
/// <param name="code">A TestDelegate</param>
/// <param name="message">The message that will be displayed on failure</param>
/// <param name="args">Arguments to be used in formatting the message</param>
public static TActual ThrowsAsync<TActual>(AsyncTestDelegate code, string message, params object[] args) where TActual : Exception
{
return (TActual)ThrowsAsync(typeof (TActual), code, message, args);
}
/// <summary>
/// Verifies that an async delegate throws a particular exception when called.
/// </summary>
/// <typeparam name="TActual">Type of the expected exception</typeparam>
/// <param name="code">A TestDelegate</param>
public static TActual ThrowsAsync<TActual>(AsyncTestDelegate code) where TActual : Exception
{
return ThrowsAsync<TActual>(code, string.Empty, null);
}
#endregion
#region CatchAsync
/// <summary>
/// Verifies that an async delegate throws an exception when called
/// and returns it.
/// </summary>
/// <param name="code">A TestDelegate</param>
/// <param name="message">The message that will be displayed on failure</param>
/// <param name="args">Arguments to be used in formatting the message</param>
public static Exception CatchAsync(AsyncTestDelegate code, string message, params object[] args)
{
return ThrowsAsync(new InstanceOfTypeConstraint(typeof(Exception)), code, message, args);
}
/// <summary>
/// Verifies that an async delegate throws an exception when called
/// and returns it.
/// </summary>
/// <param name="code">A TestDelegate</param>
public static Exception CatchAsync(AsyncTestDelegate code)
{
return ThrowsAsync(new InstanceOfTypeConstraint(typeof(Exception)), code);
}
/// <summary>
/// Verifies that an async delegate throws an exception of a certain Type
/// or one derived from it when called and returns it.
/// </summary>
/// <param name="expectedExceptionType">The expected Exception Type</param>
/// <param name="code">A TestDelegate</param>
/// <param name="message">The message that will be displayed on failure</param>
/// <param name="args">Arguments to be used in formatting the message</param>
public static Exception CatchAsync(Type expectedExceptionType, AsyncTestDelegate code, string message, params object[] args)
{
return ThrowsAsync(new InstanceOfTypeConstraint(expectedExceptionType), code, message, args);
}
/// <summary>
/// Verifies that an async delegate throws an exception of a certain Type
/// or one derived from it when called and returns it.
/// </summary>
/// <param name="expectedExceptionType">The expected Exception Type</param>
/// <param name="code">A TestDelegate</param>
public static Exception CatchAsync(Type expectedExceptionType, AsyncTestDelegate code)
{
return ThrowsAsync(new InstanceOfTypeConstraint(expectedExceptionType), code);
}
#endregion
#region CatchAsync<TActual>
/// <summary>
/// Verifies that an async delegate throws an exception of a certain Type
/// or one derived from it when called and returns it.
/// </summary>
/// <param name="code">A TestDelegate</param>
/// <param name="message">The message that will be displayed on failure</param>
/// <param name="args">Arguments to be used in formatting the message</param>
public static TActual CatchAsync<TActual>(AsyncTestDelegate code, string message, params object[] args) where TActual : Exception
{
return (TActual)ThrowsAsync(new InstanceOfTypeConstraint(typeof (TActual)), code, message, args);
}
/// <summary>
/// Verifies that an async delegate throws an exception of a certain Type
/// or one derived from it when called and returns it.
/// </summary>
/// <param name="code">A TestDelegate</param>
public static TActual CatchAsync<TActual>(AsyncTestDelegate code) where TActual : Exception
{
return (TActual)ThrowsAsync(new InstanceOfTypeConstraint(typeof (TActual)), code);
}
#endregion
#region DoesNotThrowAsync
/// <summary>
/// Verifies that an async delegate does not throw an exception
/// </summary>
/// <param name="code">A TestDelegate</param>
/// <param name="message">The message that will be displayed on failure</param>
/// <param name="args">Arguments to be used in formatting the message</param>
public static void DoesNotThrowAsync(AsyncTestDelegate code, string message, params object[] args)
{
Assert.That(code, new ThrowsNothingConstraint(), message, args);
}
/// <summary>
/// Verifies that an async delegate does not throw an exception.
/// </summary>
/// <param name="code">A TestDelegate</param>
public static void DoesNotThrowAsync(AsyncTestDelegate code)
{
DoesNotThrowAsync(code, string.Empty, null);
}
#endregion
}
}
#endif
| |
/* Copyright (C) 2008-2015 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov
*
* 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 Microsoft.Win32.SafeHandles;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
namespace Alphaleonis.Win32.Filesystem
{
/// <summary>Static class providing utility methods for working with Microsoft Windows devices and volumes.</summary>
public static class Volume
{
#region DosDevice
#region DefineDosDevice
/// <summary>Defines, redefines, or deletes MS-DOS device names.</summary>
/// <param name="deviceName">An MS-DOS device name string specifying the device the function is defining, redefining, or deleting.</param>
/// <param name="targetPath">An MS-DOS path that will implement this device.</param>
[SecurityCritical]
public static void DefineDosDevice(string deviceName, string targetPath)
{
DefineDosDeviceCore(true, deviceName, targetPath, DosDeviceAttributes.None, false);
}
/// <summary>Defines, redefines, or deletes MS-DOS device names.</summary>
/// <param name="deviceName">
/// An MS-DOS device name string specifying the device the function is defining, redefining, or deleting.
/// </param>
/// <param name="targetPath">
/// >An MS-DOS path that will implement this device. If <paramref name="deviceAttributes"/> parameter has the
/// <see cref="DosDeviceAttributes.RawTargetPath"/> flag specified, <paramref name="targetPath"/> is used as is.
/// </param>
/// <param name="deviceAttributes">
/// The controllable aspects of the DefineDosDevice function, <see cref="DosDeviceAttributes"/> flags which will be combined with the
/// default.
/// </param>
[SecurityCritical]
public static void DefineDosDevice(string deviceName, string targetPath, DosDeviceAttributes deviceAttributes)
{
DefineDosDeviceCore(true, deviceName, targetPath, deviceAttributes, false);
}
#endregion // DefineDosDevice
#region DeleteDosDevice
/// <summary>Deletes an MS-DOS device name.</summary>
/// <param name="deviceName">An MS-DOS device name specifying the device to delete.</param>
[SecurityCritical]
public static void DeleteDosDevice(string deviceName)
{
DefineDosDeviceCore(false, deviceName, null, DosDeviceAttributes.RemoveDefinition, false);
}
/// <summary>Deletes an MS-DOS device name.</summary>
/// <param name="deviceName">An MS-DOS device name string specifying the device to delete.</param>
/// <param name="targetPath">
/// A pointer to a path string that will implement this device. The string is an MS-DOS path string unless the
/// <see cref="DosDeviceAttributes.RawTargetPath"/> flag is specified, in which case this string is a path string.
/// </param>
[SecurityCritical]
public static void DeleteDosDevice(string deviceName, string targetPath)
{
DefineDosDeviceCore(false, deviceName, targetPath, DosDeviceAttributes.RemoveDefinition, false);
}
/// <summary>Deletes an MS-DOS device name.</summary>
/// <param name="deviceName">An MS-DOS device name string specifying the device to delete.</param>
/// <param name="targetPath">
/// A pointer to a path string that will implement this device. The string is an MS-DOS path string unless the
/// <see cref="DosDeviceAttributes.RawTargetPath"/> flag is specified, in which case this string is a path string.
/// </param>
/// <param name="exactMatch">
/// Only delete MS-DOS device on an exact name match. If <paramref name="exactMatch"/> is <see langword="true"/>,
/// <paramref name="targetPath"/> must be the same path used to create the mapping.
/// </param>
[SecurityCritical]
public static void DeleteDosDevice(string deviceName, string targetPath, bool exactMatch)
{
DefineDosDeviceCore(false, deviceName, targetPath, DosDeviceAttributes.RemoveDefinition, exactMatch);
}
/// <summary>Deletes an MS-DOS device name.</summary>
/// <param name="deviceName">An MS-DOS device name string specifying the device to delete.</param>
/// <param name="targetPath">
/// A pointer to a path string that will implement this device. The string is an MS-DOS path string unless the
/// <see cref="DosDeviceAttributes.RawTargetPath"/> flag is specified, in which case this string is a path string.
/// </param>
/// <param name="deviceAttributes">
/// The controllable aspects of the DefineDosDevice function <see cref="DosDeviceAttributes"/> flags which will be combined with the
/// default.
/// </param>
/// <param name="exactMatch">
/// Only delete MS-DOS device on an exact name match. If <paramref name="exactMatch"/> is <see langword="true"/>,
/// <paramref name="targetPath"/> must be the same path used to create the mapping.
/// </param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
[SecurityCritical]
public static void DeleteDosDevice(string deviceName, string targetPath, DosDeviceAttributes deviceAttributes, bool exactMatch)
{
DefineDosDeviceCore(false, deviceName, targetPath, deviceAttributes, exactMatch);
}
#endregion // DeleteDosDevice
#region QueryAllDosDevices
/// <summary>Retrieves a list of all existing MS-DOS device names.</summary>
/// <returns>An <see cref="IEnumerable{String}"/> with one or more existing MS-DOS device names.</returns>
[SecurityCritical]
public static IEnumerable<string> QueryAllDosDevices()
{
return QueryDosDevice(null, null);
}
/// <summary>Retrieves a list of all existing MS-DOS device names.</summary>
/// <param name="deviceName">
/// (Optional, default: <see langword="null"/>) An MS-DOS device name string specifying the target of the query. This parameter can be
/// "sort". In that case a sorted list of all existing MS-DOS device names is returned. This parameter can be <see langword="null"/>.
/// In that case, the <see cref="QueryDosDevice"/> function will store a list of all existing MS-DOS device names into the buffer.
/// </param>
/// <returns>An <see cref="IEnumerable{String}"/> with or more existing MS-DOS device names.</returns>
[SecurityCritical]
public static IEnumerable<string> QueryAllDosDevices(string deviceName)
{
return QueryDosDevice(null, deviceName);
}
#endregion // QueryAllDosDevices
#region QueryDosDevice
/// <summary>
/// Retrieves information about MS-DOS device names. The function can obtain the current mapping for a particular MS-DOS device name.
/// The function can also obtain a list of all existing MS-DOS device names.
/// </summary>
/// <param name="deviceName">
/// An MS-DOS device name string, or part of, specifying the target of the query. This parameter can be <see langword="null"/>. In that
/// case, the QueryDosDevice function will store a list of all existing MS-DOS device names into the buffer.
/// </param>
/// <param name="options">
/// (Optional, default: <see langword="false"/>) If options[0] = <see langword="true"/> a sorted list will be returned.
/// </param>
/// <returns>An <see cref="IEnumerable{String}"/> with one or more existing MS-DOS device names.</returns>
[SecurityCritical]
public static IEnumerable<string> QueryDosDevice(string deviceName, params string[] options)
{
// deviceName is allowed to be null.
// The deviceName cannot have a trailing backslash.
deviceName = Path.RemoveTrailingDirectorySeparator(deviceName, false);
bool searchFilter = (deviceName != null);
// Only process options if a device is supplied.
if (searchFilter)
{
// Check that at least one "options[]" has something to say. If so, rebuild them.
options = options != null && options.Any() ? new[] { deviceName, options[0] } : new[] { deviceName, string.Empty };
deviceName = null;
}
// Choose sorted output.
bool doSort = options != null &&
options.Any(s => s != null && s.Equals("sort", StringComparison.OrdinalIgnoreCase));
// Start with a larger buffer when using a searchFilter.
uint bufferSize = (uint) (searchFilter || doSort || (options == null) ? 8*NativeMethods.DefaultFileBufferSize : 256);
uint bufferResult = 0;
// ChangeErrorMode is for the Win32 SetThreadErrorMode() method, used to suppress possible pop-ups.
using (new NativeMethods.ChangeErrorMode(NativeMethods.ErrorMode.FailCriticalErrors))
while (bufferResult == 0)
{
var cBuffer = new char[bufferSize];
// QueryDosDevice()
// In the ANSI version of this function, the name is limited to MAX_PATH characters.
// To extend this limit to 32,767 wide characters, call the Unicode version of the function and prepend "\\?\" to the path.
// 2014-01-29: MSDN does not confirm LongPath usage but a Unicode version of this function exists.
bufferResult = NativeMethods.QueryDosDevice(deviceName, cBuffer, bufferSize);
int lastError = Marshal.GetLastWin32Error();
if (bufferResult == 0)
switch ((uint) lastError)
{
case Win32Errors.ERROR_MORE_DATA:
case Win32Errors.ERROR_INSUFFICIENT_BUFFER:
bufferSize *= 2;
continue;
default:
NativeError.ThrowException(lastError, deviceName);
break;
}
var dosDev = new List<string>();
var buffer = new StringBuilder();
for (int i = 0; i < bufferResult; i++)
{
if (cBuffer[i] != Path.StringTerminatorChar)
buffer.Append(cBuffer[i]);
else if (buffer.Length > 0)
{
dosDev.Add(buffer.ToString());
buffer.Length = 0;
}
}
// Choose the yield back query; filtered or list.
IEnumerable<string> selectQuery = searchFilter
? dosDev.Where(dev => options != null && dev.StartsWith(options[0], StringComparison.OrdinalIgnoreCase))
: dosDev;
foreach (string dev in (doSort) ? selectQuery.OrderBy(n => n) : selectQuery)
yield return dev;
}
}
#endregion // QueryDosDevice
#endregion // DosDevice
#region Drive
#region GetDriveFormat
/// <summary>Gets the name of the file system, such as NTFS or FAT32.</summary>
/// <remarks>Use DriveFormat to determine what formatting a drive uses.</remarks>
/// <param name="drivePath">
/// A path to a drive. For example: "C:\", "\\server\share", or "\\?\Volume{c0580d5e-2ad6-11dc-9924-806e6f6e6963}\".
/// </param>
/// <returns>The name of the file system on the specified drive or <see langword="null"/> on failure or if not available.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
[SecurityCritical]
public static string GetDriveFormat(string drivePath)
{
string fsName = new VolumeInfo(drivePath, true, true).FileSystemName;
return Utils.IsNullOrWhiteSpace(fsName) ? null : fsName;
}
#endregion // GetDriveFormat
#region GetDriveNameForNtDeviceName
/// <summary>Gets the drive letter from an MS-DOS device name. For example: "\Device\HarddiskVolume2" returns "C:\".</summary>
/// <param name="deviceName">An MS-DOS device name.</param>
/// <returns>The drive letter from an MS-DOS device name.</returns>
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Nt")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Nt")]
public static string GetDriveNameForNtDeviceName(string deviceName)
{
return (from drive in Directory.EnumerateLogicalDrivesCore(false, false)
where drive.DosDeviceName.Equals(deviceName, StringComparison.OrdinalIgnoreCase)
select drive.Name).FirstOrDefault();
}
#endregion // GetDriveNameForNtDeviceName
#region GetCurrentDriveType
/// <summary>
/// Determines, based on the root of the current directory, whether a disk drive is a removable, fixed, CD-ROM, RAM disk, or network
/// drive.
/// </summary>
/// <returns>A <see cref="DriveType"/> object.</returns>
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
[SecurityCritical]
public static DriveType GetCurrentDriveType()
{
return GetDriveType(null);
}
#endregion // GetCurrentDriveType
#region GetDriveType
/// <summary>Determines whether a disk drive is a removable, fixed, CD-ROM, RAM disk, or network drive.</summary>
/// <param name="drivePath">A path to a drive. For example: "C:\", "\\server\share", or "\\?\Volume{c0580d5e-2ad6-11dc-9924-806e6f6e6963}\"</param>
/// <returns>A <see cref="System.IO.DriveType"/> object.</returns>
[SecurityCritical]
public static DriveType GetDriveType(string drivePath)
{
// drivePath is allowed to be == null.
drivePath = Path.AddTrailingDirectorySeparator(drivePath, false);
// ChangeErrorMode is for the Win32 SetThreadErrorMode() method, used to suppress possible pop-ups.
using (new NativeMethods.ChangeErrorMode(NativeMethods.ErrorMode.FailCriticalErrors))
return NativeMethods.GetDriveType(drivePath);
}
#endregion // GetDriveType
#region GetDiskFreeSpace
/// <summary>
/// Retrieves information about the amount of space that is available on a disk volume, which is the total amount of space, the total
/// amount of free space, and the total amount of free space available to the user that is associated with the calling thread.
/// </summary>
/// <remarks>The calling application must have FILE_LIST_DIRECTORY access rights for this directory.</remarks>
/// <param name="drivePath">
/// A path to a drive. For example: "C:\", "\\server\share", or "\\?\Volume{c0580d5e-2ad6-11dc-9924-806e6f6e6963}\".
/// </param>
/// <returns>A <see ref="Alphaleonis.Win32.Filesystem.DiskSpaceInfo"/> class instance.</returns>
[SecurityCritical]
public static DiskSpaceInfo GetDiskFreeSpace(string drivePath)
{
return new DiskSpaceInfo(drivePath, null, true, true);
}
/// <summary>
/// Retrieves information about the amount of space that is available on a disk volume, which is the total amount of space, the total
/// amount of free space, and the total amount of free space available to the user that is associated with the calling thread.
/// </summary>
/// <remarks>The calling application must have FILE_LIST_DIRECTORY access rights for this directory.</remarks>
/// <param name="drivePath">
/// A path to a drive. For example: "C:\", "\\server\share", or "\\?\Volume{c0580d5e-2ad6-11dc-9924-806e6f6e6963}\".
/// </param>
/// <param name="spaceInfoType">
/// <see langword="null"/> gets both size- and disk cluster information. <see langword="true"/> Get only disk cluster information,
/// <see langword="false"/> Get only size information.
/// </param>
/// <returns>A <see ref="Alphaleonis.Win32.Filesystem.DiskSpaceInfo"/> class instance.</returns>
[SecurityCritical]
public static DiskSpaceInfo GetDiskFreeSpace(string drivePath, bool? spaceInfoType)
{
return new DiskSpaceInfo(drivePath, spaceInfoType, true, true);
}
#endregion // GetDiskFreeSpace
#region IsReady
/// <summary>Gets a value indicating whether a drive is ready.</summary>
/// <param name="drivePath">
/// A path to a drive. For example: "C:\", "\\server\share", or "\\?\Volume{c0580d5e-2ad6-11dc-9924-806e6f6e6963}\".
/// </param>
/// <returns><see langword="true"/> if <paramref name="drivePath"/> is ready; otherwise, <see langword="false"/>.</returns>
[SecurityCritical]
public static bool IsReady(string drivePath)
{
return File.ExistsCore(true, null, drivePath, PathFormat.FullPath);
}
#endregion // IsReady
#endregion // Drive
#region Volume
#region DeleteCurrentVolumeLabel
/// <summary>Deletes the label of the file system volume that is the root of the current directory.
/// </summary>
[SecurityCritical]
public static void DeleteCurrentVolumeLabel()
{
SetVolumeLabel(null, null);
}
#endregion // DeleteCurrentVolumeLabel
#region DeleteVolumeLabel
/// <summary>Deletes the label of a file system volume.</summary>
/// <exception cref="ArgumentNullException"/>
/// <param name="rootPathName">The root directory of a file system volume. This is the volume the function will remove the label.</param>
[SecurityCritical]
public static void DeleteVolumeLabel(string rootPathName)
{
if (Utils.IsNullOrWhiteSpace(rootPathName))
throw new ArgumentNullException("rootPathName");
SetVolumeLabel(rootPathName, null);
}
#endregion // DeleteVolumeLabel
#region DeleteVolumeMountPoint
/// <summary>Deletes a Drive letter or mounted folder.</summary>
/// <remarks>Deleting a mounted folder does not cause the underlying directory to be deleted.</remarks>
/// <remarks>
/// If the <paramref name="volumeMountPoint"/> parameter is a directory that is not a mounted folder, the function does nothing. The
/// directory is not deleted.
/// </remarks>
/// <remarks>
/// It's not an error to attempt to unmount a volume from a volume mount point when there is no volume actually mounted at that volume
/// mount point.
/// </remarks>
/// <param name="volumeMountPoint">The Drive letter or mounted folder to be deleted. For example, X:\ or Y:\MountX\.</param>
[SecurityCritical]
public static void DeleteVolumeMountPoint(string volumeMountPoint)
{
DeleteVolumeMountPointCore(volumeMountPoint, false);
}
#endregion // DeleteVolumeMountPoint
#region EnumerateVolumeMountPoints
/// <summary>
/// Returns an enumerable collection of <see cref="String"/> of all mounted folders (volume mount points) on the specified volume.
/// </summary>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="ArgumentException"/>
/// <param name="volumeGuid">A <see cref="string"/> containing the volume <see cref="Guid"/>.</param>
/// <returns>An enumerable collection of <see cref="String"/> of all volume mount points on the specified volume.</returns>
[SecurityCritical]
public static IEnumerable<string> EnumerateVolumeMountPoints(string volumeGuid)
{
if (Utils.IsNullOrWhiteSpace(volumeGuid))
throw new ArgumentNullException("volumeGuid");
if (!volumeGuid.StartsWith(Path.VolumePrefix + "{", StringComparison.OrdinalIgnoreCase))
throw new ArgumentException(Resources.Not_A_Valid_Guid, volumeGuid);
// A trailing backslash is required.
volumeGuid = Path.AddTrailingDirectorySeparator(volumeGuid, false);
var buffer = new StringBuilder(NativeMethods.MaxPathUnicode);
// ChangeErrorMode is for the Win32 SetThreadErrorMode() method, used to suppress possible pop-ups.
using (new NativeMethods.ChangeErrorMode(NativeMethods.ErrorMode.FailCriticalErrors))
using (SafeFindVolumeMountPointHandle handle = NativeMethods.FindFirstVolumeMountPoint(volumeGuid, buffer, (uint)buffer.Capacity))
{
int lastError = Marshal.GetLastWin32Error();
if (handle != null && handle.IsInvalid)
{
handle.Close();
switch ((uint) lastError)
{
case Win32Errors.ERROR_NO_MORE_FILES:
case Win32Errors.ERROR_PATH_NOT_FOUND: // Observed with USB stick, FAT32 formatted.
yield break;
default:
NativeError.ThrowException(lastError, volumeGuid);
break;
}
}
yield return buffer.ToString();
while (NativeMethods.FindNextVolumeMountPoint(handle, buffer, (uint)buffer.Capacity))
{
lastError = Marshal.GetLastWin32Error();
if (handle != null && handle.IsInvalid)
{
handle.Close();
switch ((uint) lastError)
{
case Win32Errors.ERROR_NO_MORE_FILES:
case Win32Errors.ERROR_PATH_NOT_FOUND: // Observed with USB stick, FAT32 formatted.
case Win32Errors.ERROR_MORE_DATA:
yield break;
default:
NativeError.ThrowException(lastError, volumeGuid);
break;
}
}
yield return buffer.ToString();
}
}
}
#endregion // EnumerateVolumeMountPoints
#region EnumerateVolumePathNames
/// <summary>
/// Returns an enumerable collection of <see cref="String"/> drive letters and mounted folder paths for the specified volume.
/// </summary>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="ArgumentException"/>
/// <param name="volumeGuid">A volume <see cref="Guid"/> path: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\.</param>
/// <returns>An enumerable collection of <see cref="String"/> containing the path names for the specified volume.</returns>
[SecurityCritical]
public static IEnumerable<string> EnumerateVolumePathNames(string volumeGuid)
{
if (Utils.IsNullOrWhiteSpace(volumeGuid))
throw new ArgumentNullException("volumeGuid");
if (!volumeGuid.StartsWith(Path.VolumePrefix + "{", StringComparison.OrdinalIgnoreCase))
throw new ArgumentException(Resources.Not_A_Valid_Guid, volumeGuid);
string volName = Path.AddTrailingDirectorySeparator(volumeGuid, false);
uint requiredLength = 10;
char[] cBuffer = new char[requiredLength];
// ChangeErrorMode is for the Win32 SetThreadErrorMode() method, used to suppress possible pop-ups.
using (new NativeMethods.ChangeErrorMode(NativeMethods.ErrorMode.FailCriticalErrors))
while (!NativeMethods.GetVolumePathNamesForVolumeName(volName, cBuffer, (uint)cBuffer.Length, out requiredLength))
{
int lastError = Marshal.GetLastWin32Error();
switch ((uint)lastError)
{
case Win32Errors.ERROR_MORE_DATA:
case Win32Errors.ERROR_INSUFFICIENT_BUFFER:
cBuffer = new char[requiredLength];
break;
default:
NativeError.ThrowException(lastError, volumeGuid);
break;
}
}
var buffer = new StringBuilder(cBuffer.Length);
foreach (char c in cBuffer)
{
if (c != Path.StringTerminatorChar)
buffer.Append(c);
else
{
if (buffer.Length > 0)
{
yield return buffer.ToString();
buffer.Length = 0;
}
}
}
}
#endregion // EnumerateVolumePathNames
#region EnumerateVolumes
/// <summary>Returns an enumerable collection of <see cref="String"/> volumes on the computer.</summary>
/// <returns>An enumerable collection of <see cref="String"/> volume names on the computer.</returns>
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
[SecurityCritical]
public static IEnumerable<string> EnumerateVolumes()
{
var buffer = new StringBuilder(NativeMethods.MaxPathUnicode);
// ChangeErrorMode is for the Win32 SetThreadErrorMode() method, used to suppress possible pop-ups.
using (new NativeMethods.ChangeErrorMode(NativeMethods.ErrorMode.FailCriticalErrors))
using (SafeFindVolumeHandle handle = NativeMethods.FindFirstVolume(buffer, (uint)buffer.Capacity))
{
while (handle != null && !handle.IsInvalid)
{
if (NativeMethods.FindNextVolume(handle, buffer, (uint)buffer.Capacity))
yield return buffer.ToString();
else
{
int lastError = Marshal.GetLastWin32Error();
handle.Close();
if (lastError == Win32Errors.ERROR_NO_MORE_FILES)
yield break;
NativeError.ThrowException(lastError);
}
}
}
}
#endregion // EnumerateVolumes
#region GetUniqueVolumeNameForPath
/// <summary>
/// Get the unique volume name for the given path.
/// </summary>
/// <exception cref="ArgumentNullException"/>
/// <param name="volumePathName">
/// A path string. Both absolute and relative file and directory names, for example "..", is acceptable in this path. If you specify a
/// relative file or directory name without a volume qualifier, GetUniqueVolumeNameForPath returns the Drive letter of the current
/// volume.
/// </param>
/// <returns>
/// <para>Returns the unique volume name in the form: "\\?\Volume{GUID}\",</para>
/// <para>or <see langword="null"/> on error or if unavailable.</para>
/// </returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
[SecurityCritical]
public static string GetUniqueVolumeNameForPath(string volumePathName)
{
if (Utils.IsNullOrWhiteSpace(volumePathName))
throw new ArgumentNullException("volumePathName");
try
{
return GetVolumeGuid(GetVolumePathName(volumePathName));
}
catch
{
return null;
}
}
#endregion // GetUniqueVolumeNameForPath
#region GetVolumeDeviceName
/// <summary>Retrieves the Win32 Device name from the Volume name.</summary>
/// <exception cref="ArgumentNullException"/>
/// <param name="volumeName">Name of the Volume.</param>
/// <returns>
/// The Win32 Device name from the Volume name (for example: "\Device\HarddiskVolume2"), or <see langword="null"/> on error or if
/// unavailable.
/// </returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
[SecurityCritical]
public static string GetVolumeDeviceName(string volumeName)
{
if (Utils.IsNullOrWhiteSpace(volumeName))
throw new ArgumentNullException("volumeName");
volumeName = Path.RemoveTrailingDirectorySeparator(volumeName, false);
#region GlobalRoot
if (volumeName.StartsWith(Path.GlobalRootPrefix, StringComparison.OrdinalIgnoreCase))
return volumeName.Substring(Path.GlobalRootPrefix.Length);
#endregion // GlobalRoot
bool doQueryDos;
#region Volume
if (volumeName.StartsWith(Path.VolumePrefix, StringComparison.OrdinalIgnoreCase))
{
// Isolate the DOS Device from the Volume name, in the format: Volume{GUID}
volumeName = volumeName.Substring(Path.LongPathPrefix.Length);
doQueryDos = true;
}
#endregion // Volume
#region Logical Drive
// Check for Logical Drives: C:, D:, ...
else
{
// Don't use char.IsLetter() here as that can be misleading.
// The only valid drive letters are: a-z and A-Z.
var c = volumeName[0];
doQueryDos = (volumeName[1] == Path.VolumeSeparatorChar && ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')));
}
#endregion // Logical Drive
if (doQueryDos)
{
try
{
// Get the real Device underneath.
string dev = QueryDosDevice(volumeName).FirstOrDefault();
return !Utils.IsNullOrWhiteSpace(dev) ? dev : null;
}
catch
{
}
}
return null;
}
#endregion // GetVolumeDeviceName
#region GetVolumeDisplayName
/// <summary>Gets the shortest display name for the specified <paramref name="volumeName"/>.</summary>
/// <remarks>This method basically returns the shortest string returned by <see cref="EnumerateVolumePathNames"/></remarks>
/// <param name="volumeName">A volume <see cref="Guid"/> path: \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\.</param>
/// <returns>
/// The shortest display name for the specified volume found, or <see langword="null"/> if no display names were found.
/// </returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
[SecurityCritical]
public static string GetVolumeDisplayName(string volumeName)
{
string[] smallestMountPoint = { new string(Path.WildcardStarMatchAllChar, NativeMethods.MaxPathUnicode) };
try
{
foreach (string m in EnumerateVolumePathNames(volumeName).Where(m => !Utils.IsNullOrWhiteSpace(m) && m.Length < smallestMountPoint[0].Length))
smallestMountPoint[0] = m;
}
catch
{
}
string result = smallestMountPoint[0][0] == Path.WildcardStarMatchAllChar ? null : smallestMountPoint[0];
return Utils.IsNullOrWhiteSpace(result) ? null : result;
}
#endregion // GetVolumeDisplayName
#region GetVolumeGuid
/// <summary>
/// Retrieves a volume <see cref="Guid"/> path for the volume that is associated with the specified volume mount point (drive letter,
/// volume GUID path, or mounted folder).
/// </summary>
/// <exception cref="ArgumentNullException"/>
/// <param name="volumeMountPoint">
/// The path of a mounted folder (for example, "Y:\MountX\") or a drive letter (for example, "X:\").
/// </param>
/// <returns>The unique volume name of the form: "\\?\Volume{GUID}\".</returns>
[SuppressMessage("Microsoft.Interoperability", "CA1404:CallGetLastErrorImmediatelyAfterPInvoke", Justification = "Marshal.GetLastWin32Error() is manipulated.")]
[SecurityCritical]
public static string GetVolumeGuid(string volumeMountPoint)
{
if (Utils.IsNullOrWhiteSpace(volumeMountPoint))
throw new ArgumentNullException("volumeMountPoint");
// The string must end with a trailing backslash ('\').
volumeMountPoint = Path.GetFullPathCore(null, volumeMountPoint, GetFullPathOptions.AsLongPath | GetFullPathOptions.AddTrailingDirectorySeparator | GetFullPathOptions.FullCheck);
var volumeGuid = new StringBuilder(100);
var uniqueName = new StringBuilder(100);
try
{
// ChangeErrorMode is for the Win32 SetThreadErrorMode() method, used to suppress possible pop-ups.
using (new NativeMethods.ChangeErrorMode(NativeMethods.ErrorMode.FailCriticalErrors))
{
// GetVolumeNameForVolumeMountPoint()
// In the ANSI version of this function, the name is limited to 248 characters.
// To extend this limit to 32,767 wide characters, call the Unicode version of the function and prepend "\\?\" to the path.
// 2013-07-18: MSDN does not confirm LongPath usage but a Unicode version of this function exists.
return NativeMethods.GetVolumeNameForVolumeMountPoint(volumeMountPoint, volumeGuid, (uint) volumeGuid.Capacity)
? NativeMethods.GetVolumeNameForVolumeMountPoint(Path.AddTrailingDirectorySeparator(volumeGuid.ToString(), false), uniqueName, (uint) uniqueName.Capacity)
? uniqueName.ToString()
: null
: null;
}
}
finally
{
uint lastError = (uint) Marshal.GetLastWin32Error();
switch (lastError)
{
case Win32Errors.ERROR_INVALID_NAME:
NativeError.ThrowException(lastError, volumeMountPoint);
break;
case Win32Errors.ERROR_MORE_DATA:
// (1) When GetVolumeNameForVolumeMountPoint() succeeds, lastError is set to Win32Errors.ERROR_MORE_DATA.
break;
default:
// (2) When volumeMountPoint is a network drive mapping or UNC path, lastError is set to Win32Errors.ERROR_INVALID_PARAMETER.
// Throw IOException.
NativeError.ThrowException(lastError, volumeMountPoint);
break;
}
}
}
#endregion // GetVolumeGuid
#region GetVolumeGuidForNtDeviceName
/// <summary>
/// Tranlates DosDevicePath to a Volume GUID. For example: "\Device\HarddiskVolumeX\path\filename.ext" can translate to: "\path\
/// filename.ext" or: "\\?\Volume{GUID}\path\filename.ext".
/// </summary>
/// <param name="dosDevice">A DosDevicePath, for example: \Device\HarddiskVolumeX\path\filename.ext.</param>
/// <returns>A translated dos path.</returns>
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Nt")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Nt")]
public static string GetVolumeGuidForNtDeviceName(string dosDevice)
{
return (from drive in Directory.EnumerateLogicalDrivesCore(false, false)
where drive.DosDeviceName.Equals(dosDevice, StringComparison.OrdinalIgnoreCase)
select drive.VolumeInfo.Guid).FirstOrDefault();
}
#endregion // GetVolumeGuidForNtDeviceName
#region GetVolumeInfo
/// <summary>Retrieves information about the file system and volume associated with the specified root file or directorystream.</summary>
/// <param name="volumePath">A path that contains the root directory.</param>
/// <returns>A <see cref="VolumeInfo"/> instance describing the volume associatied with the specified root directory.</returns>
[SecurityCritical]
public static VolumeInfo GetVolumeInfo(string volumePath)
{
return new VolumeInfo(volumePath, true, false);
}
/// <summary>Retrieves information about the file system and volume associated with the specified root file or directorystream.</summary>
/// <param name="volumeHandle">An instance to a <see cref="SafeFileHandle"/> handle.</param>
/// <returns>A <see cref="VolumeInfo"/> instance describing the volume associatied with the specified root directory.</returns>
[SecurityCritical]
public static VolumeInfo GetVolumeInfo(SafeFileHandle volumeHandle)
{
return new VolumeInfo(volumeHandle, true, true);
}
#endregion // GetVolumeInfo
#region GetVolumeLabel
/// <summary>Retrieve the label of a file system volume.</summary>
/// <param name="volumePath">
/// A path to a volume. For example: "C:\", "\\server\share", or "\\?\Volume{c0580d5e-2ad6-11dc-9924-806e6f6e6963}\".
/// </param>
/// <returns>
/// The the label of the file system volume. This function can return <c>string.Empty</c> since a volume label is generally not
/// mandatory.
/// </returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
[SecurityCritical]
public static string GetVolumeLabel(string volumePath)
{
return new VolumeInfo(volumePath, true, true).Name;
}
#endregion // GetVolumeLabel
#region GetVolumePathName
/// <summary>Retrieves the volume mount point where the specified path is mounted.</summary>
/// <exception cref="ArgumentNullException"/>
/// <param name="path">The path to the volume, for example: "C:\Windows".</param>
/// <returns>
/// <para>Returns the nearest volume root path for a given directory.</para>
/// <para>The volume path name, for example: "C:\Windows" returns: "C:\".</para>
/// </returns>
[SecurityCritical]
public static string GetVolumePathName(string path)
{
if (Utils.IsNullOrWhiteSpace(path))
throw new ArgumentNullException("path");
// ChangeErrorMode is for the Win32 SetThreadErrorMode() method, used to suppress possible pop-ups.
using (new NativeMethods.ChangeErrorMode(NativeMethods.ErrorMode.FailCriticalErrors))
{
var volumeRootPath = new StringBuilder(NativeMethods.MaxPathUnicode / 32);
string pathLp = Path.GetFullPathCore(null, path, GetFullPathOptions.AsLongPath | GetFullPathOptions.FullCheck);
// GetVolumePathName()
// In the ANSI version of this function, the name is limited to 248 characters.
// To extend this limit to 32,767 wide characters, call the Unicode version of the function and prepend "\\?\" to the path.
// 2013-07-18: MSDN does not confirm LongPath usage but a Unicode version of this function exists.
bool getOk = NativeMethods.GetVolumePathName(pathLp, volumeRootPath, (uint) volumeRootPath.Capacity);
int lastError = Marshal.GetLastWin32Error();
if (getOk)
return Path.GetRegularPathCore(volumeRootPath.ToString(), GetFullPathOptions.None);
switch ((uint) lastError)
{
// Don't throw exception on these errors.
case Win32Errors.ERROR_NO_MORE_FILES:
case Win32Errors.ERROR_INVALID_PARAMETER:
case Win32Errors.ERROR_INVALID_NAME:
break;
default:
NativeError.ThrowException(lastError, path);
break;
}
// Return original path.
return path;
}
}
#endregion // GetVolumePathName
#region IsSameVolume
/// <summary>Determines whether the volume of two file system objects is the same.</summary>
/// <param name="path1">The first filesystem ojbect with full path information.</param>
/// <param name="path2">The second file system object with full path information.</param>
/// <returns><see langword="true"/> if both filesytem objects reside on the same volume, <see langword="false"/> otherwise.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
[SecurityCritical]
public static bool IsSameVolume(string path1, string path2)
{
try
{
var volInfo1 = new VolumeInfo(GetVolumePathName(path1), true, true);
var volInfo2 = new VolumeInfo(GetVolumePathName(path2), true, true);
return volInfo1.SerialNumber == volInfo2.SerialNumber;
}
catch { }
return false;
}
#endregion // IsSameVolume
#region IsVolume
/// <summary>Determines whether the specified volume name is a defined volume on the current computer.</summary>
/// <param name="volumeMountPoint">
/// A path to a volume. For example: "C:\", "\\server\share", or "\\?\Volume{c0580d5e-2ad6-11dc-9924-806e6f6e6963}\".
/// </param>
/// <returns><see langword="true"/> on success, <see langword="false"/> otherwise.</returns>
[SecurityCritical]
public static bool IsVolume(string volumeMountPoint)
{
return !Utils.IsNullOrWhiteSpace(GetVolumeGuid(volumeMountPoint));
}
#endregion // IsVolume
#region SetCurrentVolumeLabel
/// <summary>Sets the label of the file system volume that is the root of the current directory.</summary>
/// <exception cref="ArgumentNullException"/>
/// <param name="volumeName">A name for the volume.</param>
[SecurityCritical]
public static void SetCurrentVolumeLabel(string volumeName)
{
if (Utils.IsNullOrWhiteSpace(volumeName))
throw new ArgumentNullException("volumeName");
if (!NativeMethods.SetVolumeLabel(null, volumeName))
Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
}
#endregion // SetCurrentVolumeLabel
#region SetVolumeLabel
/// <summary>Sets the label of a file system volume.</summary>
/// <param name="volumePath">
/// <para>A path to a volume. For example: "C:\", "\\server\share", or "\\?\Volume{c0580d5e-2ad6-11dc-9924-806e6f6e6963}\"</para>
/// <para>If this parameter is <see langword="null"/>, the function uses the current drive.</para>
/// </param>
/// <param name="volumeName">
/// <para>A name for the volume.</para>
/// <para>If this parameter is <see langword="null"/>, the function deletes any existing label</para>
/// <para>from the specified volume and does not assign a new label.</para>
/// </param>
[SecurityCritical]
public static void SetVolumeLabel(string volumePath, string volumeName)
{
// rootPathName == null is allowed, means current drive.
// Setting volume label only applies to Logical Drives pointing to local resources.
//if (!Path.IsLocalPath(rootPathName))
//return false;
volumePath = Path.AddTrailingDirectorySeparator(volumePath, false);
// ChangeErrorMode is for the Win32 SetThreadErrorMode() method, used to suppress possible pop-ups.
// NTFS uses a limit of 32 characters for the volume label as of Windows Server 2003.
using (new NativeMethods.ChangeErrorMode(NativeMethods.ErrorMode.FailCriticalErrors))
if (!NativeMethods.SetVolumeLabel(volumePath, volumeName))
NativeError.ThrowException(volumePath, volumeName);
}
#endregion // SetVolumeLabel
#region SetVolumeMountPoint
/// <summary>Associates a volume with a Drive letter or a directory on another volume.</summary>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="ArgumentException"/>
/// <param name="volumeMountPoint">
/// The user-mode path to be associated with the volume. This may be a Drive letter (for example, "X:\")
/// or a directory on another volume (for example, "Y:\MountX\").
/// </param>
/// <param name="volumeGuid">A <see cref="string"/> containing the volume <see cref="Guid"/>.</param>
[SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "1", Justification = "Utils.IsNullOrWhiteSpace validates arguments.")]
[SecurityCritical]
public static void SetVolumeMountPoint(string volumeMountPoint, string volumeGuid)
{
if (Utils.IsNullOrWhiteSpace(volumeMountPoint))
throw new ArgumentNullException("volumeMountPoint");
if (Utils.IsNullOrWhiteSpace(volumeGuid))
throw new ArgumentNullException("volumeGuid");
if (!volumeGuid.StartsWith(Path.VolumePrefix + "{", StringComparison.OrdinalIgnoreCase))
throw new ArgumentException(Resources.Not_A_Valid_Guid, volumeGuid);
volumeMountPoint = Path.GetFullPathCore(null, volumeMountPoint, GetFullPathOptions.AsLongPath | GetFullPathOptions.AddTrailingDirectorySeparator | GetFullPathOptions.FullCheck);
// This string must be of the form "\\?\Volume{GUID}\"
volumeGuid = Path.AddTrailingDirectorySeparator(volumeGuid, false);
// ChangeErrorMode is for the Win32 SetThreadErrorMode() method, used to suppress possible pop-ups.
using (new NativeMethods.ChangeErrorMode(NativeMethods.ErrorMode.FailCriticalErrors))
// SetVolumeMountPoint()
// In the ANSI version of this function, the name is limited to MAX_PATH characters.
// To extend this limit to 32,767 wide characters, call the Unicode version of the function and prepend "\\?\" to the path.
// 2014-01-29: MSDN does not confirm LongPath usage but a Unicode version of this function exists.
if (!NativeMethods.SetVolumeMountPoint(volumeMountPoint, volumeGuid))
{
int lastError = Marshal.GetLastWin32Error();
// If the lpszVolumeMountPoint parameter contains a path to a mounted folder,
// GetLastError returns ERROR_DIR_NOT_EMPTY, even if the directory is empty.
if (lastError != Win32Errors.ERROR_DIR_NOT_EMPTY)
NativeError.ThrowException(lastError, volumeGuid);
}
}
#endregion // SetVolumeMountPoint
#endregion // Volume
#region Internal Methods
/// <summary>Defines, redefines, or deletes MS-DOS device names.</summary>
/// <exception cref="ArgumentNullException"/>
/// <param name="isDefine">
/// <see langword="true"/> defines a new MS-DOS device. <see langword="false"/> deletes a previously defined MS-DOS device.
/// </param>
/// <param name="deviceName">
/// An MS-DOS device name string specifying the device the function is defining, redefining, or deleting.
/// </param>
/// <param name="targetPath">
/// A pointer to a path string that will implement this device. The string is an MS-DOS path string unless the
/// <see cref="DosDeviceAttributes.RawTargetPath"/> flag is specified, in which case this string is a path string.
/// </param>
/// <param name="deviceAttributes">
/// The controllable aspects of the DefineDosDevice function, <see cref="DosDeviceAttributes"/> flags which will be combined with the
/// default.
/// </param>
/// <param name="exactMatch">
/// Only delete MS-DOS device on an exact name match. If <paramref name="exactMatch"/> is <see langword="true"/>,
/// <paramref name="targetPath"/> must be the same path used to create the mapping.
/// </param>
///
/// <returns><see langword="true"/> on success, <see langword="false"/> otherwise.</returns>
[SecurityCritical]
internal static void DefineDosDeviceCore(bool isDefine, string deviceName, string targetPath, DosDeviceAttributes deviceAttributes, bool exactMatch)
{
if (Utils.IsNullOrWhiteSpace(deviceName))
throw new ArgumentNullException("deviceName");
if (isDefine)
{
// targetPath is allowed to be null.
// In no case is a trailing backslash ("\") allowed.
deviceName = Path.GetRegularPathCore(deviceName, GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.CheckInvalidPathChars);
// ChangeErrorMode is for the Win32 SetThreadErrorMode() method, used to suppress possible pop-ups.
using (new NativeMethods.ChangeErrorMode(NativeMethods.ErrorMode.FailCriticalErrors))
if (!NativeMethods.DefineDosDevice(deviceAttributes, deviceName, targetPath))
NativeError.ThrowException(deviceName, targetPath);
}
else
{
// A pointer to a path string that will implement this device.
// The string is an MS-DOS path string unless the DDD_RAW_TARGET_PATH flag is specified, in which case this string is a path string.
if (exactMatch && !Utils.IsNullOrWhiteSpace(targetPath))
deviceAttributes = deviceAttributes | DosDeviceAttributes.ExactMatchOnRemove | DosDeviceAttributes.RawTargetPath;
// Remove the MS-DOS device name. First, get the name of the Windows NT device
// from the symbolic link and then delete the symbolic link from the namespace.
DefineDosDevice(deviceName, targetPath, deviceAttributes);
}
}
/// <summary>Deletes a Drive letter or mounted folder.</summary>
/// <remarks>
/// <para>It's not an error to attempt to unmount a volume from a volume mount point when there is no volume actually mounted at that volume mount point.</para>
/// <para>Deleting a mounted folder does not cause the underlying directory to be deleted.</para>
/// </remarks>
/// <exception cref="ArgumentNullException"/>
/// <param name="volumeMountPoint">The Drive letter or mounted folder to be deleted. For example, X:\ or Y:\MountX\.</param>
/// <param name="continueOnException">
/// <see langword="true"/> suppress any exception that might be thrown a result from a failure, such as unavailable resources.
/// </param>
/// <returns>If completed successfully returns <see cref="Win32Errors.ERROR_SUCCESS"/>, otherwise the last error number.</returns>
[SecurityCritical]
internal static int DeleteVolumeMountPointCore(string volumeMountPoint, bool continueOnException)
{
if (Utils.IsNullOrWhiteSpace(volumeMountPoint))
throw new ArgumentNullException("volumeMountPoint");
int lastError = (int) Win32Errors.ERROR_SUCCESS;
// ChangeErrorMode is for the Win32 SetThreadErrorMode() method, used to suppress possible pop-ups.
using (new NativeMethods.ChangeErrorMode(NativeMethods.ErrorMode.FailCriticalErrors))
{
// DeleteVolumeMountPoint()
// In the ANSI version of this function, the name is limited to MAX_PATH characters.
// To extend this limit to 32,767 wide characters, call the Unicode version of the function and prepend "\\?\" to the path.
// 2013-01-13: MSDN does not confirm LongPath usage but a Unicode version of this function exists.
if (!NativeMethods.DeleteVolumeMountPoint(Path.AddTrailingDirectorySeparator(volumeMountPoint, false)))
lastError = Marshal.GetLastWin32Error();
if (lastError != Win32Errors.ERROR_SUCCESS && !continueOnException)
{
if (lastError == Win32Errors.ERROR_FILE_NOT_FOUND)
lastError = (int) Win32Errors.ERROR_PATH_NOT_FOUND;
NativeError.ThrowException(lastError, volumeMountPoint);
}
}
return lastError;
}
#endregion // Internal Methods
}
}
| |
/*
* 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 log4net;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
namespace OpenSim.Region.CoreModules.Avatar.Lure
{
public class LureModule : ISharedRegionModule
{
private static readonly ILog m_log = LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
private readonly List<Scene> m_scenes = new List<Scene>();
private IMessageTransferModule m_TransferModule = null;
private bool m_Enabled = true;
public void Initialise(IConfigSource config)
{
if (config.Configs["Messaging"] != null)
{
if (config.Configs["Messaging"].GetString(
"LureModule", "LureModule") !=
"LureModule")
m_Enabled = false;
}
}
public void AddRegion(Scene scene)
{
if (!m_Enabled)
return;
lock (m_scenes)
{
m_scenes.Add(scene);
scene.EventManager.OnNewClient += OnNewClient;
scene.EventManager.OnIncomingInstantMessage +=
OnGridInstantMessage;
}
}
public void RegionLoaded(Scene scene)
{
if (m_TransferModule == null)
{
m_TransferModule =
scene.RequestModuleInterface<IMessageTransferModule>();
if (m_TransferModule == null)
{
m_log.Error("[INSTANT MESSAGE]: No message transfer module, "+
"lures will not work!");
m_Enabled = false;
m_scenes.Clear();
scene.EventManager.OnNewClient -= OnNewClient;
scene.EventManager.OnIncomingInstantMessage -=
OnGridInstantMessage;
}
}
}
public void RemoveRegion(Scene scene)
{
lock (m_scenes)
{
m_scenes.Remove(scene);
scene.EventManager.OnNewClient -= OnNewClient;
scene.EventManager.OnIncomingInstantMessage -=
OnGridInstantMessage;
}
}
void OnNewClient(IClientAPI client)
{
client.OnInstantMessage += OnInstantMessage;
client.OnStartLure += OnStartLure;
client.OnTeleportLureRequest += OnTeleportLureRequest;
}
public void PostInitialise()
{
}
public void Close()
{
}
public string Name
{
get { return "LureModule"; }
}
public Type ReplaceableInterface
{
get { return null; }
}
public void OnInstantMessage(IClientAPI client, GridInstantMessage im)
{
}
public void OnStartLure(byte lureType, string message, UUID targetid, IClientAPI client)
{
if (!(client.Scene is Scene))
return;
Scene scene = (Scene)(client.Scene);
ScenePresence presence = scene.GetScenePresence(client.AgentId);
UUID dest = Util.BuildFakeParcelID(
scene.RegionInfo.RegionHandle,
(uint)presence.AbsolutePosition.X,
(uint)presence.AbsolutePosition.Y,
(uint)presence.AbsolutePosition.Z);
m_log.DebugFormat("TP invite with message {0}", message);
GridInstantMessage m = new GridInstantMessage(scene, client.AgentId,
client.FirstName+" "+client.LastName, targetid,
(byte)InstantMessageDialog.RequestTeleport, false,
message, dest, false, presence.AbsolutePosition,
new Byte[0]);
if (m_TransferModule != null)
{
m_TransferModule.SendInstantMessage(m,
delegate(bool success) { });
}
}
public void OnTeleportLureRequest(UUID lureID, uint teleportFlags, IClientAPI client)
{
if (!(client.Scene is Scene))
return;
Scene scene = (Scene)(client.Scene);
ulong handle = 0;
uint x = 128;
uint y = 128;
uint z = 70;
Util.ParseFakeParcelID(lureID, out handle, out x, out y, out z);
Vector3 position = new Vector3();
position.X = (float)x;
position.Y = (float)y;
position.Z = (float)z;
scene.RequestTeleportLocation(client, handle, position,
Vector3.Zero, teleportFlags);
}
private void OnGridInstantMessage(GridInstantMessage msg)
{
// Forward remote teleport requests
//
if (msg.dialog != 22)
return;
if (m_TransferModule != null)
{
m_TransferModule.SendInstantMessage(msg,
delegate(bool success) { });
}
}
}
}
| |
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
namespace Ssw.Cli
{
internal class ProgramRunner
{
private ProgramArgs _args;
private AppDomain _appHostDomain;
private FileSystemWatcher _watcher;
private ServerHostProxy _proxy;
private Timer _timer;
private string _binDirectoryPath = null;
public ProgramRunner Start(ProgramArgs args)
{
if (!NormalizeArgs(args))
{
return null;
}
_args = args;
var binDir = new DirectoryInfo(args.BinDirectory);
_binDirectoryPath = binDir.FullName;
_appHostDomain = AppDomain.CreateDomain("ServerHostDomain", null, binDir.FullName, null, true);
_proxy = (ServerHostProxy)_appHostDomain.CreateInstanceFromAndUnwrap(new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath, typeof(ServerHostProxy).FullName);
try
{
var errorMessage = _proxy.Start(_args.AppHostAssembly, _args.AppHostType, _args.Port);
if (!string.IsNullOrWhiteSpace(errorMessage))
{
throw new Exception(errorMessage);
}
if (_args.Port > 0)
{
Console.WriteLine("Server listening at http://localhost:" + _args.Port);
}
if (_args.Poll <= 0)
{
_watcher = new FileSystemWatcher(_binDirectoryPath)
{
Filter = "*.*",
IncludeSubdirectories = false
};
_watcher.Changed += Watcher_Changed;
_watcher.Created += Watcher_Changed;
_watcher.Deleted += Watcher_Changed;
_watcher.Renamed += Watcher_Changed;
// start the watcher
_watcher.EnableRaisingEvents = true;
}
else
{
_timerPaused = false;
if (_timer == null) _timer = new Timer(Timer_Fired, null, _args.Poll, _args.Poll);
}
Console.ForegroundColor = ConsoleColor.DarkGray;
Console.WriteLine("Watching directory: " + binDir.FullName + (_timer != null ? " (polling every " + _args.Poll + " ms)": ""));
Console.ResetColor();
}
catch (Exception ex)
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("A fatal error occurred!");
Console.WriteLine(ex.Message);
Console.WriteLine();
Console.WriteLine("Please fix the error and press enter to continue ...");
Console.ResetColor();
if (!Console.IsInputRedirected)
{
Console.ReadLine();
Start(_args);
}
}
return this;
}
public void Stop()
{
try
{
if (_watcher != null)
{
_watcher.EnableRaisingEvents = false;
_watcher.Dispose();
}
_proxy?.Stop();
}
catch { /* No big deal, we're quitting anyway */ }
if (!Console.IsInputRedirected)
{
_timer?.Dispose();
Environment.Exit(0);
}
}
private void Restart()
{
if (_appHostDomain != null)
{
AppDomain.Unload(_appHostDomain);
_appHostDomain = null;
Thread.Sleep(2000);
Start(_args);
}
else
{
Stop();
}
}
private void Watcher_Changed(object sender, FileSystemEventArgs e)
{
if (!Regex.IsMatch(e.FullPath, _args.Watch))
return;
// if we've already turned off events, don't do anything
if (!_watcher.EnableRaisingEvents) return;
// stop watching to avoid multiple triggers
_watcher.EnableRaisingEvents = false;
Console.ForegroundColor = ConsoleColor.DarkGray;
Console.WriteLine(e.ChangeType + " detected to " + e.Name + " (" + e.FullPath + ")");
Console.ResetColor();
Restart();
}
private void Timer_Fired(object state)
{
Console.WriteLine("Timer_Fired: " + _timerPaused);
if (_timerPaused) return;
_timerPaused = true;
Console.WriteLine("Checking dir " + _binDirectoryPath + " for changes");
var changesDetected = DirectoryHasChanged(_binDirectoryPath);
if (changesDetected)
{
Console.ForegroundColor = ConsoleColor.DarkGray;
Console.WriteLine("Changes detected in " + _binDirectoryPath);
Console.ResetColor();
Restart();
}
_timerPaused = false;
}
private bool _timerPaused = false;
#region Private Methods
private static bool NormalizeArgs(ProgramArgs pArgs)
{
try
{
if (!pArgs.AppHostAssembly.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) &&
!pArgs.AppHostAssembly.EndsWith(".exe", StringComparison.OrdinalIgnoreCase))
{
pArgs.AppHostAssembly += ".dll";
}
var bin = pArgs.BinDirectory;
if (!string.IsNullOrWhiteSpace(bin) &&
!Directory.Exists(bin))
{
throw new DirectoryNotFoundException("Could not find bin directory: " + pArgs.BinDirectory);
}
if (!string.IsNullOrWhiteSpace(bin))
{
pArgs.AppHostAssembly = Path.Combine(bin, pArgs.AppHostAssembly);
}
if (!File.Exists(pArgs.AppHostAssembly))
{
throw new FileNotFoundException("Could not find assembly file: " + pArgs.AppHostAssembly);
}
pArgs.BinDirectory = Path.GetDirectoryName(pArgs.AppHostAssembly);
}
catch (Exception ex)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(ex.GetType().Name + ": " + ex.Message);
Console.ResetColor();
return false;
}
return true;
}
#endregion Private Methods
#region Config File Methods
//internal static string GetConfigFile()
//{
// var configFile = GetConfigFilePath();
// if (configFile == null)
// return null;
// return File.Exists(configFile) ? configFile : null;
//}
//private static void SaveConfigFile(ProgramArgs pArgs)
//{
// var configFile = GetConfigFilePath();
// if (configFile == null)
// return;
// File.WriteAllText(configFile, pArgs.ToXml());
//}
//private static string GetConfigFilePath()
//{
// //var exe = new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath;
// var exe = Assembly.GetExecutingAssembly().Location;
// var configFileName = Path.GetFileNameWithoutExtension(exe) + ".config";
// var dirName = Path.GetDirectoryName(exe);
// return dirName == null ? null : Path.Combine(dirName, configFileName);
//}
#endregion
#region FileCompare
private DateTime? _lastAccessTime = null;
private string _directoryHash = null;
private bool DirectoryHasChanged(string directory)
{
var dir = new DirectoryInfo(directory);
var lastAccessTime = dir.LastAccessTime;
var directoryHasChanged = false;
var rebuildingDirHash = _directoryHash == null ||
_lastAccessTime.GetValueOrDefault(DateTime.MinValue) != lastAccessTime;
if (rebuildingDirHash)
{
var sb = new StringBuilder();
foreach (var fi in dir.GetFiles("*.*", SearchOption.AllDirectories))
{
if (!Regex.IsMatch(fi.FullName, _args.Watch))
continue;
sb.Append("0;" +
string.Format("{0}{1}{2}{3}", fi.Name, fi.Length, fi.CreationTime, fi.LastWriteTime)
.GetHashCode());
}
var directoryHash = sb.ToString();
directoryHasChanged = _directoryHash != null && _directoryHash != directoryHash;
_lastAccessTime = lastAccessTime;
_directoryHash = directoryHash;
}
return directoryHasChanged;
}
#endregion
}
}
| |
/* ====================================================================
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.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
using System.IO;
using System.Reflection;
using System.Diagnostics;
using System.Drawing.Printing;
using System.Xml;
using fyiReporting.RDL;
using fyiReporting.RdlDesign.Resources;
using fyiReporting.RdlViewer;
using ScintillaNET;
namespace fyiReporting.RdlDesign
{
/// <summary>
/// Summary description for RdlEditPreview.
/// </summary>
internal class RdlEditPreview : System.Windows.Forms.UserControl
{
private System.Windows.Forms.TabControl tcEHP;
private System.Windows.Forms.TabPage tpEditor;
private System.Windows.Forms.TabPage tpBrowser;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
private fyiReporting.RdlViewer.RdlViewer rdlPreview;
private System.Windows.Forms.TabPage tpDesign;
private DesignCtl dcDesign;
public FindTab FindTab;
public delegate void RdlChangeHandler(object sender, EventArgs e);
public event RdlChangeHandler OnRdlChanged;
public event DesignCtl.HeightEventHandler OnHeightChanged;
public event RdlChangeHandler OnSelectionChanged;
public event RdlChangeHandler OnSelectionMoved;
public event RdlChangeHandler OnReportItemInserted;
public event RdlChangeHandler OnDesignTabChanged;
public event DesignCtl.OpenSubreportEventHandler OnOpenSubreport;
// When toggling between the items we need to track who has latest changes
DesignTabs _DesignChanged; // last designer that triggered change
DesignTabs _CurrentTab = DesignTabs.Design;
private DesignRuler dcTopRuler;
private DesignRuler dcLeftRuler;
private Scintilla scintilla1; // file position; for use with search
private bool noFireRDLTextChanged;
// Indicators 0-7 could be in use by a lexer
// so we'll use indicator 8 to highlight words.
const int SEARCH_INDICATOR_NUM = 8;
public RdlEditPreview()
{
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
rdlPreview.Zoom=1; // force default zoom to 1
// initialize the design tab
dcTopRuler = new DesignRuler();
dcLeftRuler = new DesignRuler();
dcLeftRuler.Vertical = true; // need to set before setting Design property
dcDesign = new DesignCtl();
dcTopRuler.Design = dcDesign; // associate rulers with design ctl
dcLeftRuler.Design = dcDesign;
tpDesign.Controls.Add(dcTopRuler);
tpDesign.Controls.Add(dcLeftRuler);
tpDesign.Controls.Add(dcDesign);
// Top ruler
dcTopRuler.Height = 14;
dcTopRuler.Width = tpDesign.Width;
dcTopRuler.Dock = DockStyle.Top;
dcTopRuler.Anchor = AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top;
dcTopRuler.Enabled = false;
// Left ruler
dcLeftRuler.Width = 14;
dcLeftRuler.Height = tpDesign.Height;
dcLeftRuler.Dock = DockStyle.Left;
dcLeftRuler.Anchor = AnchorStyles.Left | AnchorStyles.Bottom | AnchorStyles.Top;
dcLeftRuler.Enabled = false;
dcTopRuler.Offset = dcLeftRuler.Width;
dcLeftRuler.Offset = dcTopRuler.Height;
// dcDesign.Dock = System.Windows.Forms.DockStyle.Bottom;
dcDesign.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Right;
dcDesign.Location = new System.Drawing.Point(dcLeftRuler.Width, dcTopRuler.Height);
dcDesign.Name = "dcDesign";
dcDesign.Size = new System.Drawing.Size(tpDesign.Width-dcLeftRuler.Width, tpDesign.Height-dcTopRuler.Height);
dcDesign.TabIndex = 0;
dcDesign.ReportChanged += new System.EventHandler(dcDesign_ReportChanged);
dcDesign.HeightChanged += new DesignCtl.HeightEventHandler(dcDesign_HeightChanged);
dcDesign.SelectionChanged += new System.EventHandler(dcDesign_SelectionChanged);
dcDesign.SelectionMoved += new System.EventHandler(dcDesign_SelectionMoved);
dcDesign.ReportItemInserted += new System.EventHandler(dcDesign_ReportItemInserted);
dcDesign.OpenSubreport += new DesignCtl.OpenSubreportEventHandler(dcDesign_OpenSubreport);
//ScintillaNET Init
ConfigureScintillaStyle(scintilla1);
scintilla1.SetSavePoint();
}
void scintilla1_TextChanged(object sender, EventArgs e)
{
_DesignChanged = DesignTabs.Edit;
if (noFireRDLTextChanged)
return;
if (OnRdlChanged != null)
{
OnRdlChanged(this, e);
}
}
private void ConfigureScintillaStyle(ScintillaNET.Scintilla scintilla)
{
// Reset the styles
scintilla.StyleResetDefault();
scintilla.Styles[Style.Default].Font = "Consolas";
scintilla.Styles[Style.Default].Size = 10;
scintilla.StyleClearAll();
// Set the XML Lexer
scintilla.Lexer = Lexer.Xml;
// Show line numbers
scintilla.Margins[0].Width = 40;
// Enable folding
scintilla.SetProperty("fold", "1");
scintilla.SetProperty("fold.compact", "1");
scintilla.SetProperty("fold.html", "1");
// Use Margin 2 for fold markers
scintilla.Margins[2].Type = MarginType.Symbol;
scintilla.Margins[2].Mask = Marker.MaskFolders;
scintilla.Margins[2].Sensitive = true;
scintilla.Margins[2].Width = 20;
// Reset folder markers
for (int i = Marker.FolderEnd; i <= Marker.FolderOpen; i++)
{
scintilla.Markers[i].SetForeColor(SystemColors.ControlLightLight);
scintilla.Markers[i].SetBackColor(SystemColors.ControlDark);
}
// Style the folder markers
scintilla.Markers[Marker.Folder].Symbol = MarkerSymbol.BoxPlus;
scintilla.Markers[Marker.Folder].SetBackColor(SystemColors.ControlText);
scintilla.Markers[Marker.FolderOpen].Symbol = MarkerSymbol.BoxMinus;
scintilla.Markers[Marker.FolderEnd].Symbol = MarkerSymbol.BoxPlusConnected;
scintilla.Markers[Marker.FolderEnd].SetBackColor(SystemColors.ControlText);
scintilla.Markers[Marker.FolderMidTail].Symbol = MarkerSymbol.TCorner;
scintilla.Markers[Marker.FolderOpenMid].Symbol = MarkerSymbol.BoxMinusConnected;
scintilla.Markers[Marker.FolderSub].Symbol = MarkerSymbol.VLine;
scintilla.Markers[Marker.FolderTail].Symbol = MarkerSymbol.LCorner;
// Enable automatic folding
scintilla.AutomaticFold = AutomaticFold.Show | AutomaticFold.Click | AutomaticFold.Change;
// Set the Styles
scintilla.StyleResetDefault();
// I like fixed font for XML
scintilla.Styles[Style.Default].Font = "Courier";
scintilla.Styles[Style.Default].Size = 10;
scintilla.StyleClearAll();
scintilla.Styles[Style.Xml.Attribute].ForeColor = Color.Red;
scintilla.Styles[Style.Xml.Entity].ForeColor = Color.Red;
scintilla.Styles[Style.Xml.Comment].ForeColor = Color.Green;
scintilla.Styles[Style.Xml.Tag].ForeColor = Color.Blue;
scintilla.Styles[Style.Xml.TagEnd].ForeColor = Color.Blue;
scintilla.Styles[Style.Xml.DoubleString].ForeColor = Color.DeepPink;
scintilla.Styles[Style.Xml.SingleString].ForeColor = Color.DeepPink;
}
internal DesignCtl DesignCtl
{
get {return dcDesign;}
}
internal RdlViewer.RdlViewer PreviewCtl
{
get { return rdlPreview; }
}
internal DesignXmlDraw DrawCtl
{
get {return dcDesign.DrawCtl;}
}
public XmlDocument ReportDocument
{
get {return dcDesign.ReportDocument;}
}
internal DesignTabs DesignTab
{
get {return _CurrentTab;}
set
{
tcEHP.SelectedIndex = (int)value;
}
}
internal void SetFocus()
{
switch (_CurrentTab)
{
case DesignTabs.Edit:
scintilla1.Focus();
break;
case DesignTabs.Preview:
rdlPreview.Focus();
break;
case DesignTabs.Design:
dcDesign.SetFocus();
break;
}
}
internal void ShowEditLines(bool bShow)
{
scintilla1.Margins[0].Width = bShow ? 40 : 0;
}
internal void ShowPreviewWaitDialog(bool bShow)
{
rdlPreview.ShowWaitDialog = bShow;
}
internal bool ShowReportItemOutline
{
get {return dcDesign.ShowReportItemOutline;}
set {dcDesign.ShowReportItemOutline = value;}
}
override public string Text
{
get
{
if (_CurrentTab == DesignTabs.Design)
return dcDesign.ReportSource;
else
return scintilla1.Text;
}
set
{
if (_CurrentTab == DesignTabs.Edit)
SetTextToScintilla(value);
else
{
dcDesign.ReportSource = value;
}
if (_CurrentTab == DesignTabs.Preview)
{
_CurrentTab = DesignTabs.Design;
tcEHP.SelectedIndex = 0; // Force current tab to design
}
}
}
public StyleInfo SelectedStyle
{
get {return dcDesign.SelectedStyle;}
}
public string SelectionName
{
get {return dcDesign.SelectionName;}
}
public PointF SelectionPosition
{
get {return dcDesign.SelectionPosition;}
}
public SizeF SelectionSize
{
get {return dcDesign.SelectionSize;}
}
public void ApplyStyleToSelected(string name, string v)
{
if (_CurrentTab == DesignTabs.Design)
dcDesign.ApplyStyleToSelected(name, v);
}
public void SetSelectedText(string v)
{
if (_CurrentTab == DesignTabs.Design)
dcDesign.SetSelectedText(v);
}
public bool CanEdit
{
get
{
return _CurrentTab != DesignTabs.Preview;
}
}
private bool modified = false;
public bool Modified
{
get
{
return modified || scintilla1.Modified;
}
set
{
_DesignChanged = _CurrentTab;
modified = value;
if (value == false)
scintilla1.SetSavePoint();
}
}
public string UndoDescription
{
get
{
return _CurrentTab == DesignTabs.Design? dcDesign.UndoDescription: "";
}
}
public void StartUndoGroup(string description)
{
if (_CurrentTab == DesignTabs.Design)
dcDesign.StartUndoGroup(description);
}
public void EndUndoGroup(bool keepChanges)
{
if (_CurrentTab == DesignTabs.Design)
dcDesign.EndUndoGroup(keepChanges);
}
public bool CanUndo
{
get
{
switch (_CurrentTab)
{
case DesignTabs.Design:
return dcDesign.CanUndo;
case DesignTabs.Edit:
return scintilla1.CanUndo;
default:
return false;
}
}
}
public bool CanRedo
{
get
{
switch (_CurrentTab)
{
case DesignTabs.Design:
return dcDesign.CanUndo;
case DesignTabs.Edit:
return scintilla1.CanRedo;
default:
return false;
}
}
}
public int SelectionLength
{
get
{
switch (_CurrentTab)
{
case DesignTabs.Design:
return dcDesign.SelectionCount;
case DesignTabs.Edit:
return scintilla1.SelectedText.Length;
case DesignTabs.Preview:
return rdlPreview.CanCopy ? 1 : 0;
default:
return 0;
}
}
}
public string SelectedText
{
get
{
switch (_CurrentTab)
{
case DesignTabs.Design:
return dcDesign.SelectedText;
case DesignTabs.Edit:
return scintilla1.SelectedText;
case DesignTabs.Preview:
return rdlPreview.SelectText;
default:
return "";
}
}
set
{
if (_CurrentTab == DesignTabs.Edit && String.IsNullOrWhiteSpace(value))
scintilla1.ClearSelections();
else if (_CurrentTab == DesignTabs.Design && value.Length == 0)
dcDesign.Delete();
}
}
public void CleanUp()
{
}
public void ClearUndo()
{
switch (_CurrentTab)
{
case DesignTabs.Design:
dcDesign.ClearUndo();
break;
case DesignTabs.Edit:
scintilla1.EmptyUndoBuffer();
break;
default:
break;
}
}
public void Undo()
{
switch (_CurrentTab)
{
case DesignTabs.Design:
dcDesign.Undo();
break;
case DesignTabs.Edit:
scintilla1.Undo();
break;
default:
break;
}
}
public void Redo()
{
switch (_CurrentTab)
{
case DesignTabs.Design:
dcDesign.Redo();
break;
case DesignTabs.Edit:
scintilla1.Redo();
break;
default:
break;
}
}
public void Cut()
{
switch (_CurrentTab)
{
case DesignTabs.Design:
dcDesign.Cut();
break;
case DesignTabs.Edit:
scintilla1.Cut();
break;
default:
break;
}
}
public void Copy()
{
switch (_CurrentTab)
{
case DesignTabs.Design:
dcDesign.Copy();
break;
case DesignTabs.Edit:
scintilla1.Copy();
break;
case DesignTabs.Preview:
rdlPreview.Copy();
break;
default:
break;
}
}
public void Clear()
{
switch (_CurrentTab)
{
case DesignTabs.Design:
dcDesign.Clear();
break;
case DesignTabs.Edit:
scintilla1.Clear();
break;
default:
break;
}
}
public void Paste()
{
switch (_CurrentTab)
{
case DesignTabs.Design:
dcDesign.Paste();
break;
case DesignTabs.Edit:
scintilla1.Paste();
break;
default:
break;
}
}
public void SelectAll()
{
switch (_CurrentTab)
{
case DesignTabs.Design:
dcDesign.SelectAll();
break;
case DesignTabs.Edit:
scintilla1.SelectAll();
break;
default:
break;
}
}
public string CurrentInsert
{
get {return dcDesign.CurrentInsert; }
set
{
dcDesign.CurrentInsert = value;
}
}
public int CurrentLine
{
get
{
return scintilla1.CurrentLine + 1;
}
}
public int CurrentCh
{
get
{
return scintilla1.GetColumn(scintilla1.CurrentPosition);
}
}
public bool SelectionTool
{
get
{
if (_CurrentTab == DesignTabs.Preview)
{
return rdlPreview.SelectTool;
}
else
return false;
}
set
{
if (_CurrentTab == DesignTabs.Preview)
{
rdlPreview.SelectTool = value;
}
}
}
/// <summary>
/// Zoom
/// </summary>
public float Zoom
{
get {return this.rdlPreview.Zoom;}
set {this.rdlPreview.Zoom = value;}
}
/// <summary>
/// ZoomMode
/// </summary>
public ZoomEnum ZoomMode
{
get {return this.rdlPreview.ZoomMode;}
set {this.rdlPreview.ZoomMode = value;}
}
public void FindNext(Control ctl, string str, bool matchCase, bool revertSearch, bool showEndMsg = true)
{
if (_CurrentTab != DesignTabs.Edit)
return;
scintilla1.SearchFlags = matchCase ? SearchFlags.MatchCase : SearchFlags.None;
HighlightWord(str);
if (revertSearch)
{
scintilla1.TargetStart = scintilla1.SelectionStart;
scintilla1.TargetEnd = 0;
}
else
{
scintilla1.TargetStart = scintilla1.SelectionEnd;
scintilla1.TargetEnd = scintilla1.TextLength;
}
var pos = scintilla1.SearchInTarget(str);
if (pos == -1)
{
if (showEndMsg)
MessageBox.Show(ctl, Strings.RdlEditPreview_ShowI_ReachedEndDocument);
}
else
{
scintilla1.GotoPosition(pos);
scintilla1.SelectionStart = scintilla1.TargetStart;
scintilla1.SelectionEnd = scintilla1.TargetEnd;
}
}
private void HighlightWord(string text)
{
// Remove all uses of our indicator
scintilla1.IndicatorCurrent = SEARCH_INDICATOR_NUM;
scintilla1.IndicatorClearRange(0, scintilla1.TextLength);
// Update indicator appearance
scintilla1.Indicators[SEARCH_INDICATOR_NUM].Style = IndicatorStyle.StraightBox;
scintilla1.Indicators[SEARCH_INDICATOR_NUM].Under = true;
scintilla1.Indicators[SEARCH_INDICATOR_NUM].ForeColor = Color.Orange;
scintilla1.Indicators[SEARCH_INDICATOR_NUM].OutlineAlpha = 50;
scintilla1.Indicators[SEARCH_INDICATOR_NUM].Alpha = 30;
// Search the document
scintilla1.TargetStart = 0;
scintilla1.TargetEnd = scintilla1.TextLength;
while (scintilla1.SearchInTarget(text) != -1)
{
// Mark the search results with the current indicator
scintilla1.IndicatorFillRange(scintilla1.TargetStart, scintilla1.TargetEnd - scintilla1.TargetStart);
// Search the remainder of the document
scintilla1.TargetStart = scintilla1.TargetEnd;
scintilla1.TargetEnd = scintilla1.TextLength;
}
}
public void ClearSearchHighlight()
{
scintilla1.IndicatorCurrent = SEARCH_INDICATOR_NUM;
scintilla1.IndicatorClearRange(0, scintilla1.TextLength);
FindTab = null;
}
public void ReplaceNext(Control ctl, string str, string strReplace, bool matchCase)
{
if (_CurrentTab != DesignTabs.Edit)
return;
if (String.Compare(scintilla1.SelectedText, str, !matchCase) == 0)
{
scintilla1.ReplaceSelection(strReplace);
}
else
{
FindNext(ctl, str, matchCase, false);
if (String.Compare(scintilla1.SelectedText, str, !matchCase) == 0)
scintilla1.ReplaceSelection(strReplace);
}
}
public void ReplaceAll(Control ctl, string str, string strReplace, bool matchCase)
{
if (_CurrentTab != DesignTabs.Edit)
return;
scintilla1.TargetStart = 0;
scintilla1.TargetEnd = scintilla1.TextLength;
scintilla1.SearchFlags = matchCase ? SearchFlags.MatchCase : SearchFlags.None;
while (scintilla1.SearchInTarget(str) != -1)
{
scintilla1.ReplaceTarget(strReplace);
// Search the remainder of the document
scintilla1.TargetStart = scintilla1.TargetEnd;
scintilla1.TargetEnd = scintilla1.TextLength;
}
}
public void Goto(Control ctl, int nLine)
{
if (_CurrentTab != DesignTabs.Edit)
return;
if(nLine > scintilla1.Lines.Count)
nLine = scintilla1.Lines.Count;
scintilla1.Lines[nLine-1].Goto();
scintilla1.SelectionStart = scintilla1.Lines[nLine - 1].Position;
scintilla1.SelectionEnd = scintilla1.Lines[nLine - 1].EndPosition;
}
/// <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()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(RdlEditPreview));
this.tcEHP = new System.Windows.Forms.TabControl();
this.tpDesign = new System.Windows.Forms.TabPage();
this.tpEditor = new System.Windows.Forms.TabPage();
this.scintilla1 = new ScintillaNET.Scintilla();
this.tpBrowser = new System.Windows.Forms.TabPage();
this.rdlPreview = new fyiReporting.RdlViewer.RdlViewer();
this.tcEHP.SuspendLayout();
this.tpEditor.SuspendLayout();
this.tpBrowser.SuspendLayout();
this.SuspendLayout();
//
// tcEHP
//
resources.ApplyResources(this.tcEHP, "tcEHP");
this.tcEHP.Controls.Add(this.tpDesign);
this.tcEHP.Controls.Add(this.tpEditor);
this.tcEHP.Controls.Add(this.tpBrowser);
this.tcEHP.Name = "tcEHP";
this.tcEHP.SelectedIndex = 0;
this.tcEHP.SelectedIndexChanged += new System.EventHandler(this.tcEHP_SelectedIndexChanged);
//
// tpDesign
//
resources.ApplyResources(this.tpDesign, "tpDesign");
this.tpDesign.Name = "tpDesign";
this.tpDesign.Tag = "design";
//
// tpEditor
//
this.tpEditor.Controls.Add(this.scintilla1);
resources.ApplyResources(this.tpEditor, "tpEditor");
this.tpEditor.Name = "tpEditor";
this.tpEditor.Tag = "edit";
//
// scintilla1
//
resources.ApplyResources(this.scintilla1, "scintilla1");
this.scintilla1.Lexer = ScintillaNET.Lexer.Xml;
this.scintilla1.Name = "scintilla1";
this.scintilla1.UseTabs = false;
this.scintilla1.UpdateUI += new System.EventHandler<ScintillaNET.UpdateUIEventArgs>(this.scintilla1_UpdateUI);
this.scintilla1.TextChanged += new System.EventHandler(this.scintilla1_TextChanged);
//
// tpBrowser
//
this.tpBrowser.Controls.Add(this.rdlPreview);
resources.ApplyResources(this.tpBrowser, "tpBrowser");
this.tpBrowser.Name = "tpBrowser";
this.tpBrowser.Tag = "preview";
//
// rdlPreview
//
this.rdlPreview.Cursor = System.Windows.Forms.Cursors.Default;
resources.ApplyResources(this.rdlPreview, "rdlPreview");
this.rdlPreview.dSubReportGetContent = null;
this.rdlPreview.Folder = null;
this.rdlPreview.HighlightAll = false;
this.rdlPreview.HighlightAllColor = System.Drawing.Color.Fuchsia;
this.rdlPreview.HighlightCaseSensitive = false;
this.rdlPreview.HighlightItemColor = System.Drawing.Color.Aqua;
this.rdlPreview.HighlightPageItem = null;
this.rdlPreview.HighlightText = null;
this.rdlPreview.Name = "rdlPreview";
this.rdlPreview.PageCurrent = 1;
this.rdlPreview.Parameters = "";
this.rdlPreview.ReportName = null;
this.rdlPreview.ScrollMode = fyiReporting.RdlViewer.ScrollModeEnum.Continuous;
this.rdlPreview.SelectTool = false;
this.rdlPreview.ShowFindPanel = false;
this.rdlPreview.ShowParameterPanel = true;
this.rdlPreview.ShowWaitDialog = true;
this.rdlPreview.SourceFile = null;
this.rdlPreview.SourceRdl = null;
this.rdlPreview.UseTrueMargins = true;
this.rdlPreview.Zoom = 0.5495112F;
this.rdlPreview.ZoomMode = fyiReporting.RdlViewer.ZoomEnum.FitWidth;
//
// RdlEditPreview
//
this.Controls.Add(this.tcEHP);
this.Name = "RdlEditPreview";
resources.ApplyResources(this, "$this");
this.tcEHP.ResumeLayout(false);
this.tpEditor.ResumeLayout(false);
this.tpBrowser.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private void dcDesign_ReportChanged(object sender, System.EventArgs e)
{
_DesignChanged = DesignTabs.Design;
if (!Modified)
SetTextToScintilla(dcDesign.ReportSource);
if (OnRdlChanged != null)
{
OnRdlChanged(this, e);
}
}
private void SetTextToScintilla(string text)
{
bool firstSet = String.IsNullOrEmpty(scintilla1.Text);
noFireRDLTextChanged = firstSet;
scintilla1.Text = text;
if (firstSet)
{
scintilla1.EmptyUndoBuffer();
scintilla1.SetSavePoint();
noFireRDLTextChanged = false;
}
}
private void dcDesign_HeightChanged(object sender, HeightEventArgs e)
{
if (OnHeightChanged != null)
{
OnHeightChanged(this, e);
}
}
private void dcDesign_ReportItemInserted(object sender, System.EventArgs e)
{
if (OnReportItemInserted != null)
{
OnReportItemInserted(this, e);
}
}
private void dcDesign_OpenSubreport(object sender, SubReportEventArgs e)
{
if (OnOpenSubreport != null)
{
OnOpenSubreport(this, e);
}
}
private void dcDesign_SelectionChanged(object sender, System.EventArgs e)
{
if (OnSelectionChanged != null)
{
OnSelectionChanged(this, e);
}
}
private void dcDesign_SelectionMoved(object sender, System.EventArgs e)
{
if (OnSelectionMoved != null)
{
OnSelectionMoved(this, e);
}
}
private void tcEHP_SelectedIndexChanged(object sender, System.EventArgs e)
{
TabControl tc = (TabControl) sender;
DesignTabs tag = (DesignTabs)tc.SelectedIndex;
// Sync up the various pane whenever they switch so the editor is always accurate
switch (_DesignChanged)
{ // Sync up the editor in every case
case DesignTabs.Design:
// sync up the editor
SetTextToScintilla(dcDesign.ReportSource);
break;
case DesignTabs.Edit:
case DesignTabs.Preview:
break;
}
// Below sync up the changed item
if (tag == DesignTabs.Preview)
{
if (rdlPreview.SourceRdl != scintilla1.Text) // sync up preview
this.rdlPreview.SourceRdl = scintilla1.Text;
}
else if (tag == DesignTabs.Design)
{
if (_DesignChanged != DesignTabs.Design)
{
try
{
dcDesign.ReportSource = scintilla1.Text;
}
catch (Exception ge)
{
MessageBox.Show(ge.Message, Strings.RdlEditPreview_Show_Report);
tc.SelectedIndex = 1; // Force current tab to edit syntax
return;
}
}
}
_CurrentTab = tag;
if (OnDesignTabChanged != null)
OnDesignTabChanged(this, e);
}
/// <summary>
/// Print the report.
/// </summary>
public void Print(PrintDocument pd)
{
this.rdlPreview.Print(pd);
}
public void SaveAs(string filename, OutputPresentationType type)
{
this.rdlPreview.SaveAs(filename, type);
}
public string GetRdlText()
{
if (_CurrentTab == DesignTabs.Design)
return dcDesign.ReportSource;
else
return scintilla1.Text;
}
public void SetRdlText(string text)
{
if (_CurrentTab == DesignTabs.Design)
{
try
{
dcDesign.ReportSource = text;
dcDesign.Refresh();
SetTextToScintilla(text);
}
catch (Exception e)
{
MessageBox.Show(e.Message, Strings.RdlEditPreview_Show_Report);
SetTextToScintilla(text);
tcEHP.SelectedIndex = (int)DesignTabs.Edit; // Force current tab to edit syntax
_DesignChanged = DesignTabs.Edit;
}
}
else
{
SetTextToScintilla(text);
}
}
/// <summary>
/// Number of pages in the report.
/// </summary>
public int PageCount
{
get {return this.rdlPreview.PageCount;}
}
/// <summary>
/// Current page in view on report
/// </summary>
public int PageCurrent
{
get {return this.rdlPreview.PageCurrent;}
}
/// <summary>
/// Page height of the report.
/// </summary>
public float PageHeight
{
get {return this.rdlPreview.PageHeight;}
}
/// <summary>
/// Page width of the report.
/// </summary>
public float PageWidth
{
get {return this.rdlPreview.PageWidth;}
}
public fyiReporting.RdlViewer.RdlViewer Viewer
{
get {return this.rdlPreview;}
}
private void scintilla1_UpdateUI(object sender, UpdateUIEventArgs e)
{
if ((e.Change & UpdateChange.Selection) > 0)
{
if (OnSelectionChanged != null)
{
OnSelectionChanged(this, e);
}
}
}
}
public enum DesignTabs
{
Design,
Edit,
Preview
}
}
| |
//---------------------------------------------------------------------------
//
// <copyright file="LineGeometry.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.KnownBoxes;
using MS.Internal.Collections;
using MS.Internal.PresentationCore;
using MS.Utility;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Runtime.InteropServices;
using System.ComponentModel.Design.Serialization;
using System.Text;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Effects;
using System.Windows.Media.Media3D;
using System.Windows.Media.Animation;
using System.Windows.Media.Composition;
using System.Windows.Media.Imaging;
using System.Windows.Markup;
using System.Windows.Media.Converters;
using System.Security;
using System.Security.Permissions;
using SR=MS.Internal.PresentationCore.SR;
using SRID=MS.Internal.PresentationCore.SRID;
// These types are aliased to match the unamanaged names used in interop
using BOOL = System.UInt32;
using WORD = System.UInt16;
using Float = System.Single;
namespace System.Windows.Media
{
sealed partial class LineGeometry : Geometry
{
//------------------------------------------------------
//
// Public Methods
//
//------------------------------------------------------
#region Public Methods
/// <summary>
/// Shadows inherited Clone() with a strongly typed
/// version for convenience.
/// </summary>
public new LineGeometry Clone()
{
return (LineGeometry)base.Clone();
}
/// <summary>
/// Shadows inherited CloneCurrentValue() with a strongly typed
/// version for convenience.
/// </summary>
public new LineGeometry CloneCurrentValue()
{
return (LineGeometry)base.CloneCurrentValue();
}
#endregion Public Methods
//------------------------------------------------------
//
// Public Properties
//
//------------------------------------------------------
private static void StartPointPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
LineGeometry target = ((LineGeometry) d);
target.PropertyChanged(StartPointProperty);
}
private static void EndPointPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
LineGeometry target = ((LineGeometry) d);
target.PropertyChanged(EndPointProperty);
}
#region Public Properties
/// <summary>
/// StartPoint - Point. Default value is new Point().
/// </summary>
public Point StartPoint
{
get
{
return (Point) GetValue(StartPointProperty);
}
set
{
SetValueInternal(StartPointProperty, value);
}
}
/// <summary>
/// EndPoint - Point. Default value is new Point().
/// </summary>
public Point EndPoint
{
get
{
return (Point) GetValue(EndPointProperty);
}
set
{
SetValueInternal(EndPointProperty, value);
}
}
#endregion Public Properties
//------------------------------------------------------
//
// Protected Methods
//
//------------------------------------------------------
#region Protected Methods
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>.
/// </summary>
/// <returns>The new Freezable.</returns>
protected override Freezable CreateInstanceCore()
{
return new LineGeometry();
}
#endregion ProtectedMethods
//------------------------------------------------------
//
// Internal Methods
//
//------------------------------------------------------
#region Internal Methods
/// <SecurityNote>
/// Critical: This code calls into an unsafe code block
/// TreatAsSafe: This code does not return any critical data.It is ok to expose
/// Channels are safe to call into and do not go cross domain and cross process
/// </SecurityNote>
[SecurityCritical,SecurityTreatAsSafe]
internal override void UpdateResource(DUCE.Channel channel, bool skipOnChannelCheck)
{
// If we're told we can skip the channel check, then we must be on channel
Debug.Assert(!skipOnChannelCheck || _duceResource.IsOnChannel(channel));
if (skipOnChannelCheck || _duceResource.IsOnChannel(channel))
{
base.UpdateResource(channel, skipOnChannelCheck);
// Read values of properties into local variables
Transform vTransform = Transform;
// Obtain handles for properties that implement DUCE.IResource
DUCE.ResourceHandle hTransform;
if (vTransform == null ||
Object.ReferenceEquals(vTransform, Transform.Identity)
)
{
hTransform = DUCE.ResourceHandle.Null;
}
else
{
hTransform = ((DUCE.IResource)vTransform).GetHandle(channel);
}
// Obtain handles for animated properties
DUCE.ResourceHandle hStartPointAnimations = GetAnimationResourceHandle(StartPointProperty, channel);
DUCE.ResourceHandle hEndPointAnimations = GetAnimationResourceHandle(EndPointProperty, channel);
// Pack & send command packet
DUCE.MILCMD_LINEGEOMETRY data;
unsafe
{
data.Type = MILCMD.MilCmdLineGeometry;
data.Handle = _duceResource.GetHandle(channel);
data.hTransform = hTransform;
if (hStartPointAnimations.IsNull)
{
data.StartPoint = StartPoint;
}
data.hStartPointAnimations = hStartPointAnimations;
if (hEndPointAnimations.IsNull)
{
data.EndPoint = EndPoint;
}
data.hEndPointAnimations = hEndPointAnimations;
// Send packed command structure
channel.SendCommand(
(byte*)&data,
sizeof(DUCE.MILCMD_LINEGEOMETRY));
}
}
}
internal override DUCE.ResourceHandle AddRefOnChannelCore(DUCE.Channel channel)
{
if (_duceResource.CreateOrAddRefOnChannel(this, channel, System.Windows.Media.Composition.DUCE.ResourceType.TYPE_LINEGEOMETRY))
{
Transform vTransform = Transform;
if (vTransform != null) ((DUCE.IResource)vTransform).AddRefOnChannel(channel);
AddRefOnChannelAnimations(channel);
UpdateResource(channel, true /* skip "on channel" check - we already know that we're on channel */ );
}
return _duceResource.GetHandle(channel);
}
internal override void ReleaseOnChannelCore(DUCE.Channel channel)
{
Debug.Assert(_duceResource.IsOnChannel(channel));
if (_duceResource.ReleaseOnChannel(channel))
{
Transform vTransform = Transform;
if (vTransform != null) ((DUCE.IResource)vTransform).ReleaseOnChannel(channel);
ReleaseOnChannelAnimations(channel);
}
}
internal override DUCE.ResourceHandle GetHandleCore(DUCE.Channel channel)
{
// Note that we are in a lock here already.
return _duceResource.GetHandle(channel);
}
internal override int GetChannelCountCore()
{
// must already be in composition lock here
return _duceResource.GetChannelCount();
}
internal override DUCE.Channel GetChannelCore(int index)
{
// Note that we are in a lock here already.
return _duceResource.GetChannel(index);
}
#endregion Internal Methods
//------------------------------------------------------
//
// Internal Properties
//
//------------------------------------------------------
#region Internal Properties
#endregion Internal Properties
//------------------------------------------------------
//
// Dependency Properties
//
//------------------------------------------------------
#region Dependency Properties
/// <summary>
/// The DependencyProperty for the LineGeometry.StartPoint property.
/// </summary>
public static readonly DependencyProperty StartPointProperty;
/// <summary>
/// The DependencyProperty for the LineGeometry.EndPoint property.
/// </summary>
public static readonly DependencyProperty EndPointProperty;
#endregion Dependency Properties
//------------------------------------------------------
//
// Internal Fields
//
//------------------------------------------------------
#region Internal Fields
internal System.Windows.Media.Composition.DUCE.MultiChannelResource _duceResource = new System.Windows.Media.Composition.DUCE.MultiChannelResource();
internal static Point s_StartPoint = new Point();
internal static Point s_EndPoint = new Point();
#endregion Internal Fields
#region Constructors
//------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
static LineGeometry()
{
// We check our static default fields which are of type Freezable
// to make sure that they are not mutable, otherwise we will throw
// if these get touched by more than one thread in the lifetime
// of your app. (Windows OS Bug #947272)
//
// Initializations
Type typeofThis = typeof(LineGeometry);
StartPointProperty =
RegisterProperty("StartPoint",
typeof(Point),
typeofThis,
new Point(),
new PropertyChangedCallback(StartPointPropertyChanged),
null,
/* isIndependentlyAnimated = */ true,
/* coerceValueCallback */ null);
EndPointProperty =
RegisterProperty("EndPoint",
typeof(Point),
typeofThis,
new Point(),
new PropertyChangedCallback(EndPointPropertyChanged),
null,
/* isIndependentlyAnimated = */ true,
/* coerceValueCallback */ null);
}
#endregion Constructors
}
}
| |
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// Copyright (c) 2008 - 2015 Jb Evain
// Copyright (c) 2008 - 2011 Novell, Inc.
//
// Licensed under the MIT/X11 license.
//
using SquabPie.Mono.Collections.Generic;
namespace SquabPie.Mono.Cecil {
public sealed class FieldDefinition : FieldReference, IMemberDefinition, IConstantProvider, IMarshalInfoProvider {
ushort attributes;
Collection<CustomAttribute> custom_attributes;
int offset = Mixin.NotResolvedMarker;
internal int rva = Mixin.NotResolvedMarker;
byte [] initial_value;
object constant = Mixin.NotResolved;
MarshalInfo marshal_info;
void ResolveLayout ()
{
if (offset != Mixin.NotResolvedMarker)
return;
if (!HasImage) {
offset = Mixin.NoDataMarker;
return;
}
offset = Module.Read (this, (field, reader) => reader.ReadFieldLayout (field));
}
public bool HasLayoutInfo {
get {
if (offset >= 0)
return true;
ResolveLayout ();
return offset >= 0;
}
}
public int Offset {
get {
if (offset >= 0)
return offset;
ResolveLayout ();
return offset >= 0 ? offset : -1;
}
set { offset = value; }
}
void ResolveRVA ()
{
if (rva != Mixin.NotResolvedMarker)
return;
if (!HasImage)
return;
rva = Module.Read (this, (field, reader) => reader.ReadFieldRVA (field));
}
public int RVA {
get {
if (rva > 0)
return rva;
ResolveRVA ();
return rva > 0 ? rva : 0;
}
}
public byte [] InitialValue {
get {
if (initial_value != null)
return initial_value;
ResolveRVA ();
if (initial_value == null)
initial_value = Empty<byte>.Array;
return initial_value;
}
set {
initial_value = value;
rva = 0;
}
}
public FieldAttributes Attributes {
get { return (FieldAttributes) attributes; }
set { attributes = (ushort) value; }
}
public bool HasConstant {
get {
this.ResolveConstant (ref constant, Module);
return constant != Mixin.NoValue;
}
set { if (!value) constant = Mixin.NoValue; }
}
public object Constant {
get { return HasConstant ? constant : null; }
set { constant = value; }
}
public bool HasCustomAttributes {
get {
if (custom_attributes != null)
return custom_attributes.Count > 0;
return this.GetHasCustomAttributes (Module);
}
}
public Collection<CustomAttribute> CustomAttributes {
get { return custom_attributes ?? (this.GetCustomAttributes (ref custom_attributes, Module)); }
}
public bool HasMarshalInfo {
get {
if (marshal_info != null)
return true;
return this.GetHasMarshalInfo (Module);
}
}
public MarshalInfo MarshalInfo {
get { return marshal_info ?? (this.GetMarshalInfo (ref marshal_info, Module)); }
set { marshal_info = value; }
}
#region FieldAttributes
public bool IsCompilerControlled {
get { return attributes.GetMaskedAttributes ((ushort) FieldAttributes.FieldAccessMask, (ushort) FieldAttributes.CompilerControlled); }
set { attributes = attributes.SetMaskedAttributes ((ushort) FieldAttributes.FieldAccessMask, (ushort) FieldAttributes.CompilerControlled, value); }
}
public bool IsPrivate {
get { return attributes.GetMaskedAttributes ((ushort) FieldAttributes.FieldAccessMask, (ushort) FieldAttributes.Private); }
set { attributes = attributes.SetMaskedAttributes ((ushort) FieldAttributes.FieldAccessMask, (ushort) FieldAttributes.Private, value); }
}
public bool IsFamilyAndAssembly {
get { return attributes.GetMaskedAttributes ((ushort) FieldAttributes.FieldAccessMask, (ushort) FieldAttributes.FamANDAssem); }
set { attributes = attributes.SetMaskedAttributes ((ushort) FieldAttributes.FieldAccessMask, (ushort) FieldAttributes.FamANDAssem, value); }
}
public bool IsAssembly {
get { return attributes.GetMaskedAttributes ((ushort) FieldAttributes.FieldAccessMask, (ushort) FieldAttributes.Assembly); }
set { attributes = attributes.SetMaskedAttributes ((ushort) FieldAttributes.FieldAccessMask, (ushort) FieldAttributes.Assembly, value); }
}
public bool IsFamily {
get { return attributes.GetMaskedAttributes ((ushort) FieldAttributes.FieldAccessMask, (ushort) FieldAttributes.Family); }
set { attributes = attributes.SetMaskedAttributes ((ushort) FieldAttributes.FieldAccessMask, (ushort) FieldAttributes.Family, value); }
}
public bool IsFamilyOrAssembly {
get { return attributes.GetMaskedAttributes ((ushort) FieldAttributes.FieldAccessMask, (ushort) FieldAttributes.FamORAssem); }
set { attributes = attributes.SetMaskedAttributes ((ushort) FieldAttributes.FieldAccessMask, (ushort) FieldAttributes.FamORAssem, value); }
}
public bool IsPublic {
get { return attributes.GetMaskedAttributes ((ushort) FieldAttributes.FieldAccessMask, (ushort) FieldAttributes.Public); }
set { attributes = attributes.SetMaskedAttributes ((ushort) FieldAttributes.FieldAccessMask, (ushort) FieldAttributes.Public, value); }
}
public bool IsStatic {
get { return attributes.GetAttributes ((ushort) FieldAttributes.Static); }
set { attributes = attributes.SetAttributes ((ushort) FieldAttributes.Static, value); }
}
public bool IsInitOnly {
get { return attributes.GetAttributes ((ushort) FieldAttributes.InitOnly); }
set { attributes = attributes.SetAttributes ((ushort) FieldAttributes.InitOnly, value); }
}
public bool IsLiteral {
get { return attributes.GetAttributes ((ushort) FieldAttributes.Literal); }
set { attributes = attributes.SetAttributes ((ushort) FieldAttributes.Literal, value); }
}
public bool IsNotSerialized {
get { return attributes.GetAttributes ((ushort) FieldAttributes.NotSerialized); }
set { attributes = attributes.SetAttributes ((ushort) FieldAttributes.NotSerialized, value); }
}
public bool IsSpecialName {
get { return attributes.GetAttributes ((ushort) FieldAttributes.SpecialName); }
set { attributes = attributes.SetAttributes ((ushort) FieldAttributes.SpecialName, value); }
}
public bool IsPInvokeImpl {
get { return attributes.GetAttributes ((ushort) FieldAttributes.PInvokeImpl); }
set { attributes = attributes.SetAttributes ((ushort) FieldAttributes.PInvokeImpl, value); }
}
public bool IsRuntimeSpecialName {
get { return attributes.GetAttributes ((ushort) FieldAttributes.RTSpecialName); }
set { attributes = attributes.SetAttributes ((ushort) FieldAttributes.RTSpecialName, value); }
}
public bool HasDefault {
get { return attributes.GetAttributes ((ushort) FieldAttributes.HasDefault); }
set { attributes = attributes.SetAttributes ((ushort) FieldAttributes.HasDefault, value); }
}
#endregion
public override bool IsDefinition {
get { return true; }
}
public new TypeDefinition DeclaringType {
get { return (TypeDefinition) base.DeclaringType; }
set { base.DeclaringType = value; }
}
public FieldDefinition (string name, FieldAttributes attributes, TypeReference fieldType)
: base (name, fieldType)
{
this.attributes = (ushort) attributes;
}
public override FieldDefinition Resolve ()
{
return this;
}
}
static partial class Mixin {
public const int NotResolvedMarker = -2;
public const int NoDataMarker = -1;
}
}
| |
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Diagnostics;
namespace UnrealBuildTool
{
/**
* Helper class for finding 3rd party headers included in public engine headers.
**/
public class ThirdPartyHeaderFinder
{
/** List of all third party headers from the current game's modules */
static List<Header> ThirdPartyHeaders;
/** List of all engine headers referenced by the current game. */
static List<Header> EngineHeaders;
/**
* Helper class for storing headers included from public engine headers
**/
class IncludePath
{
/** Path of public engine header includes from which the other header is included. */
public string PublicHeaderPath;
/** The other header included from the public engine header (may be third party or private) */
public Header OtherHeader;
public IncludePath(string InPublicPath, Header Other)
{
PublicHeaderPath = InPublicPath;
OtherHeader = Other;
}
}
/**
* Helper class for storing info on a header file.
**/
class Header
{
/** Relative path to the header file. */
public string Path;
/** Name (with extension) of the header file. */
public string Name;
/** If true this header is a public engine header file. */
public bool IsPublic;
/** Contents of the header file. */
public string Contents;
/** Pregenerated variations of includes. */
public string[] TestIncludes;
public Header(string InPath, bool InPublic)
{
Path = InPath;
Name = System.IO.Path.GetFileName(InPath);
IsPublic = InPublic;
TestIncludes = new string[]
{
"\"" + Name + "\"",
"\\" + Name + "\"",
"/" + Name + "\"",
"<" + Name + ">",
"\\" + Name + ">",
"/" + Name + ">"
};
}
public override string ToString()
{
return Path;
}
public override int GetHashCode()
{
return Path.GetHashCode();
}
}
/**
* Find all third party and private header includes in public engine headers.
**/
public static void FindThirdPartyIncludes(UnrealTargetPlatform Platform, UnrealTargetConfiguration Configuration)
{
Log.TraceInformation("Looking for third party header includes in public engine header files (this may take a few minutes)...");
TargetInfo Target = new TargetInfo(Platform, Configuration);
List<string> UncheckedModules = new List<string>();
EngineHeaders = new List<Header>();
ThirdPartyHeaders = new List<Header>();
// Find all modules referenced by the current target
List<string> ModuleFileNames = RulesCompiler.FindAllRulesSourceFiles( RulesCompiler.RulesFileType.Module, AdditionalSearchPaths:null );
foreach (string ModuleFileName in ModuleFileNames)
{
string ModuleName = Path.GetFileNameWithoutExtension(Path.GetFileNameWithoutExtension(ModuleFileName));
try
{
string UnusedModuleFilename;
ModuleRules RulesObject = RulesCompiler.CreateModuleRules(ModuleName, Target, out UnusedModuleFilename);
bool bEngineHeaders = RulesObject.Type != ModuleRules.ModuleType.External;
foreach (string SystemIncludePath in RulesObject.PublicSystemIncludePaths)
{
FindHeaders(SystemIncludePath, bEngineHeaders ? EngineHeaders : ThirdPartyHeaders, bEngineHeaders);
}
foreach (string PublicIncludePath in RulesObject.PublicIncludePaths)
{
FindHeaders(PublicIncludePath, bEngineHeaders ? EngineHeaders : ThirdPartyHeaders, bEngineHeaders);
}
}
catch (Exception)
{
// Ignore, some modules may fail here.
UncheckedModules.Add(ModuleName);
}
}
// Search for illegal includes.
List<IncludePath> ThirdPartyIncludes = new List<IncludePath>();
List<IncludePath> PrivateIncludes = new List<IncludePath>();
CheckIfThirdPartyHeadersAreIncluded(ThirdPartyIncludes, PrivateIncludes);
// List all of the included 3rd party headers unless their name matches with any of the engine header.
if (ThirdPartyIncludes.Count > 0)
{
// Remove ambiguous headers
for (int IncludeIndex = ThirdPartyIncludes.Count - 1; IncludeIndex >= 0; --IncludeIndex)
{
if (FindHeader(EngineHeaders, ThirdPartyIncludes[IncludeIndex].OtherHeader.Name) != null)
{
ThirdPartyIncludes.RemoveAt(IncludeIndex);
}
}
if (ThirdPartyIncludes.Count > 0)
{
Log.TraceInformation("Warning: Found {0} third party header includes in public engine headers. Third party headers should only be included in private engine headers.", ThirdPartyIncludes.Count);
foreach (IncludePath HeaderPath in ThirdPartyIncludes)
{
if (FindHeader(EngineHeaders, HeaderPath.OtherHeader.Name) == null)
{
Log.TraceInformation("{0} includes {1}.", HeaderPath.PublicHeaderPath, HeaderPath.OtherHeader.Path);
}
}
}
}
// List all private engine headers included from public engine headers
if (PrivateIncludes.Count > 0)
{
Log.TraceInformation("Warning: Found {0} private engine header includes in public engine headers. Private engine headers should not be included in public engine headers.", PrivateIncludes.Count);
}
foreach (IncludePath HeaderPath in PrivateIncludes)
{
Log.TraceInformation("{0} includes {1}.", HeaderPath.PublicHeaderPath, HeaderPath.OtherHeader.Path);
}
if (PrivateIncludes.Count == 0 && ThirdPartyIncludes.Count == 0)
{
Log.TraceInformation("Finished looking for third party includes. Nothing found.");
}
if (UncheckedModules.Count > 0)
{
Log.TraceInformation("Warning: The following modules could not be checked (exception while trying to create ModuleRules object):");
for (int ModuleIndex = 0; ModuleIndex < UncheckedModules.Count; ++ModuleIndex)
{
Log.TraceInformation(" {0}", UncheckedModules[ModuleIndex]);
}
}
}
static void FindHeaders(string path, List<Header> headers, bool bPublic)
{
try
{
string[] HeaderFiles = Directory.GetFiles(path, "*.h", SearchOption.TopDirectoryOnly);
for (int i = 0; i < HeaderFiles.Length; ++i)
{
headers.Add(new Header(HeaderFiles[i], bPublic));
}
}
catch (Exception)
{
// Ignore all exceptions. Some paths may be invalid.
}
}
static Header FindHeader(List<Header> Headers, string HeaderName)
{
for (int Index = 0; Index < Headers.Count; ++Index)
{
if (String.Compare(Headers[Index].Name, HeaderName, true) == 0)
{
return Headers[Index];
}
}
return null;
}
static int FindNextInclude(string HeaderContents, int StartIndex)
{
int HashIndex = StartIndex;
while ((HashIndex = HeaderContents.IndexOf('#', HashIndex)) >= 0)
{
int IncludeIndex = HashIndex + 1;
for (; IncludeIndex < HeaderContents.Length && Char.IsWhiteSpace(HeaderContents[IncludeIndex]); ++IncludeIndex) ;
if ((IncludeIndex + 7) < HeaderContents.Length && HeaderContents.Substring(IncludeIndex, 7) == "include")
{
return HashIndex;
}
else
{
HashIndex++;
}
}
return -1;
}
static bool IsAnyThirdPartyHeaderIncluded(Header EngineHeader, HashSet<Header> VisitedHeaders, string HeaderPath, List<IncludePath> ThirdPartyIncludes, List<IncludePath> PrivateIncludes)
{
// Load the header contents if it hasn't been already
string HeaderContents = EngineHeader.Contents;
if (String.IsNullOrEmpty(HeaderContents))
{
StreamReader HeaderReader = new StreamReader(EngineHeader.Path);
EngineHeader.Contents = HeaderReader.ReadToEnd();
HeaderContents = EngineHeader.Contents;
HeaderReader.Close();
HeaderReader.Dispose();
}
bool Included = false;
// Check if any of the third party headers is included in the engine header
for (int HeaderIndex = 0; HeaderIndex < ThirdPartyHeaders.Count; ++HeaderIndex)
{
Header ThirdPartyHeader = ThirdPartyHeaders[HeaderIndex];
// Search for third party headers
for (int TestIndex = 0; TestIndex < ThirdPartyHeader.TestIncludes.Length; ++TestIndex)
{
if (HeaderContents.IndexOf(ThirdPartyHeader.TestIncludes[TestIndex], StringComparison.InvariantCultureIgnoreCase) >= 0)
{
ThirdPartyIncludes.Add(new IncludePath(EngineHeader.Path, ThirdPartyHeader));
Included = true;
}
}
}
// Mark this header as visited
VisitedHeaders.Add(EngineHeader);
// Recursively check for other includes
int IncludeIndex = -1;
while ((IncludeIndex = FindNextInclude(HeaderContents, IncludeIndex + 1)) >= 0)
{
// Get the included header name
int FirstQuoteIndex = HeaderContents.IndexOf('\"', IncludeIndex + 1);
if (FirstQuoteIndex == -1)
{
FirstQuoteIndex = HeaderContents.IndexOf('<', IncludeIndex + 1);
}
if (FirstQuoteIndex > IncludeIndex)
{
int LastQuoteIndex = HeaderContents.IndexOf('\"', FirstQuoteIndex + 1);
if (LastQuoteIndex == -1)
{
LastQuoteIndex = HeaderContents.IndexOf('>', FirstQuoteIndex + 1);
}
if (FirstQuoteIndex > -1 && LastQuoteIndex > -1)
{
string IncludedHeaderName = HeaderContents.Substring(FirstQuoteIndex + 1, LastQuoteIndex - FirstQuoteIndex - 1);
if (String.IsNullOrEmpty(IncludedHeaderName) == false)
{
// Find the included header in the list of all headers
IncludedHeaderName = Path.GetFileName(IncludedHeaderName);
Header IncludedHeader = FindHeader(EngineHeaders, IncludedHeaderName);
if (IncludedHeader != null && IncludedHeader.IsPublic == false && VisitedHeaders.Contains(IncludedHeader) == false)
{
// Recursively check for other includes
IsAnyThirdPartyHeaderIncluded(IncludedHeader, VisitedHeaders, HeaderPath + " -> " + IncludedHeader.Name, ThirdPartyIncludes, PrivateIncludes);
// Remember Private headers included from Public headers
if (EngineHeader.IsPublic)
{
PrivateIncludes.Add(new IncludePath(HeaderPath, IncludedHeader));
}
}
}
}
}
}
return Included;
}
static void CheckIfThirdPartyHeadersAreIncluded(List<IncludePath> ThirdPartyIncludes, List<IncludePath> PrivateIncludes)
{
foreach (Header HeaderFile in EngineHeaders)
{
if (HeaderFile.IsPublic)
{
HashSet<Header> VisitedHeaders = new HashSet<Header>();
IsAnyThirdPartyHeaderIncluded(HeaderFile, VisitedHeaders, HeaderFile.Path, ThirdPartyIncludes, PrivateIncludes);
}
} // For each engine header
}
}
}
| |
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using C1.Win.C1Preview;
namespace PCSUtils.Framework.ReportFrame
{
/// <summary>
/// PrintPreview only. User cannot print report from here.
/// </summary>
public class PreviewOnlyNoPrintDialog : System.Windows.Forms.Form
{
#region Declaration
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
private System.Windows.Forms.Label lblFormTitle;
private C1PrintPreviewControl mrpvReportViewer;
private System.Windows.Forms.ToolBarButton c1pBtnClose;
#endregion Declaration
#region Constructors, Destructors
/// <summary>
/// Default constructor
/// </summary>
public PreviewOnlyNoPrintDialog()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
}
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#endregion Constructors, Destructors
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(PreviewOnlyNoPrintDialog));
this.lblFormTitle = new System.Windows.Forms.Label();
this.c1pBtnClose = new System.Windows.Forms.ToolBarButton();
this.mrpvReportViewer = new C1.Win.C1Preview.C1PrintPreviewControl();
((System.ComponentModel.ISupportInitialize)(this.mrpvReportViewer)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.mrpvReportViewer.PreviewPane)).BeginInit();
this.mrpvReportViewer.SuspendLayout();
this.SuspendLayout();
//
// lblFormTitle
//
this.lblFormTitle.Location = new System.Drawing.Point(280, 0);
this.lblFormTitle.Name = "lblFormTitle";
this.lblFormTitle.Size = new System.Drawing.Size(72, 16);
this.lblFormTitle.TabIndex = 1;
this.lblFormTitle.Text = "Print Preview";
this.lblFormTitle.Visible = false;
//
// c1pBtnClose
//
this.c1pBtnClose.ImageIndex = 5;
this.c1pBtnClose.Name = "c1pBtnClose";
this.c1pBtnClose.ToolTipText = "Close";
//
// mrpvReportViewer
//
this.mrpvReportViewer.Dock = System.Windows.Forms.DockStyle.Fill;
this.mrpvReportViewer.Location = new System.Drawing.Point(0, 0);
this.mrpvReportViewer.Name = "mrpvReportViewer";
//
// mrpvReportViewer.OutlineView
//
this.mrpvReportViewer.PreviewOutlineView.Dock = System.Windows.Forms.DockStyle.Fill;
this.mrpvReportViewer.PreviewOutlineView.Location = new System.Drawing.Point(0, 0);
this.mrpvReportViewer.PreviewOutlineView.Name = "OutlineView";
this.mrpvReportViewer.PreviewOutlineView.Size = new System.Drawing.Size(165, 427);
this.mrpvReportViewer.PreviewOutlineView.TabIndex = 0;
//
// mrpvReportViewer.PreviewPane
//
this.mrpvReportViewer.PreviewPane.IntegrateExternalTools = true;
this.mrpvReportViewer.PreviewPane.TabIndex = 0;
//
// mrpvReportViewer.PreviewTextSearchPanel
//
this.mrpvReportViewer.PreviewTextSearchPanel.Dock = System.Windows.Forms.DockStyle.Right;
this.mrpvReportViewer.PreviewTextSearchPanel.Location = new System.Drawing.Point(530, 0);
this.mrpvReportViewer.PreviewTextSearchPanel.MinimumSize = new System.Drawing.Size(200, 240);
this.mrpvReportViewer.PreviewTextSearchPanel.Name = "PreviewTextSearchPanel";
this.mrpvReportViewer.PreviewTextSearchPanel.Size = new System.Drawing.Size(200, 453);
this.mrpvReportViewer.PreviewTextSearchPanel.TabIndex = 0;
this.mrpvReportViewer.PreviewTextSearchPanel.Visible = false;
//
// mrpvReportViewer.ThumbnailView
//
this.mrpvReportViewer.PreviewThumbnailView.Dock = System.Windows.Forms.DockStyle.Fill;
this.mrpvReportViewer.PreviewThumbnailView.Location = new System.Drawing.Point(0, 0);
this.mrpvReportViewer.PreviewThumbnailView.Name = "ThumbnailView";
this.mrpvReportViewer.PreviewThumbnailView.Size = new System.Drawing.Size(165, 400);
this.mrpvReportViewer.PreviewThumbnailView.TabIndex = 0;
this.mrpvReportViewer.PreviewThumbnailView.UseImageAsThumbnail = false;
this.mrpvReportViewer.Size = new System.Drawing.Size(689, 473);
this.mrpvReportViewer.TabIndex = 2;
this.mrpvReportViewer.Text = "c1PrintPreviewControl1";
//
//
//
this.mrpvReportViewer.ToolBars.Page.FacingContinuous.Image = ((System.Drawing.Image)(resources.GetObject("c1PrintPreviewControl1.ToolBars.Page.FacingContinuous.Image")));
this.mrpvReportViewer.ToolBars.Page.FacingContinuous.ImageTransparentColor = System.Drawing.Color.Magenta;
this.mrpvReportViewer.ToolBars.Page.FacingContinuous.Name = "btnPageFacingContinuous";
this.mrpvReportViewer.ToolBars.Page.FacingContinuous.Size = new System.Drawing.Size(23, 22);
this.mrpvReportViewer.ToolBars.Page.FacingContinuous.Tag = "C1PreviewActionEnum.PageFacingContinuous";
this.mrpvReportViewer.ToolBars.Page.FacingContinuous.ToolTipText = "Pages Facing Continuous View";
//
//
//
this.mrpvReportViewer.ToolBars.Text.Find.Image = ((System.Drawing.Image)(resources.GetObject("c1PrintPreviewControl1.ToolBars.Text.Find.Image")));
this.mrpvReportViewer.ToolBars.Text.Find.ImageTransparentColor = System.Drawing.Color.Magenta;
this.mrpvReportViewer.ToolBars.Text.Find.Name = "btnFind";
this.mrpvReportViewer.ToolBars.Text.Find.Size = new System.Drawing.Size(23, 22);
this.mrpvReportViewer.ToolBars.Text.Find.Tag = "C1PreviewActionEnum.Find";
this.mrpvReportViewer.ToolBars.Text.Find.ToolTipText = "Find Text";
//
//
//
this.mrpvReportViewer.ToolBars.Text.SelectText.Image = ((System.Drawing.Image)(resources.GetObject("c1PrintPreviewControl1.ToolBars.Text.SelectText.Image")));
this.mrpvReportViewer.ToolBars.Text.SelectText.ImageTransparentColor = System.Drawing.Color.Magenta;
this.mrpvReportViewer.ToolBars.Text.SelectText.Name = "btnSelectTextTool";
this.mrpvReportViewer.ToolBars.Text.SelectText.Size = new System.Drawing.Size(23, 22);
this.mrpvReportViewer.ToolBars.Text.SelectText.Tag = "C1PreviewActionEnum.SelectTextTool";
this.mrpvReportViewer.ToolBars.Text.SelectText.ToolTipText = "Text Select Tool";
//
// PreviewOnlyNoPrintDialog
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(689, 473);
this.Controls.Add(this.mrpvReportViewer);
this.Controls.Add(this.lblFormTitle);
this.KeyPreview = true;
this.Name = "PreviewOnlyNoPrintDialog";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Print Preview";
this.WindowState = System.Windows.Forms.FormWindowState.Maximized;
((System.ComponentModel.ISupportInitialize)(this.mrpvReportViewer.PreviewPane)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.mrpvReportViewer)).EndInit();
this.mrpvReportViewer.ResumeLayout(false);
this.mrpvReportViewer.PerformLayout();
this.ResumeLayout(false);
}
#endregion
#region Properties
public C1PrintPreviewControl ReportViewer
{
get
{
return mrpvReportViewer;
}
set
{
mrpvReportViewer = value;
}
}
private string mstrFormTitle;
public string FormTitle
{
get
{
return mstrFormTitle;
}
set
{
mstrFormTitle = value;
this.Text = string.Format("{0} - {1}", this.lblFormTitle.Text, mstrFormTitle);
}
}
#endregion Properties
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System.Collections.Generic;
using System;
using System.Diagnostics.Contracts;
namespace Microsoft.Research.CodeAnalysis
{
public static partial class AnalysisWrapper
{
//internal class ErrorInferenceException : Exception { } // the expression should be rejected
//internal class SkipInferenceException : Exception { } // the expression should be accepted even if it does not typecheck
public static partial class TypeBindings<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable>
where Variable : IEquatable<Variable>
where Expression : IEquatable<Expression>
where Type : IEquatable<Type>
{
[ContractVerification(true)]
public class BooleanExpressionsDecompiler<LogOptions>
where LogOptions : IFrameworkLogOptions
{
#region Object invariant
[ContractInvariantMethod]
private void ObjectInvariant()
{
Contract.Invariant(this.MethodDriver != null);
}
#endregion
#region State
readonly private IMethodDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable, LogOptions> MethodDriver;
#endregion
#region Constructor
public BooleanExpressionsDecompiler(IMethodDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable, LogOptions> methodDriver)
{
Contract.Requires(methodDriver != null);
this.MethodDriver = methodDriver;
}
#endregion
#region Getters
protected IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> DecoderForMetaData
{
get
{
Contract.Ensures(Contract.Result<IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly>>() != null);
return this.MethodDriver.MetaDataDecoder;
}
}
protected IExpressionContext<Local, Parameter, Method, Field, Type, Expression, Variable> Context
{
get
{
Contract.Ensures(Contract.Result < IExpressionContext<Local, Parameter, Method, Field, Type, Expression, Variable>>() != null);
return this.MethodDriver.Context;
}
}
#endregion
public bool FixIt(APC pc, BoxedExpression input, out BoxedExpression output)
{
Contract.Requires(input != null);
Contract.Ensures(!Contract.Result<bool>() || Contract.ValueAtReturn(out output) != null);
Dictionary<BoxedExpression, Type> types;
switch (InferTypes(pc, input, out types))
{
case Status.Ok:
{
switch (FixTypes(input, types, out output))
{
case Status.Ok:
{
return true;
}
case Status.Error:
{
output = null;
return false;
}
case Status.Skip:
{
output = input;
return true;
}
default:
{
output = null;
return false;
}
}
}
case Status.Error:
{
output = null;
// We saw a case of non-compatibility
return false;
}
case Status.Skip:
{
// Mic & Francesco:
// HACK
// Authorize expressions which cannot be checked (trust the origin about the content).
// It can arise in some situations (post-conditions with parameters and fields)
// so we act as if everything was ok, because we do not have the requested information
// to test it. The problem comes from some design decision in Clousot{2} which prevents
// informations to be retrieved by the TryGetFrameworkVariable method.
// More precisely, when an expression like this.mField = value is seen, what is done now
// is that the "object" object in the left variable definition is its path instead of the symbolic value.
// That way, left & right don't have the same symbolic value and the postcondition is not considered
// as trivial and stays in the output.
// One solution would be to change quite a bit how things are done, but for the time being, just trust
// the expression here.
output = input;
return true;
}
default:
{
output = null;
return false; // reject by default
}
}
}
#region Type inference
enum Status { Error, Skip, Ok, False }
private Status InferTypes(APC pc, BoxedExpression input, out Dictionary<BoxedExpression, Type> types)
{
Contract.Requires(input != null);
Contract.Ensures(Contract.Result<Status>() != Status.Ok || Contract.ValueAtReturn(out types) != null);
types = new Dictionary<BoxedExpression, Type>();
return InferTypesInternal(pc, input, new LiftedType(), types);
}
private Status InferTypesInternal(APC pc, BoxedExpression exp, LiftedType expected, Dictionary<BoxedExpression, Type> types)
{
Contract.Requires(exp != null);
Contract.Requires(types != null);
if (exp.IsSizeOf || exp.IsNull || exp.IsIsInst)
{
if (exp.IsSizeOf)
{
types[exp] = this.DecoderForMetaData.System_Int32;
}
else if (exp.IsNull)
{
int value; // null, thus value will be 0
float valueSingle;
double valueDouble;
if (exp.IsConstantFloat64(out valueDouble))
{
types[exp] = this.DecoderForMetaData.System_Double;
}
else if (exp.IsConstantFloat32(out valueSingle))
{
types[exp] = this.DecoderForMetaData.System_Single;
}
// It is important we test for an Int after the test for doubles, because for 0.0 exp.IsConstantInt() returns true, and this will mess up the types
// This has to do with the fact that constants are polymorphic
else if (exp.IsConstantInt(out value))
{
types[exp] = this.DecoderForMetaData.System_Int32;
}
else
{
types[exp] = this.DecoderForMetaData.System_Object;
}
}
else // if (exp.IsIsInst)
{
Contract.Assert(exp.IsIsInst);
types[exp] = this.DecoderForMetaData.System_Object;
}
return Status.Ok;
}
else if (exp.IsConstant)
{
int value;
if (exp.IsConstantInt(out value))
{
types[exp] = this.DecoderForMetaData.System_Int32;
}
return Status.Ok; // otherwise we do nothing
}
else if (exp.IsResult)
{
Contract.Assert(this.MethodDriver.Context != null); // was an assume
Contract.Assert(this.MethodDriver.Context.MethodContext != null); // was an assume
types[exp] = this.DecoderForMetaData.ReturnType(this.MethodDriver.Context.MethodContext.CurrentMethod);
return Status.Ok;
}
else if (exp.IsVariable)
{
Variable var;
if (!exp.TryGetFrameworkVariable(out var))
{
object t;
if (exp.TryGetType(out t) /*&& t != null*/)
{
types[exp] = (Type)t;
}
else
{
//throw new SkipInferenceException(); // see above comment
return Status.Skip;
}
}
else
{
// Infer the type
Contract.Assert(this.Context.ValueContext != null);
var p = this.Context.ValueContext.AccessPathList(pc, var, true, false);
var last = (PathElement)null;
for (var e = p; e != null; e = e.Tail)
{
last = e.Head;
}
Type t;
if (last != null && last.TryGetResultType(out t))
{
types[exp] = t;
}
else
{
var type = this.Context.ValueContext.GetType(pc, var);
if (type.IsNormal)
{
types[exp] = type.Value;
}
}
}
// don't care about ref or out, the useful information is the type we get when computing using the variable
if (types.ContainsKey(exp))
{
if (this.DecoderForMetaData.IsManagedPointer(types[exp]))
{
types[exp] = this.DecoderForMetaData.ElementType(types[exp]);
}
}
else // The type is not there, so we give up
{
//throw new SkipInferenceException();
return Status.Skip;
}
// return true;
return Status.Ok;
}
else if (exp.IsUnary)
{
var success = InferTypesInternal(pc, exp.UnaryArgument, null, types);
if (success != Status.Ok)
{
return success;
}
Type type;
switch (exp.UnaryOp)
{
#region All the UnaryOp cases
case UnaryOperator.Conv_i:
type = this.DecoderForMetaData.System_UIntPtr;
break;
case UnaryOperator.Conv_i1:
type = this.DecoderForMetaData.System_Int8;
break;
case UnaryOperator.Conv_i2:
type = this.DecoderForMetaData.System_Int16;
break;
case UnaryOperator.Conv_i4:
type = this.DecoderForMetaData.System_Int32;
break;
case UnaryOperator.Conv_i8:
type = this.DecoderForMetaData.System_Int64;
break;
case UnaryOperator.Conv_r_un:
type = this.DecoderForMetaData.System_Single;
break;
case UnaryOperator.Conv_r4:
type = this.DecoderForMetaData.System_Single;
break;
case UnaryOperator.Conv_r8:
type = this.DecoderForMetaData.System_Double;
break;
case UnaryOperator.Conv_u:
type = this.DecoderForMetaData.System_Int32;
break;
case UnaryOperator.Conv_u1:
type = this.DecoderForMetaData.System_UInt8;
break;
case UnaryOperator.Conv_u2:
type = this.DecoderForMetaData.System_UInt16;
break;
case UnaryOperator.Conv_u4:
type = this.DecoderForMetaData.System_UInt32;
break;
case UnaryOperator.Conv_u8:
type = this.DecoderForMetaData.System_UInt64;
break;
case UnaryOperator.Neg:
return InferTypesInternal(pc, exp.UnaryArgument, new LiftedType(), types);
case UnaryOperator.Not:
// F: Mic assumes expected can be null
if (expected == null)
{
//return false;
return Status.False;
}
if (!expected.TryGetType(out type))
{
type = this.DecoderForMetaData.System_Int32;
}
break;
case UnaryOperator.WritableBytes:
type = this.DecoderForMetaData.System_UInt64;
break;
default:
// return false;
return Status.False;
#endregion
}
types[exp] = type;
// return true;
return Status.Ok;
}
else if (exp.IsBinary)
{
Type type, typeLeft, typeRight;
var expectedType =
exp.BinaryOp == BinaryOperator.LogicalAnd || exp.BinaryOp == BinaryOperator.LogicalOr ?
new LiftedType(DecoderForMetaData.System_Boolean) : new LiftedType();
var leftResult = InferTypesInternal(pc, exp.BinaryLeft, expectedType, types);
if(leftResult != Status.Ok)
{
return leftResult;
}
var rightResult = InferTypesInternal(pc, exp.BinaryRight, expectedType, types);
if (rightResult != Status.Ok)
{
return rightResult;
}
// if (InferTypesInternal(pc, exp.BinaryLeft, expectedType, types)
// &&
// InferTypesInternal(pc, exp.BinaryRight, expectedType, types) == Status.Ok)
{
if (!types.TryGetValue(exp.BinaryLeft, out typeLeft)
|| !types.TryGetValue(exp.BinaryRight, out typeRight))
{
//throw new SkipInferenceException(); // see above comment
return Status.Skip;
}
if (!AreCompatible(typeLeft, typeRight, exp.BinaryOp))
{
//throw new ErrorInferenceException(); // we know it's an invalid operation and it should be rejected
return Status.Error;
}
switch (exp.BinaryOp)
{
#region All the binaryOp cases
case BinaryOperator.Add_Ovf:
case BinaryOperator.Add_Ovf_Un:
case BinaryOperator.And:
case BinaryOperator.Add:
case BinaryOperator.Div:
case BinaryOperator.Div_Un:
case BinaryOperator.Mul:
case BinaryOperator.Mul_Ovf:
case BinaryOperator.Mul_Ovf_Un:
case BinaryOperator.Or:
case BinaryOperator.Rem:
case BinaryOperator.Rem_Un:
case BinaryOperator.Shl:
case BinaryOperator.Shr:
case BinaryOperator.Shr_Un:
case BinaryOperator.Sub:
case BinaryOperator.Sub_Ovf:
case BinaryOperator.Sub_Ovf_Un:
case BinaryOperator.Xor:
{
//type = DecoderForMetaData.IsEnum(typeRight) ? typeRight : typeLeft; // prefer enums
if (DecoderForMetaData.IsEnum(typeLeft) || DecoderForMetaData.IsEnum(typeRight))
{
if (exp.BinaryOp == BinaryOperator.Add || exp.BinaryOp == BinaryOperator.Add_Ovf || exp.BinaryOp == BinaryOperator.Add_Ovf_Un
|| exp.BinaryOp == BinaryOperator.Sub || exp.BinaryOp == BinaryOperator.Sub_Ovf || exp.BinaryOp == BinaryOperator.Sub_Ovf_Un
|| exp.BinaryOp == BinaryOperator.Shl || exp.BinaryOp == BinaryOperator.Shr || exp.BinaryOp == BinaryOperator.Shr_Un)
//type = DecoderForMetaData.System_Int32; // arithmetic between flags always return int
{
//throw new ErrorInferenceException(); // no arithmetic on flags
return Status.Error;
}
else
{
type = DecoderForMetaData.IsEnum(typeLeft) ? typeLeft : typeRight;
}
}
else
{
type = IsUnsignedIntegerType(typeRight) ? typeRight : GetWiderType(typeLeft, typeRight); // priority for unsigned operations
}
}
break;
case BinaryOperator.Ceq:
case BinaryOperator.Cge:
case BinaryOperator.Cge_Un:
case BinaryOperator.Cgt:
case BinaryOperator.Cgt_Un:
case BinaryOperator.Cle:
case BinaryOperator.Cle_Un:
case BinaryOperator.Clt:
case BinaryOperator.Clt_Un:
case BinaryOperator.Cne_Un:
case BinaryOperator.Cobjeq:
case BinaryOperator.LogicalAnd:
case BinaryOperator.LogicalOr:
{
type = this.DecoderForMetaData.System_Boolean;
}
break;
default:
//return false;
return Status.False;
#endregion
}
types[exp] = type;
//return true;
return Status.Ok;
}
}
else if (exp.IsArrayIndex)
{
types[exp] = ((BoxedExpression.ArrayIndexExpression<Type>)exp).Type;
//return true;
return Status.Ok;
}
else if (exp.IsQuantified)
{
types[exp] = this.DecoderForMetaData.System_Boolean;
// return true;
return Status.Ok;
}
#if DEBUG
Console.WriteLine("Unknown BoxedExpression kind (in InferTypes): {0}", exp);
#endif
// no other case?
// return false;
return Status.False;
}
private bool IsNarrowerType(Type left, Type right)
{
if (GetWiderType(left, right).Equals(right))
return true;
return false;
}
private Type GetWiderType(Type left, Type right)
{
if(left.Equals(right))
{
return left;
}
var int8 = DecoderForMetaData.System_Int8;
var int16 = DecoderForMetaData.System_Int16;
var int32 = DecoderForMetaData.System_Int32;
var int64 = DecoderForMetaData.System_Int64;
if (left.Equals(int8))
{
return right; // right can ve int8, 16, 32, 64
}
if (right.Equals(int8))
{
return left; // left can be int16, 32, 64
}
if (left.Equals(int16))
{
return right; // right can be int16, 32, 64
}
if (right.Equals(int16))
{
return left; // left can be int32, 64
}
if (left.Equals(int32))
{
return right; // right can be int32, 64
}
if (right.Equals(int32))
{
return left; // left can be int64
}
return left;
}
#endregion
#region Type fixing
private bool IsUnsignedIntegerType(Type t)
{
return
t.Equals(DecoderForMetaData.System_Char)
|| t.Equals(DecoderForMetaData.System_UInt8)
|| t.Equals(DecoderForMetaData.System_UInt16)
|| t.Equals(DecoderForMetaData.System_UInt32)
|| t.Equals(DecoderForMetaData.System_UInt64);
}
private bool IsSignedIntegerType(Type t)
{
return
t.Equals(DecoderForMetaData.System_Int8)
|| t.Equals(DecoderForMetaData.System_Int16)
|| t.Equals(DecoderForMetaData.System_Int32)
|| t.Equals(DecoderForMetaData.System_Int64);
}
private Type ToUnsignedType(Type t)
{
if (IsUnsignedIntegerType(t))
return t;
else if (IsSignedIntegerType(t))
{
if (t.Equals(DecoderForMetaData.System_Int8))
return DecoderForMetaData.System_UInt8;
else if (t.Equals(DecoderForMetaData.System_Int16))
return DecoderForMetaData.System_UInt16;
else if (t.Equals(DecoderForMetaData.System_Int32))
return DecoderForMetaData.System_UInt32;
else if (t.Equals(DecoderForMetaData.System_Int64))
return DecoderForMetaData.System_UInt64;
}
return t;
}
private Type ToSignedType(Type t)
{
if (IsSignedIntegerType(t))
return t;
else if (IsUnsignedIntegerType(t))
{
if (t.Equals(DecoderForMetaData.System_UInt8))
return DecoderForMetaData.System_Int8;
else if (t.Equals(DecoderForMetaData.System_UInt16))
return DecoderForMetaData.System_Int16;
else if (t.Equals(DecoderForMetaData.System_UInt32))
return DecoderForMetaData.System_Int32;
else if (t.Equals(DecoderForMetaData.System_UInt64))
return DecoderForMetaData.System_Int64;
}
return t;
}
private bool IsIntegerType(Type t)
{
return IsUnsignedIntegerType(t) || IsSignedIntegerType(t);
}
private bool AreCompatible(Type t1, Type t2, BinaryOperator op)
{
if (t1 == null || t2 == null)
return false;
if (t1.Equals(default(Type)) || t2.Equals(default(Type)))
return false;
if (t1.Equals(t2))
return true;
if (op == BinaryOperator.Cobjeq
|| op == BinaryOperator.Ceq
|| op == BinaryOperator.Cne_Un
|| op == BinaryOperator.Or
|| op == BinaryOperator.Xor
|| op == BinaryOperator.LogicalAnd
|| op == BinaryOperator.LogicalOr)
{
// It will be fixed as "true" or "false" by FixTypes
if (t1.Equals(DecoderForMetaData.System_Boolean) && IsIntegerType(t2)
|| t2.Equals(DecoderForMetaData.System_Boolean) && IsIntegerType(t1))
return true;
}
if (op == BinaryOperator.LogicalAnd || op == BinaryOperator.LogicalOr)
{
if ((IsReferenceType(t1) || IsBool(t1)) && (IsReferenceType(t2) || IsBool(t2))) return true;
}
if (op == BinaryOperator.Cobjeq || op == BinaryOperator.Ceq || op == BinaryOperator.Cne_Un)
{
// object == another object
// the check here could be more thorough, like testing whether types are actually
// convertible, but it didn't prove to be necessary
if (DecoderForMetaData.IsReferenceType(t1) && DecoderForMetaData.IsReferenceType(t2))
return true;
if (DecoderForMetaData.IsFormalTypeParameter(t1) || DecoderForMetaData.IsFormalTypeParameter(t2))
{
return true;
}
}
if (op == BinaryOperator.Cobjeq || op == BinaryOperator.Ceq || op == BinaryOperator.Cne_Un)
{
// object == 0 (will be fixed to object == null)
if ((DecoderForMetaData.IsReferenceType(t1) && IsIntegerType(t2))
|| (DecoderForMetaData.IsReferenceType(t2) && IsIntegerType(t1)))
return true;
}
if (IsIntegerType(t1) && IsIntegerType(t2))
{
if (op == BinaryOperator.Sub || op == BinaryOperator.Sub_Ovf || op == BinaryOperator.Sub_Ovf_Un)
{
if (IsUnsignedIntegerType(t1) || IsUnsignedIntegerType(t2))
return false; // No substraction on unsigned types
}
return true;
}
if (DecoderForMetaData.IsEnum(t1) && DecoderForMetaData.IsEnum(t2))
return t1.Equals(t2);
// Authorize mixing int and enums (including uint, ...), for "flag & int"
// Then it's fixed int the end by FixTypesInternal
if ((DecoderForMetaData.IsEnum(t1) && IsIntegerType(t2))
|| (DecoderForMetaData.IsEnum(t2) && IsIntegerType(t1)))
return true;
return false;
}
private Status FixTypes(BoxedExpression exp, Dictionary<BoxedExpression, Type> types, out BoxedExpression result)
{
Contract.Requires(exp != null);
Contract.Requires(types != null);
Contract.Ensures(Contract.Result<Status>() != Status.Ok || Contract.ValueAtReturn(out result) != null);
return FixTypesInternal(exp, types, new LiftedType(), out result);
}
private Status FixTypesInternal(BoxedExpression exp, Dictionary<BoxedExpression, Type> types, LiftedType expectedType, out BoxedExpression result)
{
Contract.Requires(exp != null);
Contract.Requires(types != null);
Contract.Requires(expectedType != null);
Contract.Ensures(Contract.Result<Status>() != Status.Ok || Contract.ValueAtReturn(out result) != null);
Type prevType, expectTyp;
if (exp.IsVariable && types.TryGetValue(exp, out prevType) && expectedType.TryGetType(out expectTyp) && prevType.Equals(expectTyp))
{
result = exp;
return Status.Ok;
}
int value;
if (exp.IsResult)
{
Type restype;
if (types.TryGetValue(exp, out restype))
{
if (this.DecoderForMetaData.IsUnmanagedPointer(restype))
{
//throw new ErrorInferenceException(); // unmanaged pointers are prohibited as template arguments
result = null;
return Status.Error;
}
}
}
else if (exp.IsConstantInt(out value))
{
if (IsBool(expectedType))
{
result = BoxedExpression.ConstBool(value, this.DecoderForMetaData);
return Status.Ok;
}
Type t;
if (IsEnum(expectedType, out t))
{
string name = null;
Field f;
if(this.DecoderForMetaData.TryGetEnumFieldNameFromValue(value, t, out f))
{
name = this.DecoderForMetaData.Name(f);
}
result = BoxedExpression.ConstCast(value, name, this.DecoderForMetaData.System_Int32, t, this.DecoderForMetaData);
return Status.Ok;
}
if(IsReference(expectedType, out t))
{
if (value == 0)
{
if (this.MethodDriver.MetaDataDecoder.IsReferenceType(t))
{
result = BoxedExpression.Const(null, t, this.DecoderForMetaData); // no need to cast null to System.Object
return Status.Ok;
}
else
{
result = BoxedExpression.ConstCast(null, null, t, t, this.DecoderForMetaData);
return Status.Ok;
}
}
}
}
else if (exp.IsVariable)
{
Type t;
if (types.TryGetValue(exp, out t))
{
Type expected_t;
if (expectedType.TryGetType(out expected_t))
{
// The type is not the one expected but we're dealing with integers. Let's do a brutal cast
if (!t.Equals(expected_t))
{
// Cast the variable as a expected_t
Variable var;
if (!exp.TryGetFrameworkVariable(out var))
{
result = exp; // not supposed to happen, the call must have succeeded before in InferTypes
return Status.Ok;
}
if (IsSignedIntegerType(t) && IsUnsignedIntegerType(expected_t)) // bypass signed/unsigned restriction because contracts are right
{
result = BoxedExpression.VarCastUnchecked(var, exp.AccessPath, t, expected_t);
return Status.Ok;
}
else if (IsReferenceType(t) && IsBool(expected_t))
{
// insert x != null
result = BoxedExpression.Binary(BinaryOperator.Cne_Un, exp, BoxedExpression.Const(null, t, this.DecoderForMetaData));
return Status.Ok;
}
else
{
// don't cast to System.Object, it's never relevant (it could be generated for null comparisons)
//if (expected_t.Equals(this.DecoderForMetaData.System_Object))
// return exp;
//else
result = IsNarrowerType(t, expected_t) ? // if t can be widened to expected_t, avoid generating the cast, as the c# compiler will do it
exp :
BoxedExpression.VarCast(var, exp.AccessPath, t, expected_t);
return Status.Ok;
}
}
}
}
}
else if (exp.IsBinary)
{
Type typeLeft, typeRight;
if (types.TryGetValue(exp.BinaryLeft, out typeLeft) && types.TryGetValue(exp.BinaryRight, out typeRight))
{
Contract.Assume(typeLeft != null);
Contract.Assume(typeRight != null);
var newType = Join(typeLeft, typeRight, exp.BinaryOp);
if (newType == null)
{
result = null;
return Status.Error;
}
if (this.DecoderForMetaData.IsFormalTypeParameter(typeLeft) || this.DecoderForMetaData.IsFormalTypeParameter(typeRight))
{
// Case when the two sides are of type coming from a formal parameter
if (exp.BinaryOp == BinaryOperator.Ceq || exp.BinaryOp == BinaryOperator.Cobjeq)
{
result = BoxedExpression.BinaryMethodToCall(exp.BinaryOp, exp.BinaryLeft, exp.BinaryRight, "Equals");
return Status.Ok;
}
else
{
//throw new SkipInferenceException(); // trust the contract... ?
result = null;
return Status.Skip;
}
}
BoxedExpression bLeft, bRight;
var leftStatus = FixTypesInternal(exp.BinaryLeft, types, newType, out bLeft);
if (leftStatus != Status.Ok)
{
result = null;
return leftStatus;
}
var rightStatus = FixTypesInternal(exp.BinaryRight, types, newType, out bRight);
if(rightStatus != Status.Ok)
{
result = null;
return rightStatus;
}
if (!newType.Equals(expectedType))
{
Type t;
if (expectedType.TryGetType(out t))
{
// Cast to bool only if it's not already the case
if (exp.BinaryOp != BinaryOperator.Cobjeq && exp.BinaryOp != BinaryOperator.Cne_Un && exp.BinaryOp != BinaryOperator.Ceq)
{
// Michael's code
// return BoxedExpression.BinaryCast(exp.BinaryOp, bLeft, bRight, t);
switch (exp.BinaryOp)
{
case BinaryOperator.Cge:
case BinaryOperator.Cge_Un:
case BinaryOperator.Cgt:
case BinaryOperator.Cgt_Un:
case BinaryOperator.Cle:
case BinaryOperator.Cle_Un:
case BinaryOperator.Clt:
case BinaryOperator.Clt_Un:
{
result = BoxedExpression.Binary(exp.BinaryOp, bLeft, bRight);
return Status.Ok;
}
default:
{
result = BoxedExpression.Binary(
BinaryOperator.Cne_Un,
BoxedExpression.Binary(exp.BinaryOp, bLeft, bRight),
BoxedExpression.Const(0, this.DecoderForMetaData.System_Int32, this.DecoderForMetaData));
return Status.Ok;
}
}
}
}
result = BoxedExpression.Binary(exp.BinaryOp, bLeft, bRight);
return Status.Ok;
}
else
{
result = BoxedExpression.Binary(exp.BinaryOp, bLeft, bRight);
return Status.Ok;
}
}
}
else if (exp.IsUnary)
{
Type t_cur = types[exp];
Type t_expected;
if (expectedType.TryGetType(out t_expected))
{
if (!t_cur.Equals(t_expected))
{
if (IsSignedIntegerType(t_cur) && IsUnsignedIntegerType(t_expected)) // bypass signed/unsigned restriction because contracts are right
{
result = BoxedExpression.UnaryCastUnchecked(exp.UnaryOp, exp.UnaryArgument, t_expected);
return Status.Ok;
}
else
{
result = BoxedExpression.UnaryCast(exp.UnaryOp, exp.UnaryArgument, t_expected);
return Status.Ok;
}
}
}
}
else if (exp.IsIsInst)
{
// return " result != null "
result = BoxedExpression.Binary(BinaryOperator.Cne_Un, exp, BoxedExpression.Const(null, this.DecoderForMetaData.System_Object, this.DecoderForMetaData));
return Status.Ok;
}
// Nothing to do in all the other cases
result = exp;
return Status.Ok;
}
private bool IsBool(LiftedType type)
{
Contract.Requires(type != null);
Type t;
return type.TryGetType(out t) && IsBool(t);
}
private bool IsBool(Type type)
{
return type.Equals(this.DecoderForMetaData.System_Boolean);
}
private bool IsReferenceType(Type type)
{
return this.DecoderForMetaData.IsReferenceType(type);
}
private bool IsEnum(LiftedType type, out Type t)
{
Contract.Requires(type != null);
return type.TryGetType(out t) && this.DecoderForMetaData.IsEnum(t);
}
private bool IsReference(LiftedType type, out Type t)
{
Contract.Requires(type != null);
return type.TryGetType(out t) && this.DecoderForMetaData.IsReferenceType(t);
}
private LiftedType Join(Type left, Type right, BinaryOperator bop)
{
Contract.Requires(left != null);
Contract.Requires(right != null);
if (this.DecoderForMetaData.System_Boolean.Equals(left) || this.DecoderForMetaData.System_Boolean.Equals(right))
{
return new LiftedType(this.DecoderForMetaData.System_Boolean);
}
// fix type for Flag & int
else if (this.DecoderForMetaData.IsEnum(left))
{
return new LiftedType(left);
}
else if (this.DecoderForMetaData.IsEnum(right))
{
return new LiftedType(right);
}
else if (this.DecoderForMetaData.System_Int32.Equals(left))
{
return new LiftedType(right);
}
else if (this.DecoderForMetaData.System_Int32.Equals(right))
{
return new LiftedType(left);
}
else if ((this.DecoderForMetaData.System_Object.Equals(left) && this.DecoderForMetaData.System_String.Equals(right))
|| (this.DecoderForMetaData.System_Object.Equals(right) && this.DecoderForMetaData.System_String.Equals(left)))
{
// Special case for object == string, cast the object to string
return new LiftedType(this.DecoderForMetaData.System_String);
}
else if (DecoderForMetaData.IsReferenceType(left) && !DecoderForMetaData.IsReferenceType(right))
{
return new LiftedType(left);
}
else if (!DecoderForMetaData.IsReferenceType(left) && DecoderForMetaData.IsReferenceType(right))
{
return new LiftedType(right);
}
else if (DecoderForMetaData.IsReferenceType(left) && DecoderForMetaData.IsReferenceType(right))
{
if (bop == BinaryOperator.Ceq || bop == BinaryOperator.Cobjeq || bop == BinaryOperator.Cne_Un)
{
// object == another object
if (DecoderForMetaData.DerivesFrom(left, right))
return new LiftedType(left); // no need to cast, C# rules will do it for us
else if (DecoderForMetaData.DerivesFrom(right, left))
return new LiftedType(right); // no need to cast, C# rules will do it for us
}
}
else if (left.Equals(right))
{
return new LiftedType(left);
}
//return new LiftedType(); // Top
// throw new ErrorInferenceException(); // cannot be united
return null;
}
#endregion
#region ExpectedType
private class LiftedType
{
private readonly Type type;
private readonly bool set;
public LiftedType(Type type)
{
this.type = type;
this.set = true;
}
public LiftedType()
{
this.type = default(Type);
this.set = false;
}
public bool TryGetType(out Type t)
{
t = this.type;
return this.set;
}
public override bool Equals(object obj)
{
if (obj is LiftedType)
{
var lfr = obj as LiftedType;
if (!this.set)
return !lfr.set;
return this.type.Equals(lfr.type);
}
return false;
}
public override int GetHashCode()
{
return this.type.GetHashCode();
}
public override string ToString()
{
return this.set ? type.ToString() : "Top";
}
}
#endregion
}
}
}
}
| |
#region License, Terms and Author(s)
//
// Gurtle - IBugTraqProvider for Google Code
// Copyright (c) 2008, 2009 Atif Aziz. All rights reserved.
//
// Author(s):
//
// Atif Aziz, http://www.raboof.com
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
namespace Gurtle
{
#region Imports
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
#endregion
internal sealed partial class WorkProgressForm : Form
{
private string _successStatusText = "Finished";
private string _errorStatusText = "Error: {Message}";
private string _cancelledStatusText = "User-Cancelled";
public event EventHandler WorkFailed;
public bool StartWorkOnShow { get; set; }
public bool CloseOnCompletion { get; set; }
public string SuccessStatusText
{
get { return _successStatusText ?? string.Empty; }
set { _successStatusText = value; }
}
public string ErrorStatusText
{
get { return _errorStatusText ?? string.Empty; }
set { _errorStatusText = value; }
}
public string CancelledStatusText
{
get { return _cancelledStatusText ?? string.Empty; }
set { _cancelledStatusText = value; }
}
public bool Cancelled { get; private set; }
public Exception Error { get; private set; }
public object Result { get; private set; }
public BackgroundWorker Worker { get { return _worker; } }
public WorkProgressForm()
{
InitializeComponent();
}
public void ReportProgress(int percentage)
{
ReportProgressImpl(percentage, null);
}
public void ReportProgress(string status)
{
ReportProgress(-1, status);
}
public void ReportProgress(int percentage, string status)
{
ReportProgressImpl(percentage, () => _status.Text = status);
}
public void ReportDetailLine(string line)
{
ReportProgressImpl(-1, () => _detailsBox.AppendText(line + Environment.NewLine));
}
private void ReportProgressImpl(int percentage, Action update)
{
if (InvokeRequired)
Worker.ReportProgress(percentage, update);
else
OnProgressChanged(percentage, update);
}
protected override void OnShown(EventArgs e)
{
if (StartWorkOnShow)
Worker.RunWorkerAsync();
base.OnShown(e);
}
private void Worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
OnProgressChanged(e.ProgressPercentage, (Action) e.UserState);
}
private void OnProgressChanged(int percentage, Action update)
{
if (percentage >= 0)
_bar.Value = percentage;
if (update != null)
update();
}
private void Worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
_bar.Value = _bar.Maximum;
var cancelled = Cancelled = e.Cancelled;
string status = null;
if ((Error = e.Error) == null)
{
if (cancelled)
{
if (CancelledStatusText.Length > 0)
status = CancelledStatusText;
}
else
{
Result = e.Result;
if (SuccessStatusText.Length > 0)
status = SuccessStatusText;
}
}
else
{
if (ErrorStatusText.Length > 0)
status = ErrorStatusText.FormatWith(e.Error);
var handler = WorkFailed;
if (handler != null)
handler(this, EventArgs.Empty);
}
if (status != null)
_status.Text = status;
if (CloseOnCompletion)
{
Close();
}
else
{
_cancelButton.Hide();
var button = new Button
{
Text = "&Close",
Location = _cancelButton.Location,
Size = _cancelButton.Size,
TabIndex = _cancelButton.TabIndex,
Anchor = _cancelButton.Anchor,
};
button.Click += delegate { Close(); };
CancelButton = button;
Controls.Add(button);
}
}
private void CancelButton_Click(object sender, EventArgs e)
{
_cancelButton.Enabled = false;
_worker.CancelAsync();
}
protected override void OnClosing(CancelEventArgs e)
{
e.Cancel = _worker.IsBusy;
base.OnClosing(e);
}
private void DetailsButton_Click(object sender, EventArgs e)
{
var swap = (string) _detailsButton.Tag;
_detailsButton.Tag = _detailsButton.Text;
_detailsButton.Text = swap;
var delta = (_detailsBox.Visible ? -1 : 1) * _detailsBox.Size.Height;
ClientSize = new Size(ClientSize.Width, ClientSize.Height + delta);
_detailsBox.Visible = !_detailsBox.Visible;
}
}
}
| |
using System;
using System.ComponentModel;
using System.Collections;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters;
using log4net.Appender;
using log4net.Core;
using Log2Console.Log;
namespace Log2Console.Receiver
{
[Serializable]
[DisplayName(".NET Remoting")]
public class RemotingReceiver : BaseReceiver, RemotingAppender.IRemoteLoggingSink, ISerializable
{
private const string RemotingReceiverChannelName = "RemotingReceiverChannel";
[NonSerialized]
private IChannel _channel = null;
private string _sinkName = "LoggingSink";
private int _port = 7070;
private bool _appendHostNameToLogger = true;
[Category("Configuration")]
[DisplayName("Remote Sink Name")]
public string SinkName
{
get { return _sinkName; }
set { _sinkName = value; }
}
[Category("Configuration")]
[DisplayName("Remote TCP Port Number")]
public int Port
{
get { return _port; }
set { _port = value; }
}
[Category("Behavior")]
[DisplayName("Append Host Name to Logger")]
[Description("Append the remote Host Name to the Logger Name.")]
public bool AppendHostNameToLogger
{
get { return _appendHostNameToLogger; }
set { _appendHostNameToLogger = value; }
}
/// <summary>
/// Default ctor
/// </summary>
public RemotingReceiver() { }
#region ISerializable Members
/// <summary>
/// Constructor for Serialization
/// N.B: Explicit implementation of ISerializable to mask SecurityIdentity Property of mother class
/// </summary>
public RemotingReceiver(SerializationInfo info, StreamingContext context)
{
_sinkName = info.GetString("SinkName");
_port = info.GetInt32("Port");
}
/// <summary>
/// ISerializable method override for deserialization
/// N.B: Explicit implementation of ISerializable to mask SecurityIdentity Property of mother class
/// </summary>
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("SinkName", _sinkName);
info.AddValue("Port", _port);
}
#endregion
#region IReceiver Members
[Browsable(false)]
public override string SampleClientConfig
{
get
{
return
"Configuration for log4net:" + Environment.NewLine +
"<appender name=\"RemotingAppender\" type=\"log4net.Appender.RemotingAppender\" >" + Environment.NewLine +
" <!--The remoting URL to the remoting server object-->" + Environment.NewLine +
" <sink value=\"tcp://localhost:7070/LoggingSink\" />" + Environment.NewLine +
" <!--Send all events, do not discard events when the buffer is full-->" + Environment.NewLine +
" <lossy value=\"false\" />" + Environment.NewLine +
" <!--The number of events to buffer before sending-->" + Environment.NewLine +
" <bufferSize value=\"5\" />" + Environment.NewLine +
"</appender>";
}
}
public override void Initialize()
{
// Channel already open?
_channel = ChannelServices.GetChannel(RemotingReceiverChannelName);
if (_channel == null)
{
// Allow clients to receive complete Remoting exception information
if (RemotingConfiguration.CustomErrorsEnabled(true))
RemotingConfiguration.CustomErrorsMode = CustomErrorsModes.Off;
// Create TCP Channel
try
{
BinaryClientFormatterSinkProvider clientProvider = null;
BinaryServerFormatterSinkProvider serverProvider =
new BinaryServerFormatterSinkProvider();
serverProvider.TypeFilterLevel = TypeFilterLevel.Full;
IDictionary props = new Hashtable();
props["port"] = _port.ToString();
props["name"] = RemotingReceiverChannelName;
props["typeFilterLevel"] = TypeFilterLevel.Full;
_channel = new TcpChannel(props, clientProvider, serverProvider);
ChannelServices.RegisterChannel(_channel, false);
}
catch (Exception ex)
{
throw new Exception("Remoting TCP Channel Initialization failed", ex);
}
}
Type serverType = RemotingServices.GetServerTypeForUri(_sinkName);
if ((serverType == null) || (serverType != typeof(RemotingAppender.IRemoteLoggingSink)))
{
// Marshal Receiver
try
{
RemotingServices.Marshal(this, _sinkName, typeof(RemotingAppender.IRemoteLoggingSink));
}
catch (Exception ex)
{
throw new Exception("Remoting Marshal failed", ex);
}
}
}
public override void Terminate()
{
if (_channel != null)
ChannelServices.UnregisterChannel(_channel);
_channel = null;
}
#endregion
#region Override implementation of MarshalByRefObject
/// <summary>
/// Obtains a lifetime service object to control the lifetime
/// policy for this instance.
/// </summary>
/// <returns><c>null</c> to indicate that this instance should live forever.</returns>
/// <remarks>
/// <para>
/// Obtains a lifetime service object to control the lifetime
/// policy for this instance. This object should live forever
/// therefore this implementation returns <c>null</c>.
/// </para>
/// </remarks>
public override object InitializeLifetimeService()
{
return null;
}
#endregion Override implementation of MarshalByRefObject
#region Implementation of IRemoteLoggingSink
public void LogEvents(LoggingEvent[] events)
{
if ((events == null) || (events.Length == 0) || (Notifiable == null))
return;
LogMessage[] logMsgs = new LogMessage[events.Length];
for (int i = 0; i < events.Length; i++)
logMsgs[i] = CreateLogMessage(events[i]);
Notifiable.Notify(logMsgs);
}
#endregion Implementation of IRemoteLoggingSink
protected LogMessage CreateLogMessage(LoggingEvent logEvent)
{
LogMessage logMsg = new LogMessage();
if (_appendHostNameToLogger && logEvent.Properties.Contains(LoggingEvent.HostNameProperty))
{
logMsg.RootLoggerName = logEvent.Properties[LoggingEvent.HostNameProperty].ToString();
logMsg.LoggerName = String.Format("[Host: {0}].{1}", logEvent.Properties[LoggingEvent.HostNameProperty],
logEvent.LoggerName);
}
else
{
logMsg.RootLoggerName = logEvent.LoggerName;
logMsg.LoggerName = logEvent.LoggerName;
}
logMsg.ThreadName = logEvent.ThreadName;
logMsg.Message = logEvent.RenderedMessage;
logMsg.TimeStamp = logEvent.TimeStamp;
logMsg.Level = LogUtils.GetLogLevelInfo(logEvent.Level.Value);
// Per LoggingEvent.ExceptionObject, the exception object is not serialized, but the exception
// text is available through LoggingEvent.GetExceptionString
logMsg.ExceptionString = logEvent.GetExceptionString();
// Copy properties as string
foreach (DictionaryEntry entry in logEvent.Properties)
{
if ((entry.Key == null) || (entry.Value == null))
continue;
logMsg.Properties.Add(entry.Key.ToString(), entry.Value.ToString());
}
return logMsg;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace System.Collections.Immutable.Test
{
public abstract class ImmutableDictionaryBuilderTestBase : ImmutablesTestBase
{
[Fact]
public void Add()
{
var builder = this.GetBuilder<string, int>();
builder.Add("five", 5);
builder.Add(new KeyValuePair<string, int>("six", 6));
Assert.Equal(5, builder["five"]);
Assert.Equal(6, builder["six"]);
Assert.False(builder.ContainsKey("four"));
}
/// <summary>
/// Verifies that "adding" an entry to the dictionary that already exists
/// with exactly the same key and value will *not* throw an exception.
/// </summary>
/// <remarks>
/// The BCL Dictionary type would throw in this circumstance.
/// But in an immutable world, not only do we not care so much since the result is the same.
/// </remarks>
[Fact]
public void AddExactDuplicate()
{
var builder = this.GetBuilder<string, int>();
builder.Add("five", 5);
builder.Add("five", 5);
Assert.Equal(1, builder.Count);
}
[Fact]
public void AddExistingKeyWithDifferentValue()
{
var builder = this.GetBuilder<string, int>();
builder.Add("five", 5);
Assert.Throws<ArgumentException>(() => builder.Add("five", 6));
}
[Fact]
public void Indexer()
{
var builder = this.GetBuilder<string, int>();
// Set and set again.
builder["five"] = 5;
Assert.Equal(5, builder["five"]);
builder["five"] = 5;
Assert.Equal(5, builder["five"]);
// Set to a new value.
builder["five"] = 50;
Assert.Equal(50, builder["five"]);
// Retrieve an invalid value.
Assert.Throws<KeyNotFoundException>(() => builder["foo"]);
}
[Fact]
public void ContainsPair()
{
var map = this.GetEmptyImmutableDictionary<string, int>().Add("five", 5);
var builder = this.GetBuilder(map);
Assert.True(builder.Contains(new KeyValuePair<string, int>("five", 5)));
}
[Fact]
public void RemovePair()
{
var map = this.GetEmptyImmutableDictionary<string, int>().Add("five", 5).Add("six", 6);
var builder = this.GetBuilder(map);
Assert.True(builder.Remove(new KeyValuePair<string, int>("five", 5)));
Assert.False(builder.Remove(new KeyValuePair<string, int>("foo", 1)));
Assert.Equal(1, builder.Count);
Assert.Equal(6, builder["six"]);
}
[Fact]
public void RemoveKey()
{
var map = this.GetEmptyImmutableDictionary<string, int>().Add("five", 5).Add("six", 6);
var builder = this.GetBuilder(map);
builder.Remove("five");
Assert.Equal(1, builder.Count);
Assert.Equal(6, builder["six"]);
}
[Fact]
public void CopyTo()
{
var map = this.GetEmptyImmutableDictionary<string, int>().Add("five", 5);
var builder = this.GetBuilder(map);
var array = new KeyValuePair<string, int>[2]; // intentionally larger than source.
builder.CopyTo(array, 1);
Assert.Equal(new KeyValuePair<string, int>(), array[0]);
Assert.Equal(new KeyValuePair<string, int>("five", 5), array[1]);
Assert.Throws<ArgumentNullException>(() => builder.CopyTo(null, 0));
}
[Fact]
public void IsReadOnly()
{
var builder = this.GetBuilder<string, int>();
Assert.False(builder.IsReadOnly);
}
[Fact]
public void Keys()
{
var map = this.GetEmptyImmutableDictionary<string, int>().Add("five", 5).Add("six", 6);
var builder = this.GetBuilder(map);
CollectionAssertAreEquivalent(new[] { "five", "six" }, builder.Keys);
CollectionAssertAreEquivalent(new[] { "five", "six" }, ((IReadOnlyDictionary<string, int>)builder).Keys.ToArray());
}
[Fact]
public void Values()
{
var map = this.GetEmptyImmutableDictionary<string, int>().Add("five", 5).Add("six", 6);
var builder = this.GetBuilder(map);
CollectionAssertAreEquivalent(new[] { 5, 6 }, builder.Values);
CollectionAssertAreEquivalent(new[] { 5, 6 }, ((IReadOnlyDictionary<string, int>)builder).Values.ToArray());
}
[Fact]
public void TryGetValue()
{
var map = this.GetEmptyImmutableDictionary<string, int>().Add("five", 5).Add("six", 6);
var builder = this.GetBuilder(map);
int value;
Assert.True(builder.TryGetValue("five", out value) && value == 5);
Assert.True(builder.TryGetValue("six", out value) && value == 6);
Assert.False(builder.TryGetValue("four", out value));
Assert.Equal(0, value);
}
[Fact]
public void TryGetKey()
{
var builder = Empty<int>(StringComparer.OrdinalIgnoreCase)
.Add("a", 1).ToBuilder();
string actualKey;
Assert.True(TryGetKeyHelper(builder, "a", out actualKey));
Assert.Equal("a", actualKey);
Assert.True(TryGetKeyHelper(builder, "A", out actualKey));
Assert.Equal("a", actualKey);
Assert.False(TryGetKeyHelper(builder, "b", out actualKey));
Assert.Equal("b", actualKey);
}
[Fact]
public void EnumerateTest()
{
var map = this.GetEmptyImmutableDictionary<string, int>().Add("five", 5).Add("six", 6);
var builder = this.GetBuilder(map);
using (var enumerator = builder.GetEnumerator())
{
Assert.True(enumerator.MoveNext());
Assert.True(enumerator.MoveNext());
Assert.False(enumerator.MoveNext());
}
var manualEnum = builder.GetEnumerator();
Assert.Throws<InvalidOperationException>(() => manualEnum.Current);
while (manualEnum.MoveNext()) { }
Assert.False(manualEnum.MoveNext());
Assert.Throws<InvalidOperationException>(() => manualEnum.Current);
}
[Fact]
public void IDictionaryMembers()
{
var builder = this.GetBuilder<string, int>();
var dictionary = (IDictionary)builder;
dictionary.Add("a", 1);
Assert.True(dictionary.Contains("a"));
Assert.Equal(1, dictionary["a"]);
Assert.Equal(new[] { "a" }, dictionary.Keys.Cast<string>().ToArray());
Assert.Equal(new[] { 1 }, dictionary.Values.Cast<int>().ToArray());
dictionary["a"] = 2;
Assert.Equal(2, dictionary["a"]);
dictionary.Remove("a");
Assert.False(dictionary.Contains("a"));
Assert.False(dictionary.IsFixedSize);
Assert.False(dictionary.IsReadOnly);
}
[Fact]
public void IDictionaryEnumerator()
{
var builder = this.GetBuilder<string, int>();
var dictionary = (IDictionary)builder;
dictionary.Add("a", 1);
var enumerator = dictionary.GetEnumerator();
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
Assert.Throws<InvalidOperationException>(() => enumerator.Key);
Assert.Throws<InvalidOperationException>(() => enumerator.Value);
Assert.Throws<InvalidOperationException>(() => enumerator.Entry);
Assert.True(enumerator.MoveNext());
Assert.Equal(enumerator.Entry, enumerator.Current);
Assert.Equal(enumerator.Key, enumerator.Entry.Key);
Assert.Equal(enumerator.Value, enumerator.Entry.Value);
Assert.Equal("a", enumerator.Key);
Assert.Equal(1, enumerator.Value);
Assert.False(enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
Assert.Throws<InvalidOperationException>(() => enumerator.Key);
Assert.Throws<InvalidOperationException>(() => enumerator.Value);
Assert.Throws<InvalidOperationException>(() => enumerator.Entry);
Assert.False(enumerator.MoveNext());
enumerator.Reset();
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
Assert.Throws<InvalidOperationException>(() => enumerator.Key);
Assert.Throws<InvalidOperationException>(() => enumerator.Value);
Assert.Throws<InvalidOperationException>(() => enumerator.Entry);
Assert.True(enumerator.MoveNext());
Assert.Equal(enumerator.Key, ((DictionaryEntry)enumerator.Current).Key);
Assert.Equal(enumerator.Value, ((DictionaryEntry)enumerator.Current).Value);
Assert.Equal("a", enumerator.Key);
Assert.Equal(1, enumerator.Value);
Assert.False(enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
Assert.Throws<InvalidOperationException>(() => enumerator.Key);
Assert.Throws<InvalidOperationException>(() => enumerator.Value);
Assert.Throws<InvalidOperationException>(() => enumerator.Entry);
Assert.False(enumerator.MoveNext());
}
[Fact]
public void ICollectionMembers()
{
var builder = this.GetBuilder<string, int>();
var collection = (ICollection)builder;
collection.CopyTo(new object[0], 0);
builder.Add("b", 2);
Assert.True(builder.ContainsKey("b"));
var array = new object[builder.Count + 1];
collection.CopyTo(array, 1);
Assert.Null(array[0]);
Assert.Equal(new object[] { null, new DictionaryEntry("b", 2), }, array);
Assert.False(collection.IsSynchronized);
Assert.NotNull(collection.SyncRoot);
Assert.Same(collection.SyncRoot, collection.SyncRoot);
}
protected abstract bool TryGetKeyHelper<TKey, TValue>(IDictionary<TKey, TValue> dictionary, TKey equalKey, out TKey actualKey);
/// <summary>
/// Gets the Builder for a given dictionary instance.
/// </summary>
/// <typeparam name="TKey">The type of key.</typeparam>
/// <typeparam name="TValue">The type of value.</typeparam>
/// <returns>The builder.</returns>
protected abstract IDictionary<TKey, TValue> GetBuilder<TKey, TValue>(IImmutableDictionary<TKey, TValue> basis = null);
/// <summary>
/// Gets an empty immutable dictionary.
/// </summary>
/// <typeparam name="TKey">The type of key.</typeparam>
/// <typeparam name="TValue">The type of value.</typeparam>
/// <returns>The immutable dictionary.</returns>
protected abstract IImmutableDictionary<TKey, TValue> GetEmptyImmutableDictionary<TKey, TValue>();
protected abstract IImmutableDictionary<string, TValue> Empty<TValue>(StringComparer comparer);
}
}
| |
using System;
using System.Globalization;
using System.Text;
namespace Org.BouncyCastle.Asn1
{
/**
* Generalized time object.
*/
public class DerGeneralizedTime
: Asn1Object
{
private readonly string time;
/**
* return a generalized time from the passed in object
*
* @exception ArgumentException if the object cannot be converted.
*/
public static DerGeneralizedTime GetInstance(
object obj)
{
if (obj == null || obj is DerGeneralizedTime)
{
return (DerGeneralizedTime)obj;
}
if (obj is Asn1OctetString)
{
return new DerGeneralizedTime(((Asn1OctetString)obj).GetOctets());
}
throw new ArgumentException("illegal object in GetInstance: " + obj.GetType().Name, "obj");
}
/**
* return a Generalized Time object from a tagged object.
*
* @param obj the tagged object holding the object we want
* @param explicitly true if the object is meant to be explicitly
* tagged false otherwise.
* @exception ArgumentException if the tagged object cannot
* be converted.
*/
public static DerGeneralizedTime GetInstance(
Asn1TaggedObject obj,
bool explicitly)
{
return GetInstance(obj.GetObject());
}
/**
* The correct format for this is YYYYMMDDHHMMSS[.f]Z, or without the Z
* for local time, or Z+-HHMM on the end, for difference between local
* time and UTC time. The fractional second amount f must consist of at
* least one number with trailing zeroes removed.
*
* @param time the time string.
* @exception ArgumentException if string is an illegal format.
*/
public DerGeneralizedTime(
string time)
{
this.time = time;
try
{
ToDateTime();
}
catch (FormatException e)
{
throw new ArgumentException("invalid date string: " + e.Message);
}
}
/**
* base constructor from a local time object
*/
public DerGeneralizedTime(
DateTime time)
{
this.time = time.ToString(@"yyyyMMddHHmmss\Z");
}
internal DerGeneralizedTime(
byte[] bytes)
{
//
// explicitly convert to characters
//
this.time = Encoding.ASCII.GetString(bytes, 0, bytes.Length);
}
/**
* Return the time.
* @return The time string as it appeared in the encoded object.
*/
public string TimeString
{
get { return time; }
}
/**
* return the time - always in the form of
* YYYYMMDDhhmmssGMT(+hh:mm|-hh:mm).
* <p>
* Normally in a certificate we would expect "Z" rather than "GMT",
* however adding the "GMT" means we can just use:
* <pre>
* dateF = new SimpleDateFormat("yyyyMMddHHmmssz");
* </pre>
* To read in the time and Get a date which is compatible with our local
* time zone.</p>
*/
public string GetTime()
{
//
// standardise the format.
//
if (time[time.Length - 1] == 'Z')
{
return time.Substring(0, time.Length - 1) + "GMT+00:00";
}
else
{
int signPos = time.Length - 5;
char sign = time[signPos];
if (sign == '-' || sign == '+')
{
return time.Substring(0, signPos)
+ "GMT"
+ time.Substring(signPos, 3)
+ ":"
+ time.Substring(signPos + 3);
}
else
{
signPos = time.Length - 3;
sign = time[signPos];
if (sign == '-' || sign == '+')
{
return time.Substring(0, signPos)
+ "GMT"
+ time.Substring(signPos)
+ ":00";
}
}
}
return time + CalculateGmtOffset();
}
private string CalculateGmtOffset()
{
char sign = '+';
// Note: GetUtcOffset incorporates Daylight Savings offset
int minutes = TimeZone.CurrentTimeZone.GetUtcOffset(ToDateTime()).Minutes;
if (minutes < 0)
{
sign = '-';
minutes = -minutes;
}
int hours = minutes / 60;
minutes %= 60;
return "GMT" + sign + Convert(hours) + ":" + Convert(minutes);
}
private static string Convert(
int time)
{
if (time < 10)
{
return "0" + time;
}
return time.ToString();
}
public DateTime ToDateTime()
{
string formatStr;
string d = time;
bool makeUniversal = false;
if (d.EndsWith("Z"))
{
if (HasFractionalSeconds)
{
int fCount = d.Length - d.IndexOf('.') - 2;
formatStr = @"yyyyMMddHHmmss." + FString(fCount) + @"\Z";
}
else
{
formatStr = @"yyyyMMddHHmmss\Z";
}
}
else if (time.IndexOf('-') > 0 || time.IndexOf('+') > 0)
{
d = GetTime();
makeUniversal = true;
if (HasFractionalSeconds)
{
int fCount = d.IndexOf("GMT") - 1 - d.IndexOf('.');
formatStr = @"yyyyMMddHHmmss." + FString(fCount) + @"'GMT'zzz";
}
else
{
formatStr = @"yyyyMMddHHmmss'GMT'zzz";
}
}
else
{
if (HasFractionalSeconds)
{
int fCount = d.Length - 1 - d.IndexOf('.');
formatStr = @"yyyyMMddHHmmss." + FString(fCount);
}
else
{
formatStr = @"yyyyMMddHHmmss";
}
// TODO?
// dateF.setTimeZone(new SimpleTimeZone(0, TimeZone.getDefault().getID()));
}
return ParseDateString(d, formatStr, makeUniversal);
}
private string FString(
int count)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < count; ++i)
{
sb.Append('f');
}
return sb.ToString();
}
private DateTime ParseDateString(
string dateStr,
string formatStr,
bool makeUniversal)
{
DateTime dt = DateTime.ParseExact(
dateStr,
formatStr,
DateTimeFormatInfo.InvariantInfo);
return makeUniversal ? dt.ToUniversalTime() : dt;
}
private bool HasFractionalSeconds
{
get { return time.IndexOf('.') == 14; }
}
private byte[] GetOctets()
{
return Encoding.ASCII.GetBytes(time);
}
internal override void Encode(
DerOutputStream derOut)
{
derOut.WriteEncoded(Asn1Tags.GeneralizedTime, GetOctets());
}
protected override bool Asn1Equals(
Asn1Object asn1Object)
{
DerGeneralizedTime other = asn1Object as DerGeneralizedTime;
if (other == null)
return false;
return this.time.Equals(other.time);
}
protected override int Asn1GetHashCode()
{
return time.GetHashCode();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json.Linq;
using OrchardCore.ContentManagement;
using OrchardCore.ContentManagement.Metadata;
using OrchardCore.DisplayManagement;
using OrchardCore.DisplayManagement.Descriptors;
using OrchardCore.Mvc.Utilities;
using OrchardCore.Taxonomies.Models;
namespace OrchardCore.Taxonomies
{
public class TermShapes : IShapeTableProvider
{
public void Discover(ShapeTableBuilder builder)
{
// Add standard alternates to a TermPart because it is rendered by a content display driver not a part display driver
builder.Describe("TermPart")
.OnDisplaying(context =>
{
dynamic shape = context.Shape;
var contentType = shape.ContentItem.ContentType;
var displayTypes = new[] { "", "_" + context.Shape.Metadata.DisplayType };
// [ShapeType]_[DisplayType], e.g. TermPart.Summary, TermPart.Detail
context.Shape.Metadata.Alternates.Add($"TermPart_{context.Shape.Metadata.DisplayType}");
foreach (var displayType in displayTypes)
{
// [ContentType]_[DisplayType]__[PartType], e.g. Category-TermPart, Category-TermPart.Detail
context.Shape.Metadata.Alternates.Add($"{contentType}{displayType}__TermPart");
}
});
builder.Describe("Term")
.OnProcessing(async context =>
{
dynamic termShape = context.Shape;
string identifier = termShape.TaxonomyContentItemId ?? termShape.Alias;
if (String.IsNullOrEmpty(identifier))
{
return;
}
termShape.Classes.Add("term");
// Term population is executed when processing the shape so that its value
// can be cached. IShapeDisplayEvents is called before the ShapeDescriptor
// events and thus this code can be cached.
var shapeFactory = context.ServiceProvider.GetRequiredService<IShapeFactory>();
var contentManager = context.ServiceProvider.GetRequiredService<IContentManager>();
var aliasManager = context.ServiceProvider.GetRequiredService<IContentAliasManager>();
var orchardHelper = context.ServiceProvider.GetRequiredService<IOrchardHelper>();
var contentDefinitionManager = context.ServiceProvider.GetRequiredService<IContentDefinitionManager>();
string taxonomyContentItemId = termShape.Alias != null
? await aliasManager.GetContentItemIdAsync(termShape.Alias)
: termShape.TaxonomyContentItemId;
if (taxonomyContentItemId == null)
{
return;
}
var taxonomyContentItem = await contentManager.GetAsync(taxonomyContentItemId);
if (taxonomyContentItem == null)
{
return;
}
termShape.TaxonomyContentItem = taxonomyContentItem;
termShape.TaxonomyName = taxonomyContentItem.DisplayText;
var taxonomyPart = taxonomyContentItem.As<TaxonomyPart>();
if (taxonomyPart == null)
{
return;
}
// When a TermContentItemId is provided render the term and its child terms.
var level = 0;
List<ContentItem> termItems = null;
string termContentItemId = termShape.TermContentItemId;
if (!String.IsNullOrEmpty(termContentItemId))
{
level = FindTerm(taxonomyContentItem.Content.TaxonomyPart.Terms as JArray, termContentItemId, level, out var termContentItem);
if (termContentItem == null)
{
return;
}
termItems = new List<ContentItem>
{
termContentItem
};
}
else
{
termItems = taxonomyPart.Terms;
}
if (termItems == null)
{
return;
}
string differentiator = FormatName((string)termShape.TaxonomyName);
if (!String.IsNullOrEmpty(differentiator))
{
// Term__[Differentiator] e.g. Term-Categories, Term-Tags
termShape.Metadata.Alternates.Add("Term__" + differentiator);
termShape.Differentiator = differentiator;
termShape.Classes.Add(("term-" + differentiator).HtmlClassify());
}
termShape.Classes.Add(("term-" + taxonomyPart.TermContentType).HtmlClassify());
var encodedContentType = EncodeAlternateElement(taxonomyPart.TermContentType);
// Term__[ContentType] e.g. Term-Category, Term-Tag
termShape.Metadata.Alternates.Add("Term__" + encodedContentType);
// The first level of term item shapes is created.
// Each other level is created when the term item is displayed.
foreach (var termContentItem in termItems)
{
ContentItem[] childTerms = null;
if (termContentItem.Content.Terms is JArray termsArray)
{
childTerms = termsArray.ToObject<ContentItem[]>();
}
var shape = await shapeFactory.CreateAsync("TermItem", Arguments.From(new
{
Level = level,
Term = termShape,
TermContentItem = termContentItem,
Terms = childTerms ?? Array.Empty<ContentItem>(),
TaxonomyContentItem = taxonomyContentItem,
Differentiator = differentiator
}));
// Don't use Items.Add() or the collection won't be sorted
termShape.Add(shape);
}
});
builder.Describe("TermItem")
.OnDisplaying(async context =>
{
dynamic termItem = context.Shape;
var termShape = termItem.Term;
int level = termItem.Level;
ContentItem taxonomyContentItem = termItem.TaxonomyContentItem;
var taxonomyPart = taxonomyContentItem.As<TaxonomyPart>();
string differentiator = termItem.Differentiator;
var shapeFactory = context.ServiceProvider.GetRequiredService<IShapeFactory>();
if (termItem.Terms != null)
{
foreach (var termContentItem in termItem.Terms)
{
ContentItem[] childTerms = null;
if (termContentItem.Content.Terms is JArray termsArray)
{
childTerms = termsArray.ToObject<ContentItem[]>();
}
var shape = await shapeFactory.CreateAsync("TermItem", Arguments.From(new
{
Level = level + 1,
TaxonomyContentItem = taxonomyContentItem,
Differentiator = differentiator,
TermContentItem = termContentItem,
Term = termShape,
Terms = childTerms ?? Array.Empty<ContentItem>()
}));
// Don't use Items.Add() or the collection won't be sorted
termItem.Add(shape);
}
}
var encodedContentType = EncodeAlternateElement(taxonomyPart.TermContentType);
// TermItem__level__[level] e.g. TermItem-level-2
termItem.Metadata.Alternates.Add("TermItem__level__" + level);
// TermItem__[ContentType] e.g. TermItem-Category
// TermItem__[ContentType]__level__[level] e.g. TermItem-Category-level-2
termItem.Metadata.Alternates.Add("TermItem__" + encodedContentType);
termItem.Metadata.Alternates.Add("TermItem__" + encodedContentType + "__level__" + level);
if (!String.IsNullOrEmpty(differentiator))
{
// TermItem__[Differentiator] e.g. TermItem-Categories, TermItem-Travel
// TermItem__[Differentiator]__level__[level] e.g. TermItem-Categories-level-2
termItem.Metadata.Alternates.Add("TermItem__" + differentiator);
termItem.Metadata.Alternates.Add("TermItem__" + differentiator + "__level__" + level);
// TermItem__[Differentiator]__[ContentType] e.g. TermItem-Categories-Category
// TermItem__[Differentiator]__[ContentType]__level__[level] e.g. TermItem-Categories-Category-level-2
termItem.Metadata.Alternates.Add("TermItem__" + differentiator + "__" + encodedContentType);
termItem.Metadata.Alternates.Add("TermItem__" + differentiator + "__" + encodedContentType + "__level__" + level);
}
});
builder.Describe("TermContentItem")
.OnDisplaying(displaying =>
{
dynamic termItem = displaying.Shape;
int level = termItem.Level;
string differentiator = termItem.Differentiator;
ContentItem termContentItem = termItem.TermContentItem;
var encodedContentType = EncodeAlternateElement(termContentItem.ContentItem.ContentType);
termItem.Metadata.Alternates.Add("TermContentItem__level__" + level);
// TermContentItem__[ContentType] e.g. TermContentItem-Category
// TermContentItem__[ContentType]__level__[level] e.g. TermContentItem-Category-level-2
termItem.Metadata.Alternates.Add("TermContentItem__" + encodedContentType);
termItem.Metadata.Alternates.Add("TermContentItem__" + encodedContentType + "__level__" + level);
if (!String.IsNullOrEmpty(differentiator))
{
// TermContentItem__[Differentiator] e.g. TermContentItem-Categories
termItem.Metadata.Alternates.Add("TermContentItem__" + differentiator);
// TermContentItem__[Differentiator]__level__[level] e.g. TermContentItem-Categories-level-2
termItem.Metadata.Alternates.Add("TermContentItem__" + differentiator + "__level__" + level);
// TermContentItem__[Differentiator]__[ContentType] e.g. TermContentItem-Categories-Category
// TermContentItem__[Differentiator]__[ContentType] e.g. TermContentItem-Categories-Category-level-2
termItem.Metadata.Alternates.Add("TermContentItem__" + differentiator + "__" + encodedContentType);
termItem.Metadata.Alternates.Add("TermContentItem__" + differentiator + "__" + encodedContentType + "__level__" + level);
}
});
}
private int FindTerm(JArray termsArray, string termContentItemId, int level, out ContentItem contentItem)
{
foreach (JObject term in termsArray)
{
var contentItemId = term.GetValue("ContentItemId").ToString();
if (contentItemId == termContentItemId)
{
contentItem = term.ToObject<ContentItem>();
return level;
}
if (term.GetValue("Terms") is JArray children)
{
level += 1;
level = FindTerm(children, termContentItemId, level, out var foundContentItem);
if (foundContentItem != null)
{
contentItem = foundContentItem;
return level;
}
}
}
contentItem = null;
return level;
}
/// <summary>
/// Encodes dashed and dots so that they don't conflict in filenames
/// </summary>
/// <param name="alternateElement"></param>
/// <returns></returns>
private string EncodeAlternateElement(string alternateElement)
{
return alternateElement.Replace("-", "__").Replace('.', '_');
}
/// <summary>
/// Converts "foo-ba r" to "FooBaR"
/// </summary>
private static string FormatName(string name)
{
if (String.IsNullOrEmpty(name))
{
return null;
}
name = name.Trim();
var nextIsUpper = true;
var result = new StringBuilder(name.Length);
for (var i = 0; i < name.Length; i++)
{
var c = name[i];
if (c == '-' || char.IsWhiteSpace(c))
{
nextIsUpper = true;
continue;
}
if (nextIsUpper)
{
result.Append(c.ToString().ToUpper());
}
else
{
result.Append(c);
}
nextIsUpper = false;
}
return result.ToString();
}
}
}
| |
// Visual Studio Shared Project
// 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.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell.Interop;
namespace Microsoft.PythonTools.Infrastructure {
sealed class TaskDialog {
private readonly IServiceProvider _provider;
private readonly List<TaskDialogButton> _buttons;
private readonly List<TaskDialogButton> _radioButtons;
public TaskDialog(IServiceProvider provider) {
_provider = provider;
_buttons = new List<TaskDialogButton>();
_radioButtons = new List<TaskDialogButton>();
UseCommandLinks = true;
}
public static TaskDialog ForException(
IServiceProvider provider,
Exception exception,
string message = null,
string issueTrackerUrl = null
) {
string suffix = string.IsNullOrEmpty(issueTrackerUrl) ?
Strings.UnexpectedError_Instruction :
Strings.UnexpectedError_InstructionWithLink;
if (string.IsNullOrEmpty(message)) {
message = suffix;
} else {
message += Environment.NewLine + Environment.NewLine + suffix;
}
var td = new TaskDialog(provider) {
MainInstruction = Strings.UnexpectedError_Title,
Content = message,
EnableHyperlinks = true,
CollapsedControlText = Strings.ShowDetails,
ExpandedControlText = Strings.HideDetails,
ExpandedInformation = "```{0}Build: {2}{0}{0}{1}{0}```".FormatUI(Environment.NewLine, exception, AssemblyVersionInfo.Version)
};
td.Buttons.Add(TaskDialogButton.Close);
if (!string.IsNullOrEmpty(issueTrackerUrl)) {
td.HyperlinkClicked += (s, e) => {
if (e.Url == "issuetracker") {
Process.Start(issueTrackerUrl);
}
};
}
return td;
}
public static void CallWithRetry(
Action<int> action,
IServiceProvider provider,
string title,
string failedText,
string expandControlText,
string retryButtonText,
string cancelButtonText,
Func<Exception, bool> canRetry = null
) {
for (int retryCount = 1; ; ++retryCount) {
try {
action(retryCount);
return;
} catch (Exception ex) {
if (ex.IsCriticalException()) {
throw;
}
if (canRetry != null && !canRetry(ex)) {
throw;
}
var td = new TaskDialog(provider) {
Title = title,
MainInstruction = failedText,
Content = ex.Message,
CollapsedControlText = expandControlText,
ExpandedControlText = expandControlText,
ExpandedInformation = ex.ToString()
};
var retry = new TaskDialogButton(retryButtonText);
td.Buttons.Add(retry);
td.Buttons.Add(new TaskDialogButton(cancelButtonText));
var button = td.ShowModal();
if (button != retry) {
throw new OperationCanceledException();
}
}
}
}
public static T CallWithRetry<T>(
Func<int, T> func,
IServiceProvider provider,
string title,
string failedText,
string expandControlText,
string retryButtonText,
string cancelButtonText,
Func<Exception, bool> canRetry = null
) {
for (int retryCount = 1; ; ++retryCount) {
try {
return func(retryCount);
} catch (Exception ex) {
if (ex.IsCriticalException()) {
throw;
}
if (canRetry != null && !canRetry(ex)) {
throw;
}
var td = new TaskDialog(provider) {
Title = title,
MainInstruction = failedText,
Content = ex.Message,
CollapsedControlText = expandControlText,
ExpandedControlText = expandControlText,
ExpandedInformation = ex.ToString()
};
var retry = new TaskDialogButton(retryButtonText);
var cancel = new TaskDialogButton(cancelButtonText);
td.Buttons.Add(retry);
td.Buttons.Add(cancel);
var button = td.ShowModal();
if (button == cancel) {
throw new OperationCanceledException();
}
}
}
}
public TaskDialogButton ShowModal() {
var config = new NativeMethods.TASKDIALOGCONFIG();
config.cbSize = (uint)Marshal.SizeOf(typeof(NativeMethods.TASKDIALOGCONFIG));
config.pButtons = IntPtr.Zero;
config.pRadioButtons = IntPtr.Zero;
var uiShell = (IVsUIShell)_provider.GetService(typeof(SVsUIShell));
if (uiShell == null) {
// We are shutting down, so return the default
return SelectedButton;
}
uiShell.GetDialogOwnerHwnd(out config.hwndParent);
uiShell.EnableModeless(0);
var customButtons = new List<TaskDialogButton>();
config.dwCommonButtons = 0;
foreach (var button in Buttons) {
var flag = GetButtonFlag(button);
if (flag != 0) {
config.dwCommonButtons |= flag;
} else {
customButtons.Add(button);
}
}
try {
if (customButtons.Any()) {
config.cButtons = (uint)customButtons.Count;
var ptr = config.pButtons = Marshal.AllocHGlobal(customButtons.Count * Marshal.SizeOf(typeof(NativeMethods.TASKDIALOG_BUTTON)));
for (int i = 0; i < customButtons.Count; ++i) {
NativeMethods.TASKDIALOG_BUTTON data;
data.nButtonID = GetButtonId(null, null, i);
if (string.IsNullOrEmpty(customButtons[i].Subtext)) {
data.pszButtonText = customButtons[i].Text;
} else {
data.pszButtonText = string.Format("{0}\n{1}", customButtons[i].Text, customButtons[i].Subtext);
}
Marshal.StructureToPtr(data, ptr + i * Marshal.SizeOf(typeof(NativeMethods.TASKDIALOG_BUTTON)), false);
}
} else {
config.cButtons = 0;
config.pButtons = IntPtr.Zero;
}
if (_buttons.Any() && SelectedButton != null) {
config.nDefaultButton = GetButtonId(SelectedButton, customButtons);
} else {
config.nDefaultButton = 0;
}
if (_radioButtons.Any()) {
config.cRadioButtons = (uint)_radioButtons.Count;
var ptr = config.pRadioButtons = Marshal.AllocHGlobal(_radioButtons.Count * Marshal.SizeOf(typeof(NativeMethods.TASKDIALOG_BUTTON)));
for (int i = 0; i < _radioButtons.Count; ++i) {
NativeMethods.TASKDIALOG_BUTTON data;
data.nButtonID = GetRadioId(null, null, i);
data.pszButtonText = _radioButtons[i].Text;
Marshal.StructureToPtr(data, ptr + i * Marshal.SizeOf(typeof(NativeMethods.TASKDIALOG_BUTTON)), false);
}
if (SelectedRadioButton != null) {
config.nDefaultRadioButton = GetRadioId(SelectedRadioButton, _radioButtons);
} else {
config.nDefaultRadioButton = 0;
}
}
config.pszWindowTitle = Title;
config.pszMainInstruction = MainInstruction;
config.pszContent = Content;
config.pszExpandedInformation = ExpandedInformation;
config.pszExpandedControlText = ExpandedControlText;
config.pszCollapsedControlText = CollapsedControlText;
config.pszFooter = Footer;
config.pszVerificationText = VerificationText;
config.pfCallback = Callback;
config.hMainIcon = (IntPtr)GetIconResource(MainIcon);
config.hFooterIcon = (IntPtr)GetIconResource(FooterIcon);
if (Width.HasValue) {
config.cxWidth = (uint)Width.Value;
} else {
config.dwFlags |= NativeMethods.TASKDIALOG_FLAGS.TDF_SIZE_TO_CONTENT;
}
if (EnableHyperlinks) {
config.dwFlags |= NativeMethods.TASKDIALOG_FLAGS.TDF_ENABLE_HYPERLINKS;
}
if (AllowCancellation) {
config.dwFlags |= NativeMethods.TASKDIALOG_FLAGS.TDF_ALLOW_DIALOG_CANCELLATION;
}
if (UseCommandLinks && config.cButtons > 0) {
config.dwFlags |= NativeMethods.TASKDIALOG_FLAGS.TDF_USE_COMMAND_LINKS;
}
if (!ShowExpandedInformationInContent) {
config.dwFlags |= NativeMethods.TASKDIALOG_FLAGS.TDF_EXPAND_FOOTER_AREA;
}
if (ExpandedByDefault) {
config.dwFlags |= NativeMethods.TASKDIALOG_FLAGS.TDF_EXPANDED_BY_DEFAULT;
}
if (SelectedVerified) {
config.dwFlags |= NativeMethods.TASKDIALOG_FLAGS.TDF_VERIFICATION_FLAG_CHECKED;
}
if (CanMinimize) {
config.dwFlags |= NativeMethods.TASKDIALOG_FLAGS.TDF_CAN_BE_MINIMIZED;
}
config.dwFlags |= NativeMethods.TASKDIALOG_FLAGS.TDF_POSITION_RELATIVE_TO_WINDOW;
int selectedButton, selectedRadioButton;
bool verified;
ErrorHandler.ThrowOnFailure(NativeMethods.TaskDialogIndirect(
ref config,
out selectedButton,
out selectedRadioButton,
out verified
));
SelectedButton = GetButton(selectedButton, customButtons);
SelectedRadioButton = GetRadio(selectedRadioButton, _radioButtons);
SelectedVerified = verified;
} finally {
uiShell.EnableModeless(1);
if (config.pButtons != IntPtr.Zero) {
for (int i = 0; i < customButtons.Count; ++i) {
Marshal.DestroyStructure(config.pButtons + i * Marshal.SizeOf(typeof(NativeMethods.TASKDIALOG_BUTTON)), typeof(NativeMethods.TASKDIALOG_BUTTON));
}
Marshal.FreeHGlobal(config.pButtons);
}
if (config.pRadioButtons != IntPtr.Zero) {
for (int i = 0; i < _radioButtons.Count; ++i) {
Marshal.DestroyStructure(config.pRadioButtons + i * Marshal.SizeOf(typeof(NativeMethods.TASKDIALOG_BUTTON)), typeof(NativeMethods.TASKDIALOG_BUTTON));
}
Marshal.FreeHGlobal(config.pRadioButtons);
}
}
return SelectedButton;
}
private int Callback(IntPtr hwnd, uint uNotification, UIntPtr wParam, IntPtr lParam, IntPtr lpRefData) {
try {
switch ((NativeMethods.TASKDIALOG_NOTIFICATION)uNotification) {
case NativeMethods.TASKDIALOG_NOTIFICATION.TDN_CREATED:
foreach (var btn in _buttons.Where(b => b.ElevationRequired)) {
NativeMethods.SendMessage(
hwnd,
(int)NativeMethods.TASKDIALOG_MESSAGE.TDM_SET_BUTTON_ELEVATION_REQUIRED_STATE,
new IntPtr(GetButtonId(btn, _buttons)),
new IntPtr(1)
);
}
break;
case NativeMethods.TASKDIALOG_NOTIFICATION.TDN_NAVIGATED:
break;
case NativeMethods.TASKDIALOG_NOTIFICATION.TDN_BUTTON_CLICKED:
break;
case NativeMethods.TASKDIALOG_NOTIFICATION.TDN_HYPERLINK_CLICKED:
var url = Marshal.PtrToStringUni(lParam);
var hevt = HyperlinkClicked;
if (hevt != null) {
hevt(this, new TaskDialogHyperlinkClickedEventArgs(url));
} else {
Process.Start(new ProcessStartInfo { FileName = url, UseShellExecute = true });
}
break;
case NativeMethods.TASKDIALOG_NOTIFICATION.TDN_TIMER:
break;
case NativeMethods.TASKDIALOG_NOTIFICATION.TDN_DESTROYED:
break;
case NativeMethods.TASKDIALOG_NOTIFICATION.TDN_RADIO_BUTTON_CLICKED:
break;
case NativeMethods.TASKDIALOG_NOTIFICATION.TDN_DIALOG_CONSTRUCTED:
break;
case NativeMethods.TASKDIALOG_NOTIFICATION.TDN_VERIFICATION_CLICKED:
break;
case NativeMethods.TASKDIALOG_NOTIFICATION.TDN_HELP:
break;
case NativeMethods.TASKDIALOG_NOTIFICATION.TDN_EXPANDO_BUTTON_CLICKED:
break;
default:
break;
}
return VSConstants.S_OK;
} catch (Exception ex) {
if (ex.IsCriticalException()) {
throw;
}
return Marshal.GetHRForException(ex);
}
}
public string Title { get; set; }
public string MainInstruction { get; set; }
public string Content { get; set; }
public string VerificationText { get; set; }
public string ExpandedInformation { get; set; }
public string Footer { get; set; }
public bool ExpandedByDefault { get; set; }
public bool ShowExpandedInformationInContent { get; set; }
public string ExpandedControlText { get; set; }
public string CollapsedControlText { get; set; }
public int? Width { get; set; }
public bool EnableHyperlinks { get; set; }
public bool AllowCancellation { get; set; }
public bool UseCommandLinks { get; set; }
public bool CanMinimize { get; set; }
public TaskDialogIcon MainIcon { get; set; }
public TaskDialogIcon FooterIcon { get; set; }
/// <summary>
/// Raised when a hyperlink in the dialog is clicked. If no event
/// handlers are added, the default behavior is to open an external
/// browser.
/// </summary>
public event EventHandler<TaskDialogHyperlinkClickedEventArgs> HyperlinkClicked;
public List<TaskDialogButton> Buttons {
get {
return _buttons;
}
}
public List<TaskDialogButton> RadioButtons {
get {
return _radioButtons;
}
}
public TaskDialogButton SelectedButton { get; set; }
public TaskDialogButton SelectedRadioButton { get; set; }
public bool SelectedVerified { get; set; }
private static NativeMethods.TASKDIALOG_COMMON_BUTTON_FLAGS GetButtonFlag(TaskDialogButton button) {
if (button == TaskDialogButton.OK) {
return NativeMethods.TASKDIALOG_COMMON_BUTTON_FLAGS.TDCBF_OK_BUTTON;
} else if (button == TaskDialogButton.Cancel) {
return NativeMethods.TASKDIALOG_COMMON_BUTTON_FLAGS.TDCBF_CANCEL_BUTTON;
} else if (button == TaskDialogButton.Yes) {
return NativeMethods.TASKDIALOG_COMMON_BUTTON_FLAGS.TDCBF_YES_BUTTON;
} else if (button == TaskDialogButton.No) {
return NativeMethods.TASKDIALOG_COMMON_BUTTON_FLAGS.TDCBF_NO_BUTTON;
} else if (button == TaskDialogButton.Retry) {
return NativeMethods.TASKDIALOG_COMMON_BUTTON_FLAGS.TDCBF_RETRY_BUTTON;
} else if (button == TaskDialogButton.Close) {
return NativeMethods.TASKDIALOG_COMMON_BUTTON_FLAGS.TDCBF_CLOSE_BUTTON;
} else {
return 0;
}
}
private static NativeMethods.TASKDIALOG_ICON GetIconResource(TaskDialogIcon icon) {
switch (icon) {
case TaskDialogIcon.None:
return 0;
case TaskDialogIcon.Error:
return NativeMethods.TASKDIALOG_ICON.TD_ERROR_ICON;
case TaskDialogIcon.Warning:
return NativeMethods.TASKDIALOG_ICON.TD_WARNING_ICON;
case TaskDialogIcon.Information:
return NativeMethods.TASKDIALOG_ICON.TD_INFORMATION_ICON;
case TaskDialogIcon.Shield:
return NativeMethods.TASKDIALOG_ICON.TD_SHIELD_ICON;
default:
throw new ArgumentException("Invalid TaskDialogIcon value", "icon");
}
}
private static int GetButtonId(
TaskDialogButton button,
IList<TaskDialogButton> customButtons = null,
int indexHint = -1
) {
if (indexHint >= 0) {
return indexHint + 1000;
}
if (button == TaskDialogButton.OK) {
return NativeMethods.IDOK;
} else if (button == TaskDialogButton.Cancel) {
return NativeMethods.IDCANCEL;
} else if (button == TaskDialogButton.Yes) {
return NativeMethods.IDYES;
} else if (button == TaskDialogButton.No) {
return NativeMethods.IDNO;
} else if (button == TaskDialogButton.Retry) {
return NativeMethods.IDRETRY;
} else if (button == TaskDialogButton.Close) {
return NativeMethods.IDCLOSE;
} else if (customButtons != null) {
int i = customButtons.IndexOf(button);
if (i >= 0) {
return i + 1000;
}
}
return -1;
}
private static TaskDialogButton GetButton(int id, IList<TaskDialogButton> customButtons = null) {
switch (id) {
case NativeMethods.IDOK:
return TaskDialogButton.OK;
case NativeMethods.IDCANCEL:
return TaskDialogButton.Cancel;
case NativeMethods.IDYES:
return TaskDialogButton.Yes;
case NativeMethods.IDNO:
return TaskDialogButton.No;
case NativeMethods.IDRETRY:
return TaskDialogButton.Retry;
case NativeMethods.IDCLOSE:
return TaskDialogButton.Close;
}
if (customButtons != null && id >= 1000 && id - 1000 < customButtons.Count) {
return customButtons[id - 1000];
}
return null;
}
private static int GetRadioId(
TaskDialogButton button,
IList<TaskDialogButton> buttons,
int indexHint = -1
) {
if (indexHint >= 0) {
return indexHint + 2000;
}
return buttons.IndexOf(button) + 2000;
}
private static TaskDialogButton GetRadio(int id, IList<TaskDialogButton> buttons) {
if (id >= 2000 && id - 2000 < buttons.Count) {
return buttons[id - 2000];
}
return null;
}
private static class NativeMethods {
internal const int IDOK = 1;
internal const int IDCANCEL = 2;
internal const int IDABORT = 3;
internal const int IDRETRY = 4;
internal const int IDIGNORE = 5;
internal const int IDYES = 6;
internal const int IDNO = 7;
internal const int IDCLOSE = 8;
internal enum TASKDIALOG_FLAGS {
TDF_ENABLE_HYPERLINKS = 0x0001,
TDF_USE_HICON_MAIN = 0x0002,
TDF_USE_HICON_FOOTER = 0x0004,
TDF_ALLOW_DIALOG_CANCELLATION = 0x0008,
TDF_USE_COMMAND_LINKS = 0x0010,
TDF_USE_COMMAND_LINKS_NO_ICON = 0x0020,
TDF_EXPAND_FOOTER_AREA = 0x0040,
TDF_EXPANDED_BY_DEFAULT = 0x0080,
TDF_VERIFICATION_FLAG_CHECKED = 0x0100,
TDF_SHOW_PROGRESS_BAR = 0x0200,
TDF_SHOW_MARQUEE_PROGRESS_BAR = 0x0400,
TDF_CALLBACK_TIMER = 0x0800,
TDF_POSITION_RELATIVE_TO_WINDOW = 0x1000,
TDF_RTL_LAYOUT = 0x2000,
TDF_NO_DEFAULT_RADIO_BUTTON = 0x4000,
TDF_CAN_BE_MINIMIZED = 0x8000,
TDF_SIZE_TO_CONTENT = 0x01000000
}
internal enum TASKDIALOG_COMMON_BUTTON_FLAGS {
TDCBF_OK_BUTTON = 0x0001,
TDCBF_YES_BUTTON = 0x0002,
TDCBF_NO_BUTTON = 0x0004,
TDCBF_CANCEL_BUTTON = 0x0008,
TDCBF_RETRY_BUTTON = 0x0010,
TDCBF_CLOSE_BUTTON = 0x0020
}
internal enum TASKDIALOG_NOTIFICATION : uint {
TDN_CREATED = 0,
TDN_NAVIGATED = 1,
TDN_BUTTON_CLICKED = 2, // wParam = Button ID
TDN_HYPERLINK_CLICKED = 3, // lParam = (LPCWSTR)pszHREF
TDN_TIMER = 4, // wParam = Milliseconds since dialog created or timer reset
TDN_DESTROYED = 5,
TDN_RADIO_BUTTON_CLICKED = 6, // wParam = Radio Button ID
TDN_DIALOG_CONSTRUCTED = 7,
TDN_VERIFICATION_CLICKED = 8, // wParam = 1 if checkbox checked, 0 if not, lParam is unused and always 0
TDN_HELP = 9,
TDN_EXPANDO_BUTTON_CLICKED = 10 // wParam = 0 (dialog is now collapsed), wParam != 0 (dialog is now expanded)
};
internal enum TASKDIALOG_ICON : ushort {
TD_WARNING_ICON = unchecked((ushort)-1),
TD_ERROR_ICON = unchecked((ushort)-2),
TD_INFORMATION_ICON = unchecked((ushort)-3),
TD_SHIELD_ICON = unchecked((ushort)-4)
}
const int WM_USER = 0x0400;
internal enum TASKDIALOG_MESSAGE : int {
TDM_NAVIGATE_PAGE = WM_USER + 101,
TDM_CLICK_BUTTON = WM_USER + 102, // wParam = Button ID
TDM_SET_MARQUEE_PROGRESS_BAR = WM_USER + 103, // wParam = 0 (nonMarque) wParam != 0 (Marquee)
TDM_SET_PROGRESS_BAR_STATE = WM_USER + 104, // wParam = new progress state
TDM_SET_PROGRESS_BAR_RANGE = WM_USER + 105, // lParam = MAKELPARAM(nMinRange, nMaxRange)
TDM_SET_PROGRESS_BAR_POS = WM_USER + 106, // wParam = new position
TDM_SET_PROGRESS_BAR_MARQUEE = WM_USER + 107, // wParam = 0 (stop marquee), wParam != 0 (start marquee), lparam = speed (milliseconds between repaints)
TDM_SET_ELEMENT_TEXT = WM_USER + 108, // wParam = element (TASKDIALOG_ELEMENTS), lParam = new element text (LPCWSTR)
TDM_CLICK_RADIO_BUTTON = WM_USER + 110, // wParam = Radio Button ID
TDM_ENABLE_BUTTON = WM_USER + 111, // lParam = 0 (disable), lParam != 0 (enable), wParam = Button ID
TDM_ENABLE_RADIO_BUTTON = WM_USER + 112, // lParam = 0 (disable), lParam != 0 (enable), wParam = Radio Button ID
TDM_CLICK_VERIFICATION = WM_USER + 113, // wParam = 0 (unchecked), 1 (checked), lParam = 1 (set key focus)
TDM_UPDATE_ELEMENT_TEXT = WM_USER + 114, // wParam = element (TASKDIALOG_ELEMENTS), lParam = new element text (LPCWSTR)
TDM_SET_BUTTON_ELEVATION_REQUIRED_STATE = WM_USER + 115, // wParam = Button ID, lParam = 0 (elevation not required), lParam != 0 (elevation required)
TDM_UPDATE_ICON = WM_USER + 116 // wParam = icon element (TASKDIALOG_ICON_ELEMENTS), lParam = new icon (hIcon if TDF_USE_HICON_* was set, PCWSTR otherwise)
}
[SuppressMessage("Microsoft.Interoperability", "CA1400:PInvokeEntryPointsShouldExist",
Justification = "Entry point exists but CA can't find it")]
[DllImport("comctl32.dll", SetLastError = true)]
internal static extern int TaskDialogIndirect(
ref TASKDIALOGCONFIG pTaskConfig,
out int pnButton,
out int pnRadioButton,
[MarshalAs(UnmanagedType.Bool)] out bool pfverificationFlagChecked);
internal delegate int PFTASKDIALOGCALLBACK(IntPtr hwnd, uint uNotification, UIntPtr wParam, IntPtr lParam, IntPtr lpRefData);
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal struct TASKDIALOG_BUTTON {
public int nButtonID;
[MarshalAs(UnmanagedType.LPWStr)]
public string pszButtonText;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal struct TASKDIALOGCONFIG {
public uint cbSize;
public IntPtr hwndParent;
public IntPtr hInstance;
public TASKDIALOG_FLAGS dwFlags;
public TASKDIALOG_COMMON_BUTTON_FLAGS dwCommonButtons;
[MarshalAs(UnmanagedType.LPWStr)]
public string pszWindowTitle;
public IntPtr hMainIcon;
[MarshalAs(UnmanagedType.LPWStr)]
public string pszMainInstruction;
[MarshalAs(UnmanagedType.LPWStr)]
public string pszContent;
public uint cButtons;
public IntPtr pButtons;
public int nDefaultButton;
public uint cRadioButtons;
public IntPtr pRadioButtons;
public int nDefaultRadioButton;
[MarshalAs(UnmanagedType.LPWStr)]
public string pszVerificationText;
[MarshalAs(UnmanagedType.LPWStr)]
public string pszExpandedInformation;
[MarshalAs(UnmanagedType.LPWStr)]
public string pszExpandedControlText;
[MarshalAs(UnmanagedType.LPWStr)]
public string pszCollapsedControlText;
public IntPtr hFooterIcon;
[MarshalAs(UnmanagedType.LPWStr)]
public string pszFooter;
public PFTASKDIALOGCALLBACK pfCallback;
public IntPtr lpCallbackData;
public uint cxWidth;
}
[DllImport("user32.dll")]
internal static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);
}
}
sealed class TaskDialogButton {
public TaskDialogButton(string text) {
int i = text.IndexOfAny(Environment.NewLine.ToCharArray());
if (i < 0) {
Text = text;
} else {
Text = text.Remove(i);
Subtext = text.Substring(i).TrimStart();
}
}
public TaskDialogButton(string text, string subtext) {
Text = text;
Subtext = subtext;
}
public string Text { get; set; }
public string Subtext { get; set; }
public bool ElevationRequired { get; set; }
private TaskDialogButton() { }
public static readonly TaskDialogButton OK = new TaskDialogButton();
public static readonly TaskDialogButton Cancel = new TaskDialogButton();
public static readonly TaskDialogButton Yes = new TaskDialogButton();
public static readonly TaskDialogButton No = new TaskDialogButton();
public static readonly TaskDialogButton Retry = new TaskDialogButton();
public static readonly TaskDialogButton Close = new TaskDialogButton();
}
sealed class TaskDialogHyperlinkClickedEventArgs : EventArgs {
public TaskDialogHyperlinkClickedEventArgs(string url) {
Url = url;
}
public string Url { get; }
}
enum TaskDialogIcon {
None,
Error,
Warning,
Information,
Shield
}
}
| |
/**
* 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.
*
* Contains some contributions under the Thrift Software License.
* Please see doc/old-thrift-license.txt in the Thrift distribution for
* details.
*/
using System;
using System.Net.Sockets;
namespace Thrift.Transport
{
public class TSocket : TStreamTransport
{
private TcpClient client = null;
private string host = null;
private int port = 0;
private int timeout = 0;
public TSocket(TcpClient client)
{
this.client = client;
if (IsOpen)
{
inputStream = client.GetStream();
outputStream = client.GetStream();
}
}
public TSocket(string host, int port)
: this(host, port, 0)
{
}
public TSocket(string host, int port, int timeout)
{
this.host = host;
this.port = port;
this.timeout = timeout;
InitSocket();
}
private void InitSocket()
{
this.client = TSocketVersionizer.CreateTcpClient();
this.client.ReceiveTimeout = client.SendTimeout = timeout;
this.client.Client.NoDelay = true;
}
public int Timeout
{
set
{
client.ReceiveTimeout = client.SendTimeout = timeout = value;
}
}
public TcpClient TcpClient
{
get
{
return client;
}
}
public string Host
{
get
{
return host;
}
}
public int Port
{
get
{
return port;
}
}
public override bool IsOpen
{
get
{
if (client == null)
{
return false;
}
return client.Connected;
}
}
public override void Open()
{
if (IsOpen)
{
throw new TTransportException(TTransportException.ExceptionType.AlreadyOpen, "Socket already connected");
}
if (String.IsNullOrEmpty(host))
{
throw new TTransportException(TTransportException.ExceptionType.NotOpen, "Cannot open null host");
}
if (port <= 0)
{
throw new TTransportException(TTransportException.ExceptionType.NotOpen, "Cannot open without port");
}
if (client == null)
{
InitSocket();
}
if( timeout == 0) // no timeout -> infinite
{
client.Connect(host, port);
}
else // we have a timeout -> use it
{
ConnectHelper hlp = new ConnectHelper(client);
IAsyncResult asyncres = client.BeginConnect(host, port, new AsyncCallback(ConnectCallback), hlp);
bool bConnected = asyncres.AsyncWaitHandle.WaitOne(timeout) && client.Connected;
if (!bConnected)
{
lock (hlp.Mutex)
{
if( hlp.CallbackDone)
{
asyncres.AsyncWaitHandle.Close();
client.Close();
}
else
{
hlp.DoCleanup = true;
client = null;
}
}
throw new TTransportException(TTransportException.ExceptionType.TimedOut, "Connect timed out");
}
}
inputStream = client.GetStream();
outputStream = client.GetStream();
}
static void ConnectCallback(IAsyncResult asyncres)
{
ConnectHelper hlp = asyncres.AsyncState as ConnectHelper;
lock (hlp.Mutex)
{
hlp.CallbackDone = true;
try
{
if( hlp.Client.Client != null)
hlp.Client.EndConnect(asyncres);
}
catch (Exception)
{
// catch that away
}
if (hlp.DoCleanup)
{
try {
asyncres.AsyncWaitHandle.Close();
} catch (Exception) {}
try {
if (hlp.Client is IDisposable)
((IDisposable)hlp.Client).Dispose();
} catch (Exception) {}
hlp.Client = null;
}
}
}
private class ConnectHelper
{
public object Mutex = new object();
public bool DoCleanup = false;
public bool CallbackDone = false;
public TcpClient Client;
public ConnectHelper(TcpClient client)
{
Client = client;
}
}
public override void Close()
{
base.Close();
if (client != null)
{
client.Close();
client = null;
}
}
#region " IDisposable Support "
private bool _IsDisposed;
// IDisposable
protected override void Dispose(bool disposing)
{
if (!_IsDisposed)
{
if (disposing)
{
if (client != null)
((IDisposable)client).Dispose();
base.Dispose(disposing);
}
}
_IsDisposed = true;
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void ShiftRightLogicalInt6464()
{
var test = new SimpleUnaryOpTest__ShiftRightLogicalInt6464();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleUnaryOpTest__ShiftRightLogicalInt6464
{
private const int VectorSize = 16;
private const int Op1ElementCount = VectorSize / sizeof(Int64);
private const int RetElementCount = VectorSize / sizeof(Int64);
private static Int64[] _data = new Int64[Op1ElementCount];
private static Vector128<Int64> _clsVar;
private Vector128<Int64> _fld;
private SimpleUnaryOpTest__DataTable<Int64, Int64> _dataTable;
static SimpleUnaryOpTest__ShiftRightLogicalInt6464()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (long)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _clsVar), ref Unsafe.As<Int64, byte>(ref _data[0]), VectorSize);
}
public SimpleUnaryOpTest__ShiftRightLogicalInt6464()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (long)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _fld), ref Unsafe.As<Int64, byte>(ref _data[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (long)(random.Next(0, int.MaxValue)); }
_dataTable = new SimpleUnaryOpTest__DataTable<Int64, Int64>(_data, new Int64[RetElementCount], VectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse2.ShiftRightLogical(
Unsafe.Read<Vector128<Int64>>(_dataTable.inArrayPtr),
64
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Sse2.ShiftRightLogical(
Sse2.LoadVector128((Int64*)(_dataTable.inArrayPtr)),
64
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse2.ShiftRightLogical(
Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArrayPtr)),
64
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftRightLogical), new Type[] { typeof(Vector128<Int64>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Int64>>(_dataTable.inArrayPtr),
(byte)64
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftRightLogical), new Type[] { typeof(Vector128<Int64>), typeof(byte) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Int64*)(_dataTable.inArrayPtr)),
(byte)64
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftRightLogical), new Type[] { typeof(Vector128<Int64>), typeof(byte) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArrayPtr)),
(byte)64
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Sse2.ShiftRightLogical(
_clsVar,
64
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var firstOp = Unsafe.Read<Vector128<Int64>>(_dataTable.inArrayPtr);
var result = Sse2.ShiftRightLogical(firstOp, 64);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var firstOp = Sse2.LoadVector128((Int64*)(_dataTable.inArrayPtr));
var result = Sse2.ShiftRightLogical(firstOp, 64);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var firstOp = Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArrayPtr));
var result = Sse2.ShiftRightLogical(firstOp, 64);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleUnaryOpTest__ShiftRightLogicalInt6464();
var result = Sse2.ShiftRightLogical(test._fld, 64);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Sse2.ShiftRightLogical(_fld, 64);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<Int64> firstOp, void* result, [CallerMemberName] string method = "")
{
Int64[] inArray = new Int64[Op1ElementCount];
Int64[] outArray = new Int64[RetElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
Int64[] inArray = new Int64[Op1ElementCount];
Int64[] outArray = new Int64[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(Int64[] firstOp, Int64[] result, [CallerMemberName] string method = "")
{
if (0 != result[0])
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (0 != result[i])
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Sse2)}.{nameof(Sse2.ShiftRightLogical)}<Int64>(Vector128<Int64><9>): {method} failed:");
Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="SoapSchemaImporter.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
//------------------------------------------------------------------------------
namespace System.Xml.Serialization {
using System;
using System.Xml.Schema;
using System.Xml;
using System.Collections;
using System.ComponentModel;
using System.Reflection;
using System.Diagnostics;
using System.CodeDom.Compiler;
using System.Security.Permissions;
/// <include file='doc\SoapSchemaImporter.uex' path='docs/doc[@for="SoapSchemaImporter"]/*' />
///<internalonly/>
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public class SoapSchemaImporter : SchemaImporter {
/// <include file='doc\SoapSchemaImporter.uex' path='docs/doc[@for="SoapSchemaImporter.SoapSchemaImporter"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public SoapSchemaImporter(XmlSchemas schemas) : base(schemas, CodeGenerationOptions.GenerateProperties, null, new ImportContext()) {}
/// <include file='doc\SoapSchemaImporter.uex' path='docs/doc[@for="SoapSchemaImporter.SoapSchemaImporter1"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public SoapSchemaImporter(XmlSchemas schemas, CodeIdentifiers typeIdentifiers) : base(schemas, CodeGenerationOptions.GenerateProperties, null, new ImportContext(typeIdentifiers, false)) {}
/// <include file='doc\SoapSchemaImporter.uex' path='docs/doc[@for="SoapSchemaImporter.SoapSchemaImporter2"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public SoapSchemaImporter(XmlSchemas schemas, CodeIdentifiers typeIdentifiers, CodeGenerationOptions options) : base(schemas, options, null, new ImportContext(typeIdentifiers, false)) {}
/// <include file='doc\SoapSchemaImporter.uex' path='docs/doc[@for="SoapSchemaImporter.SoapSchemaImporter3"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public SoapSchemaImporter(XmlSchemas schemas, CodeGenerationOptions options, ImportContext context) : base(schemas, options, null, context){}
/// <include file='doc\SoapSchemaImporter.uex' path='docs/doc[@for="SoapSchemaImporter.SoapSchemaImporter4"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public SoapSchemaImporter(XmlSchemas schemas, CodeGenerationOptions options, CodeDomProvider codeProvider, ImportContext context) : base(schemas, options, codeProvider, context){}
/// <include file='doc\SoapSchemaImporter.uex' path='docs/doc[@for="SoapSchemaImporter.ImportDerivedTypeMapping"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public XmlTypeMapping ImportDerivedTypeMapping(XmlQualifiedName name, Type baseType, bool baseTypeCanBeIndirect)
{
TypeMapping mapping = ImportType(name, false);
if (mapping is StructMapping) {
MakeDerived((StructMapping)mapping, baseType, baseTypeCanBeIndirect);
}
else if (baseType != null)
throw new InvalidOperationException(Res.GetString(Res.XmlPrimitiveBaseType, name.Name, name.Namespace, baseType.FullName));
ElementAccessor accessor = new ElementAccessor();
accessor.IsSoap = true;
accessor.Name = name.Name;
accessor.Namespace = name.Namespace;
accessor.Mapping = mapping;
accessor.IsNullable = true;
accessor.Form = XmlSchemaForm.Qualified;
return new XmlTypeMapping(Scope, accessor);
}
/// <include file='doc\SoapSchemaImporter.uex' path='docs/doc[@for="SoapSchemaImporter.ImportMembersMapping"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public XmlMembersMapping ImportMembersMapping(string name, string ns, SoapSchemaMember member) {
TypeMapping typeMapping = ImportType(member.MemberType, true);
if (!(typeMapping is StructMapping)) return ImportMembersMapping(name, ns, new SoapSchemaMember[] { member });
MembersMapping mapping = new MembersMapping();
mapping.TypeDesc = Scope.GetTypeDesc(typeof(object[]));
mapping.Members = ((StructMapping)typeMapping).Members;
mapping.HasWrapperElement = true;
ElementAccessor accessor = new ElementAccessor();
accessor.IsSoap = true;
accessor.Name = name;
accessor.Namespace = typeMapping.Namespace != null ? typeMapping.Namespace : ns;
accessor.Mapping = mapping;
accessor.IsNullable = false;
accessor.Form = XmlSchemaForm.Qualified;
return new XmlMembersMapping(Scope, accessor, XmlMappingAccess.Read | XmlMappingAccess.Write);
}
/// <include file='doc\SoapSchemaImporter.uex' path='docs/doc[@for="SoapSchemaImporter.ImportMembersMapping1"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public XmlMembersMapping ImportMembersMapping(string name, string ns, SoapSchemaMember[] members) {
return ImportMembersMapping(name, ns, members, true);
}
/// <include file='doc\SoapSchemaImporter.uex' path='docs/doc[@for="SoapSchemaImporter.ImportMembersMapping2"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public XmlMembersMapping ImportMembersMapping(string name, string ns, SoapSchemaMember[] members, bool hasWrapperElement) {
return ImportMembersMapping(name, ns, members, hasWrapperElement, null, false);
}
/// <include file='doc\SoapSchemaImporter.uex' path='docs/doc[@for="SoapSchemaImporter.ImportMembersMapping3"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public XmlMembersMapping ImportMembersMapping(string name, string ns, SoapSchemaMember[] members, bool hasWrapperElement, Type baseType, bool baseTypeCanBeIndirect) {
XmlSchemaComplexType type = new XmlSchemaComplexType();
XmlSchemaSequence seq = new XmlSchemaSequence();
type.Particle = seq;
foreach (SoapSchemaMember member in members) {
XmlSchemaElement element = new XmlSchemaElement();
element.Name = member.MemberName;
element.SchemaTypeName = member.MemberType;
seq.Items.Add(element);
}
CodeIdentifiers identifiers = new CodeIdentifiers();
identifiers.UseCamelCasing = true;
MembersMapping mapping = new MembersMapping();
mapping.TypeDesc = Scope.GetTypeDesc(typeof(object[]));
mapping.Members = ImportTypeMembers(type, ns, identifiers);
mapping.HasWrapperElement = hasWrapperElement;
if (baseType != null) {
for (int i = 0; i < mapping.Members.Length; i++) {
MemberMapping member = mapping.Members[i];
if (member.Accessor.Mapping is StructMapping)
MakeDerived((StructMapping)member.Accessor.Mapping, baseType, baseTypeCanBeIndirect);
}
}
ElementAccessor accessor = new ElementAccessor();
accessor.IsSoap = true;
accessor.Name = name;
accessor.Namespace = ns;
accessor.Mapping = mapping;
accessor.IsNullable = false;
accessor.Form = XmlSchemaForm.Qualified;
return new XmlMembersMapping(Scope, accessor, XmlMappingAccess.Read | XmlMappingAccess.Write);
}
ElementAccessor ImportElement(XmlSchemaElement element, string ns) {
if (!element.RefName.IsEmpty) {
throw new InvalidOperationException(Res.GetString(Res.RefSyntaxNotSupportedForElements0, element.RefName.Name, element.RefName.Namespace));
}
if (element.Name.Length == 0) {
XmlQualifiedName parentType = XmlSchemas.GetParentName(element);
throw new InvalidOperationException(Res.GetString(Res.XmlElementHasNoName, parentType.Name, parentType.Namespace));
}
TypeMapping mapping = ImportElementType(element, ns);
ElementAccessor accessor = new ElementAccessor();
accessor.IsSoap = true;
accessor.Name = element.Name;
accessor.Namespace = ns;
accessor.Mapping = mapping;
accessor.IsNullable = element.IsNillable;
accessor.Form = XmlSchemaForm.None;
return accessor;
}
TypeMapping ImportElementType(XmlSchemaElement element, string ns) {
TypeMapping mapping;
if (!element.SchemaTypeName.IsEmpty)
mapping = ImportType(element.SchemaTypeName, false);
else if (element.SchemaType != null) {
XmlQualifiedName parentType = XmlSchemas.GetParentName(element);
if (element.SchemaType is XmlSchemaComplexType) {
mapping = ImportType((XmlSchemaComplexType)element.SchemaType, ns, false);
if (!(mapping is ArrayMapping)) {
throw new InvalidOperationException(Res.GetString(Res.XmlInvalidSchemaElementType, parentType.Name, parentType.Namespace, element.Name));
}
}
else {
throw new InvalidOperationException(Res.GetString(Res.XmlInvalidSchemaElementType, parentType.Name, parentType.Namespace, element.Name));
}
}
else if (!element.SubstitutionGroup.IsEmpty) {
XmlQualifiedName parentType = XmlSchemas.GetParentName(element);
throw new InvalidOperationException(Res.GetString(Res.XmlInvalidSubstitutionGroupUse, parentType.Name, parentType.Namespace));
}
else {
XmlQualifiedName parentType = XmlSchemas.GetParentName(element);
throw new InvalidOperationException(Res.GetString(Res.XmlElementMissingType, parentType.Name, parentType.Namespace, element.Name));
}
mapping.ReferencedByElement = true;
return mapping;
}
[PermissionSet(SecurityAction.InheritanceDemand, Name="FullTrust")]
internal override void ImportDerivedTypes(XmlQualifiedName baseName) {
foreach (XmlSchema schema in Schemas) {
if (Schemas.IsReference(schema)) continue;
if (XmlSchemas.IsDataSet(schema)) continue;
XmlSchemas.Preprocess(schema);
foreach (object item in schema.SchemaTypes.Values) {
if (item is XmlSchemaType) {
XmlSchemaType type = (XmlSchemaType)item;
if (type.DerivedFrom == baseName) {
ImportType(type.QualifiedName, false);
}
}
}
}
}
TypeMapping ImportType(XmlQualifiedName name, bool excludeFromImport) {
if (name.Name == Soap.UrType && name.Namespace == XmlSchema.Namespace)
return ImportRootMapping();
object type = FindType(name);
TypeMapping mapping = (TypeMapping)ImportedMappings[type];
if (mapping == null) {
if (type is XmlSchemaComplexType)
mapping = ImportType((XmlSchemaComplexType)type, name.Namespace, excludeFromImport);
else if (type is XmlSchemaSimpleType)
mapping = ImportDataType((XmlSchemaSimpleType)type, name.Namespace, name.Name, false);
else
throw new InvalidOperationException(Res.GetString(Res.XmlInternalError));
}
if (excludeFromImport)
mapping.IncludeInSchema = false;
return mapping;
}
TypeMapping ImportType(XmlSchemaComplexType type, string typeNs, bool excludeFromImport) {
if (type.Redefined != null) {
// we do not support redefine in the current version
throw new NotSupportedException(Res.GetString(Res.XmlUnsupportedRedefine, type.Name, typeNs));
}
TypeMapping mapping = ImportAnyType(type, typeNs);
if (mapping == null)
mapping = ImportArrayMapping(type, typeNs);
if (mapping == null)
mapping = ImportStructType(type, typeNs, excludeFromImport);
return mapping;
}
TypeMapping ImportAnyType(XmlSchemaComplexType type, string typeNs){
if (type.Particle == null)
return null;
if(!(type.Particle is XmlSchemaAll ||type.Particle is XmlSchemaSequence))
return null;
XmlSchemaGroupBase group = (XmlSchemaGroupBase) type.Particle;
if (group.Items.Count != 1 || !(group.Items[0] is XmlSchemaAny))
return null;
return ImportRootMapping();
}
StructMapping ImportStructType(XmlSchemaComplexType type, string typeNs, bool excludeFromImport) {
if (type.Name == null) {
XmlSchemaElement element = (XmlSchemaElement)type.Parent;
XmlQualifiedName parentType = XmlSchemas.GetParentName(element);
throw new InvalidOperationException(Res.GetString(Res.XmlInvalidSchemaElementType, parentType.Name, parentType.Namespace, element.Name));
}
TypeDesc baseTypeDesc = null;
Mapping baseMapping = null;
if (!type.DerivedFrom.IsEmpty) {
baseMapping = ImportType(type.DerivedFrom, excludeFromImport);
if (baseMapping is StructMapping)
baseTypeDesc = ((StructMapping)baseMapping).TypeDesc;
else
baseMapping = null;
}
if (baseMapping == null) baseMapping = GetRootMapping();
Mapping previousMapping = (Mapping)ImportedMappings[type];
if (previousMapping != null) {
return (StructMapping)previousMapping;
}
string typeName = GenerateUniqueTypeName(Accessor.UnescapeName(type.Name));
StructMapping structMapping = new StructMapping();
structMapping.IsReference = Schemas.IsReference(type);
TypeFlags flags = TypeFlags.Reference;
if (type.IsAbstract) flags |= TypeFlags.Abstract;
structMapping.TypeDesc = new TypeDesc(typeName, typeName, TypeKind.Struct, baseTypeDesc, flags);
structMapping.Namespace = typeNs;
structMapping.TypeName = type.Name;
structMapping.BaseMapping = (StructMapping)baseMapping;
ImportedMappings.Add(type, structMapping);
if (excludeFromImport)
structMapping.IncludeInSchema = false;
CodeIdentifiers members = new CodeIdentifiers();
members.AddReserved(typeName);
AddReservedIdentifiersForDataBinding(members);
structMapping.Members = ImportTypeMembers(type, typeNs, members);
Scope.AddTypeMapping(structMapping);
ImportDerivedTypes(new XmlQualifiedName(type.Name, typeNs));
return structMapping;
}
MemberMapping[] ImportTypeMembers(XmlSchemaComplexType type, string typeNs, CodeIdentifiers members) {
if (type.AnyAttribute != null) {
throw new InvalidOperationException(Res.GetString(Res.XmlInvalidAnyAttributeUse, type.Name, type.QualifiedName.Namespace));
}
XmlSchemaObjectCollection items = type.Attributes;
for (int i = 0; i < items.Count; i++) {
object item = items[i];
if (item is XmlSchemaAttributeGroup) {
throw new InvalidOperationException(Res.GetString(Res.XmlSoapInvalidAttributeUse, type.Name, type.QualifiedName.Namespace));
}
if (item is XmlSchemaAttribute) {
XmlSchemaAttribute attr = (XmlSchemaAttribute)item;
if (attr.Use != XmlSchemaUse.Prohibited) throw new InvalidOperationException(Res.GetString(Res.XmlSoapInvalidAttributeUse, type.Name, type.QualifiedName.Namespace));
}
}
if (type.Particle != null) {
ImportGroup(type.Particle, members, typeNs);
}
else if (type.ContentModel != null && type.ContentModel is XmlSchemaComplexContent) {
XmlSchemaComplexContent model = (XmlSchemaComplexContent)type.ContentModel;
if (model.Content is XmlSchemaComplexContentExtension) {
if (((XmlSchemaComplexContentExtension)model.Content).Particle != null) {
ImportGroup(((XmlSchemaComplexContentExtension)model.Content).Particle, members, typeNs);
}
}
else if (model.Content is XmlSchemaComplexContentRestriction) {
if (((XmlSchemaComplexContentRestriction)model.Content).Particle != null) {
ImportGroup(((XmlSchemaComplexContentRestriction)model.Content).Particle, members, typeNs);
}
}
}
return (MemberMapping[])members.ToArray(typeof(MemberMapping));
}
void ImportGroup(XmlSchemaParticle group, CodeIdentifiers members, string ns) {
if (group is XmlSchemaChoice) {
XmlQualifiedName parentType = XmlSchemas.GetParentName(group);
throw new InvalidOperationException(Res.GetString(Res.XmlSoapInvalidChoice, parentType.Name, parentType.Namespace));
}
else
ImportGroupMembers(group, members, ns);
}
void ImportGroupMembers(XmlSchemaParticle particle, CodeIdentifiers members, string ns) {
XmlQualifiedName parentType = XmlSchemas.GetParentName(particle);
if (particle is XmlSchemaGroupRef) {
throw new InvalidOperationException(Res.GetString(Res.XmlSoapUnsupportedGroupRef, parentType.Name, parentType.Namespace));
}
else if (particle is XmlSchemaGroupBase) {
XmlSchemaGroupBase group = (XmlSchemaGroupBase)particle;
if (group.IsMultipleOccurrence)
throw new InvalidOperationException(Res.GetString(Res.XmlSoapUnsupportedGroupRepeat, parentType.Name, parentType.Namespace));
for (int i = 0; i < group.Items.Count; i++) {
object item = group.Items[i];
if (item is XmlSchemaGroupBase || item is XmlSchemaGroupRef)
throw new InvalidOperationException(Res.GetString(Res.XmlSoapUnsupportedGroupNested, parentType.Name, parentType.Namespace));
else if (item is XmlSchemaElement)
ImportElementMember((XmlSchemaElement)item, members, ns);
else if (item is XmlSchemaAny)
throw new InvalidOperationException(Res.GetString(Res.XmlSoapUnsupportedGroupAny, parentType.Name, parentType.Namespace));
}
}
}
ElementAccessor ImportArray(XmlSchemaElement element, string ns) {
if (element.SchemaType == null) return null;
if (!element.IsMultipleOccurrence) return null;
XmlSchemaType type = element.SchemaType;
ArrayMapping arrayMapping = ImportArrayMapping(type, ns);
if (arrayMapping == null) return null;
ElementAccessor arrayAccessor = new ElementAccessor();
arrayAccessor.IsSoap = true;
arrayAccessor.Name = element.Name;
arrayAccessor.Namespace = ns;
arrayAccessor.Mapping = arrayMapping;
arrayAccessor.IsNullable = false;
arrayAccessor.Form = XmlSchemaForm.None;
return arrayAccessor;
}
ArrayMapping ImportArrayMapping(XmlSchemaType type, string ns) {
ArrayMapping arrayMapping;
if (type.Name == Soap.Array && ns == Soap.Encoding) {
arrayMapping = new ArrayMapping();
TypeMapping mapping = GetRootMapping();
ElementAccessor itemAccessor = new ElementAccessor();
itemAccessor.IsSoap = true;
itemAccessor.Name = Soap.UrType;
itemAccessor.Namespace = ns;
itemAccessor.Mapping = mapping;
itemAccessor.IsNullable = true;
itemAccessor.Form = XmlSchemaForm.None;
arrayMapping.Elements = new ElementAccessor[] { itemAccessor };
arrayMapping.TypeDesc = itemAccessor.Mapping.TypeDesc.CreateArrayTypeDesc();
arrayMapping.TypeName = "ArrayOf" + CodeIdentifier.MakePascal(itemAccessor.Mapping.TypeName);
return arrayMapping;
}
if (!(type.DerivedFrom.Name == Soap.Array && type.DerivedFrom.Namespace == Soap.Encoding)) return null;
// the type should be a XmlSchemaComplexType
XmlSchemaContentModel model = ((XmlSchemaComplexType)type).ContentModel;
// the Content should be an restriction
if (!(model.Content is XmlSchemaComplexContentRestriction)) return null;
arrayMapping = new ArrayMapping();
XmlSchemaComplexContentRestriction restriction = (XmlSchemaComplexContentRestriction)model.Content;
for (int i = 0; i < restriction.Attributes.Count; i++) {
XmlSchemaAttribute attribute = restriction.Attributes[i] as XmlSchemaAttribute;
if (attribute != null && attribute.RefName.Name == Soap.ArrayType && attribute.RefName.Namespace == Soap.Encoding) {
// read the value of the wsdl:arrayType attribute
string arrayType = null;
if (attribute.UnhandledAttributes != null) {
foreach (XmlAttribute a in attribute.UnhandledAttributes) {
if (a.LocalName == Wsdl.ArrayType && a.NamespaceURI == Wsdl.Namespace) {
arrayType = a.Value;
break;
}
}
}
if (arrayType != null) {
string dims;
XmlQualifiedName typeName = TypeScope.ParseWsdlArrayType(arrayType, out dims, attribute);
TypeMapping mapping;
TypeDesc td = Scope.GetTypeDesc(typeName.Name, typeName.Namespace);
if (td != null && td.IsPrimitive) {
mapping = new PrimitiveMapping();
mapping.TypeDesc = td;
mapping.TypeName = td.DataType.Name;
}
else {
mapping = ImportType(typeName, false);
}
ElementAccessor itemAccessor = new ElementAccessor();
itemAccessor.IsSoap = true;
itemAccessor.Name = typeName.Name;
itemAccessor.Namespace = ns;
itemAccessor.Mapping = mapping;
itemAccessor.IsNullable = true;
itemAccessor.Form = XmlSchemaForm.None;
arrayMapping.Elements = new ElementAccessor[] { itemAccessor };
arrayMapping.TypeDesc = itemAccessor.Mapping.TypeDesc.CreateArrayTypeDesc();
arrayMapping.TypeName = "ArrayOf" + CodeIdentifier.MakePascal(itemAccessor.Mapping.TypeName);
return arrayMapping;
}
}
}
XmlSchemaParticle particle = restriction.Particle;
if (particle is XmlSchemaAll || particle is XmlSchemaSequence) {
XmlSchemaGroupBase group = (XmlSchemaGroupBase)particle;
if (group.Items.Count != 1 || !(group.Items[0] is XmlSchemaElement))
return null;
XmlSchemaElement itemElement = (XmlSchemaElement)group.Items[0];
if (!itemElement.IsMultipleOccurrence) return null;
ElementAccessor itemAccessor = ImportElement(itemElement, ns);
arrayMapping.Elements = new ElementAccessor[] { itemAccessor };
arrayMapping.TypeDesc = ((TypeMapping)itemAccessor.Mapping).TypeDesc.CreateArrayTypeDesc();
}
else {
return null;
}
return arrayMapping;
}
void ImportElementMember(XmlSchemaElement element, CodeIdentifiers members, string ns) {
ElementAccessor accessor;
if ((accessor = ImportArray(element, ns)) == null) {
accessor = ImportElement(element, ns);
}
MemberMapping member = new MemberMapping();
member.Name = CodeIdentifier.MakeValid(Accessor.UnescapeName(accessor.Name));
member.Name = members.AddUnique(member.Name, member);
if (member.Name.EndsWith("Specified", StringComparison.Ordinal)) {
string name = member.Name;
member.Name = members.AddUnique(member.Name, member);
members.Remove(name);
}
member.TypeDesc = ((TypeMapping)accessor.Mapping).TypeDesc;
member.Elements = new ElementAccessor[] { accessor };
if (element.IsMultipleOccurrence)
member.TypeDesc = member.TypeDesc.CreateArrayTypeDesc();
if (element.MinOccurs == 0 && member.TypeDesc.IsValueType && !member.TypeDesc.HasIsEmpty) {
member.CheckSpecified = SpecifiedAccessor.ReadWrite;
}
}
TypeMapping ImportDataType(XmlSchemaSimpleType dataType, string typeNs, string identifier, bool isList) {
TypeMapping mapping = ImportNonXsdPrimitiveDataType(dataType, typeNs);
if (mapping != null)
return mapping;
if (dataType.Content is XmlSchemaSimpleTypeRestriction) {
XmlSchemaSimpleTypeRestriction restriction = (XmlSchemaSimpleTypeRestriction)dataType.Content;
foreach (object o in restriction.Facets) {
if (o is XmlSchemaEnumerationFacet) {
return ImportEnumeratedDataType(dataType, typeNs, identifier, isList);
}
}
}
else if (dataType.Content is XmlSchemaSimpleTypeList || dataType.Content is XmlSchemaSimpleTypeUnion) {
if (dataType.Content is XmlSchemaSimpleTypeList) {
// check if we have enumeration list
XmlSchemaSimpleTypeList list = (XmlSchemaSimpleTypeList)dataType.Content;
if (list.ItemType != null) {
mapping = ImportDataType(list.ItemType, typeNs, identifier, true);
if (mapping != null) {
return mapping;
}
}
}
mapping = new PrimitiveMapping();
mapping.TypeDesc = Scope.GetTypeDesc(typeof(string));
mapping.TypeName = mapping.TypeDesc.DataType.Name;
return mapping;
}
return ImportPrimitiveDataType(dataType);
}
TypeMapping ImportEnumeratedDataType(XmlSchemaSimpleType dataType, string typeNs, string identifier, bool isList) {
TypeMapping mapping = (TypeMapping)ImportedMappings[dataType];
if (mapping != null)
return mapping;
XmlSchemaSimpleType sourceDataType = FindDataType(dataType.DerivedFrom);
TypeDesc sourceTypeDesc = Scope.GetTypeDesc(sourceDataType);
if (sourceTypeDesc != null && sourceTypeDesc != Scope.GetTypeDesc(typeof(string)))
return ImportPrimitiveDataType(dataType);
identifier = Accessor.UnescapeName(identifier);
string typeName = GenerateUniqueTypeName(identifier);
EnumMapping enumMapping = new EnumMapping();
enumMapping.IsReference = Schemas.IsReference(dataType);
enumMapping.TypeDesc = new TypeDesc(typeName, typeName, TypeKind.Enum, null, 0);
enumMapping.TypeName = identifier;
enumMapping.Namespace = typeNs;
enumMapping.IsFlags = isList;
CodeIdentifiers constants = new CodeIdentifiers();
if (!(dataType.Content is XmlSchemaSimpleTypeRestriction))
throw new InvalidOperationException(Res.GetString(Res.XmlInvalidEnumContent, dataType.Content.GetType().Name, identifier));
XmlSchemaSimpleTypeRestriction restriction = (XmlSchemaSimpleTypeRestriction)dataType.Content;
for (int i = 0; i < restriction.Facets.Count; i++) {
object facet = restriction.Facets[i];
if (!(facet is XmlSchemaEnumerationFacet)) continue;
XmlSchemaEnumerationFacet enumeration = (XmlSchemaEnumerationFacet)facet;
ConstantMapping constant = new ConstantMapping();
string constantName = CodeIdentifier.MakeValid(enumeration.Value);
constant.Name = constants.AddUnique(constantName, constant);
constant.XmlName = enumeration.Value;
constant.Value = i;
}
enumMapping.Constants = (ConstantMapping[])constants.ToArray(typeof(ConstantMapping));
if (isList && enumMapping.Constants.Length > 63) {
// if we have 64+ flag constants we cannot map the type to long enum, we will use string mapping instead.
mapping = new PrimitiveMapping();
mapping.TypeDesc = Scope.GetTypeDesc(typeof(string));
mapping.TypeName = mapping.TypeDesc.DataType.Name;
ImportedMappings.Add(dataType, mapping);
return mapping;
}
ImportedMappings.Add(dataType, enumMapping);
Scope.AddTypeMapping(enumMapping);
return enumMapping;
}
PrimitiveMapping ImportPrimitiveDataType(XmlSchemaSimpleType dataType) {
TypeDesc sourceTypeDesc = GetDataTypeSource(dataType);
PrimitiveMapping mapping = new PrimitiveMapping();
mapping.TypeDesc = sourceTypeDesc;
mapping.TypeName = sourceTypeDesc.DataType.Name;
return mapping;
}
PrimitiveMapping ImportNonXsdPrimitiveDataType(XmlSchemaSimpleType dataType, string ns) {
PrimitiveMapping mapping = null;
TypeDesc typeDesc = null;
if (dataType.Name != null && dataType.Name.Length != 0) {
typeDesc = Scope.GetTypeDesc(dataType.Name, ns);
if (typeDesc != null) {
mapping = new PrimitiveMapping();
mapping.TypeDesc = typeDesc;
mapping.TypeName = typeDesc.DataType.Name;
}
}
return mapping;
}
TypeDesc GetDataTypeSource(XmlSchemaSimpleType dataType) {
if (dataType.Name != null && dataType.Name.Length != 0) {
TypeDesc typeDesc = Scope.GetTypeDesc(dataType);
if (typeDesc != null) return typeDesc;
}
if (!dataType.DerivedFrom.IsEmpty) {
return GetDataTypeSource(FindDataType(dataType.DerivedFrom));
}
return Scope.GetTypeDesc(typeof(string));
}
XmlSchemaSimpleType FindDataType(XmlQualifiedName name) {
TypeDesc typeDesc = Scope.GetTypeDesc(name.Name, name.Namespace);
if (typeDesc != null && typeDesc.DataType is XmlSchemaSimpleType)
return (XmlSchemaSimpleType)typeDesc.DataType;
XmlSchemaSimpleType dataType = (XmlSchemaSimpleType)Schemas.Find(name, typeof(XmlSchemaSimpleType));
if (dataType != null) {
return dataType;
}
if (name.Namespace == XmlSchema.Namespace)
return (XmlSchemaSimpleType)Scope.GetTypeDesc(typeof(string)).DataType;
else
throw new InvalidOperationException(Res.GetString(Res.XmlMissingDataType, name.ToString()));
}
object FindType(XmlQualifiedName name) {
if (name != null && name.Namespace == Soap.Encoding) {
// we have a build-in support fo the encoded types, we need to make sure that we generate the same
// object model whether http://www.w3.org/2003/05/soap-encoding schema was specified or not.
object type = Schemas.Find(name, typeof(XmlSchemaComplexType));
if (type != null) {
XmlSchemaType encType = (XmlSchemaType)type;
XmlQualifiedName baseType = encType.DerivedFrom;
if (!baseType.IsEmpty) {
return FindType(baseType);
}
return encType;
}
return FindDataType(name);
}
else {
object type = Schemas.Find(name, typeof(XmlSchemaComplexType));
if (type != null) {
return type;
}
return FindDataType(name);
}
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using gagr = Google.Api.Gax.ResourceNames;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Cloud.Talent.V4Beta1
{
/// <summary>Settings for <see cref="EventServiceClient"/> instances.</summary>
public sealed partial class EventServiceSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="EventServiceSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="EventServiceSettings"/>.</returns>
public static EventServiceSettings GetDefault() => new EventServiceSettings();
/// <summary>Constructs a new <see cref="EventServiceSettings"/> object with default settings.</summary>
public EventServiceSettings()
{
}
private EventServiceSettings(EventServiceSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
CreateClientEventSettings = existing.CreateClientEventSettings;
OnCopy(existing);
}
partial void OnCopy(EventServiceSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>EventServiceClient.CreateClientEvent</c> and <c>EventServiceClient.CreateClientEventAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>Timeout: 30 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings CreateClientEventSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(30000)));
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="EventServiceSettings"/> object.</returns>
public EventServiceSettings Clone() => new EventServiceSettings(this);
}
/// <summary>
/// Builder class for <see cref="EventServiceClient"/> to provide simple configuration of credentials, endpoint etc.
/// </summary>
public sealed partial class EventServiceClientBuilder : gaxgrpc::ClientBuilderBase<EventServiceClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public EventServiceSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public EventServiceClientBuilder()
{
UseJwtAccessWithScopes = EventServiceClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref EventServiceClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<EventServiceClient> task);
/// <summary>Builds the resulting client.</summary>
public override EventServiceClient Build()
{
EventServiceClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<EventServiceClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<EventServiceClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private EventServiceClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return EventServiceClient.Create(callInvoker, Settings);
}
private async stt::Task<EventServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return EventServiceClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => EventServiceClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => EventServiceClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => EventServiceClient.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance;
}
/// <summary>EventService client wrapper, for convenient use.</summary>
/// <remarks>
/// A service handles client event report.
/// </remarks>
public abstract partial class EventServiceClient
{
/// <summary>
/// The default endpoint for the EventService service, which is a host of "jobs.googleapis.com" and a port of
/// 443.
/// </summary>
public static string DefaultEndpoint { get; } = "jobs.googleapis.com:443";
/// <summary>The default EventService scopes.</summary>
/// <remarks>
/// The default EventService scopes are:
/// <list type="bullet">
/// <item><description>https://www.googleapis.com/auth/cloud-platform</description></item>
/// <item><description>https://www.googleapis.com/auth/jobs</description></item>
/// </list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/jobs",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="EventServiceClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="EventServiceClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="EventServiceClient"/>.</returns>
public static stt::Task<EventServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new EventServiceClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="EventServiceClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="EventServiceClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="EventServiceClient"/>.</returns>
public static EventServiceClient Create() => new EventServiceClientBuilder().Build();
/// <summary>
/// Creates a <see cref="EventServiceClient"/> which uses the specified call invoker for remote operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="EventServiceSettings"/>.</param>
/// <returns>The created <see cref="EventServiceClient"/>.</returns>
internal static EventServiceClient Create(grpccore::CallInvoker callInvoker, EventServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
EventService.EventServiceClient grpcClient = new EventService.EventServiceClient(callInvoker);
return new EventServiceClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
/// by another call to this method.
/// </remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC EventService client</summary>
public virtual EventService.EventServiceClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Report events issued when end user interacts with customer's application
/// that uses Cloud Talent Solution. You may inspect the created events in
/// [self service
/// tools](https://console.cloud.google.com/talent-solution/overview).
/// [Learn
/// more](https://cloud.google.com/talent-solution/docs/management-tools)
/// about self service tools.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual ClientEvent CreateClientEvent(CreateClientEventRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Report events issued when end user interacts with customer's application
/// that uses Cloud Talent Solution. You may inspect the created events in
/// [self service
/// tools](https://console.cloud.google.com/talent-solution/overview).
/// [Learn
/// more](https://cloud.google.com/talent-solution/docs/management-tools)
/// about self service tools.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<ClientEvent> CreateClientEventAsync(CreateClientEventRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Report events issued when end user interacts with customer's application
/// that uses Cloud Talent Solution. You may inspect the created events in
/// [self service
/// tools](https://console.cloud.google.com/talent-solution/overview).
/// [Learn
/// more](https://cloud.google.com/talent-solution/docs/management-tools)
/// about self service tools.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<ClientEvent> CreateClientEventAsync(CreateClientEventRequest request, st::CancellationToken cancellationToken) =>
CreateClientEventAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Report events issued when end user interacts with customer's application
/// that uses Cloud Talent Solution. You may inspect the created events in
/// [self service
/// tools](https://console.cloud.google.com/talent-solution/overview).
/// [Learn
/// more](https://cloud.google.com/talent-solution/docs/management-tools)
/// about self service tools.
/// </summary>
/// <param name="parent">
/// Required. Resource name of the tenant under which the event is created.
///
/// The format is "projects/{project_id}/tenants/{tenant_id}", for example,
/// "projects/foo/tenant/bar". If tenant id is unspecified, a default tenant
/// is created, for example, "projects/foo".
/// </param>
/// <param name="clientEvent">
/// Required. Events issued when end user interacts with customer's application that
/// uses Cloud Talent Solution.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual ClientEvent CreateClientEvent(string parent, ClientEvent clientEvent, gaxgrpc::CallSettings callSettings = null) =>
CreateClientEvent(new CreateClientEventRequest
{
Parent = gax::GaxPreconditions.CheckNotNullOrEmpty(parent, nameof(parent)),
ClientEvent = gax::GaxPreconditions.CheckNotNull(clientEvent, nameof(clientEvent)),
}, callSettings);
/// <summary>
/// Report events issued when end user interacts with customer's application
/// that uses Cloud Talent Solution. You may inspect the created events in
/// [self service
/// tools](https://console.cloud.google.com/talent-solution/overview).
/// [Learn
/// more](https://cloud.google.com/talent-solution/docs/management-tools)
/// about self service tools.
/// </summary>
/// <param name="parent">
/// Required. Resource name of the tenant under which the event is created.
///
/// The format is "projects/{project_id}/tenants/{tenant_id}", for example,
/// "projects/foo/tenant/bar". If tenant id is unspecified, a default tenant
/// is created, for example, "projects/foo".
/// </param>
/// <param name="clientEvent">
/// Required. Events issued when end user interacts with customer's application that
/// uses Cloud Talent Solution.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<ClientEvent> CreateClientEventAsync(string parent, ClientEvent clientEvent, gaxgrpc::CallSettings callSettings = null) =>
CreateClientEventAsync(new CreateClientEventRequest
{
Parent = gax::GaxPreconditions.CheckNotNullOrEmpty(parent, nameof(parent)),
ClientEvent = gax::GaxPreconditions.CheckNotNull(clientEvent, nameof(clientEvent)),
}, callSettings);
/// <summary>
/// Report events issued when end user interacts with customer's application
/// that uses Cloud Talent Solution. You may inspect the created events in
/// [self service
/// tools](https://console.cloud.google.com/talent-solution/overview).
/// [Learn
/// more](https://cloud.google.com/talent-solution/docs/management-tools)
/// about self service tools.
/// </summary>
/// <param name="parent">
/// Required. Resource name of the tenant under which the event is created.
///
/// The format is "projects/{project_id}/tenants/{tenant_id}", for example,
/// "projects/foo/tenant/bar". If tenant id is unspecified, a default tenant
/// is created, for example, "projects/foo".
/// </param>
/// <param name="clientEvent">
/// Required. Events issued when end user interacts with customer's application that
/// uses Cloud Talent Solution.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<ClientEvent> CreateClientEventAsync(string parent, ClientEvent clientEvent, st::CancellationToken cancellationToken) =>
CreateClientEventAsync(parent, clientEvent, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Report events issued when end user interacts with customer's application
/// that uses Cloud Talent Solution. You may inspect the created events in
/// [self service
/// tools](https://console.cloud.google.com/talent-solution/overview).
/// [Learn
/// more](https://cloud.google.com/talent-solution/docs/management-tools)
/// about self service tools.
/// </summary>
/// <param name="parent">
/// Required. Resource name of the tenant under which the event is created.
///
/// The format is "projects/{project_id}/tenants/{tenant_id}", for example,
/// "projects/foo/tenant/bar". If tenant id is unspecified, a default tenant
/// is created, for example, "projects/foo".
/// </param>
/// <param name="clientEvent">
/// Required. Events issued when end user interacts with customer's application that
/// uses Cloud Talent Solution.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual ClientEvent CreateClientEvent(TenantName parent, ClientEvent clientEvent, gaxgrpc::CallSettings callSettings = null) =>
CreateClientEvent(new CreateClientEventRequest
{
ParentAsTenantName = gax::GaxPreconditions.CheckNotNull(parent, nameof(parent)),
ClientEvent = gax::GaxPreconditions.CheckNotNull(clientEvent, nameof(clientEvent)),
}, callSettings);
/// <summary>
/// Report events issued when end user interacts with customer's application
/// that uses Cloud Talent Solution. You may inspect the created events in
/// [self service
/// tools](https://console.cloud.google.com/talent-solution/overview).
/// [Learn
/// more](https://cloud.google.com/talent-solution/docs/management-tools)
/// about self service tools.
/// </summary>
/// <param name="parent">
/// Required. Resource name of the tenant under which the event is created.
///
/// The format is "projects/{project_id}/tenants/{tenant_id}", for example,
/// "projects/foo/tenant/bar". If tenant id is unspecified, a default tenant
/// is created, for example, "projects/foo".
/// </param>
/// <param name="clientEvent">
/// Required. Events issued when end user interacts with customer's application that
/// uses Cloud Talent Solution.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<ClientEvent> CreateClientEventAsync(TenantName parent, ClientEvent clientEvent, gaxgrpc::CallSettings callSettings = null) =>
CreateClientEventAsync(new CreateClientEventRequest
{
ParentAsTenantName = gax::GaxPreconditions.CheckNotNull(parent, nameof(parent)),
ClientEvent = gax::GaxPreconditions.CheckNotNull(clientEvent, nameof(clientEvent)),
}, callSettings);
/// <summary>
/// Report events issued when end user interacts with customer's application
/// that uses Cloud Talent Solution. You may inspect the created events in
/// [self service
/// tools](https://console.cloud.google.com/talent-solution/overview).
/// [Learn
/// more](https://cloud.google.com/talent-solution/docs/management-tools)
/// about self service tools.
/// </summary>
/// <param name="parent">
/// Required. Resource name of the tenant under which the event is created.
///
/// The format is "projects/{project_id}/tenants/{tenant_id}", for example,
/// "projects/foo/tenant/bar". If tenant id is unspecified, a default tenant
/// is created, for example, "projects/foo".
/// </param>
/// <param name="clientEvent">
/// Required. Events issued when end user interacts with customer's application that
/// uses Cloud Talent Solution.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<ClientEvent> CreateClientEventAsync(TenantName parent, ClientEvent clientEvent, st::CancellationToken cancellationToken) =>
CreateClientEventAsync(parent, clientEvent, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Report events issued when end user interacts with customer's application
/// that uses Cloud Talent Solution. You may inspect the created events in
/// [self service
/// tools](https://console.cloud.google.com/talent-solution/overview).
/// [Learn
/// more](https://cloud.google.com/talent-solution/docs/management-tools)
/// about self service tools.
/// </summary>
/// <param name="parent">
/// Required. Resource name of the tenant under which the event is created.
///
/// The format is "projects/{project_id}/tenants/{tenant_id}", for example,
/// "projects/foo/tenant/bar". If tenant id is unspecified, a default tenant
/// is created, for example, "projects/foo".
/// </param>
/// <param name="clientEvent">
/// Required. Events issued when end user interacts with customer's application that
/// uses Cloud Talent Solution.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual ClientEvent CreateClientEvent(gagr::ProjectName parent, ClientEvent clientEvent, gaxgrpc::CallSettings callSettings = null) =>
CreateClientEvent(new CreateClientEventRequest
{
ParentAsProjectName = gax::GaxPreconditions.CheckNotNull(parent, nameof(parent)),
ClientEvent = gax::GaxPreconditions.CheckNotNull(clientEvent, nameof(clientEvent)),
}, callSettings);
/// <summary>
/// Report events issued when end user interacts with customer's application
/// that uses Cloud Talent Solution. You may inspect the created events in
/// [self service
/// tools](https://console.cloud.google.com/talent-solution/overview).
/// [Learn
/// more](https://cloud.google.com/talent-solution/docs/management-tools)
/// about self service tools.
/// </summary>
/// <param name="parent">
/// Required. Resource name of the tenant under which the event is created.
///
/// The format is "projects/{project_id}/tenants/{tenant_id}", for example,
/// "projects/foo/tenant/bar". If tenant id is unspecified, a default tenant
/// is created, for example, "projects/foo".
/// </param>
/// <param name="clientEvent">
/// Required. Events issued when end user interacts with customer's application that
/// uses Cloud Talent Solution.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<ClientEvent> CreateClientEventAsync(gagr::ProjectName parent, ClientEvent clientEvent, gaxgrpc::CallSettings callSettings = null) =>
CreateClientEventAsync(new CreateClientEventRequest
{
ParentAsProjectName = gax::GaxPreconditions.CheckNotNull(parent, nameof(parent)),
ClientEvent = gax::GaxPreconditions.CheckNotNull(clientEvent, nameof(clientEvent)),
}, callSettings);
/// <summary>
/// Report events issued when end user interacts with customer's application
/// that uses Cloud Talent Solution. You may inspect the created events in
/// [self service
/// tools](https://console.cloud.google.com/talent-solution/overview).
/// [Learn
/// more](https://cloud.google.com/talent-solution/docs/management-tools)
/// about self service tools.
/// </summary>
/// <param name="parent">
/// Required. Resource name of the tenant under which the event is created.
///
/// The format is "projects/{project_id}/tenants/{tenant_id}", for example,
/// "projects/foo/tenant/bar". If tenant id is unspecified, a default tenant
/// is created, for example, "projects/foo".
/// </param>
/// <param name="clientEvent">
/// Required. Events issued when end user interacts with customer's application that
/// uses Cloud Talent Solution.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<ClientEvent> CreateClientEventAsync(gagr::ProjectName parent, ClientEvent clientEvent, st::CancellationToken cancellationToken) =>
CreateClientEventAsync(parent, clientEvent, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>EventService client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// A service handles client event report.
/// </remarks>
public sealed partial class EventServiceClientImpl : EventServiceClient
{
private readonly gaxgrpc::ApiCall<CreateClientEventRequest, ClientEvent> _callCreateClientEvent;
/// <summary>
/// Constructs a client wrapper for the EventService service, with the specified gRPC client and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">The base <see cref="EventServiceSettings"/> used within this client.</param>
public EventServiceClientImpl(EventService.EventServiceClient grpcClient, EventServiceSettings settings)
{
GrpcClient = grpcClient;
EventServiceSettings effectiveSettings = settings ?? EventServiceSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callCreateClientEvent = clientHelper.BuildApiCall<CreateClientEventRequest, ClientEvent>(grpcClient.CreateClientEventAsync, grpcClient.CreateClientEvent, effectiveSettings.CreateClientEventSettings).WithGoogleRequestParam("parent", request => request.Parent);
Modify_ApiCall(ref _callCreateClientEvent);
Modify_CreateClientEventApiCall(ref _callCreateClientEvent);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_CreateClientEventApiCall(ref gaxgrpc::ApiCall<CreateClientEventRequest, ClientEvent> call);
partial void OnConstruction(EventService.EventServiceClient grpcClient, EventServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC EventService client</summary>
public override EventService.EventServiceClient GrpcClient { get; }
partial void Modify_CreateClientEventRequest(ref CreateClientEventRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Report events issued when end user interacts with customer's application
/// that uses Cloud Talent Solution. You may inspect the created events in
/// [self service
/// tools](https://console.cloud.google.com/talent-solution/overview).
/// [Learn
/// more](https://cloud.google.com/talent-solution/docs/management-tools)
/// about self service tools.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override ClientEvent CreateClientEvent(CreateClientEventRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_CreateClientEventRequest(ref request, ref callSettings);
return _callCreateClientEvent.Sync(request, callSettings);
}
/// <summary>
/// Report events issued when end user interacts with customer's application
/// that uses Cloud Talent Solution. You may inspect the created events in
/// [self service
/// tools](https://console.cloud.google.com/talent-solution/overview).
/// [Learn
/// more](https://cloud.google.com/talent-solution/docs/management-tools)
/// about self service tools.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<ClientEvent> CreateClientEventAsync(CreateClientEventRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_CreateClientEventRequest(ref request, ref callSettings);
return _callCreateClientEvent.Async(request, callSettings);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void MinByte()
{
var test = new SimpleBinaryOpTest__MinByte();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (Sse2.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (Sse2.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Sse2.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Sse2.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Sse2.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__MinByte
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Byte[] inArray1, Byte[] inArray2, Byte[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Byte>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Byte>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Byte>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Byte, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Byte, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<Byte> _fld1;
public Vector128<Byte> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__MinByte testClass)
{
var result = Sse2.Min(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__MinByte testClass)
{
fixed (Vector128<Byte>* pFld1 = &_fld1)
fixed (Vector128<Byte>* pFld2 = &_fld2)
{
var result = Sse2.Min(
Sse2.LoadVector128((Byte*)(pFld1)),
Sse2.LoadVector128((Byte*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte);
private static Byte[] _data1 = new Byte[Op1ElementCount];
private static Byte[] _data2 = new Byte[Op2ElementCount];
private static Vector128<Byte> _clsVar1;
private static Vector128<Byte> _clsVar2;
private Vector128<Byte> _fld1;
private Vector128<Byte> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__MinByte()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
}
public SimpleBinaryOpTest__MinByte()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
_dataTable = new DataTable(_data1, _data2, new Byte[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse2.Min(
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse2.Min(
Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse2.Min(
Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sse2).GetMethod(nameof(Sse2.Min), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse2).GetMethod(nameof(Sse2.Min), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse2).GetMethod(nameof(Sse2.Min), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse2.Min(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Byte>* pClsVar1 = &_clsVar1)
fixed (Vector128<Byte>* pClsVar2 = &_clsVar2)
{
var result = Sse2.Min(
Sse2.LoadVector128((Byte*)(pClsVar1)),
Sse2.LoadVector128((Byte*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr);
var result = Sse2.Min(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr));
var result = Sse2.Min(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr));
var result = Sse2.Min(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__MinByte();
var result = Sse2.Min(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleBinaryOpTest__MinByte();
fixed (Vector128<Byte>* pFld1 = &test._fld1)
fixed (Vector128<Byte>* pFld2 = &test._fld2)
{
var result = Sse2.Min(
Sse2.LoadVector128((Byte*)(pFld1)),
Sse2.LoadVector128((Byte*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse2.Min(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Byte>* pFld1 = &_fld1)
fixed (Vector128<Byte>* pFld2 = &_fld2)
{
var result = Sse2.Min(
Sse2.LoadVector128((Byte*)(pFld1)),
Sse2.LoadVector128((Byte*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse2.Min(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Sse2.Min(
Sse2.LoadVector128((Byte*)(&test._fld1)),
Sse2.LoadVector128((Byte*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Byte> op1, Vector128<Byte> op2, void* result, [CallerMemberName] string method = "")
{
Byte[] inArray1 = new Byte[Op1ElementCount];
Byte[] inArray2 = new Byte[Op2ElementCount];
Byte[] outArray = new Byte[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Byte>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Byte[] inArray1 = new Byte[Op1ElementCount];
Byte[] inArray2 = new Byte[Op2ElementCount];
Byte[] outArray = new Byte[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Byte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Byte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Byte>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Byte[] left, Byte[] right, Byte[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (Math.Min(left[0], right[0]) != result[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (Math.Min(left[i], right[i]) != result[i])
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.Min)}<Byte>(Vector128<Byte>, Vector128<Byte>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.DataLake.Store
{
using Azure;
using DataLake;
using Management;
using Azure;
using Management;
using DataLake;
using Models;
using Rest;
using Rest.Azure;
using Rest.Azure.OData;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// AccountOperations operations.
/// </summary>
public partial interface IAccountOperations
{
/// <summary>
/// Creates the specified Data Lake Store account.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake
/// Store account.
/// </param>
/// <param name='name'>
/// The name of the Data Lake Store account to create.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to create the Data Lake Store account.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<DataLakeStoreAccount>> CreateWithHttpMessagesAsync(string resourceGroupName, string name, DataLakeStoreAccount parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Updates the specified Data Lake Store account information.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake
/// Store account.
/// </param>
/// <param name='name'>
/// The name of the Data Lake Store account to update.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to update the Data Lake Store account.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<DataLakeStoreAccount>> UpdateWithHttpMessagesAsync(string resourceGroupName, string name, DataLakeStoreAccountUpdateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes the specified Data Lake Store account.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake
/// Store account.
/// </param>
/// <param name='name'>
/// The name of the Data Lake Store account to delete.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the specified Data Lake Store account.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake
/// Store account.
/// </param>
/// <param name='name'>
/// The name of the Data Lake Store account to retrieve.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<DataLakeStoreAccount>> GetWithHttpMessagesAsync(string resourceGroupName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Attempts to enable a user managed key vault for encryption of the
/// specified Data Lake Store account.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake
/// Store account.
/// </param>
/// <param name='accountName'>
/// The name of the Data Lake Store account to attempt to enable the
/// Key Vault for.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> EnableKeyVaultWithHttpMessagesAsync(string resourceGroupName, string accountName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists the Data Lake Store accounts within a specific resource
/// group. The response includes a link to the next page of results, if
/// any.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake
/// Store account(s).
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='select'>
/// OData Select statement. Limits the properties on each entry to just
/// those requested, e.g. Categories?$select=CategoryName,Description.
/// Optional.
/// </param>
/// <param name='count'>
/// A Boolean value of true or false to request a count of the matching
/// resources included with the resources in the response, e.g.
/// Categories?$count=true. Optional.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<DataLakeStoreAccount>>> ListByResourceGroupWithHttpMessagesAsync(string resourceGroupName, ODataQuery<DataLakeStoreAccount> odataQuery = default(ODataQuery<DataLakeStoreAccount>), string select = default(string), bool? count = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists the Data Lake Store accounts within the subscription. The
/// response includes a link to the next page of results, if any.
/// </summary>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='select'>
/// OData Select statement. Limits the properties on each entry to just
/// those requested, e.g. Categories?$select=CategoryName,Description.
/// Optional.
/// </param>
/// <param name='count'>
/// The Boolean value of true or false to request a count of the
/// matching resources included with the resources in the response,
/// e.g. Categories?$count=true. Optional.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<DataLakeStoreAccount>>> ListWithHttpMessagesAsync(ODataQuery<DataLakeStoreAccount> odataQuery = default(ODataQuery<DataLakeStoreAccount>), string select = default(string), bool? count = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates the specified Data Lake Store account.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake
/// Store account.
/// </param>
/// <param name='name'>
/// The name of the Data Lake Store account to create.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to create the Data Lake Store account.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<DataLakeStoreAccount>> BeginCreateWithHttpMessagesAsync(string resourceGroupName, string name, DataLakeStoreAccount parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Updates the specified Data Lake Store account information.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake
/// Store account.
/// </param>
/// <param name='name'>
/// The name of the Data Lake Store account to update.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to update the Data Lake Store account.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<DataLakeStoreAccount>> BeginUpdateWithHttpMessagesAsync(string resourceGroupName, string name, DataLakeStoreAccountUpdateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes the specified Data Lake Store account.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake
/// Store account.
/// </param>
/// <param name='name'>
/// The name of the Data Lake Store account to delete.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists the Data Lake Store accounts within a specific resource
/// group. The response includes a link to the next page of results, if
/// any.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<DataLakeStoreAccount>>> ListByResourceGroupNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists the Data Lake Store accounts within the subscription. The
/// response includes a link to the next page of results, if any.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<DataLakeStoreAccount>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
using System;
using System.Text;
namespace CodeSource.SkipList
{
public class SkipList
{
/* This "Node" class models a node in the Skip List structure. It holds a pair of (key, value)
* and also three pointers towards Node situated to the right, upwards and downwards. */
private class Node
{
public Node(IComparable key, object value)
{
this.key = key;
this.value = value;
this.right = this.up = this.down = null;
}
public Node() : this(null, null) {}
public IComparable key;
public object value;
public Node right, up, down;
}
/* Public constructor of the class. Receives as parameters the maximum number
* of paralel lists and the probability. */
public SkipList(int maxListsCount, double probability)
{
/* Store the maximum number of lists and the probability. */
this.maxListsCount = maxListsCount;
this.probability = probability;
/* Initialize the sentinel nodes. We will have for each list a distinct
* first sentinel, but the second sentinel will be shared among all lists. */
this.head = new Node[maxListsCount + 1];
for (int i = 0; i <= maxListsCount; i++)
this.head[i] = new Node();
this.tail = new Node();
/* Link the first sentinels of the lists one to another. Also link all first
* sentinels to the unique second sentinel. */
for (int i = 0; i <= maxListsCount; i++)
{
head[i].right = tail;
if (i > 0)
{
head[i].down = head[i-1];
head[i-1].up = head[i];
}
}
/* For the beginning we have no additional list, only the bottom list. */
this.currentListsCount = 0;
}
/* This is another public constructor. It creates a skip list with 11 aditional lists
* and with a probability of 0.5. */
public SkipList() : this(11, 0.5) {}
/* Inserts a pair of (key, value) into the Skip List structure. */
public void Insert(IComparable key, object value)
{
/* When inserting a key into the list, we will start from the top list and
* move right until we find a node that has a greater key than the one we want to insert.
* At this moment we move down to the next list and then again right.
*
* In this array we store the rightmost node that we reach on each level. We need to
* store them because when we will insert the new key in the lists, it will be inserted
* after these rightmost nodes. */
Node[] next = new Node[maxListsCount + 1];
/* Now we will parse the skip list structure, from the top list, going right and then down
* and then right again and then down again and so on. We use a "cursor" variable that will
* represent the current node that we reached in the skip list structure. */
Node cursor = head[currentListsCount];
for (int i=currentListsCount; i>=0; i--)
{
/* If we are not at the topmost list, then we move down with one level. */
if (i < currentListsCount)
cursor = cursor.down;
/* While we do not reach the second sentinel and we do not find a greater
* numeric value than the one we want to insert, keep moving right. */
while ((cursor.right != tail) && (cursor.right.key.CompareTo(key) < 0))
cursor = cursor.right;
/* Store this rightmost reached node on this level. */
next[i] = cursor;
}
/* Here we are on the bottom list, and we test to see if the new value to add
* is not already in the skip list. If it already exists, then we just update
* the value of the key. */
if ((next[0].right != tail) && (next[0].right.key.Equals(key)))
{
next[0].right.value = value;
}
/* If the number to insert is not in the list, then we flip the coin and insert
* it in the lists. */
else
{
/* We find a new level number which will tell us in how many lists to add the new number.
* This new random level number is generated by flipping the coin (see below). */
int newLevel = NewRandomLevel();
/* If the new level is greater than the current number of lists, then we extend our
* "rightmost nodes" array to include more lists. In the same time we increase the
* number of current lists. */
if (newLevel > currentListsCount)
{
for (int i = currentListsCount + 1; i <= newLevel; i++)
next[i] = head[i];
currentListsCount = newLevel;
}
/* Now we add the node to the lists and adjust the pointers accordingly.
* We add the node starting from the bottom list and moving up to the next lists.
* When we get above the bottom list, we start updating the "up" and "down" pointer of the
* nodes. */
Node prevNode = null;
Node n = null;
for (int i = 0; i <= newLevel; i++)
{
prevNode = n;
n = new Node(key, value);
n.right = next[i].right;
next[i].right = n;
if (i > 0)
{
n.down = prevNode;
prevNode.up = n;
}
}
}
}
/* This method computes a random value, smaller than the maximum admitted lists count. This random
* value will tell us into how many lists to insert a new key. */
private int NewRandomLevel()
{
int newLevel = 0;
while ((newLevel < maxListsCount) && FlipCoin())
newLevel++;
return newLevel;
}
/* This method simulates the flipping of a coin. It returns true, or false, similar to a coint which
* falls on one face or the other. */
private bool FlipCoin()
{
double d = r.NextDouble();
return (d < this.probability);
}
/* This method removes a key from the Skip List structure. */
public void Remove(IComparable key)
{
/* For removal too we will search for the element to remove. While searching
* the element, we parse each list, starting from the top list and going down
* towards the bottom list. On each list, we move from the first sentinel node
* rightwards until either we reach the second sentinel node, either we find
* a node with a key greater or equal than the key we want to remove.
*
* For each list we remember the rightmost node that we reached. */
Node[] next = new Node[maxListsCount + 1];
/* We search for the value to remove. We start from the topmost list, from the first
* sentinel node and move right, down, right, down, etc.
* As we said above, we will remember for each
* level the rightmost node that we reach. */
Node cursor = head[currentListsCount];
for (int i = currentListsCount; i >= 0; i--)
{
/* If we are not on the top level, then we move down one level. */
if (i < currentListsCount)
cursor = cursor.down;
/* Move right as long as we encounter values smaller than the value we want to
* remove. */
while ((cursor.right != tail) && (cursor.right.key.CompareTo(key) < 0))
cursor = cursor.right;
/* When we got here, either we reached the second sentinel node on the current
* level, either we found a node that is not smaller than the value we want to
* remove. It is possible that the node we found is equal to the value that we
* want to remove, or it can be greater. In both cases we will store this
* rightmost node. */
next[i] = cursor;
}
/* When we got here, we parsed even the bottom list and we stopped before a node
* that is greater or equal with the value to remove. We test to see if it is equal
* with the value or not. If it is equal, then we remove the value from the bottom
* list and also from the lists above. */
if ((next[0].right != tail) && (next[0].right.key.Equals(key)))
{
/* Parse each existing list. */
for (int i=currentListsCount; i>=0; i--)
{
/* And if the rightmost reached node is followed by the key to remove, then
* remove the key from the list. */
if ((next[i].right != tail) && next[i].right.key.Equals(key))
next[i].right = next[i].right.right;
}
}
}
/* Finds a key in a Skip List structure. Returns the object associated with that key, or null
* if the key is not found. */
public object Find(IComparable key)
{
/* We parse the skip list structure starting from the topmost list, from the first sentinel
* node. As long as we have keys smaller than the key we search for, we keep moving right.
* When we find a key that is greater or equal that the key we search, then we go down one
* level and there we try to go again right. When we reach the bottom list, we stop. */
Node cursor = head[currentListsCount];
for (int i = currentListsCount; i >= 0; i--)
{
if (i < currentListsCount)
cursor = cursor.down;
while ((cursor.right != tail) && (cursor.right.key.CompareTo(key) < 0))
cursor = cursor.right;
}
/* Here we are on the bottom list. Now we see if the searched key is there or not.
* If it is, we return the value associated with it. If not, we return null. */
if ((cursor.right != tail) && (cursor.right.key.Equals(key)))
return cursor.right.value;
else
return null;
}
/* This method prints the content of the Skip List structure. It can be useful for debugging. */
override public string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append("current number of lists: "+currentListsCount);
for (int i=currentListsCount; i>=0; i--)
{
sb.Append(Environment.NewLine);
Node cursor = head[i];
while (cursor != null)
{
sb.Append("[");
if (cursor.key != null)
sb.Append(cursor.key.ToString());
else
sb.Append("N/A");
sb.Append(", ");
if (cursor.value != null)
sb.Append(cursor.value.ToString());
else
sb.Append("N/A");
sb.Append("] ");
cursor = cursor.right;
}
}
sb.Append(Environment.NewLine);
sb.Append("--------------");
return sb.ToString();
}
/* This array will hold the first sentinel node from each list. */
private Node[] head;
/* This node will represent the second sentinel for the lists. It is enough
* to store only one sentinel node and link all lists to it, instead of creating
* sentinel nodes for each list separately. */
private Node tail;
/* This number represents the maximum number of lists that can be created.
* However it is possible that not all lists are created, depending on how
* the coin flips. In order to optimize the operations we will not create all
* lists from the beginning, but will create them only as necessary. */
private int maxListsCount;
/* This number represents the number of currently created lists. It can be smaller
* than the number of maximum accepted lists. */
private int currentListsCount;
/* This number represents the probability of adding a new element to another list above
* the bottom list. Usually this probability is 0.5 and is equivalent to the probability
* of flipping a coin (that is why we say that we flip a coin and then decide if we
* add the element to another list). However it is better to leave this probability
* easy to change, because in some situations a smaller or a greater probability can
* be better suited. */
private double probability;
/* This is a random number generator that is used for simulating the flipping of the coin. */
private Random r = new Random();
}
}
| |
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
using System.Text;
namespace EduHub.Data.Entities
{
/// <summary>
/// Subject Selections & Marks Data Set
/// </summary>
[GeneratedCode("EduHub Data", "0.9")]
public sealed partial class STMADataSet : EduHubDataSet<STMA>
{
/// <inheritdoc />
public override string Name { get { return "STMA"; } }
/// <inheritdoc />
public override bool SupportsEntityLastModified { get { return true; } }
internal STMADataSet(EduHubContext Context)
: base(Context)
{
Index_CKEY = new Lazy<NullDictionary<string, IReadOnlyList<STMA>>>(() => this.ToGroupedNullDictionary(i => i.CKEY));
Index_IDENT = new Lazy<NullDictionary<int?, IReadOnlyList<STMA>>>(() => this.ToGroupedNullDictionary(i => i.IDENT));
Index_LW_DATE = new Lazy<NullDictionary<DateTime?, IReadOnlyList<STMA>>>(() => this.ToGroupedNullDictionary(i => i.LW_DATE));
Index_MKEY = new Lazy<NullDictionary<string, IReadOnlyList<STMA>>>(() => this.ToGroupedNullDictionary(i => i.MKEY));
Index_SCHOOL_YEAR = new Lazy<NullDictionary<string, IReadOnlyList<STMA>>>(() => this.ToGroupedNullDictionary(i => i.SCHOOL_YEAR));
Index_SKEY = new Lazy<Dictionary<string, IReadOnlyList<STMA>>>(() => this.ToGroupedDictionary(i => i.SKEY));
Index_TID = new Lazy<Dictionary<int, STMA>>(() => this.ToDictionary(i => i.TID));
Index_TTPERIOD = new Lazy<NullDictionary<string, IReadOnlyList<STMA>>>(() => this.ToGroupedNullDictionary(i => i.TTPERIOD));
}
/// <summary>
/// Matches CSV file headers to actions, used to deserialize <see cref="STMA" />
/// </summary>
/// <param name="Headers">The CSV column headers</param>
/// <returns>An array of actions which deserialize <see cref="STMA" /> fields for each CSV column header</returns>
internal override Action<STMA, string>[] BuildMapper(IReadOnlyList<string> Headers)
{
var mapper = new Action<STMA, string>[Headers.Count];
for (var i = 0; i < Headers.Count; i++) {
switch (Headers[i]) {
case "TID":
mapper[i] = (e, v) => e.TID = int.Parse(v);
break;
case "SKEY":
mapper[i] = (e, v) => e.SKEY = v;
break;
case "MKEY":
mapper[i] = (e, v) => e.MKEY = v;
break;
case "CKEY":
mapper[i] = (e, v) => e.CKEY = v;
break;
case "PRIORITY":
mapper[i] = (e, v) => e.PRIORITY = v == null ? (short?)null : short.Parse(v);
break;
case "CLASS":
mapper[i] = (e, v) => e.CLASS = v == null ? (short?)null : short.Parse(v);
break;
case "FULLNAME":
mapper[i] = (e, v) => e.FULLNAME = v;
break;
case "TEACHER_NAME":
mapper[i] = (e, v) => e.TEACHER_NAME = v;
break;
case "IDENT":
mapper[i] = (e, v) => e.IDENT = v == null ? (int?)null : int.Parse(v);
break;
case "LOCK":
mapper[i] = (e, v) => e.LOCK = v == null ? (short?)null : short.Parse(v);
break;
case "TRPERIOD":
mapper[i] = (e, v) => e.TRPERIOD = v == null ? (int?)null : int.Parse(v);
break;
case "TTPERIOD":
mapper[i] = (e, v) => e.TTPERIOD = v;
break;
case "CYEAR":
mapper[i] = (e, v) => e.CYEAR = v == null ? (short?)null : short.Parse(v);
break;
case "CREATED":
mapper[i] = (e, v) => e.CREATED = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
break;
case "DROPOUT":
mapper[i] = (e, v) => e.DROPOUT = v == null ? (short?)null : short.Parse(v);
break;
case "GRADE01":
mapper[i] = (e, v) => e.GRADE01 = v;
break;
case "GRADE02":
mapper[i] = (e, v) => e.GRADE02 = v;
break;
case "GRADE03":
mapper[i] = (e, v) => e.GRADE03 = v;
break;
case "GRADE04":
mapper[i] = (e, v) => e.GRADE04 = v;
break;
case "GRADE05":
mapper[i] = (e, v) => e.GRADE05 = v;
break;
case "COMMENTA":
mapper[i] = (e, v) => e.COMMENTA = v;
break;
case "COMMENTB":
mapper[i] = (e, v) => e.COMMENTB = v;
break;
case "SCHOOL_YEAR":
mapper[i] = (e, v) => e.SCHOOL_YEAR = v;
break;
case "TOT_CLASS_PERIODS":
mapper[i] = (e, v) => e.TOT_CLASS_PERIODS = v == null ? (short?)null : short.Parse(v);
break;
case "TOT_APPROVED_ABS":
mapper[i] = (e, v) => e.TOT_APPROVED_ABS = v == null ? (short?)null : short.Parse(v);
break;
case "TOT_UNAPPROVED_ABS":
mapper[i] = (e, v) => e.TOT_UNAPPROVED_ABS = v == null ? (short?)null : short.Parse(v);
break;
case "EQUIVALENT_KLA":
mapper[i] = (e, v) => e.EQUIVALENT_KLA = v;
break;
case "LW_DATE":
mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
break;
case "LW_TIME":
mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v);
break;
case "LW_USER":
mapper[i] = (e, v) => e.LW_USER = v;
break;
default:
mapper[i] = MapperNoOp;
break;
}
}
return mapper;
}
/// <summary>
/// Merges <see cref="STMA" /> delta entities
/// </summary>
/// <param name="Entities">Iterator for base <see cref="STMA" /> entities</param>
/// <param name="DeltaEntities">List of delta <see cref="STMA" /> entities</param>
/// <returns>A merged <see cref="IEnumerable{STMA}"/> of entities</returns>
internal override IEnumerable<STMA> ApplyDeltaEntities(IEnumerable<STMA> Entities, List<STMA> DeltaEntities)
{
HashSet<int> Index_TID = new HashSet<int>(DeltaEntities.Select(i => i.TID));
using (var deltaIterator = DeltaEntities.GetEnumerator())
{
using (var entityIterator = Entities.GetEnumerator())
{
while (deltaIterator.MoveNext())
{
var deltaClusteredKey = deltaIterator.Current.SKEY;
bool yieldEntity = false;
while (entityIterator.MoveNext())
{
var entity = entityIterator.Current;
bool overwritten = Index_TID.Remove(entity.TID);
if (entity.SKEY.CompareTo(deltaClusteredKey) <= 0)
{
if (!overwritten)
{
yield return entity;
}
}
else
{
yieldEntity = !overwritten;
break;
}
}
yield return deltaIterator.Current;
if (yieldEntity)
{
yield return entityIterator.Current;
}
}
while (entityIterator.MoveNext())
{
yield return entityIterator.Current;
}
}
}
}
#region Index Fields
private Lazy<NullDictionary<string, IReadOnlyList<STMA>>> Index_CKEY;
private Lazy<NullDictionary<int?, IReadOnlyList<STMA>>> Index_IDENT;
private Lazy<NullDictionary<DateTime?, IReadOnlyList<STMA>>> Index_LW_DATE;
private Lazy<NullDictionary<string, IReadOnlyList<STMA>>> Index_MKEY;
private Lazy<NullDictionary<string, IReadOnlyList<STMA>>> Index_SCHOOL_YEAR;
private Lazy<Dictionary<string, IReadOnlyList<STMA>>> Index_SKEY;
private Lazy<Dictionary<int, STMA>> Index_TID;
private Lazy<NullDictionary<string, IReadOnlyList<STMA>>> Index_TTPERIOD;
#endregion
#region Index Methods
/// <summary>
/// Find STMA by CKEY field
/// </summary>
/// <param name="CKEY">CKEY value used to find STMA</param>
/// <returns>List of related STMA entities</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<STMA> FindByCKEY(string CKEY)
{
return Index_CKEY.Value[CKEY];
}
/// <summary>
/// Attempt to find STMA by CKEY field
/// </summary>
/// <param name="CKEY">CKEY value used to find STMA</param>
/// <param name="Value">List of related STMA entities</param>
/// <returns>True if the list of related STMA entities is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByCKEY(string CKEY, out IReadOnlyList<STMA> Value)
{
return Index_CKEY.Value.TryGetValue(CKEY, out Value);
}
/// <summary>
/// Attempt to find STMA by CKEY field
/// </summary>
/// <param name="CKEY">CKEY value used to find STMA</param>
/// <returns>List of related STMA entities, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<STMA> TryFindByCKEY(string CKEY)
{
IReadOnlyList<STMA> value;
if (Index_CKEY.Value.TryGetValue(CKEY, out value))
{
return value;
}
else
{
return null;
}
}
/// <summary>
/// Find STMA by IDENT field
/// </summary>
/// <param name="IDENT">IDENT value used to find STMA</param>
/// <returns>List of related STMA entities</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<STMA> FindByIDENT(int? IDENT)
{
return Index_IDENT.Value[IDENT];
}
/// <summary>
/// Attempt to find STMA by IDENT field
/// </summary>
/// <param name="IDENT">IDENT value used to find STMA</param>
/// <param name="Value">List of related STMA entities</param>
/// <returns>True if the list of related STMA entities is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByIDENT(int? IDENT, out IReadOnlyList<STMA> Value)
{
return Index_IDENT.Value.TryGetValue(IDENT, out Value);
}
/// <summary>
/// Attempt to find STMA by IDENT field
/// </summary>
/// <param name="IDENT">IDENT value used to find STMA</param>
/// <returns>List of related STMA entities, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<STMA> TryFindByIDENT(int? IDENT)
{
IReadOnlyList<STMA> value;
if (Index_IDENT.Value.TryGetValue(IDENT, out value))
{
return value;
}
else
{
return null;
}
}
/// <summary>
/// Find STMA by LW_DATE field
/// </summary>
/// <param name="LW_DATE">LW_DATE value used to find STMA</param>
/// <returns>List of related STMA entities</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<STMA> FindByLW_DATE(DateTime? LW_DATE)
{
return Index_LW_DATE.Value[LW_DATE];
}
/// <summary>
/// Attempt to find STMA by LW_DATE field
/// </summary>
/// <param name="LW_DATE">LW_DATE value used to find STMA</param>
/// <param name="Value">List of related STMA entities</param>
/// <returns>True if the list of related STMA entities is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByLW_DATE(DateTime? LW_DATE, out IReadOnlyList<STMA> Value)
{
return Index_LW_DATE.Value.TryGetValue(LW_DATE, out Value);
}
/// <summary>
/// Attempt to find STMA by LW_DATE field
/// </summary>
/// <param name="LW_DATE">LW_DATE value used to find STMA</param>
/// <returns>List of related STMA entities, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<STMA> TryFindByLW_DATE(DateTime? LW_DATE)
{
IReadOnlyList<STMA> value;
if (Index_LW_DATE.Value.TryGetValue(LW_DATE, out value))
{
return value;
}
else
{
return null;
}
}
/// <summary>
/// Find STMA by MKEY field
/// </summary>
/// <param name="MKEY">MKEY value used to find STMA</param>
/// <returns>List of related STMA entities</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<STMA> FindByMKEY(string MKEY)
{
return Index_MKEY.Value[MKEY];
}
/// <summary>
/// Attempt to find STMA by MKEY field
/// </summary>
/// <param name="MKEY">MKEY value used to find STMA</param>
/// <param name="Value">List of related STMA entities</param>
/// <returns>True if the list of related STMA entities is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByMKEY(string MKEY, out IReadOnlyList<STMA> Value)
{
return Index_MKEY.Value.TryGetValue(MKEY, out Value);
}
/// <summary>
/// Attempt to find STMA by MKEY field
/// </summary>
/// <param name="MKEY">MKEY value used to find STMA</param>
/// <returns>List of related STMA entities, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<STMA> TryFindByMKEY(string MKEY)
{
IReadOnlyList<STMA> value;
if (Index_MKEY.Value.TryGetValue(MKEY, out value))
{
return value;
}
else
{
return null;
}
}
/// <summary>
/// Find STMA by SCHOOL_YEAR field
/// </summary>
/// <param name="SCHOOL_YEAR">SCHOOL_YEAR value used to find STMA</param>
/// <returns>List of related STMA entities</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<STMA> FindBySCHOOL_YEAR(string SCHOOL_YEAR)
{
return Index_SCHOOL_YEAR.Value[SCHOOL_YEAR];
}
/// <summary>
/// Attempt to find STMA by SCHOOL_YEAR field
/// </summary>
/// <param name="SCHOOL_YEAR">SCHOOL_YEAR value used to find STMA</param>
/// <param name="Value">List of related STMA entities</param>
/// <returns>True if the list of related STMA entities is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindBySCHOOL_YEAR(string SCHOOL_YEAR, out IReadOnlyList<STMA> Value)
{
return Index_SCHOOL_YEAR.Value.TryGetValue(SCHOOL_YEAR, out Value);
}
/// <summary>
/// Attempt to find STMA by SCHOOL_YEAR field
/// </summary>
/// <param name="SCHOOL_YEAR">SCHOOL_YEAR value used to find STMA</param>
/// <returns>List of related STMA entities, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<STMA> TryFindBySCHOOL_YEAR(string SCHOOL_YEAR)
{
IReadOnlyList<STMA> value;
if (Index_SCHOOL_YEAR.Value.TryGetValue(SCHOOL_YEAR, out value))
{
return value;
}
else
{
return null;
}
}
/// <summary>
/// Find STMA by SKEY field
/// </summary>
/// <param name="SKEY">SKEY value used to find STMA</param>
/// <returns>List of related STMA entities</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<STMA> FindBySKEY(string SKEY)
{
return Index_SKEY.Value[SKEY];
}
/// <summary>
/// Attempt to find STMA by SKEY field
/// </summary>
/// <param name="SKEY">SKEY value used to find STMA</param>
/// <param name="Value">List of related STMA entities</param>
/// <returns>True if the list of related STMA entities is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindBySKEY(string SKEY, out IReadOnlyList<STMA> Value)
{
return Index_SKEY.Value.TryGetValue(SKEY, out Value);
}
/// <summary>
/// Attempt to find STMA by SKEY field
/// </summary>
/// <param name="SKEY">SKEY value used to find STMA</param>
/// <returns>List of related STMA entities, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<STMA> TryFindBySKEY(string SKEY)
{
IReadOnlyList<STMA> value;
if (Index_SKEY.Value.TryGetValue(SKEY, out value))
{
return value;
}
else
{
return null;
}
}
/// <summary>
/// Find STMA by TID field
/// </summary>
/// <param name="TID">TID value used to find STMA</param>
/// <returns>Related STMA entity</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public STMA FindByTID(int TID)
{
return Index_TID.Value[TID];
}
/// <summary>
/// Attempt to find STMA by TID field
/// </summary>
/// <param name="TID">TID value used to find STMA</param>
/// <param name="Value">Related STMA entity</param>
/// <returns>True if the related STMA entity is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByTID(int TID, out STMA Value)
{
return Index_TID.Value.TryGetValue(TID, out Value);
}
/// <summary>
/// Attempt to find STMA by TID field
/// </summary>
/// <param name="TID">TID value used to find STMA</param>
/// <returns>Related STMA entity, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public STMA TryFindByTID(int TID)
{
STMA value;
if (Index_TID.Value.TryGetValue(TID, out value))
{
return value;
}
else
{
return null;
}
}
/// <summary>
/// Find STMA by TTPERIOD field
/// </summary>
/// <param name="TTPERIOD">TTPERIOD value used to find STMA</param>
/// <returns>List of related STMA entities</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<STMA> FindByTTPERIOD(string TTPERIOD)
{
return Index_TTPERIOD.Value[TTPERIOD];
}
/// <summary>
/// Attempt to find STMA by TTPERIOD field
/// </summary>
/// <param name="TTPERIOD">TTPERIOD value used to find STMA</param>
/// <param name="Value">List of related STMA entities</param>
/// <returns>True if the list of related STMA entities is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByTTPERIOD(string TTPERIOD, out IReadOnlyList<STMA> Value)
{
return Index_TTPERIOD.Value.TryGetValue(TTPERIOD, out Value);
}
/// <summary>
/// Attempt to find STMA by TTPERIOD field
/// </summary>
/// <param name="TTPERIOD">TTPERIOD value used to find STMA</param>
/// <returns>List of related STMA entities, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<STMA> TryFindByTTPERIOD(string TTPERIOD)
{
IReadOnlyList<STMA> value;
if (Index_TTPERIOD.Value.TryGetValue(TTPERIOD, out value))
{
return value;
}
else
{
return null;
}
}
#endregion
#region SQL Integration
/// <summary>
/// Returns a <see cref="SqlCommand"/> which checks for the existence of a STMA table, and if not found, creates the table and associated indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[STMA]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[STMA](
[TID] int IDENTITY NOT NULL,
[SKEY] varchar(10) NOT NULL,
[MKEY] varchar(5) NULL,
[CKEY] varchar(5) NULL,
[PRIORITY] smallint NULL,
[CLASS] smallint NULL,
[FULLNAME] varchar(30) NULL,
[TEACHER_NAME] varchar(30) NULL,
[IDENT] int NULL,
[LOCK] smallint NULL,
[TRPERIOD] int NULL,
[TTPERIOD] varchar(8) NULL,
[CYEAR] smallint NULL,
[CREATED] datetime NULL,
[DROPOUT] smallint NULL,
[GRADE01] varchar(1) NULL,
[GRADE02] varchar(1) NULL,
[GRADE03] varchar(1) NULL,
[GRADE04] varchar(1) NULL,
[GRADE05] varchar(1) NULL,
[COMMENTA] varchar(MAX) NULL,
[COMMENTB] varchar(MAX) NULL,
[SCHOOL_YEAR] varchar(4) NULL,
[TOT_CLASS_PERIODS] smallint NULL,
[TOT_APPROVED_ABS] smallint NULL,
[TOT_UNAPPROVED_ABS] smallint NULL,
[EQUIVALENT_KLA] varchar(8) NULL,
[LW_DATE] datetime NULL,
[LW_TIME] smallint NULL,
[LW_USER] varchar(128) NULL,
CONSTRAINT [STMA_Index_TID] PRIMARY KEY NONCLUSTERED (
[TID] ASC
)
);
CREATE NONCLUSTERED INDEX [STMA_Index_CKEY] ON [dbo].[STMA]
(
[CKEY] ASC
);
CREATE NONCLUSTERED INDEX [STMA_Index_IDENT] ON [dbo].[STMA]
(
[IDENT] ASC
);
CREATE NONCLUSTERED INDEX [STMA_Index_LW_DATE] ON [dbo].[STMA]
(
[LW_DATE] ASC
);
CREATE NONCLUSTERED INDEX [STMA_Index_MKEY] ON [dbo].[STMA]
(
[MKEY] ASC
);
CREATE NONCLUSTERED INDEX [STMA_Index_SCHOOL_YEAR] ON [dbo].[STMA]
(
[SCHOOL_YEAR] ASC
);
CREATE CLUSTERED INDEX [STMA_Index_SKEY] ON [dbo].[STMA]
(
[SKEY] ASC
);
CREATE NONCLUSTERED INDEX [STMA_Index_TTPERIOD] ON [dbo].[STMA]
(
[TTPERIOD] ASC
);
END");
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which disables all non-clustered table indexes.
/// Typically called before <see cref="SqlBulkCopy"/> to improve performance.
/// <see cref="GetSqlRebuildIndexesCommand(SqlConnection)"/> should be called to rebuild and enable indexes after performance sensitive work is completed.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>A <see cref="SqlCommand"/> which (when executed) will disable all non-clustered table indexes</returns>
public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[STMA]') AND name = N'STMA_Index_CKEY')
ALTER INDEX [STMA_Index_CKEY] ON [dbo].[STMA] DISABLE;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[STMA]') AND name = N'STMA_Index_IDENT')
ALTER INDEX [STMA_Index_IDENT] ON [dbo].[STMA] DISABLE;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[STMA]') AND name = N'STMA_Index_LW_DATE')
ALTER INDEX [STMA_Index_LW_DATE] ON [dbo].[STMA] DISABLE;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[STMA]') AND name = N'STMA_Index_MKEY')
ALTER INDEX [STMA_Index_MKEY] ON [dbo].[STMA] DISABLE;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[STMA]') AND name = N'STMA_Index_SCHOOL_YEAR')
ALTER INDEX [STMA_Index_SCHOOL_YEAR] ON [dbo].[STMA] DISABLE;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[STMA]') AND name = N'STMA_Index_TID')
ALTER INDEX [STMA_Index_TID] ON [dbo].[STMA] DISABLE;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[STMA]') AND name = N'STMA_Index_TTPERIOD')
ALTER INDEX [STMA_Index_TTPERIOD] ON [dbo].[STMA] DISABLE;
");
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which rebuilds and enables all non-clustered table indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>A <see cref="SqlCommand"/> which (when executed) will rebuild and enable all non-clustered table indexes</returns>
public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[STMA]') AND name = N'STMA_Index_CKEY')
ALTER INDEX [STMA_Index_CKEY] ON [dbo].[STMA] REBUILD PARTITION = ALL;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[STMA]') AND name = N'STMA_Index_IDENT')
ALTER INDEX [STMA_Index_IDENT] ON [dbo].[STMA] REBUILD PARTITION = ALL;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[STMA]') AND name = N'STMA_Index_LW_DATE')
ALTER INDEX [STMA_Index_LW_DATE] ON [dbo].[STMA] REBUILD PARTITION = ALL;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[STMA]') AND name = N'STMA_Index_MKEY')
ALTER INDEX [STMA_Index_MKEY] ON [dbo].[STMA] REBUILD PARTITION = ALL;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[STMA]') AND name = N'STMA_Index_SCHOOL_YEAR')
ALTER INDEX [STMA_Index_SCHOOL_YEAR] ON [dbo].[STMA] REBUILD PARTITION = ALL;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[STMA]') AND name = N'STMA_Index_TID')
ALTER INDEX [STMA_Index_TID] ON [dbo].[STMA] REBUILD PARTITION = ALL;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[STMA]') AND name = N'STMA_Index_TTPERIOD')
ALTER INDEX [STMA_Index_TTPERIOD] ON [dbo].[STMA] REBUILD PARTITION = ALL;
");
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which deletes the <see cref="STMA"/> entities passed
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <param name="Entities">The <see cref="STMA"/> entities to be deleted</param>
public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<STMA> Entities)
{
SqlCommand command = new SqlCommand();
int parameterIndex = 0;
StringBuilder builder = new StringBuilder();
List<int> Index_TID = new List<int>();
foreach (var entity in Entities)
{
Index_TID.Add(entity.TID);
}
builder.AppendLine("DELETE [dbo].[STMA] WHERE");
// Index_TID
builder.Append("[TID] IN (");
for (int index = 0; index < Index_TID.Count; index++)
{
if (index != 0)
builder.Append(", ");
// TID
var parameterTID = $"@p{parameterIndex++}";
builder.Append(parameterTID);
command.Parameters.Add(parameterTID, SqlDbType.Int).Value = Index_TID[index];
}
builder.Append(");");
command.Connection = SqlConnection;
command.CommandText = builder.ToString();
return command;
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the STMA data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the STMA data set</returns>
public override EduHubDataSetDataReader<STMA> GetDataSetDataReader()
{
return new STMADataReader(Load());
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the STMA data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the STMA data set</returns>
public override EduHubDataSetDataReader<STMA> GetDataSetDataReader(List<STMA> Entities)
{
return new STMADataReader(new EduHubDataSetLoadedReader<STMA>(this, Entities));
}
// Modest implementation to primarily support SqlBulkCopy
private class STMADataReader : EduHubDataSetDataReader<STMA>
{
public STMADataReader(IEduHubDataSetReader<STMA> Reader)
: base (Reader)
{
}
public override int FieldCount { get { return 30; } }
public override object GetValue(int i)
{
switch (i)
{
case 0: // TID
return Current.TID;
case 1: // SKEY
return Current.SKEY;
case 2: // MKEY
return Current.MKEY;
case 3: // CKEY
return Current.CKEY;
case 4: // PRIORITY
return Current.PRIORITY;
case 5: // CLASS
return Current.CLASS;
case 6: // FULLNAME
return Current.FULLNAME;
case 7: // TEACHER_NAME
return Current.TEACHER_NAME;
case 8: // IDENT
return Current.IDENT;
case 9: // LOCK
return Current.LOCK;
case 10: // TRPERIOD
return Current.TRPERIOD;
case 11: // TTPERIOD
return Current.TTPERIOD;
case 12: // CYEAR
return Current.CYEAR;
case 13: // CREATED
return Current.CREATED;
case 14: // DROPOUT
return Current.DROPOUT;
case 15: // GRADE01
return Current.GRADE01;
case 16: // GRADE02
return Current.GRADE02;
case 17: // GRADE03
return Current.GRADE03;
case 18: // GRADE04
return Current.GRADE04;
case 19: // GRADE05
return Current.GRADE05;
case 20: // COMMENTA
return Current.COMMENTA;
case 21: // COMMENTB
return Current.COMMENTB;
case 22: // SCHOOL_YEAR
return Current.SCHOOL_YEAR;
case 23: // TOT_CLASS_PERIODS
return Current.TOT_CLASS_PERIODS;
case 24: // TOT_APPROVED_ABS
return Current.TOT_APPROVED_ABS;
case 25: // TOT_UNAPPROVED_ABS
return Current.TOT_UNAPPROVED_ABS;
case 26: // EQUIVALENT_KLA
return Current.EQUIVALENT_KLA;
case 27: // LW_DATE
return Current.LW_DATE;
case 28: // LW_TIME
return Current.LW_TIME;
case 29: // LW_USER
return Current.LW_USER;
default:
throw new ArgumentOutOfRangeException(nameof(i));
}
}
public override bool IsDBNull(int i)
{
switch (i)
{
case 2: // MKEY
return Current.MKEY == null;
case 3: // CKEY
return Current.CKEY == null;
case 4: // PRIORITY
return Current.PRIORITY == null;
case 5: // CLASS
return Current.CLASS == null;
case 6: // FULLNAME
return Current.FULLNAME == null;
case 7: // TEACHER_NAME
return Current.TEACHER_NAME == null;
case 8: // IDENT
return Current.IDENT == null;
case 9: // LOCK
return Current.LOCK == null;
case 10: // TRPERIOD
return Current.TRPERIOD == null;
case 11: // TTPERIOD
return Current.TTPERIOD == null;
case 12: // CYEAR
return Current.CYEAR == null;
case 13: // CREATED
return Current.CREATED == null;
case 14: // DROPOUT
return Current.DROPOUT == null;
case 15: // GRADE01
return Current.GRADE01 == null;
case 16: // GRADE02
return Current.GRADE02 == null;
case 17: // GRADE03
return Current.GRADE03 == null;
case 18: // GRADE04
return Current.GRADE04 == null;
case 19: // GRADE05
return Current.GRADE05 == null;
case 20: // COMMENTA
return Current.COMMENTA == null;
case 21: // COMMENTB
return Current.COMMENTB == null;
case 22: // SCHOOL_YEAR
return Current.SCHOOL_YEAR == null;
case 23: // TOT_CLASS_PERIODS
return Current.TOT_CLASS_PERIODS == null;
case 24: // TOT_APPROVED_ABS
return Current.TOT_APPROVED_ABS == null;
case 25: // TOT_UNAPPROVED_ABS
return Current.TOT_UNAPPROVED_ABS == null;
case 26: // EQUIVALENT_KLA
return Current.EQUIVALENT_KLA == null;
case 27: // LW_DATE
return Current.LW_DATE == null;
case 28: // LW_TIME
return Current.LW_TIME == null;
case 29: // LW_USER
return Current.LW_USER == null;
default:
return false;
}
}
public override string GetName(int ordinal)
{
switch (ordinal)
{
case 0: // TID
return "TID";
case 1: // SKEY
return "SKEY";
case 2: // MKEY
return "MKEY";
case 3: // CKEY
return "CKEY";
case 4: // PRIORITY
return "PRIORITY";
case 5: // CLASS
return "CLASS";
case 6: // FULLNAME
return "FULLNAME";
case 7: // TEACHER_NAME
return "TEACHER_NAME";
case 8: // IDENT
return "IDENT";
case 9: // LOCK
return "LOCK";
case 10: // TRPERIOD
return "TRPERIOD";
case 11: // TTPERIOD
return "TTPERIOD";
case 12: // CYEAR
return "CYEAR";
case 13: // CREATED
return "CREATED";
case 14: // DROPOUT
return "DROPOUT";
case 15: // GRADE01
return "GRADE01";
case 16: // GRADE02
return "GRADE02";
case 17: // GRADE03
return "GRADE03";
case 18: // GRADE04
return "GRADE04";
case 19: // GRADE05
return "GRADE05";
case 20: // COMMENTA
return "COMMENTA";
case 21: // COMMENTB
return "COMMENTB";
case 22: // SCHOOL_YEAR
return "SCHOOL_YEAR";
case 23: // TOT_CLASS_PERIODS
return "TOT_CLASS_PERIODS";
case 24: // TOT_APPROVED_ABS
return "TOT_APPROVED_ABS";
case 25: // TOT_UNAPPROVED_ABS
return "TOT_UNAPPROVED_ABS";
case 26: // EQUIVALENT_KLA
return "EQUIVALENT_KLA";
case 27: // LW_DATE
return "LW_DATE";
case 28: // LW_TIME
return "LW_TIME";
case 29: // LW_USER
return "LW_USER";
default:
throw new ArgumentOutOfRangeException(nameof(ordinal));
}
}
public override int GetOrdinal(string name)
{
switch (name)
{
case "TID":
return 0;
case "SKEY":
return 1;
case "MKEY":
return 2;
case "CKEY":
return 3;
case "PRIORITY":
return 4;
case "CLASS":
return 5;
case "FULLNAME":
return 6;
case "TEACHER_NAME":
return 7;
case "IDENT":
return 8;
case "LOCK":
return 9;
case "TRPERIOD":
return 10;
case "TTPERIOD":
return 11;
case "CYEAR":
return 12;
case "CREATED":
return 13;
case "DROPOUT":
return 14;
case "GRADE01":
return 15;
case "GRADE02":
return 16;
case "GRADE03":
return 17;
case "GRADE04":
return 18;
case "GRADE05":
return 19;
case "COMMENTA":
return 20;
case "COMMENTB":
return 21;
case "SCHOOL_YEAR":
return 22;
case "TOT_CLASS_PERIODS":
return 23;
case "TOT_APPROVED_ABS":
return 24;
case "TOT_UNAPPROVED_ABS":
return 25;
case "EQUIVALENT_KLA":
return 26;
case "LW_DATE":
return 27;
case "LW_TIME":
return 28;
case "LW_USER":
return 29;
default:
throw new ArgumentOutOfRangeException(nameof(name));
}
}
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Web;
namespace Umbraco.Core
{
///<summary>
/// Extension methods for dictionary & concurrentdictionary
///</summary>
internal static class DictionaryExtensions
{
/// <summary>
/// Method to Get a value by the key. If the key doesn't exist it will create a new TVal object for the key and return it.
/// </summary>
/// <typeparam name="TKey"></typeparam>
/// <typeparam name="TVal"></typeparam>
/// <param name="dict"></param>
/// <param name="key"></param>
/// <returns></returns>
public static TVal GetOrCreate<TKey, TVal>(this IDictionary<TKey, TVal> dict, TKey key)
where TVal : class, new()
{
if (dict.ContainsKey(key) == false)
{
dict.Add(key, new TVal());
}
return dict[key];
}
/// <summary>
/// Updates an item with the specified key with the specified value
/// </summary>
/// <typeparam name="TKey"></typeparam>
/// <typeparam name="TValue"></typeparam>
/// <param name="dict"></param>
/// <param name="key"></param>
/// <param name="updateFactory"></param>
/// <returns></returns>
/// <remarks>
/// Taken from: http://stackoverflow.com/questions/12240219/is-there-a-way-to-use-concurrentdictionary-tryupdate-with-a-lambda-expression
///
/// If there is an item in the dictionary with the key, it will keep trying to update it until it can
/// </remarks>
public static bool TryUpdate<TKey, TValue>(this ConcurrentDictionary<TKey, TValue> dict, TKey key, Func<TValue, TValue> updateFactory)
{
TValue curValue;
while (dict.TryGetValue(key, out curValue))
{
if (dict.TryUpdate(key, updateFactory(curValue), curValue))
return true;
//if we're looping either the key was removed by another thread, or another thread
//changed the value, so we start again.
}
return false;
}
/// <summary>
/// Updates an item with the specified key with the specified value
/// </summary>
/// <typeparam name="TKey"></typeparam>
/// <typeparam name="TValue"></typeparam>
/// <param name="dict"></param>
/// <param name="key"></param>
/// <param name="updateFactory"></param>
/// <returns></returns>
/// <remarks>
/// Taken from: http://stackoverflow.com/questions/12240219/is-there-a-way-to-use-concurrentdictionary-tryupdate-with-a-lambda-expression
///
/// WARNING: If the value changes after we've retreived it, then the item will not be updated
/// </remarks>
public static bool TryUpdateOptimisitic<TKey, TValue>(this ConcurrentDictionary<TKey, TValue> dict, TKey key, Func<TValue, TValue> updateFactory)
{
TValue curValue;
if (!dict.TryGetValue(key, out curValue))
return false;
dict.TryUpdate(key, updateFactory(curValue), curValue);
return true;//note we return true whether we succeed or not, see explanation below.
}
/// <summary>
/// Converts a dictionary to another type by only using direct casting
/// </summary>
/// <typeparam name="TKeyOut"></typeparam>
/// <typeparam name="TValOut"></typeparam>
/// <param name="d"></param>
/// <returns></returns>
public static IDictionary<TKeyOut, TValOut> ConvertTo<TKeyOut, TValOut>(this IDictionary d)
{
var result = new Dictionary<TKeyOut, TValOut>();
foreach (DictionaryEntry v in d)
{
result.Add((TKeyOut)v.Key, (TValOut)v.Value);
}
return result;
}
/// <summary>
/// Converts a dictionary to another type using the specified converters
/// </summary>
/// <typeparam name="TKeyOut"></typeparam>
/// <typeparam name="TValOut"></typeparam>
/// <param name="d"></param>
/// <param name="keyConverter"></param>
/// <param name="valConverter"></param>
/// <returns></returns>
public static IDictionary<TKeyOut, TValOut> ConvertTo<TKeyOut, TValOut>(this IDictionary d, Func<object, TKeyOut> keyConverter, Func<object, TValOut> valConverter)
{
var result = new Dictionary<TKeyOut, TValOut>();
foreach (DictionaryEntry v in d)
{
result.Add(keyConverter(v.Key), valConverter(v.Value));
}
return result;
}
/// <summary>
/// Converts a dictionary to a NameValueCollection
/// </summary>
/// <param name="d"></param>
/// <returns></returns>
public static NameValueCollection ToNameValueCollection(this IDictionary<string, string> d)
{
var n = new NameValueCollection();
foreach (var i in d)
{
n.Add(i.Key, i.Value);
}
return n;
}
/// <summary>
/// Merges all key/values from the sources dictionaries into the destination dictionary
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="TK"></typeparam>
/// <typeparam name="TV"></typeparam>
/// <param name="destination">The source dictionary to merge other dictionaries into</param>
/// <param name="overwrite">
/// By default all values will be retained in the destination if the same keys exist in the sources but
/// this can changed if overwrite = true, then any key/value found in any of the sources will overwritten in the destination. Note that
/// it will just use the last found key/value if this is true.
/// </param>
/// <param name="sources">The other dictionaries to merge values from</param>
public static void MergeLeft<T, TK, TV>(this T destination, IEnumerable<IDictionary<TK, TV>> sources, bool overwrite = false)
where T : IDictionary<TK, TV>
{
foreach (var p in sources.SelectMany(src => src).Where(p => overwrite || destination.ContainsKey(p.Key) == false))
{
destination[p.Key] = p.Value;
}
}
/// <summary>
/// Merges all key/values from the sources dictionaries into the destination dictionary
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="TK"></typeparam>
/// <typeparam name="TV"></typeparam>
/// <param name="destination">The source dictionary to merge other dictionaries into</param>
/// <param name="overwrite">
/// By default all values will be retained in the destination if the same keys exist in the sources but
/// this can changed if overwrite = true, then any key/value found in any of the sources will overwritten in the destination. Note that
/// it will just use the last found key/value if this is true.
/// </param>
/// <param name="source">The other dictionary to merge values from</param>
public static void MergeLeft<T, TK, TV>(this T destination, IDictionary<TK, TV> source, bool overwrite = false)
where T : IDictionary<TK, TV>
{
destination.MergeLeft(new[] {source}, overwrite);
}
/// <summary>
/// Returns the value of the key value based on the key, if the key is not found, a null value is returned
/// </summary>
/// <typeparam name="TKey">The type of the key.</typeparam>
/// <typeparam name="TVal">The type of the val.</typeparam>
/// <param name="d">The d.</param>
/// <param name="key">The key.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns></returns>
public static TVal GetValue<TKey, TVal>(this IDictionary<TKey, TVal> d, TKey key, TVal defaultValue = default(TVal))
{
if (d.ContainsKey(key))
{
return d[key];
}
return defaultValue;
}
/// <summary>
/// Returns the value of the key value based on the key as it's string value, if the key is not found, then an empty string is returned
/// </summary>
/// <param name="d"></param>
/// <param name="key"></param>
/// <returns></returns>
public static string GetValueAsString<TKey, TVal>(this IDictionary<TKey, TVal> d, TKey key)
{
if (d.ContainsKey(key))
{
return d[key].ToString();
}
return String.Empty;
}
/// <summary>
/// Returns the value of the key value based on the key as it's string value, if the key is not found or is an empty string, then the provided default value is returned
/// </summary>
/// <param name="d"></param>
/// <param name="key"></param>
/// <param name="defaultValue"></param>
/// <returns></returns>
public static string GetValueAsString<TKey, TVal>(this IDictionary<TKey, TVal> d, TKey key, string defaultValue)
{
if (d.ContainsKey(key))
{
var value = d[key].ToString();
if (value != string.Empty)
return value;
}
return defaultValue;
}
/// <summary>contains key ignore case.</summary>
/// <param name="dictionary">The dictionary.</param>
/// <param name="key">The key.</param>
/// <typeparam name="TValue">Value Type</typeparam>
/// <returns>The contains key ignore case.</returns>
public static bool ContainsKeyIgnoreCase<TValue>(this IDictionary<string, TValue> dictionary, string key)
{
return dictionary.Keys.InvariantContains(key);
}
/// <summary>
/// Converts a dictionary object to a query string representation such as:
/// firstname=shannon&lastname=deminick
/// </summary>
/// <param name="d"></param>
/// <returns></returns>
public static string ToQueryString(this IDictionary<string, object> d)
{
if (!d.Any()) return "";
var builder = new StringBuilder();
foreach (var i in d)
{
builder.Append(String.Format("{0}={1}&", HttpUtility.UrlEncode(i.Key), i.Value == null ? string.Empty : HttpUtility.UrlEncode(i.Value.ToString())));
}
return builder.ToString().TrimEnd('&');
}
/// <summary>The get entry ignore case.</summary>
/// <param name="dictionary">The dictionary.</param>
/// <param name="key">The key.</param>
/// <typeparam name="TValue">The type</typeparam>
/// <returns>The entry</returns>
public static TValue GetValueIgnoreCase<TValue>(this IDictionary<string, TValue> dictionary, string key)
{
return dictionary.GetValueIgnoreCase(key, default(TValue));
}
/// <summary>The get entry ignore case.</summary>
/// <param name="dictionary">The dictionary.</param>
/// <param name="key">The key.</param>
/// <param name="defaultValue">The default value.</param>
/// <typeparam name="TValue">The type</typeparam>
/// <returns>The entry</returns>
public static TValue GetValueIgnoreCase<TValue>(this IDictionary<string, TValue> dictionary, string key, TValue defaultValue)
{
key = dictionary.Keys.FirstOrDefault(i => i.InvariantEquals(key));
return key.IsNullOrWhiteSpace() == false
? dictionary[key]
: defaultValue;
}
}
}
| |
/*
* 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.Drawing;
using System.IO;
using System.Net;
using Nini.Config;
using OpenMetaverse;
using OpenMetaverse.Imaging;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using log4net;
using System.Reflection;
namespace OpenSim.Region.CoreModules.Scripting.LoadImageURL
{
public class LoadImageURLModule : IRegionModule, IDynamicTextureRender
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private string m_name = "LoadImageURL";
private Scene m_scene;
private IDynamicTextureManager m_textureManager;
private string m_proxyurl = "";
private string m_proxyexcepts = "";
#region IDynamicTextureRender Members
public string GetName()
{
return m_name;
}
public string GetContentType()
{
return ("image");
}
public bool SupportsAsynchronous()
{
return true;
}
public byte[] ConvertUrl(string url, string extraParams)
{
return null;
}
public byte[] ConvertStream(Stream data, string extraParams)
{
return null;
}
public bool AsyncConvertUrl(UUID id, string url, string extraParams)
{
MakeHttpRequest(url, id);
return true;
}
public bool AsyncConvertData(UUID id, string bodyData, string extraParams)
{
return false;
}
public void GetDrawStringSize(string text, string fontName, int fontSize,
out double xSize, out double ySize)
{
xSize = 0;
ySize = 0;
}
#endregion
#region IRegionModule Members
public void Initialise(Scene scene, IConfigSource config)
{
if (m_scene == null)
{
m_scene = scene;
}
m_proxyurl = config.Configs["Startup"].GetString("HttpProxy");
m_proxyexcepts = config.Configs["Startup"].GetString("HttpProxyExceptions");
}
public void PostInitialise()
{
m_textureManager = m_scene.RequestModuleInterface<IDynamicTextureManager>();
if (m_textureManager != null)
{
m_textureManager.RegisterRender(GetContentType(), this);
}
}
public void Close()
{
}
public string Name
{
get { return m_name; }
}
public bool IsSharedModule
{
get { return true; }
}
#endregion
private void MakeHttpRequest(string url, UUID requestID)
{
WebRequest request = HttpWebRequest.Create(url);
if (m_proxyurl != null && m_proxyurl.Length > 0)
{
if (m_proxyexcepts != null && m_proxyexcepts.Length > 0)
{
string[] elist = m_proxyexcepts.Split(';');
request.Proxy = new WebProxy(m_proxyurl, true, elist);
}
else
{
request.Proxy = new WebProxy(m_proxyurl, true);
}
}
RequestState state = new RequestState((HttpWebRequest) request, requestID);
// IAsyncResult result = request.BeginGetResponse(new AsyncCallback(HttpRequestReturn), state);
request.BeginGetResponse(new AsyncCallback(HttpRequestReturn), state);
TimeSpan t = (DateTime.UtcNow - new DateTime(1970, 1, 1));
state.TimeOfRequest = (int) t.TotalSeconds;
}
private void HttpRequestReturn(IAsyncResult result)
{
RequestState state = (RequestState) result.AsyncState;
WebRequest request = (WebRequest) state.Request;
Stream stream = null;
byte[] imageJ2000 = new byte[0];
try
{
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);
if (response != null && response.StatusCode == HttpStatusCode.OK)
{
stream = response.GetResponseStream();
if (stream != null)
{
try
{
Bitmap image = new Bitmap(stream);
Size newsize;
// TODO: make this a bit less hard coded
if ((image.Height < 64) && (image.Width < 64))
{
newsize = new Size(32, 32);
}
else if ((image.Height < 128) && (image.Width < 128))
{
newsize = new Size(64, 64);
}
else if ((image.Height < 256) && (image.Width < 256))
{
newsize = new Size(128, 128);
}
else if ((image.Height < 512 && image.Width < 512))
{
newsize = new Size(256, 256);
}
else if ((image.Height < 1024 && image.Width < 1024))
{
newsize = new Size(512, 512);
}
else
{
newsize = new Size(1024, 1024);
}
Bitmap resize = new Bitmap(image, newsize);
imageJ2000 = OpenJPEG.EncodeFromImage(resize, true);
}
catch (Exception)
{
m_log.Error("[LOADIMAGEURLMODULE]: OpenJpeg Conversion Failed. Empty byte data returned!");
}
}
else
{
m_log.WarnFormat("[LOADIMAGEURLMODULE] No data returned");
}
}
}
catch (WebException)
{
}
finally
{
if (stream != null)
{
stream.Close();
}
}
m_log.DebugFormat("[LOADIMAGEURLMODULE] Returning {0} bytes of image data for request {1}",
imageJ2000.Length, state.RequestID);
m_textureManager.ReturnData(state.RequestID, imageJ2000);
}
#region Nested type: RequestState
public class RequestState
{
public HttpWebRequest Request = null;
public UUID RequestID = UUID.Zero;
public int TimeOfRequest = 0;
public RequestState(HttpWebRequest request, UUID requestID)
{
Request = request;
RequestID = requestID;
}
}
#endregion
}
}
| |
/*
* XmlDTDReader.cs - Implementation of the
* "System.Xml.Private.XmlDTDReader" class.
*
* Copyright (C) 2004 Free Software Foundation, Inc.
*
* 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
*/
namespace System.Xml.Private
{
using System;
using System.Text;
internal sealed class XmlDTDReader : XmlErrorProcessor
{
// Internals.
private XmlParserContext context;
private XmlDTDParserInput input;
private XmlResolver resolver;
// Constructor.
public XmlDTDReader(XmlParserContext context)
: base(null)
{
this.context = context;
this.input = null;
this.resolver = null;
}
#if !ECMA_COMPAT
//
// NOTE: Any dtd rule handling should be done via objects accessible
// through parser context properties.
//
// Get the valid flag, which is set iff no invalid pe references were found.
public bool Valid
{
get { return input.Valid; }
}
#endif
// Get or set the parser context.
public XmlParserContext Context
{
get { return context; }
set { context = value; }
}
// Initialize this dtd reader.
public void Init
(XmlParserInput input,
XmlResolver resolver)
{
base.ErrorHandler = input.ErrorHandler;
this.input = new XmlDTDParserInput(input, context.NameTable);
this.resolver = resolver;
}
// Read a doctype declaration.
//
// Already read: '<!DOCTYPE'
public void Read()
{
// turn off pe scanning
input.ScanForPE = false;
// require whitespace, then read the name
if(!input.SkipWhitespace()) { Error(/* TODO */); }
context.DocTypeName = input.ReadName();
// value of internal subset defaults to empty
context.InternalSubset = String.Empty;
// values of the public and system ids default to empty
context.PublicId = String.Empty;
context.SystemId = String.Empty;
// check for an external id
bool hasWS = input.SkipWhitespace();
if(!input.PeekChar()) { Error("Xml_UnexpectedEOF"); }
if(input.peekChar == 'S' || input.peekChar == 'P')
{
// external id must be preceded by whitespace
if(!hasWS) { Error(/* TODO */); }
// allow only an external id, not a public id
ReadExternalOrPublicID(false, true);
// skip potentially optional whitespace
hasWS = input.SkipWhitespace();
// get the peekChar ready for internal subset check
if(!input.PeekChar()) { Error("Xml_UnexpectedEOF"); }
}
// check for an internal subset
if(input.peekChar == '[')
{
// internal subset must be preceded by whitespace
if(!hasWS) { Error(/* TODO */); }
// move input to '['
input.NextChar();
// push the internal subset log onto the log stack
input.Logger.Push(new StringBuilder());
// read the internal subset
ReadInternalSubset();
// get the internal subset from the log and pop it from the logger
context.InternalSubset = input.Logger.Pop().ToString();
// skip optional whitespace
input.SkipWhitespace();
}
// the dtd must end with '>' at this point
input.Expect('>');
}
// Read attribute definitions.
//
// Already read: ''
[TODO]
private void ReadAttributeDefinitions()
{
// TODO: add support for a dtd rule handling object
// read an arbitrary number of attribute definitions
while(true)
{
// skip potentially optional whitespace
bool hasWS = input.SkipWhitespace();
// check for the end of the attribute list
if(!input.PeekChar()) { Error("Xml_UnexpectedEOF"); }
if(input.peekChar == '>') { return; }
// the attribute name must be preceded by whitespace
if(!hasWS) { Error(/* TODO */); }
// read the attribute name
input.ReadName();
// the attribute type must be preceded by whitespace
if(!input.SkipWhitespace()) { Error(/* TODO */); }
// read the attribute type
ReadAttributeType();
// the default declaration must be preceded by whitespace
if(!input.SkipWhitespace()) { Error(/* TODO */); }
// read the default declaration
ReadDefaultDeclaration();
}
}
// Read an attribute list declaration.
//
// Already read: '<!ATTLIST'
[TODO]
private void ReadAttributeListDeclaration()
{
// TODO: add support for a dtd rule handling object
// the element name must be preceded by whitespace
if(!input.SkipWhitespace()) { Error(/* TODO */); }
// read the element name
input.ReadName();
// read the attribute definitions
ReadAttributeDefinitions();
#if !ECMA_COMPAT
// part of validity checks
input.EndTag();
#endif
// the attribute list must end with '>' at this point
input.Expect('>');
}
// Read an attribute type.
//
// Already read: ''
[TODO]
private void ReadAttributeType()
{
// TODO: add support for a dtd rule handling object
// handle all the possible attribute types
if(!input.NextChar()) { Error("Xml_UnexpectedEOF"); }
switch(input.currChar)
{
// handle CDATA case
case 'C':
{
// TODO: handle CDATA case here
input.Expect("DATA");
}
break;
// handle ID, IDREF, and IDREFS cases
case 'I':
{
input.Expect('D');
if(!input.PeekChar()) { Error("Xml_UnexpectedEOF"); }
if(input.peekChar == 'R')
{
input.Expect("REF");
if(!input.PeekChar()) { Error("Xml_UnexpectedEOF"); }
if(input.peekChar == 'S')
{
// TODO: handle IDREFS case here
input.NextChar();
}
#if !ECMA_COMPAT
else
{
// TODO: handle IDREF case here
}
#endif
}
#if !ECMA_COMPAT
else
{
// TODO: handle ID case here
}
#endif
}
break;
// handle ENTITY and ENTITIES cases
case 'E':
{
input.Expect("NTIT");
if(!input.PeekChar()) { Error("Xml_UnexpectedEOF"); }
if(input.peekChar == 'Y')
{
// TODO: handle ENTITY case here
input.NextChar();
}
else
{
// TODO: handle ENTITIES case here
input.Expect("IES");
}
}
break;
// handle NMTOKEN, NMTOKENS, and NOTATION cases
case 'N':
{
if(!input.PeekChar()) { Error("Xml_UnexpectedEOF"); }
if(input.peekChar == 'M')
{
input.Expect("MTOKEN");
if(!input.PeekChar()) { Error("Xml_UnexpectedEOF"); }
if(input.peekChar == 'S')
{
// TODO: handle NMTOKENS case here
input.NextChar();
}
#if !ECMA_COMPAT
else
{
// TODO: handle NMTOKEN case here
}
#endif
}
else
{
// TODO: handle NOTATION case here
input.Expect("OTATION");
// enumeration must be preceded by whitespace
if(!input.SkipWhitespace()) { Error(/* TODO */); }
// the enumeration starts with a '(' character
input.Expect('(');
// skip optional whitespace and read the first name
input.SkipWhitespace();
input.ReadName();
input.SkipWhitespace();
// read additional names
while(input.NextChar() && input.currChar == '|')
{
// skip optional whitespace and read a name
input.SkipWhitespace();
input.ReadName();
input.SkipWhitespace();
}
// the enumeration must end with ')' at this point
if(input.currChar != ')') { Error(/* TODO */); }
}
}
break;
// handle enumeration case
default:
{
// TODO: handle enumeration case here
// the enumeration starts with a '(' character
input.Expect('(');
// skip optional whitespace and read the first name token
input.SkipWhitespace();
input.ReadNameToken();
input.SkipWhitespace();
// read additional name tokens
while(input.NextChar() && input.currChar == '|')
{
// skip optional whitespace and read a name token
input.SkipWhitespace();
input.ReadNameToken();
input.SkipWhitespace();
}
// the enumeration must end with ')' at this point
if(input.currChar != ')') { Error(/* TODO */); }
}
break;
}
}
// Read an attribute value literal.
//
// Already read: ''
[TODO]
private void ReadAttributeValue()
{
// TODO: add support for a dtd rule handling object
// scan for a valid quote character
if(!input.NextChar()) { Error("Xml_UnexpectedEOF"); }
char quoteChar = input.currChar;
if(quoteChar != '"' && quoteChar != '\'')
{
Error(/* TODO */);
}
// pe scanning on string literals isn't handled inline
input.ScanForPE = false;
// read until we hit the quote character
while(input.NextChar() && input.currChar != quoteChar)
{
// TODO: do something with what we read here
}
// turn inline pe scanning back on
input.ScanForPE = true;
// we hit eof, otherwise we'd have quoteChar, so give an error
if(input.currChar != quoteChar) { Error("Xml_UnexpectedEOF"); }
}
// Read a choice or sequence.
//
// Already read: '('
[TODO]
private void ReadChoiceOrSequence()
{
// TODO: add support for a dtd rule handling object
// skip optional whitespace and read the first content particle
input.SkipWhitespace();
ReadContentParticle();
input.SkipWhitespace();
// scan for a separator or finish with the ')' character
if(!input.NextChar()) { Error("Xml_UnexpectedEOF"); }
char separator = (char)0;
if(input.currChar == ')')
{
return;
}
else if(input.currChar == '|' || input.currChar == ',')
{
// store the separator
separator = input.currChar;
// skip optional whitespace and read the second cp
input.SkipWhitespace();
ReadContentParticle();
input.SkipWhitespace();
}
else
{
Error(/* TODO */);
// Shouldnt reach here.
separator = (char)0;
}
// read until we've consumed all the content particles
while(input.NextChar() && input.currChar == separator)
{
// skip optional whitespace and read a content particle
input.SkipWhitespace();
ReadContentParticle();
input.SkipWhitespace();
}
// the choice or sequence must end with ')' at this point
if(input.currChar != ')') { Error(/* TODO */); }
}
// Read a comment.
//
// Already read: '<!--'
[TODO]
private void ReadComment()
{
// turn pe scanning off inside comments
input.ScanForPE = false;
// read until we hit '-->'
while(input.NextChar())
{
if(input.currChar == '-')
{
if(!input.NextChar()) { Error("Xml_UnexpectedEOF"); }
if(input.currChar == '-')
{
#if !ECMA_COMPAT
// part of validity checks
input.EndTag();
#endif
input.Expect('>');
// turn pe scanning back on
input.ScanForPE = true;
return;
}
}
}
Error("Xml_UnexpectedEOF");
}
// Read a content particle.
//
// Already read: ''
[TODO]
private void ReadContentParticle()
{
// TODO: add support for a dtd rule handling object
// check for a choice or sequence, otherwise expect a name
if(!input.PeekChar()) { Error("Xml_UnexpectedEOF"); }
if(input.peekChar == '(')
{
input.NextChar();
ReadChoiceOrSequence();
}
else
{
input.ReadName();
}
// check for optional occurance modifiers
if(!input.PeekChar()) { Error("Xml_UnexpectedEOF"); }
switch(input.peekChar)
{
case '?':
case '*':
case '+':
{
input.NextChar();
}
break;
}
}
// Read a content specification.
//
// Already read: ''
[TODO]
private void ReadContentSpecification()
{
// TODO: add support for a dtd rule handling object
// handle all the possible content specs
if(!input.PeekChar()) { Error("Xml_UnexpectedEOF"); }
switch(input.peekChar)
{
// handle EMPTY case
case 'E':
{
// TODO: handle EMPTY case here
input.Expect("EMPTY");
}
break;
// handle ANY case
case 'A':
{
// TODO: handle ANY case here
input.Expect("ANY");
}
break;
// handle Mixed and children cases
default:
{
// both cases must start with a '(' character
input.Expect('(');
// skip optional whitespace
input.SkipWhitespace();
// check for Mixed or children
if(!input.PeekChar()) { Error("Xml_UnexpectedEOF"); }
if(input.peekChar == '#')
{
// TODO: handle Mixed case here
// require '#PCDATA' at this point
input.Expect("#PCDATA");
// skip optional whitespace
input.SkipWhitespace();
// check for the finishing ')' character
if(!input.PeekChar()) { Error("Xml_UnexpectedEOF"); }
if(input.peekChar == ')')
{
input.NextChar();
return;
}
// read until we've consumed all the names
while(input.NextChar() && input.currChar == '|')
{
// skip optional whitespace and read a name
input.SkipWhitespace();
input.ReadName();
input.SkipWhitespace();
}
// the Mixed case must end with ')*' at this point
if(input.currChar != ')') { Error(/* TODO */); }
input.Expect('*');
}
else
{
// TODO: handle children case here
// read a choice or sequence
ReadChoiceOrSequence();
// read optional occurance modifiers
if(!input.PeekChar()) { Error("Xml_UnexpectedEOF"); }
switch(input.peekChar)
{
case '?':
case '*':
case '+':
{
input.NextChar();
}
break;
}
}
}
break;
}
}
// Read a default declaration.
//
// Already read: ''
[TODO]
private void ReadDefaultDeclaration()
{
// TODO: add support for a dtd rule handling object
// handle all the possible default declarations
if(!input.PeekChar()) { Error("Xml_UnexpectedEOF"); }
if(input.peekChar == '#')
{
input.NextChar();
if(!input.PeekChar()) { Error("Xml_UnexpectedEOF"); }
switch(input.peekChar)
{
// handle #REQUIRED case
case 'R':
{
// TODO: handle #REQUIRED case here
input.Expect("REQUIRED");
}
break;
// handle #IMPLIED case
case 'I':
{
// TODO: handle #IMPLIED case here
input.Expect("IMPLIED");
}
break;
// handle #FIXED case
default:
{
// TODO: handle #FIXED case here
input.Expect("FIXED");
// require whitespace followed by an attribute value
if(!input.SkipWhitespace()) { Error(/* TODO */); }
ReadAttributeValue();
}
break;
}
}
else
{
// TODO: handle attribute value case here
ReadAttributeValue();
}
}
// Read an element declaration.
//
// Already read: '<!ELEMENT'
[TODO]
private void ReadElementDeclaration()
{
// TODO: add support for a dtd rule handling object
// require whitespace, then read the name
if(!input.SkipWhitespace()) { Error(/* TODO */); }
String name = input.ReadName();
// require whitespace, then read the content specification
if(!input.SkipWhitespace()) { Error(/* TODO */); }
ReadContentSpecification();
// skip optional whitespace
input.SkipWhitespace();
#if !ECMA_COMPAT
// part of validity checks
input.EndTag();
#endif
// the element declaration must end with '>' at this point
input.Expect('>');
}
// Read an entity declaration.
//
// Already read: '<!ENTITY'
[TODO]
private void ReadEntityDeclaration()
{
// TODO: add support for a dtd rule handling object
// skip required whitespace
if(!input.SkipWhitespace()) { Error(/* TODO */); }
// check for parameter or general entity
if(!input.PeekChar()) { Error("Xml_UnexpectedEOF"); }
if(input.peekChar == '%')
{
input.NextChar();
// skip required whitespace and read the entity name
if(!input.SkipWhitespace()) { Error(/* TODO */); }
String name = input.ReadName();
if(!input.SkipWhitespace()) { Error(/* TODO */); }
// read the entity definition
String value = ReadEntityDefinition(true);
// add the pe to the pe table
if(value != null)
{
input.ParameterEntities[name] = value;
}
}
else
{
// read the entity name
input.ReadName();
// skip required whitespace
if(!input.SkipWhitespace()) { Error(/* TODO */); }
// read the entity definition
ReadEntityDefinition(false);
}
// skip optional whitespace
input.SkipWhitespace();
#if !ECMA_COMPAT
// part of validity checks
input.EndTag();
#endif
// the entity declaration must end with '>' at this point
input.Expect('>');
}
// Read a parameter or general entity definition.
//
// Already read: ''
[TODO]
private String ReadEntityDefinition(bool parameter)
{
// TODO: add support for a dtd rule handling object
// check for an entity value or external id
if(!input.PeekChar()) { Error("Xml_UnexpectedEOF"); }
char quoteChar = input.peekChar;
if(quoteChar != '"' && quoteChar != '\'')
{
// read external id
ReadExternalOrPublicID(false);
// read optional notation data declaration
if(!parameter)
{
// skip potentially optional whitespace
bool hasWS = input.SkipWhitespace();
// check for and read the notation data declaration
if(!input.PeekChar()) { Error("Xml_UnexpectedEOF"); }
if(input.peekChar == 'N')
{
// the declaration must be preceded by whitespace
if(!hasWS) { Error(/* TODO */); }
// require 'NDATA' at this point
input.Expect("NDATA");
// skip required whitespace
if(!input.SkipWhitespace()) { Error(/* TODO */); }
// read the name
input.ReadName();
}
}
return null;
}
else
{
// move to quote character
input.NextChar();
// pe scanning on string literals isn't handled inline
input.ScanForPE = false;
// create our log and push it onto the logger's log stack
StringBuilder log = new StringBuilder();
input.Logger.Push(log);
// read until we hit the quote character
while(input.PeekChar() && input.peekChar != quoteChar)
{
input.NextChar();
}
// pop the log from the log stack
input.Logger.Pop();
// the entity value must be properly terminated
input.Expect(quoteChar);
// turn inline pe scanning back on
input.ScanForPE = true;
// return the entity value contents
return log.ToString();
}
}
// Read an external or public id.
//
// Already read: ''
private void ReadExternalOrPublicID(bool allowPub)
{
ReadExternalOrPublicID(allowPub, false);
}
[TODO]
private void ReadExternalOrPublicID(bool allowPub, bool setContext)
{
// TODO: load external subsets and parse them...
// remember not to log them in the internal subset log
// handle 'SYSTEM' or 'PUBLIC'
if(!input.NextChar()) { Error("Xml_UnexpectedEOF"); }
if(input.currChar == 'S')
{
// require that the input match 'SYSTEM'
input.Expect("YSTEM");
// require whitespace
if(!input.SkipWhitespace()) { Error(/* TODO */); }
// scan for a valid quote character
if(!input.NextChar()) { Error("Xml_UnexpectedEOF"); }
char quoteChar = input.currChar;
if(quoteChar != '"' && quoteChar != '\'')
{
Error(/* TODO */);
}
// pe scanning on string literals isn't handled inline
input.ScanForPE = false;
// create our log and push it onto the log stack
StringBuilder log = new StringBuilder();
input.Logger.Push(log);
// read until we hit the quote character
while(input.NextChar() && input.currChar != quoteChar) {}
// we hit eof, otherwise we'd have quoteChar, so give an error
if(input.currChar != quoteChar) { Error("Xml_UnexpectedEOF"); }
// pop the log from the log stack
input.Logger.Pop();
// set the system id
if(setContext) { context.SystemId = log.ToString(); }
// turn inline pe scanning back on
input.ScanForPE = true;
}
else if(input.currChar == 'P')
{
// require that the input match 'PUBLIC'
input.Expect("UBLIC");
// require whitespace
if(!input.SkipWhitespace()) { Error(/* TODO */); }
// scan for a valid quote character
if(!input.NextChar()) { Error("Xml_UnexpectedEOF"); }
char quoteChar = input.currChar;
if(quoteChar != '"' && quoteChar != '\'')
{
Error(/* TODO */);
}
// pe scanning on string literals isn't handled inline
input.ScanForPE = false;
// create our log and push it onto the log stack
StringBuilder log = new StringBuilder();
input.Logger.Push(log);
// read until we hit the quote character
while(input.NextChar() && input.currChar != quoteChar)
{
// ensure we get valid public literal characters
if(!XmlCharInfo.IsPublicId(input.currChar))
{
Error(/* TODO */);
}
}
// we hit eof, otherwise we'd have quoteChar, so give an error
if(input.currChar != quoteChar) { Error("Xml_UnexpectedEOF"); }
// pop the log from the log stack
input.Logger.Pop();
// set the system id
if(setContext) { context.PublicId = log.ToString(); }
// reset the log
log.Length = 0;
// turn inline pe scanning back on
input.ScanForPE = true;
// skip potentially optional whitespace
bool hasWS = input.SkipWhitespace();
// scan for a valid quote character
if(!input.PeekChar()) { Error("Xml_UnexpectedEOF"); }
quoteChar = input.peekChar;
if(quoteChar != '"' && quoteChar != '\'')
{
// this is permitted to end here only for public ids
if(allowPub) { return; }
Error(/* TODO */);
}
input.NextChar();
// the system literal must be preceded by whitespace
if(!hasWS) { Error(/* TODO */); }
// pe scanning on string literals isn't handled inline
input.ScanForPE = false;
// push the log onto the log stack
input.Logger.Push(log);
// read until we hit the quote character
while(input.NextChar() && input.currChar != quoteChar) {}
// we hit eof, otherwise we'd have quoteChar, so give an error
if(input.currChar != quoteChar) { Error("Xml_UnexpectedEOF"); }
// pop the log from the log stack
input.Logger.Pop();
// set the system id
if(setContext) { context.SystemId = log.ToString(); }
// turn inline pe scanning back on
input.ScanForPE = true;
}
else
{
// we didn't see 'SYSTEM' or 'PUBLIC' so give an error
Error(/* TODO */);
}
}
// Read the internal subset of a dtd.
//
// Already read: '['
[TODO]
private void ReadInternalSubset()
{
// turn on pe scanning
input.ScanForPE = true;
// read until we consume all of the internal subset
while(input.PeekChar() && input.peekChar != ']')
{
// read a tag or skip whitespace
if(input.peekChar == '<')
{
input.NextChar();
// read a qmark or emark tag
if(!input.NextChar()) { Error("Xml_UnexpectedEOF"); }
if(input.currChar == '!')
{
// read a declaration or comment
if(!input.NextChar()) { Error("Xml_UnexpectedEOF"); }
switch(input.currChar)
{
// handle ELEMENT and ENTITY cases
case 'E':
{
if(!input.NextChar()) { Error("Xml_UnexpectedEOF"); }
if(input.currChar == 'L')
{
input.Expect("EMENT");
ReadElementDeclaration();
}
else if(input.currChar == 'N')
{
input.Expect("TITY");
ReadEntityDeclaration();
}
else
{
Error(/* TODO */);
}
}
break;
// handle ATTLIST case
case 'A':
{
input.Expect("TTLIST");
ReadAttributeListDeclaration();
}
break;
// handle NOTATION case
case 'N':
{
input.Expect("OTATION");
ReadNotationDeclaration();
}
break;
// handle comment case
case '-':
{
input.Expect('-');
ReadComment();
}
break;
// handle unknown case
default:
{
Error(/* TODO */);
}
break;
}
}
else if(input.currChar == '?')
{
// read a processing instruction
ReadProcessingInstruction();
}
else
{
Error(/* TODO */);
}
}
else if(!input.SkipWhitespace())
{
Error(/* TODO */);
}
}
// turn off pe scanning
input.ScanForPE = false;
// ensure that the ending ']' is not a part of a pe
input.ResetPE();
// the internal subset must end with ']' at this point
StringBuilder log = input.Logger.Pop();
input.Expect(']');
input.Logger.Push(log);
}
// Read a notation declaration.
//
// Already read: '<!NOTATION'
[TODO]
private void ReadNotationDeclaration()
{
// TODO: add support for a dtd rule handling object
// skip required whitespace and read the name
if(!input.SkipWhitespace()) { Error(/* TODO */); }
input.ReadName();
if(!input.SkipWhitespace()) { Error(/* TODO */); }
// read the external id
ReadExternalOrPublicID(false);
// skip optional whitespace
input.SkipWhitespace();
#if !ECMA_COMPAT
// part of validity checks
input.EndTag();
#endif
// the notation declaration must end with '>' at this point
input.Expect('>');
}
// Read a processing instruction.
//
// Already read: '<?'
[TODO]
private void ReadProcessingInstruction()
{
// read the target name
// TODO: check target for ('X'|'x')('M'|'m')('L'|'l')
input.ReadName();
// turn off pe scanning
input.ScanForPE = false;
// skip potentially optional whitespace
bool hasWS = input.SkipWhitespace();
// check for the closing characters
if(!input.NextChar()) { Error("Xml_UnexpectedEOF"); }
if(!input.PeekChar()) { Error("Xml_UnexpectedEOF"); }
if(input.currChar == '?' && input.peekChar == '>')
{
#if !ECMA_COMPAT
// part of validity checks
input.EndTag();
#endif
input.NextChar();
return;
}
// pi content must be preceded by whitespace
if(!hasWS) { Error(/* TODO */); }
// read until we consume all of the pi content
while(input.NextChar() && input.PeekChar())
{
if(input.currChar == '?' && input.peekChar == '>')
{
#if !ECMA_COMPAT
// part of validity checks
input.EndTag();
#endif
// turn on pe scanning
input.ScanForPE = true;
input.NextChar();
return;
}
}
// if we make it this far, we hit eof
Error("Xml_UnexpectedEOF");
}
}; // class XmlDTDReader
}; // namespace System.Xml.Private
| |
/*
* @author Valentin Simonov / http://va.lent.in/
*/
using System.Collections.Generic;
using TouchScript.Utils;
using UnityEngine;
namespace TouchScript.Behaviors.Visualizer
{
/// <summary>
/// <para>Touch visualizer which shows touch circles with debug text using Unity UI.</para>
/// <para>The script should be placed on an element with RectTransform or a Canvas. A reference prefab is provided in TouchScript package.</para>
/// </summary>
[HelpURL("http://touchscript.github.io/docs/html/T_TouchScript_Behaviors_TouchVisualizer.htm")]
public class TouchVisualizer : MonoBehaviour
{
#region Public properties
/// <summary>
/// Gets or sets touch UI element prefab which represents a touch on screen.
/// </summary>
/// <value> A prefab with a script derived from TouchProxyBase. </value>
public TouchProxyBase TouchProxy
{
get { return touchProxy; }
set
{
touchProxy = value;
updateDefaultSize();
}
}
/// <summary>
/// Gets or sets a value indicating whether touch id text should be displayed on screen.
/// </summary>
/// <value> <c>true</c> if touch id text should be displayed on screen; otherwise, <c>false</c>. </value>
public bool ShowTouchId
{
get { return showTouchId; }
set { showTouchId = value; }
}
/// <summary>
/// Gets or sets a value indicating whether touch tags text should be displayed on screen.
/// </summary>
/// <value> <c>true</c> if touch tags text should be displayed on screen; otherwise, <c>false</c>. </value>
public bool ShowTags
{
get { return showTags; }
set { showTags = value; }
}
/// <summary>
/// Gets or sets whether <see cref="TouchVisualizer"/> is using DPI to scale touch cursors.
/// </summary>
/// <value> <c>true</c> if DPI value is used; otherwise, <c>false</c>. </value>
public bool UseDPI
{
get { return useDPI; }
set { useDPI = value; }
}
/// <summary>
/// Gets or sets the size of touch cursors in cm. This value is only used when <see cref="UseDPI"/> is set to <c>true</c>.
/// </summary>
/// <value> The size of touch cursors in cm. </value>
public float TouchSize
{
get { return touchSize; }
set { touchSize = value; }
}
#endregion
#region Private variables
[SerializeField]
private TouchProxyBase touchProxy;
[SerializeField]
private bool showTouchId = true;
[SerializeField]
private bool showTags = false;
[SerializeField]
private bool useDPI = true;
[SerializeField]
private float touchSize = 1f;
private int defaultSize = 64;
private RectTransform rect;
private ObjectPool<TouchProxyBase> pool;
private Dictionary<int, TouchProxyBase> proxies = new Dictionary<int, TouchProxyBase>(10);
#endregion
#region Unity methods
private void Awake()
{
pool = new ObjectPool<TouchProxyBase>(10, instantiateProxy, null, clearProxy);
rect = transform as RectTransform;
if (rect == null)
{
Debug.LogError("TouchVisualizer must be on an UI element!");
enabled = false;
}
updateDefaultSize();
}
private void OnEnable()
{
if (TouchManager.Instance != null)
{
TouchManager.Instance.TouchesBegan += touchesBeganHandler;
TouchManager.Instance.TouchesEnded += touchesEndedHandler;
TouchManager.Instance.TouchesMoved += touchesMovedHandler;
TouchManager.Instance.TouchesCancelled += touchesCancelledHandler;
}
}
private void OnDisable()
{
if (TouchManager.Instance != null)
{
TouchManager.Instance.TouchesBegan -= touchesBeganHandler;
TouchManager.Instance.TouchesEnded -= touchesEndedHandler;
TouchManager.Instance.TouchesMoved -= touchesMovedHandler;
TouchManager.Instance.TouchesCancelled -= touchesCancelledHandler;
}
}
#endregion
#region Private functions
private TouchProxyBase instantiateProxy()
{
return Instantiate(touchProxy);
}
private void clearProxy(TouchProxyBase proxy)
{
proxy.Hide();
}
private int getTouchSize()
{
if (useDPI) return (int) (touchSize * TouchManager.Instance.DotsPerCentimeter);
return defaultSize;
}
private void updateDefaultSize()
{
if (touchProxy != null)
{
var rt = touchProxy.GetComponent<RectTransform>();
if (rt) defaultSize = (int) rt.sizeDelta.x;
}
}
#endregion
#region Event handlers
private void touchesBeganHandler(object sender, TouchEventArgs e)
{
if (touchProxy == null) return;
var count = e.Touches.Count;
for (var i = 0; i < count; i++)
{
var touch = e.Touches[i];
var proxy = pool.Get();
proxy.Size = getTouchSize();
proxy.ShowTouchId = showTouchId;
proxy.ShowTags = showTags;
proxy.Init(rect, touch);
proxies.Add(touch.Id, proxy);
}
}
private void touchesMovedHandler(object sender, TouchEventArgs e)
{
var count = e.Touches.Count;
for (var i = 0; i < count; i++)
{
var touch = e.Touches[i];
TouchProxyBase proxy;
if (!proxies.TryGetValue(touch.Id, out proxy)) return;
proxy.UpdateTouch(touch);
}
}
private void touchesEndedHandler(object sender, TouchEventArgs e)
{
var count = e.Touches.Count;
for (var i = 0; i < count; i++)
{
var touch = e.Touches[i];
TouchProxyBase proxy;
if (!proxies.TryGetValue(touch.Id, out proxy)) return;
proxies.Remove(touch.Id);
pool.Release(proxy);
}
}
private void touchesCancelledHandler(object sender, TouchEventArgs e)
{
touchesEndedHandler(sender, e);
}
#endregion
}
}
| |
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.Conditions
{
using System;
using System.Globalization;
/// <summary>
/// Condition relational (<b>==</b>, <b>!=</b>, <b><</b>, <b><=</b>,
/// <b>></b> or <b>>=</b>) expression.
/// </summary>
internal sealed class ConditionRelationalExpression : ConditionExpression
{
/// <summary>
/// Initializes a new instance of the <see cref="ConditionRelationalExpression" /> class.
/// </summary>
/// <param name="leftExpression">The left expression.</param>
/// <param name="rightExpression">The right expression.</param>
/// <param name="relationalOperator">The relational operator.</param>
public ConditionRelationalExpression(ConditionExpression leftExpression, ConditionExpression rightExpression, ConditionRelationalOperator relationalOperator)
{
this.LeftExpression = leftExpression;
this.RightExpression = rightExpression;
this.RelationalOperator = relationalOperator;
}
/// <summary>
/// Gets the left expression.
/// </summary>
/// <value>The left expression.</value>
public ConditionExpression LeftExpression { get; private set; }
/// <summary>
/// Gets the right expression.
/// </summary>
/// <value>The right expression.</value>
public ConditionExpression RightExpression { get; private set; }
/// <summary>
/// Gets the relational operator.
/// </summary>
/// <value>The operator.</value>
public ConditionRelationalOperator RelationalOperator { get; private set; }
/// <summary>
/// Returns a string representation of the expression.
/// </summary>
/// <returns>
/// A <see cref="T:System.String"/> that represents the condition expression.
/// </returns>
public override string ToString()
{
return "(" + this.LeftExpression + " " + this.GetOperatorString() + " " + this.RightExpression + ")";
}
/// <summary>
/// Evaluates the expression.
/// </summary>
/// <param name="context">Evaluation context.</param>
/// <returns>Expression result.</returns>
protected override object EvaluateNode(LogEventInfo context)
{
object v1 = this.LeftExpression.Evaluate(context);
object v2 = this.RightExpression.Evaluate(context);
return Compare(v1, v2, this.RelationalOperator);
}
/// <summary>
/// Compares the specified values using specified relational operator.
/// </summary>
/// <param name="leftValue">The first value.</param>
/// <param name="rightValue">The second value.</param>
/// <param name="relationalOperator">The relational operator.</param>
/// <returns>Result of the given relational operator.</returns>
private static object Compare(object leftValue, object rightValue, ConditionRelationalOperator relationalOperator)
{
StringComparer comparer = StringComparer.InvariantCulture;
PromoteTypes(ref leftValue, ref rightValue);
switch (relationalOperator)
{
case ConditionRelationalOperator.Equal:
return comparer.Compare(leftValue, rightValue) == 0;
case ConditionRelationalOperator.NotEqual:
return comparer.Compare(leftValue, rightValue) != 0;
case ConditionRelationalOperator.Greater:
return comparer.Compare(leftValue, rightValue) > 0;
case ConditionRelationalOperator.GreaterOrEqual:
return comparer.Compare(leftValue, rightValue) >= 0;
case ConditionRelationalOperator.LessOrEqual:
return comparer.Compare(leftValue, rightValue) <= 0;
case ConditionRelationalOperator.Less:
return comparer.Compare(leftValue, rightValue) < 0;
default:
throw new NotSupportedException("Relational operator " + relationalOperator + " is not supported.");
}
}
private static void PromoteTypes(ref object val1, ref object val2)
{
if (val1 == null || val2 == null)
{
return;
}
if (val1.GetType() == val2.GetType())
{
return;
}
if (val1 is DateTime || val2 is DateTime)
{
val1 = Convert.ToDateTime(val1, CultureInfo.InvariantCulture);
val2 = Convert.ToDateTime(val2, CultureInfo.InvariantCulture);
return;
}
if (val1 is string || val2 is string)
{
val1 = Convert.ToString(val1, CultureInfo.InvariantCulture);
val2 = Convert.ToString(val2, CultureInfo.InvariantCulture);
return;
}
if (val1 is double || val2 is double)
{
val1 = Convert.ToDouble(val1, CultureInfo.InvariantCulture);
val2 = Convert.ToDouble(val2, CultureInfo.InvariantCulture);
return;
}
if (val1 is float || val2 is float)
{
val1 = Convert.ToSingle(val1, CultureInfo.InvariantCulture);
val2 = Convert.ToSingle(val2, CultureInfo.InvariantCulture);
return;
}
if (val1 is decimal || val2 is decimal)
{
val1 = Convert.ToDecimal(val1, CultureInfo.InvariantCulture);
val2 = Convert.ToDecimal(val2, CultureInfo.InvariantCulture);
return;
}
if (val1 is long || val2 is long)
{
val1 = Convert.ToInt64(val1, CultureInfo.InvariantCulture);
val2 = Convert.ToInt64(val2, CultureInfo.InvariantCulture);
return;
}
if (val1 is int || val2 is int)
{
val1 = Convert.ToInt32(val1, CultureInfo.InvariantCulture);
val2 = Convert.ToInt32(val2, CultureInfo.InvariantCulture);
return;
}
if (val1 is bool || val2 is bool)
{
val1 = Convert.ToBoolean(val1, CultureInfo.InvariantCulture);
val2 = Convert.ToBoolean(val2, CultureInfo.InvariantCulture);
return;
}
throw new ConditionEvaluationException("Cannot find common type for '" + val1.GetType().Name + "' and '" + val2.GetType().Name + "'.");
}
private string GetOperatorString()
{
switch (this.RelationalOperator)
{
case ConditionRelationalOperator.Equal:
return "==";
case ConditionRelationalOperator.NotEqual:
return "!=";
case ConditionRelationalOperator.Greater:
return ">";
case ConditionRelationalOperator.Less:
return "<";
case ConditionRelationalOperator.GreaterOrEqual:
return ">=";
case ConditionRelationalOperator.LessOrEqual:
return "<=";
default:
throw new NotSupportedException("Relational operator " + this.RelationalOperator + " is not supported.");
}
}
}
}
| |
#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.Configuration;
using System.Reflection;
using log4net.Util;
using log4net.Repository;
namespace log4net.Core
{
/// <summary>
/// Static manager that controls the creation of repositories
/// </summary>
/// <remarks>
/// <para>
/// Static manager that controls the creation of repositories
/// </para>
/// <para>
/// This class is used by the wrapper managers (e.g. <see cref="log4net.LogManager"/>)
/// to provide access to the <see cref="ILogger"/> objects.
/// </para>
/// <para>
/// This manager also holds the <see cref="IRepositorySelector"/> that is used to
/// lookup and create repositories. The selector can be set either programmatically using
/// the <see cref="RepositorySelector"/> property, or by setting the <c>log4net.RepositorySelector</c>
/// AppSetting in the applications config file to the fully qualified type name of the
/// selector to use.
/// </para>
/// </remarks>
/// <author>Nicko Cadell</author>
/// <author>Gert Driesen</author>
public sealed class LoggerManager
{
#region Private Instance Constructors
/// <summary>
/// Private constructor to prevent instances. Only static methods should be used.
/// </summary>
/// <remarks>
/// <para>
/// Private constructor to prevent instances. Only static methods should be used.
/// </para>
/// </remarks>
private LoggerManager()
{
}
#endregion Private Instance Constructors
#region Static Constructor
/// <summary>
/// Hook the shutdown event
/// </summary>
/// <remarks>
/// <para>
/// On the full .NET runtime, the static constructor hooks up the
/// <c>AppDomain.ProcessExit</c> and <c>AppDomain.DomainUnload</c>> events.
/// These are used to shutdown the log4net system as the application exits.
/// </para>
/// </remarks>
static LoggerManager()
{
try
{
// Register the AppDomain events, note we have to do this with a
// method call rather than directly here because the AppDomain
// makes a LinkDemand which throws the exception during the JIT phase.
RegisterAppDomainEvents();
}
catch(System.Security.SecurityException)
{
LogLog.Debug(declaringType, "Security Exception (ControlAppDomain LinkDemand) while trying "+
"to register Shutdown handler with the AppDomain. LoggerManager.Shutdown() "+
"will not be called automatically when the AppDomain exits. It must be called "+
"programmatically.");
}
// Dump out our assembly version into the log if debug is enabled
LogLog.Debug(declaringType, GetVersionInfo());
// Set the default repository selector
#if NETCF
s_repositorySelector = new CompactRepositorySelector(typeof(log4net.Repository.Hierarchy.Hierarchy));
#else
// Look for the RepositorySelector type specified in the AppSettings 'log4net.RepositorySelector'
string appRepositorySelectorTypeName = SystemInfo.GetAppSetting("log4net.RepositorySelector");
if (appRepositorySelectorTypeName != null && appRepositorySelectorTypeName.Length > 0)
{
// Resolve the config string into a Type
Type appRepositorySelectorType = null;
try
{
appRepositorySelectorType = SystemInfo.GetTypeFromString(appRepositorySelectorTypeName, false, true);
}
catch(Exception ex)
{
LogLog.Error(declaringType, "Exception while resolving RepositorySelector Type ["+appRepositorySelectorTypeName+"]", ex);
}
if (appRepositorySelectorType != null)
{
// Create an instance of the RepositorySelectorType
object appRepositorySelectorObj = null;
try
{
appRepositorySelectorObj = Activator.CreateInstance(appRepositorySelectorType);
}
catch(Exception ex)
{
LogLog.Error(declaringType, "Exception while creating RepositorySelector ["+appRepositorySelectorType.FullName+"]", ex);
}
if (appRepositorySelectorObj != null && appRepositorySelectorObj is IRepositorySelector)
{
s_repositorySelector = (IRepositorySelector)appRepositorySelectorObj;
}
else
{
LogLog.Error(declaringType, "RepositorySelector Type ["+appRepositorySelectorType.FullName+"] is not an IRepositorySelector");
}
}
}
// Create the DefaultRepositorySelector if not configured above
if (s_repositorySelector == null)
{
s_repositorySelector = new DefaultRepositorySelector(typeof(log4net.Repository.Hierarchy.Hierarchy));
}
#endif
}
/// <summary>
/// Register for ProcessExit and DomainUnload events on the AppDomain
/// </summary>
/// <remarks>
/// <para>
/// This needs to be in a separate method because the events make
/// a LinkDemand for the ControlAppDomain SecurityPermission. Because
/// this is a LinkDemand it is demanded at JIT time. Therefore we cannot
/// catch the exception in the method itself, we have to catch it in the
/// caller.
/// </para>
/// </remarks>
private static void RegisterAppDomainEvents()
{
#if !NETCF
// ProcessExit seems to be fired if we are part of the default domain
AppDomain.CurrentDomain.ProcessExit += new EventHandler(OnProcessExit);
// Otherwise DomainUnload is fired
AppDomain.CurrentDomain.DomainUnload += new EventHandler(OnDomainUnload);
#endif
}
#endregion Static Constructor
#region Public Static Methods
/// <summary>
/// Return the default <see cref="ILoggerRepository"/> instance.
/// </summary>
/// <param name="repository">the repository to lookup in</param>
/// <returns>Return the default <see cref="ILoggerRepository"/> instance</returns>
/// <remarks>
/// <para>
/// Gets the <see cref="ILoggerRepository"/> for the repository specified
/// by the <paramref name="repository"/> argument.
/// </para>
/// </remarks>
public static ILoggerRepository GetRepository(string repository)
{
if (repository == null)
{
throw new ArgumentNullException("repository");
}
return RepositorySelector.GetRepository(repository);
}
/// <summary>
/// Returns the default <see cref="ILoggerRepository"/> instance.
/// </summary>
/// <param name="repositoryAssembly">The assembly to use to lookup the repository.</param>
/// <returns>The default <see cref="ILoggerRepository"/> instance.</returns>
/// <remarks>
/// <para>
/// Returns the default <see cref="ILoggerRepository"/> instance.
/// </para>
/// </remarks>
public static ILoggerRepository GetRepository(Assembly repositoryAssembly)
{
if (repositoryAssembly == null)
{
throw new ArgumentNullException("repositoryAssembly");
}
return RepositorySelector.GetRepository(repositoryAssembly);
}
/// <summary>
/// Returns the named logger if it exists.
/// </summary>
/// <param name="repository">The repository to lookup in.</param>
/// <param name="name">The fully qualified logger name to look for.</param>
/// <returns>
/// The logger found, or <c>null</c> if the named logger does not exist in the
/// specified repository.
/// </returns>
/// <remarks>
/// <para>
/// If the named logger exists (in the specified repository) then it
/// returns a reference to the logger, otherwise it returns
/// <c>null</c>.
/// </para>
/// </remarks>
public static ILogger Exists(string repository, string name)
{
if (repository == null)
{
throw new ArgumentNullException("repository");
}
if (name == null)
{
throw new ArgumentNullException("name");
}
return RepositorySelector.GetRepository(repository).Exists(name);
}
/// <summary>
/// Returns the named logger if it exists.
/// </summary>
/// <param name="repositoryAssembly">The assembly to use to lookup the repository.</param>
/// <param name="name">The fully qualified logger name to look for.</param>
/// <returns>
/// The logger found, or <c>null</c> if the named logger does not exist in the
/// specified assembly's repository.
/// </returns>
/// <remarks>
/// <para>
/// If the named logger exists (in the specified assembly's repository) then it
/// returns a reference to the logger, otherwise it returns
/// <c>null</c>.
/// </para>
/// </remarks>
public static ILogger Exists(Assembly repositoryAssembly, string name)
{
if (repositoryAssembly == null)
{
throw new ArgumentNullException("repositoryAssembly");
}
if (name == null)
{
throw new ArgumentNullException("name");
}
return RepositorySelector.GetRepository(repositoryAssembly).Exists(name);
}
/// <summary>
/// Returns all the currently defined loggers in the specified repository.
/// </summary>
/// <param name="repository">The repository to lookup in.</param>
/// <returns>All the defined loggers.</returns>
/// <remarks>
/// <para>
/// The root logger is <b>not</b> included in the returned array.
/// </para>
/// </remarks>
public static ILogger[] GetCurrentLoggers(string repository)
{
if (repository == null)
{
throw new ArgumentNullException("repository");
}
return RepositorySelector.GetRepository(repository).GetCurrentLoggers();
}
/// <summary>
/// Returns all the currently defined loggers in the specified assembly's repository.
/// </summary>
/// <param name="repositoryAssembly">The assembly to use to lookup the repository.</param>
/// <returns>All the defined loggers.</returns>
/// <remarks>
/// <para>
/// The root logger is <b>not</b> included in the returned array.
/// </para>
/// </remarks>
public static ILogger[] GetCurrentLoggers(Assembly repositoryAssembly)
{
if (repositoryAssembly == null)
{
throw new ArgumentNullException("repositoryAssembly");
}
return RepositorySelector.GetRepository(repositoryAssembly).GetCurrentLoggers();
}
/// <summary>
/// Retrieves or creates a named logger.
/// </summary>
/// <param name="repository">The repository to lookup in.</param>
/// <param name="name">The name of the logger to retrieve.</param>
/// <returns>The logger with the name specified.</returns>
/// <remarks>
/// <para>
/// Retrieves a logger named as the <paramref name="name"/>
/// parameter. If the named logger already exists, then the
/// existing instance will be returned. Otherwise, a new instance is
/// created.
/// </para>
/// <para>
/// By default, loggers do not have a set level but inherit
/// it from the hierarchy. This is one of the central features of
/// log4net.
/// </para>
/// </remarks>
public static ILogger GetLogger(string repository, string name)
{
if (repository == null)
{
throw new ArgumentNullException("repository");
}
if (name == null)
{
throw new ArgumentNullException("name");
}
return RepositorySelector.GetRepository(repository).GetLogger(name);
}
/// <summary>
/// Retrieves or creates a named logger.
/// </summary>
/// <param name="repositoryAssembly">The assembly to use to lookup the repository.</param>
/// <param name="name">The name of the logger to retrieve.</param>
/// <returns>The logger with the name specified.</returns>
/// <remarks>
/// <para>
/// Retrieves a logger named as the <paramref name="name"/>
/// parameter. If the named logger already exists, then the
/// existing instance will be returned. Otherwise, a new instance is
/// created.
/// </para>
/// <para>
/// By default, loggers do not have a set level but inherit
/// it from the hierarchy. This is one of the central features of
/// log4net.
/// </para>
/// </remarks>
public static ILogger GetLogger(Assembly repositoryAssembly, string name)
{
if (repositoryAssembly == null)
{
throw new ArgumentNullException("repositoryAssembly");
}
if (name == null)
{
throw new ArgumentNullException("name");
}
return RepositorySelector.GetRepository(repositoryAssembly).GetLogger(name);
}
/// <summary>
/// Shorthand for <see cref="M:LogManager.GetLogger(string)"/>.
/// </summary>
/// <param name="repository">The repository to lookup in.</param>
/// <param name="type">The <paramref name="type"/> of which the fullname will be used as the name of the logger to retrieve.</param>
/// <returns>The logger with the name specified.</returns>
/// <remarks>
/// <para>
/// Gets the logger for the fully qualified name of the type specified.
/// </para>
/// </remarks>
public static ILogger GetLogger(string repository, Type type)
{
if (repository == null)
{
throw new ArgumentNullException("repository");
}
if (type == null)
{
throw new ArgumentNullException("type");
}
return RepositorySelector.GetRepository(repository).GetLogger(type.FullName);
}
/// <summary>
/// Shorthand for <see cref="M:LogManager.GetLogger(string)"/>.
/// </summary>
/// <param name="repositoryAssembly">the assembly to use to lookup the repository</param>
/// <param name="type">The <paramref name="type"/> of which the fullname will be used as the name of the logger to retrieve.</param>
/// <returns>The logger with the name specified.</returns>
/// <remarks>
/// <para>
/// Gets the logger for the fully qualified name of the type specified.
/// </para>
/// </remarks>
public static ILogger GetLogger(Assembly repositoryAssembly, Type type)
{
if (repositoryAssembly == null)
{
throw new ArgumentNullException("repositoryAssembly");
}
if (type == null)
{
throw new ArgumentNullException("type");
}
return RepositorySelector.GetRepository(repositoryAssembly).GetLogger(type.FullName);
}
/// <summary>
/// Shuts down the log4net system.
/// </summary>
/// <remarks>
/// <para>
/// Calling this method will <b>safely</b> close and remove all
/// appenders in all the loggers including root contained in all the
/// default repositories.
/// </para>
/// <para>
/// Some appenders need to be closed before the application exists.
/// Otherwise, pending logging events might be lost.
/// </para>
/// <para>
/// The <c>shutdown</c> method is careful to close nested
/// appenders before closing regular appenders. This is allows
/// configurations where a regular appender is attached to a logger
/// and again to a nested appender.
/// </para>
/// </remarks>
public static void Shutdown()
{
foreach(ILoggerRepository repository in GetAllRepositories())
{
repository.Shutdown();
}
}
/// <summary>
/// Shuts down the repository for the repository specified.
/// </summary>
/// <param name="repository">The repository to shutdown.</param>
/// <remarks>
/// <para>
/// Calling this method will <b>safely</b> close and remove all
/// appenders in all the loggers including root contained in the
/// repository for the <paramref name="repository"/> specified.
/// </para>
/// <para>
/// Some appenders need to be closed before the application exists.
/// Otherwise, pending logging events might be lost.
/// </para>
/// <para>
/// The <c>shutdown</c> method is careful to close nested
/// appenders before closing regular appenders. This is allows
/// configurations where a regular appender is attached to a logger
/// and again to a nested appender.
/// </para>
/// </remarks>
public static void ShutdownRepository(string repository)
{
if (repository == null)
{
throw new ArgumentNullException("repository");
}
RepositorySelector.GetRepository(repository).Shutdown();
}
/// <summary>
/// Shuts down the repository for the repository specified.
/// </summary>
/// <param name="repositoryAssembly">The assembly to use to lookup the repository.</param>
/// <remarks>
/// <para>
/// Calling this method will <b>safely</b> close and remove all
/// appenders in all the loggers including root contained in the
/// repository for the repository. The repository is looked up using
/// the <paramref name="repositoryAssembly"/> specified.
/// </para>
/// <para>
/// Some appenders need to be closed before the application exists.
/// Otherwise, pending logging events might be lost.
/// </para>
/// <para>
/// The <c>shutdown</c> method is careful to close nested
/// appenders before closing regular appenders. This is allows
/// configurations where a regular appender is attached to a logger
/// and again to a nested appender.
/// </para>
/// </remarks>
public static void ShutdownRepository(Assembly repositoryAssembly)
{
if (repositoryAssembly == null)
{
throw new ArgumentNullException("repositoryAssembly");
}
RepositorySelector.GetRepository(repositoryAssembly).Shutdown();
}
/// <summary>
/// Resets all values contained in this repository instance to their defaults.
/// </summary>
/// <param name="repository">The repository to reset.</param>
/// <remarks>
/// <para>
/// Resets all values contained in the repository instance to their
/// defaults. This removes all appenders from all loggers, sets
/// the level of all non-root loggers to <c>null</c>,
/// sets their additivity flag to <c>true</c> and sets the level
/// of the root logger to <see cref="Level.Debug"/>. Moreover,
/// message disabling is set its default "off" value.
/// </para>
/// </remarks>
public static void ResetConfiguration(string repository)
{
if (repository == null)
{
throw new ArgumentNullException("repository");
}
RepositorySelector.GetRepository(repository).ResetConfiguration();
}
/// <summary>
/// Resets all values contained in this repository instance to their defaults.
/// </summary>
/// <param name="repositoryAssembly">The assembly to use to lookup the repository to reset.</param>
/// <remarks>
/// <para>
/// Resets all values contained in the repository instance to their
/// defaults. This removes all appenders from all loggers, sets
/// the level of all non-root loggers to <c>null</c>,
/// sets their additivity flag to <c>true</c> and sets the level
/// of the root logger to <see cref="Level.Debug"/>. Moreover,
/// message disabling is set its default "off" value.
/// </para>
/// </remarks>
public static void ResetConfiguration(Assembly repositoryAssembly)
{
if (repositoryAssembly == null)
{
throw new ArgumentNullException("repositoryAssembly");
}
RepositorySelector.GetRepository(repositoryAssembly).ResetConfiguration();
}
/// <summary>
/// Creates a repository with the specified name.
/// </summary>
/// <param name="repository">The name of the repository, this must be unique amongst repositories.</param>
/// <returns>The <see cref="ILoggerRepository"/> created for the repository.</returns>
/// <remarks>
/// <para>
/// Creates the default type of <see cref="ILoggerRepository"/> which is a
/// <see cref="log4net.Repository.Hierarchy.Hierarchy"/> object.
/// </para>
/// <para>
/// The <paramref name="repository"/> name must be unique. Repositories cannot be redefined.
/// An <see cref="Exception"/> will be thrown if the repository already exists.
/// </para>
/// </remarks>
/// <exception cref="LogException">The specified repository already exists.</exception>
public static ILoggerRepository CreateRepository(string repository)
{
if (repository == null)
{
throw new ArgumentNullException("repository");
}
return RepositorySelector.CreateRepository(repository, null);
}
/// <summary>
/// Creates a repository with the specified name and repository type.
/// </summary>
/// <param name="repository">The name of the repository, this must be unique to the repository.</param>
/// <param name="repositoryType">A <see cref="Type"/> that implements <see cref="ILoggerRepository"/>
/// and has a no arg constructor. An instance of this type will be created to act
/// as the <see cref="ILoggerRepository"/> for the repository specified.</param>
/// <returns>The <see cref="ILoggerRepository"/> created for the repository.</returns>
/// <remarks>
/// <para>
/// The <paramref name="repository"/> name must be unique. Repositories cannot be redefined.
/// An Exception will be thrown if the repository already exists.
/// </para>
/// </remarks>
/// <exception cref="LogException">The specified repository already exists.</exception>
public static ILoggerRepository CreateRepository(string repository, Type repositoryType)
{
if (repository == null)
{
throw new ArgumentNullException("repository");
}
if (repositoryType == null)
{
throw new ArgumentNullException("repositoryType");
}
return RepositorySelector.CreateRepository(repository, repositoryType);
}
/// <summary>
/// Creates a repository for the specified assembly and repository type.
/// </summary>
/// <param name="repositoryAssembly">The assembly to use to get the name of the repository.</param>
/// <param name="repositoryType">A <see cref="Type"/> that implements <see cref="ILoggerRepository"/>
/// and has a no arg constructor. An instance of this type will be created to act
/// as the <see cref="ILoggerRepository"/> for the repository specified.</param>
/// <returns>The <see cref="ILoggerRepository"/> created for the repository.</returns>
/// <remarks>
/// <para>
/// The <see cref="ILoggerRepository"/> created will be associated with the repository
/// specified such that a call to <see cref="M:GetRepository(Assembly)"/> with the
/// same assembly specified will return the same repository instance.
/// </para>
/// </remarks>
public static ILoggerRepository CreateRepository(Assembly repositoryAssembly, Type repositoryType)
{
if (repositoryAssembly == null)
{
throw new ArgumentNullException("repositoryAssembly");
}
if (repositoryType == null)
{
throw new ArgumentNullException("repositoryType");
}
return RepositorySelector.CreateRepository(repositoryAssembly, repositoryType);
}
/// <summary>
/// Gets an array of all currently defined repositories.
/// </summary>
/// <returns>An array of all the known <see cref="ILoggerRepository"/> objects.</returns>
/// <remarks>
/// <para>
/// Gets an array of all currently defined repositories.
/// </para>
/// </remarks>
public static ILoggerRepository[] GetAllRepositories()
{
return RepositorySelector.GetAllRepositories();
}
/// <summary>
/// Gets or sets the repository selector used by the <see cref="LogManager" />.
/// </summary>
/// <value>
/// The repository selector used by the <see cref="LogManager" />.
/// </value>
/// <remarks>
/// <para>
/// The repository selector (<see cref="IRepositorySelector"/>) is used by
/// the <see cref="LogManager"/> to create and select repositories
/// (<see cref="ILoggerRepository"/>).
/// </para>
/// <para>
/// The caller to <see cref="LogManager"/> supplies either a string name
/// or an assembly (if not supplied the assembly is inferred using
/// <see cref="M:Assembly.GetCallingAssembly()"/>).
/// </para>
/// <para>
/// This context is used by the selector to lookup a specific repository.
/// </para>
/// <para>
/// For the full .NET Framework, the default repository is <c>DefaultRepositorySelector</c>;
/// for the .NET Compact Framework <c>CompactRepositorySelector</c> is the default
/// repository.
/// </para>
/// </remarks>
public static IRepositorySelector RepositorySelector
{
get { return s_repositorySelector; }
set { s_repositorySelector = value; }
}
#endregion Public Static Methods
#region Private Static Methods
/// <summary>
/// Internal method to get pertinent version info.
/// </summary>
/// <returns>A string of version info.</returns>
private static string GetVersionInfo()
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
// Grab the currently executing assembly
Assembly myAssembly = Assembly.GetExecutingAssembly();
// Build Up message
sb.Append("log4net assembly [").Append(myAssembly.FullName).Append("]. ");
sb.Append("Loaded from [").Append(SystemInfo.AssemblyLocationInfo(myAssembly)).Append("]. ");
sb.Append("(.NET Runtime [").Append(Environment.Version.ToString()).Append("]");
sb.Append(" on ").Append(Environment.OSVersion.ToString());
sb.Append(")");
return sb.ToString();
}
#if (!NETCF)
/// <summary>
/// Called when the <see cref="AppDomain.DomainUnload"/> event fires
/// </summary>
/// <param name="sender">the <see cref="AppDomain"/> that is exiting</param>
/// <param name="e">null</param>
/// <remarks>
/// <para>
/// Called when the <see cref="AppDomain.DomainUnload"/> event fires.
/// </para>
/// <para>
/// When the event is triggered the log4net system is <see cref="M:Shutdown()"/>.
/// </para>
/// </remarks>
private static void OnDomainUnload(object sender, EventArgs e)
{
Shutdown();
}
/// <summary>
/// Called when the <see cref="AppDomain.ProcessExit"/> event fires
/// </summary>
/// <param name="sender">the <see cref="AppDomain"/> that is exiting</param>
/// <param name="e">null</param>
/// <remarks>
/// <para>
/// Called when the <see cref="AppDomain.ProcessExit"/> event fires.
/// </para>
/// <para>
/// When the event is triggered the log4net system is <see cref="M:Shutdown()"/>.
/// </para>
/// </remarks>
private static void OnProcessExit(object sender, EventArgs e)
{
Shutdown();
}
#endif
#endregion Private Static Methods
#region Private Static Fields
/// <summary>
/// The fully qualified type of the LoggerManager class.
/// </summary>
/// <remarks>
/// Used by the internal logger to record the Type of the
/// log message.
/// </remarks>
private readonly static Type declaringType = typeof(LoggerManager);
/// <summary>
/// Initialize the default repository selector
/// </summary>
private static IRepositorySelector s_repositorySelector;
#endregion Private Static Fields
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Collections;
using System.Diagnostics;
using System.Drawing;
using OpenLiveWriter.BlogClient.Clients;
using OpenLiveWriter.CoreServices;
using OpenLiveWriter.CoreServices.Settings;
using OpenLiveWriter.Extensibility.BlogClient;
using OpenLiveWriter.Interop.Windows;
using OpenLiveWriter.BlogClient.Providers ;
using OpenLiveWriter.BlogClient.Detection;
namespace OpenLiveWriter.BlogClient
{
public class BlogSettings : IBlogSettingsAccessor, IBlogSettingsDetectionContext, IDisposable
{
public static string[] GetBlogIds()
{
string[] blogIds = SettingsKey.GetSubSettingNames();
for (int i = 0; i < blogIds.Length; i++)
{
if (!BlogIdIsValid(blogIds[i]))
{
blogIds[i] = null;
}
}
return (string[])ArrayHelper.Compact(blogIds);
}
public static BlogDescriptor[] GetBlogs(bool sortByName)
{
string[] ids = GetBlogIds() ;
BlogDescriptor[] blogs = new BlogDescriptor[ids.Length] ;
for ( int i=0; i<ids.Length; i++ )
{
using ( BlogSettings settings = BlogSettings.ForBlogId(ids[i]) )
blogs[i] = new BlogDescriptor( ids[i], settings.BlogName, settings.HomepageUrl ) ;
}
if ( sortByName )
Array.Sort( blogs, new BlogDescriptor.Comparer() ) ;
return blogs ;
}
public static bool BlogIdIsValid(string id)
{
BlogSettings blogSettings = null;
try
{
blogSettings = BlogSettings.ForBlogId(id);
if (!blogSettings.IsValid)
return false;
return BlogClientManager.IsValidClientType(blogSettings.ClientType);
}
catch (ArgumentException)
{
Trace.WriteLine("Default blog has invalid client type, ignoring blog.");
return false;
}
finally
{
if(blogSettings != null)
blogSettings.Dispose();
}
}
public static string DefaultBlogId
{
get
{
// try to get an explicitly set default profile id
string defaultKey = SettingsKey.GetString( DEFAULT_WEBLOG, String.Empty );
// if a default is specified and the key exists
if (BlogIdIsValid(defaultKey))
{
return defaultKey;
}
// if one is not specified then get the first one stored (if any)
// (update the value while doing this so we don't have to repeat
// this calculation)
string[] blogIds = GetBlogIds() ;
if ( blogIds != null && blogIds.Length > 0 )
{
DefaultBlogId = blogIds[0] ;
return blogIds[0] ;
}
else
return String.Empty ;
}
set
{
SettingsKey.SetString( DEFAULT_WEBLOG, value ?? String.Empty);
}
}
public const string DEFAULT_WEBLOG = "DefaultWeblog" ;
public delegate void BlogSettingsListener(string blogId);
public static event BlogSettingsListener BlogSettingsDeleted;
private static void OnBlogSettingsDeleted(string blogId)
{
if(BlogSettingsDeleted != null)
BlogSettingsDeleted(blogId);
}
public static BlogSettings ForBlogId( string id )
{
return new BlogSettings( id ) ;
}
private BlogSettings( string id )
{
try
{
Guid guid = new Guid(id);
_id = guid.ToString();
}
catch(FormatException ex)
{
GC.SuppressFinalize(this);
Trace.WriteLine("Failed to load blog settings for: " + id);
throw new ArgumentException("Invalid Blog Id " + id, ex);
}
}
/// <summary>
/// used as a key into settings storage
/// </summary>
public string Id
{
get
{
return _id;
}
}
private string _id;
public bool IsValid
{
get
{
return SettingsKey.HasSubSettings(Id);
}
}
public bool IsSpacesBlog
{
get { return Settings.GetBoolean( IS_SPACES_BLOG, false); }
set { Settings.SetBoolean( IS_SPACES_BLOG, value); }
}
private const string IS_SPACES_BLOG = "IsSpacesBlog" ;
public bool IsSharePointBlog
{
get { return Settings.GetBoolean( IS_SHAREPOINT_BLOG, false); }
set { Settings.SetBoolean( IS_SHAREPOINT_BLOG, value); }
}
private const string IS_SHAREPOINT_BLOG = "IsSharePointBlog" ;
/// <summary>
/// Id of the weblog on the host service
/// </summary>
public string HostBlogId
{
get { return Settings.GetString( BLOG_ID, String.Empty ) ; }
set { Settings.SetString( BLOG_ID, value ) ; }
}
private const string BLOG_ID = "BlogId" ;
public string BlogName
{
get { return Settings.GetString( BLOG_NAME, String.Empty ) ; }
set { Settings.SetString( BLOG_NAME, value ) ; }
}
private const string BLOG_NAME = "BlogName" ;
public string HomepageUrl
{
get { return Settings.GetString( HOMEPAGE_URL, String.Empty ) ; }
set { Settings.SetString( HOMEPAGE_URL, value ) ; }
}
private const string HOMEPAGE_URL = "HomepageUrl" ;
public bool ForceManualConfig
{
get { return Settings.GetBoolean( FORCE_MANUAL_CONFIG, false ) ; }
set { Settings.SetBoolean( FORCE_MANUAL_CONFIG, value ) ; }
}
private const string FORCE_MANUAL_CONFIG = "ForceManualConfig" ;
public WriterEditingManifestDownloadInfo ManifestDownloadInfo
{
get
{
lock(_manifestDownloadInfoLock)
{
using ( SettingsPersisterHelper manifestKey = Settings.GetSubSettings(WRITER_MANIFEST) )
{
// at a minimum must have a source-url
string sourceUrl = manifestKey.GetString(MANIFEST_SOURCE_URL, String.Empty) ;
if ( sourceUrl != String.Empty )
{
return new WriterEditingManifestDownloadInfo(
sourceUrl,
manifestKey.GetDateTime(MANIFEST_EXPIRES, DateTime.MinValue),
manifestKey.GetDateTime(MANIFEST_LAST_MODIFIED, DateTime.MinValue),
manifestKey.GetString(MANIFEST_ETAG, String.Empty) );
}
else
{
return null ;
}
}
}
}
set
{
lock(_manifestDownloadInfoLock)
{
if ( value != null )
{
using ( SettingsPersisterHelper manifestKey = Settings.GetSubSettings(WRITER_MANIFEST) )
{
manifestKey.SetString(MANIFEST_SOURCE_URL, value.SourceUrl);
manifestKey.SetDateTime(MANIFEST_EXPIRES, value.Expires);
manifestKey.SetDateTime(MANIFEST_LAST_MODIFIED, value.LastModified);
manifestKey.SetString(MANIFEST_ETAG, value.ETag);
}
}
else
{
if ( Settings.HasSubSettings(WRITER_MANIFEST) )
Settings.UnsetSubsettingTree(WRITER_MANIFEST);
}
}
}
}
private const string WRITER_MANIFEST = "Manifest" ;
private const string MANIFEST_SOURCE_URL = "SourceUrl" ;
private const string MANIFEST_EXPIRES = "Expires" ;
private const string MANIFEST_LAST_MODIFIED = "LastModified" ;
private const string MANIFEST_ETAG = "ETag" ;
private readonly static object _manifestDownloadInfoLock = new object();
public string WriterManifestUrl
{
get { return Settings.GetString( WRITER_MANIFEST_URL, String.Empty ) ; }
set { Settings.SetString( WRITER_MANIFEST_URL, value ) ; }
}
private const string WRITER_MANIFEST_URL = "ManifestUrl" ;
public void SetProvider( string providerId, string serviceName )
{
Settings.SetString( PROVIDER_ID, providerId ) ;
Settings.SetString( SERVICE_NAME, serviceName );
}
public string ProviderId
{
get
{
string providerId = Settings.GetString( PROVIDER_ID, String.Empty );
if (providerId == "16B3FA3F-DAD7-4c93-A407-81CAE076883E")
return "5FD58F3F-A36E-4aaf-8ABE-764248961FA0";
else
return providerId ;
}
}
private const string PROVIDER_ID = "ProviderId" ;
public string ServiceName
{
get { return Settings.GetString( SERVICE_NAME, String.Empty ) ; }
}
private const string SERVICE_NAME = "ServiceName" ;
public string ClientType
{
get
{
string clientType = Settings.GetString( CLIENT_TYPE, String.Empty ) ;
// temporary hack for migration of MovableType blogs
// TODO: is there a cleaner place to do this?
if ( clientType == "MoveableType")
return "MovableType" ;
return clientType ;
}
set
{
// TODO:OLW
// Hack to stop old Spaces configs to be violently/accidentally
// upgrading to Atom. At time of this writing, this condition gets
// hit by ServiceUpdateChecker running. This prevents the client
// type from being changed in the registry from WindowsLiveSpaces
// to WindowsLiveSpacesAtom; the only practical effect of letting
// the write go to disk would be that you can't go back to an
// older build of Writer. We don't have perfect forward compatibility
// anyway--going through the config wizard with a Spaces blog will
// also break older builds. But it seems like it's going too far
// that just starting Writer will make that change.
// We can take this out, if desired, anytime after Wave 3 goes final.
if (value == "WindowsLiveSpacesAtom" && Settings.GetString(CLIENT_TYPE, string.Empty) == "WindowsLiveSpaces")
return;
Settings.SetString(CLIENT_TYPE, value);
}
}
private const string CLIENT_TYPE = "ClientType" ;
public string PostApiUrl
{
get { return Settings.GetString( POST_API_URL, String.Empty ) ; }
set { Settings.SetString( POST_API_URL, value ) ; }
}
private const string POST_API_URL = "PostApiUrl" ;
public IDictionary HomePageOverrides
{
get
{
lock (_homepageOptionOverridesLock)
{
IDictionary homepageOptionOverrides = new Hashtable();
// Trying to avoid the creation of this key, so we will know when the service update runs whether we need to build
// these settings for the first time.
if (Settings.HasSubSettings(HOMEPAGE_OPTION_OVERRIDES))
{
using (SettingsPersisterHelper homepageOptionOverridesKey = Settings.GetSubSettings(HOMEPAGE_OPTION_OVERRIDES))
{
foreach (string optionName in homepageOptionOverridesKey.GetNames())
homepageOptionOverrides.Add(optionName, homepageOptionOverridesKey.GetString(optionName, String.Empty));
}
}
return homepageOptionOverrides;
}
}
set
{
lock (_homepageOptionOverridesLock)
{
// delete existing overrides
Settings.UnsetSubsettingTree(HOMEPAGE_OPTION_OVERRIDES);
// re-write overrides
using (SettingsPersisterHelper homepageOptionOverridesKey = Settings.GetSubSettings(HOMEPAGE_OPTION_OVERRIDES))
{
foreach (DictionaryEntry entry in value)
homepageOptionOverridesKey.SetString(entry.Key.ToString(), entry.Value.ToString());
}
}
}
}
private const string HOMEPAGE_OPTION_OVERRIDES = "HomepageOptions";
private readonly static object _homepageOptionOverridesLock = new object();
public IDictionary OptionOverrides
{
get
{
lock( _optionOverridesLock )
{
IDictionary optionOverrides = new Hashtable() ;
using ( SettingsPersisterHelper optionOverridesKey = Settings.GetSubSettings(OPTION_OVERRIDES) )
{
foreach ( string optionName in optionOverridesKey.GetNames() )
optionOverrides.Add(optionName, optionOverridesKey.GetString(optionName, String.Empty ) ) ;
}
return optionOverrides;
}
}
set
{
lock( _optionOverridesLock )
{
// safely delete existing overrides
Settings.UnsetSubsettingTree(OPTION_OVERRIDES) ;
// re-write overrides
using ( SettingsPersisterHelper optionOverridesKey = Settings.GetSubSettings(OPTION_OVERRIDES) )
{
foreach ( DictionaryEntry entry in value )
optionOverridesKey.SetString( entry.Key.ToString(), entry.Value.ToString() ) ;
}
}
}
}
private const string OPTION_OVERRIDES = "ManifestOptions" ;
private readonly static object _optionOverridesLock = new object();
public IDictionary UserOptionOverrides
{
get
{
lock( _userOptionOverridesLock )
{
IDictionary userOptionOverrides = new Hashtable() ;
using ( SettingsPersisterHelper userOptionOverridesKey = Settings.GetSubSettings(USER_OPTION_OVERRIDES) )
{
foreach ( string optionName in userOptionOverridesKey.GetNames() )
userOptionOverrides.Add(optionName, userOptionOverridesKey.GetString(optionName, String.Empty ) ) ;
}
return userOptionOverrides;
}
}
set
{
lock( _userOptionOverridesLock )
{
// delete existing overrides
Settings.UnsetSubsettingTree(USER_OPTION_OVERRIDES);
// re-write overrides
using ( SettingsPersisterHelper userOptionOverridesKey = Settings.GetSubSettings(USER_OPTION_OVERRIDES) )
{
foreach ( DictionaryEntry entry in value )
userOptionOverridesKey.SetString( entry.Key.ToString(), entry.Value.ToString() ) ;
}
}
}
}
private const string USER_OPTION_OVERRIDES = "UserOptionOverrides" ;
private readonly static object _userOptionOverridesLock = new object();
IBlogCredentialsAccessor IBlogSettingsAccessor.Credentials
{
get
{
return new BlogCredentialsAccessor(Id, Credentials) ;
}
}
IBlogCredentialsAccessor IBlogSettingsDetectionContext.Credentials
{
get
{
return (this as IBlogSettingsAccessor).Credentials ;
}
}
public IBlogCredentials Credentials
{
get
{
if ( _blogCredentials == null )
{
CredentialsDomain credentialsDomain = new CredentialsDomain(ServiceName, BlogName, FavIcon, Image);
_blogCredentials = new BlogCredentials(Settings, credentialsDomain);
}
return _blogCredentials ;
}
set
{
BlogCredentialsHelper.Copy(value, Credentials) ;
}
}
private BlogCredentials _blogCredentials ;
public IBlogProviderButtonDescription[] ButtonDescriptions
{
get
{
lock( _buttonsLock )
{
ArrayList buttonDescriptions = new ArrayList();
using (SettingsPersisterHelper providerButtons = Settings.GetSubSettings(BUTTONS_KEY))
{
foreach ( string buttonId in providerButtons.GetSubSettingNames() )
{
using ( SettingsPersisterHelper buttonKey = providerButtons.GetSubSettings(buttonId) )
buttonDescriptions.Add( new BlogProviderButtonDescriptionFromSettings(buttonKey) ) ;
}
}
return buttonDescriptions.ToArray(typeof(IBlogProviderButtonDescription)) as IBlogProviderButtonDescription[] ;
}
}
set
{
lock( _buttonsLock )
{
// write button descriptions
using (SettingsPersisterHelper providerButtons = Settings.GetSubSettings(BUTTONS_KEY))
{
// track buttons that have been deleted (assume all have been deleted and then
// remove deleted buttons from the list as they are referenced)
ArrayList deletedButtons = new ArrayList(providerButtons.GetSubSettingNames());
// write the descriptions
foreach (IBlogProviderButtonDescription buttonDescription in value)
{
// write
using ( SettingsPersisterHelper buttonKey = providerButtons.GetSubSettings(buttonDescription.Id) )
BlogProviderButtonDescriptionFromSettings.SaveFrameButtonDescriptionToSettings(buttonDescription, buttonKey);
// note that this button should not be deleted
deletedButtons.Remove(buttonDescription.Id);
}
// execute deletes
foreach ( string buttonId in deletedButtons)
providerButtons.UnsetSubsettingTree(buttonId);
}
}
}
}
private const string BUTTONS_KEY = "CustomButtons" ;
private readonly static object _buttonsLock = new object();
public bool LastPublishFailed
{
get { return Settings.GetBoolean( LAST_PUBLISH_FAILED, false ) ; }
set { Settings.SetBoolean( LAST_PUBLISH_FAILED, value ) ; }
}
private const string LAST_PUBLISH_FAILED = "LastPublishFailed" ;
public byte[] FavIcon
{
get { return Settings.GetByteArray( FAV_ICON, null ) ; }
set { Settings.SetByteArray( FAV_ICON, value ) ; }
}
private const string FAV_ICON = "FavIcon" ;
public byte[] Image
{
get { return Settings.GetByteArray( IMAGE, null ) ; }
set
{
byte[] imageBytes = value ;
if ( imageBytes != null && imageBytes.Length == 0 )
imageBytes = null ;
Settings.SetByteArray( IMAGE, imageBytes );
}
}
private const string IMAGE = "ImageBytes" ;
public byte[] WatermarkImage
{
get { return Settings.GetByteArray( WATERMARK_IMAGE, null ) ; }
set
{
byte[] watermarkBytes = value ;
if ( watermarkBytes != null && watermarkBytes.Length == 0 )
watermarkBytes = null ;
Settings.SetByteArray( WATERMARK_IMAGE, watermarkBytes );
}
}
private const string WATERMARK_IMAGE = "WatermarkImageBytes" ;
public BlogPostCategory[] Categories
{
get
{
lock( _categoriesLock )
{
// get the categories
ArrayList categories = new ArrayList() ;
using ( SettingsPersisterHelper categoriesKey = Settings.GetSubSettings(CATEGORIES) )
{
foreach ( string id in categoriesKey.GetSubSettingNames() )
{
using ( SettingsPersisterHelper categoryKey = categoriesKey.GetSubSettings(id) )
{
string name = categoryKey.GetString(CATEGORY_NAME, id) ;
string parent = categoryKey.GetString(CATEGORY_PARENT, String.Empty) ;
categories.Add( new BlogPostCategory( id, name, parent ) ) ;
}
}
}
if ( categories.Count > 0 )
return (BlogPostCategory[])categories.ToArray(typeof(BlogPostCategory)) ;
else // if we got no categories using the new format, try the old format
return LegacyCategories ;
}
}
set
{
lock( _categoriesLock )
{
// delete existing categories
SettingsPersisterHelper settings = Settings;
using (settings.BatchUpdate())
{
settings.UnsetSubsettingTree(CATEGORIES);
// re-write categories
using (SettingsPersisterHelper categoriesKey = settings.GetSubSettings(CATEGORIES))
{
foreach (BlogPostCategory category in value)
{
using (SettingsPersisterHelper categoryKey = categoriesKey.GetSubSettings(category.Id))
{
categoryKey.SetString(CATEGORY_NAME, category.Name);
categoryKey.SetString(CATEGORY_PARENT, category.Parent);
}
}
}
}
}
}
}
private const string CATEGORIES = "Categories" ;
private const string CATEGORY_NAME = "Name" ;
private const string CATEGORY_PARENT = "Parent" ;
private readonly static object _categoriesLock = new object();
private static readonly Dictionary<string, XmlSettingsPersister> _keywordPersister = new Dictionary<string, XmlSettingsPersister>();
/// <summary>
/// Make sure to own _keywordsLock before calling this property
/// </summary>
private XmlSettingsPersister KeywordPersister
{
get
{
if (!_keywordPersister.ContainsKey(KeywordPath))
{
_keywordPersister.Add(KeywordPath,XmlFileSettingsPersister.Open(KeywordPath));
}
return _keywordPersister[KeywordPath];
}
}
public BlogPostKeyword[] Keywords
{
get
{
lock (_keywordsLock)
{
ArrayList keywords = new ArrayList();
// Get all of the keyword subkeys
using (XmlSettingsPersister keywordsKey = (XmlSettingsPersister)KeywordPersister.GetSubSettings(KEYWORDS))
{
// Read the name out of the subkey
foreach (string id in keywordsKey.GetSubSettings())
{
using (ISettingsPersister categoryKey = keywordsKey.GetSubSettings(id))
{
string name = (string)categoryKey.Get(KEYWORD_NAME, typeof(string), id);
keywords.Add(new BlogPostKeyword(name));
}
}
}
if (keywords.Count > 0)
return (BlogPostKeyword[]) keywords.ToArray(typeof (BlogPostKeyword));
else
return new BlogPostKeyword[0];
}
}
set
{
lock (_keywordsLock)
{
// safely delete existing categories
XmlSettingsPersister keywordPersister = KeywordPersister;
using (keywordPersister.BatchUpdate())
{
keywordPersister.UnsetSubSettingsTree(KEYWORDS);
// re-write keywords
using (ISettingsPersister keywordsKey = keywordPersister.GetSubSettings(KEYWORDS))
{
foreach (BlogPostKeyword keyword in value)
{
using (ISettingsPersister keywordKey = keywordsKey.GetSubSettings(keyword.Name))
{
keywordKey.Set(KEYWORD_NAME, keyword.Name);
}
}
}
}
}
}
}
private const string KEYWORDS = "Keywords";
private const string KEYWORD_NAME = "Name";
private readonly static object _keywordsLock = new object();
private string _keywordPath;
/// <summary>
/// The path to an xml file in the %APPDATA% folder that contains keywords for the current blog
/// </summary>
private string KeywordPath
{
get
{
if (string.IsNullOrEmpty(_keywordPath))
{
string folderPath = Path.Combine(ApplicationEnvironment.ApplicationDataDirectory, "Keywords");
if(!Directory.Exists(folderPath))
Directory.CreateDirectory(folderPath);
_keywordPath = Path.Combine(folderPath, String.Format(CultureInfo.InvariantCulture, "keywords_{0}.xml", Id));
}
return _keywordPath;
}
}
private BlogPostCategory[] LegacyCategories
{
get
{
ArrayList categories = new ArrayList() ;
using ( SettingsPersisterHelper categoriesKey = Settings.GetSubSettings(CATEGORIES) )
{
foreach ( string id in categoriesKey.GetNames() )
categories.Add( new BlogPostCategory( id, categoriesKey.GetString( id, id ) ) ) ;
}
return (BlogPostCategory[])categories.ToArray(typeof(BlogPostCategory)) ;
}
}
public AuthorInfo[] Authors
{
get
{
lock( _authorsLock )
{
// get the authors
ArrayList authors = new ArrayList() ;
using ( SettingsPersisterHelper authorsKey = Settings.GetSubSettings(AUTHORS) )
{
foreach ( string id in authorsKey.GetSubSettingNames() )
{
using ( SettingsPersisterHelper authorKey = authorsKey.GetSubSettings(id) )
{
string name = authorKey.GetString(AUTHOR_NAME, String.Empty) ;
if ( name != String.Empty )
authors.Add( new AuthorInfo( id, name ) ) ;
else
Trace.Fail("Unexpected empty author name for id " + id);
}
}
}
return (AuthorInfo[])authors.ToArray(typeof(AuthorInfo)) ;
}
}
set
{
lock( _authorsLock )
{
// safely delete existing
SettingsPersisterHelper settings = Settings;
using (settings.BatchUpdate())
{
settings.UnsetSubsettingTree(AUTHORS);
// re-write
using (SettingsPersisterHelper authorsKey = settings.GetSubSettings(AUTHORS))
{
foreach (AuthorInfo author in value)
{
using (SettingsPersisterHelper authorKey = authorsKey.GetSubSettings(author.Id))
{
authorKey.SetString(AUTHOR_NAME, author.Name);
}
}
}
}
}
}
}
private const string AUTHORS = "Authors" ;
private const string AUTHOR_NAME = "Name" ;
private readonly static object _authorsLock = new object();
public PageInfo[] Pages
{
get
{
lock( _pagesLock )
{
// get the authors
ArrayList pages = new ArrayList() ;
using ( SettingsPersisterHelper pagesKey = Settings.GetSubSettings(PAGES) )
{
foreach ( string id in pagesKey.GetSubSettingNames() )
{
using ( SettingsPersisterHelper pageKey = pagesKey.GetSubSettings(id) )
{
string title = pageKey.GetString(PAGE_TITLE, String.Empty) ;
DateTime datePublished = pageKey.GetDateTime(PAGE_DATE_PUBLISHED, DateTime.MinValue) ;
string parentId = pageKey.GetString(PAGE_PARENT_ID, String.Empty) ;
pages.Add( new PageInfo(id, title, datePublished, parentId) ) ;
}
}
}
return (PageInfo[])pages.ToArray(typeof(PageInfo)) ;
}
}
set
{
lock( _pagesLock )
{
// safely delete existing
SettingsPersisterHelper settings = Settings;
using (settings.BatchUpdate())
{
settings.UnsetSubsettingTree(PAGES);
// re-write
using (SettingsPersisterHelper pagesKey = settings.GetSubSettings(PAGES))
{
foreach (PageInfo page in value)
{
using (SettingsPersisterHelper pageKey = pagesKey.GetSubSettings(page.Id))
{
pageKey.SetString(PAGE_TITLE, page.Title);
pageKey.SetDateTime(PAGE_DATE_PUBLISHED, page.DatePublished);
pageKey.SetString(PAGE_PARENT_ID, page.ParentId);
}
}
}
}
}
}
}
private const string PAGES = "Pages" ;
private const string PAGE_TITLE = "Name" ;
private const string PAGE_DATE_PUBLISHED = "DatePublished" ;
private const string PAGE_PARENT_ID = "ParentId" ;
private readonly static object _pagesLock = new object();
public FileUploadSupport FileUploadSupport
{
get
{
int intVal = Settings.GetInt32( FILE_UPLOAD_SUPPORT, (Int32)FileUploadSupport.Weblog );
switch (intVal)
{
case (int)FileUploadSupport.FTP:
return FileUploadSupport.FTP;
case (int)FileUploadSupport.Weblog:
default:
return FileUploadSupport.Weblog;
}
}
set { Settings.SetInt32( FILE_UPLOAD_SUPPORT, (Int32)value ) ; }
}
private const string FILE_UPLOAD_SUPPORT = "FileUploadSupport" ;
public IBlogFileUploadSettings FileUploadSettings
{
get
{
if ( _fileUploadSettings == null )
_fileUploadSettings = new BlogFileUploadSettings(Settings.GetSubSettings("FileUploadSettings"));
return _fileUploadSettings ;
}
}
private BlogFileUploadSettings _fileUploadSettings ;
public IBlogFileUploadSettings AtomPublishingProtocolSettings
{
get
{
if ( _atomPublishingProtocolSettings == null )
_atomPublishingProtocolSettings = new BlogFileUploadSettings(Settings.GetSubSettings("AtomSettings"));
return _atomPublishingProtocolSettings ;
}
}
private BlogFileUploadSettings _atomPublishingProtocolSettings ;
public BlogPublishingPluginSettings PublishingPluginSettings
{
get { return new BlogPublishingPluginSettings(Settings.GetSubSettings("PublishingPlugins")); }
}
/// <summary>
/// Delete this profile
/// </summary>
public void Delete()
{
// dispose the profile
Dispose() ;
using ( MetaLock(APPLY_UPDATES_LOCK) )
{
// delete the underlying settings tree
SettingsKey.UnsetSubsettingTree( _id ) ;
}
// if we are the default profile then set the default to null
if ( _id == DefaultBlogId )
DefaultBlogId = String.Empty ;
OnBlogSettingsDeleted(_id);
}
public void ApplyUpdates(IBlogSettingsDetectionContext settingsContext)
{
using ( MetaLock(APPLY_UPDATES_LOCK) )
{
if ( BlogSettings.BlogIdIsValid(_id) )
{
if ( settingsContext.ManifestDownloadInfo != null )
ManifestDownloadInfo = settingsContext.ManifestDownloadInfo ;
if ( settingsContext.ClientType != null )
ClientType = settingsContext.ClientType ;
if ( settingsContext.FavIcon != null )
FavIcon = settingsContext.FavIcon ;
if ( settingsContext.Image != null )
Image = settingsContext.Image ;
if ( settingsContext.WatermarkImage != null )
WatermarkImage = settingsContext.WatermarkImage ;
if ( settingsContext.Categories != null )
Categories = settingsContext.Categories ;
if (settingsContext.Keywords != null)
Keywords = settingsContext.Keywords;
if ( settingsContext.ButtonDescriptions != null )
ButtonDescriptions = settingsContext.ButtonDescriptions ;
if ( settingsContext.OptionOverrides != null )
OptionOverrides = settingsContext.OptionOverrides ;
if (settingsContext.HomePageOverrides != null)
HomePageOverrides = settingsContext.HomePageOverrides;
}
else
{
throw new InvalidOperationException("Attempted to apply updates to invalid blog-id") ;
}
}
}
public static IDisposable ApplyUpdatesLock(string id)
{
return _metaLock.Lock(APPLY_UPDATES_LOCK + id) ;
}
private static readonly MetaLock _metaLock = new MetaLock();
private IDisposable MetaLock(string contextName)
{
return _metaLock.Lock(contextName + _id) ;
}
private const string APPLY_UPDATES_LOCK = "ApplyUpdates" ;
public void Dispose()
{
if ( _blogCredentials != null )
{
_blogCredentials.Dispose() ;
_blogCredentials = null ;
}
if ( _fileUploadSettings != null )
{
_fileUploadSettings.Dispose() ;
_fileUploadSettings = null ;
}
if ( _atomPublishingProtocolSettings != null )
{
_atomPublishingProtocolSettings.Dispose() ;
_atomPublishingProtocolSettings = null ;
}
if ( _settings != null )
{
_settings.Dispose() ;
_settings = null ;
}
// This block is unsafe because it's easy for a persister
// to be disposed while it's still being used on another
// thread.
// if (_keywordPersister.ContainsKey(KeywordPath))
// {
// _keywordPersister[KeywordPath].Dispose();
// _keywordPersister.Remove(KeywordPath);
// }
GC.SuppressFinalize(this) ;
}
~BlogSettings()
{
Trace.Fail(String.Format(CultureInfo.InvariantCulture, "Failed to dispose BlogSettings!!! BlogId: {0} // BlogName: {1}", Id, BlogName));
}
public IBlogFileUploadSettings FileUpload
{
get
{
return FileUploadSettings ;
}
}
/// <summary>
/// Key for this weblog
/// </summary>
private SettingsPersisterHelper Settings
{
get
{
if ( _settings == null )
_settings = GetWeblogSettingsKey( _id ) ;
return _settings;
}
}
private SettingsPersisterHelper _settings ;
#region Class Configuration (location of settings, etc)
public static SettingsPersisterHelper GetProviderButtonsSettingsKey(string blogId)
{
return GetWeblogSettingsKey(blogId).GetSubSettings(BUTTONS_KEY) ;
}
public static SettingsPersisterHelper GetWeblogSettingsKey(string blogId)
{
return SettingsKey.GetSubSettings(blogId);
}
public static SettingsPersisterHelper SettingsKey
{
get
{
return _settingsKey ;
}
}
private static SettingsPersisterHelper _settingsKey = ApplicationEnvironment.UserSettingsRoot.GetSubSettings("Weblogs") ;
#endregion
}
public class BlogCredentials : IBlogCredentials, IDisposable
{
public BlogCredentials(SettingsPersisterHelper settingsRoot, ICredentialsDomain domain)
{
_settingsRoot = settingsRoot ;
_domain = domain;
}
public string Username
{
get { return GetUsername(); }
set { CredentialsSettings.SetString( USERNAME, value ) ; }
}
private const string USERNAME = "Username" ;
public string Password
{
get
{
return GetPassword() ?? string.Empty;
}
set
{
// save an encrypted password
try
{
CredentialsSettings.SetEncryptedString(PASSWORD, value);
}
catch(Exception e)
{
Trace.Fail("Failed to encrypt weblog password: " + e.Message, e.StackTrace);
}
}
}
private const string PASSWORD = "Password" ;
public string[] CustomValues
{
get
{
ArrayList customValues = new ArrayList();
string[] names = CredentialsSettings.GetNames();
foreach ( string name in names )
if ( name != USERNAME && name != PASSWORD )
customValues.Add(name) ;
return customValues.ToArray(typeof(string)) as string[] ;
}
}
public string GetCustomValue(string name)
{
return CredentialsSettings.GetString(name, String.Empty) ;
}
public void SetCustomValue(string name, string value)
{
CredentialsSettings.SetString(name, value);
}
public void Clear()
{
Username = String.Empty ;
Password = String.Empty ;
foreach ( string name in CredentialsSettings.GetNames() )
CredentialsSettings.SetString(name, null);
}
public ICredentialsDomain Domain
{
get { return _domain; }
set { _domain = value; }
}
private ICredentialsDomain _domain;
public void Dispose()
{
if ( _credentialsSettingsRoot != null )
_credentialsSettingsRoot.Dispose();
}
private SettingsPersisterHelper CredentialsSettings
{
get
{
if ( _credentialsSettingsRoot == null )
_credentialsSettingsRoot = _settingsRoot.GetSubSettings("Credentials") ;
return _credentialsSettingsRoot ;
}
}
/// <summary>
/// Get Username from either the credentials key or the root key
/// (seamless migration of accounts that existed prior to us moving
/// the credentials into their own subkey)
/// </summary>
/// <returns></returns>
private string GetUsername()
{
string username = CredentialsSettings.GetString(USERNAME, null);
if ( username != null )
return username ;
else
return _settingsRoot.GetString(USERNAME,String.Empty) ;
}
/// <summary>
/// Get Password from either the credentials key or the root key
/// (seamless migration of accounts that existed prior to us moving
/// the credentials into their own subkey)
/// </summary>
/// <returns></returns>
private string GetPassword()
{
string password = CredentialsSettings.GetEncryptedString(PASSWORD);
if ( password != null )
return password ;
else
return _settingsRoot.GetEncryptedString(PASSWORD) ;
}
private SettingsPersisterHelper _credentialsSettingsRoot ;
private SettingsPersisterHelper _settingsRoot ;
}
public class BlogFileUploadSettings : IBlogFileUploadSettings, IDisposable
{
public BlogFileUploadSettings( SettingsPersisterHelper settings )
{
_settings = settings ;
}
public string GetValue(string name)
{
return _settings.GetString( name, String.Empty ) ;
}
public void SetValue(string name, string value)
{
_settings.SetString(name, value);
}
public string[] Names
{
get { return _settings.GetNames(); }
}
public void Dispose()
{
if ( _settings != null )
{
_settings.Dispose() ;
_settings = null ;
}
}
private SettingsPersisterHelper _settings ;
}
}
| |
// 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;
/*********************************************
Notes on tests:
test_01:
Testing several assignments to see that they maintain order when hoisted.
test_02:
Like test_01, but with two loops.
test_03:
Like test_02, but nested.
test_04:
The increment is not invariant.
test_05:
Like test_04 but with two increments.
test_06:
Loop has one invariant and one not invariant.
test_07:
Like test_06, but with a different not invariant.
test_08:
Another not invariant assignemnt in a loop.
test_09:
An invariant addition.
test_10:
Like test_09 with a zero trip.
Test_11:
A nested invariant with a zero trip.
test_12:
Nested invariant with an add.
test_13:
Nested conflicting invariants.
Plus permutations:
int
long
uint
Notes:
It may be useful to run these tests with constant prop off.
*********************************************/
internal class test
{
public static int Main()
{
int failed_tests = 0;
// Test 01
if (test_01() != 9)
{
Console.WriteLine("FAIL: test_01");
failed_tests++;
}
// Test 02
if (test_02() != 3)
{
Console.WriteLine("FAIL: test_02");
failed_tests++;
}
// Test 03
if (test_03() != 3)
{
Console.WriteLine("FAIL: test_03");
failed_tests++;
}
// Test 04
if (test_04() != 10)
{
Console.WriteLine("FAIL: test_04");
failed_tests++;
}
// Test 05
if (test_05() != 20)
{
Console.WriteLine("FAIL: test_05");
failed_tests++;
}
// Test 06
if (test_06() != 8)
{
Console.WriteLine("FAIL: test_06");
failed_tests++;
}
// Test 07
if (test_07() != 16)
{
Console.WriteLine("FAIL: test_07");
failed_tests++;
}
// Test 08
if (test_08() != 9)
{
Console.WriteLine("FAIL: test_08");
failed_tests++;
}
// Test 09
if (test_09() != 3)
{
Console.WriteLine("FAIL: test_09");
failed_tests++;
}
// Test 10
if (test_10() != 0)
{
Console.WriteLine("FAIL: test_10");
failed_tests++;
}
// Test 11
if (test_11() != 0)
{
Console.WriteLine("FAIL: test_11");
failed_tests++;
}
// Test 12
if (test_12() != 2)
{
Console.WriteLine("FAIL: test_12");
failed_tests++;
}
// Test 13
if (test_13() != 7)
{
Console.WriteLine("FAIL: test_13");
failed_tests++;
}
// Test 01
if (test_101() != 9)
{
Console.WriteLine("FAIL: test_101");
failed_tests++;
}
// Test 02
if (test_102() != 3)
{
Console.WriteLine("FAIL: test_102");
failed_tests++;
}
// Test 03
if (test_103() != 3)
{
Console.WriteLine("FAIL: test_103");
failed_tests++;
}
// Test 04
if (test_104() != 10)
{
Console.WriteLine("FAIL: test_104");
failed_tests++;
}
// Test 05
if (test_105() != 20)
{
Console.WriteLine("FAIL: test_105");
failed_tests++;
}
// Test 06
if (test_106() != 8)
{
Console.WriteLine("FAIL: test_106");
failed_tests++;
}
// Test 07
if (test_107() != 16)
{
Console.WriteLine("FAIL: test_107");
failed_tests++;
}
// Test 08
if (test_108() != 9)
{
Console.WriteLine("FAIL: test_108");
failed_tests++;
}
// Test 09
if (test_109() != 3)
{
Console.WriteLine("FAIL: test_109");
failed_tests++;
}
// Test 10
if (test_110() != 0)
{
Console.WriteLine("FAIL: test_110");
failed_tests++;
}
// Test 11
if (test_111() != 0)
{
Console.WriteLine("FAIL: test_111");
failed_tests++;
}
// Test 12
if (test_112() != 2)
{
Console.WriteLine("FAIL: test_112");
failed_tests++;
}
// Test 13
if (test_113() != 7)
{
Console.WriteLine("FAIL: test_113");
failed_tests++;
}
// Test 01
if (test_201() != 9)
{
Console.WriteLine("FAIL: test_201");
failed_tests++;
}
// Test 02
if (test_202() != 3)
{
Console.WriteLine("FAIL: test_202");
failed_tests++;
}
// Test 03
if (test_203() != 3)
{
Console.WriteLine("FAIL: test_203");
failed_tests++;
}
// Test 04
if (test_204() != 10)
{
Console.WriteLine("FAIL: test_204");
failed_tests++;
}
// Test 05
if (test_205() != 20)
{
Console.WriteLine("FAIL: test_205");
failed_tests++;
}
// Test 06
if (test_206() != 8)
{
Console.WriteLine("FAIL: test_206");
failed_tests++;
}
// Test 07
if (test_207() != 16)
{
Console.WriteLine("FAIL: test_207");
failed_tests++;
}
// Test 08
if (test_208() != 9)
{
Console.WriteLine("FAIL: test_208");
failed_tests++;
}
// Test 09
if (test_209() != 3)
{
Console.WriteLine("FAIL: test_209");
failed_tests++;
}
// Test 10
if (test_210() != 0)
{
Console.WriteLine("FAIL: test_210");
failed_tests++;
}
// Test 11
if (test_211() != 0)
{
Console.WriteLine("FAIL: test_211");
failed_tests++;
}
// Test 12
if (test_212() != 2)
{
Console.WriteLine("FAIL: test_212");
failed_tests++;
}
// Test 13
if (test_213() != 7)
{
Console.WriteLine("FAIL: test_213");
failed_tests++;
}
return (failed_tests == 0) ? 100 : 1;
}
public static int test_13()
{
int a = 0;
for (int i = 0; i < 10; i++)
{
a = 9;
for (int j = 0; j < 10; j++)
{
a = 7;
}
}
return a;
}
public static int test_12()
{
int a = 0; int b = 0;
for (int i = 0; i < 10; i++)
{
b = 1;
for (int j = 0; j < 10; j++)
{
a = 1 + b;
}
}
return a;
}
public static int test_11()
{
int a = 0;
for (int i = 0; i < 0; i++)
{
for (int j = 0; j < 10; j++)
{
a = 1;
}
}
return a;
}
public static int test_10()
{
int a = 0; int b = 0; int c = 0;
int k = 0;
for (int i = 0; i < k; i++)
{
a = 1; b = 2; c = a + b;
}
return c;
}
public static int test_09()
{
int a = 0; int b = 0; int c = 0;
for (int i = 0; i < 10; i++)
{
a = 1; b = 2; c = a + b;
}
return c;
}
public static int test_08()
{
int a = 0;
for (int i = 0; i < 10; i++)
{
a = i;
}
return a;
}
public static int test_07()
{
int a = 0;
for (int i = 0; i < 10; i++)
{
a = 7; a += i;
}
return a;
}
public static int test_06()
{
int a = 0;
for (int i = 0; i < 10; i++)
{
a = 7; a++;
}
return a;
}
public static int test_05()
{
int a = 0;
for (int i = 0; i < 10; i++)
{
a++; a++;
}
return a;
}
public static int test_04()
{
int a = 0;
for (int i = 0; i < 10; i++)
{
a++;
}
return a;
}
public static int test_01()
{
int a = 0;
for (int i = 0; i < 10; i++)
{
a = 7; a = 8; a = 9;
}
return a;
}
public static int test_02()
{
int a = 0;
for (int i = 0; i < 10; i++)
{
a = 7; a = 8; a = 9;
}
for (int j = 0; j < 10; j++)
{
a = 1; a = 2; a = 3;
}
return a;
}
public static int test_03()
{
int a = 0;
for (int k = 0; k < 10; k++)
{
for (int i = 0; i < 10; i++)
{
a = 7; a = 8; a = 9;
}
for (int j = 0; j < 10; j++)
{
a = 1; a = 2; a = 3;
}
}
return a;
}
public static long test_113()
{
long a = 0;
for (long i = 0; i < 10; i++)
{
a = 9;
for (long j = 0; j < 10; j++)
{
a = 7;
}
}
return a;
}
public static long test_112()
{
long a = 0; long b = 0;
for (long i = 0; i < 10; i++)
{
b = 1;
for (long j = 0; j < 10; j++)
{
a = 1 + b;
}
}
return a;
}
public static long test_111()
{
long a = 0;
for (long i = 0; i < 0; i++)
{
for (long j = 0; j < 10; j++)
{
a = 1;
}
}
return a;
}
public static long test_110()
{
long a = 0; long b = 0; long c = 0;
long k = 0;
for (long i = 0; i < k; i++)
{
a = 1; b = 2; c = a + b;
}
return c;
}
public static long test_109()
{
long a = 0; long b = 0; long c = 0;
for (long i = 0; i < 10; i++)
{
a = 1; b = 2; c = a + b;
}
return c;
}
public static long test_108()
{
long a = 0;
for (long i = 0; i < 10; i++)
{
a = i;
}
return a;
}
public static long test_107()
{
long a = 0;
for (long i = 0; i < 10; i++)
{
a = 7; a += i;
}
return a;
}
public static long test_106()
{
long a = 0;
for (long i = 0; i < 10; i++)
{
a = 7; a++;
}
return a;
}
public static long test_105()
{
long a = 0;
for (long i = 0; i < 10; i++)
{
a++; a++;
}
return a;
}
public static long test_104()
{
long a = 0;
for (long i = 0; i < 10; i++)
{
a++;
}
return a;
}
public static long test_101()
{
long a = 0;
for (long i = 0; i < 10; i++)
{
a = 7; a = 8; a = 9;
}
return a;
}
public static long test_102()
{
long a = 0;
for (long i = 0; i < 10; i++)
{
a = 7; a = 8; a = 9;
}
for (long j = 0; j < 10; j++)
{
a = 1; a = 2; a = 3;
}
return a;
}
public static long test_103()
{
long a = 0;
for (long k = 0; k < 10; k++)
{
for (long i = 0; i < 10; i++)
{
a = 7; a = 8; a = 9;
}
for (long j = 0; j < 10; j++)
{
a = 1; a = 2; a = 3;
}
}
return a;
}
public static uint test_213()
{
uint a = 0;
for (uint i = 0; i < 10; i++)
{
a = 9;
for (uint j = 0; j < 10; j++)
{
a = 7;
}
}
return a;
}
public static uint test_212()
{
uint a = 0; uint b = 0;
for (uint i = 0; i < 10; i++)
{
b = 1;
for (uint j = 0; j < 10; j++)
{
a = 1 + b;
}
}
return a;
}
public static uint test_211()
{
uint a = 0;
for (uint i = 0; i < 0; i++)
{
for (uint j = 0; j < 10; j++)
{
a = 1;
}
}
return a;
}
public static uint test_210()
{
uint a = 0; uint b = 0; uint c = 0;
uint k = 0;
for (uint i = 0; i < k; i++)
{
a = 1; b = 2; c = a + b;
}
return c;
}
public static uint test_209()
{
uint a = 0; uint b = 0; uint c = 0;
for (uint i = 0; i < 10; i++)
{
a = 1; b = 2; c = a + b;
}
return c;
}
public static uint test_208()
{
uint a = 0;
for (uint i = 0; i < 10; i++)
{
a = i;
}
return a;
}
public static uint test_207()
{
uint a = 0;
for (uint i = 0; i < 10; i++)
{
a = 7; a += i;
}
return a;
}
public static uint test_206()
{
uint a = 0;
for (uint i = 0; i < 10; i++)
{
a = 7; a++;
}
return a;
}
public static uint test_205()
{
uint a = 0;
for (uint i = 0; i < 10; i++)
{
a++; a++;
}
return a;
}
public static uint test_204()
{
uint a = 0;
for (uint i = 0; i < 10; i++)
{
a++;
}
return a;
}
public static uint test_201()
{
uint a = 0;
for (uint i = 0; i < 10; i++)
{
a = 7; a = 8; a = 9;
}
return a;
}
public static uint test_202()
{
uint a = 0;
for (uint i = 0; i < 10; i++)
{
a = 7; a = 8; a = 9;
}
for (uint j = 0; j < 10; j++)
{
a = 1; a = 2; a = 3;
}
return a;
}
public static uint test_203()
{
uint a = 0;
for (uint k = 0; k < 10; k++)
{
for (uint i = 0; i < 10; i++)
{
a = 7; a = 8; a = 9;
}
for (uint j = 0; j < 10; j++)
{
a = 1; a = 2; a = 3;
}
}
return a;
}
}
| |
using System;
using System.Collections;
using System.Text;
using System.Data;
using Inform;
namespace Xenosynth.Security {
/// <summary>
/// Permissions provide a more granular way to control access to resources and features than roles. Permissions can be assigned to roles in the Xenosynth Admin.
/// </summary>
public class Permissions {
/// <summary>
/// Inserts a new Permission into the database.
/// </summary>
/// <param name="p">
/// A <see cref="Permission"/>
/// </param>
public static void Insert(Permission p) {
p.ID = Guid.NewGuid();
DataStore ds = DataStoreServices.GetDataStore("Xenosynth");
ds.Insert(p);
}
/// <summary>
/// Finds all Permissions.
/// </summary>
/// <returns>
/// A <see cref="IList"/>
/// </returns>
public static IList FindAllPermissions() {
DataStore ds = DataStoreServices.GetDataStore("Xenosynth");
IFindCollectionCommand cmd = ds.CreateFindCollectionCommand(typeof(Permission), "ORDER BY Category, Name");
return cmd.Execute();
}
/// <summary>
/// Finds a Permission by the unique identifier.
/// </summary>
/// <param name="permissionID">
/// A <see cref="Guid"/>
/// </param>
/// <returns>
/// A <see cref="Permission"/>
/// </returns>
public static Permission FindPermissionByID(Guid permissionID) {
//TODO: Push internal and add cache?
DataStore ds = DataStoreServices.GetDataStore("Xenosynth");
return (Permission)ds.FindByPrimaryKey(typeof(Permission), permissionID);
}
/// <summary>
/// Finds a Permission by the key.
/// </summary>
/// <param name="key">
/// A <see cref="System.String"/>
/// </param>
/// <returns>
/// A <see cref="Permission"/>
/// </returns>
public static Permission FindPermissionByKey(string key) {
//TODO: Push internal and add cache?
DataStore ds = DataStoreServices.GetDataStore("Xenosynth");
IFindObjectCommand cmd = ds.CreateFindObjectCommand(typeof(Permission), "WHERE [Key] = @Key");
cmd.CreateInputParameter("@Key", key);
return (Permission)cmd.Execute();
}
/// <summary>
/// Finds all roles for the Permission.
/// </summary>
/// <param name="permissionID">
/// A <see cref="Guid"/>
/// </param>
/// <returns>
/// A <see cref="System.String[]"/>
/// </returns>
public static string[] FindRolesForPermission(Guid permissionID) {
//TODO: Push internal and add cache?
DataStore ds = DataStoreServices.GetDataStore("Xenosynth");
IDataAccessCommand cmd = ds.CreateDataAccessCommand("SELECT RoleName FROM xs_RolePermissions WHERE PermissionID = @PermissionID");
cmd.CreateInputParameter("@PermissionID", permissionID);
IDataReader r = cmd.ExecuteReader();
ArrayList roles = new ArrayList();
try {
while (r.Read()) {
roles.Add(r.GetString(0));
}
} finally {
r.Close();
}
return (string[])roles.ToArray(typeof(string));
}
/// <summary>
/// Whether the permission indentified by the key exists.
/// </summary>
/// <param name="key">
/// A <see cref="System.String"/>
/// </param>
/// <returns>
/// A <see cref="System.Boolean"/>
/// </returns>
public static bool PermissionExists(string key) {
DataStore ds = DataStoreServices.GetDataStore("Xenosynth");
return FindPermissionByKey(key) != null; //HACK: Speed up.
}
/// <summary>
/// Whether the role has the Permission.
/// </summary>
/// <param name="role">
/// A <see cref="System.String"/>
/// </param>
/// <param name="permissionID">
/// A <see cref="Guid"/>
/// </param>
/// <returns>
/// A <see cref="System.Boolean"/>
/// </returns>
public static bool RoleHasPermission(string role, Guid permissionID) {
DataStore ds = DataStoreServices.GetDataStore("Xenosynth");
IDataAccessCommand cmd = ds.CreateDataAccessCommand("SELECT COUNT(*) FROM xs_RolePermissions WHERE PermissionID = @PermissionID AND RoleName = @Role ");
cmd.CreateInputParameter("@PermissionID", permissionID);
cmd.CreateInputParameter("@Role", role);
return (int)cmd.ExecuteScalar() > 0;
}
//public static bool UserHasPermission(string key) {
// DataStore ds = DataStoreServices.GetDataStore("Xenosynth");
// return FindPermissionByKey(key) != null; //HACK: Speed up.
//}
/// <summary>
/// Adds the Permission to the role.
/// </summary>
/// <param name="role">
/// A <see cref="System.String"/>
/// </param>
/// <param name="permissionID">
/// A <see cref="Guid"/>
/// </param>
public static void AddPermissionToRole(string role, Guid permissionID) {
if (!RoleHasPermission(role, permissionID)) {
DataStore ds = DataStoreServices.GetDataStore("Xenosynth");
IDataAccessCommand cmd = ds.CreateDataAccessCommand("INSERT INTO xs_RolePermissions VALUES (@PermissionID, @Role)");
cmd.CreateInputParameter("@PermissionID", permissionID);
cmd.CreateInputParameter("@Role", role);
cmd.ExecuteScalar();
}
}
/// <summary>
/// Removes the Permission from the role.
/// </summary>
/// <param name="role">
/// A <see cref="System.String"/>
/// </param>
/// <param name="permissionID">
/// A <see cref="Guid"/>
/// </param>
public static void RemovePermissionFromRole(string role, Guid permissionID) {
DataStore ds = DataStoreServices.GetDataStore("Xenosynth");
IDataAccessCommand cmd = ds.CreateDataAccessCommand("DELETE FROM xs_RolePermissions WHERE PermissionID = @PermissionID AND RoleName = @Role");
cmd.CreateInputParameter("@PermissionID", permissionID);
cmd.CreateInputParameter("@Role", role);
cmd.ExecuteScalar();
}
/// <summary>
/// Whether the current User has the Permission.
/// </summary>
/// <param name="key">
/// A <see cref="System.String"/>
/// </param>
/// <returns>
/// A <see cref="System.Boolean"/>
/// </returns>
public static bool UserHasPermission(string key) {
Permission p = FindPermissionByKey(key);
string[] roles = p.Roles;
foreach (string role in roles) {
if (System.Web.HttpContext.Current.User.IsInRole(role)) {
return true;
}
}
return false;
}
/// <summary>
/// Deletes the Permission from the database.
/// </summary>
/// <param name="permissionID">
/// A <see cref="Guid"/>
/// </param>
public static void DeletePermission(Guid permissionID) {
DataStore ds = DataStoreServices.GetDataStore("Xenosynth");
IDataAccessCommand cmd = ds.CreateDataAccessCommand("DELETE FROM xs_RolePermissions WHERE PermissionID = @PermissionID");
cmd.CreateInputParameter("@PermissionID", permissionID);
cmd.ExecuteScalar();
ds.Delete(typeof(Permission), permissionID);
}
}
}
| |
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
//
// Idea got from and adapted to work in avalonia
// http://silverlight.codeplex.com/SourceControl/changeset/view/74775#Release/Silverlight4/Source/Controls.Layout.Toolkit/LayoutTransformer/LayoutTransformer.cs
//
using Avalonia.Controls.Primitives;
using Avalonia.Media;
using Avalonia.VisualTree;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reactive.Linq;
namespace Avalonia.Controls
{
/// <summary>
/// Control that implements support for transformations as if applied by LayoutTransform.
/// </summary>
public class LayoutTransformControl : ContentControl
{
public static readonly AvaloniaProperty<Transform> LayoutTransformProperty =
AvaloniaProperty.Register<LayoutTransformControl, Transform>(nameof(LayoutTransform));
static LayoutTransformControl()
{
LayoutTransformProperty.Changed
.AddClassHandler<LayoutTransformControl>(x => x.OnLayoutTransformChanged);
}
/// <summary>
/// Gets or sets a graphics transformation that should apply to this element when layout is performed.
/// </summary>
public Transform LayoutTransform
{
get { return GetValue(LayoutTransformProperty); }
set { SetValue(LayoutTransformProperty, value); }
}
public Control TransformRoot => _transformRoot ??
(_transformRoot = this.GetVisualChildren().OfType<Control>().FirstOrDefault());
/// <summary>
/// Provides the behavior for the "Arrange" pass of layout.
/// </summary>
/// <param name="finalSize">The final area within the parent that this element should use to arrange itself and its children.</param>
/// <returns>The actual size used.</returns>
protected override Size ArrangeOverride(Size finalSize)
{
if (TransformRoot == null || LayoutTransform == null)
{
return base.ArrangeOverride(finalSize);
}
// Determine the largest available size after the transformation
Size finalSizeTransformed = ComputeLargestTransformedSize(finalSize);
if (IsSizeSmaller(finalSizeTransformed, TransformRoot.DesiredSize))
{
// Some elements do not like being given less space than they asked for (ex: TextBlock)
// Bump the working size up to do the right thing by them
finalSizeTransformed = TransformRoot.DesiredSize;
}
// Transform the working size to find its width/height
Rect transformedRect = new Rect(0, 0, finalSizeTransformed.Width, finalSizeTransformed.Height).TransformToAABB(_transformation);
// Create the Arrange rect to center the transformed content
Rect finalRect = new Rect(
-transformedRect.X + ((finalSize.Width - transformedRect.Width) / 2),
-transformedRect.Y + ((finalSize.Height - transformedRect.Height) / 2),
finalSizeTransformed.Width,
finalSizeTransformed.Height);
// Perform an Arrange on TransformRoot (containing Child)
Size arrangedsize;
TransformRoot.Arrange(finalRect);
arrangedsize = TransformRoot.Bounds.Size;
// This is the first opportunity under Silverlight to find out the Child's true DesiredSize
if (IsSizeSmaller(finalSizeTransformed, arrangedsize) && (Size.Empty == _childActualSize))
{
//// Unfortunately, all the work so far is invalid because the wrong DesiredSize was used
//// Make a note of the actual DesiredSize
//_childActualSize = arrangedsize;
//// Force a new measure/arrange pass
//InvalidateMeasure();
}
else
{
// Clear the "need to measure/arrange again" flag
_childActualSize = Size.Empty;
}
// Return result to perform the transformation
return finalSize;
}
/// <summary>
/// Provides the behavior for the "Measure" pass of layout.
/// </summary>
/// <param name="availableSize">The available size that this element can give to child elements.</param>
/// <returns>The size that this element determines it needs during layout, based on its calculations of child element sizes.</returns>
protected override Size MeasureOverride(Size availableSize)
{
if (TransformRoot == null || LayoutTransform == null)
{
return base.MeasureOverride(availableSize);
}
Size measureSize;
if (_childActualSize == Size.Empty)
{
// Determine the largest size after the transformation
measureSize = ComputeLargestTransformedSize(availableSize);
}
else
{
// Previous measure/arrange pass determined that Child.DesiredSize was larger than believed
measureSize = _childActualSize;
}
// Perform a measure on the TransformRoot (containing Child)
TransformRoot.Measure(measureSize);
var desiredSize = TransformRoot.DesiredSize;
// Transform DesiredSize to find its width/height
Rect transformedDesiredRect = new Rect(0, 0, desiredSize.Width, desiredSize.Height).TransformToAABB(_transformation);
Size transformedDesiredSize = new Size(transformedDesiredRect.Width, transformedDesiredRect.Height);
// Return result to allocate enough space for the transformation
return transformedDesiredSize;
}
/// <summary>
/// Builds the visual tree for the LayoutTransformerControl when a new
/// template is applied.
/// </summary>
protected override void OnTemplateApplied(TemplateAppliedEventArgs e)
{
base.OnTemplateApplied(e);
_matrixTransform = new MatrixTransform();
if (null != TransformRoot)
{
TransformRoot.RenderTransform = _matrixTransform;
TransformRoot.RenderTransformOrigin = new RelativePoint(0, 0, RelativeUnit.Absolute);
}
ApplyLayoutTransform();
}
/// <summary>
/// Acceptable difference between two doubles.
/// </summary>
private const double AcceptableDelta = 0.0001;
/// <summary>
/// Number of decimals to round the Matrix to.
/// </summary>
private const int DecimalsAfterRound = 4;
/// <summary>
/// Actual DesiredSize of Child element (the value it returned from its MeasureOverride method).
/// </summary>
private Size _childActualSize = Size.Empty;
/// <summary>
/// RenderTransform/MatrixTransform applied to TransformRoot.
/// </summary>
private MatrixTransform _matrixTransform;
/// <summary>
/// Transformation matrix corresponding to _matrixTransform.
/// </summary>
private Matrix _transformation;
private IDisposable _transformChangedEvent = null;
private Control _transformRoot;
/// <summary>
/// Returns true if Size a is smaller than Size b in either dimension.
/// </summary>
/// <param name="a">Second Size.</param>
/// <param name="b">First Size.</param>
/// <returns>True if Size a is smaller than Size b in either dimension.</returns>
private static bool IsSizeSmaller(Size a, Size b)
{
return (a.Width + AcceptableDelta < b.Width) || (a.Height + AcceptableDelta < b.Height);
}
/// <summary>
/// Rounds the non-offset elements of a Matrix to avoid issues due to floating point imprecision.
/// </summary>
/// <param name="matrix">Matrix to round.</param>
/// <param name="decimals">Number of decimal places to round to.</param>
/// <returns>Rounded Matrix.</returns>
private static Matrix RoundMatrix(Matrix matrix, int decimals)
{
return new Matrix(
Math.Round(matrix.M11, decimals),
Math.Round(matrix.M12, decimals),
Math.Round(matrix.M21, decimals),
Math.Round(matrix.M22, decimals),
matrix.M31,
matrix.M32);
}
/// <summary>
/// Applies the layout transform on the LayoutTransformerControl content.
/// </summary>
/// <remarks>
/// Only used in advanced scenarios (like animating the LayoutTransform).
/// Should be used to notify the LayoutTransformer control that some aspect
/// of its Transform property has changed.
/// </remarks>
private void ApplyLayoutTransform()
{
if (LayoutTransform == null) return;
// Get the transform matrix and apply it
_transformation = RoundMatrix(LayoutTransform.Value, DecimalsAfterRound);
if (null != _matrixTransform)
{
_matrixTransform.Matrix = _transformation;
}
// New transform means re-layout is necessary
InvalidateMeasure();
}
/// <summary>
/// Compute the largest usable size (greatest area) after applying the transformation to the specified bounds.
/// </summary>
/// <param name="arrangeBounds">Arrange bounds.</param>
/// <returns>Largest Size possible.</returns>
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "Closely corresponds to WPF's FrameworkElement.FindMaximalAreaLocalSpaceRect.")]
private Size ComputeLargestTransformedSize(Size arrangeBounds)
{
// Computed largest transformed size
Size computedSize = Size.Empty;
// Detect infinite bounds and constrain the scenario
bool infiniteWidth = double.IsInfinity(arrangeBounds.Width);
if (infiniteWidth)
{
// arrangeBounds.Width = arrangeBounds.Height;
arrangeBounds = arrangeBounds.WithWidth(arrangeBounds.Height);
}
bool infiniteHeight = double.IsInfinity(arrangeBounds.Height);
if (infiniteHeight)
{
//arrangeBounds.Height = arrangeBounds.Width;
arrangeBounds = arrangeBounds.WithHeight(arrangeBounds.Width);
}
// Capture the matrix parameters
double a = _transformation.M11;
double b = _transformation.M12;
double c = _transformation.M21;
double d = _transformation.M22;
// Compute maximum possible transformed width/height based on starting width/height
// These constraints define two lines in the positive x/y quadrant
double maxWidthFromWidth = Math.Abs(arrangeBounds.Width / a);
double maxHeightFromWidth = Math.Abs(arrangeBounds.Width / c);
double maxWidthFromHeight = Math.Abs(arrangeBounds.Height / b);
double maxHeightFromHeight = Math.Abs(arrangeBounds.Height / d);
// The transformed width/height that maximize the area under each segment is its midpoint
// At most one of the two midpoints will satisfy both constraints
double idealWidthFromWidth = maxWidthFromWidth / 2;
double idealHeightFromWidth = maxHeightFromWidth / 2;
double idealWidthFromHeight = maxWidthFromHeight / 2;
double idealHeightFromHeight = maxHeightFromHeight / 2;
// Compute slope of both constraint lines
double slopeFromWidth = -(maxHeightFromWidth / maxWidthFromWidth);
double slopeFromHeight = -(maxHeightFromHeight / maxWidthFromHeight);
if ((0 == arrangeBounds.Width) || (0 == arrangeBounds.Height))
{
// Check for empty bounds
computedSize = new Size(arrangeBounds.Width, arrangeBounds.Height);
}
else if (infiniteWidth && infiniteHeight)
{
// Check for completely unbound scenario
computedSize = new Size(double.PositiveInfinity, double.PositiveInfinity);
}
else if (!_transformation.HasInverse)
{
// Check for singular matrix
computedSize = new Size(0, 0);
}
else if ((0 == b) || (0 == c))
{
// Check for 0/180 degree special cases
double maxHeight = (infiniteHeight ? double.PositiveInfinity : maxHeightFromHeight);
double maxWidth = (infiniteWidth ? double.PositiveInfinity : maxWidthFromWidth);
if ((0 == b) && (0 == c))
{
// No constraints
computedSize = new Size(maxWidth, maxHeight);
}
else if (0 == b)
{
// Constrained by width
double computedHeight = Math.Min(idealHeightFromWidth, maxHeight);
computedSize = new Size(
maxWidth - Math.Abs((c * computedHeight) / a),
computedHeight);
}
else if (0 == c)
{
// Constrained by height
double computedWidth = Math.Min(idealWidthFromHeight, maxWidth);
computedSize = new Size(
computedWidth,
maxHeight - Math.Abs((b * computedWidth) / d));
}
}
else if ((0 == a) || (0 == d))
{
// Check for 90/270 degree special cases
double maxWidth = (infiniteHeight ? double.PositiveInfinity : maxWidthFromHeight);
double maxHeight = (infiniteWidth ? double.PositiveInfinity : maxHeightFromWidth);
if ((0 == a) && (0 == d))
{
// No constraints
computedSize = new Size(maxWidth, maxHeight);
}
else if (0 == a)
{
// Constrained by width
double computedHeight = Math.Min(idealHeightFromHeight, maxHeight);
computedSize = new Size(
maxWidth - Math.Abs((d * computedHeight) / b),
computedHeight);
}
else if (0 == d)
{
// Constrained by height
double computedWidth = Math.Min(idealWidthFromWidth, maxWidth);
computedSize = new Size(
computedWidth,
maxHeight - Math.Abs((a * computedWidth) / c));
}
}
else if (idealHeightFromWidth <= ((slopeFromHeight * idealWidthFromWidth) + maxHeightFromHeight))
{
// Check the width midpoint for viability (by being below the height constraint line)
computedSize = new Size(idealWidthFromWidth, idealHeightFromWidth);
}
else if (idealHeightFromHeight <= ((slopeFromWidth * idealWidthFromHeight) + maxHeightFromWidth))
{
// Check the height midpoint for viability (by being below the width constraint line)
computedSize = new Size(idealWidthFromHeight, idealHeightFromHeight);
}
else
{
// Neither midpoint is viable; use the intersection of the two constraint lines instead
// Compute width by setting heights equal (m1*x+c1=m2*x+c2)
double computedWidth = (maxHeightFromHeight - maxHeightFromWidth) / (slopeFromWidth - slopeFromHeight);
// Compute height from width constraint line (y=m*x+c; using height would give same result)
computedSize = new Size(
computedWidth,
(slopeFromWidth * computedWidth) + maxHeightFromWidth);
}
// Return result
return computedSize;
}
private void OnLayoutTransformChanged(AvaloniaPropertyChangedEventArgs e)
{
var newTransform = e.NewValue as Transform;
if (_transformChangedEvent != null)
{
_transformChangedEvent.Dispose();
_transformChangedEvent = null;
}
if (newTransform != null)
{
_transformChangedEvent = Observable.FromEventPattern<EventHandler, EventArgs>(
v => newTransform.Changed += v, v => newTransform.Changed -= v)
.Subscribe(onNext: v => ApplyLayoutTransform());
}
ApplyLayoutTransform();
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using gagr = Google.Api.Gax.ResourceNames;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Cloud.PhishingProtection.V1Beta1
{
/// <summary>Settings for <see cref="PhishingProtectionServiceV1Beta1Client"/> instances.</summary>
public sealed partial class PhishingProtectionServiceV1Beta1Settings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="PhishingProtectionServiceV1Beta1Settings"/>.</summary>
/// <returns>A new instance of the default <see cref="PhishingProtectionServiceV1Beta1Settings"/>.</returns>
public static PhishingProtectionServiceV1Beta1Settings GetDefault() => new PhishingProtectionServiceV1Beta1Settings();
/// <summary>
/// Constructs a new <see cref="PhishingProtectionServiceV1Beta1Settings"/> object with default settings.
/// </summary>
public PhishingProtectionServiceV1Beta1Settings()
{
}
private PhishingProtectionServiceV1Beta1Settings(PhishingProtectionServiceV1Beta1Settings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
ReportPhishingSettings = existing.ReportPhishingSettings;
OnCopy(existing);
}
partial void OnCopy(PhishingProtectionServiceV1Beta1Settings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>PhishingProtectionServiceV1Beta1Client.ReportPhishing</c> and
/// <c>PhishingProtectionServiceV1Beta1Client.ReportPhishingAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>Timeout: 600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings ReportPhishingSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(600000)));
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="PhishingProtectionServiceV1Beta1Settings"/> object.</returns>
public PhishingProtectionServiceV1Beta1Settings Clone() => new PhishingProtectionServiceV1Beta1Settings(this);
}
/// <summary>
/// Builder class for <see cref="PhishingProtectionServiceV1Beta1Client"/> to provide simple configuration of
/// credentials, endpoint etc.
/// </summary>
public sealed partial class PhishingProtectionServiceV1Beta1ClientBuilder : gaxgrpc::ClientBuilderBase<PhishingProtectionServiceV1Beta1Client>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public PhishingProtectionServiceV1Beta1Settings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public PhishingProtectionServiceV1Beta1ClientBuilder()
{
UseJwtAccessWithScopes = PhishingProtectionServiceV1Beta1Client.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref PhishingProtectionServiceV1Beta1Client client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<PhishingProtectionServiceV1Beta1Client> task);
/// <summary>Builds the resulting client.</summary>
public override PhishingProtectionServiceV1Beta1Client Build()
{
PhishingProtectionServiceV1Beta1Client client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<PhishingProtectionServiceV1Beta1Client> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<PhishingProtectionServiceV1Beta1Client> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private PhishingProtectionServiceV1Beta1Client BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return PhishingProtectionServiceV1Beta1Client.Create(callInvoker, Settings);
}
private async stt::Task<PhishingProtectionServiceV1Beta1Client> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return PhishingProtectionServiceV1Beta1Client.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => PhishingProtectionServiceV1Beta1Client.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() =>
PhishingProtectionServiceV1Beta1Client.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => PhishingProtectionServiceV1Beta1Client.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance;
}
/// <summary>PhishingProtectionServiceV1Beta1 client wrapper, for convenient use.</summary>
/// <remarks>
/// Service to report phishing URIs.
/// </remarks>
public abstract partial class PhishingProtectionServiceV1Beta1Client
{
/// <summary>
/// The default endpoint for the PhishingProtectionServiceV1Beta1 service, which is a host of
/// "phishingprotection.googleapis.com" and a port of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "phishingprotection.googleapis.com:443";
/// <summary>The default PhishingProtectionServiceV1Beta1 scopes.</summary>
/// <remarks>
/// The default PhishingProtectionServiceV1Beta1 scopes are:
/// <list type="bullet">
/// <item><description>https://www.googleapis.com/auth/cloud-platform</description></item>
/// </list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/cloud-platform",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="PhishingProtectionServiceV1Beta1Client"/> using the default credentials,
/// endpoint and settings. To specify custom credentials or other settings, use
/// <see cref="PhishingProtectionServiceV1Beta1ClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="PhishingProtectionServiceV1Beta1Client"/>.</returns>
public static stt::Task<PhishingProtectionServiceV1Beta1Client> CreateAsync(st::CancellationToken cancellationToken = default) =>
new PhishingProtectionServiceV1Beta1ClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="PhishingProtectionServiceV1Beta1Client"/> using the default credentials,
/// endpoint and settings. To specify custom credentials or other settings, use
/// <see cref="PhishingProtectionServiceV1Beta1ClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="PhishingProtectionServiceV1Beta1Client"/>.</returns>
public static PhishingProtectionServiceV1Beta1Client Create() =>
new PhishingProtectionServiceV1Beta1ClientBuilder().Build();
/// <summary>
/// Creates a <see cref="PhishingProtectionServiceV1Beta1Client"/> which uses the specified call invoker for
/// remote operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="PhishingProtectionServiceV1Beta1Settings"/>.</param>
/// <returns>The created <see cref="PhishingProtectionServiceV1Beta1Client"/>.</returns>
internal static PhishingProtectionServiceV1Beta1Client Create(grpccore::CallInvoker callInvoker, PhishingProtectionServiceV1Beta1Settings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
PhishingProtectionServiceV1Beta1.PhishingProtectionServiceV1Beta1Client grpcClient = new PhishingProtectionServiceV1Beta1.PhishingProtectionServiceV1Beta1Client(callInvoker);
return new PhishingProtectionServiceV1Beta1ClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
/// by another call to this method.
/// </remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC PhishingProtectionServiceV1Beta1 client</summary>
public virtual PhishingProtectionServiceV1Beta1.PhishingProtectionServiceV1Beta1Client GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Reports a URI suspected of containing phishing content to be reviewed. Once
/// the report review is complete, its result can be found in the Cloud
/// Security Command Center findings dashboard for Phishing Protection. If the
/// result verifies the existence of malicious phishing content, the site will
/// be added the to [Google's Social Engineering
/// lists](https://support.google.com/webmasters/answer/6350487/) in order to
/// protect users that could get exposed to this threat in the future.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual ReportPhishingResponse ReportPhishing(ReportPhishingRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Reports a URI suspected of containing phishing content to be reviewed. Once
/// the report review is complete, its result can be found in the Cloud
/// Security Command Center findings dashboard for Phishing Protection. If the
/// result verifies the existence of malicious phishing content, the site will
/// be added the to [Google's Social Engineering
/// lists](https://support.google.com/webmasters/answer/6350487/) in order to
/// protect users that could get exposed to this threat in the future.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<ReportPhishingResponse> ReportPhishingAsync(ReportPhishingRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Reports a URI suspected of containing phishing content to be reviewed. Once
/// the report review is complete, its result can be found in the Cloud
/// Security Command Center findings dashboard for Phishing Protection. If the
/// result verifies the existence of malicious phishing content, the site will
/// be added the to [Google's Social Engineering
/// lists](https://support.google.com/webmasters/answer/6350487/) in order to
/// protect users that could get exposed to this threat in the future.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<ReportPhishingResponse> ReportPhishingAsync(ReportPhishingRequest request, st::CancellationToken cancellationToken) =>
ReportPhishingAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Reports a URI suspected of containing phishing content to be reviewed. Once
/// the report review is complete, its result can be found in the Cloud
/// Security Command Center findings dashboard for Phishing Protection. If the
/// result verifies the existence of malicious phishing content, the site will
/// be added the to [Google's Social Engineering
/// lists](https://support.google.com/webmasters/answer/6350487/) in order to
/// protect users that could get exposed to this threat in the future.
/// </summary>
/// <param name="parent">
/// Required. The name of the project for which the report will be created,
/// in the format "projects/{project_number}".
/// </param>
/// <param name="uri">
/// Required. The URI that is being reported for phishing content to be analyzed.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual ReportPhishingResponse ReportPhishing(string parent, string uri, gaxgrpc::CallSettings callSettings = null) =>
ReportPhishing(new ReportPhishingRequest
{
Parent = gax::GaxPreconditions.CheckNotNullOrEmpty(parent, nameof(parent)),
Uri = gax::GaxPreconditions.CheckNotNullOrEmpty(uri, nameof(uri)),
}, callSettings);
/// <summary>
/// Reports a URI suspected of containing phishing content to be reviewed. Once
/// the report review is complete, its result can be found in the Cloud
/// Security Command Center findings dashboard for Phishing Protection. If the
/// result verifies the existence of malicious phishing content, the site will
/// be added the to [Google's Social Engineering
/// lists](https://support.google.com/webmasters/answer/6350487/) in order to
/// protect users that could get exposed to this threat in the future.
/// </summary>
/// <param name="parent">
/// Required. The name of the project for which the report will be created,
/// in the format "projects/{project_number}".
/// </param>
/// <param name="uri">
/// Required. The URI that is being reported for phishing content to be analyzed.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<ReportPhishingResponse> ReportPhishingAsync(string parent, string uri, gaxgrpc::CallSettings callSettings = null) =>
ReportPhishingAsync(new ReportPhishingRequest
{
Parent = gax::GaxPreconditions.CheckNotNullOrEmpty(parent, nameof(parent)),
Uri = gax::GaxPreconditions.CheckNotNullOrEmpty(uri, nameof(uri)),
}, callSettings);
/// <summary>
/// Reports a URI suspected of containing phishing content to be reviewed. Once
/// the report review is complete, its result can be found in the Cloud
/// Security Command Center findings dashboard for Phishing Protection. If the
/// result verifies the existence of malicious phishing content, the site will
/// be added the to [Google's Social Engineering
/// lists](https://support.google.com/webmasters/answer/6350487/) in order to
/// protect users that could get exposed to this threat in the future.
/// </summary>
/// <param name="parent">
/// Required. The name of the project for which the report will be created,
/// in the format "projects/{project_number}".
/// </param>
/// <param name="uri">
/// Required. The URI that is being reported for phishing content to be analyzed.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<ReportPhishingResponse> ReportPhishingAsync(string parent, string uri, st::CancellationToken cancellationToken) =>
ReportPhishingAsync(parent, uri, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Reports a URI suspected of containing phishing content to be reviewed. Once
/// the report review is complete, its result can be found in the Cloud
/// Security Command Center findings dashboard for Phishing Protection. If the
/// result verifies the existence of malicious phishing content, the site will
/// be added the to [Google's Social Engineering
/// lists](https://support.google.com/webmasters/answer/6350487/) in order to
/// protect users that could get exposed to this threat in the future.
/// </summary>
/// <param name="parent">
/// Required. The name of the project for which the report will be created,
/// in the format "projects/{project_number}".
/// </param>
/// <param name="uri">
/// Required. The URI that is being reported for phishing content to be analyzed.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual ReportPhishingResponse ReportPhishing(gagr::ProjectName parent, string uri, gaxgrpc::CallSettings callSettings = null) =>
ReportPhishing(new ReportPhishingRequest
{
ParentAsProjectName = gax::GaxPreconditions.CheckNotNull(parent, nameof(parent)),
Uri = gax::GaxPreconditions.CheckNotNullOrEmpty(uri, nameof(uri)),
}, callSettings);
/// <summary>
/// Reports a URI suspected of containing phishing content to be reviewed. Once
/// the report review is complete, its result can be found in the Cloud
/// Security Command Center findings dashboard for Phishing Protection. If the
/// result verifies the existence of malicious phishing content, the site will
/// be added the to [Google's Social Engineering
/// lists](https://support.google.com/webmasters/answer/6350487/) in order to
/// protect users that could get exposed to this threat in the future.
/// </summary>
/// <param name="parent">
/// Required. The name of the project for which the report will be created,
/// in the format "projects/{project_number}".
/// </param>
/// <param name="uri">
/// Required. The URI that is being reported for phishing content to be analyzed.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<ReportPhishingResponse> ReportPhishingAsync(gagr::ProjectName parent, string uri, gaxgrpc::CallSettings callSettings = null) =>
ReportPhishingAsync(new ReportPhishingRequest
{
ParentAsProjectName = gax::GaxPreconditions.CheckNotNull(parent, nameof(parent)),
Uri = gax::GaxPreconditions.CheckNotNullOrEmpty(uri, nameof(uri)),
}, callSettings);
/// <summary>
/// Reports a URI suspected of containing phishing content to be reviewed. Once
/// the report review is complete, its result can be found in the Cloud
/// Security Command Center findings dashboard for Phishing Protection. If the
/// result verifies the existence of malicious phishing content, the site will
/// be added the to [Google's Social Engineering
/// lists](https://support.google.com/webmasters/answer/6350487/) in order to
/// protect users that could get exposed to this threat in the future.
/// </summary>
/// <param name="parent">
/// Required. The name of the project for which the report will be created,
/// in the format "projects/{project_number}".
/// </param>
/// <param name="uri">
/// Required. The URI that is being reported for phishing content to be analyzed.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<ReportPhishingResponse> ReportPhishingAsync(gagr::ProjectName parent, string uri, st::CancellationToken cancellationToken) =>
ReportPhishingAsync(parent, uri, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>PhishingProtectionServiceV1Beta1 client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// Service to report phishing URIs.
/// </remarks>
public sealed partial class PhishingProtectionServiceV1Beta1ClientImpl : PhishingProtectionServiceV1Beta1Client
{
private readonly gaxgrpc::ApiCall<ReportPhishingRequest, ReportPhishingResponse> _callReportPhishing;
/// <summary>
/// Constructs a client wrapper for the PhishingProtectionServiceV1Beta1 service, with the specified gRPC client
/// and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">
/// The base <see cref="PhishingProtectionServiceV1Beta1Settings"/> used within this client.
/// </param>
public PhishingProtectionServiceV1Beta1ClientImpl(PhishingProtectionServiceV1Beta1.PhishingProtectionServiceV1Beta1Client grpcClient, PhishingProtectionServiceV1Beta1Settings settings)
{
GrpcClient = grpcClient;
PhishingProtectionServiceV1Beta1Settings effectiveSettings = settings ?? PhishingProtectionServiceV1Beta1Settings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callReportPhishing = clientHelper.BuildApiCall<ReportPhishingRequest, ReportPhishingResponse>(grpcClient.ReportPhishingAsync, grpcClient.ReportPhishing, effectiveSettings.ReportPhishingSettings).WithGoogleRequestParam("parent", request => request.Parent);
Modify_ApiCall(ref _callReportPhishing);
Modify_ReportPhishingApiCall(ref _callReportPhishing);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_ReportPhishingApiCall(ref gaxgrpc::ApiCall<ReportPhishingRequest, ReportPhishingResponse> call);
partial void OnConstruction(PhishingProtectionServiceV1Beta1.PhishingProtectionServiceV1Beta1Client grpcClient, PhishingProtectionServiceV1Beta1Settings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC PhishingProtectionServiceV1Beta1 client</summary>
public override PhishingProtectionServiceV1Beta1.PhishingProtectionServiceV1Beta1Client GrpcClient { get; }
partial void Modify_ReportPhishingRequest(ref ReportPhishingRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Reports a URI suspected of containing phishing content to be reviewed. Once
/// the report review is complete, its result can be found in the Cloud
/// Security Command Center findings dashboard for Phishing Protection. If the
/// result verifies the existence of malicious phishing content, the site will
/// be added the to [Google's Social Engineering
/// lists](https://support.google.com/webmasters/answer/6350487/) in order to
/// protect users that could get exposed to this threat in the future.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override ReportPhishingResponse ReportPhishing(ReportPhishingRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_ReportPhishingRequest(ref request, ref callSettings);
return _callReportPhishing.Sync(request, callSettings);
}
/// <summary>
/// Reports a URI suspected of containing phishing content to be reviewed. Once
/// the report review is complete, its result can be found in the Cloud
/// Security Command Center findings dashboard for Phishing Protection. If the
/// result verifies the existence of malicious phishing content, the site will
/// be added the to [Google's Social Engineering
/// lists](https://support.google.com/webmasters/answer/6350487/) in order to
/// protect users that could get exposed to this threat in the future.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<ReportPhishingResponse> ReportPhishingAsync(ReportPhishingRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_ReportPhishingRequest(ref request, ref callSettings);
return _callReportPhishing.Async(request, callSettings);
}
}
}
| |
using System;
using System.Collections;
using System.Data.SqlClient;
using System.IO;
using Rainbow.Framework;
using Rainbow.Framework.Content.Data;
using Rainbow.Framework.Site.Configuration;
using Rainbow.Framework.Web.UI;
using History=Rainbow.Framework.History;
using Path=Rainbow.Framework.Settings.Path;
namespace Rainbow.Content.Web.Modules
{
/// <summary>
/// Update and edit documents.
/// Update 14 nov 2002 - Bug on buttonclick events
/// </summary>
[History("Jes1111", "2003/03/04", "Cache flushing now handled by inherited page")]
[History("jviladiu@portalServices.net", "2004/07/02", "Corrections for save documents in database")]
public partial class DocumentsEdit : AddEditItemPage
{
#region Declarations
/// <summary>
///
/// </summary>
private string PathToSave;
#endregion
/// <summary>
/// The Page_Load event on this Page is used to obtain the ModuleID
/// and ItemID of the document to edit.
/// It then uses the DocumentDB() data component
/// to populate the page's edit controls with the document details.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
private void Page_Load(object sender, EventArgs e)
{
// If the page is being requested the first time, determine if an
// document itemID value is specified, and if so populate page
// contents with the document details
if (!Page.IsPostBack)
{
if (ModuleID > 0)
PathToSave = ((SettingItem) moduleSettings["DocumentPath"]).FullPath;
if (ItemID > 0)
{
// Obtain a single row of document information
DocumentDB documents = new DocumentDB();
SqlDataReader dr = documents.GetSingleDocument(ItemID, WorkFlowVersion.Staging);
try
{
// Load first row into Datareader
if (dr.Read())
{
NameField.Text = (string) dr["FileFriendlyName"];
PathField.Text = (string) dr["FileNameUrl"];
CategoryField.Text = (string) dr["Category"];
CreatedBy.Text = (string) dr["CreatedByUser"];
CreatedDate.Text = ((DateTime) dr["CreatedDate"]).ToShortDateString();
// 15/7/2004 added localization by Mario Endara mario@softworks.com.uy
if (CreatedBy.Text == "unknown")
{
CreatedBy.Text = General.GetString("UNKNOWN", "unknown");
}
}
}
finally
{
dr.Close();
}
}
}
}
/// <summary>
/// Set the module guids with free access to this page
/// </summary>
/// <value>The allowed modules.</value>
protected override ArrayList AllowedModules
{
get
{
ArrayList al = new ArrayList();
al.Add("F9645B82-CB45-4C4C-BB2D-72FA42FE2B75");
return al;
}
}
/// <summary>
/// The UpdateBtn_Click event handler on this Page is used to either
/// create or update an document. It uses the DocumentDB()
/// data component to encapsulate all data functionality.
/// </summary>
/// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
[History("jviladiu@portalServices.net", "2004/07/02", "Corrections for save documents in database")]
protected override void OnUpdate(EventArgs e)
{
base.OnUpdate(e);
byte[] buffer = new byte[0];
int size = 0;
// Only Update if Input Data is Valid
if (Page.IsValid)
{
// Create an instance of the Document DB component
DocumentDB documents = new DocumentDB();
// Determine whether a file was uploaded
if (FileUpload.PostedFile.FileName != string.Empty)
{
FileInfo fInfo = new FileInfo(FileUpload.PostedFile.FileName);
if (bool.Parse(moduleSettings["DOCUMENTS_DBSAVE"].ToString()))
{
Stream stream = FileUpload.PostedFile.InputStream;
buffer = new byte[FileUpload.PostedFile.ContentLength];
size = FileUpload.PostedFile.ContentLength;
try
{
stream.Read(buffer, 0, size);
PathField.Text = fInfo.Name;
}
finally
{
stream.Close(); //by manu
}
}
else
{
PathToSave = ((SettingItem) moduleSettings["DocumentPath"]).FullPath;
// jviladiu@portalServices.net (02/07/2004). Create the Directory if not exists.
if (!Directory.Exists(Server.MapPath(PathToSave)))
Directory.CreateDirectory(Server.MapPath(PathToSave));
string virtualPath = Path.WebPathCombine(PathToSave, fInfo.Name);
string physicalPath = Server.MapPath(virtualPath);
// while(System.IO.File.Exists(physicalPath))
// {
// // Calculate virtualPath of the newly uploaded file
// virtualPath = Rainbow.Framework.Settings.Path.WebPathCombine(PathToSave, Guid.NewGuid().ToString() + fInfo.Extension);
//
// // Calculate physical path of the newly uploaded file
// phyiscalPath = Server.MapPath(virtualPath);
// }
while (File.Exists(physicalPath))
{
try
{
// Delete file before upload
File.Delete(physicalPath);
}
catch (Exception ex)
{
Message.Text =
General.GetString("ERROR_FILE_DELETE", "Error while deleting file!<br>") +
ex.Message;
return;
}
}
try
{
// Save file to uploads directory
FileUpload.PostedFile.SaveAs(physicalPath);
// Update PathFile with uploaded virtual file location
PathField.Text = virtualPath;
}
catch (Exception ex)
{
Message.Text = General.GetString("ERROR_FILE_NAME", "Invalid file name!<br>") + ex.Message;
return;
}
}
}
// Change for save contenType and document buffer
// documents.UpdateDocument(ModuleID, ItemID, PortalSettings.CurrentUser.Identity.Email, NameField.Text, PathField.Text, CategoryField.Text, new byte[0], 0, string.Empty );
string contentType = PathField.Text.Substring(PathField.Text.LastIndexOf(".") + 1).ToLower();
documents.UpdateDocument(ModuleID, ItemID, PortalSettings.CurrentUser.Identity.Email, NameField.Text,
PathField.Text, CategoryField.Text, buffer, size, contentType);
RedirectBackToReferringPage();
}
}
/// <summary>
/// The DeleteBtn_Click event handler on this Page is used to delete an
/// a document. It uses the Rainbow.DocumentsDB()
/// data component to encapsulate all data functionality.
/// </summary>
/// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
protected override void OnDelete(EventArgs e)
{
base.OnDelete(e);
// Only attempt to delete the item if it is an existing item
// (new items will have "ItemID" of 0)
//TODO: Ask confim before delete
if (ItemID != 0)
{
DocumentDB documents = new DocumentDB();
documents.DeleteDocument(ItemID, Server.MapPath(PathField.Text));
}
RedirectBackToReferringPage();
}
#region Web Form Designer generated code
/// <summary>
/// Raises OnInitEvent
/// </summary>
/// <param name="e">An <see cref="T:System.EventArgs"></see> that contains the event data.</param>
protected override void OnInit(EventArgs e)
{
this.Load += new EventHandler(this.Page_Load);
//Translate
CreatedLabel.Text = General.GetString("CREATED_BY");
OnLabel.Text = General.GetString("ON");
PageTitleLabel.Text = General.GetString("DOCUMENT_DETAILS");
FileNameLabel.Text = General.GetString("FILE_NAME");
CategoryLabel.Text = General.GetString("CATEGORY");
UrlLabel.Text = General.GetString("URL");
UploadLabel.Text = General.GetString("UPLOAD_FILE");
OrLabel.Text = "---" + General.GetString("OR") + "---";
RequiredFieldValidator1.Text = General.GetString("VALID_FILE_NAME");
base.OnInit(e);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Web;
using Umbraco.Core.Models;
using Umbraco.Core.Models.PublishedContent;
using Umbraco.Web;
using Umbraco.ModelsBuilder;
using Umbraco.ModelsBuilder.Umbraco;
[assembly: PureLiveAssembly]
[assembly:ModelsBuilderAssembly(PureLive = true, SourceHash = "92e037532f784717")]
[assembly:System.Reflection.AssemblyVersion("0.0.0.1")]
// FILE: models.generated.cs
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Umbraco.ModelsBuilder v3.0.10.102
//
// Changes to this file will be lost if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Umbraco.Web.PublishedContentModels
{
/// <summary>Product</summary>
[PublishedContentModel("product")]
public partial class Product : PublishedContentModel
{
#pragma warning disable 0109 // new is redundant
public new const string ModelTypeAlias = "product";
public new const PublishedItemType ModelItemType = PublishedItemType.Content;
#pragma warning restore 0109
public Product(IPublishedContent content)
: base(content)
{ }
#pragma warning disable 0109 // new is redundant
public new static PublishedContentType GetModelContentType()
{
return PublishedContentType.Get(ModelItemType, ModelTypeAlias);
}
#pragma warning restore 0109
public static PublishedPropertyType GetModelPropertyType<TValue>(Expression<Func<Product, TValue>> selector)
{
return PublishedContentModelUtility.GetModelPropertyType(GetModelContentType(), selector);
}
///<summary>
/// Description
///</summary>
[ImplementPropertyType("description")]
public IHtmlString Description
{
get { return this.GetPropertyValue<IHtmlString>("description"); }
}
///<summary>
/// Image
///</summary>
[ImplementPropertyType("image")]
public IPublishedContent Image
{
get { return this.GetPropertyValue<IPublishedContent>("image"); }
}
///<summary>
/// Price
///</summary>
[ImplementPropertyType("priceJMD")]
public string PriceJmd
{
get { return this.GetPropertyValue<string>("priceJMD"); }
}
///<summary>
/// Name
///</summary>
[ImplementPropertyType("productName")]
public string ProductName
{
get { return this.GetPropertyValue<string>("productName"); }
}
///<summary>
/// SKU
///</summary>
[ImplementPropertyType("sku")]
public string Sku
{
get { return this.GetPropertyValue<string>("sku"); }
}
///<summary>
/// Stock
///</summary>
[ImplementPropertyType("stock")]
public object Stock
{
get { return this.GetPropertyValue("stock"); }
}
///<summary>
/// Variants
///</summary>
[ImplementPropertyType("variants")]
public Newtonsoft.Json.Linq.JToken Variants
{
get { return this.GetPropertyValue<Newtonsoft.Json.Linq.JToken>("variants"); }
}
}
/// <summary>Product list</summary>
[PublishedContentModel("productList")]
public partial class ProductList : PublishedContentModel
{
#pragma warning disable 0109 // new is redundant
public new const string ModelTypeAlias = "productList";
public new const PublishedItemType ModelItemType = PublishedItemType.Content;
#pragma warning restore 0109
public ProductList(IPublishedContent content)
: base(content)
{ }
#pragma warning disable 0109 // new is redundant
public new static PublishedContentType GetModelContentType()
{
return PublishedContentType.Get(ModelItemType, ModelTypeAlias);
}
#pragma warning restore 0109
public static PublishedPropertyType GetModelPropertyType<TValue>(Expression<Func<ProductList, TValue>> selector)
{
return PublishedContentModelUtility.GetModelPropertyType(GetModelContentType(), selector);
}
}
/// <summary>Cart step</summary>
[PublishedContentModel("cartStep")]
public partial class CartStep : PublishedContentModel
{
#pragma warning disable 0109 // new is redundant
public new const string ModelTypeAlias = "cartStep";
public new const PublishedItemType ModelItemType = PublishedItemType.Content;
#pragma warning restore 0109
public CartStep(IPublishedContent content)
: base(content)
{ }
#pragma warning disable 0109 // new is redundant
public new static PublishedContentType GetModelContentType()
{
return PublishedContentType.Get(ModelItemType, ModelTypeAlias);
}
#pragma warning restore 0109
public static PublishedPropertyType GetModelPropertyType<TValue>(Expression<Func<CartStep, TValue>> selector)
{
return PublishedContentModelUtility.GetModelPropertyType(GetModelContentType(), selector);
}
}
/// <summary>Frontpage</summary>
[PublishedContentModel("frontpage")]
public partial class Frontpage : PublishedContentModel
{
#pragma warning disable 0109 // new is redundant
public new const string ModelTypeAlias = "frontpage";
public new const PublishedItemType ModelItemType = PublishedItemType.Content;
#pragma warning restore 0109
public Frontpage(IPublishedContent content)
: base(content)
{ }
#pragma warning disable 0109 // new is redundant
public new static PublishedContentType GetModelContentType()
{
return PublishedContentType.Get(ModelItemType, ModelTypeAlias);
}
#pragma warning restore 0109
public static PublishedPropertyType GetModelPropertyType<TValue>(Expression<Func<Frontpage, TValue>> selector)
{
return PublishedContentModelUtility.GetModelPropertyType(GetModelContentType(), selector);
}
///<summary>
/// Featured products
///</summary>
[ImplementPropertyType("featuredProducts")]
public IEnumerable<IPublishedContent> FeaturedProducts
{
get { return this.GetPropertyValue<IEnumerable<IPublishedContent>>("featuredProducts"); }
}
///<summary>
/// Slider
///</summary>
[ImplementPropertyType("slider")]
public IEnumerable<IPublishedContent> Slider
{
get { return this.GetPropertyValue<IEnumerable<IPublishedContent>>("slider"); }
}
///<summary>
/// Store
///</summary>
[ImplementPropertyType("store")]
public object Store
{
get { return this.GetPropertyValue("store"); }
}
}
/// <summary>Cart</summary>
[PublishedContentModel("cart")]
public partial class Cart : PublishedContentModel
{
#pragma warning disable 0109 // new is redundant
public new const string ModelTypeAlias = "cart";
public new const PublishedItemType ModelItemType = PublishedItemType.Content;
#pragma warning restore 0109
public Cart(IPublishedContent content)
: base(content)
{ }
#pragma warning disable 0109 // new is redundant
public new static PublishedContentType GetModelContentType()
{
return PublishedContentType.Get(ModelItemType, ModelTypeAlias);
}
#pragma warning restore 0109
public static PublishedPropertyType GetModelPropertyType<TValue>(Expression<Func<Cart, TValue>> selector)
{
return PublishedContentModelUtility.GetModelPropertyType(GetModelContentType(), selector);
}
}
/// <summary>Variant</summary>
[PublishedContentModel("variant")]
public partial class Variant : PublishedContentModel
{
#pragma warning disable 0109 // new is redundant
public new const string ModelTypeAlias = "variant";
public new const PublishedItemType ModelItemType = PublishedItemType.Content;
#pragma warning restore 0109
public Variant(IPublishedContent content)
: base(content)
{ }
#pragma warning disable 0109 // new is redundant
public new static PublishedContentType GetModelContentType()
{
return PublishedContentType.Get(ModelItemType, ModelTypeAlias);
}
#pragma warning restore 0109
public static PublishedPropertyType GetModelPropertyType<TValue>(Expression<Func<Variant, TValue>> selector)
{
return PublishedContentModelUtility.GetModelPropertyType(GetModelContentType(), selector);
}
///<summary>
/// Price
///</summary>
[ImplementPropertyType("priceJMD")]
public string PriceJmd
{
get { return this.GetPropertyValue<string>("priceJMD"); }
}
///<summary>
/// Name
///</summary>
[ImplementPropertyType("productName")]
public string ProductName
{
get { return this.GetPropertyValue<string>("productName"); }
}
///<summary>
/// Sku
///</summary>
[ImplementPropertyType("sku")]
public string Sku
{
get { return this.GetPropertyValue<string>("sku"); }
}
///<summary>
/// Stock: Remember to add a sku for the product. Without a sku the variant cannot have it's own stock.
///</summary>
[ImplementPropertyType("stock")]
public object Stock
{
get { return this.GetPropertyValue("stock"); }
}
}
/// <summary>Attributes</summary>
[PublishedContentModel("attributes")]
public partial class Attributes : PublishedContentModel
{
#pragma warning disable 0109 // new is redundant
public new const string ModelTypeAlias = "attributes";
public new const PublishedItemType ModelItemType = PublishedItemType.Content;
#pragma warning restore 0109
public Attributes(IPublishedContent content)
: base(content)
{ }
#pragma warning disable 0109 // new is redundant
public new static PublishedContentType GetModelContentType()
{
return PublishedContentType.Get(ModelItemType, ModelTypeAlias);
}
#pragma warning restore 0109
public static PublishedPropertyType GetModelPropertyType<TValue>(Expression<Func<Attributes, TValue>> selector)
{
return PublishedContentModelUtility.GetModelPropertyType(GetModelContentType(), selector);
}
}
/// <summary>Attribute group</summary>
[PublishedContentModel("attributeGroup")]
public partial class AttributeGroup : PublishedContentModel
{
#pragma warning disable 0109 // new is redundant
public new const string ModelTypeAlias = "attributeGroup";
public new const PublishedItemType ModelItemType = PublishedItemType.Content;
#pragma warning restore 0109
public AttributeGroup(IPublishedContent content)
: base(content)
{ }
#pragma warning disable 0109 // new is redundant
public new static PublishedContentType GetModelContentType()
{
return PublishedContentType.Get(ModelItemType, ModelTypeAlias);
}
#pragma warning restore 0109
public static PublishedPropertyType GetModelPropertyType<TValue>(Expression<Func<AttributeGroup, TValue>> selector)
{
return PublishedContentModelUtility.GetModelPropertyType(GetModelContentType(), selector);
}
}
/// <summary>Attribute</summary>
[PublishedContentModel("attribute")]
public partial class Attribute : PublishedContentModel
{
#pragma warning disable 0109 // new is redundant
public new const string ModelTypeAlias = "attribute";
public new const PublishedItemType ModelItemType = PublishedItemType.Content;
#pragma warning restore 0109
public Attribute(IPublishedContent content)
: base(content)
{ }
#pragma warning disable 0109 // new is redundant
public new static PublishedContentType GetModelContentType()
{
return PublishedContentType.Get(ModelItemType, ModelTypeAlias);
}
#pragma warning restore 0109
public static PublishedPropertyType GetModelPropertyType<TValue>(Expression<Func<Attribute, TValue>> selector)
{
return PublishedContentModelUtility.GetModelPropertyType(GetModelContentType(), selector);
}
}
/// <summary>Folder</summary>
[PublishedContentModel("Folder")]
public partial class Folder : PublishedContentModel
{
#pragma warning disable 0109 // new is redundant
public new const string ModelTypeAlias = "Folder";
public new const PublishedItemType ModelItemType = PublishedItemType.Media;
#pragma warning restore 0109
public Folder(IPublishedContent content)
: base(content)
{ }
#pragma warning disable 0109 // new is redundant
public new static PublishedContentType GetModelContentType()
{
return PublishedContentType.Get(ModelItemType, ModelTypeAlias);
}
#pragma warning restore 0109
public static PublishedPropertyType GetModelPropertyType<TValue>(Expression<Func<Folder, TValue>> selector)
{
return PublishedContentModelUtility.GetModelPropertyType(GetModelContentType(), selector);
}
///<summary>
/// Contents:
///</summary>
[ImplementPropertyType("contents")]
public object Contents
{
get { return this.GetPropertyValue("contents"); }
}
}
/// <summary>Image</summary>
[PublishedContentModel("Image")]
public partial class Image : PublishedContentModel
{
#pragma warning disable 0109 // new is redundant
public new const string ModelTypeAlias = "Image";
public new const PublishedItemType ModelItemType = PublishedItemType.Media;
#pragma warning restore 0109
public Image(IPublishedContent content)
: base(content)
{ }
#pragma warning disable 0109 // new is redundant
public new static PublishedContentType GetModelContentType()
{
return PublishedContentType.Get(ModelItemType, ModelTypeAlias);
}
#pragma warning restore 0109
public static PublishedPropertyType GetModelPropertyType<TValue>(Expression<Func<Image, TValue>> selector)
{
return PublishedContentModelUtility.GetModelPropertyType(GetModelContentType(), selector);
}
///<summary>
/// Size
///</summary>
[ImplementPropertyType("umbracoBytes")]
public string UmbracoBytes
{
get { return this.GetPropertyValue<string>("umbracoBytes"); }
}
///<summary>
/// Type
///</summary>
[ImplementPropertyType("umbracoExtension")]
public string UmbracoExtension
{
get { return this.GetPropertyValue<string>("umbracoExtension"); }
}
///<summary>
/// Upload image
///</summary>
[ImplementPropertyType("umbracoFile")]
public string UmbracoFile
{
get { return this.GetPropertyValue<string>("umbracoFile"); }
}
///<summary>
/// Height
///</summary>
[ImplementPropertyType("umbracoHeight")]
public string UmbracoHeight
{
get { return this.GetPropertyValue<string>("umbracoHeight"); }
}
///<summary>
/// Width
///</summary>
[ImplementPropertyType("umbracoWidth")]
public string UmbracoWidth
{
get { return this.GetPropertyValue<string>("umbracoWidth"); }
}
}
/// <summary>File</summary>
[PublishedContentModel("File")]
public partial class File : PublishedContentModel
{
#pragma warning disable 0109 // new is redundant
public new const string ModelTypeAlias = "File";
public new const PublishedItemType ModelItemType = PublishedItemType.Media;
#pragma warning restore 0109
public File(IPublishedContent content)
: base(content)
{ }
#pragma warning disable 0109 // new is redundant
public new static PublishedContentType GetModelContentType()
{
return PublishedContentType.Get(ModelItemType, ModelTypeAlias);
}
#pragma warning restore 0109
public static PublishedPropertyType GetModelPropertyType<TValue>(Expression<Func<File, TValue>> selector)
{
return PublishedContentModelUtility.GetModelPropertyType(GetModelContentType(), selector);
}
///<summary>
/// Size
///</summary>
[ImplementPropertyType("umbracoBytes")]
public string UmbracoBytes
{
get { return this.GetPropertyValue<string>("umbracoBytes"); }
}
///<summary>
/// Type
///</summary>
[ImplementPropertyType("umbracoExtension")]
public string UmbracoExtension
{
get { return this.GetPropertyValue<string>("umbracoExtension"); }
}
///<summary>
/// Upload file
///</summary>
[ImplementPropertyType("umbracoFile")]
public string UmbracoFile
{
get { return this.GetPropertyValue<string>("umbracoFile"); }
}
}
/// <summary>Member</summary>
[PublishedContentModel("Member")]
public partial class Member : PublishedContentModel
{
#pragma warning disable 0109 // new is redundant
public new const string ModelTypeAlias = "Member";
public new const PublishedItemType ModelItemType = PublishedItemType.Member;
#pragma warning restore 0109
public Member(IPublishedContent content)
: base(content)
{ }
#pragma warning disable 0109 // new is redundant
public new static PublishedContentType GetModelContentType()
{
return PublishedContentType.Get(ModelItemType, ModelTypeAlias);
}
#pragma warning restore 0109
public static PublishedPropertyType GetModelPropertyType<TValue>(Expression<Func<Member, TValue>> selector)
{
return PublishedContentModelUtility.GetModelPropertyType(GetModelContentType(), selector);
}
///<summary>
/// Is Approved
///</summary>
[ImplementPropertyType("umbracoMemberApproved")]
public bool UmbracoMemberApproved
{
get { return this.GetPropertyValue<bool>("umbracoMemberApproved"); }
}
///<summary>
/// Comments
///</summary>
[ImplementPropertyType("umbracoMemberComments")]
public string UmbracoMemberComments
{
get { return this.GetPropertyValue<string>("umbracoMemberComments"); }
}
///<summary>
/// Failed Password Attempts
///</summary>
[ImplementPropertyType("umbracoMemberFailedPasswordAttempts")]
public string UmbracoMemberFailedPasswordAttempts
{
get { return this.GetPropertyValue<string>("umbracoMemberFailedPasswordAttempts"); }
}
///<summary>
/// Last Lockout Date
///</summary>
[ImplementPropertyType("umbracoMemberLastLockoutDate")]
public string UmbracoMemberLastLockoutDate
{
get { return this.GetPropertyValue<string>("umbracoMemberLastLockoutDate"); }
}
///<summary>
/// Last Login Date
///</summary>
[ImplementPropertyType("umbracoMemberLastLogin")]
public string UmbracoMemberLastLogin
{
get { return this.GetPropertyValue<string>("umbracoMemberLastLogin"); }
}
///<summary>
/// Last Password Change Date
///</summary>
[ImplementPropertyType("umbracoMemberLastPasswordChangeDate")]
public string UmbracoMemberLastPasswordChangeDate
{
get { return this.GetPropertyValue<string>("umbracoMemberLastPasswordChangeDate"); }
}
///<summary>
/// Is Locked Out
///</summary>
[ImplementPropertyType("umbracoMemberLockedOut")]
public bool UmbracoMemberLockedOut
{
get { return this.GetPropertyValue<bool>("umbracoMemberLockedOut"); }
}
///<summary>
/// Password Answer
///</summary>
[ImplementPropertyType("umbracoMemberPasswordRetrievalAnswer")]
public string UmbracoMemberPasswordRetrievalAnswer
{
get { return this.GetPropertyValue<string>("umbracoMemberPasswordRetrievalAnswer"); }
}
///<summary>
/// Password Question
///</summary>
[ImplementPropertyType("umbracoMemberPasswordRetrievalQuestion")]
public string UmbracoMemberPasswordRetrievalQuestion
{
get { return this.GetPropertyValue<string>("umbracoMemberPasswordRetrievalQuestion"); }
}
}
}
// EOF
| |
//
// DockItemContainer.cs
//
// Author:
// Lluis Sanchez Gual
//
//
// Copyright (C) 2007 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using Gtk;
using Mono.Unix;
namespace Pinta.Docking
{
class DockItemContainer: EventBox
{
DockItem item;
Widget widget;
Container borderFrame;
Box contentBox;
VBox mainBox;
public DockItemContainer (DockFrame frame, DockItem item)
{
this.item = item;
mainBox = new VBox ();
Add (mainBox);
mainBox.ResizeMode = Gtk.ResizeMode.Queue;
mainBox.Spacing = 0;
ShowAll ();
mainBox.PackStart (item.GetToolbar (PositionType.Top).Container, false, false, 0);
HBox hbox = new HBox ();
hbox.Show ();
hbox.PackStart (item.GetToolbar (PositionType.Left).Container, false, false, 0);
contentBox = new HBox ();
contentBox.Show ();
hbox.PackStart (contentBox, true, true, 0);
hbox.PackStart (item.GetToolbar (PositionType.Right).Container, false, false, 0);
mainBox.PackStart (hbox, true, true, 0);
mainBox.PackStart (item.GetToolbar (PositionType.Bottom).Container, false, false, 0);
}
DockVisualStyle visualStyle;
public DockVisualStyle VisualStyle {
get { return visualStyle; }
set { visualStyle = value; UpdateVisualStyle (); }
}
void OnClickDock (object s, EventArgs a)
{
if (item.Status == DockItemStatus.AutoHide || item.Status == DockItemStatus.Floating)
item.Status = DockItemStatus.Dockable;
else
item.Status = DockItemStatus.AutoHide;
}
public void UpdateContent ()
{
if (widget != null)
((Gtk.Container)widget.Parent).Remove (widget);
widget = item.Content;
if (item.DrawFrame) {
if (borderFrame == null) {
borderFrame = new CustomFrame (1, 1, 1, 1);
borderFrame.Show ();
contentBox.Add (borderFrame);
}
if (widget != null) {
borderFrame.Add (widget);
widget.Show ();
}
}
else if (widget != null) {
if (borderFrame != null) {
contentBox.Remove (borderFrame);
borderFrame = null;
}
contentBox.Add (widget);
widget.Show ();
}
UpdateVisualStyle ();
}
void UpdateVisualStyle ()
{
if (VisualStyle != null) {
if (widget != null)
SetTreeStyle (widget);
item.GetToolbar (PositionType.Top).SetStyle (VisualStyle);
item.GetToolbar (PositionType.Left).SetStyle (VisualStyle);
item.GetToolbar (PositionType.Right).SetStyle (VisualStyle);
item.GetToolbar (PositionType.Bottom).SetStyle (VisualStyle);
}
}
void SetTreeStyle (Gtk.Widget w)
{
if (w is Gtk.TreeView) {
if (w.IsRealized)
OnTreeRealized (w, null);
else
w.Realized += OnTreeRealized;
}
else {
var c = w as Gtk.Container;
if (c != null) {
foreach (var cw in c.Children)
SetTreeStyle (cw);
}
}
}
void OnTreeRealized (object sender, EventArgs e)
{
var w = (Gtk.TreeView)sender;
if (VisualStyle.TreeBackgroundColor != null) {
w.ModifyBase (StateType.Normal, VisualStyle.TreeBackgroundColor.Value);
w.ModifyBase (StateType.Insensitive, VisualStyle.TreeBackgroundColor.Value);
} else {
w.ModifyBase (StateType.Normal, Parent.Style.Base (StateType.Normal));
w.ModifyBase (StateType.Insensitive, Parent.Style.Base (StateType.Insensitive));
}
}
protected override bool OnExposeEvent (Gdk.EventExpose evnt)
{
if (VisualStyle.TabStyle == DockTabStyle.Normal) {
Gdk.GC gc = new Gdk.GC (GdkWindow);
gc.RgbFgColor = VisualStyle.PadBackgroundColor.Value;
evnt.Window.DrawRectangle (gc, true, Allocation);
gc.Dispose ();
}
return base.OnExposeEvent (evnt);
}
}
class CustomFrame: Bin
{
Gtk.Widget child;
int topMargin;
int bottomMargin;
int leftMargin;
int rightMargin;
int topPadding;
int bottomPadding;
int leftPadding;
int rightPadding;
Gdk.Color backgroundColor;
bool backgroundColorSet;
public CustomFrame ()
{
}
public CustomFrame (int topMargin, int bottomMargin, int leftMargin, int rightMargin)
{
SetMargins (topMargin, bottomMargin, leftMargin, rightMargin);
}
public void SetMargins (int topMargin, int bottomMargin, int leftMargin, int rightMargin)
{
this.topMargin = topMargin;
this.bottomMargin = bottomMargin;
this.leftMargin = leftMargin;
this.rightMargin = rightMargin;
}
public void SetPadding (int topPadding, int bottomPadding, int leftPadding, int rightPadding)
{
this.topPadding = topPadding;
this.bottomPadding = bottomPadding;
this.leftPadding = leftPadding;
this.rightPadding = rightPadding;
}
public bool GradientBackround { get; set; }
public Gdk.Color BackgroundColor {
get { return backgroundColor; }
set { backgroundColor = value; backgroundColorSet = true; }
}
protected override void OnAdded (Widget widget)
{
base.OnAdded (widget);
child = widget;
}
protected override void OnRemoved (Widget widget)
{
base.OnRemoved (widget);
child = null;
}
protected override void OnSizeRequested (ref Requisition requisition)
{
if (child != null) {
requisition = child.SizeRequest ();
requisition.Width += leftMargin + rightMargin + leftPadding + rightPadding;
requisition.Height += topMargin + bottomMargin + topPadding + bottomPadding;
} else {
requisition.Width = 0;
requisition.Height = 0;
}
}
protected override void OnSizeAllocated (Gdk.Rectangle allocation)
{
base.OnSizeAllocated (allocation);
if (allocation.Width > leftMargin + rightMargin + leftPadding + rightPadding) {
allocation.X += leftMargin + leftPadding;
allocation.Width -= leftMargin + rightMargin + leftPadding + rightPadding;
}
if (allocation.Height > topMargin + bottomMargin + topPadding + bottomPadding) {
allocation.Y += topMargin + topPadding;
allocation.Height -= topMargin + bottomMargin + topPadding + bottomPadding;
}
if (child != null)
child.SizeAllocate (allocation);
}
protected override bool OnExposeEvent (Gdk.EventExpose evnt)
{
Gdk.Rectangle rect = Allocation;
//Gdk.Rectangle.Right and Bottom are inconsistent
int right = rect.X + rect.Width, bottom = rect.Y + rect.Height;
var bcolor = backgroundColorSet ? BackgroundColor : Style.Background (Gtk.StateType.Normal);
using (Cairo.Context cr = Gdk.CairoHelper.Create (evnt.Window)) {
if (GradientBackround) {
cr.NewPath ();
cr.MoveTo (rect.X, rect.Y);
cr.RelLineTo (rect.Width, 0);
cr.RelLineTo (0, rect.Height);
cr.RelLineTo (-rect.Width, 0);
cr.RelLineTo (0, -rect.Height);
cr.ClosePath ();
using (Cairo.Gradient pat = new Cairo.LinearGradient (rect.X, rect.Y, rect.X, bottom)) {
pat.AddColorStop (0, bcolor.ToCairoColor ());
Xwt.Drawing.Color gcol = bcolor.ToXwtColor ();
gcol.Light -= 0.1;
if (gcol.Light < 0)
gcol.Light = 0;
pat.AddColorStop (1, gcol.ToCairoColor ());
cr.SetSource (pat);
cr.Fill ();
}
} else {
if (backgroundColorSet) {
Gdk.GC gc = new Gdk.GC (GdkWindow);
gc.RgbFgColor = bcolor;
evnt.Window.DrawRectangle (gc, true, rect.X, rect.Y, rect.Width, rect.Height);
gc.Dispose ();
}
}
}
base.OnExposeEvent (evnt);
using (Cairo.Context cr = Gdk.CairoHelper.Create (evnt.Window)) {
cr.SetSourceColor (Style.Dark (Gtk.StateType.Normal).ToCairoColor ());
double y = rect.Y + topMargin / 2d;
cr.LineWidth = topMargin;
cr.Line (rect.X, y, right, y);
cr.Stroke ();
y = bottom - bottomMargin / 2d;
cr.LineWidth = bottomMargin;
cr.Line (rect.X, y, right, y);
cr.Stroke ();
double x = rect.X + leftMargin / 2d;
cr.LineWidth = leftMargin;
cr.Line (x, rect.Y, x, bottom);
cr.Stroke ();
x = right - rightMargin / 2d;
cr.LineWidth = rightMargin;
cr.Line (x, rect.Y, x, bottom);
cr.Stroke ();
return false;
}
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="ModuleInfo.cs" company="Protobuild Project">
// The MIT License (MIT)
//
// Copyright (c) Various Authors
//
// 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.Xml;
using System.Xml.Linq;
namespace Protobuild
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml.Serialization;
/// <summary>
/// Represents a Protobuild module.
/// </summary>
public class ModuleInfo
{
/// <summary>
/// Initializes a new instance of the <see cref="Protobuild.ModuleInfo"/> class.
/// </summary>
public ModuleInfo()
{
this.DefaultAction = "resync";
this.GenerateNuGetRepositories = true;
}
/// <summary>
/// Gets or sets the name of the module.
/// </summary>
/// <value>The module name.</value>
public string Name { get; set; }
/// <summary>
/// The root path of this module.
/// </summary>
public string Path { get; set; }
/// <summary>
/// Gets or sets the default action to be taken when Protobuild runs in the module.
/// </summary>
/// <value>The default action that Protobuild will take.</value>
public string DefaultAction { get; set; }
/// <summary>
/// Gets or sets a comma seperated list of default platforms when the host platform is Windows.
/// </summary>
/// <value>The comma seperated list of default platforms when the host platform is Windows.</value>
public string DefaultWindowsPlatforms { get; set; }
/// <summary>
/// Gets or sets a comma seperated list of default platforms when the host platform is Mac OS.
/// </summary>
/// <value>The comma seperated list of default platforms when the host platform is Mac OS.</value>
public string DefaultMacOSPlatforms { get; set; }
/// <summary>
/// Gets or sets a comma seperated list of default platforms when the host platform is Linux.
/// </summary>
/// <value>The comma seperated list of default platforms when the host platform is Linux.</value>
public string DefaultLinuxPlatforms { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the NuGet repositories.config file is generated.
/// </summary>
/// <value><c>true</c> if the NuGet repositories.config file is generated; otherwise, <c>false</c>.</value>
public bool GenerateNuGetRepositories { get; set; }
/// <summary>
/// Gets or sets a comma seperated list of supported platforms in this module.
/// </summary>
/// <value>The comma seperated list of supported platforms.</value>
public string SupportedPlatforms { get; set; }
/// <summary>
/// Gets or sets a value indicating whether synchronisation is completely disabled in this module.
/// </summary>
/// <value><c>true</c> if synchronisation is disabled and will be skipped; otherwise, <c>false</c>.</value>
public bool? DisableSynchronisation { get; set; }
/// <summary>
/// Gets or sets the name of the default startup project.
/// </summary>
/// <value>The name of the default startup project.</value>
public string DefaultStartupProject { get; set; }
/// <summary>
/// Gets or sets a set of package references.
/// </summary>
/// <value>The registered packages.</value>
public List<PackageRef> Packages { get; set; }
/// <summary>
/// Loads the Protobuild module from the Module.xml file.
/// </summary>
/// <param name="xmlFile">The path to a Module.xml file.</param>
/// <returns>The loaded Protobuild module.</returns>
public static ModuleInfo Load(string xmlFile)
{
var def = new ModuleInfo();
var doc = XDocument.Load(xmlFile);
var xsi = doc.Root == null ? null : doc.Root.Attribute(XName.Get("xsi", "http://www.w3.org/2000/xmlns/"));
if (xsi != null && xsi.Value == "http://www.w3.org/2001/XMLSchema-instance")
{
// This is a previous module info format.
var serializer = new XmlSerializer(typeof(ModuleInfo));
var reader = new StreamReader(xmlFile);
var module = (ModuleInfo)serializer.Deserialize(reader);
module.Path = new FileInfo(xmlFile).Directory.Parent.FullName;
reader.Close();
// Re-save in the new format.
if (xmlFile == System.IO.Path.Combine("Build", "Module.xml"))
{
module.Save(xmlFile);
}
return module;
}
Func<string, string> getStringValue = name =>
{
if (doc.Root == null)
{
return null;
}
var elem = doc.Root.Element(XName.Get(name));
if (elem == null)
{
return null;
}
return elem.Value;
};
def.Name = getStringValue("Name");
def.Path = new FileInfo(xmlFile).Directory.Parent.FullName;
def.DefaultAction = getStringValue("DefaultAction");
def.DefaultLinuxPlatforms = getStringValue("DefaultLinuxPlatforms");
def.DefaultMacOSPlatforms = getStringValue("DefaultMacOSPlatforms");
def.DefaultWindowsPlatforms = getStringValue("DefaultWindowsPlatforms");
def.DefaultStartupProject = getStringValue("DefaultStartupProject");
def.SupportedPlatforms = getStringValue("SupportedPlatforms");
def.DisableSynchronisation = getStringValue("DisableSynchronisation") == "true";
def.GenerateNuGetRepositories = getStringValue("GenerateNuGetRepositories") == "true";
def.Packages = new List<PackageRef>();
if (doc.Root != null)
{
var packagesElem = doc.Root.Element(XName.Get("Packages"));
if (packagesElem != null)
{
var packages = packagesElem.Elements();
foreach (var package in packages)
{
def.Packages.Add(new PackageRef
{
Folder = package.Attribute(XName.Get("Folder")).Value,
GitRef = package.Attribute(XName.Get("GitRef")).Value,
Uri = package.Attribute(XName.Get("Uri")).Value,
});
}
}
}
return def;
}
/// <summary>
/// Loads all of the project definitions present in the current module.
/// </summary>
/// <returns>The loaded project definitions.</returns>
public DefinitionInfo[] GetDefinitions()
{
var result = new List<DefinitionInfo>();
var path = System.IO.Path.Combine(this.Path, "Build", "Projects");
if (!Directory.Exists(path))
{
return new DefinitionInfo[0];
}
foreach (var file in new DirectoryInfo(path).GetFiles("*.definition"))
{
result.Add(DefinitionInfo.Load(file.FullName));
}
return result.ToArray();
}
/// <summary>
/// Loads all of the project definitions present in the current module and all submodules.
/// </summary>
/// <returns>The loaded project definitions.</returns>
/// <param name="relative">The current directory being scanned.</param>
public IEnumerable<DefinitionInfo> GetDefinitionsRecursively(string platform = null, string relative = "")
{
var definitions = new List<DefinitionInfo>();
foreach (var definition in this.GetDefinitions())
{
definition.AbsolutePath = (this.Path + '\\' + definition.RelativePath).Trim('\\');
definition.RelativePath = (relative + '\\' + definition.RelativePath).Trim('\\');
definition.ModulePath = this.Path;
definitions.Add(definition);
}
foreach (var submodule in this.GetSubmodules(platform))
{
var from = this.Path.Replace('\\', '/').TrimEnd('/') + "/";
var to = submodule.Path.Replace('\\', '/');
var subRelativePath = (new Uri(from).MakeRelativeUri(new Uri(to)))
.ToString().Replace('/', '\\');
foreach (var definition in submodule.GetDefinitionsRecursively(platform, subRelativePath.Trim('\\')))
{
definitions.Add(definition);
}
}
return definitions.Distinct(new DefinitionEqualityComparer());
}
private class DefinitionEqualityComparer : IEqualityComparer<DefinitionInfo>
{
public bool Equals(DefinitionInfo a, DefinitionInfo b)
{
return a.ModulePath == b.ModulePath &&
a.Name == b.Name;
}
public int GetHashCode(DefinitionInfo obj)
{
return obj.ModulePath.GetHashCode() + obj.Name.GetHashCode() * 37;
}
}
/// <summary>
/// Loads all of the submodules present in this module.
/// </summary>
/// <returns>The loaded submodules.</returns>
public ModuleInfo[] GetSubmodules(string platform = null)
{
var modules = new List<ModuleInfo>();
foreach (var directoryInit in new DirectoryInfo(this.Path).GetDirectories())
{
var directory = directoryInit;
if (File.Exists(System.IO.Path.Combine(directory.FullName, ".redirect")))
{
// This is a redirected submodule (due to package resolution). Load the
// module from it's actual path.
using (var reader = new StreamReader(System.IO.Path.Combine(directory.FullName, ".redirect")))
{
var targetPath = reader.ReadToEnd().Trim();
directory = new DirectoryInfo(targetPath);
}
}
var build = directory.GetDirectories().FirstOrDefault(x => x.Name == "Build");
if (build == null)
{
continue;
}
var module = build.GetFiles().FirstOrDefault(x => x.Name == "Module.xml");
if (module == null)
{
continue;
}
modules.Add(ModuleInfo.Load(module.FullName));
}
if (platform != null)
{
foreach (var directoryInit in new DirectoryInfo(this.Path).GetDirectories())
{
var directory = directoryInit;
if (File.Exists(System.IO.Path.Combine(directory.FullName, ".redirect")))
{
// This is a redirected submodule (due to package resolution). Load the
// module from it's actual path.
using (var reader = new StreamReader(System.IO.Path.Combine(directory.FullName, ".redirect")))
{
var targetPath = reader.ReadToEnd().Trim();
directory = new DirectoryInfo(targetPath);
}
}
var platformDirectory = new DirectoryInfo(System.IO.Path.Combine(directory.FullName, platform));
if (!platformDirectory.Exists)
{
continue;
}
var build = platformDirectory.GetDirectories().FirstOrDefault(x => x.Name == "Build");
if (build == null)
{
continue;
}
var module = build.GetFiles().FirstOrDefault(x => x.Name == "Module.xml");
if (module == null)
{
continue;
}
modules.Add(ModuleInfo.Load(module.FullName));
}
}
return modules.ToArray();
}
/// <summary>
/// Saves the current module to a Module.xml file.
/// </summary>
/// <param name="xmlFile">The path to a Module.xml file.</param>
public void Save(string xmlFile)
{
var doc = new XmlDocument();
var root = doc.CreateElement("Module");
doc.AppendChild(root);
Action<string, string> createStringElement = (name, val) =>
{
if (val != null)
{
var e = doc.CreateElement(name);
e.InnerText = val;
root.AppendChild(e);
}
};
Action<string, bool?> createBooleanElement = (name, val) =>
{
if (val != null)
{
var e = doc.CreateElement(name);
e.InnerText = val.Value ? "true" : "false";
root.AppendChild(e);
}
};
createStringElement("Name", Name);
createStringElement("DefaultAction", DefaultAction);
createStringElement("DefaultLinuxPlatforms", DefaultLinuxPlatforms);
createStringElement("DefaultMacOSPlatforms", DefaultMacOSPlatforms);
createStringElement("DefaultWindowsPlatforms", DefaultWindowsPlatforms);
createStringElement("DefaultStartupProject", DefaultStartupProject);
createStringElement("SupportedPlatforms", SupportedPlatforms);
createBooleanElement("DisableSynchronisation", DisableSynchronisation);
createBooleanElement("GenerateNuGetRepositories", GenerateNuGetRepositories);
if (Packages != null && Packages.Count > 0)
{
var elem = doc.CreateElement("Packages");
root.AppendChild(elem);
foreach (var package in Packages)
{
var packageElem = doc.CreateElement("Package");
packageElem.SetAttribute("Uri", package.Uri);
packageElem.SetAttribute("Folder", package.Folder);
packageElem.SetAttribute("GitRef", package.GitRef);
elem.AppendChild(packageElem);
}
}
using (var writer = XmlWriter.Create(xmlFile, new XmlWriterSettings {Indent = true, IndentChars = " "}))
{
doc.Save(writer);
}
}
private string[] featureCache;
/// <summary>
/// Determines whether the instance of Protobuild in this module
/// has a specified feature.
/// </summary>
public bool HasProtobuildFeature(string feature)
{
if (featureCache == null)
{
var result = this.RunProtobuild("--query-features", true);
var exitCode = result.Item1;
var stdout = result.Item2;
if (exitCode != 0 || stdout.Contains("Protobuild.exe [options]"))
{
featureCache = new string[0];
}
featureCache = stdout.Split('\n');
}
return featureCache.Contains(feature);
}
/// <summary>
/// Runs the instance of Protobuild.exe present in the module.
/// </summary>
/// <param name="args">The arguments to pass to Protobuild.</param>
public Tuple<int, string, string> RunProtobuild(string args, bool capture = false)
{
if (ExecEnvironment.RunProtobuildInProcess && !capture)
{
var old = Environment.CurrentDirectory;
try
{
Environment.CurrentDirectory = this.Path;
return new Tuple<int, string, string>(
ExecEnvironment.InvokeSelf(args.Split(' ')),
string.Empty,
string.Empty);
}
finally
{
Environment.CurrentDirectory = old;
}
}
var protobuildPath = System.IO.Path.Combine(this.Path, "Protobuild.exe");
try
{
var chmodStartInfo = new ProcessStartInfo
{
FileName = "chmod",
Arguments = "a+x Protobuild.exe",
WorkingDirectory = this.Path,
CreateNoWindow = true,
UseShellExecute = false
};
Process.Start(chmodStartInfo);
}
catch (ExecEnvironment.SelfInvokeExitException)
{
throw;
}
catch
{
}
var stdout = string.Empty;
var stderr = string.Empty;
for (var attempt = 0; attempt < 3; attempt++)
{
if (File.Exists(protobuildPath))
{
var pi = new ProcessStartInfo
{
FileName = protobuildPath,
Arguments = args,
WorkingDirectory = this.Path,
CreateNoWindow = true,
RedirectStandardError = true,
RedirectStandardInput = true,
RedirectStandardOutput = true,
UseShellExecute = false
};
var p = new Process { StartInfo = pi };
p.OutputDataReceived += (sender, eventArgs) =>
{
if (!string.IsNullOrEmpty(eventArgs.Data))
{
if (capture)
{
stdout += eventArgs.Data + "\n";
}
else
{
Console.WriteLine(eventArgs.Data);
}
}
};
p.ErrorDataReceived += (sender, eventArgs) =>
{
if (!string.IsNullOrEmpty(eventArgs.Data))
{
if (capture)
{
stderr += eventArgs.Data + "\n";
}
else
{
Console.Error.WriteLine(eventArgs.Data);
}
}
};
try
{
p.Start();
}
catch (System.ComponentModel.Win32Exception ex)
{
if (ex.Message.Contains("Cannot find the specified file"))
{
// Mono sometimes throws this error even though the
// file does exist on disk. The best guess is there's
// a race condition between performing chmod on the
// file and Mono actually seeing it as an executable file.
// Show a warning and sleep for a bit before retrying.
if (attempt != 2)
{
Console.WriteLine("WARNING: Unable to execute Protobuild.exe, will retry again...");
System.Threading.Thread.Sleep(2000);
continue;
}
else
{
Console.WriteLine("ERROR: Still unable to execute Protobuild.exe.");
throw;
}
}
}
p.BeginOutputReadLine();
p.BeginErrorReadLine();
p.WaitForExit();
return new Tuple<int, string, string>(p.ExitCode, stdout, stderr);
}
}
return new Tuple<int, string, string>(1, string.Empty, string.Empty);
}
/// <summary>
/// Normalizes the platform string from user input, automatically correcting case
/// and validating against a list of supported platforms.
/// </summary>
/// <returns>The platform string.</returns>
/// <param name="platform">The normalized platform string.</param>
public string NormalizePlatform(string platform)
{
var supportedPlatforms = "Android,iOS,Linux,MacOS,Ouya,PCL,PSMobile,Windows,Windows8,WindowsGL,WindowsPhone,WindowsPhone81";
var defaultPlatforms = true;
if (!string.IsNullOrEmpty(this.SupportedPlatforms))
{
supportedPlatforms = this.SupportedPlatforms;
defaultPlatforms = false;
}
var supportedPlatformsArray = supportedPlatforms.Split(new[] { ',' })
.Select(x => x.Trim())
.Where(x => !string.IsNullOrWhiteSpace(x))
.ToArray();
// Search the array to find a platform that matches case insensitively
// to the specified platform. If we are using the default list, then we allow
// other platforms to be specified (in case the developer has modified the XSLT to
// support others but is not using <SupportedPlatforms>). If the developer has
// explicitly set the supported platforms, then we return null if the user passes
// an unknown platform (the caller is expected to exit at this point).
foreach (var supportedPlatform in supportedPlatformsArray)
{
if (string.Compare(supportedPlatform, platform, true) == 0)
{
return supportedPlatform;
}
}
if (defaultPlatforms)
{
return platform;
}
else
{
return null;
}
}
}
}
| |
//-----------------------------------------------------------------------------
// Torque
// Copyright GarageGames, LLC 2011
//-----------------------------------------------------------------------------
if ( isObject( moveMap ) )
moveMap.delete();
new ActionMap(moveMap);
//------------------------------------------------------------------------------
// Non-remapable binds
//------------------------------------------------------------------------------
function escapeFromGame()
{
if ( $Server::ServerType $= "SinglePlayer" )
MessageBoxYesNo( "Exit", "Exit from this Mission?", "disconnect();", "");
else
MessageBoxYesNo( "Disconnect", "Disconnect from the server?", "disconnect();", "");
}
moveMap.bindCmd(keyboard, "escape", "", "handleEscape();");
function showPlayerList(%val)
{
if (%val)
PlayerListGui.toggle();
}
moveMap.bind( keyboard, F2, showPlayerList );
function showControlsHelp(%val)
{
if (%val)
ControlsHelpDlg.toggle();
}
moveMap.bind(keyboard, h, showControlsHelp);
function hideHUDs(%val)
{
if (%val)
HudlessPlayGui.toggle();
}
moveMap.bind(keyboard, "ctrl h", hideHUDs);
function doScreenShotHudless(%val)
{
if(%val)
{
canvas.setContent(HudlessPlayGui);
//doScreenshot(%val);
schedule(10, 0, "doScreenShot", %val);
}
else
canvas.setContent(PlayGui);
}
moveMap.bind(keyboard, "alt p", doScreenShotHudless);
//------------------------------------------------------------------------------
// Movement Keys
//------------------------------------------------------------------------------
$movementSpeed = 1; // m/s
function setSpeed(%speed)
{
if(%speed)
$movementSpeed = %speed;
}
function moveleft(%val)
{
$mvLeftAction = %val * $movementSpeed;
}
function moveright(%val)
{
$mvRightAction = %val * $movementSpeed;
}
function moveforward(%val)
{
$mvForwardAction = %val * $movementSpeed;
}
function movebackward(%val)
{
$mvBackwardAction = %val * $movementSpeed;
}
function moveup(%val)
{
$mvUpAction = %val * $movementSpeed;
}
function movedown(%val)
{
$mvDownAction = %val * $movementSpeed;
}
function turnLeft( %val )
{
$mvYawRightSpeed = %val ? $Pref::Input::KeyboardTurnSpeed : 0;
}
function turnRight( %val )
{
$mvYawLeftSpeed = %val ? $Pref::Input::KeyboardTurnSpeed : 0;
}
function panUp( %val )
{
$mvPitchDownSpeed = %val ? $Pref::Input::KeyboardTurnSpeed : 0;
}
function panDown( %val )
{
$mvPitchUpSpeed = %val ? $Pref::Input::KeyboardTurnSpeed : 0;
}
function getMouseAdjustAmount(%val)
{
// based on a default camera FOV of 90'
return(%val * ($cameraFov / 90) * 0.01) * $pref::Input::LinkMouseSensitivity;
}
function getGamepadAdjustAmount(%val)
{
// based on a default camera FOV of 90'
return(%val * ($cameraFov / 90) * 0.01) * 10.0;
}
function yaw(%val)
{
%yawAdj = getMouseAdjustAmount(%val);
if(ServerConnection.isControlObjectRotDampedCamera())
{
// Clamp and scale
%yawAdj = mClamp(%yawAdj, -m2Pi()+0.01, m2Pi()-0.01);
%yawAdj *= 0.5;
}
$mvYaw += %yawAdj;
}
function pitch(%val)
{
%pitchAdj = getMouseAdjustAmount(%val);
if(ServerConnection.isControlObjectRotDampedCamera())
{
// Clamp and scale
%pitchAdj = mClamp(%pitchAdj, -m2Pi()+0.01, m2Pi()-0.01);
%pitchAdj *= 0.5;
}
$mvPitch += %pitchAdj;
}
function jump(%val)
{
$mvTriggerCount2++;
}
function gamePadMoveX( %val )
{
if(%val > 0)
{
$mvRightAction = %val * $movementSpeed;
$mvLeftAction = 0;
}
else
{
$mvRightAction = 0;
$mvLeftAction = -%val * $movementSpeed;
}
}
function gamePadMoveY( %val )
{
if(%val > 0)
{
$mvForwardAction = %val * $movementSpeed;
$mvBackwardAction = 0;
}
else
{
$mvForwardAction = 0;
$mvBackwardAction = -%val * $movementSpeed;
}
}
function gamepadYaw(%val)
{
%yawAdj = getGamepadAdjustAmount(%val);
if(ServerConnection.isControlObjectRotDampedCamera())
{
// Clamp and scale
%yawAdj = mClamp(%yawAdj, -m2Pi()+0.01, m2Pi()-0.01);
%yawAdj *= 0.5;
}
if(%yawAdj > 0)
{
$mvYawLeftSpeed = %yawAdj;
$mvYawRightSpeed = 0;
}
else
{
$mvYawLeftSpeed = 0;
$mvYawRightSpeed = -%yawAdj;
}
}
function gamepadPitch(%val)
{
%pitchAdj = getGamepadAdjustAmount(%val);
if(ServerConnection.isControlObjectRotDampedCamera())
{
// Clamp and scale
%pitchAdj = mClamp(%pitchAdj, -m2Pi()+0.01, m2Pi()-0.01);
%pitchAdj *= 0.5;
}
if(%pitchAdj > 0)
{
$mvPitchDownSpeed = %pitchAdj;
$mvPitchUpSpeed = 0;
}
else
{
$mvPitchDownSpeed = 0;
$mvPitchUpSpeed = -%pitchAdj;
}
}
moveMap.bind( keyboard, a, moveleft );
moveMap.bind( keyboard, d, moveright );
moveMap.bind( keyboard, left, moveleft );
moveMap.bind( keyboard, right, moveright );
moveMap.bind( keyboard, w, moveforward );
moveMap.bind( keyboard, s, movebackward );
moveMap.bind( keyboard, up, moveforward );
moveMap.bind( keyboard, down, movebackward );
moveMap.bind( keyboard, e, moveup );
moveMap.bind( keyboard, c, movedown );
moveMap.bind( keyboard, space, jump );
moveMap.bind( mouse, xaxis, yaw );
moveMap.bind( mouse, yaxis, pitch );
moveMap.bind( gamepad, thumbrx, "D", "-0.23 0.23", gamepadYaw );
moveMap.bind( gamepad, thumbry, "D", "-0.23 0.23", gamepadPitch );
moveMap.bind( gamepad, thumblx, "D", "-0.23 0.23", gamePadMoveX );
moveMap.bind( gamepad, thumbly, "D", "-0.23 0.23", gamePadMoveY );
moveMap.bind( gamepad, btn_a, jump );
moveMap.bindCmd( gamepad, btn_back, "disconnect();", "" );
moveMap.bindCmd(gamepad, dpadl, "toggleLightColorViz();", "");
moveMap.bindCmd(gamepad, dpadu, "toggleDepthViz();", "");
moveMap.bindCmd(gamepad, dpadd, "toggleNormalsViz();", "");
moveMap.bindCmd(gamepad, dpadr, "toggleLightSpecularViz();", "");
// ----------------------------------------------------------------------------
// Stance/pose
// ----------------------------------------------------------------------------
function doCrouch(%val)
{
$mvTriggerCount3++;
}
moveMap.bind(keyboard, x, doCrouch);
moveMap.bind(gamepad, btn_b, doCrouch);
//------------------------------------------------------------------------------
// Mouse Trigger
//------------------------------------------------------------------------------
function mouseFire(%val)
{
$mvTriggerCount0++;
}
function altTrigger(%val)
{
$mvTriggerCount1++;
}
moveMap.bind( mouse, button0, mouseFire );
moveMap.bind( mouse, button1, altTrigger );
//------------------------------------------------------------------------------
// Gamepad Trigger
//------------------------------------------------------------------------------
function gamepadFire(%val)
{
if(%val > 0.1 && !$gamepadFireTriggered)
{
$gamepadFireTriggered = true;
$mvTriggerCount0++;
}
else if(%val <= 0.1 && $gamepadFireTriggered)
{
$gamepadFireTriggered = false;
$mvTriggerCount0++;
}
}
function gamepadAltTrigger(%val)
{
if(%val > 0.1 && !$gamepadAltTriggerTriggered)
{
$gamepadAltTriggerTriggered = true;
$mvTriggerCount1++;
}
else if(%val <= 0.1 && $gamepadAltTriggerTriggered)
{
$gamepadAltTriggerTriggered = false;
$mvTriggerCount1++;
}
}
moveMap.bind(gamepad, triggerr, gamepadFire);
moveMap.bind(gamepad, triggerl, gamepadAltTrigger);
//------------------------------------------------------------------------------
// Zoom and FOV functions
//------------------------------------------------------------------------------
if($Pref::player::CurrentFOV $= "")
$Pref::player::CurrentFOV = $pref::Player::DefaultFOV / 2;
// toggleZoomFOV() works by dividing the CurrentFOV by 2. Each time that this
// toggle is hit it simply divides the CurrentFOV by 2 once again. If the
// FOV is reduced below a certain threshold then it resets to equal half of the
// DefaultFOV value. This gives us 4 zoom levels to cycle through.
function toggleZoomFOV()
{
$Pref::Player::CurrentFOV = $Pref::Player::CurrentFOV / 2;
if($Pref::Player::CurrentFOV < 5)
$Pref::Player::CurrentFOV = $Pref::Player::DefaultFov / 2;
if(ServerConnection.zoomed)
setFOV($Pref::Player::CurrentFOV);
else
setFOV($Pref::Player::DefaultFOV);
}
function setZoomFOV(%val)
{
if(%val)
toggleZoomFOV();
}
function toggleZoom(%val)
{
if (%val)
{
ServerConnection.zoomed = true;
setFov($Pref::Player::CurrentFOV);
Reticle.setVisible(false);
zoomReticle.setVisible(true);
DOFPostEffect.setAutoFocus( true );
DOFPostEffect.setFocusParams( 0.5, 0.5, 50, 500, -5, 5 );
DOFPostEffect.enable();
}
else
{
ServerConnection.zoomed = false;
setFov($Pref::Player::defaultFOV);
Reticle.setVisible(true);
zoomReticle.setVisible(false);
DOFPostEffect.disable();
}
}
moveMap.bind(keyboard, f, setZoomFOV); // f for field of view
moveMap.bind(keyboard, z, toggleZoom); // z for zoom
//------------------------------------------------------------------------------
// Camera & View functions
//------------------------------------------------------------------------------
function toggleFreeLook( %val )
{
if ( %val )
$mvFreeLook = true;
else
$mvFreeLook = false;
}
function toggleFirstPerson(%val)
{
if (%val)
{
ServerConnection.setFirstPerson(!ServerConnection.isFirstPerson());
}
}
function toggleCamera(%val)
{
if (%val)
commandToServer('ToggleCamera');
}
moveMap.bind( keyboard, v, toggleFreeLook ); // v for vanity
moveMap.bind(keyboard, tab, toggleFirstPerson );
moveMap.bind(keyboard, "alt c", toggleCamera);
moveMap.bind( gamepad, btn_start, toggleCamera );
moveMap.bind( gamepad, btn_x, toggleFirstPerson );
// ----------------------------------------------------------------------------
// Misc. Player stuff
// ----------------------------------------------------------------------------
// Gideon does not have these animations, so the player does not need access to
// them. Commenting instead of removing so as to retain an example for those
// who will want to use a player model that has these animations and wishes to
// use them.
//moveMap.bindCmd(keyboard, "ctrl w", "commandToServer('playCel',\"wave\");", "");
//moveMap.bindCmd(keyboard, "ctrl s", "commandToServer('playCel',\"salute\");", "");
moveMap.bindCmd(keyboard, "ctrl k", "commandToServer('suicide');", "");
//------------------------------------------------------------------------------
// Item manipulation
//------------------------------------------------------------------------------
moveMap.bindCmd(keyboard, "1", "commandToServer('use',\"Rifle\");", "");
moveMap.bindCmd(keyboard, "2", "commandToServer('use',\"RocketLauncher\");", "");
function unmountWeapon(%val)
{
if (%val)
commandToServer('unmountWeapon');
}
moveMap.bind(keyboard, 0, unmountWeapon);
function throwWeapon(%val)
{
if (%val)
commandToServer('Throw', "Weapon");
}
function tossAmmo(%val)
{
if (%val)
commandToServer('Throw', "Ammo");
}
moveMap.bind(keyboard, "alt w", throwWeapon);
moveMap.bind(keyboard, "alt a", tossAmmo);
function nextWeapon(%val)
{
if (%val)
commandToServer('cycleWeapon', "next");
}
function prevWeapon(%val)
{
if (%val)
commandToServer('cycleWeapon', "prev");
}
function mouseWheelWeaponCycle(%val)
{
if (%val < 0)
commandToServer('cycleWeapon', "next");
else if (%val > 0)
commandToServer('cycleWeapon', "prev");
}
moveMap.bind(keyboard, q, nextWeapon);
moveMap.bind(keyboard, "ctrl q", prevWeapon);
moveMap.bind(mouse, "zaxis", mouseWheelWeaponCycle);
//------------------------------------------------------------------------------
// Message HUD functions
//------------------------------------------------------------------------------
function pageMessageHudUp( %val )
{
if ( %val )
pageUpMessageHud();
}
function pageMessageHudDown( %val )
{
if ( %val )
pageDownMessageHud();
}
function resizeMessageHud( %val )
{
if ( %val )
cycleMessageHudSize();
}
moveMap.bind(keyboard, u, toggleMessageHud );
//moveMap.bind(keyboard, y, teamMessageHud );
moveMap.bind(keyboard, "pageUp", pageMessageHudUp );
moveMap.bind(keyboard, "pageDown", pageMessageHudDown );
moveMap.bind(keyboard, "p", resizeMessageHud );
//------------------------------------------------------------------------------
// Demo recording functions
//------------------------------------------------------------------------------
function startRecordingDemo( %val )
{
if ( %val )
startDemoRecord();
}
function stopRecordingDemo( %val )
{
if ( %val )
stopDemoRecord();
}
moveMap.bind( keyboard, F3, startRecordingDemo );
moveMap.bind( keyboard, F4, stopRecordingDemo );
//------------------------------------------------------------------------------
// Helper Functions
//------------------------------------------------------------------------------
function dropCameraAtPlayer(%val)
{
if (%val)
commandToServer('dropCameraAtPlayer');
}
function dropPlayerAtCamera(%val)
{
if (%val)
commandToServer('DropPlayerAtCamera');
}
moveMap.bind(keyboard, "F8", dropCameraAtPlayer);
moveMap.bind(keyboard, "F7", dropPlayerAtCamera);
function bringUpOptions(%val)
{
if (%val)
Canvas.pushDialog(OptionsDlg);
}
GlobalActionMap.bind(keyboard, "ctrl o", bringUpOptions);
//------------------------------------------------------------------------------
// Debugging Functions
//------------------------------------------------------------------------------
$MFDebugRenderMode = 0;
function cycleDebugRenderMode(%val)
{
if (!%val)
return;
$MFDebugRenderMode++;
if ($MFDebugRenderMode > 16)
$MFDebugRenderMode = 0;
if ($MFDebugRenderMode == 15)
$MFDebugRenderMode = 16;
setInteriorRenderMode($MFDebugRenderMode);
if (isObject(ChatHud))
{
%message = "Setting Interior debug render mode to ";
%debugMode = "Unknown";
switch($MFDebugRenderMode)
{
case 0:
%debugMode = "NormalRender";
case 1:
%debugMode = "NormalRenderLines";
case 2:
%debugMode = "ShowDetail";
case 3:
%debugMode = "ShowAmbiguous";
case 4:
%debugMode = "ShowOrphan";
case 5:
%debugMode = "ShowLightmaps";
case 6:
%debugMode = "ShowTexturesOnly";
case 7:
%debugMode = "ShowPortalZones";
case 8:
%debugMode = "ShowOutsideVisible";
case 9:
%debugMode = "ShowCollisionFans";
case 10:
%debugMode = "ShowStrips";
case 11:
%debugMode = "ShowNullSurfaces";
case 12:
%debugMode = "ShowLargeTextures";
case 13:
%debugMode = "ShowHullSurfaces";
case 14:
%debugMode = "ShowVehicleHullSurfaces";
// Depreciated
//case 15:
// %debugMode = "ShowVertexColors";
case 16:
%debugMode = "ShowDetailLevel";
}
ChatHud.addLine(%message @ %debugMode);
}
}
GlobalActionMap.bind(keyboard, "F9", cycleDebugRenderMode);
//------------------------------------------------------------------------------
//
// Start profiler by pressing ctrl f3
// ctrl f3 - starts profile that will dump to console and file
//
function doProfile(%val)
{
if (%val)
{
// key down -- start profile
echo("Starting profile session...");
profilerReset();
profilerEnable(true);
}
else
{
// key up -- finish off profile
echo("Ending profile session...");
profilerDumpToFile("profilerDumpToFile" @ getSimTime() @ ".txt");
profilerEnable(false);
}
}
GlobalActionMap.bind(keyboard, "ctrl F3", doProfile);
//------------------------------------------------------------------------------
// Misc.
//------------------------------------------------------------------------------
GlobalActionMap.bind(keyboard, "tilde", toggleConsole);
GlobalActionMap.bindCmd(keyboard, "alt k", "cls();","");
GlobalActionMap.bindCmd(keyboard, "alt enter", "", "Canvas.attemptFullscreenToggle();");
GlobalActionMap.bindCmd(keyboard, "F1", "", "contextHelp();");
moveMap.bindCmd(keyboard, "n", "toggleNetGraph();", "");
// ----------------------------------------------------------------------------
// Useful vehicle stuff
// ----------------------------------------------------------------------------
// Trace a line along the direction the crosshair is pointing
// If you find a car with a player in it...eject them
function carjack()
{
%player = LocalClientConnection.getControlObject();
if (%player.getClassName() $= "Player")
{
%eyeVec = %player.getEyeVector();
%startPos = %player.getEyePoint();
%endPos = VectorAdd(%startPos, VectorScale(%eyeVec, 1000));
%target = ContainerRayCast(%startPos, %endPos, $TypeMasks::VehicleObjectType);
if (%target)
{
// See if anyone is mounted in the car's driver seat
%mount = %target.getMountNodeObject(0);
// Can only carjack bots
// remove '&& %mount.getClassName() $= "AIPlayer"' to allow you
// to carjack anyone/anything
if (%mount && %mount.getClassName() $= "AIPlayer")
{
commandToServer('carUnmountObj', %mount);
}
}
}
}
// Bind the keys to the carjack command
moveMap.bindCmd(keyboard, "ctrl z", "carjack();", "");
// Starting vehicle action map code
if ( isObject( vehicleMap ) )
vehicleMap.delete();
new ActionMap(vehicleMap);
// The key command for flipping the car
vehicleMap.bindCmd(keyboard, "ctrl x", "commandToServer(\'flipCar\');", "");
function getOut()
{
vehicleMap.pop();
moveMap.push();
commandToServer('dismountVehicle');
}
function brakeLights()
{
// Turn on/off the Cheetah's head lights.
commandToServer('toggleBrakeLights');
}
function brake(%val)
{
commandToServer('toggleBrakeLights');
$mvTriggerCount2++;
}
vehicleMap.bind( keyboard, w, moveforward );
vehicleMap.bind( keyboard, s, movebackward );
vehicleMap.bind( keyboard, up, moveforward );
vehicleMap.bind( keyboard, down, movebackward );
vehicleMap.bind( mouse, xaxis, yaw );
vehicleMap.bind( mouse, yaxis, pitch );
vehicleMap.bind( mouse, button0, mouseFire );
vehicleMap.bind( mouse, button1, altTrigger );
vehicleMap.bindCmd(keyboard, "ctrl f","getout();","");
vehicleMap.bind(keyboard, space, brake);
vehicleMap.bindCmd(keyboard, "l", "brakeLights();", "");
vehicleMap.bindCmd(keyboard, "escape", "", "handleEscape();");
vehicleMap.bind(keyboard, h, showControlsHelp);
vehicleMap.bind( keyboard, v, toggleFreeLook ); // v for vanity
//vehicleMap.bind(keyboard, tab, toggleFirstPerson );
vehicleMap.bind(keyboard, "alt c", toggleCamera);
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
namespace System.Xml.Tests
{
public class HasChildNodesTests
{
[Fact]
public static void ElementWithManyChildren()
{
var xml = "<root>\r\n text node one\r\n <elem1 child1=\"\" child2=\"duu\" child3=\"e1;e2;\" child4=\"a1\" child5=\"goody\">\r\n text node two e1; text node three\r\n </elem1><!-- comment3 --><?PI3 processing instruction?>e2;<foo /><![CDATA[ <opentag> without an </endtag> and & <! are all ok here ]]><elem2 att1=\"id1\" att2=\"up\" att3=\"attribute3\"><a /></elem2><elem2> \r\n elem2-text1\r\n <a> \r\n this-is-a \r\n </a> \r\n\r\n elem2-text2\r\n e3;e4;<!-- elem2-comment1-->\r\n elem2-text3\r\n\r\n <b> \r\n this-is-b\r\n </b>\r\n\r\n elem2-text4\r\n <?elem2_PI elem2-PI?>\r\n elem2-text5\r\n\r\n </elem2></root>";
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml(xml);
Assert.True(xmlDocument.HasChildNodes);
}
[Fact]
public static void DocumentWithOnlyDocumentElement()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<doc/>");
Assert.False(xmlDocument.DocumentElement.HasChildNodes);
Assert.True(xmlDocument.HasChildNodes);
}
[Fact]
public static void AddAnAttributeToAnElementWithNoChild()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<doc><elem1/></doc>");
var node = (XmlElement)xmlDocument.DocumentElement.FirstChild;
node.SetAttribute("att1", "foo");
Assert.False(node.HasChildNodes);
}
[Fact]
public static void AppendAnElementNOdeToAnElementNodeWithNoChild()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<doc><elem1 att1='foo'/></doc>");
var node = (XmlElement)xmlDocument.DocumentElement.FirstChild;
var newNode = xmlDocument.CreateElement("newElem");
Assert.False(node.HasChildNodes);
node.AppendChild(newNode);
Assert.True(node.HasChildNodes);
}
[Fact]
public static void AttributeWithEmptyString()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root attr='value'/>");
Assert.True(xmlDocument.DocumentElement.Attributes[0].HasChildNodes);
}
[Fact]
public static void AttributeWithStringValue()
{
var xmlDocument = new XmlDocument();
var node = xmlDocument.CreateAttribute("attribute");
node.Value = "attribute_value";
Assert.True(node.HasChildNodes);
}
[Fact]
public static void ElementWithAttributeAndNoChild()
{
var xmlDocument = new XmlDocument();
var node = xmlDocument.CreateElement("elem1");
var attribute = xmlDocument.CreateAttribute("attrib");
attribute.Value = "foo";
node.Attributes.Append(attribute);
Assert.False(node.HasChildNodes);
}
[Fact]
public static void CloneAnElementWithChildNode()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<elem1 att1='foo'>text<a /></elem1>");
var clonedTrue = xmlDocument.DocumentElement.CloneNode(true);
var clonedFalse = xmlDocument.DocumentElement.CloneNode(false);
Assert.True(clonedTrue.HasChildNodes);
Assert.False(clonedFalse.HasChildNodes);
}
[Fact]
public static void RemoveAllChildren()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root><child1/><child2/><child3/></root>");
Assert.Equal(3, xmlDocument.DocumentElement.ChildNodes.Count);
Assert.True(xmlDocument.DocumentElement.HasChildNodes);
for (int i = 0; i < 3; i++)
xmlDocument.DocumentElement.RemoveChild(xmlDocument.DocumentElement.ChildNodes[0]);
Assert.Equal(0, xmlDocument.DocumentElement.ChildNodes.Count);
Assert.False(xmlDocument.DocumentElement.HasChildNodes);
}
[Fact]
public static void RemoveAllChildrenAddAnElement()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root><child1/><child2/><child3/></root>");
Assert.Equal(3, xmlDocument.DocumentElement.ChildNodes.Count);
Assert.True(xmlDocument.DocumentElement.HasChildNodes);
for (int i = 0; i < 3; i++)
xmlDocument.DocumentElement.RemoveChild(xmlDocument.DocumentElement.ChildNodes[0]);
Assert.Equal(0, xmlDocument.DocumentElement.ChildNodes.Count);
Assert.False(xmlDocument.DocumentElement.HasChildNodes);
var elem = xmlDocument.CreateElement("elem");
xmlDocument.DocumentElement.AppendChild(elem);
Assert.Equal(1, xmlDocument.DocumentElement.ChildNodes.Count);
Assert.True(xmlDocument.DocumentElement.HasChildNodes);
}
[Fact]
public static void RemoveOnlyChildOfNode()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root><child1/></root>");
Assert.Equal(1, xmlDocument.DocumentElement.ChildNodes.Count);
Assert.True(xmlDocument.DocumentElement.HasChildNodes);
xmlDocument.DocumentElement.RemoveChild(xmlDocument.DocumentElement.ChildNodes[0]);
Assert.Equal(0, xmlDocument.DocumentElement.ChildNodes.Count);
Assert.False(xmlDocument.DocumentElement.HasChildNodes);
}
[Fact]
public static void InsertAChildToDocumentFragment()
{
var xmlDocument = new XmlDocument();
var fragment = xmlDocument.CreateDocumentFragment();
var elem = xmlDocument.CreateElement("elem");
fragment.AppendChild(elem);
Assert.True(fragment.HasChildNodes);
}
[Fact]
public static void CheckNoChildrenOnPI()
{
var xmlDocument = new XmlDocument();
Assert.False(xmlDocument.CreateProcessingInstruction("PI", "info").HasChildNodes);
}
[Fact]
public static void CheckNoChildrenOnComment()
{
var xmlDocument = new XmlDocument();
Assert.False(xmlDocument.CreateComment("info").HasChildNodes);
}
[Fact]
public static void CheckNoChildrenOnText()
{
var xmlDocument = new XmlDocument();
Assert.False(xmlDocument.CreateTextNode("info").HasChildNodes);
}
[Fact]
public static void CheckNoChildrenOnCData()
{
var xmlDocument = new XmlDocument();
Assert.False(xmlDocument.CreateCDataSection("info").HasChildNodes);
}
[Fact]
public static void ReplaceNodeWithChildrenWithEmptyNode()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root><child1/><child2/></root>");
var newNode = xmlDocument.CreateElement("newElement");
Assert.True(xmlDocument.DocumentElement.HasChildNodes);
xmlDocument.ReplaceChild(newNode, xmlDocument.DocumentElement);
Assert.False(xmlDocument.DocumentElement.HasChildNodes);
}
}
}
| |
// (c) Copyright Esri, 2010 - 2013
// This source is subject to the Apache 2.0 License.
// Please see http://www.apache.org/licenses/LICENSE-2.0.html for details.
// All other rights reserved.
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Resources;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geoprocessing;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Display;
namespace ESRI.ArcGIS.OSM.GeoProcessing
{
[Guid("dd42d75c-abd2-4925-9886-75db3ad55d78")]
[ClassInterface(ClassInterfaceType.None)]
[ProgId("OSMEditor.GPCopyLayerExtensions")]
[ComVisible(false)]
public class GPCopyLayerExtensions : ESRI.ArcGIS.Geoprocessing.IGPFunction2
{
string m_DisplayName = "Copy Layer Extensions";
int in_sourcelayerNumber, in_targetlayerNumber, out_layerNumber;
ResourceManager resourceManager = null;
OSMGPFactory osmGPFactory = null;
public GPCopyLayerExtensions()
{
try
{
resourceManager = new ResourceManager("ESRI.ArcGIS.OSM.GeoProcessing.OSMGPToolsStrings", this.GetType().Assembly);
m_DisplayName = String.Empty;
osmGPFactory = new OSMGPFactory();
}
catch { }
}
#region "IGPFunction2 Implementations"
public ESRI.ArcGIS.esriSystem.UID DialogCLSID
{
get
{
return default(ESRI.ArcGIS.esriSystem.UID);
}
}
public string DisplayName
{
get
{
if (String.IsNullOrEmpty(m_DisplayName))
{
m_DisplayName = osmGPFactory.GetFunctionName(OSMGPFactory.m_CopyLayerExtensionName).DisplayName;
}
return m_DisplayName;
}
}
public void Execute(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.esriSystem.ITrackCancel TrackCancel, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager envMgr, ESRI.ArcGIS.Geodatabase.IGPMessages message)
{
try
{
IGPUtilities3 gpUtilities3 = new GPUtilitiesClass();
if (TrackCancel == null)
{
TrackCancel = new CancelTrackerClass();
}
IGPParameter inputSourceLayerParameter = paramvalues.get_Element(in_sourcelayerNumber) as IGPParameter;
IGPValue inputSourceLayerGPValue = gpUtilities3.UnpackGPValue(inputSourceLayerParameter) as IGPValue;
IGPParameter inputTargetLayerParameter = paramvalues.get_Element(in_targetlayerNumber) as IGPParameter;
IGPValue inputTargetLayerGPValue = gpUtilities3.UnpackGPValue(inputTargetLayerParameter) as IGPValue;
ILayer sourceLayer = gpUtilities3.DecodeLayer(inputSourceLayerGPValue);
ILayer targetLayer = gpUtilities3.DecodeLayer(inputTargetLayerGPValue);
ILayerExtensions sourceLayerExtensions = sourceLayer as ILayerExtensions;
if (sourceLayerExtensions == null)
{
message.AddWarning(resourceManager.GetString("GPTools_GPCopyLayerExtension_source_noext_support"));
return;
}
ILayerExtensions targetLayerExtensions = targetLayer as ILayerExtensions;
if (targetLayerExtensions == null)
{
message.AddWarning(resourceManager.GetString("GPTools_GPCopyLayerExtension_target_noext_support"));
return;
}
// test if the feature classes already exists,
// if they do and the environments settings are such that an overwrite is not allowed we need to abort at this point
IGeoProcessorSettings gpSettings = (IGeoProcessorSettings)envMgr;
if (gpSettings.OverwriteOutput == true)
{
}
else
{
if (gpUtilities3.Exists(inputTargetLayerGPValue) == true)
{
message.AddError(120003, String.Format(resourceManager.GetString("GPTools_GPCopyLayerExtension_targetlayeralreadyexists"), inputTargetLayerGPValue.GetAsText()));
return;
}
}
for (int targetExtensionIndex = 0; targetExtensionIndex < targetLayerExtensions.ExtensionCount; targetExtensionIndex++)
{
targetLayerExtensions.RemoveExtension(targetExtensionIndex);
}
for (int sourceExtensionIndex = 0; sourceExtensionIndex < sourceLayerExtensions.ExtensionCount; sourceExtensionIndex++)
{
targetLayerExtensions.AddExtension(sourceLayerExtensions.get_Extension(sourceExtensionIndex));
}
}
catch (Exception ex)
{
message.AddError(120004, ex.Message);
}
}
public ESRI.ArcGIS.esriSystem.IName FullName
{
get
{
IName fullName = null;
if (osmGPFactory != null)
{
fullName = osmGPFactory.GetFunctionName(OSMGPFactory.m_CopyLayerExtensionName) as IName;
}
return fullName;
}
}
public object GetRenderer(ESRI.ArcGIS.Geoprocessing.IGPParameter pParam)
{
return default(object);
}
public int HelpContext
{
get
{
return default(int);
}
}
public string HelpFile
{
get
{
return default(string);
}
}
public bool IsLicensed()
{
return true;
}
public string MetadataFile
{
get
{
string metadafile = "gptransferlayerextension.xml";
try
{
string[] languageid = System.Threading.Thread.CurrentThread.CurrentUICulture.Name.Split("-".ToCharArray());
string ArcGISInstallationLocation = OSMGPFactory.GetArcGIS10InstallLocation();
string localizedMetaDataFileShort = ArcGISInstallationLocation + System.IO.Path.DirectorySeparatorChar.ToString() + "help" + System.IO.Path.DirectorySeparatorChar.ToString() + "gp" + System.IO.Path.DirectorySeparatorChar.ToString() + "gptransferlayerextension_" + languageid[0] + ".xml";
string localizedMetaDataFileLong = ArcGISInstallationLocation + System.IO.Path.DirectorySeparatorChar.ToString() + "help" + System.IO.Path.DirectorySeparatorChar.ToString() + "gp" + System.IO.Path.DirectorySeparatorChar.ToString() + "gptransferlayerextension_" + System.Threading.Thread.CurrentThread.CurrentUICulture.Name + ".xml";
if (System.IO.File.Exists(localizedMetaDataFileShort))
{
metadafile = localizedMetaDataFileShort;
}
else if (System.IO.File.Exists(localizedMetaDataFileLong))
{
metadafile = localizedMetaDataFileLong;
}
}
catch { }
return metadafile;
}
}
public string Name
{
get
{
return OSMGPFactory.m_CopyLayerExtensionName;
}
}
public ESRI.ArcGIS.esriSystem.IArray ParameterInfo
{
get
{
IArray parameters = new ArrayClass();
IGPParameterEdit3 inputSourceLayer = new GPParameterClass() as IGPParameterEdit3;
inputSourceLayer.Name = "in_sourcelayer";
inputSourceLayer.DisplayName = resourceManager.GetString("GPTools_GPCopyLayerExtension_inputsourcelayer_displayname");
inputSourceLayer.ParameterType = esriGPParameterType.esriGPParameterTypeRequired;
inputSourceLayer.Direction = esriGPParameterDirection.esriGPParameterDirectionInput;
inputSourceLayer.DataType = new GPLayerTypeClass();
in_sourcelayerNumber = 0;
parameters.Add((IGPParameter)inputSourceLayer);
IGPParameterEdit3 inputTargetLayer = new GPParameterClass() as IGPParameterEdit3;
inputTargetLayer.Name = "in_targetlayer";
inputTargetLayer.DisplayName = resourceManager.GetString("GPTools_GPCopyLayerExtension_inputtargetlayer_displayname");
inputTargetLayer.ParameterType = esriGPParameterType.esriGPParameterTypeRequired;
inputTargetLayer.Direction = esriGPParameterDirection.esriGPParameterDirectionInput;
inputTargetLayer.DataType = new GPLayerTypeClass();
in_targetlayerNumber = 1;
parameters.Add((IGPParameter)inputTargetLayer);
IGPParameterEdit3 outputLayer = new GPParameterClass() as IGPParameterEdit3;
outputLayer.Name = "out_layer";
outputLayer.DisplayName = resourceManager.GetString("GPTools_GPCopyLayerExtension_outputlayer_displayname");
outputLayer.ParameterType = esriGPParameterType.esriGPParameterTypeDerived;
outputLayer.Direction = esriGPParameterDirection.esriGPParameterDirectionOutput;
outputLayer.DataType = new GPLayerTypeClass();
outputLayer.AddDependency("in_targetlayer");
out_layerNumber = 2;
parameters.Add((IGPParameter)outputLayer);
return parameters;
}
}
public void UpdateMessages(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager pEnvMgr, ESRI.ArcGIS.Geodatabase.IGPMessages Messages)
{
}
public void UpdateParameters(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager pEnvMgr)
{
}
public ESRI.ArcGIS.Geodatabase.IGPMessages Validate(ESRI.ArcGIS.esriSystem.IArray paramvalues, bool updateValues, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager envMgr)
{
return default(ESRI.ArcGIS.Geodatabase.IGPMessages);
}
#endregion
}
}
| |
/*
Project Orleans Cloud Service SDK ver. 1.0
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the ""Software""), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Runtime.Remoting;
using System.Threading.Tasks;
using Orleans.Core;
using Orleans.Runtime;
using Orleans.Runtime.Configuration;
using Orleans.TestingHost.Extensions;
namespace Orleans.TestingHost
{
/// <summary>
/// A host class for local testing with Orleans using in-process silos.
///
/// Runs a Primary and Secondary silo in seperate app domains, and client in the main app domain.
/// Additional silos can also be started in-process if required for particular test cases.
/// </summary>
/// <remarks>
/// Make sure the following files are included in any test projects that use <c>TestingSiloHost</c>,
/// and ensure "Copy if Newer" is set to ensure the config files are included in the test set.
/// <code>
/// OrleansConfigurationForTesting.xml
/// ClientConfigurationForTesting.xml
/// </code>
/// Also make sure that your test project references your test grains and test grain interfaces
/// projects, and has CopyLocal=True set on those references [which should be the default].
/// </remarks>
public abstract class TestingSiloHost
{
protected static AppDomain SharedMemoryDomain;
protected static SiloHandle Primary = null;
protected static SiloHandle Secondary = null;
protected static readonly List<SiloHandle> additionalSilos = new List<SiloHandle>();
protected readonly TestingSiloOptions siloInitOptions;
protected readonly TestingClientOptions clientInitOptions;
private static TimeSpan _livenessStabilizationTime;
protected static readonly Random random = new Random();
public static string DeploymentId = null;
public static string DeploymentIdPrefix = null;
public const int BasePort = 22222;
public const int ProxyBasePort = 40000;
private static int InstanceCounter = 0;
public IGrainFactory GrainFactory { get; private set; }
public Logger logger
{
get { return GrainClient.Logger; }
}
/// <summary>
/// Start the default Primary and Secondary test silos, plus client in-process,
/// using the default silo config options.
/// </summary>
protected TestingSiloHost()
: this(new TestingSiloOptions(), new TestingClientOptions())
{
}
/// <summary>
/// Start the default Primary and Secondary test silos, plus client in-process,
/// ensuring that fresh silos are started if they were already running.
/// </summary>
protected TestingSiloHost(bool startFreshOrleans)
: this(new TestingSiloOptions { StartFreshOrleans = startFreshOrleans }, new TestingClientOptions())
{
}
/// <summary>
/// Start the default Primary and Secondary test silos, plus client in-process,
/// using the specified silo config options.
/// </summary>
protected TestingSiloHost(TestingSiloOptions siloOptions)
: this(siloOptions, new TestingClientOptions())
{
}
/// <summary>
/// Start the default Primary and Secondary test silos, plus client in-process,
/// using the specified silo and client config options.
/// </summary>
protected TestingSiloHost(TestingSiloOptions siloOptions, TestingClientOptions clientOptions)
{
siloInitOptions = siloOptions;
clientInitOptions = clientOptions;
AppDomain.CurrentDomain.UnhandledException += ReportUnobservedException;
try
{
InitializeAsync(siloOptions, clientOptions).Wait();
string startMsg = "----------------------------- STARTING NEW UNIT TEST SILO HOST: " + GetType().FullName + " -------------------------------------";
WriteLog(startMsg);
}
catch (TimeoutException te)
{
throw new TimeoutException("Timeout during test initialization", te);
}
catch (Exception ex)
{
Exception baseExc = ex.GetBaseException();
if (baseExc is TimeoutException)
{
throw new TimeoutException("Timeout during test initialization", ex);
}
// IMPORTANT:
// Do NOT re-throw the original exception here, also not as an internal exception inside AggregateException
// Due to the way MS tests works, if the original exception is an Orleans exception,
// it's assembly might not be loaded yet in this phase of the test.
// As a result, we will get "MSTest: Unit Test Adapter threw exception: Type is not resolved for member XXX"
// and will loose the oroginal exception. This makes debugging tests super hard!
// The root cause has to do with us initializing our tests from Test constructor and not from TestInitialize method.
// More details: http://dobrzanski.net/2010/09/20/mstest-unit-test-adapter-threw-exception-type-is-not-resolved-for-member/
throw new Exception(
string.Format("Exception during test initialization: {0}",
TraceLogger.PrintException(baseExc)));
}
}
/// <summary>
/// Get the list of current active silos.
/// </summary>
/// <returns>List of current silos.</returns>
public IEnumerable<SiloHandle> GetActiveSilos()
{
WriteLog("GetActiveSilos: Primary={0} Secondary={1} + {2} Additional={3}",
Primary, Secondary, additionalSilos.Count, additionalSilos);
if (null != Primary && Primary.Silo != null) yield return Primary;
if (null != Secondary && Secondary.Silo != null) yield return Secondary;
if (additionalSilos.Count > 0)
foreach (var s in additionalSilos)
if (null != s && s.Silo != null)
yield return s;
}
/// <summary>
/// Find the silo handle for the specified silo address.
/// </summary>
/// <param name="siloAddress">Silo address to be found.</param>
/// <returns>SiloHandle of the appropriate silo, or <c>null</c> if not found.</returns>
public SiloHandle GetSiloForAddress(SiloAddress siloAddress)
{
List<SiloHandle> activeSilos = GetActiveSilos().ToList();
var ret = activeSilos.Where(s => s.Silo.SiloAddress.Equals(siloAddress)).FirstOrDefault();
return ret;
}
/// <summary>
/// Wait for the silo liveness sub-system to detect and act on any recent cluster membership changes.
/// </summary>
/// <param name="didKill">Whether recent membership changes we done by graceful Stop.</param>
public async Task WaitForLivenessToStabilizeAsync(bool didKill = false)
{
TimeSpan stabilizationTime = _livenessStabilizationTime;
WriteLog(Environment.NewLine + Environment.NewLine + "WaitForLivenessToStabilize is about to sleep for {0}", stabilizationTime);
await Task.Delay(stabilizationTime);
WriteLog("WaitForLivenessToStabilize is done sleeping");
}
private static TimeSpan GetLivenessStabilizationTime(GlobalConfiguration global, bool didKill = false)
{
TimeSpan stabilizationTime = TimeSpan.Zero;
if (didKill)
{
// in case of hard kill (kill and not Stop), we should give silos time to detect failures first.
stabilizationTime = TestingUtils.Multiply(global.ProbeTimeout, global.NumMissedProbesLimit);
}
if (global.UseLivenessGossip)
{
stabilizationTime += TimeSpan.FromSeconds(5);
}
else
{
stabilizationTime += TestingUtils.Multiply(global.TableRefreshTimeout, 2);
}
return stabilizationTime;
}
/// <summary>
/// Start an additional silo, so that it joins the existing cluster with the default Primary and Secondary silos.
/// </summary>
/// <returns>SiloHandle for the newly started silo.</returns>
public SiloHandle StartAdditionalSilo()
{
SiloHandle instance = StartOrleansSilo(
Silo.SiloType.Secondary,
siloInitOptions,
InstanceCounter++);
additionalSilos.Add(instance);
return instance;
}
/// <summary>
/// Start a number of additional silo, so that they join the existing cluster with the default Primary and Secondary silos.
/// </summary>
/// <param name="numExtraSilos">Number of additional silos to start.</param>
/// <returns>List of SiloHandles for the newly started silos.</returns>
public List<SiloHandle> StartAdditionalSilos(int numExtraSilos)
{
List<SiloHandle> instances = new List<SiloHandle>();
for (int i = 0; i < numExtraSilos; i++)
{
SiloHandle instance = StartAdditionalSilo();
instances.Add(instance);
}
return instances;
}
/// <summary>
/// Stop any additional silos, not including the default Primary and Secondary silos.
/// </summary>
public static void StopAdditionalSilos()
{
foreach (SiloHandle instance in additionalSilos)
{
StopSilo(instance);
}
additionalSilos.Clear();
}
/// <summary>
/// Stop the default Primary and Secondary silos.
/// </summary>
public static void StopDefaultSilos()
{
try
{
GrainClient.Uninitialize();
}
catch (Exception exc) { WriteLog("Exception Uninitializing grain client: {0}", exc); }
StopSilo(Secondary);
StopSilo(Primary);
Secondary = null;
Primary = null;
InstanceCounter = 0;
DeploymentId = null;
}
/// <summary>
/// Stop all current silos.
/// </summary>
public static void StopAllSilos()
{
StopAdditionalSilos();
StopDefaultSilos();
}
/// <summary>
/// Restart the default Primary and Secondary silos.
/// </summary>
public void RestartDefaultSilos()
{
TestingSiloOptions primarySiloOptions = Primary.Options;
TestingSiloOptions secondarySiloOptions = Secondary.Options;
// Restart as the same deployment
string deploymentId = DeploymentId;
StopDefaultSilos();
DeploymentId = deploymentId;
primarySiloOptions.PickNewDeploymentId = false;
secondarySiloOptions.PickNewDeploymentId = false;
Primary = StartOrleansSilo(Silo.SiloType.Primary, primarySiloOptions, InstanceCounter++);
Secondary = StartOrleansSilo(Silo.SiloType.Secondary, secondarySiloOptions, InstanceCounter++);
WaitForLivenessToStabilizeAsync().Wait();
GrainClient.Initialize();
}
/// <summary>
/// Start a Secondary silo with a given instanceCounter
/// (allows to set the port number as before or new, depending on the scenario).
/// </summary>
public void StartSecondarySilo(TestingSiloOptions secondarySiloOptions, int instanceCounter)
{
secondarySiloOptions.PickNewDeploymentId = false;
Secondary = StartOrleansSilo(Silo.SiloType.Secondary, secondarySiloOptions, instanceCounter);
}
/// <summary>
/// Do a semi-graceful Stop of the specified silo.
/// </summary>
/// <param name="instance">Silo to be stopped.</param>
public static void StopSilo(SiloHandle instance)
{
if (instance != null)
{
StopOrleansSilo(instance, true);
}
}
/// <summary>
/// Do an immediate Kill of the specified silo.
/// </summary>
/// <param name="instance">Silo to be killed.</param>
public static void KillSilo(SiloHandle instance)
{
if (instance != null)
{
// do NOT stop, just kill directly, to simulate crash.
StopOrleansSilo(instance, false);
}
}
/// <summary>
/// Do a Stop or Kill of the specified silo, followed by a restart.
/// </summary>
/// <param name="instance">Silo to be restarted.</param>
public SiloHandle RestartSilo(SiloHandle instance)
{
if (instance != null)
{
var options = instance.Options;
var type = instance.Silo.Type;
StopOrleansSilo(instance, true);
instance = StartOrleansSilo(type, options, InstanceCounter++);
return instance;
}
return null;
}
#region Private methods
private async Task InitializeAsync(TestingSiloOptions options, TestingClientOptions clientOptions)
{
bool doStartPrimary = false;
bool doStartSecondary = false;
if (options.StartFreshOrleans)
{
// the previous test was !startFresh, so we need to cleanup after it.
if (Primary != null || Secondary != null || GrainClient.IsInitialized)
{
StopDefaultSilos();
}
StopAdditionalSilos();
if (options.StartPrimary)
{
doStartPrimary = true;
}
if (options.StartSecondary)
{
doStartSecondary = true;
}
}
else
{
if (options.StartPrimary && Primary == null)
{
// first time.
doStartPrimary = true;
}
if (options.StartSecondary && Secondary == null)
{
doStartSecondary = true;
}
}
if (options.PickNewDeploymentId && String.IsNullOrEmpty(DeploymentId))
{
DeploymentId = GetDeploymentId();
}
if (options.ParallelStart)
{
var handles = new List<Task<SiloHandle>>();
if (doStartPrimary)
{
int instanceCount = InstanceCounter++;
handles.Add(Task.Run(() => StartOrleansSilo(Silo.SiloType.Primary, options, instanceCount)));
}
if (doStartSecondary)
{
int instanceCount = InstanceCounter++;
handles.Add(Task.Run(() => StartOrleansSilo(Silo.SiloType.Secondary, options, instanceCount)));
}
await Task.WhenAll(handles.ToArray());
if (doStartPrimary)
{
Primary = await handles[0];
}
if (doStartSecondary)
{
Secondary = await handles[1];
}
}else
{
if (doStartPrimary)
{
Primary = StartOrleansSilo(Silo.SiloType.Primary, options, InstanceCounter++);
}
if (doStartSecondary)
{
Secondary = StartOrleansSilo(Silo.SiloType.Secondary, options, InstanceCounter++);
}
}
if (!GrainClient.IsInitialized && options.StartClient)
{
ClientConfiguration clientConfig;
if (clientOptions.ClientConfigFile != null)
{
clientConfig = ClientConfiguration.LoadFromFile(clientOptions.ClientConfigFile.FullName);
}
else
{
clientConfig = ClientConfiguration.StandardLoad();
}
if (clientOptions.ProxiedGateway && clientOptions.Gateways != null)
{
clientConfig.Gateways = clientOptions.Gateways;
if (clientOptions.PreferedGatewayIndex >= 0)
clientConfig.PreferedGatewayIndex = clientOptions.PreferedGatewayIndex;
}
if (clientOptions.PropagateActivityId)
{
clientConfig.PropagateActivityId = clientOptions.PropagateActivityId;
}
if (!String.IsNullOrEmpty(DeploymentId))
{
clientConfig.DeploymentId = DeploymentId;
}
if (Debugger.IsAttached)
{
// Test is running inside debugger - Make timeout ~= infinite
clientConfig.ResponseTimeout = TimeSpan.FromMilliseconds(1000000);
}
else if (clientOptions.ResponseTimeout > TimeSpan.Zero)
{
clientConfig.ResponseTimeout = clientOptions.ResponseTimeout;
}
if (options.LargeMessageWarningThreshold > 0)
{
clientConfig.LargeMessageWarningThreshold = options.LargeMessageWarningThreshold;
}
clientConfig.AdjustForTestEnvironment();
GrainClient.Initialize(clientConfig);
GrainFactory = GrainClient.GrainFactory;
}
}
private static SiloHandle StartOrleansSilo(Silo.SiloType type, TestingSiloOptions options, int instanceCount, AppDomain shared = null)
{
// Load initial config settings, then apply some overrides below.
ClusterConfiguration config = new ClusterConfiguration();
if (options.SiloConfigFile == null)
{
config.StandardLoad();
}
else
{
config.LoadFromFile(options.SiloConfigFile.FullName);
}
int basePort = options.BasePort < 0 ? BasePort : options.BasePort;
if (config.Globals.SeedNodes.Count > 0 && options.BasePort < 0)
{
config.PrimaryNode = config.Globals.SeedNodes[0];
}
else
{
config.PrimaryNode = new IPEndPoint(IPAddress.Loopback, basePort);
}
config.Globals.SeedNodes.Clear();
config.Globals.SeedNodes.Add(config.PrimaryNode);
if (!String.IsNullOrEmpty(DeploymentId))
{
config.Globals.DeploymentId = DeploymentId;
}
config.Defaults.PropagateActivityId = options.PropagateActivityId;
if (options.LargeMessageWarningThreshold > 0)
{
config.Defaults.LargeMessageWarningThreshold = options.LargeMessageWarningThreshold;
}
config.Globals.LivenessType = options.LivenessType;
config.Globals.ReminderServiceType = options.ReminderServiceType;
if (!String.IsNullOrEmpty(options.DataConnectionString))
{
config.Globals.DataConnectionString = options.DataConnectionString;
}
config.AdjustForTestEnvironment();
_livenessStabilizationTime = GetLivenessStabilizationTime(config.Globals);
string siloName;
switch (type)
{
case Silo.SiloType.Primary:
siloName = "Primary";
break;
default:
siloName = "Secondary_" + instanceCount.ToString(CultureInfo.InvariantCulture);
break;
}
NodeConfiguration nodeConfig = config.GetConfigurationForNode(siloName);
nodeConfig.HostNameOrIPAddress = "loopback";
nodeConfig.Port = basePort + instanceCount;
nodeConfig.DefaultTraceLevel = config.Defaults.DefaultTraceLevel;
nodeConfig.PropagateActivityId = config.Defaults.PropagateActivityId;
nodeConfig.BulkMessageLimit = config.Defaults.BulkMessageLimit;
if (nodeConfig.ProxyGatewayEndpoint != null && nodeConfig.ProxyGatewayEndpoint.Address != null)
{
nodeConfig.ProxyGatewayEndpoint = new IPEndPoint(nodeConfig.ProxyGatewayEndpoint.Address, ProxyBasePort + instanceCount);
}
config.Globals.ExpectedClusterSize = 2;
config.Overrides[siloName] = nodeConfig;
WriteLog("Starting a new silo in app domain {0} with config {1}", siloName, config.ToString(siloName));
AppDomain appDomain;
Silo silo = LoadSiloInNewAppDomain(siloName, type, config, out appDomain);
silo.Start();
SiloHandle retValue = new SiloHandle
{
Name = siloName,
Silo = silo,
Options = options,
Endpoint = silo.SiloAddress.Endpoint,
AppDomain = appDomain,
};
return retValue;
}
private static void StopOrleansSilo(SiloHandle instance, bool stopGracefully)
{
if (stopGracefully)
{
try { if (instance.Silo != null) instance.Silo.Shutdown(); }
catch (RemotingException re) { Console.WriteLine(re); /* Ignore error */ }
catch (Exception exc) { Console.WriteLine(exc); throw; }
}
try
{
UnloadSiloInAppDomain(instance.AppDomain);
}
catch (Exception exc) { Console.WriteLine(exc); throw; }
instance.AppDomain = null;
instance.Silo = null;
instance.Process = null;
}
private static Silo LoadSiloInNewAppDomain(string siloName, Silo.SiloType type, ClusterConfiguration config, out AppDomain appDomain)
{
AppDomainSetup setup = GetAppDomainSetupInfo();
appDomain = AppDomain.CreateDomain(siloName, null, setup);
var args = new object[] { siloName, type, config };
var silo = (Silo)appDomain.CreateInstanceFromAndUnwrap(
"OrleansRuntime.dll", typeof(Silo).FullName, false,
BindingFlags.Default, null, args, CultureInfo.CurrentCulture,
new object[] { });
appDomain.UnhandledException += ReportUnobservedException;
return silo;
}
private static void UnloadSiloInAppDomain(AppDomain appDomain)
{
if (appDomain != null)
{
appDomain.UnhandledException -= ReportUnobservedException;
AppDomain.Unload(appDomain);
}
}
private static AppDomainSetup GetAppDomainSetupInfo()
{
AppDomain currentAppDomain = AppDomain.CurrentDomain;
return new AppDomainSetup
{
ApplicationBase = Environment.CurrentDirectory,
ConfigurationFile = currentAppDomain.SetupInformation.ConfigurationFile,
ShadowCopyFiles = currentAppDomain.SetupInformation.ShadowCopyFiles,
ShadowCopyDirectories = currentAppDomain.SetupInformation.ShadowCopyDirectories,
CachePath = currentAppDomain.SetupInformation.CachePath
};
}
private string GetDeploymentId()
{
if (!String.IsNullOrEmpty(DeploymentId))
{
return DeploymentId;
}
string prefix = DeploymentIdPrefix ?? "testdepid-";
int randomSuffix = random.Next(1000);
DateTime now = DateTime.UtcNow;
string DateTimeFormat = "yyyy-MM-dd-hh-mm-ss-fff";
string depId = String.Format("{0}{1}-{2}",
prefix, now.ToString(DateTimeFormat, CultureInfo.InvariantCulture), randomSuffix);
return depId;
}
private static void ReportUnobservedException(object sender, UnhandledExceptionEventArgs eventArgs)
{
Exception exception = (Exception)eventArgs.ExceptionObject;
Console.WriteLine("Unobserved exception: {0}", exception);
}
public static void WriteLog(string format, params object[] args)
{
Console.WriteLine(format, args);
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Globalization
{
public partial class ChineseLunisolarCalendar : System.Globalization.EastAsianLunisolarCalendar
{
public ChineseLunisolarCalendar() { }
public override int[] Eras { get { return default(int[]); } }
public override System.DateTime MaxSupportedDateTime { get { return default(System.DateTime); } }
public override System.DateTime MinSupportedDateTime { get { return default(System.DateTime); } }
public override int GetEra(System.DateTime time) { return default(int); }
}
public abstract partial class EastAsianLunisolarCalendar : System.Globalization.Calendar
{
internal EastAsianLunisolarCalendar() { }
public override int TwoDigitYearMax { get { return default(int); } set { } }
public override System.DateTime AddMonths(System.DateTime time, int months) { return default(System.DateTime); }
public override System.DateTime AddYears(System.DateTime time, int years) { return default(System.DateTime); }
public int GetCelestialStem(int sexagenaryYear) { return default(int); }
public override int GetDayOfMonth(System.DateTime time) { return default(int); }
public override System.DayOfWeek GetDayOfWeek(System.DateTime time) { return default(System.DayOfWeek); }
public override int GetDayOfYear(System.DateTime time) { return default(int); }
public override int GetDaysInMonth(int year, int month, int era) { return default(int); }
public override int GetDaysInYear(int year, int era) { return default(int); }
public override int GetLeapMonth(int year, int era) { return default(int); }
public override int GetMonth(System.DateTime time) { return default(int); }
public override int GetMonthsInYear(int year, int era) { return default(int); }
public virtual int GetSexagenaryYear(System.DateTime time) { return default(int); }
public int GetTerrestrialBranch(int sexagenaryYear) { return default(int); }
public override int GetYear(System.DateTime time) { return default(int); }
public override bool IsLeapDay(int year, int month, int day, int era) { return default(bool); }
public override bool IsLeapMonth(int year, int month, int era) { return default(bool); }
public override bool IsLeapYear(int year, int era) { return default(bool); }
public override System.DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) { return default(System.DateTime); }
public override int ToFourDigitYear(int year) { return default(int); }
}
public partial class GregorianCalendar : System.Globalization.Calendar
{
public GregorianCalendar() { }
public GregorianCalendar(System.Globalization.GregorianCalendarTypes type) { }
public virtual System.Globalization.GregorianCalendarTypes CalendarType { get { return default(System.Globalization.GregorianCalendarTypes); } set { } }
public override int[] Eras { get { return default(int[]); } }
public override System.DateTime MaxSupportedDateTime { get { return default(System.DateTime); } }
public override System.DateTime MinSupportedDateTime { get { return default(System.DateTime); } }
public override int TwoDigitYearMax { get { return default(int); } set { } }
public override System.DateTime AddMonths(System.DateTime time, int months) { return default(System.DateTime); }
public override System.DateTime AddYears(System.DateTime time, int years) { return default(System.DateTime); }
public override int GetDayOfMonth(System.DateTime time) { return default(int); }
public override System.DayOfWeek GetDayOfWeek(System.DateTime time) { return default(System.DayOfWeek); }
public override int GetDayOfYear(System.DateTime time) { return default(int); }
public override int GetDaysInMonth(int year, int month, int era) { return default(int); }
public override int GetDaysInYear(int year, int era) { return default(int); }
public override int GetEra(System.DateTime time) { return default(int); }
public override int GetLeapMonth(int year, int era) { return default(int); }
public override int GetMonth(System.DateTime time) { return default(int); }
public override int GetMonthsInYear(int year, int era) { return default(int); }
public override int GetYear(System.DateTime time) { return default(int); }
public override bool IsLeapDay(int year, int month, int day, int era) { return default(bool); }
public override bool IsLeapMonth(int year, int month, int era) { return default(bool); }
public override bool IsLeapYear(int year, int era) { return default(bool); }
public override System.DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) { return default(System.DateTime); }
public override int ToFourDigitYear(int year) { return default(int); }
}
public enum GregorianCalendarTypes
{
Arabic = 10,
Localized = 1,
MiddleEastFrench = 9,
TransliteratedEnglish = 11,
TransliteratedFrench = 12,
USEnglish = 2,
}
public partial class HebrewCalendar : System.Globalization.Calendar
{
public HebrewCalendar() { }
public override int[] Eras { get { return default(int[]); } }
public override System.DateTime MaxSupportedDateTime { get { return default(System.DateTime); } }
public override System.DateTime MinSupportedDateTime { get { return default(System.DateTime); } }
public override int TwoDigitYearMax { get { return default(int); } set { } }
public override System.DateTime AddMonths(System.DateTime time, int months) { return default(System.DateTime); }
public override System.DateTime AddYears(System.DateTime time, int years) { return default(System.DateTime); }
public override int GetDayOfMonth(System.DateTime time) { return default(int); }
public override System.DayOfWeek GetDayOfWeek(System.DateTime time) { return default(System.DayOfWeek); }
public override int GetDayOfYear(System.DateTime time) { return default(int); }
public override int GetDaysInMonth(int year, int month, int era) { return default(int); }
public override int GetDaysInYear(int year, int era) { return default(int); }
public override int GetEra(System.DateTime time) { return default(int); }
public override int GetLeapMonth(int year, int era) { return default(int); }
public override int GetMonth(System.DateTime time) { return default(int); }
public override int GetMonthsInYear(int year, int era) { return default(int); }
public override int GetYear(System.DateTime time) { return default(int); }
public override bool IsLeapDay(int year, int month, int day, int era) { return default(bool); }
public override bool IsLeapMonth(int year, int month, int era) { return default(bool); }
public override bool IsLeapYear(int year, int era) { return default(bool); }
public override System.DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) { return default(System.DateTime); }
public override int ToFourDigitYear(int year) { return default(int); }
}
public partial class HijriCalendar : System.Globalization.Calendar
{
public HijriCalendar() { }
public override int[] Eras { get { return default(int[]); } }
public int HijriAdjustment { get { return default(int); } set { } }
public override System.DateTime MaxSupportedDateTime { get { return default(System.DateTime); } }
public override System.DateTime MinSupportedDateTime { get { return default(System.DateTime); } }
public override int TwoDigitYearMax { get { return default(int); } set { } }
public override System.DateTime AddMonths(System.DateTime time, int months) { return default(System.DateTime); }
public override System.DateTime AddYears(System.DateTime time, int years) { return default(System.DateTime); }
public override int GetDayOfMonth(System.DateTime time) { return default(int); }
public override System.DayOfWeek GetDayOfWeek(System.DateTime time) { return default(System.DayOfWeek); }
public override int GetDayOfYear(System.DateTime time) { return default(int); }
public override int GetDaysInMonth(int year, int month, int era) { return default(int); }
public override int GetDaysInYear(int year, int era) { return default(int); }
public override int GetEra(System.DateTime time) { return default(int); }
public override int GetLeapMonth(int year, int era) { return default(int); }
public override int GetMonth(System.DateTime time) { return default(int); }
public override int GetMonthsInYear(int year, int era) { return default(int); }
public override int GetYear(System.DateTime time) { return default(int); }
public override bool IsLeapDay(int year, int month, int day, int era) { return default(bool); }
public override bool IsLeapMonth(int year, int month, int era) { return default(bool); }
public override bool IsLeapYear(int year, int era) { return default(bool); }
public override System.DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) { return default(System.DateTime); }
public override int ToFourDigitYear(int year) { return default(int); }
}
public partial class JapaneseCalendar : System.Globalization.Calendar
{
public JapaneseCalendar() { }
public override int[] Eras { get { return default(int[]); } }
public override System.DateTime MaxSupportedDateTime { get { return default(System.DateTime); } }
public override System.DateTime MinSupportedDateTime { get { return default(System.DateTime); } }
public override int TwoDigitYearMax { get { return default(int); } set { } }
public override System.DateTime AddMonths(System.DateTime time, int months) { return default(System.DateTime); }
public override System.DateTime AddYears(System.DateTime time, int years) { return default(System.DateTime); }
public override int GetDayOfMonth(System.DateTime time) { return default(int); }
public override System.DayOfWeek GetDayOfWeek(System.DateTime time) { return default(System.DayOfWeek); }
public override int GetDayOfYear(System.DateTime time) { return default(int); }
public override int GetDaysInMonth(int year, int month, int era) { return default(int); }
public override int GetDaysInYear(int year, int era) { return default(int); }
public override int GetEra(System.DateTime time) { return default(int); }
public override int GetLeapMonth(int year, int era) { return default(int); }
public override int GetMonth(System.DateTime time) { return default(int); }
public override int GetMonthsInYear(int year, int era) { return default(int); }
public override int GetWeekOfYear(System.DateTime time, System.Globalization.CalendarWeekRule rule, System.DayOfWeek firstDayOfWeek) { return default(int); }
public override int GetYear(System.DateTime time) { return default(int); }
public override bool IsLeapDay(int year, int month, int day, int era) { return default(bool); }
public override bool IsLeapMonth(int year, int month, int era) { return default(bool); }
public override bool IsLeapYear(int year, int era) { return default(bool); }
public override System.DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) { return default(System.DateTime); }
public override int ToFourDigitYear(int year) { return default(int); }
}
public partial class JapaneseLunisolarCalendar : System.Globalization.EastAsianLunisolarCalendar
{
public JapaneseLunisolarCalendar() { }
public override int[] Eras { get { return default(int[]); } }
public override System.DateTime MaxSupportedDateTime { get { return default(System.DateTime); } }
public override System.DateTime MinSupportedDateTime { get { return default(System.DateTime); } }
public override int GetEra(System.DateTime time) { return default(int); }
}
public partial class JulianCalendar : System.Globalization.Calendar
{
public JulianCalendar() { }
public override int[] Eras { get { return default(int[]); } }
public override System.DateTime MaxSupportedDateTime { get { return default(System.DateTime); } }
public override System.DateTime MinSupportedDateTime { get { return default(System.DateTime); } }
public override int TwoDigitYearMax { get { return default(int); } set { } }
public override System.DateTime AddMonths(System.DateTime time, int months) { return default(System.DateTime); }
public override System.DateTime AddYears(System.DateTime time, int years) { return default(System.DateTime); }
public override int GetDayOfMonth(System.DateTime time) { return default(int); }
public override System.DayOfWeek GetDayOfWeek(System.DateTime time) { return default(System.DayOfWeek); }
public override int GetDayOfYear(System.DateTime time) { return default(int); }
public override int GetDaysInMonth(int year, int month, int era) { return default(int); }
public override int GetDaysInYear(int year, int era) { return default(int); }
public override int GetEra(System.DateTime time) { return default(int); }
public override int GetLeapMonth(int year, int era) { return default(int); }
public override int GetMonth(System.DateTime time) { return default(int); }
public override int GetMonthsInYear(int year, int era) { return default(int); }
public override int GetYear(System.DateTime time) { return default(int); }
public override bool IsLeapDay(int year, int month, int day, int era) { return default(bool); }
public override bool IsLeapMonth(int year, int month, int era) { return default(bool); }
public override bool IsLeapYear(int year, int era) { return default(bool); }
public override System.DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) { return default(System.DateTime); }
public override int ToFourDigitYear(int year) { return default(int); }
}
public partial class KoreanCalendar : System.Globalization.Calendar
{
public KoreanCalendar() { }
public override int[] Eras { get { return default(int[]); } }
public override System.DateTime MaxSupportedDateTime { get { return default(System.DateTime); } }
public override System.DateTime MinSupportedDateTime { get { return default(System.DateTime); } }
public override int TwoDigitYearMax { get { return default(int); } set { } }
public override System.DateTime AddMonths(System.DateTime time, int months) { return default(System.DateTime); }
public override System.DateTime AddYears(System.DateTime time, int years) { return default(System.DateTime); }
public override int GetDayOfMonth(System.DateTime time) { return default(int); }
public override System.DayOfWeek GetDayOfWeek(System.DateTime time) { return default(System.DayOfWeek); }
public override int GetDayOfYear(System.DateTime time) { return default(int); }
public override int GetDaysInMonth(int year, int month, int era) { return default(int); }
public override int GetDaysInYear(int year, int era) { return default(int); }
public override int GetEra(System.DateTime time) { return default(int); }
public override int GetLeapMonth(int year, int era) { return default(int); }
public override int GetMonth(System.DateTime time) { return default(int); }
public override int GetMonthsInYear(int year, int era) { return default(int); }
public override int GetWeekOfYear(System.DateTime time, System.Globalization.CalendarWeekRule rule, System.DayOfWeek firstDayOfWeek) { return default(int); }
public override int GetYear(System.DateTime time) { return default(int); }
public override bool IsLeapDay(int year, int month, int day, int era) { return default(bool); }
public override bool IsLeapMonth(int year, int month, int era) { return default(bool); }
public override bool IsLeapYear(int year, int era) { return default(bool); }
public override System.DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) { return default(System.DateTime); }
public override int ToFourDigitYear(int year) { return default(int); }
}
public partial class KoreanLunisolarCalendar : System.Globalization.EastAsianLunisolarCalendar
{
public KoreanLunisolarCalendar() { }
public override int[] Eras { get { return default(int[]); } }
public override System.DateTime MaxSupportedDateTime { get { return default(System.DateTime); } }
public override System.DateTime MinSupportedDateTime { get { return default(System.DateTime); } }
public override int GetEra(System.DateTime time) { return default(int); }
}
public partial class PersianCalendar : System.Globalization.Calendar
{
public PersianCalendar() { }
public override int[] Eras { get { return default(int[]); } }
public override System.DateTime MaxSupportedDateTime { get { return default(System.DateTime); } }
public override System.DateTime MinSupportedDateTime { get { return default(System.DateTime); } }
public override int TwoDigitYearMax { get { return default(int); } set { } }
public override System.DateTime AddMonths(System.DateTime time, int months) { return default(System.DateTime); }
public override System.DateTime AddYears(System.DateTime time, int years) { return default(System.DateTime); }
public override int GetDayOfMonth(System.DateTime time) { return default(int); }
public override System.DayOfWeek GetDayOfWeek(System.DateTime time) { return default(System.DayOfWeek); }
public override int GetDayOfYear(System.DateTime time) { return default(int); }
public override int GetDaysInMonth(int year, int month, int era) { return default(int); }
public override int GetDaysInYear(int year, int era) { return default(int); }
public override int GetEra(System.DateTime time) { return default(int); }
public override int GetLeapMonth(int year, int era) { return default(int); }
public override int GetMonth(System.DateTime time) { return default(int); }
public override int GetMonthsInYear(int year, int era) { return default(int); }
public override int GetYear(System.DateTime time) { return default(int); }
public override bool IsLeapDay(int year, int month, int day, int era) { return default(bool); }
public override bool IsLeapMonth(int year, int month, int era) { return default(bool); }
public override bool IsLeapYear(int year, int era) { return default(bool); }
public override System.DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) { return default(System.DateTime); }
public override int ToFourDigitYear(int year) { return default(int); }
}
public partial class TaiwanCalendar : System.Globalization.Calendar
{
public TaiwanCalendar() { }
public override int[] Eras { get { return default(int[]); } }
public override System.DateTime MaxSupportedDateTime { get { return default(System.DateTime); } }
public override System.DateTime MinSupportedDateTime { get { return default(System.DateTime); } }
public override int TwoDigitYearMax { get { return default(int); } set { } }
public override System.DateTime AddMonths(System.DateTime time, int months) { return default(System.DateTime); }
public override System.DateTime AddYears(System.DateTime time, int years) { return default(System.DateTime); }
public override int GetDayOfMonth(System.DateTime time) { return default(int); }
public override System.DayOfWeek GetDayOfWeek(System.DateTime time) { return default(System.DayOfWeek); }
public override int GetDayOfYear(System.DateTime time) { return default(int); }
public override int GetDaysInMonth(int year, int month, int era) { return default(int); }
public override int GetDaysInYear(int year, int era) { return default(int); }
public override int GetEra(System.DateTime time) { return default(int); }
public override int GetLeapMonth(int year, int era) { return default(int); }
public override int GetMonth(System.DateTime time) { return default(int); }
public override int GetMonthsInYear(int year, int era) { return default(int); }
public override int GetWeekOfYear(System.DateTime time, System.Globalization.CalendarWeekRule rule, System.DayOfWeek firstDayOfWeek) { return default(int); }
public override int GetYear(System.DateTime time) { return default(int); }
public override bool IsLeapDay(int year, int month, int day, int era) { return default(bool); }
public override bool IsLeapMonth(int year, int month, int era) { return default(bool); }
public override bool IsLeapYear(int year, int era) { return default(bool); }
public override System.DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) { return default(System.DateTime); }
public override int ToFourDigitYear(int year) { return default(int); }
}
public partial class TaiwanLunisolarCalendar : System.Globalization.EastAsianLunisolarCalendar
{
public TaiwanLunisolarCalendar() { }
public override int[] Eras { get { return default(int[]); } }
public override System.DateTime MaxSupportedDateTime { get { return default(System.DateTime); } }
public override System.DateTime MinSupportedDateTime { get { return default(System.DateTime); } }
public override int GetEra(System.DateTime time) { return default(int); }
}
public partial class ThaiBuddhistCalendar : System.Globalization.Calendar
{
public ThaiBuddhistCalendar() { }
public override int[] Eras { get { return default(int[]); } }
public override System.DateTime MaxSupportedDateTime { get { return default(System.DateTime); } }
public override System.DateTime MinSupportedDateTime { get { return default(System.DateTime); } }
public override int TwoDigitYearMax { get { return default(int); } set { } }
public override System.DateTime AddMonths(System.DateTime time, int months) { return default(System.DateTime); }
public override System.DateTime AddYears(System.DateTime time, int years) { return default(System.DateTime); }
public override int GetDayOfMonth(System.DateTime time) { return default(int); }
public override System.DayOfWeek GetDayOfWeek(System.DateTime time) { return default(System.DayOfWeek); }
public override int GetDayOfYear(System.DateTime time) { return default(int); }
public override int GetDaysInMonth(int year, int month, int era) { return default(int); }
public override int GetDaysInYear(int year, int era) { return default(int); }
public override int GetEra(System.DateTime time) { return default(int); }
public override int GetLeapMonth(int year, int era) { return default(int); }
public override int GetMonth(System.DateTime time) { return default(int); }
public override int GetMonthsInYear(int year, int era) { return default(int); }
public override int GetWeekOfYear(System.DateTime time, System.Globalization.CalendarWeekRule rule, System.DayOfWeek firstDayOfWeek) { return default(int); }
public override int GetYear(System.DateTime time) { return default(int); }
public override bool IsLeapDay(int year, int month, int day, int era) { return default(bool); }
public override bool IsLeapMonth(int year, int month, int era) { return default(bool); }
public override bool IsLeapYear(int year, int era) { return default(bool); }
public override System.DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) { return default(System.DateTime); }
public override int ToFourDigitYear(int year) { return default(int); }
}
public partial class UmAlQuraCalendar : System.Globalization.Calendar
{
public UmAlQuraCalendar() { }
public override int[] Eras { get { return default(int[]); } }
public override System.DateTime MaxSupportedDateTime { get { return default(System.DateTime); } }
public override System.DateTime MinSupportedDateTime { get { return default(System.DateTime); } }
public override int TwoDigitYearMax { get { return default(int); } set { } }
public override System.DateTime AddMonths(System.DateTime time, int months) { return default(System.DateTime); }
public override System.DateTime AddYears(System.DateTime time, int years) { return default(System.DateTime); }
public override int GetDayOfMonth(System.DateTime time) { return default(int); }
public override System.DayOfWeek GetDayOfWeek(System.DateTime time) { return default(System.DayOfWeek); }
public override int GetDayOfYear(System.DateTime time) { return default(int); }
public override int GetDaysInMonth(int year, int month, int era) { return default(int); }
public override int GetDaysInYear(int year, int era) { return default(int); }
public override int GetEra(System.DateTime time) { return default(int); }
public override int GetLeapMonth(int year, int era) { return default(int); }
public override int GetMonth(System.DateTime time) { return default(int); }
public override int GetMonthsInYear(int year, int era) { return default(int); }
public override int GetYear(System.DateTime time) { return default(int); }
public override bool IsLeapDay(int year, int month, int day, int era) { return default(bool); }
public override bool IsLeapMonth(int year, int month, int era) { return default(bool); }
public override bool IsLeapYear(int year, int era) { return default(bool); }
public override System.DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) { return default(System.DateTime); }
public override int ToFourDigitYear(int year) { return default(int); }
}
}
| |
// 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.Globalization;
using System.IO;
using System.Text.Unicode;
using Xunit;
namespace System.Text.Encodings.Web.Tests
{
public class UnicodeEncoderBaseTests
{
[Fact]
public void Ctor_WithCustomFilters()
{
// Arrange
var filter = new TextEncoderSettings();
filter.AllowCharacters('a', 'b');
filter.AllowCharacters('\0', '&', '\uFFFF', 'd');
UnicodeEncoderBase encoder = new CustomUnicodeEncoderBase(filter);
// Act & assert
Assert.Equal("a", encoder.Encode("a"));
Assert.Equal("b", encoder.Encode("b"));
Assert.Equal("[U+0063]", encoder.Encode("c"));
Assert.Equal("d", encoder.Encode("d"));
Assert.Equal("[U+0000]", encoder.Encode("\0")); // we still always encode control chars
Assert.Equal("[U+0026]", encoder.Encode("&")); // we still always encode HTML-special chars
Assert.Equal("[U+FFFF]", encoder.Encode("\uFFFF")); // we still always encode non-chars and other forbidden chars
}
[Fact]
public void Ctor_WithUnicodeRanges()
{
// Arrange
UnicodeEncoderBase encoder = new CustomUnicodeEncoderBase(new TextEncoderSettings(UnicodeRanges.Latin1Supplement, UnicodeRanges.MiscellaneousSymbols));
// Act & assert
Assert.Equal("[U+0061]", encoder.Encode("a"));
Assert.Equal("\u00E9", encoder.Encode("\u00E9" /* LATIN SMALL LETTER E WITH ACUTE */));
Assert.Equal("\u2601", encoder.Encode("\u2601" /* CLOUD */));
}
[Fact]
public void Encode_AllRangesAllowed_StillEncodesForbiddenChars_Simple()
{
// Arrange
UnicodeEncoderBase encoder = new CustomUnicodeEncoderBase(UnicodeRanges.All);
const string input = "Hello <>&\'\"+ there!";
const string expected = "Hello [U+003C][U+003E][U+0026][U+0027][U+0022][U+002B] there!";
// Act & assert
Assert.Equal(expected, encoder.Encode(input));
}
[Fact]
public void Encode_AllRangesAllowed_StillEncodesForbiddenChars_Extended()
{
// Arrange
UnicodeEncoderBase encoder = new CustomUnicodeEncoderBase(UnicodeRanges.All);
// Act & assert - BMP chars
for (int i = 0; i <= 0xFFFF; i++)
{
string input = new string((char)i, 1);
string expected;
if (IsSurrogateCodePoint(i))
{
expected = "\uFFFD"; // unpaired surrogate -> Unicode replacement char
}
else
{
bool mustEncode = false;
switch (i)
{
case '<':
case '>':
case '&':
case '\"':
case '\'':
case '+':
mustEncode = true;
break;
}
if (i <= 0x001F || (0x007F <= i && i <= 0x9F))
{
mustEncode = true; // control char
}
else if (!UnicodeHelpers.IsCharacterDefined((char)i))
{
mustEncode = true; // undefined (or otherwise disallowed) char
}
if (mustEncode)
{
expected = string.Format(CultureInfo.InvariantCulture, "[U+{0:X4}]", i);
}
else
{
expected = input; // no encoding
}
}
string retVal = encoder.Encode(input);
Assert.Equal(expected, retVal);
}
// Act & assert - astral chars
for (int i = 0x10000; i <= 0x10FFFF; i++)
{
string input = char.ConvertFromUtf32(i);
string expected = string.Format(CultureInfo.InvariantCulture, "[U+{0:X}]", i);
string retVal = encoder.Encode(input);
Assert.Equal(expected, retVal);
}
}
[Fact]
public void Encode_BadSurrogates_ReturnsUnicodeReplacementChar()
{
// Arrange
UnicodeEncoderBase encoder = new CustomUnicodeEncoderBase(UnicodeRanges.All); // allow all codepoints
// "a<unpaired leading>b<unpaired trailing>c<trailing before leading>d<unpaired trailing><valid>e<high at end of string>"
const string input = "a\uD800b\uDFFFc\uDFFF\uD800d\uDFFF\uD800\uDFFFe\uD800";
const string expected = "a\uFFFDb\uFFFDc\uFFFD\uFFFDd\uFFFD[U+103FF]e\uFFFD";
// Act
string retVal = encoder.Encode(input);
// Assert
Assert.Equal(expected, retVal);
}
[Fact]
public void Encode_EmptyStringInput_ReturnsEmptyString()
{
// Arrange
UnicodeEncoderBase encoder = new CustomUnicodeEncoderBase(UnicodeRanges.All);
// Act & assert
Assert.Equal("", encoder.Encode(""));
}
[Fact]
public void Encode_InputDoesNotRequireEncoding_ReturnsOriginalStringInstance()
{
// Arrange
UnicodeEncoderBase encoder = new CustomUnicodeEncoderBase(UnicodeRanges.All);
string input = "Hello, there!";
// Act & assert
Assert.Same(input, encoder.Encode(input));
}
[Fact]
public void Encode_NullInput_ReturnsNull()
{
// Arrange
UnicodeEncoderBase encoder = new CustomUnicodeEncoderBase(UnicodeRanges.All);
// Act & assert
Assert.Null(encoder.Encode(null));
}
[Fact]
public void Encode_WithCharsRequiringEncodingAtBeginning()
{
Assert.Equal("[U+0026]Hello, there!", new CustomUnicodeEncoderBase(UnicodeRanges.All).Encode("&Hello, there!"));
}
[Fact]
public void Encode_WithCharsRequiringEncodingAtEnd()
{
Assert.Equal("Hello, there![U+0026]", new CustomUnicodeEncoderBase(UnicodeRanges.All).Encode("Hello, there!&"));
}
[Fact]
public void Encode_WithCharsRequiringEncodingInMiddle()
{
Assert.Equal("Hello, [U+0026]there!", new CustomUnicodeEncoderBase(UnicodeRanges.All).Encode("Hello, &there!"));
}
[Fact]
public void Encode_WithCharsRequiringEncodingInterspersed()
{
Assert.Equal("Hello, [U+003C]there[U+003E]!", new CustomUnicodeEncoderBase(UnicodeRanges.All).Encode("Hello, <there>!"));
}
[Fact]
public void Encode_CharArray_ParameterChecking_NegativeTestCases()
{
// Arrange
CustomUnicodeEncoderBase encoder = new CustomUnicodeEncoderBase();
// Act & assert
Assert.Throws<ArgumentNullException>(() => encoder.Encode((char[])null, 0, 0, new StringWriter()));
Assert.Throws<ArgumentNullException>(() => encoder.Encode("abc".ToCharArray(), 0, 3, null));
Assert.Throws<ArgumentOutOfRangeException>(() => encoder.Encode("abc".ToCharArray(), -1, 2, new StringWriter()));
Assert.Throws<ArgumentOutOfRangeException>(() => encoder.Encode("abc".ToCharArray(), 2, 2, new StringWriter()));
Assert.Throws<ArgumentOutOfRangeException>(() => encoder.Encode("abc".ToCharArray(), 4, 0, new StringWriter()));
Assert.Throws<ArgumentOutOfRangeException>(() => encoder.Encode("abc".ToCharArray(), 2, -1, new StringWriter()));
Assert.Throws<ArgumentOutOfRangeException>(() => encoder.Encode("abc".ToCharArray(), 1, 3, new StringWriter()));
}
//[Fact]
//public void Encode_CharArray_ZeroCount_DoesNotCallIntoTextWriter()
//{
// // Arrange
// CustomUnicodeEncoderBase encoder = new CustomUnicodeEncoderBase();
// TextWriter output = new Mock<TextWriter>(MockBehavior.Strict).Object;
// // Act
// encoder.Encode("abc".ToCharArray(), 2, 0, output);
// // Assert
// // If we got this far (without TextWriter throwing), success!
//}
[Fact]
public void Encode_CharArray_AllCharsValid()
{
// Arrange
CustomUnicodeEncoderBase encoder = new CustomUnicodeEncoderBase(UnicodeRanges.All);
StringWriter output = new StringWriter();
// Act
encoder.Encode("abc&xyz".ToCharArray(), 4, 2, output);
// Assert
Assert.Equal("xy", output.ToString());
}
[Fact]
public void Encode_CharArray_AllCharsInvalid()
{
// Arrange
CustomUnicodeEncoderBase encoder = new CustomUnicodeEncoderBase();
StringWriter output = new StringWriter();
// Act
encoder.Encode("abc&xyz".ToCharArray(), 4, 2, output);
// Assert
Assert.Equal("[U+0078][U+0079]", output.ToString());
}
[Fact]
public void Encode_CharArray_SomeCharsValid()
{
// Arrange
CustomUnicodeEncoderBase encoder = new CustomUnicodeEncoderBase(UnicodeRanges.All);
StringWriter output = new StringWriter();
// Act
encoder.Encode("abc&xyz".ToCharArray(), 2, 3, output);
// Assert
Assert.Equal("c[U+0026]x", output.ToString());
}
[Fact]
public void Encode_StringSubstring_ParameterChecking_NegativeTestCases()
{
// Arrange
CustomUnicodeEncoderBase encoder = new CustomUnicodeEncoderBase();
// Act & assert
Assert.Throws<ArgumentNullException>(() => encoder.Encode((string)null, 0, 0, new StringWriter()));
Assert.Throws<ArgumentNullException>(() => encoder.Encode("abc", 0, 3, null));
Assert.Throws<ArgumentOutOfRangeException>(() => encoder.Encode("abc", -1, 2, new StringWriter()));
Assert.Throws<ArgumentOutOfRangeException>(() => encoder.Encode("abc", 2, 2, new StringWriter()));
Assert.Throws<ArgumentOutOfRangeException>(() => encoder.Encode("abc", 4, 0, new StringWriter()));
Assert.Throws<ArgumentOutOfRangeException>(() => encoder.Encode("abc", 2, -1, new StringWriter()));
Assert.Throws<ArgumentOutOfRangeException>(() => encoder.Encode("abc", 1, 3, new StringWriter()));
}
//[Fact]
//public void Encode_StringSubstring_ZeroCount_DoesNotCallIntoTextWriter()
//{
// // Arrange
// CustomUnicodeEncoderBase encoder = new CustomUnicodeEncoderBase();
// TextWriter output = new Mock<TextWriter>(MockBehavior.Strict).Object;
// // Act
// encoder.Encode("abc", 2, 0, output);
// // Assert
// // If we got this far (without TextWriter throwing), success!
//}
[Fact]
public void Encode_StringSubstring_AllCharsValid()
{
// Arrange
CustomUnicodeEncoderBase encoder = new CustomUnicodeEncoderBase(UnicodeRanges.All);
StringWriter output = new StringWriter();
// Act
encoder.Encode("abc&xyz", 4, 2, output);
// Assert
Assert.Equal("xy", output.ToString());
}
//[Fact]
//public void Encode_StringSubstring_EntireString_AllCharsValid_ForwardDirectlyToOutput()
//{
// // Arrange
// CustomUnicodeEncoderBase encoder = new CustomUnicodeEncoderBase(UnicodeRanges.All);
// var mockWriter = new Mock<TextWriter>(MockBehavior.Strict);
// mockWriter.Setup(o => o.Write("abc")).Verifiable();
// // Act
// encoder.Encode("abc", 0, 3, mockWriter.Object);
// // Assert
// mockWriter.Verify();
//}
[Fact]
public void Encode_StringSubstring_AllCharsInvalid()
{
// Arrange
CustomUnicodeEncoderBase encoder = new CustomUnicodeEncoderBase();
StringWriter output = new StringWriter();
// Act
encoder.Encode("abc&xyz", 4, 2, output);
// Assert
Assert.Equal("[U+0078][U+0079]", output.ToString());
}
[Fact]
public void Encode_StringSubstring_SomeCharsValid()
{
// Arrange
CustomUnicodeEncoderBase encoder = new CustomUnicodeEncoderBase(UnicodeRanges.All);
StringWriter output = new StringWriter();
// Act
encoder.Encode("abc&xyz", 2, 3, output);
// Assert
Assert.Equal("c[U+0026]x", output.ToString());
}
[Fact]
public void Encode_StringSubstring_EntireString_SomeCharsValid()
{
// Arrange
CustomUnicodeEncoderBase encoder = new CustomUnicodeEncoderBase(UnicodeRanges.All);
StringWriter output = new StringWriter();
// Act
const string input = "abc&xyz";
encoder.Encode(input, 0, input.Length, output);
// Assert
Assert.Equal("abc[U+0026]xyz", output.ToString());
}
private static bool IsSurrogateCodePoint(int codePoint)
{
return (0xD800 <= codePoint && codePoint <= 0xDFFF);
}
private sealed class CustomTextEncoderSettings : TextEncoderSettings
{
private readonly int[] _allowedCodePoints;
public CustomTextEncoderSettings(params int[] allowedCodePoints)
{
_allowedCodePoints = allowedCodePoints;
}
public override IEnumerable<int> GetAllowedCodePoints()
{
return _allowedCodePoints;
}
}
private sealed class CustomUnicodeEncoderBase : UnicodeEncoderBase
{
// We pass a (known bad) value of 1 for 'max output chars per input char',
// which also tests that the code behaves properly even if the original
// estimate is incorrect.
public CustomUnicodeEncoderBase(TextEncoderSettings filter)
: base(filter, maxOutputCharsPerInputChar: 1)
{
}
public CustomUnicodeEncoderBase(params UnicodeRange[] allowedRanges)
: this(new TextEncoderSettings(allowedRanges))
{
}
protected override void WriteEncodedScalar(ref Writer writer, uint value)
{
writer.Write(string.Format(CultureInfo.InvariantCulture, "[U+{0:X4}]", value));
}
}
}
}
| |
using System;
using System.Windows.Forms;
using System.ComponentModel;
using System.Xml.Serialization;
using System.Runtime.InteropServices;
namespace Lauo
{
public class Hotkey : IMessageFilter, IDisposable
{
#region Interop
[DllImport("user32.dll", SetLastError = true)]
private static extern int RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, Keys vk);
[DllImport("user32.dll", SetLastError=true)]
private static extern int UnregisterHotKey(IntPtr hWnd, int id);
private const uint WM_HOTKEY = 0x312;
private const uint MOD_ALT = 0x1;
private const uint MOD_CONTROL = 0x2;
private const uint MOD_SHIFT = 0x4;
private const uint MOD_WIN = 0x8;
private const uint ERROR_HOTKEY_ALREADY_REGISTERED = 1409;
#endregion
private static int currentID;
private const int maximumID = 0xBFFF;
private Keys keyCode;
private bool shift;
private bool control;
private bool alt;
private bool windows;
[XmlIgnore]
private int id;
[XmlIgnore]
private bool registered;
[XmlIgnore]
private Control windowControl;
public event HandledEventHandler Pressed;
public Hotkey() : this(Keys.None, false, false, false, false)
{
// No work done here!
}
public Hotkey(Keys keyCode, bool shift, bool control, bool alt, bool windows)
{
// Assign properties
this.KeyCode = keyCode;
this.Shift = shift;
this.Control = control;
this.Alt = alt;
this.Windows = windows;
// Register us as a message filter
Application.AddMessageFilter(this);
}
~Hotkey() {
Dispose();
}
public void Dispose() {// Unregister the hotkey if necessary
if (this.Registered) { this.Unregister(); }
}
public Hotkey Clone()
{
// Clone the whole object
return new Hotkey(this.keyCode, this.shift, this.control, this.alt, this.windows);
}
public bool GetCanRegister(Control windowControl)
{
// Handle any exceptions: they mean "no, you can't register" :)
try
{
// Attempt to register
if (!this.Register(windowControl))
{ return false; }
// Unregister and say we managed it
this.Unregister();
return true;
}
catch (Win32Exception)
{ return false; }
catch (NotSupportedException)
{ return false; }
}
public bool Register(Control windowControl)
{
// Check that we have not registered
if (this.registered)
{ throw new NotSupportedException("You cannot register a hotkey that is already registered"); }
// We can't register an empty hotkey
if (this.Empty)
{ throw new NotSupportedException("You cannot register an empty hotkey"); }
// Get an ID for the hotkey and increase current ID
this.id = Hotkey.currentID;
Hotkey.currentID = Hotkey.currentID + 1 % Hotkey.maximumID;
// Translate modifier keys into unmanaged version
uint modifiers = (this.Alt ? Hotkey.MOD_ALT : 0) | (this.Control ? Hotkey.MOD_CONTROL : 0) |
(this.Shift ? Hotkey.MOD_SHIFT : 0) | (this.Windows ? Hotkey.MOD_WIN : 0);
// Register the hotkey
if (Hotkey.RegisterHotKey(windowControl.Handle, this.id, modifiers, keyCode) == 0)
{
// Is the error that the hotkey is registered?
if (Marshal.GetLastWin32Error() == ERROR_HOTKEY_ALREADY_REGISTERED)
{ return false; }
else
{ throw new Win32Exception(); }
}
// Save the control reference and register state
this.registered = true;
this.windowControl = windowControl;
// We successfully registered
return true;
}
public void Unregister()
{
// Check that we have registered
if (!this.registered)
{ throw new NotSupportedException("You cannot unregister a hotkey that is not registered"); }
// It's possible that the control itself has died: in that case, no need to unregister!
if (!this.windowControl.IsDisposed)
{
// Clean up after ourselves
if (Hotkey.UnregisterHotKey(this.windowControl.Handle, this.id) == 0)
{ throw new Win32Exception(); }
}
// Clear the control reference and register state
this.registered = false;
this.windowControl = null;
}
private void Reregister()
{
// Only do something if the key is already registered
if (!this.registered)
{ return; }
// Save control reference
Control windowControl = this.windowControl;
// Unregister and then reregister again
this.Unregister();
this.Register(windowControl);
}
public bool PreFilterMessage(ref Message message)
{
// Only process WM_HOTKEY messages
if (message.Msg != Hotkey.WM_HOTKEY)
{ return false; }
// Check that the ID is our key and we are registerd
if (this.registered && (message.WParam.ToInt32() == this.id))
{
// Fire the event and pass on the event if our handlers didn't handle it
return this.OnPressed();
}
else
{ return false; }
}
private bool OnPressed()
{
// Fire the event if we can
HandledEventArgs handledEventArgs = new HandledEventArgs(false);
if (this.Pressed != null)
{ this.Pressed(this, handledEventArgs); }
// Return whether we handled the event or not
return handledEventArgs.Handled;
}
public override string ToString()
{
// We can be empty
if (this.Empty)
{ return "(none)"; }
// Build key name
string keyName = Enum.GetName(typeof(Keys), this.keyCode);;
switch (this.keyCode)
{
case Keys.D0:
case Keys.D1:
case Keys.D2:
case Keys.D3:
case Keys.D4:
case Keys.D5:
case Keys.D6:
case Keys.D7:
case Keys.D8:
case Keys.D9:
// Strip the first character
keyName = keyName.Substring(1);
break;
default:
// Leave everything alone
break;
}
// Build modifiers
string modifiers = "";
if (this.shift)
{ modifiers += "Shift+"; }
if (this.control)
{ modifiers += "Control+"; }
if (this.alt)
{ modifiers += "Alt+"; }
if (this.windows)
{ modifiers += "Windows+"; }
// Return result
return modifiers + keyName;
}
public bool Empty
{
get { return this.keyCode == Keys.None; }
}
public bool Registered
{
get { return this.registered; }
}
public Keys KeyCode
{
get { return this.keyCode; }
set
{
// Save and reregister
this.keyCode = value;
this.Reregister();
}
}
public bool Shift
{
get { return this.shift; }
set
{
// Save and reregister
this.shift = value;
this.Reregister();
}
}
public bool Control
{
get { return this.control; }
set
{
// Save and reregister
this.control = value;
this.Reregister();
}
}
public bool Alt
{
get { return this.alt; }
set
{
// Save and reregister
this.alt = value;
this.Reregister();
}
}
public bool Windows
{
get { return this.windows; }
set
{
// Save and reregister
this.windows = value;
this.Reregister();
}
}
}
}
| |
using System;
using UnityEditor.Callbacks;
using UnityEditor.TestTools.TestRunner.Api;
using UnityEditor.TestTools.TestRunner.GUI;
using UnityEngine;
namespace UnityEditor.TestTools.TestRunner
{
[Serializable]
internal class TestRunnerWindow : EditorWindow, IHasCustomMenu
{
internal static class Styles
{
public static GUIStyle info;
public static GUIStyle testList;
static Styles()
{
info = new GUIStyle(EditorStyles.wordWrappedLabel);
info.wordWrap = false;
info.stretchHeight = true;
info.margin.right = 15;
testList = new GUIStyle("CN Box");
testList.margin.top = 0;
testList.padding.left = 3;
}
}
private readonly GUIContent m_GUIHorizontalSplit = EditorGUIUtility.TrTextContent("Horizontal layout");
private readonly GUIContent m_GUIVerticalSplit = EditorGUIUtility.TrTextContent("Vertical layout");
private readonly GUIContent m_GUIEnableaPlaymodeTestsRunner = EditorGUIUtility.TrTextContent("Enable playmode tests for all assemblies");
private readonly GUIContent m_GUIDisablePlaymodeTestsRunner = EditorGUIUtility.TrTextContent("Disable playmode tests for all assemblies");
private readonly GUIContent m_GUIRunPlayModeTestAsEditModeTests = EditorGUIUtility.TrTextContent("Run playmode tests as editmode tests");
internal static TestRunnerWindow s_Instance;
private bool m_IsBuilding;
[NonSerialized]
private bool m_Enabled;
public TestFilterSettings filterSettings;
private readonly SplitterState m_Spl = new SplitterState(new float[] { 75, 25 }, new[] { 32, 32 }, null);
private TestRunnerWindowSettings m_Settings;
private enum TestRunnerMenuLabels
{
PlayMode = 0,
EditMode = 1
}
[SerializeField]
private int m_TestTypeToolbarIndex = (int)TestRunnerMenuLabels.EditMode;
[SerializeField]
private PlayModeTestListGUI m_PlayModeTestListGUI;
[SerializeField]
private EditModeTestListGUI m_EditModeTestListGUI;
internal TestListGUI m_SelectedTestTypes;
private ITestRunnerApi m_testRunnerApi;
private WindowResultUpdater m_WindowResultUpdater;
[MenuItem("Window/General/Test Runner", false, 201, false)]
public static void ShowPlaymodeTestsRunnerWindowCodeBased()
{
if (s_Instance != null)
{
try
{
s_Instance.Close();
}
catch (Exception exception)
{
Debug.LogException(exception);
}
}
s_Instance = GetWindow<TestRunnerWindow>("Test Runner");
s_Instance.Show();
}
static TestRunnerWindow()
{
InitBackgroundRunners();
}
private static void InitBackgroundRunners()
{
EditorApplication.playModeStateChanged -= OnPlayModeStateChanged;
EditorApplication.playModeStateChanged += OnPlayModeStateChanged;
}
[DidReloadScripts]
private static void CompilationCallback()
{
UpdateWindow();
}
private static void OnPlayModeStateChanged(PlayModeStateChange state)
{
if (s_Instance && state == PlayModeStateChange.EnteredEditMode && s_Instance.m_SelectedTestTypes.HasTreeData())
{
//repaint message details after exit playmode
s_Instance.m_SelectedTestTypes.TestSelectionCallback(s_Instance.m_SelectedTestTypes.m_TestListState.selectedIDs.ToArray());
s_Instance.Repaint();
}
}
public void OnDestroy()
{
EditorApplication.playModeStateChanged -= OnPlayModeStateChanged;
if (m_testRunnerApi != null)
{
m_testRunnerApi.UnregisterCallbacks(m_WindowResultUpdater);
}
}
private void OnEnable()
{
s_Instance = this;
SelectTestListGUI(m_TestTypeToolbarIndex);
m_testRunnerApi = ScriptableObject.CreateInstance<TestRunnerApi>();
m_WindowResultUpdater = new WindowResultUpdater();
m_testRunnerApi.RegisterCallbacks(m_WindowResultUpdater);
}
private void Enable()
{
m_Settings = new TestRunnerWindowSettings("UnityEditor.PlaymodeTestsRunnerWindow");
filterSettings = new TestFilterSettings("UnityTest.IntegrationTestsRunnerWindow");
if (m_SelectedTestTypes == null)
{
SelectTestListGUI(m_TestTypeToolbarIndex);
}
StartRetrieveTestList();
m_SelectedTestTypes.Reload();
m_Enabled = true;
}
private void SelectTestListGUI(int testTypeToolbarIndex)
{
if (testTypeToolbarIndex == (int)TestRunnerMenuLabels.PlayMode)
{
if (m_PlayModeTestListGUI == null)
{
m_PlayModeTestListGUI = new PlayModeTestListGUI();
}
m_SelectedTestTypes = m_PlayModeTestListGUI;
}
else if (testTypeToolbarIndex == (int)TestRunnerMenuLabels.EditMode)
{
if (m_EditModeTestListGUI == null)
{
m_EditModeTestListGUI = new EditModeTestListGUI();
}
m_SelectedTestTypes = m_EditModeTestListGUI;
}
}
private void StartRetrieveTestList()
{
if (!m_SelectedTestTypes.HasTreeData())
{
m_testRunnerApi.RetrieveTestList(new ExecutionSettings() { filter = new Filter() { testMode = m_SelectedTestTypes.TestMode } }, (rootTest) =>
{
m_SelectedTestTypes.Init(this, rootTest);
m_SelectedTestTypes.Reload();
});
}
}
public void OnGUI()
{
if (!m_Enabled)
{
Enable();
}
if (BuildPipeline.isBuildingPlayer)
{
m_IsBuilding = true;
}
else if (m_IsBuilding)
{
m_IsBuilding = false;
Repaint();
}
EditorGUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
var selectedIndex = m_TestTypeToolbarIndex;
m_TestTypeToolbarIndex = GUILayout.Toolbar(m_TestTypeToolbarIndex, Enum.GetNames(typeof(TestRunnerMenuLabels)), "LargeButton", UnityEngine.GUI.ToolbarButtonSize.FitToContents);
GUILayout.FlexibleSpace();
EditorGUILayout.EndHorizontal();
if (selectedIndex != m_TestTypeToolbarIndex)
{
SelectTestListGUI(m_TestTypeToolbarIndex);
StartRetrieveTestList();
}
EditorGUILayout.BeginVertical();
using (new EditorGUI.DisabledScope(EditorApplication.isPlayingOrWillChangePlaymode))
{
m_SelectedTestTypes.PrintHeadPanel();
}
EditorGUILayout.EndVertical();
if (m_Settings.verticalSplit)
SplitterGUILayout.BeginVerticalSplit(m_Spl);
else
SplitterGUILayout.BeginHorizontalSplit(m_Spl);
EditorGUILayout.BeginVertical();
EditorGUILayout.BeginVertical(Styles.testList);
m_SelectedTestTypes.RenderTestList();
EditorGUILayout.EndVertical();
EditorGUILayout.EndVertical();
m_SelectedTestTypes.RenderDetails();
if (m_Settings.verticalSplit)
SplitterGUILayout.EndVerticalSplit();
else
SplitterGUILayout.EndHorizontalSplit();
}
public void AddItemsToMenu(GenericMenu menu)
{
menu.AddItem(m_GUIVerticalSplit, m_Settings.verticalSplit, m_Settings.ToggleVerticalSplit);
menu.AddItem(m_GUIHorizontalSplit, !m_Settings.verticalSplit, m_Settings.ToggleVerticalSplit);
menu.AddSeparator(null);
var playModeTestRunnerEnabled = PlayerSettings.playModeTestRunnerEnabled;
var currentActive = playModeTestRunnerEnabled ? m_GUIDisablePlaymodeTestsRunner : m_GUIEnableaPlaymodeTestsRunner;
if (EditorPrefs.GetBool("InternalMode", false))
{
menu.AddItem(m_GUIRunPlayModeTestAsEditModeTests, PlayerSettings.runPlayModeTestAsEditModeTest, () =>
{
PlayerSettings.runPlayModeTestAsEditModeTest = !PlayerSettings.runPlayModeTestAsEditModeTest;
});
}
menu.AddItem(currentActive, false, () =>
{
PlayerSettings.playModeTestRunnerEnabled = !playModeTestRunnerEnabled;
EditorUtility.DisplayDialog(currentActive.text, "You need to restart the editor now", "Ok");
});
}
public void RebuildUIFilter()
{
if (m_SelectedTestTypes != null && m_SelectedTestTypes.HasTreeData())
{
m_SelectedTestTypes.RebuildUIFilter();
}
}
public static void UpdateWindow()
{
if (s_Instance != null && s_Instance.m_SelectedTestTypes != null)
{
s_Instance.m_SelectedTestTypes.Repaint();
s_Instance.Repaint();
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void OrInt32()
{
var test = new SimpleBinaryOpTest__OrInt32();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (Avx.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (Avx.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Avx.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Avx.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Avx.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__OrInt32
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Int32[] inArray1, Int32[] inArray2, Int32[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int32>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int32>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int32>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int32, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int32, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector256<Int32> _fld1;
public Vector256<Int32> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__OrInt32 testClass)
{
var result = Avx2.Or(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__OrInt32 testClass)
{
fixed (Vector256<Int32>* pFld1 = &_fld1)
fixed (Vector256<Int32>* pFld2 = &_fld2)
{
var result = Avx2.Or(
Avx.LoadVector256((Int32*)(pFld1)),
Avx.LoadVector256((Int32*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32);
private static Int32[] _data1 = new Int32[Op1ElementCount];
private static Int32[] _data2 = new Int32[Op2ElementCount];
private static Vector256<Int32> _clsVar1;
private static Vector256<Int32> _clsVar2;
private Vector256<Int32> _fld1;
private Vector256<Int32> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__OrInt32()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>());
}
public SimpleBinaryOpTest__OrInt32()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
_dataTable = new DataTable(_data1, _data2, new Int32[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx2.Or(
Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx2.Or(
Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx2.Or(
Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx2).GetMethod(nameof(Avx2.Or), new Type[] { typeof(Vector256<Int32>), typeof(Vector256<Int32>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx2).GetMethod(nameof(Avx2.Or), new Type[] { typeof(Vector256<Int32>), typeof(Vector256<Int32>) })
.Invoke(null, new object[] {
Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx2).GetMethod(nameof(Avx2.Or), new Type[] { typeof(Vector256<Int32>), typeof(Vector256<Int32>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx2.Or(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector256<Int32>* pClsVar1 = &_clsVar1)
fixed (Vector256<Int32>* pClsVar2 = &_clsVar2)
{
var result = Avx2.Or(
Avx.LoadVector256((Int32*)(pClsVar1)),
Avx.LoadVector256((Int32*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr);
var result = Avx2.Or(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr));
var result = Avx2.Or(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr));
var result = Avx2.Or(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__OrInt32();
var result = Avx2.Or(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleBinaryOpTest__OrInt32();
fixed (Vector256<Int32>* pFld1 = &test._fld1)
fixed (Vector256<Int32>* pFld2 = &test._fld2)
{
var result = Avx2.Or(
Avx.LoadVector256((Int32*)(pFld1)),
Avx.LoadVector256((Int32*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx2.Or(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector256<Int32>* pFld1 = &_fld1)
fixed (Vector256<Int32>* pFld2 = &_fld2)
{
var result = Avx2.Or(
Avx.LoadVector256((Int32*)(pFld1)),
Avx.LoadVector256((Int32*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx2.Or(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Avx2.Or(
Avx.LoadVector256((Int32*)(&test._fld1)),
Avx.LoadVector256((Int32*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector256<Int32> op1, Vector256<Int32> op2, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int32>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Int32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Int32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int32>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Int32[] left, Int32[] right, Int32[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if ((int)(left[0] | right[0]) != result[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((int)(left[i] | right[i]) != result[i])
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.Or)}<Int32>(Vector256<Int32>, Vector256<Int32>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using Newtonsoft.Json;
using QuantConnect.Data;
using QuantConnect.Interfaces;
using QuantConnect.Securities;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Regression test to demonstrate setting custom Symbol Properties and Market Hours for a custom data import
/// </summary>
/// <meta name="tag" content="using data" />
/// <meta name="tag" content="custom data" />
/// <meta name="tag" content="crypto" />
/// <meta name="tag" content="regression test" />
public class CustomDataPropertiesRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private string _ticker = "BTC";
private Security _bitcoin;
/// <summary>
/// Initialize the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
/// </summary>
public override void Initialize()
{
SetStartDate(2011, 9, 13);
SetEndDate(2015, 12, 01);
//Set the cash for the strategy:
SetCash(100000);
// Define our custom data properties and exchange hours
var properties = new SymbolProperties("Bitcoin", "USD", 1, 0.01m, 0.01m, _ticker);
var exchangeHours = SecurityExchangeHours.AlwaysOpen(TimeZones.NewYork);
// Add the custom data to our algorithm with our custom properties and exchange hours
_bitcoin = AddData<Bitcoin>(_ticker, properties, exchangeHours);
//Verify our symbol properties were changed and loaded into this security
if (_bitcoin.SymbolProperties != properties)
{
throw new Exception("Failed to set and retrieve custom SymbolProperties for BTC");
}
//Verify our exchange hours were changed and loaded into this security
if (_bitcoin.Exchange.Hours != exchangeHours)
{
throw new Exception("Failed to set and retrieve custom ExchangeHours for BTC");
}
// For regression purposes on AddData overloads, this call is simply to ensure Lean can accept this
// with default params and is not routed to a breaking function.
AddData<Bitcoin>("BTCUSD");
}
/// <summary>
/// Event Handler for Bitcoin Data Events: These Bitcoin objects are created from our
/// "Bitcoin" type below and fired into this event handler.
/// </summary>
/// <param name="data">One(1) Bitcoin Object, streamed into our algorithm synchronized in time with our other data streams</param>
public void OnData(Bitcoin data)
{
//If we don't have any bitcoin "SHARES" -- invest"
if (!Portfolio.Invested)
{
//Bitcoin used as a tradable asset, like stocks, futures etc.
if (data.Close != 0)
{
//Access custom data symbols using <ticker>.<custom-type>
Order("BTC.Bitcoin", Portfolio.MarginRemaining / Math.Abs(data.Close + 1));
}
}
}
public override void OnEndOfAlgorithm()
{
// Reset our Symbol property value, for testing purposes.
SymbolPropertiesDatabase.SetEntry(Market.USA, MarketHoursDatabase.GetDatabaseSymbolKey(_bitcoin.Symbol), SecurityType.Base,
SymbolProperties.GetDefault("USD"));
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "157.498%"},
{"Drawdown", "84.800%"},
{"Expectancy", "0"},
{"Net Profit", "5319.081%"},
{"Sharpe Ratio", "2.086"},
{"Probabilistic Sharpe Ratio", "69.456%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "1.736"},
{"Beta", "0.142"},
{"Annual Standard Deviation", "0.84"},
{"Annual Variance", "0.706"},
{"Information Ratio", "1.925"},
{"Tracking Error", "0.846"},
{"Treynor Ratio", "12.334"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", "BTC.Bitcoin 2S"},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "2.269"},
{"Return Over Maximum Drawdown", "1.858"},
{"Portfolio Turnover", "0"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
{"Long Insight Count", "0"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$0"},
{"Total Accumulated Estimated Alpha Value", "$0"},
{"Mean Population Estimated Insight Value", "$0"},
{"Mean Population Direction", "0%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "0d80bb47bd16b5bc6989a4c1c7aa8349"}
};
/// <summary>
/// Custom Data Type: Bitcoin data from Quandl - http://www.quandl.com/help/api-for-bitcoin-data
/// </summary>
public class Bitcoin : BaseData
{
[JsonProperty("timestamp")]
public int Timestamp = 0;
[JsonProperty("open")]
public decimal Open = 0;
[JsonProperty("high")]
public decimal High = 0;
[JsonProperty("low")]
public decimal Low = 0;
[JsonProperty("last")]
public decimal Close = 0;
[JsonProperty("bid")]
public decimal Bid = 0;
[JsonProperty("ask")]
public decimal Ask = 0;
[JsonProperty("vwap")]
public decimal WeightedPrice = 0;
[JsonProperty("volume")]
public decimal VolumeBTC = 0;
public decimal VolumeUSD = 0;
/// <summary>
/// 1. DEFAULT CONSTRUCTOR: Custom data types need a default constructor.
/// We search for a default constructor so please provide one here. It won't be used for data, just to generate the "Factory".
/// </summary>
public Bitcoin()
{
Symbol = "BTC";
}
/// <summary>
/// 2. RETURN THE STRING URL SOURCE LOCATION FOR YOUR DATA:
/// This is a powerful and dynamic select source file method. If you have a large dataset, 10+mb we recommend you break it into smaller files. E.g. One zip per year.
/// We can accept raw text or ZIP files. We read the file extension to determine if it is a zip file.
/// </summary>
/// <param name="config">Configuration object</param>
/// <param name="date">Date of this source file</param>
/// <param name="isLiveMode">true if we're in live mode, false for backtesting mode</param>
/// <returns>String URL of source file.</returns>
public override SubscriptionDataSource GetSource(SubscriptionDataConfig config, DateTime date, bool isLiveMode)
{
if (isLiveMode)
{
return new SubscriptionDataSource("https://www.bitstamp.net/api/ticker/", SubscriptionTransportMedium.Rest);
}
//return "http://my-ftp-server.com/futures-data-" + date.ToString("Ymd") + ".zip";
// OR simply return a fixed small data file. Large files will slow down your backtest
return new SubscriptionDataSource("https://www.quantconnect.com/api/v2/proxy/quandl/api/v3/datasets/BCHARTS/BITSTAMPUSD.csv?order=asc&api_key=WyAazVXnq7ATy_fefTqm", SubscriptionTransportMedium.RemoteFile);
}
/// <summary>
/// 3. READER METHOD: Read 1 line from data source and convert it into Object.
/// Each line of the CSV File is presented in here. The backend downloads your file, loads it into memory and then line by line
/// feeds it into your algorithm
/// </summary>
/// <param name="line">string line from the data source file submitted above</param>
/// <param name="config">Subscription data, symbol name, data type</param>
/// <param name="date">Current date we're requesting. This allows you to break up the data source into daily files.</param>
/// <param name="isLiveMode">true if we're in live mode, false for backtesting mode</param>
/// <returns>New Bitcoin Object which extends BaseData.</returns>
public override BaseData Reader(SubscriptionDataConfig config, string line, DateTime date, bool isLiveMode)
{
var coin = new Bitcoin();
if (isLiveMode)
{
//Example Line Format:
//{"high": "441.00", "last": "421.86", "timestamp": "1411606877", "bid": "421.96", "vwap": "428.58", "volume": "14120.40683975", "low": "418.83", "ask": "421.99"}
try
{
coin = JsonConvert.DeserializeObject<Bitcoin>(line);
coin.EndTime = DateTime.UtcNow.ConvertFromUtc(config.ExchangeTimeZone);
coin.Value = coin.Close;
}
catch { /* Do nothing, possible error in json decoding */ }
return coin;
}
//Example Line Format:
//Date Open High Low Close Volume (BTC) Volume (Currency) Weighted Price
//2011-09-13 5.8 6.0 5.65 5.97 58.37138238, 346.0973893944 5.929230648356
try
{
string[] data = line.Split(',');
coin.Time = DateTime.Parse(data[0], CultureInfo.InvariantCulture);
coin.EndTime = coin.Time.AddDays(1);
coin.Open = Convert.ToDecimal(data[1], CultureInfo.InvariantCulture);
coin.High = Convert.ToDecimal(data[2], CultureInfo.InvariantCulture);
coin.Low = Convert.ToDecimal(data[3], CultureInfo.InvariantCulture);
coin.Close = Convert.ToDecimal(data[4], CultureInfo.InvariantCulture);
coin.VolumeBTC = Convert.ToDecimal(data[5], CultureInfo.InvariantCulture);
coin.VolumeUSD = Convert.ToDecimal(data[6], CultureInfo.InvariantCulture);
coin.WeightedPrice = Convert.ToDecimal(data[7], CultureInfo.InvariantCulture);
coin.Value = coin.Close;
}
catch { /* Do nothing, skip first title row */ }
return coin;
}
}
}
}
| |
/*
* Exchange Web Services Managed API
*
* Copyright (c) Microsoft Corporation
* All rights reserved.
*
* MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this
* software and associated documentation files (the "Software"), to deal in the Software
* without restriction, including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
* FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
namespace Microsoft.Exchange.WebServices.Data
{
using System;
/// <summary>
/// Represents the Id of a folder.
/// </summary>
public sealed class FolderId : ServiceId
{
private WellKnownFolderName? folderName;
private Mailbox mailbox;
/// <summary>
/// Initializes a new instance of the <see cref="FolderId"/> class.
/// </summary>
internal FolderId()
: base()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="FolderId"/> class. Use this constructor
/// to link this FolderId to an existing folder that you have the unique Id of.
/// </summary>
/// <param name="uniqueId">The unique Id used to initialize the FolderId.</param>
public FolderId(string uniqueId)
: base(uniqueId)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="FolderId"/> class. Use this constructor
/// to link this FolderId to a well known folder (e.g. Inbox, Calendar or Contacts).
/// </summary>
/// <param name="folderName">The folder name used to initialize the FolderId.</param>
public FolderId(WellKnownFolderName folderName)
: base()
{
this.folderName = folderName;
}
/// <summary>
/// Initializes a new instance of the <see cref="FolderId"/> class. Use this constructor
/// to link this FolderId to a well known folder (e.g. Inbox, Calendar or Contacts) in a
/// specific mailbox.
/// </summary>
/// <param name="folderName">The folder name used to initialize the FolderId.</param>
/// <param name="mailbox">The mailbox used to initialize the FolderId.</param>
public FolderId(WellKnownFolderName folderName, Mailbox mailbox)
: this(folderName)
{
this.mailbox = mailbox;
}
/// <summary>
/// Gets the name of the XML element.
/// </summary>
/// <returns>XML element name.</returns>
internal override string GetXmlElementName()
{
return this.FolderName.HasValue ? XmlElementNames.DistinguishedFolderId : XmlElementNames.FolderId;
}
/// <summary>
/// Writes attributes to XML.
/// </summary>
/// <param name="writer">The writer.</param>
internal override void WriteAttributesToXml(EwsServiceXmlWriter writer)
{
if (this.FolderName.HasValue)
{
writer.WriteAttributeValue(XmlAttributeNames.Id, this.FolderName.Value.ToString().ToLowerInvariant());
if (this.Mailbox != null)
{
this.Mailbox.WriteToXml(writer, XmlElementNames.Mailbox);
}
}
else
{
base.WriteAttributesToXml(writer);
}
}
/// <summary>
/// Validates FolderId against a specified request version.
/// </summary>
/// <param name="version">The version.</param>
internal void Validate(ExchangeVersion version)
{
// The FolderName property is a WellKnownFolderName, an enumeration type. If the property
// is set, make sure that the value is valid for the request version.
if (this.FolderName.HasValue)
{
EwsUtilities.ValidateEnumVersionValue(this.FolderName.Value, version);
}
}
/// <summary>
/// Gets the name of the folder associated with the folder Id. Name and Id are mutually exclusive; if one is set, the other is null.
/// </summary>
public WellKnownFolderName? FolderName
{
get { return this.folderName; }
}
/// <summary>
/// Gets the mailbox of the folder. Mailbox is only set when FolderName is set.
/// </summary>
public Mailbox Mailbox
{
get { return this.mailbox; }
}
/// <summary>
/// Defines an implicit conversion between string and FolderId.
/// </summary>
/// <param name="uniqueId">The unique Id to convert to FolderId.</param>
/// <returns>A FolderId initialized with the specified unique Id.</returns>
public static implicit operator FolderId(string uniqueId)
{
return new FolderId(uniqueId);
}
/// <summary>
/// Defines an implicit conversion between WellKnownFolderName and FolderId.
/// </summary>
/// <param name="folderName">The folder name to convert to FolderId.</param>
/// <returns>A FolderId initialized with the specified folder name.</returns>
public static implicit operator FolderId(WellKnownFolderName folderName)
{
return new FolderId(folderName);
}
/// <summary>
/// True if this instance is valid, false otherthise.
/// </summary>
/// <value><c>true</c> if this instance is valid; otherwise, <c>false</c>.</value>
internal override bool IsValid
{
get
{
if (this.FolderName.HasValue)
{
return (this.Mailbox == null) || this.Mailbox.IsValid;
}
else
{
return base.IsValid;
}
}
}
/// <summary>
/// Determines whether the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>.
/// </summary>
/// <param name="obj">The <see cref="T:System.Object"/> to compare with the current <see cref="T:System.Object"/>.</param>
/// <returns>
/// true if the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>; otherwise, false.
/// </returns>
/// <exception cref="T:System.NullReferenceException">The <paramref name="obj"/> parameter is null.</exception>
public override bool Equals(object obj)
{
if (object.ReferenceEquals(this, obj))
{
return true;
}
else
{
FolderId other = obj as FolderId;
if (other == null)
{
return false;
}
else if (this.FolderName.HasValue)
{
if (other.FolderName.HasValue && this.FolderName.Value.Equals(other.FolderName.Value))
{
if (this.Mailbox != null)
{
return this.Mailbox.Equals(other.Mailbox);
}
else if (other.Mailbox == null)
{
return true;
}
}
}
else if (base.Equals(other))
{
return true;
}
return false;
}
}
/// <summary>
/// Serves as a hash function for a particular type.
/// </summary>
/// <returns>
/// A hash code for the current <see cref="T:System.Object"/>.
/// </returns>
public override int GetHashCode()
{
int hashCode;
if (this.FolderName.HasValue)
{
hashCode = this.FolderName.Value.GetHashCode();
if ((this.Mailbox != null) && this.Mailbox.IsValid)
{
hashCode = hashCode ^ this.Mailbox.GetHashCode();
}
}
else
{
hashCode = base.GetHashCode();
}
return hashCode;
}
/// <summary>
/// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
/// </summary>
/// <returns>
/// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
/// </returns>
public override string ToString()
{
if (this.IsValid)
{
if (this.FolderName.HasValue)
{
if ((this.Mailbox != null) && mailbox.IsValid)
{
return string.Format("{0} ({1})", this.folderName.Value, this.Mailbox.ToString());
}
else
{
return this.FolderName.Value.ToString();
}
}
else
{
return base.ToString();
}
}
else
{
return string.Empty;
}
}
}
}
| |
using System.Collections.Generic;
using System.Diagnostics;
using EcsRx.Components;
using EcsRx.Components.Database;
using EcsRx.Components.Lookups;
using EcsRx.Entities;
using EcsRx.Plugins.Batching.Batches;
namespace EcsRx.Plugins.Batching.Builders
{
public class ReferenceBatchBuilder<T1, T2> : IReferenceBatchBuilder<T1, T2>
where T1 : class, IComponent
where T2 : class, IComponent
{
public IComponentDatabase ComponentDatabase { get; }
private readonly int _componentTypeId1, _componentTypeId2;
public ReferenceBatchBuilder(IComponentDatabase componentDatabase, IComponentTypeLookup componentTypeLookup)
{
ComponentDatabase = componentDatabase;
_componentTypeId1 = componentTypeLookup.GetComponentType(typeof(T1));
_componentTypeId2 = componentTypeLookup.GetComponentType(typeof(T2));
}
public ReferenceBatch<T1, T2>[] Build(IReadOnlyList<IEntity> entities)
{
var componentArray1 = ComponentDatabase.GetComponents<T1>(_componentTypeId1);
var componentArray2 = ComponentDatabase.GetComponents<T2>(_componentTypeId2);
var batches = new ReferenceBatch<T1, T2>[entities.Count];
for (var i = 0; i < entities.Count; i++)
{
if (entities.Count != batches.Length)
{ return new ReferenceBatch<T1, T2>[0]; }
var entity = entities[i];
var component1Allocation = entity.ComponentAllocations[_componentTypeId1];
var component2Allocation = entity.ComponentAllocations[_componentTypeId2];
batches[i] = new ReferenceBatch<T1, T2>(entity.Id, componentArray1[component1Allocation], componentArray2[component2Allocation]);
}
return batches;
}
}
public class ReferenceBatchBuilder<T1, T2, T3> : IReferenceBatchBuilder<T1, T2, T3>
where T1 : class, IComponent
where T2 : class, IComponent
where T3 : class, IComponent
{
public IComponentDatabase ComponentDatabase { get; }
private readonly int _componentTypeId1, _componentTypeId2, _componentTypeId3;
public ReferenceBatchBuilder(IComponentDatabase componentDatabase, IComponentTypeLookup componentTypeLookup)
{
ComponentDatabase = componentDatabase;
_componentTypeId1 = componentTypeLookup.GetComponentType(typeof(T1));
_componentTypeId2 = componentTypeLookup.GetComponentType(typeof(T2));
_componentTypeId3 = componentTypeLookup.GetComponentType(typeof(T3));
}
public ReferenceBatch<T1, T2, T3>[] Build(IReadOnlyList<IEntity> entities)
{
var componentArray1 = ComponentDatabase.GetComponents<T1>(_componentTypeId1);
var componentArray2 = ComponentDatabase.GetComponents<T2>(_componentTypeId2);
var componentArray3 = ComponentDatabase.GetComponents<T3>(_componentTypeId3);
var batches = new ReferenceBatch<T1, T2, T3>[entities.Count];
for (var i = 0; i < entities.Count; i++)
{
if (entities.Count != batches.Length)
{ return new ReferenceBatch<T1, T2, T3>[0]; }
var entity = entities[i];
var component1Allocation = entity.ComponentAllocations[_componentTypeId1];
var component2Allocation = entity.ComponentAllocations[_componentTypeId2];
var component3Allocation = entity.ComponentAllocations[_componentTypeId3];
batches[i] = new ReferenceBatch<T1, T2, T3>(
entity.Id, componentArray1[component1Allocation], componentArray2[component2Allocation],
componentArray3[component3Allocation]);
}
return batches;
}
}
public class ReferenceBatchBuilder<T1, T2, T3, T4> : IReferenceBatchBuilder<T1, T2, T3, T4>
where T1 : class, IComponent
where T2 : class, IComponent
where T3 : class, IComponent
where T4 : class, IComponent
{
public IComponentDatabase ComponentDatabase { get; }
private readonly int _componentTypeId1, _componentTypeId2, _componentTypeId3, _componentTypeId4;
public ReferenceBatchBuilder(IComponentDatabase componentDatabase, IComponentTypeLookup componentTypeLookup)
{
ComponentDatabase = componentDatabase;
_componentTypeId1 = componentTypeLookup.GetComponentType(typeof(T1));
_componentTypeId2 = componentTypeLookup.GetComponentType(typeof(T2));
_componentTypeId3 = componentTypeLookup.GetComponentType(typeof(T3));
_componentTypeId4 = componentTypeLookup.GetComponentType(typeof(T4));
}
public ReferenceBatch<T1, T2, T3, T4>[] Build(IReadOnlyList<IEntity> entities)
{
var componentArray1 = ComponentDatabase.GetComponents<T1>(_componentTypeId1);
var componentArray2 = ComponentDatabase.GetComponents<T2>(_componentTypeId2);
var componentArray3 = ComponentDatabase.GetComponents<T3>(_componentTypeId3);
var componentArray4 = ComponentDatabase.GetComponents<T4>(_componentTypeId4);
var batches = new ReferenceBatch<T1, T2, T3, T4>[entities.Count];
for (var i = 0; i < entities.Count; i++)
{
if (entities.Count != batches.Length)
{ return new ReferenceBatch<T1, T2, T3, T4>[0]; }
var entity = entities[i];
var component1Allocation = entity.ComponentAllocations[_componentTypeId1];
var component2Allocation = entity.ComponentAllocations[_componentTypeId2];
var component3Allocation = entity.ComponentAllocations[_componentTypeId3];
var component4Allocation = entity.ComponentAllocations[_componentTypeId4];
batches[i] = new ReferenceBatch<T1, T2, T3, T4>(
entity.Id, componentArray1[component1Allocation], componentArray2[component2Allocation],
componentArray3[component3Allocation], componentArray4[component4Allocation]);
}
return batches;
}
}
public class ReferenceBatchBuilder<T1, T2, T3, T4, T5> : IReferenceBatchBuilder<T1, T2, T3, T4, T5>
where T1 : class, IComponent
where T2 : class, IComponent
where T3 : class, IComponent
where T4 : class, IComponent
where T5 : class, IComponent
{
public IComponentDatabase ComponentDatabase { get; }
private readonly int _componentTypeId1, _componentTypeId2, _componentTypeId3,
_componentTypeId4, _componentTypeId5;
public ReferenceBatchBuilder(IComponentDatabase componentDatabase, IComponentTypeLookup componentTypeLookup)
{
ComponentDatabase = componentDatabase;
_componentTypeId1 = componentTypeLookup.GetComponentType(typeof(T1));
_componentTypeId2 = componentTypeLookup.GetComponentType(typeof(T2));
_componentTypeId3 = componentTypeLookup.GetComponentType(typeof(T3));
_componentTypeId4 = componentTypeLookup.GetComponentType(typeof(T4));
_componentTypeId5 = componentTypeLookup.GetComponentType(typeof(T5));
}
public ReferenceBatch<T1, T2, T3, T4, T5>[] Build(IReadOnlyList<IEntity> entities)
{
var componentArray1 = ComponentDatabase.GetComponents<T1>(_componentTypeId1);
var componentArray2 = ComponentDatabase.GetComponents<T2>(_componentTypeId2);
var componentArray3 = ComponentDatabase.GetComponents<T3>(_componentTypeId3);
var componentArray4 = ComponentDatabase.GetComponents<T4>(_componentTypeId4);
var componentArray5 = ComponentDatabase.GetComponents<T5>(_componentTypeId5);
var batches = new ReferenceBatch<T1, T2, T3, T4, T5>[entities.Count];
for (var i = 0; i < entities.Count; i++)
{
if (entities.Count != batches.Length)
{ return new ReferenceBatch<T1, T2, T3, T4, T5>[0]; }
var entity = entities[i];
var component1Allocation = entity.ComponentAllocations[_componentTypeId1];
var component2Allocation = entity.ComponentAllocations[_componentTypeId2];
var component3Allocation = entity.ComponentAllocations[_componentTypeId3];
var component4Allocation = entity.ComponentAllocations[_componentTypeId4];
var component5Allocation = entity.ComponentAllocations[_componentTypeId5];
batches[i] = new ReferenceBatch<T1, T2, T3, T4, T5>(
entity.Id, componentArray1[component1Allocation], componentArray2[component2Allocation],
componentArray3[component3Allocation], componentArray4[component4Allocation],
componentArray5[component5Allocation]);
}
return batches;
}
}
public class ReferenceBatchBuilder<T1, T2, T3, T4, T5, T6> : IReferenceBatchBuilder<T1, T2, T3, T4, T5, T6>
where T1 : class, IComponent
where T2 : class, IComponent
where T3 : class, IComponent
where T4 : class, IComponent
where T5 : class, IComponent
where T6 : class, IComponent
{
public IComponentDatabase ComponentDatabase { get; }
private readonly int _componentTypeId1, _componentTypeId2, _componentTypeId3,
_componentTypeId4, _componentTypeId5, _componentTypeId6;
public ReferenceBatchBuilder(IComponentDatabase componentDatabase, IComponentTypeLookup componentTypeLookup)
{
ComponentDatabase = componentDatabase;
_componentTypeId1 = componentTypeLookup.GetComponentType(typeof(T1));
_componentTypeId2 = componentTypeLookup.GetComponentType(typeof(T2));
_componentTypeId3 = componentTypeLookup.GetComponentType(typeof(T3));
_componentTypeId4 = componentTypeLookup.GetComponentType(typeof(T4));
_componentTypeId5 = componentTypeLookup.GetComponentType(typeof(T5));
_componentTypeId6 = componentTypeLookup.GetComponentType(typeof(T6));
}
public ReferenceBatch<T1, T2, T3, T4, T5, T6>[] Build(IReadOnlyList<IEntity> entities)
{
var componentArray1 = ComponentDatabase.GetComponents<T1>(_componentTypeId1);
var componentArray2 = ComponentDatabase.GetComponents<T2>(_componentTypeId2);
var componentArray3 = ComponentDatabase.GetComponents<T3>(_componentTypeId3);
var componentArray4 = ComponentDatabase.GetComponents<T4>(_componentTypeId4);
var componentArray5 = ComponentDatabase.GetComponents<T5>(_componentTypeId5);
var componentArray6 = ComponentDatabase.GetComponents<T6>(_componentTypeId6);
var batches = new ReferenceBatch<T1, T2, T3, T4, T5, T6>[entities.Count];
for (var i = 0; i < entities.Count; i++)
{
if (entities.Count != batches.Length)
{ return new ReferenceBatch<T1, T2, T3, T4, T5, T6>[0]; }
var entity = entities[i];
var component1Allocation = entity.ComponentAllocations[_componentTypeId1];
var component2Allocation = entity.ComponentAllocations[_componentTypeId2];
var component3Allocation = entity.ComponentAllocations[_componentTypeId3];
var component4Allocation = entity.ComponentAllocations[_componentTypeId4];
var component5Allocation = entity.ComponentAllocations[_componentTypeId5];
var component6Allocation = entity.ComponentAllocations[_componentTypeId6];
batches[i] = new ReferenceBatch<T1, T2, T3, T4, T5, T6>(
entity.Id, componentArray1[component1Allocation], componentArray2[component2Allocation],
componentArray3[component3Allocation], componentArray4[component4Allocation],
componentArray5[component5Allocation], componentArray6[component6Allocation]);
}
return batches;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.