context stringlengths 2.52k 185k | gt stringclasses 1 value |
|---|---|
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Windows;
using System.Windows.Media;
namespace FontAwesome.Sharp
{
// cf.:
// * http://stackoverflow.com/questions/23108181/changing-font-icon-in-wpf-using-font-awesome
// * http://www.codeproject.com/Tips/634540/Using-Font-Icons
public static class IconHelper
{
#region Public
public static bool ThrowOnNullFonts = false;
public static readonly IconChar[] Orphans = {
IconChar.None
// not contained in any of the ttf-fonts!
,IconChar.FontAwesomeLogoFull
};
/// <summary>
/// All valid icons.
/// </summary>
public static readonly IconChar[] Icons = Enum.GetValues(typeof(IconChar))
.Cast<IconChar>().Except(Orphans).ToArray();
/// <summary>
/// Default brush / color.
/// </summary>
public static readonly Brush DefaultBrush = SystemColors.WindowTextBrush; // this is TextBlock default brush
/// <summary>
/// Default icon size in pixels.
/// </summary>
public const int DefaultSize = 48;
/// <summary>
/// Load the specified font from assembly resource stream
/// </summary>
/// <param name="assembly">The assembly to load from</param>
/// <param name="path">The resource path in the assembly</param>
/// <param name="fontTitle">The resource name</param>
/// <returns></returns>
public static FontFamily LoadFont(this Assembly assembly, string path, string fontTitle)
{
return new(BaseUri, $"./{assembly.GetName().Name};component/{path}/#{fontTitle}");
}
/// <summary>
/// Renders an image for the specified font and icon
/// </summary>
/// <typeparam name="TEnum">The icon enum type</typeparam>
/// <param name="fontFamily">The icon font</param>
/// <param name="icon">The icon to render</param>
/// <param name="brush">The icon brush / color</param>
/// <param name="size">The icon size in pixels</param>
/// <returns>The rendered image</returns>
public static ImageSource ToImageSource<TEnum>(this FontFamily fontFamily, TEnum icon,
Brush brush = null, double size = DefaultSize)
where TEnum : struct, IConvertible, IComparable, IFormattable
{
return fontFamily.GetTypefaces().Find(icon, out var gt, out var glyphIndex) != null
? ToImageSource(brush, size, gt, glyphIndex)
: null;
}
/// <summary>
/// Renders an image for the specified font and icon
/// </summary>
/// <param name="iconChar">The icon to render</param>
/// <param name="brush">The icon brush / color</param>
/// <param name="size">The icon size in pixels</param>
/// <returns>The rendered image</returns>
public static ImageSource ToImageSource(this IconChar iconChar,
Brush brush = null, double size = DefaultSize)
{
var typeFace = Typefaces.Find(iconChar, out var gt, out var glyphIndex);
return typeFace == null ? null : ToImageSource(brush, size, gt, glyphIndex);
}
/// <summary>
/// Renders an image for the specified font, style and icon
/// </summary>
/// <param name="iconChar">The icon to render</param>
/// <param name="iconFont">The icon font style</param>
/// <param name="brush">The icon brush / color</param>
/// <param name="size">The icon size in pixels</param>
/// <returns>The rendered image</returns>
public static ImageSource ToImageSource(this IconChar iconChar, IconFont iconFont,
Brush brush = null, double size = DefaultSize)
{
var typeface = TypefaceFor(iconChar, iconFont);
if (typeface == null) return null;
return typeface.TryFind(iconChar.UniCode(), out var gt, out var glyphIndex) ? ToImageSource(brush, size, gt, glyphIndex) : null;
}
/// <summary>
/// Convert icon code to UTF-32 unicode character
/// </summary>
/// <typeparam name="TEnum">The icon enum type</typeparam>
/// <param name="icon">The icon</param>
/// <returns>Character code</returns>
public static string ToChar<TEnum>(this TEnum icon) where TEnum : struct, IConvertible, IComparable, IFormattable
{
return char.ConvertFromUtf32(icon.UniCode());
}
/// <summary>
/// Load typefaces from assembly resources
/// </summary>
/// <param name="assembly">The assembly to load from</param>
/// <param name="path">The resource path (directory)</param>
/// <param name="fontTitles">The font resource item names</param>
/// <returns>The loaded typefaces</returns>
public static Typeface[] LoadTypefaces(this Assembly assembly, string path,
IEnumerable<string> fontTitles)
{
return fontTitles.Select(fontTitle =>
{
var fontFamily = assembly.LoadFont(path, fontTitle);
return new Typeface(fontFamily, FontStyles.Normal, FontWeights.Normal, FontStretches.Normal);
}).ToArray();
}
/// <summary>
/// Find the typeface containing the specified icon
/// </summary>
/// <typeparam name="TEnum">The icon enum type</typeparam>
/// <param name="typefaces"></param>
/// <param name="icon">The icon</param>
/// <param name="gt">The found font face</param>
/// <param name="glyphIndex">The glyph index into the font face for the specified icon</param>
/// <returns></returns>
public static Typeface Find<TEnum>(this IEnumerable<Typeface> typefaces,
TEnum icon, out GlyphTypeface gt, out ushort glyphIndex)
where TEnum : struct, IConvertible, IComparable, IFormattable
{
var iconCode = icon.UniCode();
gt = null;
glyphIndex = NoSuchGlyph;
foreach (var typeface in typefaces)
{
if (typeface.TryFind(iconCode, out gt, out glyphIndex))
return typeface;
}
return null;
}
private const ushort NoSuchGlyph = 42;
private static bool TryFind(this Typeface typeface, int iconCode, out GlyphTypeface gt, out ushort glyphIndex)
{
gt = null;
glyphIndex = NoSuchGlyph;
return typeface.TryGetGlyphTypeface(out gt) && gt.CharacterToGlyphMap.TryGetValue(iconCode, out glyphIndex);
}
#endregion
#region Internal
internal static FontFamily FontFor(IconChar iconChar)
{
return TypefaceFor(iconChar)?.FontFamily;
}
internal static FontFamily FontFor(IconChar iconChar, IconFont iconFont)
{
return TypefaceFor(iconChar, iconFont)?.FontFamily;
}
internal static Typeface TypefaceFor(IconChar iconChar)
{
return Orphans.Contains(iconChar) ? null : Typefaces.Find(iconChar.UniCode(), out _, out _);
}
internal static Typeface TypefaceFor(IconChar iconChar, IconFont iconFont)
{
if (iconFont == IconFont.Auto) return TypefaceFor(iconChar);
var key = (int)iconFont;
if (TypefaceForStyle.TryGetValue(key, out var typeFace)) return typeFace;
if (!FontTitles.TryGetValue(key, out var name))
return Throw($"No font loaded for style: {iconFont}");
typeFace = Typefaces.FirstOrDefault(t => t.FontFamily.Source.EndsWith(name));
if (typeFace == null)
return Throw($"No font loaded for '{name}'");
TypefaceForStyle.Add(key, typeFace);
return typeFace;
}
private static readonly Dictionary<int, Typeface> TypefaceForStyle = new();
internal static Typeface Throw(string message)
{
if (ThrowOnNullFonts) throw new InvalidOperationException(message);
return default;
}
internal static readonly Uri BaseUri = new($"{System.IO.Packaging.PackUriHelper.UriSchemePack}://application:,,,/");
#endregion
#region Private
private static ImageSource ToImageSource(Brush foregroundBrush, double size, GlyphTypeface gt, ushort glyphIndex)
{
var fontSize = PixelsToPoints(size);
var width = gt.AdvanceWidths[glyphIndex];
#pragma warning disable CS0618 // Deprecated constructor
var glyphRun = new GlyphRun(gt, 0, false, fontSize,
new[] { glyphIndex }, new Point(0, 0), new[] { width },
null, null, null, null, null, null);
#pragma warning restore CS0618
var glyphRunDrawing = new GlyphRunDrawing(foregroundBrush ?? DefaultBrush, glyphRun);
return new DrawingImage(glyphRunDrawing);
}
private static int UniCode<TEnum>(this TEnum icon)
where TEnum : struct, IConvertible, IComparable, IFormattable
{
return icon.ToInt32(CultureInfo.InvariantCulture);
}
internal static readonly Dictionary<int, string> FontTitles = new Dictionary<int, string>()
{
{ (int)IconFont.Regular, "Font Awesome 5 Free Regular"}, // fa-regular-400.ttf
{ (int)IconFont.Solid, "Font Awesome 5 Free Solid"}, // fa-solid-900.ttf
{ (int)IconFont.Brands, "Font Awesome 5 Brands Regular"} // fa-brands-400.ttf
};
//internal static Dictionary<int, String> FontForStyle
private static readonly Typeface[] Typefaces = typeof(IconHelper).Assembly.LoadTypefaces("fonts", FontTitles.Values);
private static readonly int Dpi = GetDpi();
private static double PixelsToPoints(double size)
{
// pixels to points, cf.: http://stackoverflow.com/a/139712/2592915
return size * (72.0 / Dpi);
}
[SuppressMessage("ReSharper", "PossibleNullReferenceException")]
private static int GetDpi()
{
// How can I get the DPI in WPF?, cf.: http://stackoverflow.com/a/12487917/2592915
var dpiProperty = typeof(SystemParameters).GetProperty("Dpi", BindingFlags.NonPublic | BindingFlags.Static);
return (int)dpiProperty.GetValue(null, null);
}
#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 OrUInt32()
{
var test = new SimpleBinaryOpTest__OrUInt32();
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 SimpleBinaryOpTest__OrUInt32
{
private const int VectorSize = 16;
private const int Op1ElementCount = VectorSize / sizeof(UInt32);
private const int Op2ElementCount = VectorSize / sizeof(UInt32);
private const int RetElementCount = VectorSize / sizeof(UInt32);
private static UInt32[] _data1 = new UInt32[Op1ElementCount];
private static UInt32[] _data2 = new UInt32[Op2ElementCount];
private static Vector128<UInt32> _clsVar1;
private static Vector128<UInt32> _clsVar2;
private Vector128<UInt32> _fld1;
private Vector128<UInt32> _fld2;
private SimpleBinaryOpTest__DataTable<UInt32, UInt32, UInt32> _dataTable;
static SimpleBinaryOpTest__OrUInt32()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (uint)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _clsVar1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (uint)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _clsVar2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), VectorSize);
}
public SimpleBinaryOpTest__OrUInt32()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (uint)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (uint)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (uint)(random.Next(0, int.MaxValue)); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (uint)(random.Next(0, int.MaxValue)); }
_dataTable = new SimpleBinaryOpTest__DataTable<UInt32, UInt32, UInt32>(_data1, _data2, new UInt32[RetElementCount], VectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse2.Or(
Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Sse2.Or(
Sse2.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((UInt32*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse2.Or(
Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.Or), new Type[] { typeof(Vector128<UInt32>), typeof(Vector128<UInt32>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.Or), new Type[] { typeof(Vector128<UInt32>), typeof(Vector128<UInt32>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((UInt32*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.Or), new Type[] { typeof(Vector128<UInt32>), typeof(Vector128<UInt32>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Sse2.Or(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray2Ptr);
var result = Sse2.Or(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Sse2.LoadVector128((UInt32*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadVector128((UInt32*)(_dataTable.inArray2Ptr));
var result = Sse2.Or(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray2Ptr));
var result = Sse2.Or(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__OrUInt32();
var result = Sse2.Or(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Sse2.Or(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<UInt32> left, Vector128<UInt32> right, void* result, [CallerMemberName] string method = "")
{
UInt32[] inArray1 = new UInt32[Op1ElementCount];
UInt32[] inArray2 = new UInt32[Op2ElementCount];
UInt32[] outArray = new UInt32[RetElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
UInt32[] inArray1 = new UInt32[Op1ElementCount];
UInt32[] inArray2 = new UInt32[Op2ElementCount];
UInt32[] outArray = new UInt32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(UInt32[] left, UInt32[] right, UInt32[] result, [CallerMemberName] string method = "")
{
if ((uint)(left[0] | right[0]) != result[0])
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((uint)(left[i] | right[i]) != result[i])
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Sse2)}.{nameof(Sse2.Or)}<UInt32>(Vector128<UInt32>, Vector128<UInt32>): {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using ZitaAsteria.Scene;
using ZitaAsteria.MenuSystem;
using ZAsteroids.World.Weapons;
using DPSF;
using ZAsteroids.World.HUD;
namespace ZitaAsteria
{
/// <summary>
/// This is the main game class for Pilot Project
/// </summary>
public partial class ZAsteroidsGameClass : Microsoft.Xna.Framework.Game
{
/// <summary>
/// Allows the game to perform any initialization it needs to before starting to run.
/// This is where it can query for any required services and load any non-graphic
/// related content. Calling base.Initialize will enumerate through any components
/// and initialize them as well.
/// </summary>
protected override void Initialize()
{
base.Initialize();
}
/// <summary>
/// LoadContent will be called once per game and is the place to load
/// all of your content.
/// </summary>
protected override void LoadContent()
{
WorldContainer.ProfilingEnabled = false;
WorldContainer.ShowFrameRate = false;
WorldContainer.DepthBufferDisabledStencilState = new DepthStencilState();
WorldContainer.DepthBufferDisabledStencilState.DepthBufferEnable = false;
WorldContainer.DepthBufferEnabledStencilState = new DepthStencilState();
WorldContainer.DepthBufferEnabledStencilState.DepthBufferEnable = true;
WorldContainer.graphicsDevice = this.GraphicsDevice;
this.GraphicsDevice.DeviceReset += new EventHandler<EventArgs>(GraphicsDevice_DeviceReset);
WorldContainer.graphicsDeviceManager = graphics;
//WorldContainer.gameClass = this;
//// Declare the Particle System Manager to manage the Particle Systems (DPSF)
WorldContainer.particleSystemManager = new ParticleSystemManager();
elapsedSeconds = 0;
gameEnded = false;
// Create a new SpriteBatch, which can be used to draw textures.
WorldContainer.spriteBatch = new SpriteBatch(WorldContainer.graphicsDevice);
DateTime preContent = DateTime.Now;
//Initialize the static world content class
WorldContent.InitializeContent(Content, WorldContainer.graphicsDevice,
SharedContent.ContentInitializationTypes.MenuContent |
SharedContent.ContentInitializationTypes.MusicContent |
SharedContent.ContentInitializationTypes.SfxContent |
SharedContent.ContentInitializationTypes.EffectsContent);
if (WorldContainer.ProfilingEnabled || WorldContainer.ShowFrameRate)
{
//Initialize the framerate counter
frameRateCounter.Initialize();
if (WorldContainer.ProfilingEnabled)
{
frameRateCounter.ProfileEntries.Add("Content", new ProfileEntry("Content", preContent));
frameRateCounter.ProfileEntries["Content"].EndTime = DateTime.Now;
frameRateCounter.ProfileEntries.Add("ObjMan", new ProfileEntry("ObjMan", DateTime.Now));
}
}
//Initialise the ObjectManager
ObjectManager.Initialize_ForZAsteroids();
if (WorldContainer.ProfilingEnabled)
{
frameRateCounter.ProfileEntries["ObjMan"].EndTime = DateTime.Now;
frameRateCounter.ProfileEntries.Add("General", new ProfileEntry("General", DateTime.Now));
}
// General Sound Effect Manager : Must be done after sfxContent Loaded
WorldContainer.soundEffectsMgr = new SoundEffectsMgr();
//Set up the music manager.
WorldContainer.musicManager = new ZitaAsteria.Scene.MusicManager();
WorldContainer.musicManager.Initialize();
WorldContainer.musicManager.setMusicVolume();
////Create the shader textures
shaderRenderTarget = new RenderTarget2D(graphics.GraphicsDevice,
graphics.GraphicsDevice.PresentationParameters.BackBufferWidth,
graphics.GraphicsDevice.PresentationParameters.BackBufferHeight,
true,
graphics.GraphicsDevice.PresentationParameters.BackBufferFormat,
graphics.GraphicsDevice.PresentationParameters.DepthStencilFormat,
graphics.GraphicsDevice.PresentationParameters.MultiSampleCount,
graphics.GraphicsDevice.PresentationParameters.RenderTargetUsage);
shaderTexture = new Texture2D(graphics.GraphicsDevice, shaderRenderTarget.Width, shaderRenderTarget.Height,
true, graphics.GraphicsDevice.PresentationParameters.BackBufferFormat);
//Create the menu controller
MenuContainer.MenuSystemScene = new MenuSystemScene();
MenuContainer.MenuSystemScene.Initialize(GraphicsDevice, WorldContent.menuContentManager);
MenuContainer.Satellite.SceneRotation = new Vector3(0, 0, 0);
//And give the ship a weapon.
Weapon = new LaserWeapon();
Weapon.Initialize();
HUDProperties.DrawLines = new bool[]
{
false,
false,
false,
false,
false
};
// HUD stuff
_score = new ZAsteroids.World.HUD.HUDScore();
_score.Initialize();
_score.Enable(true);
_hudModeInfo = new ZAsteroids.World.HUD.HUDGameState();
_hudModeInfo.Initialize();
_hudModeInfo.Enable(true);
_upgrade = new ZAsteroids.World.HUD.HUDUpgrade();
_upgrade.Initialize();
_upgrade.Enable(true);
_crosshair = new ZAsteroids.World.HUD.HUDCrosshair();
_crosshair.Initialize();
_crosshair.Enable(true);
_general = new ZAsteroids.World.HUD.HUDGeneral();
_general.Initialize();
_general.Enable(true);
_shields = new ZAsteroids.World.HUD.HUDSheilds();
_shields.Initialize();
_shields.Enable(true);
_hudSphere = new ZAsteroids.World.HUD.HUDSphere();
_hudSphere.Initialize();
_hudSphere.Enable(true);
_hudSatellite = new HUDSatellite();
_hudSatellite.Initialize();
_hudSatellite.Enable(true);
_hudIntroScreen = new HUDIntroScreen();
_hudIntroScreen.Initialize();
_hudControls = new HUDControls();
_hudControls.Initialize();
_hudDamage = new HUDDamage();
_hudDamage.Initialize();
_hudDamage.Enable(true);
// Compute the Aspect Ratio of the window
fAspectRatio = (float)WorldContainer.graphicsDevice.Viewport.Width / (float)WorldContainer.graphicsDevice.Viewport.Height;
_gameManager = new ZAsteroids.World.GameManager(this);
HUDProperties.GameManager = _gameManager;
_gameManager.Initialize();
//Initialize the upgrades
_upgradeManager = new ZAsteroids.World.Upgrades.UpgradeManager(_gameManager);
HUDProperties.UpgradeManager = _upgradeManager;
//Do a garbage collection after initialization
GC.Collect();
}
/// <summary>
/// UnloadContent will be called once per game and is the place to unload
/// all content.
/// </summary>
protected override void UnloadContent()
{
//Create the framerate counter.
//frameRateCounter = null;
// Declare the Particle System Manager to manage the Particle Systems (DPSF)
WorldContainer.particleSystemManager.DestroyAndRemoveAllParticleSystems();
}
public void restart()
{
UnloadContent();
Initialize();
LoadContent();
}
public void unloadGameData()
{
UnloadContent();
base.Initialize();
}
public void configureGraphicsDevice()
{
//DISABLE Anti-Aliasing
graphics.PreferMultiSampling = false;
//Set the device size...
this.graphics.PreferredBackBufferWidth = (int)GameConfiguration.Resolutions[WorldContainer.gameConfiguration.DisplayResolutionS].X;
this.graphics.PreferredBackBufferHeight = (int)GameConfiguration.Resolutions[WorldContainer.gameConfiguration.DisplayResolutionS].Y;
this.graphics.SynchronizeWithVerticalRetrace = WorldContainer.gameConfiguration.VSyncEnabled; // Disable V-Sync
#if XBOX
graphics.IsFullScreen = true;
// WorldContainer.gameConfiguration.selectedResolution = new Vector2(GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Width, GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Height);
#else
if (graphics.IsFullScreen != WorldContainer.gameConfiguration.FullScreen)
{
graphics.ToggleFullScreen();
}
#endif
this.graphics.ApplyChanges();
//LoadContent();
}
public void configurePeripheralSettings()
{
// WorldContainer.soundEffectsMgr.setSoundFXVolume();
WorldContainer.musicManager.setMusicVolume();
}
} // END of Partial class GameClass_Initialisation
}
| |
using System;
using System.Collections.Generic;
using JetBrains.Annotations;
using Robust.Client.Animations;
using Robust.Client.GameObjects;
using Robust.Shared.GameObjects;
using Robust.Shared.IoC;
using Robust.Shared.Serialization;
using Robust.Shared.Serialization.Manager.Attributes;
using static Content.Shared.VendingMachines.SharedVendingMachineComponent;
namespace Content.Client.VendingMachines.UI
{
[UsedImplicitly]
public sealed class VendingMachineVisualizer : AppearanceVisualizer, ISerializationHooks
{
// TODO: Should default to off or broken if damaged
//
// TODO: The length of these animations is supposed to be dictated
// by the vending machine's pack prototype's `AnimationDuration`
// but we have no good way of passing that data from the server
// to the client at the moment. Rework Visualizers?
private Dictionary<string, bool> _baseStates = new();
private static readonly Dictionary<string, VendingMachineVisualLayers> LayerMap =
new()
{
{"off", VendingMachineVisualLayers.Unlit},
{"screen", VendingMachineVisualLayers.Screen},
{"normal", VendingMachineVisualLayers.Base},
{"normal-unshaded", VendingMachineVisualLayers.BaseUnshaded},
{"eject", VendingMachineVisualLayers.Base},
{"eject-unshaded", VendingMachineVisualLayers.BaseUnshaded},
{"deny", VendingMachineVisualLayers.Base},
{"deny-unshaded", VendingMachineVisualLayers.BaseUnshaded},
{"broken", VendingMachineVisualLayers.Unlit},
};
[DataField("screen")]
private bool _screen;
[DataField("normal")]
private bool _normal;
[DataField("normalUnshaded")]
private bool _normalUnshaded;
[DataField("eject")]
private bool _eject;
[DataField("ejectUnshaded")]
private bool _ejectUnshaded;
[DataField("deny")]
private bool _deny;
[DataField("denyUnshaded")]
private bool _denyUnshaded;
[DataField("broken")]
private bool _broken;
[DataField("brokenUnshaded")]
private bool _brokenUnshaded;
private readonly Dictionary<string, Animation> _animations = new();
void ISerializationHooks.AfterDeserialization()
{
// Used a dictionary so the yaml can adhere to the style-guide and the texture states can be clear
var states = new Dictionary<string, bool>
{
{"off", true},
{"screen", _screen},
{"normal", _normal},
{"normal-unshaded", _normalUnshaded},
{"eject", _eject},
{"eject-unshaded", _ejectUnshaded},
{"deny", _deny},
{"deny-unshaded", _denyUnshaded},
{"broken", _broken},
{"broken-unshaded", _brokenUnshaded},
};
_baseStates = states;
if (_baseStates["deny"])
{
InitializeAnimation("deny");
}
if (_baseStates["deny-unshaded"])
{
InitializeAnimation("deny-unshaded", true);
}
if (_baseStates["eject"])
{
InitializeAnimation("eject");
}
if (_baseStates["eject-unshaded"])
{
InitializeAnimation("eject-unshaded", true);
}
}
private void InitializeAnimation(string key, bool unshaded = false)
{
_animations.Add(key, new Animation {Length = TimeSpan.FromSeconds(1.2f)});
var flick = new AnimationTrackSpriteFlick();
_animations[key].AnimationTracks.Add(flick);
flick.LayerKey = unshaded ? VendingMachineVisualLayers.BaseUnshaded : VendingMachineVisualLayers.Base;
flick.KeyFrames.Add(new AnimationTrackSpriteFlick.KeyFrame(key, 0f));
}
public override void InitializeEntity(EntityUid entity)
{
base.InitializeEntity(entity);
IoCManager.Resolve<IEntityManager>().EnsureComponent<AnimationPlayerComponent>(entity);
}
private void HideLayers(ISpriteComponent spriteComponent)
{
foreach (var layer in spriteComponent.AllLayers)
{
layer.Visible = false;
}
spriteComponent.LayerSetVisible(VendingMachineVisualLayers.Unlit, true);
}
public override void OnChangeData(AppearanceComponent component)
{
base.OnChangeData(component);
var entMan = IoCManager.Resolve<IEntityManager>();
var sprite = entMan.GetComponent<ISpriteComponent>(component.Owner);
var animPlayer = entMan.GetComponent<AnimationPlayerComponent>(component.Owner);
if (!component.TryGetData(VendingMachineVisuals.VisualState, out VendingMachineVisualState state))
{
state = VendingMachineVisualState.Normal;
}
// Hide last state
HideLayers(sprite);
ActivateState(sprite, "off");
switch (state)
{
case VendingMachineVisualState.Normal:
ActivateState(sprite, "screen");
ActivateState(sprite, "normal-unshaded");
ActivateState(sprite, "normal");
break;
case VendingMachineVisualState.Off:
break;
case VendingMachineVisualState.Broken:
ActivateState(sprite, "broken-unshaded");
ActivateState(sprite, "broken");
break;
case VendingMachineVisualState.Deny:
ActivateState(sprite, "screen");
ActivateAnimation(sprite, animPlayer, "deny-unshaded");
ActivateAnimation(sprite, animPlayer, "deny");
break;
case VendingMachineVisualState.Eject:
ActivateState(sprite, "screen");
ActivateAnimation(sprite, animPlayer, "eject-unshaded");
ActivateAnimation(sprite, animPlayer, "eject");
break;
default:
throw new ArgumentOutOfRangeException();
}
}
// Helper methods just to avoid all of that hard-to-read-indented code
private void ActivateState(ISpriteComponent spriteComponent, string stateId)
{
// No state for it on the rsi :(
if (!_baseStates[stateId])
{
return;
}
var stateLayer = LayerMap[stateId];
spriteComponent.LayerSetVisible(stateLayer, true);
spriteComponent.LayerSetState(stateLayer, stateId);
}
private void ActivateAnimation(ISpriteComponent spriteComponent, AnimationPlayerComponent animationPlayer, string key)
{
if (!_animations.TryGetValue(key, out var animation))
{
return;
}
if (!animationPlayer.HasRunningAnimation(key))
{
spriteComponent.LayerSetVisible(LayerMap[key], true);
animationPlayer.Play(animation, key);
}
}
public enum VendingMachineVisualLayers : byte
{
// Off / Broken. The other layers will overlay this if the machine is on.
Unlit,
// Normal / Deny / Eject
Base,
BaseUnshaded,
// Screens that are persistent (where the machine is not off or broken)
Screen,
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2015 Charlie Poole
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using System.Collections;
using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal;
using NUnit.TestData.TestCaseAttributeFixture;
using NUnit.TestUtilities;
namespace NUnit.Framework.Attributes
{
[TestFixture]
public class TestCaseAttributeTests
{
[TestCase(12, 3, 4)]
[TestCase(12, 2, 6)]
[TestCase(12, 4, 3)]
public void IntegerDivisionWithResultPassedToTest(int n, int d, int q)
{
Assert.AreEqual(q, n / d);
}
[TestCase(12, 3, ExpectedResult = 4)]
[TestCase(12, 2, ExpectedResult = 6)]
[TestCase(12, 4, ExpectedResult = 3)]
public int IntegerDivisionWithResultCheckedByNUnit(int n, int d)
{
return n / d;
}
[TestCase(2, 2, ExpectedResult=4)]
public double CanConvertIntToDouble(double x, double y)
{
return x + y;
}
[TestCase("2.2", "3.3", ExpectedResult = 5.5)]
public decimal CanConvertStringToDecimal(decimal x, decimal y)
{
return x + y;
}
[TestCase(2.2, 3.3, ExpectedResult = 5.5)]
public decimal CanConvertDoubleToDecimal(decimal x, decimal y)
{
return x + y;
}
[TestCase(5, 2, ExpectedResult = 7)]
public decimal CanConvertIntToDecimal(decimal x, decimal y)
{
return x + y;
}
[TestCase(5, 2, ExpectedResult = 7)]
public short CanConvertSmallIntsToShort(short x, short y)
{
return (short)(x + y);
}
[TestCase(5, 2, ExpectedResult = 7)]
public byte CanConvertSmallIntsToByte(byte x, byte y)
{
return (byte)(x + y);
}
[TestCase(5, 2, ExpectedResult = 7)]
public sbyte CanConvertSmallIntsToSByte(sbyte x, sbyte y)
{
return (sbyte)(x + y);
}
[TestCase("MethodCausesConversionOverflow", RunState.NotRunnable)]
[TestCase("VoidTestCaseWithExpectedResult", RunState.NotRunnable)]
[TestCase("TestCaseWithNullableReturnValueAndNullExpectedResult", RunState.Runnable)]
public void TestCaseRunnableState(string methodName, RunState expectedState)
{
var test = (Test)TestBuilder.MakeParameterizedMethodSuite(
typeof(TestCaseAttributeFixture), methodName).Tests[0];
Assert.AreEqual(expectedState, test.RunState);
}
[TestCase("12-October-1942")]
public void CanConvertStringToDateTime(DateTime dt)
{
Assert.AreEqual(1942, dt.Year);
}
[TestCase("4:44:15")]
public void CanConvertStringToTimeSpan(TimeSpan ts)
{
Assert.AreEqual(4, ts.Hours);
Assert.AreEqual(44, ts.Minutes);
Assert.AreEqual(15, ts.Seconds);
}
[TestCase(null)]
public void CanPassNullAsFirstArgument(object a)
{
Assert.IsNull(a);
}
[TestCase(new object[] { 1, "two", 3.0 })]
[TestCase(new object[] { "zip" })]
public void CanPassObjectArrayAsFirstArgument(object[] a)
{
}
[TestCase(new object[] { "a", "b" })]
public void CanPassArrayAsArgument(object[] array)
{
Assert.AreEqual("a", array[0]);
Assert.AreEqual("b", array[1]);
}
[TestCase("a", "b")]
public void ArgumentsAreCoalescedInObjectArray(object[] array)
{
Assert.AreEqual("a", array[0]);
Assert.AreEqual("b", array[1]);
}
[TestCase(1, "b")]
public void ArgumentsOfDifferentTypeAreCoalescedInObjectArray(object[] array)
{
Assert.AreEqual(1, array[0]);
Assert.AreEqual("b", array[1]);
}
[TestCase(ExpectedResult = null)]
public object ResultCanBeNull()
{
return null;
}
[TestCase("a", "b")]
public void HandlesParamsArrayAsSoleArgument(params string[] array)
{
Assert.AreEqual("a", array[0]);
Assert.AreEqual("b", array[1]);
}
[TestCase("a")]
public void HandlesParamsArrayWithOneItemAsSoleArgument(params string[] array)
{
Assert.AreEqual("a", array[0]);
}
[TestCase("a", "b", "c", "d")]
public void HandlesParamsArrayAsLastArgument(string s1, string s2, params object[] array)
{
Assert.AreEqual("a", s1);
Assert.AreEqual("b", s2);
Assert.AreEqual("c", array[0]);
Assert.AreEqual("d", array[1]);
}
[TestCase("a", "b")]
public void HandlesParamsArrayWithNoItemsAsLastArgument(string s1, string s2, params object[] array)
{
Assert.AreEqual("a", s1);
Assert.AreEqual("b", s2);
Assert.AreEqual(0, array.Length);
}
[TestCase("a", "b", "c")]
public void HandlesParamsArrayWithOneItemAsLastArgument(string s1, string s2, params object[] array)
{
Assert.AreEqual("a", s1);
Assert.AreEqual("b", s2);
Assert.AreEqual("c", array[0]);
}
[Test]
public void CanSpecifyDescription()
{
Test test = (Test)TestBuilder.MakeParameterizedMethodSuite(
typeof(TestCaseAttributeFixture), "MethodHasDescriptionSpecified").Tests[0];
Assert.AreEqual("My Description", test.Properties.Get(PropertyNames.Description));
}
[Test]
public void CanSpecifyTestName()
{
Test test = (Test)TestBuilder.MakeParameterizedMethodSuite(
typeof(TestCaseAttributeFixture), "MethodHasTestNameSpecified").Tests[0];
Assert.AreEqual("XYZ", test.Name);
Assert.AreEqual("NUnit.TestData.TestCaseAttributeFixture.TestCaseAttributeFixture.XYZ", test.FullName);
}
[Test]
public void CanSpecifyCategory()
{
Test test = (Test)TestBuilder.MakeParameterizedMethodSuite(
typeof(TestCaseAttributeFixture), "MethodHasSingleCategory").Tests[0];
IList categories = test.Properties["Category"];
Assert.AreEqual(new string[] { "XYZ" }, categories);
}
[Test]
public void CanSpecifyMultipleCategories()
{
Test test = (Test)TestBuilder.MakeParameterizedMethodSuite(
typeof(TestCaseAttributeFixture), "MethodHasMultipleCategories").Tests[0];
IList categories = test.Properties["Category"];
Assert.AreEqual(new string[] { "X", "Y", "Z" }, categories);
}
[Test]
public void CanIgnoreIndividualTestCases()
{
TestSuite suite = TestBuilder.MakeParameterizedMethodSuite(
typeof(TestCaseAttributeFixture), "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));
testCase = TestFinder.Find("MethodWithIgnoredTestCases(3)", 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(TestCaseAttributeFixture), "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"));
}
#if !PORTABLE
[Test]
public void CanIncludePlatform()
{
bool isLinux = System.IO.Path.DirectorySeparatorChar == '/';
TestSuite suite = TestBuilder.MakeParameterizedMethodSuite(
typeof(TestCaseAttributeFixture), "MethodWithIncludePlatform");
Test testCase1 = TestFinder.Find("MethodWithIncludePlatform(1)", suite, false);
Test testCase2 = TestFinder.Find("MethodWithIncludePlatform(2)", suite, false);
if (isLinux)
{
Assert.That(testCase1.RunState, Is.EqualTo(RunState.Skipped));
Assert.That(testCase2.RunState, Is.EqualTo(RunState.Runnable));
}
else
{
Assert.That(testCase1.RunState, Is.EqualTo(RunState.Runnable));
Assert.That(testCase2.RunState, Is.EqualTo(RunState.Skipped));
}
}
[Test]
public void CanExcludePlatform()
{
bool isLinux = System.IO.Path.DirectorySeparatorChar == '/';
TestSuite suite = TestBuilder.MakeParameterizedMethodSuite(
typeof(TestCaseAttributeFixture), "MethodWitExcludePlatform");
Test testCase1 = TestFinder.Find("MethodWitExcludePlatform(1)", suite, false);
Test testCase2 = TestFinder.Find("MethodWitExcludePlatform(2)", suite, false);
if (isLinux)
{
Assert.That(testCase1.RunState, Is.EqualTo(RunState.Runnable));
Assert.That(testCase2.RunState, Is.EqualTo(RunState.Skipped));
}
else
{
Assert.That(testCase1.RunState, Is.EqualTo(RunState.Skipped));
Assert.That(testCase2.RunState, Is.EqualTo(RunState.Runnable));
}
}
#endif
#region Nullable<> tests
[TestCase(12, 3, 4)]
[TestCase(12, 2, 6)]
[TestCase(12, 4, 3)]
public void NullableIntegerDivisionWithResultPassedToTest(int? n, int? d, int? q)
{
Assert.AreEqual(q, n / d);
}
[TestCase(12, 3, ExpectedResult = 4)]
[TestCase(12, 2, ExpectedResult = 6)]
[TestCase(12, 4, ExpectedResult = 3)]
public int? NullableIntegerDivisionWithResultCheckedByNUnit(int? n, int? d)
{
return n / d;
}
[TestCase(2, 2, ExpectedResult = 4)]
public double? CanConvertIntToNullableDouble(double? x, double? y)
{
return x + y;
}
[TestCase(1)]
public void CanConvertIntToNullableShort(short? x)
{
Assert.That(x.HasValue);
Assert.That(x.Value, Is.EqualTo(1));
}
[TestCase(1)]
public void CanConvertIntToNullableByte(byte? x)
{
Assert.That(x.HasValue);
Assert.That(x.Value, Is.EqualTo(1));
}
[TestCase(1)]
public void CanConvertIntToNullableSByte(sbyte? x)
{
Assert.That(x.HasValue);
Assert.That(x.Value, Is.EqualTo(1));
}
[TestCase("2.2", "3.3", ExpectedResult = 5.5)]
public decimal? CanConvertStringToNullableDecimal(decimal? x, decimal? y)
{
Assert.That(x.HasValue);
Assert.That(y.HasValue);
return x.Value + y.Value;
}
[TestCase(null)]
public void SupportsNullableDecimal(decimal? x)
{
Assert.That(x.HasValue, Is.False);
}
[TestCase(2.2, 3.3, ExpectedResult = 5.5)]
public decimal? CanConvertDoubleToNullableDecimal(decimal? x, decimal? y)
{
return x + y;
}
[TestCase(5, 2, ExpectedResult = 7)]
public decimal? CanConvertIntToNullableDecimal(decimal? x, decimal? y)
{
return x + y;
}
[TestCase(5, 2, ExpectedResult = 7)]
public short? CanConvertSmallIntsToNullableShort(short? x, short? y)
{
return (short)(x + y);
}
[TestCase(5, 2, ExpectedResult = 7)]
public byte? CanConvertSmallIntsToNullableByte(byte? x, byte? y)
{
return (byte)(x + y);
}
[TestCase(5, 2, ExpectedResult = 7)]
public sbyte? CanConvertSmallIntsToNullableSByte(sbyte? x, sbyte? y)
{
return (sbyte)(x + y);
}
[TestCase("12-October-1942")]
public void CanConvertStringToNullableDateTime(DateTime? dt)
{
Assert.That(dt.HasValue);
Assert.AreEqual(1942, dt.Value.Year);
}
[TestCase(null)]
public void SupportsNullableDateTime(DateTime? dt)
{
Assert.That(dt.HasValue, Is.False);
}
[TestCase("4:44:15")]
public void CanConvertStringToNullableTimeSpan(TimeSpan? ts)
{
Assert.That(ts.HasValue);
Assert.AreEqual(4, ts.Value.Hours);
Assert.AreEqual(44, ts.Value.Minutes);
Assert.AreEqual(15, ts.Value.Seconds);
}
[TestCase(null)]
public void SupportsNullableTimeSpan(TimeSpan? dt)
{
Assert.That(dt.HasValue, Is.False);
}
[TestCase(1)]
public void NullableSimpleFormalParametersWithArgument(int? a)
{
Assert.AreEqual(1, a);
}
[TestCase(null)]
public void NullableSimpleFormalParametersWithNullArgument(int? a)
{
Assert.IsNull(a);
}
[TestCase(null, ExpectedResult = null)]
[TestCase(1, ExpectedResult = 1)]
public int? TestCaseWithNullableReturnValue(int? a)
{
return a;
}
#endregion
}
}
| |
// Copyright 2004-2009 Castle Project - http://www.castleproject.org/
//
// 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 CastleProjectHooks.Tests
{
using System;
using System.Text.RegularExpressions;
using NUnit.Framework;
using Castle.SvnHooks;
using Castle.SvnHooks.CastleProject;
/// <summary>
/// Summary description for PreCommitSourceHeaderTestCase.
/// </summary>
[TestFixture] public class PreCommitSourceHeaderTestCase
{
private const String HEADER =
"// Copyright 2004-2009 Castle Project - http://www.castleproject.org/\n" +
"// \n" +
"// Licensed under the Apache License, Version 2.0 (the \"License\");\n" +
"// you may not use this file except in compliance with the License.\n" +
"// You may obtain a copy of the License at\n" +
"// \n" +
"// http://www.apache.org/licenses/LICENSE-2.0\n" +
"// \n" +
"// Unless required by applicable law or agreed to in writing, software\n" +
"// distributed under the License is distributed on an \"AS IS\" BASIS,\n" +
"// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n" +
"// See the License for the specific language governing permissions and\n" +
"// limitations under the License.\n";
IPreCommit hook;
#region Setup / Teardown
[TestFixtureSetUp] public void FixtureSetUp()
{
hook = new PreCommitSourceHeader("cs");
}
#endregion
[Test] public void OnlyHeader()
{
AssertNoErrors(HEADER);
}
[Test] public void StartsWithHeader()
{
String contents = HEADER + '\n' +
"\n" +
"namespace Testing\n" +
"{\n" +
" using System;\n" +
" public class Test\n" +
" {\n"+
" }\n"+
"}";
AssertNoErrors(contents);
}
[Test] public void LeadingBlankRows()
{
String contents =
'\n' +
" \n" +
"\t\t\t\n" +
HEADER;
AssertNoErrors(contents);
}
[Test] public void ExtraLeadingAndTrailingWhiteSpace()
{
String contents = Regex.Replace(HEADER, "^//", " \t //").Replace("\n", " \t \n");
AssertNoErrors(contents);
}
[Test] public void ExtraWhiteSpaceInHeader()
{
String contents = HEADER.Replace(" ", " \t ");
AssertNoErrors(contents);
}
[Test] public void ExtraLineFeedsInHeader()
{
String contents = HEADER.Replace("\n", "\n\n");
AssertErrors(contents, 1,
"Blank lines are not allowed in the Apache License 2.0 header");
}
[Test] public void UsingBeforeHeader()
{
String contents =
"using System;\n" +
"\n" +
HEADER;
AssertErrors(contents, 1,
"No text or code is allowed before the Apache License 2.0 header");
}
[Test] public void MalformedHeader()
{
String contents = HEADER.Replace("www.apache.org", "www.microsoft.com");
AssertErrors(contents, 1,
"Apache License 2.0 header has errors on line 7");
}
[Test] public void MalformedHeaderMultipleRows()
{
String contents = HEADER.Replace("f", "?");
AssertErrors(contents, 4,
"Apache License 2.0 header has errors on line 4",
"Apache License 2.0 header has errors on line 5",
"Apache License 2.0 header has errors on line 9",
"Apache License 2.0 header has errors on line 12");
}
[Test] public void MalformedFirstLineHeader()
{
String contents = HEADER.Replace("Castle Project - http://www.castleproject.org/", "Me!");
AssertErrors(contents, 1,
"Apache License 2.0 header is missing or there are errors on the first line");
}
[Test] public void EmptyFile()
{
AssertErrors(String.Empty, 1,
"Apache License 2.0 header is missing or there are errors on the first line");
}
[Test] public void FileWithoutHeader()
{
String contents = "using System;\n" +
"\n" +
"namespace Testing\n" +
"{\n" +
" using System;\n" +
" public class Test\n" +
" {\n"+
" }\n"+
"}";
AssertErrors(contents, 1,
"Apache License 2.0 header is missing or there are errors on the first line");
}
[Test] public void UncheckedExtension()
{
AssertNoErrors(String.Empty, "trunk/file.txt");
}
[Test] public void Deleted()
{
using(RepositoryFile file = new RepositoryFile(new MockRepository(String.Empty), "File.cs", RepositoryStatus.Deleted, RepositoryStatus.Unchanged))
{
Error[] errors = hook.PreCommit(file);
Assert.AreEqual(0, errors.Length);
}
}
[Test] public void AssemblyInfo()
{
AssertNoErrors(String.Empty, "trunk/AssemblyInfo.cs");
}
private void AssertNoErrors(String contents, String fileName)
{
using(RepositoryFile file = MockRepository.GetFile(contents, fileName))
{
Error[] errors = hook.PreCommit(file);
Assert.AreEqual(0, errors.Length);
}
}
private void AssertNoErrors(String contents)
{
AssertNoErrors(contents, "trunk/File.cs");
}
private void AssertErrors(String contents, int count, params String[] messages)
{
using(RepositoryFile file = MockRepository.GetFile(contents, "trunk/File.cs"))
{
Error[] errors = hook.PreCommit(file);
Assert.AreEqual(count, errors.Length);
for(int i = 0; i < count; i++)
{
Assert.AreEqual(messages[i], errors[i].Description);
Assert.AreEqual(file, errors[i].File);
}
}
}
private class MockRepository : IRepository
{
public MockRepository(String contents)
{
if (contents == null)
throw new ArgumentNullException("contents");
this.Contents = contents;
}
public static RepositoryFile GetFile(String contents, String fileName)
{
return new RepositoryFile(new MockRepository(contents), fileName, RepositoryStatus.Unchanged, RepositoryStatus.Unchanged);
}
#region IRepository Members
public string[] GetProperty(string path, string property)
{
// TODO: Add MockRepository.GetProperty implementation
return null;
}
public System.IO.Stream GetFileContents(string path)
{
return new System.IO.MemoryStream(System.Text.Encoding.ASCII.GetBytes(Contents), false);
}
#endregion
private readonly String Contents;
}
}
}
| |
using J2N.Text;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using JCG = J2N.Collections.Generic;
/*
* dk.brics.automaton
*
* Copyright (c) 2001-2009 Anders Moeller
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* this SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* this SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
namespace Lucene.Net.Util.Automaton
{
using Util = Lucene.Net.Util.Fst.Util;
/// <summary>
/// Special automata operations.
/// <para/>
/// @lucene.experimental
/// </summary>
public static class SpecialOperations // LUCENENET specific - made static since all members are static
{
/// <summary>
/// Finds the largest entry whose value is less than or equal to <paramref name="c"/>, or 0 if
/// there is no such entry.
/// </summary>
internal static int FindIndex(int c, int[] points)
{
int a = 0;
int b = points.Length;
while (b - a > 1)
{
int d = (int)((uint)(a + b) >> 1);
if (points[d] > c)
{
b = d;
}
else if (points[d] < c)
{
a = d;
}
else
{
return d;
}
}
return a;
}
/// <summary>
/// Returns <c>true</c> if the language of this automaton is finite.
/// </summary>
public static bool IsFinite(Automaton a)
{
if (a.IsSingleton)
{
return true;
}
return IsFinite(a.initial, new OpenBitSet(a.GetNumberOfStates()), new OpenBitSet(a.GetNumberOfStates()));
}
/// <summary>
/// Checks whether there is a loop containing <paramref name="s"/>. (This is sufficient since
/// there are never transitions to dead states.)
/// </summary>
// TODO: not great that this is recursive... in theory a
// large automata could exceed java's stack
private static bool IsFinite(State s, OpenBitSet path, OpenBitSet visited)
{
path.Set(s.number);
foreach (Transition t in s.GetTransitions())
{
if (path.Get(t.to.number) || (!visited.Get(t.to.number) && !IsFinite(t.to, path, visited)))
{
return false;
}
}
path.Clear(s.number);
visited.Set(s.number);
return true;
}
/// <summary>
/// Returns the longest string that is a prefix of all accepted strings and
/// visits each state at most once.
/// </summary>
/// <returns> Common prefix. </returns>
public static string GetCommonPrefix(Automaton a)
{
if (a.IsSingleton)
{
return a.singleton;
}
StringBuilder b = new StringBuilder();
JCG.HashSet<State> visited = new JCG.HashSet<State>();
State s = a.initial;
bool done;
do
{
done = true;
visited.Add(s);
if (!s.accept && s.NumTransitions == 1)
{
Transition t = s.GetTransitions().First();
if (t.min == t.max && !visited.Contains(t.to))
{
b.AppendCodePoint(t.min);
s = t.to;
done = false;
}
}
} while (!done);
return b.ToString();
}
// TODO: this currently requites a determinized machine,
// but it need not -- we can speed it up by walking the
// NFA instead. it'd still be fail fast.
public static BytesRef GetCommonPrefixBytesRef(Automaton a)
{
if (a.IsSingleton)
{
return new BytesRef(a.singleton);
}
BytesRef @ref = new BytesRef(10);
JCG.HashSet<State> visited = new JCG.HashSet<State>();
State s = a.initial;
bool done;
do
{
done = true;
visited.Add(s);
if (!s.accept && s.NumTransitions == 1)
{
Transition t = s.GetTransitions().First();
if (t.min == t.max && !visited.Contains(t.to))
{
@ref.Grow(++@ref.Length);
@ref.Bytes[@ref.Length - 1] = (byte)t.min;
s = t.to;
done = false;
}
}
} while (!done);
return @ref;
}
/// <summary>
/// Returns the longest string that is a suffix of all accepted strings and
/// visits each state at most once.
/// </summary>
/// <returns> Common suffix. </returns>
public static string GetCommonSuffix(Automaton a)
{
if (a.IsSingleton) // if singleton, the suffix is the string itself.
{
return a.singleton;
}
// reverse the language of the automaton, then reverse its common prefix.
Automaton r = (Automaton)a.Clone();
Reverse(r);
r.Determinize();
return (new StringBuilder(SpecialOperations.GetCommonPrefix(r))).Reverse().ToString();
}
public static BytesRef GetCommonSuffixBytesRef(Automaton a)
{
if (a.IsSingleton) // if singleton, the suffix is the string itself.
{
return new BytesRef(a.singleton);
}
// reverse the language of the automaton, then reverse its common prefix.
Automaton r = (Automaton)a.Clone();
Reverse(r);
r.Determinize();
BytesRef @ref = SpecialOperations.GetCommonPrefixBytesRef(r);
ReverseBytes(@ref);
return @ref;
}
private static void ReverseBytes(BytesRef @ref)
{
if (@ref.Length <= 1)
{
return;
}
int num = @ref.Length >> 1;
for (int i = @ref.Offset; i < (@ref.Offset + num); i++)
{
var b = @ref.Bytes[i];
@ref.Bytes[i] = @ref.Bytes[@ref.Offset * 2 + @ref.Length - i - 1];
@ref.Bytes[@ref.Offset * 2 + @ref.Length - i - 1] = b;
}
}
/// <summary>
/// Reverses the language of the given (non-singleton) automaton while returning
/// the set of new initial states.
/// </summary>
public static ISet<State> Reverse(Automaton a)
{
a.ExpandSingleton();
// reverse all edges
Dictionary<State, ISet<Transition>> m = new Dictionary<State, ISet<Transition>>();
State[] states = a.GetNumberedStates();
ISet<State> accept = new JCG.HashSet<State>();
foreach (State s in states)
{
if (s.Accept)
{
accept.Add(s);
}
}
foreach (State r in states)
{
m[r] = new JCG.HashSet<Transition>();
r.accept = false;
}
foreach (State r in states)
{
foreach (Transition t in r.GetTransitions())
{
m[t.to].Add(new Transition(t.min, t.max, r));
}
}
foreach (State r in states)
{
ISet<Transition> tr = m[r];
r.SetTransitions(tr.ToArray(/*new Transition[tr.Count]*/));
}
// make new initial+final states
a.initial.accept = true;
a.initial = new State();
foreach (State r in accept)
{
a.initial.AddEpsilon(r); // ensures that all initial states are reachable
}
a.deterministic = false;
a.ClearNumberedStates();
return accept;
}
// TODO: this is a dangerous method ... Automaton could be
// huge ... and it's better in general for caller to
// enumerate & process in a single walk:
/// <summary>
/// Returns the set of accepted strings, assuming that at most
/// <paramref name="limit"/> strings are accepted. If more than <paramref name="limit"/>
/// strings are accepted, the first limit strings found are returned. If <paramref name="limit"/><0, then
/// the limit is infinite.
/// </summary>
public static ISet<Int32sRef> GetFiniteStrings(Automaton a, int limit)
{
JCG.HashSet<Int32sRef> strings = new JCG.HashSet<Int32sRef>();
if (a.IsSingleton)
{
if (limit > 0)
{
strings.Add(Util.ToUTF32(a.Singleton, new Int32sRef()));
}
}
else if (!GetFiniteStrings(a.initial, new JCG.HashSet<State>(), strings, new Int32sRef(), limit))
{
return strings;
}
return strings;
}
/// <summary>
/// Returns the strings that can be produced from the given state, or
/// <c>false</c> if more than <paramref name="limit"/> strings are found.
/// <paramref name="limit"/><0 means "infinite".
/// </summary>
private static bool GetFiniteStrings(State s, JCG.HashSet<State> pathstates, JCG.HashSet<Int32sRef> strings, Int32sRef path, int limit)
{
pathstates.Add(s);
foreach (Transition t in s.GetTransitions())
{
if (pathstates.Contains(t.to))
{
return false;
}
for (int n = t.min; n <= t.max; n++)
{
path.Grow(path.Length + 1);
path.Int32s[path.Length] = n;
path.Length++;
if (t.to.accept)
{
strings.Add(Int32sRef.DeepCopyOf(path));
if (limit >= 0 && strings.Count > limit)
{
return false;
}
}
if (!GetFiniteStrings(t.to, pathstates, strings, path, limit))
{
return false;
}
path.Length--;
}
}
pathstates.Remove(s);
return true;
}
}
}
| |
// Copyright (c) 2016-2018 SIL International
// This software is licensed under the MIT license (http://opensource.org/licenses/MIT)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using SIL.LCModel;
using SIL.LCModel.Core.KernelInterfaces;
namespace LfMerge.Core.DataConverters.CanonicalSources
{
public struct SemDomQuestion
{
public string Question;
public string ExampleWords; // Might be null if none found
public string ExampleSentences; // Might be null if none found
}
public class CanonicalSemanticDomainItem : CanonicalItem
{
// Get an <AUni ws="en"> type value
// or an <AStr ws="en"><Run ws="en"> type value as well.
// Will never return null. Returns an empty string if no text found.
private string GetStr(XmlReader reader, out string ws)
{
ws = string.Empty;
string result = string.Empty;
string name = reader.LocalName;
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
{
switch (reader.LocalName)
{
case "AUni":
case "Run":
ws = reader.GetAttribute("ws");
result = reader.ReadInnerXml();
break;
case "Uni":
result = reader.ReadInnerXml();
break;
}
}
break;
case XmlNodeType.EndElement:
if (reader.LocalName == name)
{
// Advance past closing element before returning
reader.Read();
return result ?? string.Empty;
}
break;
}
}
return result ?? string.Empty;
}
private SemDomQuestion GetQuestion(XmlReader reader, out string ws)
{
ws = string.Empty;
SemDomQuestion result = new SemDomQuestion();
if (reader.LocalName != "CmDomainQ")
return result; // If we weren't on the right kind of node, return empty SemDomQuestion
string name = reader.LocalName;
while (reader.Read())
{
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
{
switch (reader.LocalName)
{
case "Question":
result.Question = GetStr(reader, out ws);
break;
case "ExampleWords":
result.ExampleWords = GetStr(reader, out ws);
break;
case "ExampleSentences":
result.ExampleSentences = GetStr(reader, out ws);
break;
}
}
break;
case XmlNodeType.EndElement:
if (reader.LocalName == "CmDomainQ")
{
// Advance past closing element before returning
reader.Read();
return result;
}
break;
}
}
}
return result;
}
public override void PopulateFromXml(XmlReader reader)
{
if (reader.LocalName != "CmSemanticDomain")
return; // If we weren't on the right kind of node, do nothing
GuidStr = reader.GetAttribute("guid");
string ws = string.Empty; // Used as the out param in GetStr()
// Note that if the writing systems in the SemDom.xml file are inconsistent, then
// using a single out parameter everywhere may create inconsistent results. If we
// ever need to parse a SemDom.xml with multiple writing systems in it, we might
// have to change how we handle the "out ws" parameters in this function.
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
{
switch (reader.LocalName)
{
case "CmSemanticDomain":
var child = new CanonicalSemanticDomainItem();
child.PopulateFromXml(reader);
AppendChild(child);
break;
case "Abbreviation":
string abbrev = GetStr(reader, out ws);
AddAbbrev(ws, abbrev);
break;
case "Name":
string name = GetStr(reader, out ws);
AddName(ws, name);
break;
case "Description":
string desc = GetStr(reader, out ws);
AddDescription(ws, desc);
break;
case "OcmCodes":
List<string> ocmCodes = GetExtraDataList<string>("OcmCodes");
string ocmCodesText = GetStr(reader, out ws);
ocmCodes.AddRange(ocmCodesText.Split(new string[] { "; " }, StringSplitOptions.None));
break;
case "LouwNidaCodes":
List<string> louwNidaCodes = GetExtraDataList<string>("OcmCodes");
string louwNidaCodesText = GetStr(reader, out ws);
louwNidaCodes.AddRange(louwNidaCodesText.Split(new string[] { "; " }, StringSplitOptions.None));
break;
case "CmDomainQ":
Dictionary<string, List<SemDomQuestion>> questionsDict = GetExtraDataWsDict<SemDomQuestion>("Questions");
SemDomQuestion question = GetQuestion(reader, out ws);
List<SemDomQuestion> questions = GetListFromDict<SemDomQuestion>(questionsDict, ws);
questions.Add(question);
break;
}
break;
}
case XmlNodeType.EndElement:
{
if (reader.LocalName == "CmSemanticDomain")
{
Key = AbbrevByWs(KeyWs);
reader.Read(); // Skip past the closing element before returning
return;
}
break;
}
}
}
}
protected override void PopulatePossibilityFromExtraData(ICmPossibility poss)
{
ICmSemanticDomain semdom = poss as ICmSemanticDomain;
if (semdom == null)
return;
ILgWritingSystemFactory wsf = semdom.Cache.WritingSystemFactory;
var questionFactory = semdom.Cache.ServiceLocator.GetInstance<ICmDomainQFactory>();
Dictionary<string, List<SemDomQuestion>> questionsByWs = GetExtraDataWsDict<SemDomQuestion>("Questions");
// This dict looks like {"en": (question 1, question 2...)} but each question object wants to get data that
// looks more or less like {"en": "the question in English", "fr": "la question en francais"}...
// So first we ensure that there are enough question objects available, and then we'll access them by index
// as we step through the writing systems.
int numQuestions = questionsByWs.Values.Select(questionList => questionList.Count).Max();
while (semdom.QuestionsOS.Count < numQuestions)
{
semdom.QuestionsOS.Add(questionFactory.Create());
}
foreach (string ws in questionsByWs.Keys)
{
int wsId = wsf.GetWsFromStr(ws);
int i = 0;
foreach (SemDomQuestion qStruct in questionsByWs[ws])
{
// TODO: Find out what set_String() would do with a null value. Would it remove the string?
// If it would *remove* it, then we might be able to replace string.Empty with nulls in the code below
// Right now, just be extra-cautious and ensure we never put nulls into set_String().
semdom.QuestionsOS[i].Question.set_String(wsId, qStruct.Question ?? string.Empty);
semdom.QuestionsOS[i].ExampleSentences.set_String(wsId, qStruct.ExampleSentences ?? string.Empty);
semdom.QuestionsOS[i].ExampleWords.set_String(wsId, qStruct.ExampleWords ?? string.Empty);
i++;
}
}
}
}
}
| |
// 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.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
public static unsafe class DateTimeTests
{
[Fact]
public static void TestConstructors()
{
DateTime dt = new DateTime(2012, 6, 11);
ValidateYearMonthDay(dt, 2012, 6, 11);
dt = new DateTime(2012, 12, 31, 13, 50, 10);
ValidateYearMonthDay(dt, 2012, 12, 31, 13, 50, 10);
dt = new DateTime(1973, 10, 6, 14, 30, 0, 500);
ValidateYearMonthDay(dt, 1973, 10, 6, 14, 30, 0, 500);
dt = new DateTime(1986, 8, 15, 10, 20, 5, DateTimeKind.Local);
ValidateYearMonthDay(dt, 1986, 8, 15, 10, 20, 5);
}
[Fact]
public static void TestDateTimeLimits()
{
DateTime dt = DateTime.MaxValue;
ValidateYearMonthDay(dt, 9999, 12, 31);
dt = DateTime.MinValue;
ValidateYearMonthDay(dt, 1, 1, 1);
}
[Fact]
public static void TestLeapYears()
{
Assert.Equal(true, DateTime.IsLeapYear(2004));
Assert.Equal(false, DateTime.IsLeapYear(2005));
}
[Fact]
public static void TestAddition()
{
DateTime dt = new DateTime(1986, 8, 15, 10, 20, 5, 70);
Assert.Equal(17, dt.AddDays(2).Day);
Assert.Equal(13, dt.AddDays(-2).Day);
Assert.Equal(10, dt.AddMonths(2).Month);
Assert.Equal(6, dt.AddMonths(-2).Month);
Assert.Equal(1996, dt.AddYears(10).Year);
Assert.Equal(1976, dt.AddYears(-10).Year);
Assert.Equal(13, dt.AddHours(3).Hour);
Assert.Equal(7, dt.AddHours(-3).Hour);
Assert.Equal(25, dt.AddMinutes(5).Minute);
Assert.Equal(15, dt.AddMinutes(-5).Minute);
Assert.Equal(35, dt.AddSeconds(30).Second);
Assert.Equal(2, dt.AddSeconds(-3).Second);
Assert.Equal(80, dt.AddMilliseconds(10).Millisecond);
Assert.Equal(60, dt.AddMilliseconds(-10).Millisecond);
}
[Fact]
public static void TestDayOfWeek()
{
DateTime dt = new DateTime(2012, 6, 18);
Assert.Equal(DayOfWeek.Monday, dt.DayOfWeek);
}
[Fact]
public static void TestTimeSpan()
{
DateTime dt = new DateTime(2012, 6, 18, 10, 5, 1, 0);
TimeSpan ts = dt.TimeOfDay;
DateTime newDate = dt.Subtract(ts);
Assert.Equal(new DateTime(2012, 6, 18, 0, 0, 0, 0).Ticks, newDate.Ticks);
Assert.Equal(dt.Ticks, newDate.Add(ts).Ticks);
}
[Fact]
public static void TestToday()
{
DateTime today = DateTime.Today;
DateTime now = DateTime.Now;
ValidateYearMonthDay(today, now.Year, now.Month, now.Day);
today = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second, DateTimeKind.Utc);
Assert.Equal(DateTimeKind.Utc, today.Kind);
Assert.Equal(false, today.IsDaylightSavingTime());
}
[Fact]
public static void TestCoversion()
{
DateTime today = DateTime.Today;
long dateTimeRaw = today.ToBinary();
Assert.Equal(today, DateTime.FromBinary(dateTimeRaw));
dateTimeRaw = today.ToFileTime();
Assert.Equal(today, DateTime.FromFileTime(dateTimeRaw));
dateTimeRaw = today.ToFileTimeUtc();
Assert.Equal(today, DateTime.FromFileTimeUtc(dateTimeRaw).ToLocalTime());
}
[Fact]
public static void TestOperators()
{
System.DateTime date1 = new System.DateTime(1996, 6, 3, 22, 15, 0);
System.DateTime date2 = new System.DateTime(1996, 12, 6, 13, 2, 0);
System.DateTime date3 = new System.DateTime(1996, 10, 12, 8, 42, 0);
// diff1 gets 185 days, 14 hours, and 47 minutes.
System.TimeSpan diff1 = date2.Subtract(date1);
Assert.Equal(new TimeSpan(185, 14, 47, 0), diff1);
// date4 gets 4/9/1996 5:55:00 PM.
System.DateTime date4 = date3.Subtract(diff1);
Assert.Equal(new DateTime(1996, 4, 9, 17, 55, 0), date4);
// diff2 gets 55 days 4 hours and 20 minutes.
System.TimeSpan diff2 = date2 - date3;
Assert.Equal(new TimeSpan(55, 4, 20, 0), diff2);
// date5 gets 4/9/1996 5:55:00 PM.
System.DateTime date5 = date1 - diff2;
Assert.Equal(new DateTime(1996, 4, 9, 17, 55, 0), date5);
}
[Fact]
public static void TestParsingDateTimeWithTimeDesignator()
{
DateTime result;
Assert.True(DateTime.TryParse("4/21 5am", new CultureInfo("en-US"), DateTimeStyles.None, out result));
Assert.Equal(4, result.Month);
Assert.Equal(21, result.Day);
Assert.Equal(5, result.Hour);
Assert.True(DateTime.TryParse("4/21 5pm", new CultureInfo("en-US"), DateTimeStyles.None, out result));
Assert.Equal(4, result.Month);
Assert.Equal(21, result.Day);
Assert.Equal(17, result.Hour);
}
public class MyFormater : IFormatProvider
{
public object GetFormat(Type formatType)
{
if (typeof(IFormatProvider) == formatType)
{
return this;
}
else
{
return null;
}
}
}
[Fact]
public static void TestParseWithAdjustToUniversal()
{
var formater = new MyFormater();
var dateBefore = DateTime.Now.ToString();
var dateAfter = DateTime.ParseExact(dateBefore, "G", formater, DateTimeStyles.AdjustToUniversal);
Assert.Equal(dateBefore, dateAfter.ToString());
}
[Fact]
public static void TestFormatParse()
{
DateTime dt = new DateTime(2012, 12, 21, 10, 8, 6);
CultureInfo ci = new CultureInfo("ja-JP");
string s = string.Format(ci, "{0}", dt);
Assert.Equal(dt, DateTime.Parse(s, ci));
}
[Fact]
public static void TestParse1()
{
DateTime src = DateTime.MaxValue;
String s = src.ToString();
DateTime in_1 = DateTime.Parse(s);
String actual = in_1.ToString();
Assert.Equal(s, actual);
}
[Fact]
public static void TestParse2()
{
DateTime src = DateTime.MaxValue;
String s = src.ToString();
DateTime in_1 = DateTime.Parse(s, null);
String actual = in_1.ToString();
Assert.Equal(s, actual);
}
[Fact]
public static void TestParse3()
{
DateTime src = DateTime.MaxValue;
String s = src.ToString();
DateTime in_1 = DateTime.Parse(s, null, DateTimeStyles.None);
String actual = in_1.ToString();
Assert.Equal(s, actual);
}
[Fact]
public static void TestParseExact3()
{
DateTime src = DateTime.MaxValue;
String s = src.ToString("g");
DateTime in_1 = DateTime.ParseExact(s, "g", null);
String actual = in_1.ToString("g");
Assert.Equal(s, actual);
}
[Fact]
public static void TestParseExact4()
{
DateTime src = DateTime.MaxValue;
String s = src.ToString("g");
DateTime in_1 = DateTime.ParseExact(s, "g", null, DateTimeStyles.None);
String actual = in_1.ToString("g");
Assert.Equal(s, actual);
}
[Fact]
public static void TestParseExact4a()
{
DateTime src = DateTime.MaxValue;
String s = src.ToString("g");
String[] formats = { "g" };
DateTime in_1 = DateTime.ParseExact(s, formats, null, DateTimeStyles.None);
String actual = in_1.ToString("g");
Assert.Equal(s, actual);
}
[Fact]
public static void TestTryParse2()
{
DateTime src = DateTime.MaxValue;
String s = src.ToString("g");
DateTime in_1;
bool b = DateTime.TryParse(s, out in_1);
Assert.True(b);
String actual = in_1.ToString("g");
Assert.Equal(s, actual);
}
[Fact]
public static void TestTryParse4()
{
DateTime src = DateTime.MaxValue;
String s = src.ToString("g");
DateTime in_1;
bool b = DateTime.TryParse(s, null, DateTimeStyles.None, out in_1);
Assert.True(b);
String actual = in_1.ToString("g");
Assert.Equal(s, actual);
}
[Fact]
public static void TestTryParseExact()
{
DateTime src = DateTime.MaxValue;
String s = src.ToString("g");
DateTime in_1;
bool b = DateTime.TryParseExact(s, "g", null, DateTimeStyles.None, out in_1);
Assert.True(b);
String actual = in_1.ToString("g");
Assert.Equal(s, actual);
}
[Fact]
public static void TestTryParseExactA()
{
DateTime src = DateTime.MaxValue;
String s = src.ToString("g");
String[] formats = { "g" };
DateTime in_1;
bool b = DateTime.TryParseExact(s, formats, null, DateTimeStyles.None, out in_1);
Assert.True(b);
String actual = in_1.ToString("g");
Assert.Equal(s, actual);
}
[Fact]
public static void TestGetDateTimeFormats()
{
char[] allStandardFormats =
{
'd', 'D', 'f', 'F', 'g', 'G',
'm', 'M', 'o', 'O', 'r', 'R',
's', 't', 'T', 'u', 'U', 'y', 'Y',
};
DateTime july28 = new DateTime(2009, 7, 28, 5, 23, 15);
List<string> july28Formats = new List<string>();
foreach (char format in allStandardFormats)
{
string[] dates = july28.GetDateTimeFormats(format);
Assert.True(dates.Length > 0);
DateTime parsedDate;
Assert.True(DateTime.TryParseExact(dates[0], format.ToString(), CultureInfo.CurrentCulture, DateTimeStyles.None, out parsedDate));
july28Formats.AddRange(dates);
}
List<string> actualJuly28Formats = july28.GetDateTimeFormats().ToList();
Assert.Equal(july28Formats.OrderBy(t => t), actualJuly28Formats.OrderBy(t => t));
actualJuly28Formats = july28.GetDateTimeFormats(CultureInfo.CurrentCulture).ToList();
Assert.Equal(july28Formats.OrderBy(t => t), actualJuly28Formats.OrderBy(t => t));
}
[Theory]
[InlineData("fi-FI")]
[InlineData("nb-NO")]
[InlineData("nb-SJ")]
[InlineData("sr-Cyrl-XK")]
[InlineData("sr-Latn-ME")]
[InlineData("sr-Latn-RS")]
[InlineData("sr-Latn-XK")]
[ActiveIssue(3391, PlatformID.AnyUnix)]
public static void TestDateTimeParsingWithSpecialCultures(string cultureName)
{
// Test DateTime parsing with cultures which has the date separator and time separator are same
CultureInfo ci;
try
{
ci = new CultureInfo(cultureName);
}
catch (CultureNotFoundException)
{
// ignore un-supported culture in current platform
return;
}
DateTime date = DateTime.Now;
// truncate the milliseconds as it is not showing in time formatting patterns
date = new DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second);
string dateString = date.ToString(ci.DateTimeFormat.ShortDatePattern, ci);
DateTime parsedDate;
Assert.True(DateTime.TryParse(dateString, ci, DateTimeStyles.None, out parsedDate));
Assert.Equal(date.Date, parsedDate);
dateString = date.ToString(ci.DateTimeFormat.LongDatePattern, ci);
Assert.True(DateTime.TryParse(dateString, ci, DateTimeStyles.None, out parsedDate));
Assert.Equal(date.Date, parsedDate);
dateString = date.ToString(ci.DateTimeFormat.FullDateTimePattern, ci);
Assert.True(DateTime.TryParse(dateString, ci, DateTimeStyles.None, out parsedDate));
Assert.Equal(date, parsedDate);
dateString = date.ToString(ci.DateTimeFormat.LongTimePattern, ci);
Assert.True(DateTime.TryParse(dateString, ci, DateTimeStyles.None, out parsedDate));
Assert.Equal(date.TimeOfDay, parsedDate.TimeOfDay);
}
[Fact]
public static void TestGetDateTimeFormats_FormatSpecifier_InvalidFormat()
{
DateTime july28 = new DateTime(2009, 7, 28, 5, 23, 15);
Assert.Throws<FormatException>(() => july28.GetDateTimeFormats('x'));
}
internal static void ValidateYearMonthDay(DateTime dt, int year, int month, int day)
{
Assert.Equal(dt.Year, year);
Assert.Equal(dt.Month, month);
Assert.Equal(dt.Day, day);
}
internal static void ValidateYearMonthDay(DateTime dt, int year, int month, int day, int hour, int minute, int second)
{
ValidateYearMonthDay(dt, year, month, day);
Assert.Equal(dt.Hour, hour);
Assert.Equal(dt.Minute, minute);
Assert.Equal(dt.Second, second);
}
internal static void ValidateYearMonthDay(DateTime dt, int year, int month, int day, int hour, int minute, int second, int millisecond)
{
ValidateYearMonthDay(dt, year, month, day, hour, minute, second);
Assert.Equal(dt.Millisecond, millisecond);
}
}
| |
// 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.Runtime.InteropServices;
using Xunit;
namespace System.IO.Tests
{
public class Directory_GetFileSystemEntries_str_str : Directory_GetFileSystemEntries_str
{
#region Utilities
public override string[] GetEntries(string dirName)
{
return Directory.GetFileSystemEntries(dirName, "*");
}
public virtual string[] GetEntries(string dirName, string searchPattern)
{
return Directory.GetFileSystemEntries(dirName, searchPattern);
}
#endregion
#region UniversalTests
[Fact]
public void SearchPatternNull()
{
Assert.Throws<ArgumentNullException>(() => GetEntries(TestDirectory, null));
}
[Fact]
public void SearchPatternEmpty()
{
// To avoid OS differences we have decided not to throw an argument exception when empty
// string passed. But we should return 0 items.
Assert.Empty(GetEntries(TestDirectory, string.Empty));
}
[Fact]
public void SearchPatternValid()
{
Assert.Empty(GetEntries(TestDirectory, "a..b abc..d")); //Should not throw
}
[Fact]
public void SearchPatternDotIsStar()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
testDir.CreateSubdirectory("TestDir1");
testDir.CreateSubdirectory("TestDir2");
using (File.Create(Path.Combine(testDir.FullName, "TestFile1")))
using (File.Create(Path.Combine(testDir.FullName, "TestFile2")))
{
string[] strArr = GetEntries(testDir.FullName, ".");
if (TestFiles)
{
Assert.Contains(Path.Combine(testDir.FullName, "TestFile1"), strArr);
Assert.Contains(Path.Combine(testDir.FullName, "TestFile2"), strArr);
}
if (TestDirectories)
{
Assert.Contains(Path.Combine(testDir.FullName, "TestDir1"), strArr);
Assert.Contains(Path.Combine(testDir.FullName, "TestDir2"), strArr);
}
}
}
[Fact]
public void SearchPatternWithTrailingStar()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
testDir.CreateSubdirectory("TestDir1");
testDir.CreateSubdirectory("TestDir2");
testDir.CreateSubdirectory("TestDir3");
using (File.Create(Path.Combine(testDir.FullName, "TestFile1")))
using (File.Create(Path.Combine(testDir.FullName, "TestFile2")))
using (File.Create(Path.Combine(testDir.FullName, "Test1File2")))
using (File.Create(Path.Combine(testDir.FullName, "Test1Dir2")))
{
string[] strArr = GetEntries(testDir.FullName, "Test1*");
if (TestFiles)
{
Assert.Contains(Path.Combine(testDir.FullName, "Test1File2"), strArr);
Assert.Contains(Path.Combine(testDir.FullName, "Test1Dir2"), strArr);
}
strArr = GetEntries(testDir.FullName, "*");
if (TestFiles)
{
Assert.Contains(Path.Combine(testDir.FullName, "TestFile1"), strArr);
Assert.Contains(Path.Combine(testDir.FullName, "TestFile2"), strArr);
Assert.Contains(Path.Combine(testDir.FullName, "Test1File2"), strArr);
Assert.Contains(Path.Combine(testDir.FullName, "Test1Dir2"), strArr);
}
if (TestDirectories)
{
Assert.Contains(Path.Combine(testDir.FullName, "TestDir1"), strArr);
Assert.Contains(Path.Combine(testDir.FullName, "TestDir2"), strArr);
Assert.Contains(Path.Combine(testDir.FullName, "TestDir3"), strArr);
}
}
}
[Fact]
public void SearchPatternWithLeadingStar()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
testDir.CreateSubdirectory("TestDir1");
testDir.CreateSubdirectory("TestDir2");
testDir.CreateSubdirectory("TestDir3");
using (File.Create(Path.Combine(testDir.FullName, "TestFile1")))
using (File.Create(Path.Combine(testDir.FullName, "TestFile2")))
using (File.Create(Path.Combine(testDir.FullName, "Test1File2")))
using (File.Create(Path.Combine(testDir.FullName, "Test1Dir2")))
{
string[] strArr = GetEntries(testDir.FullName, "*2");
if (TestFiles)
{
Assert.Contains(Path.Combine(testDir.FullName, "Test1Dir2"), strArr);
Assert.Contains(Path.Combine(testDir.FullName, "Test1File2"), strArr);
Assert.Contains(Path.Combine(testDir.FullName, "TestFile2"), strArr);
}
if (TestDirectories)
{
Assert.Contains(Path.Combine(testDir.FullName, "TestDir2"), strArr);
}
strArr = GetEntries(testDir.FullName, "*Dir*");
if (TestFiles)
{
Assert.Contains(Path.Combine(testDir.FullName, "Test1Dir2"), strArr);
}
if (TestDirectories)
{
Assert.Contains(Path.Combine(testDir.FullName, "TestDir1"), strArr);
Assert.Contains(Path.Combine(testDir.FullName, "TestDir2"), strArr);
Assert.Contains(Path.Combine(testDir.FullName, "TestDir3"), strArr);
}
}
}
[Fact]
public void SearchPatternByExtension()
{
if (TestFiles)
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
using (File.Create(Path.Combine(testDir.FullName, "TestFile1.txt")))
using (File.Create(Path.Combine(testDir.FullName, "TestFile2.xxt")))
using (File.Create(Path.Combine(testDir.FullName, "Test1File2.txt")))
using (File.Create(Path.Combine(testDir.FullName, "Test1Dir2.txx")))
{
string[] strArr = GetEntries(testDir.FullName, "*.txt");
Assert.Equal(2, strArr.Length);
Assert.Contains(Path.Combine(testDir.FullName, "TestFile1.txt"), strArr);
Assert.Contains(Path.Combine(testDir.FullName, "Test1File2.txt"), strArr);
}
}
}
[Fact]
public void SearchPatternExactMatch()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
Directory.CreateDirectory(Path.Combine(testDir.FullName, "AAA"));
Directory.CreateDirectory(Path.Combine(testDir.FullName, "AAAB"));
Directory.CreateDirectory(Path.Combine(testDir.FullName, "CAAA"));
using (File.Create(Path.Combine(testDir.FullName, "AAABB")))
using (File.Create(Path.Combine(testDir.FullName, "AAABBC")))
using (File.Create(Path.Combine(testDir.FullName, "CAAABB")))
{
if (TestFiles)
{
string[] results = GetEntries(testDir.FullName, "AAABB");
Assert.Equal(1, results.Length);
Assert.Contains(Path.Combine(testDir.FullName, "AAABB"), results);
}
if (TestDirectories)
{
string[] results = GetEntries(testDir.FullName, "AAA");
Assert.Equal(1, results.Length);
Assert.Contains(Path.Combine(testDir.FullName, "AAA"), results);
}
}
}
[Fact]
public void SearchPatternIgnoreSubDirectories()
{
//Shouldn't get files on full path by default
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
Directory.CreateDirectory(Path.Combine(testDir.FullName, GetTestFileName()));
using (File.Create(Path.Combine(testDir.FullName, GetTestFileName())))
using (File.Create(Path.Combine(TestDirectory, GetTestFileName())))
{
string[] results = GetEntries(TestDirectory, Path.Combine(testDir.Name, "*"));
if (TestDirectories && TestFiles)
Assert.Equal(2, results.Length);
else
Assert.Equal(1, results.Length);
}
}
#endregion
#region PlatformSpecific
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Long path segment in search pattern throws PathTooLongException
public void WindowsSearchPatternLongSegment()
{
// Create a path segment longer than the normal max of 255
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
string longName = new string('k', 257);
Assert.Throws<PathTooLongException>(() => GetEntries(testDir.FullName, longName));
}
[ConditionalFact(nameof(AreAllLongPathsAvailable))]
[SkipOnTargetFramework(Tfm.BelowNet462 | Tfm.Core50, "long path support added in 4.6.2")]
public void SearchPatternLongPath()
{
// Create a destination path longer than the traditional Windows limit of 256 characters
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
string longName = new string('k', 254);
string longFullname = Path.Combine(testDir.FullName, longName);
if (TestFiles)
{
using (File.Create(longFullname)) { }
}
else
{
Directory.CreateDirectory(longFullname);
}
string[] results = GetEntries(testDir.FullName, longName);
Assert.Contains(longFullname, results);
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Search pattern with double dots throws ArgumentException
public void WindowsSearchPatternWithDoubleDots()
{
Assert.Throws<ArgumentException>(() => GetEntries(TestDirectory, Path.Combine("..ab ab.. .. abc..d", "abc..")));
Assert.Throws<ArgumentException>(() => GetEntries(TestDirectory, ".."));
Assert.Throws<ArgumentException>(() => GetEntries(TestDirectory, @".." + Path.DirectorySeparatorChar));
}
[ActiveIssue(11584)]
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Windows-invalid search patterns throw
public void WindowsSearchPatternInvalid()
{
Assert.Throws<ArgumentException>(() => GetEntries(TestDirectory, "\0"));
Assert.Throws<ArgumentException>(() => GetEntries(TestDirectory, ">"));
Char[] invalidFileNames = Path.GetInvalidFileNameChars();
for (int i = 0; i < invalidFileNames.Length; i++)
{
switch (invalidFileNames[i])
{
case '\\':
case '/':
Assert.Throws<DirectoryNotFoundException>(() => GetEntries(Directory.GetCurrentDirectory(), string.Format("te{0}st", invalidFileNames[i].ToString())));
break;
//We don't throw in V1 too
case ':':
//History:
// 1) we assumed that this will work in all non-9x machine
// 2) Then only in XP
// 3) NTFS?
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) &&
FileSystemDebugInfo.IsCurrentDriveNTFS()) // testing NTFS
{
Assert.Throws<IOException>(() => GetEntries(Directory.GetCurrentDirectory(), string.Format("te{0}st", invalidFileNames[i].ToString())));
}
else
{
GetEntries(Directory.GetCurrentDirectory(), string.Format("te{0}st", invalidFileNames[i].ToString()));
}
break;
case '*':
case '?':
GetEntries(Directory.GetCurrentDirectory(), string.Format("te{0}st", invalidFileNames[i].ToString()));
break;
default:
Assert.Throws<ArgumentException>(() => GetEntries(Directory.GetCurrentDirectory(), string.Format("te{0}st", invalidFileNames[i].ToString())));
break;
}
}
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Unix-invalid sarch patterns throw ArgumentException
public void UnixSearchPatternInvalid()
{
Assert.Throws<ArgumentException>(() => GetEntries(TestDirectory, "\0"));
Assert.Throws<ArgumentException>(() => GetEntries(TestDirectory, string.Format("te{0}st", "\0".ToString())));
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // ? in search pattern returns results
public virtual void WindowsSearchPatternQuestionMarks()
{
string testDir1Str = GetTestFileName();
DirectoryInfo testDir = new DirectoryInfo(TestDirectory);
DirectoryInfo testDir1 = testDir.CreateSubdirectory(testDir1Str);
using (File.Create(Path.Combine(TestDirectory, testDir1Str, GetTestFileName())))
using (File.Create(Path.Combine(TestDirectory, GetTestFileName())))
{
string[] results = GetEntries(TestDirectory, string.Format("{0}.???", new string('?', GetTestFileName().Length)));
if (TestFiles && TestDirectories)
Assert.Equal(2, results.Length);
else
Assert.Equal(1, results.Length);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Whitespace in search pattern returns nothing
public void WindowsSearchPatternWhitespace()
{
Assert.Empty(GetEntries(TestDirectory, " "));
Assert.Empty(GetEntries(TestDirectory, "\n"));
Assert.Empty(GetEntries(TestDirectory, " "));
Assert.Empty(GetEntries(TestDirectory, "\t"));
}
[Fact]
[PlatformSpecific(CaseSensitivePlatforms)]
public void SearchPatternCaseSensitive()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
string testBase = GetTestFileName();
testDir.CreateSubdirectory(testBase + "aBBb");
testDir.CreateSubdirectory(testBase + "aBBB");
File.Create(Path.Combine(testDir.FullName, testBase + "AAAA")).Dispose();
File.Create(Path.Combine(testDir.FullName, testBase + "aAAa")).Dispose();
if (TestDirectories)
{
Assert.Equal(2, GetEntries(testDir.FullName, "*BB*").Length);
}
if (TestFiles)
{
Assert.Equal(2, GetEntries(testDir.FullName, "*AA*").Length);
}
}
[Fact]
[PlatformSpecific(CaseInsensitivePlatforms)]
public void SearchPatternCaseInsensitive()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
string testBase = GetTestFileName();
testDir.CreateSubdirectory(testBase + "aBBb");
testDir.CreateSubdirectory(testBase + "aBBB");
File.Create(Path.Combine(testDir.FullName, testBase + "AAAA")).Dispose();
File.Create(Path.Combine(testDir.FullName, testBase + "aAAa")).Dispose();
if (TestDirectories)
{
Assert.Equal(1, GetEntries(testDir.FullName, "*BB*").Length);
}
if (TestFiles)
{
Assert.Equal(1, GetEntries(testDir.FullName, "*AA*").Length);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Unix-valid chars in file search patterns
public void UnixSearchPatternFileValidChar()
{
if (TestFiles)
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
foreach (string valid in WindowsInvalidUnixValid)
File.Create(Path.Combine(testDir.FullName, valid)).Dispose();
foreach (string valid in WindowsInvalidUnixValid)
Assert.Contains(Path.Combine(testDir.FullName, valid), GetEntries(testDir.FullName, valid));
}
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Unix-valid chars in directory search patterns
public void UnixSearchPatternDirectoryValidChar()
{
if (TestDirectories)
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
foreach (string valid in WindowsInvalidUnixValid)
testDir.CreateSubdirectory(valid);
foreach (string valid in WindowsInvalidUnixValid)
Assert.Contains(Path.Combine(testDir.FullName, valid), GetEntries(testDir.FullName, valid));
}
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Search pattern with DoubleDots on Unix
public void UnixSearchPatternWithDoubleDots()
{
// search pattern is valid but directory doesn't exist
Assert.Throws<DirectoryNotFoundException>(() => GetEntries(TestDirectory, Path.Combine("..ab ab.. .. abc..d", "abc..")));
// invalid search pattern trying to go up a directory with ..
Assert.Throws<ArgumentException>(() => GetEntries(TestDirectory, ".."));
Assert.Throws<ArgumentException>(() => GetEntries(TestDirectory, @".." + Path.DirectorySeparatorChar));
Assert.Throws<ArgumentException>(() => GetEntries(TestDirectory, Path.Combine("..ab ab.. .. abc..d", "abc", "..")));
Assert.Throws<ArgumentException>(() => GetEntries(TestDirectory, Path.Combine("..ab ab.. .. abc..d", "..", "abc")));
Assert.Throws<ArgumentException>(() => GetEntries(TestDirectory, Path.Combine("..", "..ab ab.. .. abc..d", "abc")));
Assert.Throws<ArgumentException>(() => GetEntries(TestDirectory, Path.Combine("..", "..ab ab.. .. abc..d", "abc") + Path.DirectorySeparatorChar));
}
#endregion
}
}
| |
#region License
// Copyright (c) 2010-2019, Mark Final
// 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 BuildAMation nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion // License
using Bam.Core;
using System.Linq;
namespace boost
{
interface IConfigureBoost :
Bam.Core.IModuleConfiguration
{
bool EnableAutoLinking { get; }
}
sealed class ConfigureBoost :
IConfigureBoost
{
public ConfigureBoost(
Bam.Core.Environment buildEnvironment) => this.EnableAutoLinking = true;
public bool EnableAutoLinking { get; set; }
}
[Bam.Core.ModuleGroup("Thirdparty/Boost")]
abstract class GenericBoostModule :
C.Cxx.DynamicLibrary,
Bam.Core.IHasModuleConfiguration
{
global::System.Type Bam.Core.IHasModuleConfiguration.ReadOnlyInterfaceType => typeof(IConfigureBoost);
global::System.Type Bam.Core.IHasModuleConfiguration.WriteableClassType => typeof(ConfigureBoost);
protected GenericBoostModule(
string name) => this.Name = name;
private string Name { get; set; }
protected C.Cxx.ObjectFileCollection BoostSource { get; private set; }
protected C.HeaderFileCollection BoostHeaders { get; private set; }
protected override void
Init()
{
base.Init();
this.SetSemanticVersion(1, 6, 7);
if (this.BuildEnvironment.Platform.Includes(Bam.Core.EPlatform.Windows))
{
var visualC = Bam.Core.Graph.Instance.Packages.First(item => item.Name == "VisualC");
string vcVer = string.Empty;
if (visualC.Version == "16")
{
vcVer = "142";
}
else if (visualC.Version == "15.0")
{
vcVer = "141";
}
else if (visualC.Version == "14.0")
{
vcVer = "140";
}
else if (visualC.Version == "12.0")
{
vcVer = "120";
}
else if (visualC.Version == "11.0")
{
vcVer = "110";
}
else if (visualC.Version == "10.0")
{
vcVer = "100";
}
else
{
throw new Bam.Core.Exception($"Unsupported version of VisualC, {visualC.Version}");
}
this.Macros[Bam.Core.ModuleMacroNames.OutputName] = this.CreateTokenizedString(
string.Format("boost_{0}-vc{1}-$(boost_vc_mode)-{2}_{3}{4}",
this.Name,
vcVer,
this.Macros[C.ModuleMacroNames.MajorVersion].ToString(),
this.Macros[C.ModuleMacroNames.MinorVersion].ToString(),
this.Macros[C.ModuleMacroNames.PatchVersion].ToString()));
}
else if (this.BuildEnvironment.Platform.Includes(Bam.Core.EPlatform.Linux))
{
this.Macros[Bam.Core.ModuleMacroNames.OutputName] = TokenizedString.CreateVerbatim(string.Format("boost_{0}", this.Name));
}
else if (this.BuildEnvironment.Platform.Includes(Bam.Core.EPlatform.OSX))
{
this.Macros[Bam.Core.ModuleMacroNames.OutputName] = TokenizedString.CreateVerbatim(string.Format("boost_{0}", this.Name));
}
else
{
throw new Bam.Core.Exception("Invalid platform for Boost builds");
}
this.BoostHeaders = this.CreateHeaderCollection(string.Format("$(packagedir)/boost/{0}/**.hpp", this.Name));
this.BoostSource = this.CreateCxxSourceCollection();
this.BoostSource.ClosingPatch(settings =>
{
if (settings is VisualCCommon.ICommonCompilerSettings vcCompiler)
{
// boost_vc_mode is a macro used on the link step, so must use the encapsulating module of the source
// (since it depends on a compilation property)
var encapsulating = this.EncapsulatingModule;
if (vcCompiler.RuntimeLibrary == VisualCCommon.ERuntimeLibrary.MultiThreadedDebugDLL)
{
encapsulating.Macros["boost_vc_mode"] = TokenizedString.CreateVerbatim("mt-gd");
}
else
{
encapsulating.Macros["boost_vc_mode"] = TokenizedString.CreateVerbatim("mt");
}
}
});
this.PublicPatch((settings, appliedTo) =>
{
if (settings is C.ICommonPreprocessorSettings preprocessor)
{
preprocessor.SystemIncludePaths.AddUnique(this.CreateTokenizedString("$(packagedir)"));
var configuration = this.Configuration as IConfigureBoost;
if (!configuration.EnableAutoLinking)
{
preprocessor.PreprocessorDefines.Add("BOOST_ALL_NO_LIB");
}
preprocessor.PreprocessorDefines.Add("BOOST_ALL_DYN_LINK");
}
if (settings is GccCommon.ICommonCompilerSettings)
{
if (this.BoostSource.Compiler.Version.AtLeast(GccCommon.ToolchainVersion.GCC_8))
{
var compiler = settings as C.ICommonCompilerSettings;
compiler.DisableWarnings.AddUnique("parentheses");
}
}
});
this.BoostSource.PrivatePatch(settings =>
{
var cxxCompiler = settings as C.ICxxOnlyCompilerSettings;
cxxCompiler.LanguageStandard = C.Cxx.ELanguageStandard.Cxx11;
cxxCompiler.StandardLibrary = C.Cxx.EStandardLibrary.libcxx;
cxxCompiler.ExceptionHandler = C.Cxx.EExceptionHandler.Asynchronous;
if (settings is VisualCCommon.ICommonCompilerSettings vcCompiler)
{
vcCompiler.WarningLevel = VisualCCommon.EWarningLevel.Level4;
}
if (settings is GccCommon.ICommonCompilerSettings gccCompiler)
{
gccCompiler.AllWarnings = true;
gccCompiler.ExtraWarnings = true;
gccCompiler.Pedantic = true;
}
if (settings is ClangCommon.ICommonCompilerSettings clangCompiler)
{
clangCompiler.AllWarnings = true;
clangCompiler.ExtraWarnings = true;
clangCompiler.Pedantic = true;
}
});
this.PrivatePatch(settings =>
{
if (settings is C.ICxxOnlyLinkerSettings cxxLinker)
{
cxxLinker.StandardLibrary = C.Cxx.EStandardLibrary.libcxx;
}
});
}
}
}
| |
using System;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using System.Security.Permissions;
namespace Free.Controls.TreeView.Tree
{
[Serializable]
public sealed class TreeNodeAdv : ISerializable
{
#region NodeCollection
private class NodeCollection : Collection<TreeNodeAdv>
{
private TreeNodeAdv _owner;
public NodeCollection(TreeNodeAdv owner)
{
_owner=owner;
}
protected override void ClearItems()
{
while(this.Count!=0)
this.RemoveAt(this.Count-1);
}
protected override void InsertItem(int index, TreeNodeAdv item)
{
if(item==null)
throw new ArgumentNullException("item");
if(item.Parent!=_owner)
{
if(item.Parent!=null)
item.Parent.Nodes.Remove(item);
item._parent=_owner;
item._index=index;
for(int i=index; i<Count; i++)
this[i]._index++;
base.InsertItem(index, item);
}
if(_owner.Tree!=null&&_owner.Tree.Model==null)
{
_owner.Tree.SmartFullUpdate();
}
}
protected override void RemoveItem(int index)
{
TreeNodeAdv item=this[index];
item._parent=null;
item._index=-1;
for(int i=index+1; i<Count; i++)
this[i]._index--;
base.RemoveItem(index);
if(_owner.Tree!=null&&_owner.Tree.Model==null)
{
_owner.Tree.UpdateSelection();
_owner.Tree.SmartFullUpdate();
}
}
protected override void SetItem(int index, TreeNodeAdv item)
{
if(item==null)
throw new ArgumentNullException("item");
RemoveAt(index);
InsertItem(index, item);
}
}
#endregion
#region Events
public event EventHandler<TreeViewAdvEventArgs> Collapsing;
internal void OnCollapsing()
{
if(Collapsing!=null)
Collapsing(this, new TreeViewAdvEventArgs(this));
}
public event EventHandler<TreeViewAdvEventArgs> Collapsed;
internal void OnCollapsed()
{
if(Collapsed!=null)
Collapsed(this, new TreeViewAdvEventArgs(this));
}
public event EventHandler<TreeViewAdvEventArgs> Expanding;
internal void OnExpanding()
{
if(Expanding!=null)
Expanding(this, new TreeViewAdvEventArgs(this));
}
public event EventHandler<TreeViewAdvEventArgs> Expanded;
internal void OnExpanded()
{
if(Expanded!=null)
Expanded(this, new TreeViewAdvEventArgs(this));
}
#endregion
#region Properties
private TreeViewAdv _tree;
public TreeViewAdv Tree
{
get { return _tree; }
}
private int _row;
public int Row
{
get { return _row; }
internal set { _row=value; }
}
private int _index=-1;
public int Index
{
get
{
return _index;
}
}
private bool _isSelected;
public bool IsSelected
{
get { return _isSelected; }
set
{
if(_isSelected!=value)
{
if(Tree.IsMyNode(this))
{
//_tree.OnSelectionChanging
if(value)
{
if(!_tree.Selection.Contains(this))
_tree.Selection.Add(this);
if(_tree.Selection.Count==1)
_tree.CurrentNode=this;
}
else
_tree.Selection.Remove(this);
_tree.UpdateView();
_tree.OnSelectionChanged();
}
_isSelected=value;
}
}
}
/// <summary>
/// Returns true if all parent nodes of this node are expanded.
/// </summary>
internal bool IsVisible
{
get
{
TreeNodeAdv node=_parent;
while(node!=null)
{
if(!node.IsExpanded)
return false;
node=node.Parent;
}
return true;
}
}
private bool _isLeaf;
public bool IsLeaf
{
get { return _isLeaf; }
internal set { _isLeaf=value; }
}
private bool _isExpandedOnce;
public bool IsExpandedOnce
{
get { return _isExpandedOnce; }
internal set { _isExpandedOnce=value; }
}
private bool _isExpanded;
public bool IsExpanded
{
get { return _isExpanded; }
set
{
if(value)
Expand();
else
Collapse();
}
}
internal void AssignIsExpanded(bool value)
{
_isExpanded=value;
}
private TreeNodeAdv _parent;
public TreeNodeAdv Parent
{
get { return _parent; }
}
public int Level
{
get
{
if(_parent==null)
return 0;
else
return _parent.Level+1;
}
}
public TreeNodeAdv PreviousNode
{
get
{
if(_parent!=null)
{
int index=Index;
if(index>0)
return _parent.Nodes[index-1];
}
return null;
}
}
public TreeNodeAdv NextNode
{
get
{
if(_parent!=null)
{
int index=Index;
if(index<_parent.Nodes.Count-1)
return _parent.Nodes[index+1];
}
return null;
}
}
internal TreeNodeAdv BottomNode
{
get
{
TreeNodeAdv parent=this.Parent;
if(parent!=null)
{
if(parent.NextNode!=null)
return parent.NextNode;
else
return parent.BottomNode;
}
return null;
}
}
internal TreeNodeAdv NextVisibleNode
{
get
{
if(IsExpanded&&Nodes.Count>0)
return Nodes[0];
else
{
TreeNodeAdv nn=NextNode;
if(nn!=null)
return nn;
else
return BottomNode;
}
}
}
public bool CanExpand
{
get
{
return (Nodes.Count>0||(!IsExpandedOnce&&!IsLeaf));
}
}
private object _tag;
public object Tag
{
get { return _tag; }
}
private Collection<TreeNodeAdv> _nodes;
internal Collection<TreeNodeAdv> Nodes
{
get { return _nodes; }
}
private ReadOnlyCollection<TreeNodeAdv> _children;
public ReadOnlyCollection<TreeNodeAdv> Children
{
get
{
return _children;
}
}
private int? _rightBounds;
internal int? RightBounds
{
get { return _rightBounds; }
set { _rightBounds=value; }
}
private int? _height;
internal int? Height
{
get { return _height; }
set { _height=value; }
}
private bool _isExpandingNow;
internal bool IsExpandingNow
{
get { return _isExpandingNow; }
set { _isExpandingNow=value; }
}
private bool _autoExpandOnStructureChanged=false;
public bool AutoExpandOnStructureChanged
{
get { return _autoExpandOnStructureChanged; }
set { _autoExpandOnStructureChanged=value; }
}
#endregion
public TreeNodeAdv(object tag)
: this(null, tag)
{
}
internal TreeNodeAdv(TreeViewAdv tree, object tag)
{
_row=-1;
_tree=tree;
_nodes=new NodeCollection(this);
_children=new ReadOnlyCollection<TreeNodeAdv>(_nodes);
_tag=tag;
}
public override string ToString()
{
if(Tag!=null)
return Tag.ToString();
else
return base.ToString();
}
public void Collapse()
{
if(_isExpanded)
Collapse(true);
}
public void CollapseAll()
{
Collapse(false);
}
public void Collapse(bool ignoreChildren)
{
SetIsExpanded(false, ignoreChildren);
}
public void Expand()
{
if(!_isExpanded)
Expand(true);
}
public void ExpandAll()
{
Expand(false);
}
public void Expand(bool ignoreChildren)
{
SetIsExpanded(true, ignoreChildren);
}
private void SetIsExpanded(bool value, bool ignoreChildren)
{
if(Tree==null)
_isExpanded=value;
else
Tree.SetIsExpanded(this, value, ignoreChildren);
}
#region ISerializable Members
private TreeNodeAdv(SerializationInfo info, StreamingContext context)
: this(null, null)
{
int nodesCount=0;
nodesCount=info.GetInt32("NodesCount");
_isExpanded=info.GetBoolean("IsExpanded");
_tag=info.GetValue("Tag", typeof(object));
for(int i=0; i<nodesCount; i++)
{
TreeNodeAdv child=(TreeNodeAdv)info.GetValue("Child"+i, typeof(TreeNodeAdv));
Nodes.Add(child);
}
}
[SecurityPermission(SecurityAction.Demand, SerializationFormatter=true)]
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("IsExpanded", IsExpanded);
info.AddValue("NodesCount", Nodes.Count);
if((Tag!=null)&&Tag.GetType().IsSerializable)
info.AddValue("Tag", Tag, Tag.GetType());
for(int i=0; i<Nodes.Count; i++)
info.AddValue("Child"+i, Nodes[i], typeof(TreeNodeAdv));
}
#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.Xml.Serialization
{
using System;
using System.IO;
using System.Collections;
using System.ComponentModel;
using System.Threading;
using System.Reflection;
using System.Security;
using System.Globalization;
///<internalonly/>
public abstract class XmlSerializationGeneratedCode
{
internal void Init(TempAssembly tempAssembly)
{
}
// this method must be called at the end of serialization
internal void Dispose()
{
}
}
internal class XmlSerializationCodeGen
{
private IndentedWriter _writer;
private int _nextMethodNumber = 0;
private Hashtable _methodNames = new Hashtable();
private ReflectionAwareCodeGen _raCodeGen;
private TypeScope[] _scopes;
private TypeDesc _stringTypeDesc = null;
private TypeDesc _qnameTypeDesc = null;
private string _access;
private string _className;
private TypeMapping[] _referencedMethods;
private int _references = 0;
private Hashtable _generatedMethods = new Hashtable();
internal XmlSerializationCodeGen(IndentedWriter writer, TypeScope[] scopes, string access, string className)
{
_writer = writer;
_scopes = scopes;
if (scopes.Length > 0)
{
_stringTypeDesc = scopes[0].GetTypeDesc(typeof(string));
_qnameTypeDesc = scopes[0].GetTypeDesc(typeof(XmlQualifiedName));
}
_raCodeGen = new ReflectionAwareCodeGen(writer);
_className = className;
_access = access;
}
internal IndentedWriter Writer { get { return _writer; } }
internal int NextMethodNumber { get { return _nextMethodNumber; } set { _nextMethodNumber = value; } }
internal ReflectionAwareCodeGen RaCodeGen { get { return _raCodeGen; } }
internal TypeDesc StringTypeDesc { get { return _stringTypeDesc; } }
internal TypeDesc QnameTypeDesc { get { return _qnameTypeDesc; } }
internal string ClassName { get { return _className; } }
internal string Access { get { return _access; } }
internal TypeScope[] Scopes { get { return _scopes; } }
internal Hashtable MethodNames { get { return _methodNames; } }
internal Hashtable GeneratedMethods { get { return _generatedMethods; } }
internal virtual void GenerateMethod(TypeMapping mapping) { }
internal void GenerateReferencedMethods()
{
while (_references > 0)
{
TypeMapping mapping = _referencedMethods[--_references];
GenerateMethod(mapping);
}
}
internal string ReferenceMapping(TypeMapping mapping)
{
if (!mapping.IsSoap)
{
if (_generatedMethods[mapping] == null)
{
_referencedMethods = EnsureArrayIndex(_referencedMethods, _references);
_referencedMethods[_references++] = mapping;
}
}
return (string)_methodNames[mapping];
}
private TypeMapping[] EnsureArrayIndex(TypeMapping[] a, int index)
{
if (a == null) return new TypeMapping[32];
if (index < a.Length) return a;
TypeMapping[] b = new TypeMapping[a.Length + 32];
Array.Copy(a, b, index);
return b;
}
internal void WriteQuotedCSharpString(string value)
{
_raCodeGen.WriteQuotedCSharpString(value);
}
internal void GenerateHashtableGetBegin(string privateName, string publicName)
{
_writer.Write(typeof(Hashtable).FullName);
_writer.Write(" ");
_writer.Write(privateName);
_writer.WriteLine(" = null;");
_writer.Write("public override ");
_writer.Write(typeof(Hashtable).FullName);
_writer.Write(" ");
_writer.Write(publicName);
_writer.WriteLine(" {");
_writer.Indent++;
_writer.WriteLine("get {");
_writer.Indent++;
_writer.Write("if (");
_writer.Write(privateName);
_writer.WriteLine(" == null) {");
_writer.Indent++;
_writer.Write(typeof(Hashtable).FullName);
_writer.Write(" _tmp = new ");
_writer.Write(typeof(Hashtable).FullName);
_writer.WriteLine("();");
}
internal void GenerateHashtableGetEnd(string privateName)
{
_writer.Write("if (");
_writer.Write(privateName);
_writer.Write(" == null) ");
_writer.Write(privateName);
_writer.WriteLine(" = _tmp;");
_writer.Indent--;
_writer.WriteLine("}");
_writer.Write("return ");
_writer.Write(privateName);
_writer.WriteLine(";");
_writer.Indent--;
_writer.WriteLine("}");
_writer.Indent--;
_writer.WriteLine("}");
}
internal void GeneratePublicMethods(string privateName, string publicName, string[] methods, XmlMapping[] xmlMappings)
{
GenerateHashtableGetBegin(privateName, publicName);
if (methods != null && methods.Length != 0 && xmlMappings != null && xmlMappings.Length == methods.Length)
{
for (int i = 0; i < methods.Length; i++)
{
if (methods[i] == null)
continue;
_writer.Write("_tmp[");
WriteQuotedCSharpString(xmlMappings[i].Key);
_writer.Write("] = ");
WriteQuotedCSharpString(methods[i]);
_writer.WriteLine(";");
}
}
GenerateHashtableGetEnd(privateName);
}
internal void GenerateSupportedTypes(Type[] types)
{
_writer.Write("public override ");
_writer.Write(typeof(bool).FullName);
_writer.Write(" CanSerialize(");
_writer.Write(typeof(Type).FullName);
_writer.WriteLine(" type) {");
_writer.Indent++;
Hashtable uniqueTypes = new Hashtable();
for (int i = 0; i < types.Length; i++)
{
Type type = types[i];
if (type == null)
continue;
if (!type.IsPublic && !type.IsNestedPublic)
continue;
if (uniqueTypes[type] != null)
continue;
if (DynamicAssemblies.IsTypeDynamic(type))
continue;
if (type.IsGenericType || type.ContainsGenericParameters && DynamicAssemblies.IsTypeDynamic(type.GetGenericArguments()))
continue;
uniqueTypes[type] = type;
_writer.Write("if (type == typeof(");
_writer.Write(CodeIdentifier.GetCSharpName(type));
_writer.WriteLine(")) return true;");
}
_writer.WriteLine("return false;");
_writer.Indent--;
_writer.WriteLine("}");
}
internal string GenerateBaseSerializer(string baseSerializer, string readerClass, string writerClass, CodeIdentifiers classes)
{
baseSerializer = CodeIdentifier.MakeValid(baseSerializer);
baseSerializer = classes.AddUnique(baseSerializer, baseSerializer);
_writer.WriteLine();
_writer.Write("public abstract class ");
_writer.Write(CodeIdentifier.GetCSharpName(baseSerializer));
_writer.Write(" : ");
_writer.Write(typeof(XmlSerializer).FullName);
_writer.WriteLine(" {");
_writer.Indent++;
_writer.Write("protected override ");
_writer.Write(typeof(XmlSerializationReader).FullName);
_writer.WriteLine(" CreateReader() {");
_writer.Indent++;
_writer.Write("return new ");
_writer.Write(readerClass);
_writer.WriteLine("();");
_writer.Indent--;
_writer.WriteLine("}");
_writer.Write("protected override ");
_writer.Write(typeof(XmlSerializationWriter).FullName);
_writer.WriteLine(" CreateWriter() {");
_writer.Indent++;
_writer.Write("return new ");
_writer.Write(writerClass);
_writer.WriteLine("();");
_writer.Indent--;
_writer.WriteLine("}");
_writer.Indent--;
_writer.WriteLine("}");
return baseSerializer;
}
internal string GenerateTypedSerializer(string readMethod, string writeMethod, XmlMapping mapping, CodeIdentifiers classes, string baseSerializer, string readerClass, string writerClass)
{
string serializerName = CodeIdentifier.MakeValid(Accessor.UnescapeName(mapping.Accessor.Mapping.TypeDesc.Name));
serializerName = classes.AddUnique(serializerName + "Serializer", mapping);
_writer.WriteLine();
_writer.Write("public sealed class ");
_writer.Write(CodeIdentifier.GetCSharpName(serializerName));
_writer.Write(" : ");
_writer.Write(baseSerializer);
_writer.WriteLine(" {");
_writer.Indent++;
_writer.WriteLine();
_writer.Write("public override ");
_writer.Write(typeof(bool).FullName);
_writer.Write(" CanDeserialize(");
_writer.Write(typeof(XmlReader).FullName);
_writer.WriteLine(" xmlReader) {");
_writer.Indent++;
if (mapping.Accessor.Any)
{
_writer.WriteLine("return true;");
}
else
{
_writer.Write("return xmlReader.IsStartElement(");
WriteQuotedCSharpString(mapping.Accessor.Name);
_writer.Write(", ");
WriteQuotedCSharpString(mapping.Accessor.Namespace);
_writer.WriteLine(");");
}
_writer.Indent--;
_writer.WriteLine("}");
if (writeMethod != null)
{
_writer.WriteLine();
_writer.Write("protected override void Serialize(object objectToSerialize, ");
_writer.Write(typeof(XmlSerializationWriter).FullName);
_writer.WriteLine(" writer) {");
_writer.Indent++;
_writer.Write("((");
_writer.Write(writerClass);
_writer.Write(")writer).");
_writer.Write(writeMethod);
_writer.Write("(");
if (mapping is XmlMembersMapping)
{
_writer.Write("(object[])");
}
_writer.WriteLine("objectToSerialize);");
_writer.Indent--;
_writer.WriteLine("}");
}
if (readMethod != null)
{
_writer.WriteLine();
_writer.Write("protected override object Deserialize(");
_writer.Write(typeof(XmlSerializationReader).FullName);
_writer.WriteLine(" reader) {");
_writer.Indent++;
_writer.Write("return ((");
_writer.Write(readerClass);
_writer.Write(")reader).");
_writer.Write(readMethod);
_writer.WriteLine("();");
_writer.Indent--;
_writer.WriteLine("}");
}
_writer.Indent--;
_writer.WriteLine("}");
return serializerName;
}
private void GenerateTypedSerializers(Hashtable serializers)
{
string privateName = "typedSerializers";
GenerateHashtableGetBegin(privateName, "TypedSerializers");
foreach (string key in serializers.Keys)
{
_writer.Write("_tmp.Add(");
WriteQuotedCSharpString(key);
_writer.Write(", new ");
_writer.Write((string)serializers[key]);
_writer.WriteLine("());");
}
GenerateHashtableGetEnd("typedSerializers");
}
//GenerateGetSerializer(serializers, xmlMappings);
private void GenerateGetSerializer(Hashtable serializers, XmlMapping[] xmlMappings)
{
_writer.Write("public override ");
_writer.Write(typeof(XmlSerializer).FullName);
_writer.Write(" GetSerializer(");
_writer.Write(typeof(Type).FullName);
_writer.WriteLine(" type) {");
_writer.Indent++;
for (int i = 0; i < xmlMappings.Length; i++)
{
if (xmlMappings[i] is XmlTypeMapping)
{
Type type = xmlMappings[i].Accessor.Mapping.TypeDesc.Type;
if (type == null)
continue;
if (!type.IsPublic && !type.IsNestedPublic)
continue;
if (DynamicAssemblies.IsTypeDynamic(type))
continue;
if (type.IsGenericType || type.ContainsGenericParameters && DynamicAssemblies.IsTypeDynamic(type.GetGenericArguments()))
continue;
_writer.Write("if (type == typeof(");
_writer.Write(CodeIdentifier.GetCSharpName(type));
_writer.Write(")) return new ");
_writer.Write((string)serializers[xmlMappings[i].Key]);
_writer.WriteLine("();");
}
}
_writer.WriteLine("return null;");
_writer.Indent--;
_writer.WriteLine("}");
}
internal void GenerateSerializerContract(string className, XmlMapping[] xmlMappings, Type[] types, string readerType, string[] readMethods, string writerType, string[] writerMethods, Hashtable serializers)
{
_writer.WriteLine();
_writer.Write("public class XmlSerializerContract : global::");
_writer.Write(typeof(XmlSerializerImplementation).FullName);
_writer.WriteLine(" {");
_writer.Indent++;
_writer.Write("public override global::");
_writer.Write(typeof(XmlSerializationReader).FullName);
_writer.Write(" Reader { get { return new ");
_writer.Write(readerType);
_writer.WriteLine("(); } }");
_writer.Write("public override global::");
_writer.Write(typeof(XmlSerializationWriter).FullName);
_writer.Write(" Writer { get { return new ");
_writer.Write(writerType);
_writer.WriteLine("(); } }");
GeneratePublicMethods(nameof(readMethods), "ReadMethods", readMethods, xmlMappings);
GeneratePublicMethods("writeMethods", "WriteMethods", writerMethods, xmlMappings);
GenerateTypedSerializers(serializers);
GenerateSupportedTypes(types);
GenerateGetSerializer(serializers, xmlMappings);
_writer.Indent--;
_writer.WriteLine("}");
}
internal static bool IsWildcard(SpecialMapping mapping)
{
if (mapping is SerializableMapping)
return ((SerializableMapping)mapping).IsAny;
return mapping.TypeDesc.CanBeElementValue;
}
}
}
| |
using System;
using System.IO;
using System.Diagnostics;
using System.Reflection;
using System.Reflection.Emit;
using System.Threading;
using System.Globalization;
namespace Volante.Impl
{
internal class CodeGenerator
{
public GeneratedSerializer Generate(ClassDescriptor desc)
{
ModuleBuilder module = EmitAssemblyModule();
Type newCls = EmitClass(module, desc);
return (GeneratedSerializer)module.Assembly.CreateInstance(newCls.Name);
}
public Type CreateWrapper(Type type)
{
return EmitClassWrapper(EmitAssemblyModule(), type);
}
private ModuleBuilder EmitAssemblyModule()
{
if (dynamicModule == null)
{
AssemblyName assemblyName = new AssemblyName();
assemblyName.Name = "GeneratedSerializerAssembly";
//Create a new assembly with one module
AssemblyBuilder assembly = Thread.GetDomain().DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
dynamicModule = assembly.DefineDynamicModule("GeneratedSerializerModule");
}
return dynamicModule;
}
private MethodBuilder GetBuilder(TypeBuilder serializerType, MethodInfo methodInterface)
{
Type returnType = methodInterface.ReturnType;
ParameterInfo[] methodParams = methodInterface.GetParameters();
Type[] paramTypes = new Type[methodParams.Length];
for (int i = 0; i < methodParams.Length; i++)
{
paramTypes[i] = methodParams[i].ParameterType;
}
return serializerType.DefineMethod(methodInterface.Name,
MethodAttributes.Public | MethodAttributes.Virtual,
returnType,
paramTypes);
}
private void generatePackField(ILGenerator il, FieldInfo f, MethodInfo pack)
{
il.Emit(OpCodes.Ldarg_3); // buf
il.Emit(OpCodes.Ldloc_1, offs); // offs
il.Emit(OpCodes.Ldloc_0, obj);
il.Emit(OpCodes.Ldfld, f);
il.Emit(OpCodes.Call, pack);
il.Emit(OpCodes.Stloc_1, offs); // offs
}
private void generatePackMethod(ClassDescriptor desc, MethodBuilder builder)
{
ILGenerator il = builder.GetILGenerator();
il.Emit(OpCodes.Ldarg_2); // obj
il.Emit(OpCodes.Castclass, desc.cls);
obj = il.DeclareLocal(desc.cls);
il.Emit(OpCodes.Stloc_0, obj);
il.Emit(OpCodes.Ldc_I4, ObjectHeader.Sizeof);
offs = il.DeclareLocal(typeof(int));
il.Emit(OpCodes.Stloc_1, offs);
ClassDescriptor.FieldDescriptor[] flds = desc.allFields;
for (int i = 0, n = flds.Length; i < n; i++)
{
ClassDescriptor.FieldDescriptor fd = flds[i];
FieldInfo f = fd.field;
switch (fd.type)
{
case ClassDescriptor.FieldType.tpByte:
case ClassDescriptor.FieldType.tpSByte:
generatePackField(il, f, packI1);
continue;
case ClassDescriptor.FieldType.tpBoolean:
generatePackField(il, f, packBool);
continue;
case ClassDescriptor.FieldType.tpShort:
case ClassDescriptor.FieldType.tpUShort:
case ClassDescriptor.FieldType.tpChar:
generatePackField(il, f, packI2);
continue;
case ClassDescriptor.FieldType.tpEnum:
case ClassDescriptor.FieldType.tpInt:
case ClassDescriptor.FieldType.tpUInt:
generatePackField(il, f, packI4);
continue;
case ClassDescriptor.FieldType.tpLong:
case ClassDescriptor.FieldType.tpULong:
generatePackField(il, f, packI8);
continue;
case ClassDescriptor.FieldType.tpFloat:
generatePackField(il, f, packF4);
continue;
case ClassDescriptor.FieldType.tpDouble:
generatePackField(il, f, packF8);
continue;
case ClassDescriptor.FieldType.tpDecimal:
generatePackField(il, f, packDecimal);
continue;
case ClassDescriptor.FieldType.tpGuid:
generatePackField(il, f, packGuid);
continue;
case ClassDescriptor.FieldType.tpDate:
generatePackField(il, f, packDate);
continue;
case ClassDescriptor.FieldType.tpString:
generatePackField(il, f, packString);
continue;
default:
il.Emit(OpCodes.Ldarg_1); // db
il.Emit(OpCodes.Ldarg_3); // buf
il.Emit(OpCodes.Ldloc_1, offs);
il.Emit(OpCodes.Ldloc_0, obj);
il.Emit(OpCodes.Ldfld, f);
il.Emit(OpCodes.Ldnull); // fd
il.Emit(OpCodes.Ldc_I4, (int)fd.type);
il.Emit(OpCodes.Ldloc_0, obj);
il.Emit(OpCodes.Call, packField);
il.Emit(OpCodes.Stloc_1, offs);
continue;
}
}
il.Emit(OpCodes.Ldloc_1, offs);
il.Emit(OpCodes.Ret);
}
private void generateUnpackMethod(ClassDescriptor desc, MethodBuilder builder)
{
ILGenerator il = builder.GetILGenerator();
il.Emit(OpCodes.Ldarg_2);
il.Emit(OpCodes.Castclass, desc.cls);
LocalBuilder obj = il.DeclareLocal(desc.cls);
il.Emit(OpCodes.Stloc_0, obj);
il.Emit(OpCodes.Ldc_I4, ObjectHeader.Sizeof);
LocalBuilder offs = il.DeclareLocal(typeof(int));
il.Emit(OpCodes.Stloc_1, offs);
LocalBuilder val = il.DeclareLocal(typeof(object));
ClassDescriptor.FieldDescriptor[] flds = desc.allFields;
for (int i = 0, n = flds.Length; i < n; i++)
{
ClassDescriptor.FieldDescriptor fd = flds[i];
FieldInfo f = fd.field;
if (f == null)
{
switch (fd.type)
{
case ClassDescriptor.FieldType.tpByte:
case ClassDescriptor.FieldType.tpSByte:
case ClassDescriptor.FieldType.tpBoolean:
il.Emit(OpCodes.Ldloc_1, offs);
il.Emit(OpCodes.Ldc_I4_1);
il.Emit(OpCodes.Add);
il.Emit(OpCodes.Stloc_1, offs);
continue;
case ClassDescriptor.FieldType.tpShort:
case ClassDescriptor.FieldType.tpUShort:
case ClassDescriptor.FieldType.tpChar:
il.Emit(OpCodes.Ldloc_1, offs);
il.Emit(OpCodes.Ldc_I4_2);
il.Emit(OpCodes.Add);
il.Emit(OpCodes.Stloc_1, offs);
continue;
case ClassDescriptor.FieldType.tpEnum:
case ClassDescriptor.FieldType.tpInt:
case ClassDescriptor.FieldType.tpUInt:
case ClassDescriptor.FieldType.tpFloat:
il.Emit(OpCodes.Ldloc_1, offs);
il.Emit(OpCodes.Ldc_I4_4);
il.Emit(OpCodes.Add);
il.Emit(OpCodes.Stloc_1, offs);
continue;
case ClassDescriptor.FieldType.tpLong:
case ClassDescriptor.FieldType.tpULong:
case ClassDescriptor.FieldType.tpDate:
case ClassDescriptor.FieldType.tpDouble:
il.Emit(OpCodes.Ldloc_1, offs);
il.Emit(OpCodes.Ldc_I4_8);
il.Emit(OpCodes.Add);
il.Emit(OpCodes.Stloc_1, offs);
continue;
case ClassDescriptor.FieldType.tpDecimal:
case ClassDescriptor.FieldType.tpGuid:
il.Emit(OpCodes.Ldloc_1, offs);
il.Emit(OpCodes.Ldc_I4, 16);
il.Emit(OpCodes.Add);
il.Emit(OpCodes.Stloc_1, offs);
continue;
default:
il.Emit(OpCodes.Ldarg_1); // db
il.Emit(OpCodes.Ldarg_3); // body
il.Emit(OpCodes.Ldloc_1, offs);
il.Emit(OpCodes.Ldnull); // fd
il.Emit(OpCodes.Ldc_I4, (int)fd.type);
il.Emit(OpCodes.Call, skipField);
il.Emit(OpCodes.Stloc_1, offs); // offs
continue;
}
}
else
{
switch (fd.type)
{
case ClassDescriptor.FieldType.tpByte:
il.Emit(OpCodes.Ldloc_0, obj);
il.Emit(OpCodes.Ldarg_3); // body
il.Emit(OpCodes.Ldloc_1, offs);
il.Emit(OpCodes.Ldelem_U1);
il.Emit(OpCodes.Stfld, f);
il.Emit(OpCodes.Ldloc_1, offs);
il.Emit(OpCodes.Ldc_I4_1);
il.Emit(OpCodes.Add);
il.Emit(OpCodes.Stloc_1, offs);
continue;
case ClassDescriptor.FieldType.tpSByte:
il.Emit(OpCodes.Ldloc_0, obj);
il.Emit(OpCodes.Ldarg_3); // body
il.Emit(OpCodes.Ldloc_1, offs);
il.Emit(OpCodes.Ldelem_U1);
il.Emit(OpCodes.Conv_I1);
il.Emit(OpCodes.Stfld, f);
il.Emit(OpCodes.Ldloc_1, offs);
il.Emit(OpCodes.Ldc_I4_1);
il.Emit(OpCodes.Add);
il.Emit(OpCodes.Stloc_1, offs);
continue;
case ClassDescriptor.FieldType.tpBoolean:
il.Emit(OpCodes.Ldloc_0, obj);
il.Emit(OpCodes.Ldarg_3); // body
il.Emit(OpCodes.Ldloc_1, offs);
il.Emit(OpCodes.Ldelem_U1);
il.Emit(OpCodes.Stfld, f);
il.Emit(OpCodes.Ldloc_1, offs);
il.Emit(OpCodes.Ldc_I4_1);
il.Emit(OpCodes.Add);
il.Emit(OpCodes.Stloc_1, offs);
continue;
case ClassDescriptor.FieldType.tpShort:
il.Emit(OpCodes.Ldloc_0, obj);
il.Emit(OpCodes.Ldarg_3); // body
il.Emit(OpCodes.Ldloc_1, offs);
il.Emit(OpCodes.Call, unpackI2);
il.Emit(OpCodes.Stfld, f);
il.Emit(OpCodes.Ldloc_1, offs);
il.Emit(OpCodes.Ldc_I4_2);
il.Emit(OpCodes.Add);
il.Emit(OpCodes.Stloc_1, offs);
continue;
case ClassDescriptor.FieldType.tpUShort:
case ClassDescriptor.FieldType.tpChar:
il.Emit(OpCodes.Ldloc_0, obj);
il.Emit(OpCodes.Ldarg_3); // body
il.Emit(OpCodes.Ldloc_1, offs);
il.Emit(OpCodes.Call, unpackI2);
il.Emit(OpCodes.Conv_U2);
il.Emit(OpCodes.Stfld, f);
il.Emit(OpCodes.Ldloc_1, offs);
il.Emit(OpCodes.Ldc_I4_2);
il.Emit(OpCodes.Add);
il.Emit(OpCodes.Stloc_1, offs);
continue;
case ClassDescriptor.FieldType.tpEnum:
case ClassDescriptor.FieldType.tpInt:
case ClassDescriptor.FieldType.tpUInt:
il.Emit(OpCodes.Ldloc_0, obj);
il.Emit(OpCodes.Ldarg_3); // body
il.Emit(OpCodes.Ldloc_1, offs);
il.Emit(OpCodes.Call, unpackI4);
il.Emit(OpCodes.Stfld, f);
il.Emit(OpCodes.Ldloc_1, offs);
il.Emit(OpCodes.Ldc_I4_4);
il.Emit(OpCodes.Add);
il.Emit(OpCodes.Stloc_1, offs);
continue;
case ClassDescriptor.FieldType.tpLong:
case ClassDescriptor.FieldType.tpULong:
il.Emit(OpCodes.Ldloc_0, obj);
il.Emit(OpCodes.Ldarg_3); // body
il.Emit(OpCodes.Ldloc_1, offs);
il.Emit(OpCodes.Call, unpackI8);
il.Emit(OpCodes.Stfld, f);
il.Emit(OpCodes.Ldloc_1, offs);
il.Emit(OpCodes.Ldc_I4_8);
il.Emit(OpCodes.Add);
il.Emit(OpCodes.Stloc_1, offs);
continue;
case ClassDescriptor.FieldType.tpFloat:
il.Emit(OpCodes.Ldloc_0, obj);
il.Emit(OpCodes.Ldarg_3); // body
il.Emit(OpCodes.Ldloc_1, offs);
il.Emit(OpCodes.Call, unpackF4);
il.Emit(OpCodes.Stfld, f);
il.Emit(OpCodes.Ldloc_1, offs);
il.Emit(OpCodes.Ldc_I4_4);
il.Emit(OpCodes.Add);
il.Emit(OpCodes.Stloc_1, offs);
continue;
case ClassDescriptor.FieldType.tpDouble:
il.Emit(OpCodes.Ldloc_0, obj);
il.Emit(OpCodes.Ldarg_3); // body
il.Emit(OpCodes.Ldloc_1, offs);
il.Emit(OpCodes.Call, unpackF8);
il.Emit(OpCodes.Stfld, f);
il.Emit(OpCodes.Ldloc_1, offs);
il.Emit(OpCodes.Ldc_I4_8);
il.Emit(OpCodes.Add);
il.Emit(OpCodes.Stloc_1, offs);
continue;
case ClassDescriptor.FieldType.tpDecimal:
il.Emit(OpCodes.Ldloc_0, obj);
il.Emit(OpCodes.Ldarg_3); // body
il.Emit(OpCodes.Ldloc_1, offs);
il.Emit(OpCodes.Call, unpackDecimal);
il.Emit(OpCodes.Stfld, f);
il.Emit(OpCodes.Ldloc_1, offs);
il.Emit(OpCodes.Ldc_I4, 16);
il.Emit(OpCodes.Add);
il.Emit(OpCodes.Stloc_1, offs);
continue;
case ClassDescriptor.FieldType.tpGuid:
il.Emit(OpCodes.Ldloc_0, obj);
il.Emit(OpCodes.Ldarg_3); // body
il.Emit(OpCodes.Ldloc_1, offs);
il.Emit(OpCodes.Call, unpackGuid);
il.Emit(OpCodes.Stfld, f);
il.Emit(OpCodes.Ldloc_1, offs);
il.Emit(OpCodes.Ldc_I4, 16);
il.Emit(OpCodes.Add);
il.Emit(OpCodes.Stloc_1, offs);
continue;
case ClassDescriptor.FieldType.tpDate:
il.Emit(OpCodes.Ldloc_0, obj);
il.Emit(OpCodes.Ldarg_3); // body
il.Emit(OpCodes.Ldloc_1, offs);
il.Emit(OpCodes.Call, unpackDate);
il.Emit(OpCodes.Stfld, f);
il.Emit(OpCodes.Ldloc_1, offs);
il.Emit(OpCodes.Ldc_I4_8);
il.Emit(OpCodes.Add);
il.Emit(OpCodes.Stloc_1, offs);
continue;
case ClassDescriptor.FieldType.tpString:
il.Emit(OpCodes.Ldarg_3); // body
il.Emit(OpCodes.Ldloc_1, offs);
il.Emit(OpCodes.Ldloc_0, obj);
il.Emit(OpCodes.Ldflda, f);
il.Emit(OpCodes.Call, unpackString);
il.Emit(OpCodes.Stloc_1, offs);
continue;
default:
il.Emit(OpCodes.Ldarg_1); // db
il.Emit(OpCodes.Ldarg_3); // body
il.Emit(OpCodes.Ldloc_1, offs);
il.Emit(OpCodes.Ldarg_S, 4); // recursiveLoading
il.Emit(OpCodes.Ldloca, val);
il.Emit(OpCodes.Ldnull); // fd
il.Emit(OpCodes.Ldc_I4, (int)fd.type);
il.Emit(OpCodes.Ldloc_0, obj);
il.Emit(OpCodes.Call, unpackField);
il.Emit(OpCodes.Stloc_1, offs); // offs
il.Emit(OpCodes.Ldloc_0, obj);
il.Emit(OpCodes.Ldloc, val);
il.Emit(OpCodes.Castclass, f.FieldType);
il.Emit(OpCodes.Stfld, f);
continue;
}
}
}
il.Emit(OpCodes.Ret);
}
private void generateNewMethod(ClassDescriptor desc, MethodBuilder builder)
{
ILGenerator il = builder.GetILGenerator();
il.Emit(OpCodes.Newobj, desc.defaultConstructor);
il.Emit(OpCodes.Ret);
}
private Type EmitClass(ModuleBuilder module, ClassDescriptor desc)
{
counter += 1;
String generatedClassName = "GeneratedSerializerClass" + counter;
TypeBuilder serializerType = module.DefineType(generatedClassName, TypeAttributes.Public);
Type serializerInterface = typeof(GeneratedSerializer);
serializerType.AddInterfaceImplementation(serializerInterface);
//Add a constructor
//TODO: wasn't used, figure out if was needed
//ConstructorBuilder constructor =
// serializerType.DefineDefaultConstructor(MethodAttributes.Public);
MethodInfo packInterface = serializerInterface.GetMethod("pack");
MethodBuilder packBuilder = GetBuilder(serializerType, packInterface);
generatePackMethod(desc, packBuilder);
serializerType.DefineMethodOverride(packBuilder, packInterface);
MethodInfo unpackInterface = serializerInterface.GetMethod("unpack");
MethodBuilder unpackBuilder = GetBuilder(serializerType, unpackInterface);
generateUnpackMethod(desc, unpackBuilder);
serializerType.DefineMethodOverride(unpackBuilder, unpackInterface);
MethodInfo newInterface = serializerInterface.GetMethod("newInstance");
MethodBuilder newBuilder = GetBuilder(serializerType, newInterface);
generateNewMethod(desc, newBuilder);
serializerType.DefineMethodOverride(newBuilder, newInterface);
serializerType.CreateType();
return serializerType;
}
private Type EmitClassWrapper(ModuleBuilder module, Type type)
{
String generatedClassName = type.Name + "Wrapper";
TypeBuilder wrapperType;
if (type.IsInterface)
{
wrapperType = module.DefineType(generatedClassName, TypeAttributes.Public,
typeof(IResource).IsAssignableFrom(type) ? typeof(PersistentResource) : typeof(Persistent));
wrapperType.AddInterfaceImplementation(type);
}
else
{
wrapperType = module.DefineType(generatedClassName, TypeAttributes.Public, type);
}
wrapperType.AddInterfaceImplementation(typeof(PersistentWrapper));
//Add a constructor
//TODO: wasn't used, figure out if was needed
//ConstructorBuilder constructor =
// wrapperType.DefineDefaultConstructor(MethodAttributes.Public);
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
for (int i = 0; i < properties.Length; i++)
{
PropertyInfo prop = properties[i];
MethodInfo getter = prop.GetGetMethod(true);
MethodInfo setter = prop.GetSetMethod(true);
if (getter != null && setter != null && getter.IsVirtual && setter.IsVirtual)
{
Type returnType = getter.ReturnType;
String fieldName = prop.Name;
Type fieldType;
if (typeof(IPersistent).IsAssignableFrom(returnType))
{
fieldType = typeof(int);
fieldName = "r_" + fieldName;
}
else
{
fieldType = returnType;
fieldName = "s_" + fieldName;
}
if (fieldType.IsArray && typeof(IPersistent).IsAssignableFrom(fieldType.GetElementType()))
throw new DatabaseException(DatabaseException.ErrorCode.UNSUPPORTED_TYPE);
FieldBuilder fb = wrapperType.DefineField(fieldName, fieldType, FieldAttributes.Private);
MethodBuilder getterImpl = wrapperType.DefineMethod(getter.Name,
MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.NewSlot,
returnType,
new Type[] { });
ILGenerator il = getterImpl.GetILGenerator();
if (fieldType != returnType)
{
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Callvirt, getDatabase);
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldfld, fb);
il.Emit(OpCodes.Callvirt, getByOid);
il.Emit(OpCodes.Castclass, returnType);
}
else
{
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldfld, fb);
}
il.Emit(OpCodes.Ret);
wrapperType.DefineMethodOverride(getterImpl, getter);
MethodBuilder setterImpl = wrapperType.DefineMethod(setter.Name,
MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.NewSlot,
null,
new Type[] { returnType });
il = setterImpl.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
if (fieldType != returnType)
{
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Callvirt, getDatabase);
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Callvirt, makePersistent);
}
else
{
il.Emit(OpCodes.Ldarg_1);
}
il.Emit(OpCodes.Stfld, fb);
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Callvirt, modify);
il.Emit(OpCodes.Ret);
wrapperType.DefineMethodOverride(setterImpl, setter);
}
}
wrapperType.CreateType();
return wrapperType;
}
public static CodeGenerator Instance
{
get
{
if (instance == null)
instance = new CodeGenerator();
return instance;
}
}
private static CodeGenerator instance;
private LocalBuilder obj;
private LocalBuilder offs;
private MethodInfo packBool = typeof(ByteBuffer).GetMethod("packBool");
private MethodInfo packI1 = typeof(ByteBuffer).GetMethod("packI1");
private MethodInfo packI2 = typeof(ByteBuffer).GetMethod("packI2");
private MethodInfo packI4 = typeof(ByteBuffer).GetMethod("packI4");
private MethodInfo packI8 = typeof(ByteBuffer).GetMethod("packI8");
private MethodInfo packF4 = typeof(ByteBuffer).GetMethod("packF4");
private MethodInfo packF8 = typeof(ByteBuffer).GetMethod("packF8");
private MethodInfo packDecimal = typeof(ByteBuffer).GetMethod("packDecimal");
private MethodInfo packGuid = typeof(ByteBuffer).GetMethod("packGuid");
private MethodInfo packDate = typeof(ByteBuffer).GetMethod("packDate");
private MethodInfo packString = typeof(ByteBuffer).GetMethod("packString");
private MethodInfo packField = typeof(DatabaseImpl).GetMethod("packField");
private MethodInfo unpackI2 = typeof(Bytes).GetMethod("unpack2");
private MethodInfo unpackI4 = typeof(Bytes).GetMethod("unpack4");
private MethodInfo unpackI8 = typeof(Bytes).GetMethod("unpack8");
private MethodInfo unpackF4 = typeof(Bytes).GetMethod("unpackF4");
private MethodInfo unpackF8 = typeof(Bytes).GetMethod("unpackF8");
private MethodInfo unpackDecimal = typeof(Bytes).GetMethod("unpackDecimal");
private MethodInfo unpackGuid = typeof(Bytes).GetMethod("unpackGuid");
private MethodInfo unpackDate = typeof(Bytes).GetMethod("unpackDate");
private MethodInfo unpackString = typeof(Bytes).GetMethod("unpackString");
private MethodInfo unpackField = typeof(DatabaseImpl).GetMethod("unpackField");
private MethodInfo skipField = typeof(DatabaseImpl).GetMethod("skipField");
private MethodInfo modify = typeof(IPersistent).GetMethod("Modify");
private MethodInfo getDatabase = typeof(IPersistent).GetProperty("Database").GetGetMethod();
private MethodInfo getByOid = typeof(IDatabase).GetMethod("GetObjectByOid");
private MethodInfo makePersistent = typeof(IDatabase).GetMethod("MakePersistent");
private ModuleBuilder dynamicModule;
private int counter;
}
}
| |
/*
* Copyright (c) 2006-2014, openmetaverse.org
* All rights reserved.
*
* - Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* - Neither the name of the openmetaverse.org nor the names
* of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Runtime.InteropServices;
using System.Globalization;
namespace OpenMetaverse
{
/// <summary>
/// A three-dimensional vector with doubleing-point values
/// </summary>
[Serializable]
[StructLayout(LayoutKind.Sequential)]
public struct Vector3d : IComparable<Vector3d>, IEquatable<Vector3d>
{
/// <summary>X value</summary>
public double X;
/// <summary>Y value</summary>
public double Y;
/// <summary>Z value</summary>
public double Z;
#region Constructors
public Vector3d(double x, double y, double z)
{
X = x;
Y = y;
Z = z;
}
public Vector3d(double value)
{
X = value;
Y = value;
Z = value;
}
/// <summary>
/// Constructor, builds a vector from a byte array
/// </summary>
/// <param name="byteArray">Byte array containing three eight-byte doubles</param>
/// <param name="pos">Beginning position in the byte array</param>
public Vector3d(byte[] byteArray, int pos)
{
X = Y = Z = 0d;
FromBytes(byteArray, pos);
}
public Vector3d(Vector3 vector)
{
X = vector.X;
Y = vector.Y;
Z = vector.Z;
}
public Vector3d(Vector3d vector)
{
X = vector.X;
Y = vector.Y;
Z = vector.Z;
}
#endregion Constructors
#region Public Methods
public double Length()
{
return Math.Sqrt(DistanceSquared(this, Zero));
}
public double LengthSquared()
{
return DistanceSquared(this, Zero);
}
public void Normalize()
{
this = Normalize(this);
}
/// <summary>
/// Test if this vector is equal to another vector, within a given
/// tolerance range
/// </summary>
/// <param name="vec">Vector to test against</param>
/// <param name="tolerance">The acceptable magnitude of difference
/// between the two vectors</param>
/// <returns>True if the magnitude of difference between the two vectors
/// is less than the given tolerance, otherwise false</returns>
public bool ApproxEquals(Vector3d vec, double tolerance)
{
Vector3d diff = this - vec;
return (diff.LengthSquared() <= tolerance * tolerance);
}
/// <summary>
/// IComparable.CompareTo implementation
/// </summary>
public int CompareTo(Vector3d vector)
{
return this.Length().CompareTo(vector.Length());
}
/// <summary>
/// Test if this vector is composed of all finite numbers
/// </summary>
public bool IsFinite()
{
return (Utils.IsFinite(X) && Utils.IsFinite(Y) && Utils.IsFinite(Z));
}
/// <summary>
/// Builds a vector from a byte array
/// </summary>
/// <param name="byteArray">Byte array containing a 24 byte vector</param>
/// <param name="pos">Beginning position in the byte array</param>
public void FromBytes(byte[] byteArray, int pos)
{
if (!BitConverter.IsLittleEndian)
{
// Big endian architecture
byte[] conversionBuffer = new byte[24];
Buffer.BlockCopy(byteArray, pos, conversionBuffer, 0, 24);
Array.Reverse(conversionBuffer, 0, 8);
Array.Reverse(conversionBuffer, 8, 8);
Array.Reverse(conversionBuffer, 16, 8);
X = BitConverter.ToDouble(conversionBuffer, 0);
Y = BitConverter.ToDouble(conversionBuffer, 8);
Z = BitConverter.ToDouble(conversionBuffer, 16);
}
else
{
// Little endian architecture
X = BitConverter.ToDouble(byteArray, pos);
Y = BitConverter.ToDouble(byteArray, pos + 8);
Z = BitConverter.ToDouble(byteArray, pos + 16);
}
}
/// <summary>
/// Returns the raw bytes for this vector
/// </summary>
/// <returns>A 24 byte array containing X, Y, and Z</returns>
public byte[] GetBytes()
{
byte[] byteArray = new byte[24];
ToBytes(byteArray, 0);
return byteArray;
}
/// <summary>
/// Writes the raw bytes for this vector to a byte array
/// </summary>
/// <param name="dest">Destination byte array</param>
/// <param name="pos">Position in the destination array to start
/// writing. Must be at least 24 bytes before the end of the array</param>
public void ToBytes(byte[] dest, int pos)
{
Buffer.BlockCopy(BitConverter.GetBytes(X), 0, dest, pos + 0, 8);
Buffer.BlockCopy(BitConverter.GetBytes(Y), 0, dest, pos + 8, 8);
Buffer.BlockCopy(BitConverter.GetBytes(Z), 0, dest, pos + 16, 8);
if (!BitConverter.IsLittleEndian)
{
Array.Reverse(dest, pos + 0, 8);
Array.Reverse(dest, pos + 8, 8);
Array.Reverse(dest, pos + 16, 8);
}
}
#endregion Public Methods
#region Static Methods
public static Vector3d Add(Vector3d value1, Vector3d value2)
{
value1.X += value2.X;
value1.Y += value2.Y;
value1.Z += value2.Z;
return value1;
}
public static Vector3d Clamp(Vector3d value1, Vector3d min, Vector3d max)
{
return new Vector3d(
Utils.Clamp(value1.X, min.X, max.X),
Utils.Clamp(value1.Y, min.Y, max.Y),
Utils.Clamp(value1.Z, min.Z, max.Z));
}
public static Vector3d Cross(Vector3d value1, Vector3d value2)
{
return new Vector3d(
value1.Y * value2.Z - value2.Y * value1.Z,
value1.Z * value2.X - value2.Z * value1.X,
value1.X * value2.Y - value2.X * value1.Y);
}
public static double Distance(Vector3d value1, Vector3d value2)
{
return Math.Sqrt(DistanceSquared(value1, value2));
}
public static double DistanceSquared(Vector3d value1, Vector3d value2)
{
return
(value1.X - value2.X) * (value1.X - value2.X) +
(value1.Y - value2.Y) * (value1.Y - value2.Y) +
(value1.Z - value2.Z) * (value1.Z - value2.Z);
}
public static Vector3d Divide(Vector3d value1, Vector3d value2)
{
value1.X /= value2.X;
value1.Y /= value2.Y;
value1.Z /= value2.Z;
return value1;
}
public static Vector3d Divide(Vector3d value1, double value2)
{
double factor = 1d / value2;
value1.X *= factor;
value1.Y *= factor;
value1.Z *= factor;
return value1;
}
public static double Dot(Vector3d value1, Vector3d value2)
{
return value1.X * value2.X + value1.Y * value2.Y + value1.Z * value2.Z;
}
public static Vector3d Lerp(Vector3d value1, Vector3d value2, double amount)
{
return new Vector3d(
Utils.Lerp(value1.X, value2.X, amount),
Utils.Lerp(value1.Y, value2.Y, amount),
Utils.Lerp(value1.Z, value2.Z, amount));
}
public static Vector3d Max(Vector3d value1, Vector3d value2)
{
return new Vector3d(
Math.Max(value1.X, value2.X),
Math.Max(value1.Y, value2.Y),
Math.Max(value1.Z, value2.Z));
}
public static Vector3d Min(Vector3d value1, Vector3d value2)
{
return new Vector3d(
Math.Min(value1.X, value2.X),
Math.Min(value1.Y, value2.Y),
Math.Min(value1.Z, value2.Z));
}
public static Vector3d Multiply(Vector3d value1, Vector3d value2)
{
value1.X *= value2.X;
value1.Y *= value2.Y;
value1.Z *= value2.Z;
return value1;
}
public static Vector3d Multiply(Vector3d value1, double scaleFactor)
{
value1.X *= scaleFactor;
value1.Y *= scaleFactor;
value1.Z *= scaleFactor;
return value1;
}
public static Vector3d Negate(Vector3d value)
{
value.X = -value.X;
value.Y = -value.Y;
value.Z = -value.Z;
return value;
}
public static Vector3d Normalize(Vector3d value)
{
double factor = Distance(value, Zero);
if (factor > Double.Epsilon)
{
factor = 1d / factor;
value.X *= factor;
value.Y *= factor;
value.Z *= factor;
}
else
{
value.X = 0d;
value.Y = 0d;
value.Z = 0d;
}
return value;
}
/// <summary>
/// Parse a vector from a string
/// </summary>
/// <param name="val">A string representation of a 3D vector, enclosed
/// in arrow brackets and separated by commas</param>
public static Vector3d Parse(string val)
{
char[] splitChar = { ',' };
string[] split = val.Replace("<", String.Empty).Replace(">", String.Empty).Split(splitChar);
return new Vector3d(
Double.Parse(split[0].Trim(), Utils.EnUsCulture),
Double.Parse(split[1].Trim(), Utils.EnUsCulture),
Double.Parse(split[2].Trim(), Utils.EnUsCulture));
}
public static bool TryParse(string val, out Vector3d result)
{
try
{
result = Parse(val);
return true;
}
catch (Exception)
{
result = Vector3d.Zero;
return false;
}
}
/// <summary>
/// Interpolates between two vectors using a cubic equation
/// </summary>
public static Vector3d SmoothStep(Vector3d value1, Vector3d value2, double amount)
{
return new Vector3d(
Utils.SmoothStep(value1.X, value2.X, amount),
Utils.SmoothStep(value1.Y, value2.Y, amount),
Utils.SmoothStep(value1.Z, value2.Z, amount));
}
public static Vector3d Subtract(Vector3d value1, Vector3d value2)
{
value1.X -= value2.X;
value1.Y -= value2.Y;
value1.Z -= value2.Z;
return value1;
}
#endregion Static Methods
#region Overrides
public override bool Equals(object obj)
{
return (obj is Vector3d) ? this == (Vector3d)obj : false;
}
public bool Equals(Vector3d other)
{
return this == other;
}
public override int GetHashCode()
{
return X.GetHashCode() ^ Y.GetHashCode() ^ Z.GetHashCode();
}
/// <summary>
/// Get a formatted string representation of the vector
/// </summary>
/// <returns>A string representation of the vector</returns>
public override string ToString()
{
return String.Format(Utils.EnUsCulture, "<{0}, {1}, {2}>", X, Y, Z);
}
/// <summary>
/// Get a string representation of the vector elements with up to three
/// decimal digits and separated by spaces only
/// </summary>
/// <returns>Raw string representation of the vector</returns>
public string ToRawString()
{
CultureInfo enUs = new CultureInfo("en-us");
enUs.NumberFormat.NumberDecimalDigits = 3;
return String.Format(enUs, "{0} {1} {2}", X, Y, Z);
}
#endregion Overrides
#region Operators
public static bool operator ==(Vector3d value1, Vector3d value2)
{
return value1.X == value2.X
&& value1.Y == value2.Y
&& value1.Z == value2.Z;
}
public static bool operator !=(Vector3d value1, Vector3d value2)
{
return !(value1 == value2);
}
public static Vector3d operator +(Vector3d value1, Vector3d value2)
{
value1.X += value2.X;
value1.Y += value2.Y;
value1.Z += value2.Z;
return value1;
}
public static Vector3d operator -(Vector3d value)
{
value.X = -value.X;
value.Y = -value.Y;
value.Z = -value.Z;
return value;
}
public static Vector3d operator -(Vector3d value1, Vector3d value2)
{
value1.X -= value2.X;
value1.Y -= value2.Y;
value1.Z -= value2.Z;
return value1;
}
public static Vector3d operator *(Vector3d value1, Vector3d value2)
{
value1.X *= value2.X;
value1.Y *= value2.Y;
value1.Z *= value2.Z;
return value1;
}
public static Vector3d operator *(Vector3d value, double scaleFactor)
{
value.X *= scaleFactor;
value.Y *= scaleFactor;
value.Z *= scaleFactor;
return value;
}
public static Vector3d operator /(Vector3d value1, Vector3d value2)
{
value1.X /= value2.X;
value1.Y /= value2.Y;
value1.Z /= value2.Z;
return value1;
}
public static Vector3d operator /(Vector3d value, double divider)
{
double factor = 1d / divider;
value.X *= factor;
value.Y *= factor;
value.Z *= factor;
return value;
}
/// <summary>
/// Cross product between two vectors
/// </summary>
public static Vector3d operator %(Vector3d value1, Vector3d value2)
{
return Cross(value1, value2);
}
/// <summary>
/// Implicit casting for Vector3 > Vector3d
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static implicit operator Vector3d(Vector3 value)
{
return new Vector3d(value);
}
#endregion Operators
/// <summary>A vector with a value of 0,0,0</summary>
public readonly static Vector3d Zero = new Vector3d();
/// <summary>A vector with a value of 1,1,1</summary>
public readonly static Vector3d One = new Vector3d();
/// <summary>A unit vector facing forward (X axis), value of 1,0,0</summary>
public readonly static Vector3d UnitX = new Vector3d(1d, 0d, 0d);
/// <summary>A unit vector facing left (Y axis), value of 0,1,0</summary>
public readonly static Vector3d UnitY = new Vector3d(0d, 1d, 0d);
/// <summary>A unit vector facing up (Z axis), value of 0,0,1</summary>
public readonly static Vector3d UnitZ = new Vector3d(0d, 0d, 1d);
}
}
| |
/*
* 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.Net;
using OpenMetaverse;
using OpenMetaverse.Packets;
using OpenMetaverse.StructuredData;
using OpenMetaverse.Messages.Linden;
namespace OpenSim.Region.ClientStack.Linden
{
public class EventQueueHelper
{
private EventQueueHelper() {} // no construction possible, it's an utility class
private static byte[] ulongToByteArray(ulong uLongValue)
{
// Reverse endianness of RegionHandle
return new byte[]
{
(byte)((uLongValue >> 56) % 256),
(byte)((uLongValue >> 48) % 256),
(byte)((uLongValue >> 40) % 256),
(byte)((uLongValue >> 32) % 256),
(byte)((uLongValue >> 24) % 256),
(byte)((uLongValue >> 16) % 256),
(byte)((uLongValue >> 8) % 256),
(byte)(uLongValue % 256)
};
}
// private static byte[] uintToByteArray(uint uIntValue)
// {
// byte[] result = new byte[4];
// Utils.UIntToBytesBig(uIntValue, result, 0);
// return result;
// }
public static OSD BuildEvent(string eventName, OSD eventBody)
{
OSDMap llsdEvent = new OSDMap(2);
llsdEvent.Add("message", new OSDString(eventName));
llsdEvent.Add("body", eventBody);
return llsdEvent;
}
public static OSD EnableSimulator(ulong handle, IPEndPoint endPoint, int regionSizeX, int regionSizeY)
{
OSDMap llsdSimInfo = new OSDMap(5);
llsdSimInfo.Add("Handle", new OSDBinary(ulongToByteArray(handle)));
llsdSimInfo.Add("IP", new OSDBinary(endPoint.Address.GetAddressBytes()));
llsdSimInfo.Add("Port", OSD.FromInteger(endPoint.Port));
llsdSimInfo.Add("RegionSizeX", OSD.FromUInteger((uint)regionSizeX));
llsdSimInfo.Add("RegionSizeY", OSD.FromUInteger((uint)regionSizeY));
OSDArray arr = new OSDArray(1);
arr.Add(llsdSimInfo);
OSDMap llsdBody = new OSDMap(1);
llsdBody.Add("SimulatorInfo", arr);
return BuildEvent("EnableSimulator", llsdBody);
}
public static OSD DisableSimulator(ulong handle)
{
//OSDMap llsdSimInfo = new OSDMap(1);
//llsdSimInfo.Add("Handle", new OSDBinary(regionHandleToByteArray(handle)));
//OSDArray arr = new OSDArray(1);
//arr.Add(llsdSimInfo);
OSDMap llsdBody = new OSDMap(0);
//llsdBody.Add("SimulatorInfo", arr);
return BuildEvent("DisableSimulator", llsdBody);
}
public static OSD CrossRegion(ulong handle, Vector3 pos, Vector3 lookAt,
IPEndPoint newRegionExternalEndPoint,
string capsURL, UUID agentID, UUID sessionID,
int regionSizeX, int regionSizeY)
{
OSDArray lookAtArr = new OSDArray(3);
lookAtArr.Add(OSD.FromReal(lookAt.X));
lookAtArr.Add(OSD.FromReal(lookAt.Y));
lookAtArr.Add(OSD.FromReal(lookAt.Z));
OSDArray positionArr = new OSDArray(3);
positionArr.Add(OSD.FromReal(pos.X));
positionArr.Add(OSD.FromReal(pos.Y));
positionArr.Add(OSD.FromReal(pos.Z));
OSDMap infoMap = new OSDMap(2);
infoMap.Add("LookAt", lookAtArr);
infoMap.Add("Position", positionArr);
OSDArray infoArr = new OSDArray(1);
infoArr.Add(infoMap);
OSDMap agentDataMap = new OSDMap(2);
agentDataMap.Add("AgentID", OSD.FromUUID(agentID));
agentDataMap.Add("SessionID", OSD.FromUUID(sessionID));
OSDArray agentDataArr = new OSDArray(1);
agentDataArr.Add(agentDataMap);
OSDMap regionDataMap = new OSDMap(6);
regionDataMap.Add("RegionHandle", OSD.FromBinary(ulongToByteArray(handle)));
regionDataMap.Add("SeedCapability", OSD.FromString(capsURL));
regionDataMap.Add("SimIP", OSD.FromBinary(newRegionExternalEndPoint.Address.GetAddressBytes()));
regionDataMap.Add("SimPort", OSD.FromInteger(newRegionExternalEndPoint.Port));
regionDataMap.Add("RegionSizeX", OSD.FromUInteger((uint)regionSizeX));
regionDataMap.Add("RegionSizeY", OSD.FromUInteger((uint)regionSizeY));
OSDArray regionDataArr = new OSDArray(1);
regionDataArr.Add(regionDataMap);
OSDMap llsdBody = new OSDMap(3);
llsdBody.Add("Info", infoArr);
llsdBody.Add("AgentData", agentDataArr);
llsdBody.Add("RegionData", regionDataArr);
return BuildEvent("CrossedRegion", llsdBody);
}
public static OSD TeleportFinishEvent(
ulong regionHandle, byte simAccess, IPEndPoint regionExternalEndPoint,
uint locationID, uint flags, string capsURL, UUID agentID,
int regionSizeX, int regionSizeY)
{
// not sure why flags get overwritten here
if ((flags & (uint)TeleportFlags.IsFlying) != 0)
flags = (uint)TeleportFlags.ViaLocation | (uint)TeleportFlags.IsFlying;
else
flags = (uint)TeleportFlags.ViaLocation;
OSDMap info = new OSDMap();
info.Add("AgentID", OSD.FromUUID(agentID));
info.Add("LocationID", OSD.FromInteger(4)); // TODO what is this?
info.Add("RegionHandle", OSD.FromBinary(ulongToByteArray(regionHandle)));
info.Add("SeedCapability", OSD.FromString(capsURL));
info.Add("SimAccess", OSD.FromInteger(simAccess));
info.Add("SimIP", OSD.FromBinary(regionExternalEndPoint.Address.GetAddressBytes()));
info.Add("SimPort", OSD.FromInteger(regionExternalEndPoint.Port));
// info.Add("TeleportFlags", OSD.FromULong(1L << 4)); // AgentManager.TeleportFlags.ViaLocation
info.Add("TeleportFlags", OSD.FromUInteger(flags));
info.Add("RegionSizeX", OSD.FromUInteger((uint)regionSizeX));
info.Add("RegionSizeY", OSD.FromUInteger((uint)regionSizeY));
OSDArray infoArr = new OSDArray();
infoArr.Add(info);
OSDMap body = new OSDMap();
body.Add("Info", infoArr);
return BuildEvent("TeleportFinish", body);
}
public static OSD ScriptRunningReplyEvent(UUID objectID, UUID itemID, bool running, bool mono)
{
OSDMap script = new OSDMap();
script.Add("ObjectID", OSD.FromUUID(objectID));
script.Add("ItemID", OSD.FromUUID(itemID));
script.Add("Running", OSD.FromBoolean(running));
script.Add("Mono", OSD.FromBoolean(mono));
OSDArray scriptArr = new OSDArray();
scriptArr.Add(script);
OSDMap body = new OSDMap();
body.Add("Script", scriptArr);
return BuildEvent("ScriptRunningReply", body);
}
public static OSD EstablishAgentCommunication(UUID agentID, string simIpAndPort, string seedcap,
ulong regionHandle, int regionSizeX, int regionSizeY)
{
OSDMap body = new OSDMap(6)
{
{"agent-id", new OSDUUID(agentID)},
{"sim-ip-and-port", new OSDString(simIpAndPort)},
{"seed-capability", new OSDString(seedcap)},
{"region-handle", OSD.FromULong(regionHandle)},
{"region-size-x", OSD.FromUInteger((uint)regionSizeX)},
{"region-size-y", OSD.FromUInteger((uint)regionSizeY)}
};
return BuildEvent("EstablishAgentCommunication", body);
}
public static OSD KeepAliveEvent()
{
return BuildEvent("FAKEEVENT", new OSDMap());
}
public static OSD AgentParams(UUID agentID, bool checkEstate, int godLevel, bool limitedToEstate)
{
OSDMap body = new OSDMap(4);
body.Add("agent_id", new OSDUUID(agentID));
body.Add("check_estate", new OSDInteger(checkEstate ? 1 : 0));
body.Add("god_level", new OSDInteger(godLevel));
body.Add("limited_to_estate", new OSDInteger(limitedToEstate ? 1 : 0));
return body;
}
public static OSD InstantMessageParams(UUID fromAgent, string message, UUID toAgent,
string fromName, byte dialog, uint timeStamp, bool offline, int parentEstateID,
Vector3 position, uint ttl, UUID transactionID, bool fromGroup, byte[] binaryBucket)
{
OSDMap messageParams = new OSDMap(15);
messageParams.Add("type", new OSDInteger((int)dialog));
OSDArray positionArray = new OSDArray(3);
positionArray.Add(OSD.FromReal(position.X));
positionArray.Add(OSD.FromReal(position.Y));
positionArray.Add(OSD.FromReal(position.Z));
messageParams.Add("position", positionArray);
messageParams.Add("region_id", new OSDUUID(UUID.Zero));
messageParams.Add("to_id", new OSDUUID(toAgent));
messageParams.Add("source", new OSDInteger(0));
OSDMap data = new OSDMap(1);
data.Add("binary_bucket", OSD.FromBinary(binaryBucket));
messageParams.Add("data", data);
messageParams.Add("message", new OSDString(message));
messageParams.Add("id", new OSDUUID(transactionID));
messageParams.Add("from_name", new OSDString(fromName));
messageParams.Add("timestamp", new OSDInteger((int)timeStamp));
messageParams.Add("offline", new OSDInteger(offline ? 1 : 0));
messageParams.Add("parent_estate_id", new OSDInteger(parentEstateID));
messageParams.Add("ttl", new OSDInteger((int)ttl));
messageParams.Add("from_id", new OSDUUID(fromAgent));
messageParams.Add("from_group", new OSDInteger(fromGroup ? 1 : 0));
return messageParams;
}
public static OSD InstantMessage(UUID fromAgent, string message, UUID toAgent,
string fromName, byte dialog, uint timeStamp, bool offline, int parentEstateID,
Vector3 position, uint ttl, UUID transactionID, bool fromGroup, byte[] binaryBucket,
bool checkEstate, int godLevel, bool limitedToEstate)
{
OSDMap im = new OSDMap(2);
im.Add("message_params", InstantMessageParams(fromAgent, message, toAgent,
fromName, dialog, timeStamp, offline, parentEstateID,
position, ttl, transactionID, fromGroup, binaryBucket));
im.Add("agent_params", AgentParams(fromAgent, checkEstate, godLevel, limitedToEstate));
return im;
}
public static OSD ChatterboxInvitation(UUID sessionID, string sessionName,
UUID fromAgent, string message, UUID toAgent, string fromName, byte dialog,
uint timeStamp, bool offline, int parentEstateID, Vector3 position,
uint ttl, UUID transactionID, bool fromGroup, byte[] binaryBucket)
{
OSDMap body = new OSDMap(5);
body.Add("session_id", new OSDUUID(sessionID));
body.Add("from_name", new OSDString(fromName));
body.Add("session_name", new OSDString(sessionName));
body.Add("from_id", new OSDUUID(fromAgent));
body.Add("instantmessage", InstantMessage(fromAgent, message, toAgent,
fromName, dialog, timeStamp, offline, parentEstateID, position,
ttl, transactionID, fromGroup, binaryBucket, true, 0, true));
OSDMap chatterboxInvitation = new OSDMap(2);
chatterboxInvitation.Add("message", new OSDString("ChatterBoxInvitation"));
chatterboxInvitation.Add("body", body);
return chatterboxInvitation;
}
public static OSD ChatterBoxSessionAgentListUpdates(UUID sessionID,
UUID agentID, bool canVoiceChat, bool isModerator, bool textMute)
{
OSDMap body = new OSDMap();
OSDMap agentUpdates = new OSDMap();
OSDMap infoDetail = new OSDMap();
OSDMap mutes = new OSDMap();
mutes.Add("text", OSD.FromBoolean(textMute));
infoDetail.Add("can_voice_chat", OSD.FromBoolean(canVoiceChat));
infoDetail.Add("is_moderator", OSD.FromBoolean(isModerator));
infoDetail.Add("mutes", mutes);
OSDMap info = new OSDMap();
info.Add("info", infoDetail);
agentUpdates.Add(agentID.ToString(), info);
body.Add("agent_updates", agentUpdates);
body.Add("session_id", OSD.FromUUID(sessionID));
body.Add("updates", new OSD());
OSDMap chatterBoxSessionAgentListUpdates = new OSDMap();
chatterBoxSessionAgentListUpdates.Add("message", OSD.FromString("ChatterBoxSessionAgentListUpdates"));
chatterBoxSessionAgentListUpdates.Add("body", body);
return chatterBoxSessionAgentListUpdates;
}
public static OSD GroupMembership(AgentGroupDataUpdatePacket groupUpdatePacket)
{
OSDMap groupUpdate = new OSDMap();
groupUpdate.Add("message", OSD.FromString("AgentGroupDataUpdate"));
OSDMap body = new OSDMap();
OSDArray agentData = new OSDArray();
OSDMap agentDataMap = new OSDMap();
agentDataMap.Add("AgentID", OSD.FromUUID(groupUpdatePacket.AgentData.AgentID));
agentData.Add(agentDataMap);
body.Add("AgentData", agentData);
OSDArray groupData = new OSDArray();
foreach (AgentGroupDataUpdatePacket.GroupDataBlock groupDataBlock in groupUpdatePacket.GroupData)
{
OSDMap groupDataMap = new OSDMap();
groupDataMap.Add("ListInProfile", OSD.FromBoolean(false));
groupDataMap.Add("GroupID", OSD.FromUUID(groupDataBlock.GroupID));
groupDataMap.Add("GroupInsigniaID", OSD.FromUUID(groupDataBlock.GroupInsigniaID));
groupDataMap.Add("Contribution", OSD.FromInteger(groupDataBlock.Contribution));
groupDataMap.Add("GroupPowers", OSD.FromBinary(ulongToByteArray(groupDataBlock.GroupPowers)));
groupDataMap.Add("GroupName", OSD.FromString(Utils.BytesToString(groupDataBlock.GroupName)));
groupDataMap.Add("AcceptNotices", OSD.FromBoolean(groupDataBlock.AcceptNotices));
groupData.Add(groupDataMap);
}
body.Add("GroupData", groupData);
groupUpdate.Add("body", body);
return groupUpdate;
}
public static OSD PlacesQuery(PlacesReplyPacket PlacesReply)
{
OSDMap placesReply = new OSDMap();
placesReply.Add("message", OSD.FromString("PlacesReplyMessage"));
OSDMap body = new OSDMap();
OSDArray agentData = new OSDArray();
OSDMap agentDataMap = new OSDMap();
agentDataMap.Add("AgentID", OSD.FromUUID(PlacesReply.AgentData.AgentID));
agentDataMap.Add("QueryID", OSD.FromUUID(PlacesReply.AgentData.QueryID));
agentDataMap.Add("TransactionID", OSD.FromUUID(PlacesReply.TransactionData.TransactionID));
agentData.Add(agentDataMap);
body.Add("AgentData", agentData);
OSDArray QueryData = new OSDArray();
foreach (PlacesReplyPacket.QueryDataBlock groupDataBlock in PlacesReply.QueryData)
{
OSDMap QueryDataMap = new OSDMap();
QueryDataMap.Add("ActualArea", OSD.FromInteger(groupDataBlock.ActualArea));
QueryDataMap.Add("BillableArea", OSD.FromInteger(groupDataBlock.BillableArea));
QueryDataMap.Add("Description", OSD.FromBinary(groupDataBlock.Desc));
QueryDataMap.Add("Dwell", OSD.FromInteger((int)groupDataBlock.Dwell));
QueryDataMap.Add("Flags", OSD.FromString(Convert.ToString(groupDataBlock.Flags)));
QueryDataMap.Add("GlobalX", OSD.FromInteger((int)groupDataBlock.GlobalX));
QueryDataMap.Add("GlobalY", OSD.FromInteger((int)groupDataBlock.GlobalY));
QueryDataMap.Add("GlobalZ", OSD.FromInteger((int)groupDataBlock.GlobalZ));
QueryDataMap.Add("Name", OSD.FromBinary(groupDataBlock.Name));
QueryDataMap.Add("OwnerID", OSD.FromUUID(groupDataBlock.OwnerID));
QueryDataMap.Add("SimName", OSD.FromBinary(groupDataBlock.SimName));
QueryDataMap.Add("SnapShotID", OSD.FromUUID(groupDataBlock.SnapshotID));
QueryDataMap.Add("ProductSku", OSD.FromInteger(0));
QueryDataMap.Add("Price", OSD.FromInteger(groupDataBlock.Price));
QueryData.Add(QueryDataMap);
}
body.Add("QueryData", QueryData);
placesReply.Add("QueryData[]", body);
return placesReply;
}
public static OSD ParcelProperties(ParcelPropertiesMessage parcelPropertiesMessage)
{
OSDMap message = new OSDMap();
message.Add("message", OSD.FromString("ParcelProperties"));
OSD message_body = parcelPropertiesMessage.Serialize();
message.Add("body", message_body);
return message;
}
public static OSD partPhysicsProperties(uint localID, byte physhapetype,
float density, float friction, float bounce, float gravmod)
{
OSDMap physinfo = new OSDMap(6);
physinfo["LocalID"] = localID;
physinfo["Density"] = density;
physinfo["Friction"] = friction;
physinfo["GravityMultiplier"] = gravmod;
physinfo["Restitution"] = bounce;
physinfo["PhysicsShapeType"] = (int)physhapetype;
OSDArray array = new OSDArray(1);
array.Add(physinfo);
OSDMap llsdBody = new OSDMap(1);
llsdBody.Add("ObjectData", array);
return BuildEvent("ObjectPhysicsProperties", llsdBody);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Abp.Application.Features;
using Abp.Authorization.Roles;
using Abp.Configuration;
using Abp.Domain.Repositories;
using Abp.Domain.Services;
using Abp.Domain.Uow;
using Abp.IdentityFramework;
using Abp.Localization;
using Abp.MultiTenancy;
using Abp.Organizations;
using Abp.Runtime.Caching;
using Abp.Runtime.Security;
using Abp.Runtime.Session;
using Abp.Zero;
using Abp.Zero.Configuration;
using Microsoft.AspNet.Identity;
namespace Abp.Authorization.Users
{
/// <summary>
/// Extends <see cref="UserManager{TUser,TKey}"/> of ASP.NET Identity Framework.
/// </summary>
public abstract class AbpUserManager<TRole, TUser>
: UserManager<TUser, long>,
IDomainService
where TRole : AbpRole<TUser>, new()
where TUser : AbpUser<TUser>
{
protected IUserPermissionStore<TUser> UserPermissionStore
{
get
{
if (!(Store is IUserPermissionStore<TUser>))
{
throw new AbpException("Store is not IUserPermissionStore");
}
return Store as IUserPermissionStore<TUser>;
}
}
public ILocalizationManager LocalizationManager { get; }
public IAbpSession AbpSession { get; set; }
public FeatureDependencyContext FeatureDependencyContext { get; set; }
protected AbpRoleManager<TRole, TUser> RoleManager { get; }
public AbpUserStore<TRole, TUser> AbpStore { get; }
private readonly IPermissionManager _permissionManager;
private readonly IUnitOfWorkManager _unitOfWorkManager;
private readonly ICacheManager _cacheManager;
private readonly IRepository<OrganizationUnit, long> _organizationUnitRepository;
private readonly IRepository<UserOrganizationUnit, long> _userOrganizationUnitRepository;
private readonly IOrganizationUnitSettings _organizationUnitSettings;
private readonly ISettingManager _settingManager;
protected AbpUserManager(
AbpUserStore<TRole, TUser> userStore,
AbpRoleManager<TRole, TUser> roleManager,
IPermissionManager permissionManager,
IUnitOfWorkManager unitOfWorkManager,
ICacheManager cacheManager,
IRepository<OrganizationUnit, long> organizationUnitRepository,
IRepository<UserOrganizationUnit, long> userOrganizationUnitRepository,
IOrganizationUnitSettings organizationUnitSettings,
ILocalizationManager localizationManager,
IdentityEmailMessageService emailService,
ISettingManager settingManager,
IUserTokenProviderAccessor userTokenProviderAccessor)
: base(userStore)
{
AbpStore = userStore;
RoleManager = roleManager;
LocalizationManager = localizationManager;
_settingManager = settingManager;
_permissionManager = permissionManager;
_unitOfWorkManager = unitOfWorkManager;
_cacheManager = cacheManager;
_organizationUnitRepository = organizationUnitRepository;
_userOrganizationUnitRepository = userOrganizationUnitRepository;
_organizationUnitSettings = organizationUnitSettings;
AbpSession = NullAbpSession.Instance;
UserLockoutEnabledByDefault = true;
DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
MaxFailedAccessAttemptsBeforeLockout = 5;
EmailService = emailService;
UserTokenProvider = userTokenProviderAccessor.GetUserTokenProviderOrNull<TUser>();
}
public override async Task<IdentityResult> CreateAsync(TUser user)
{
var result = await CheckDuplicateUsernameOrEmailAddressAsync(user.Id, user.UserName, user.EmailAddress);
if (!result.Succeeded)
{
return result;
}
var tenantId = GetCurrentTenantId();
if (tenantId.HasValue && !user.TenantId.HasValue)
{
user.TenantId = tenantId.Value;
}
return await base.CreateAsync(user);
}
/// <summary>
/// Check whether a user is granted for a permission.
/// </summary>
/// <param name="userId">User id</param>
/// <param name="permissionName">Permission name</param>
public virtual async Task<bool> IsGrantedAsync(long userId, string permissionName)
{
return await IsGrantedAsync(
userId,
_permissionManager.GetPermission(permissionName)
);
}
/// <summary>
/// Check whether a user is granted for a permission.
/// </summary>
/// <param name="user">User</param>
/// <param name="permission">Permission</param>
public virtual Task<bool> IsGrantedAsync(TUser user, Permission permission)
{
return IsGrantedAsync(user.Id, permission);
}
/// <summary>
/// Check whether a user is granted for a permission.
/// </summary>
/// <param name="userId">User id</param>
/// <param name="permission">Permission</param>
public virtual async Task<bool> IsGrantedAsync(long userId, Permission permission)
{
//Check for multi-tenancy side
if (!permission.MultiTenancySides.HasFlag(AbpSession.MultiTenancySide))
{
return false;
}
//Check for depended features
if (permission.FeatureDependency != null && AbpSession.MultiTenancySide == MultiTenancySides.Tenant)
{
if (!await permission.FeatureDependency.IsSatisfiedAsync(FeatureDependencyContext))
{
return false;
}
}
//Get cached user permissions
var cacheItem = await GetUserPermissionCacheItemAsync(userId);
if (cacheItem == null)
{
return false;
}
//Check for user-specific value
if (cacheItem.GrantedPermissions.Contains(permission.Name))
{
return true;
}
if (cacheItem.ProhibitedPermissions.Contains(permission.Name))
{
return false;
}
//Check for roles
foreach (var roleId in cacheItem.RoleIds)
{
if (await RoleManager.IsGrantedAsync(roleId, permission))
{
return true;
}
}
return false;
}
/// <summary>
/// Gets granted permissions for a user.
/// </summary>
/// <param name="user">Role</param>
/// <returns>List of granted permissions</returns>
public virtual async Task<IReadOnlyList<Permission>> GetGrantedPermissionsAsync(TUser user)
{
var permissionList = new List<Permission>();
foreach (var permission in _permissionManager.GetAllPermissions())
{
if (await IsGrantedAsync(user.Id, permission))
{
permissionList.Add(permission);
}
}
return permissionList;
}
/// <summary>
/// Sets all granted permissions of a user at once.
/// Prohibits all other permissions.
/// </summary>
/// <param name="user">The user</param>
/// <param name="permissions">Permissions</param>
public virtual async Task SetGrantedPermissionsAsync(TUser user, IEnumerable<Permission> permissions)
{
var oldPermissions = await GetGrantedPermissionsAsync(user);
var newPermissions = permissions.ToArray();
foreach (var permission in oldPermissions.Where(p => !newPermissions.Contains(p)))
{
await ProhibitPermissionAsync(user, permission);
}
foreach (var permission in newPermissions.Where(p => !oldPermissions.Contains(p)))
{
await GrantPermissionAsync(user, permission);
}
}
/// <summary>
/// Prohibits all permissions for a user.
/// </summary>
/// <param name="user">User</param>
public async Task ProhibitAllPermissionsAsync(TUser user)
{
foreach (var permission in _permissionManager.GetAllPermissions())
{
await ProhibitPermissionAsync(user, permission);
}
}
/// <summary>
/// Resets all permission settings for a user.
/// It removes all permission settings for the user.
/// User will have permissions according to his roles.
/// This method does not prohibit all permissions.
/// For that, use <see cref="ProhibitAllPermissionsAsync"/>.
/// </summary>
/// <param name="user">User</param>
public async Task ResetAllPermissionsAsync(TUser user)
{
await UserPermissionStore.RemoveAllPermissionSettingsAsync(user);
}
/// <summary>
/// Grants a permission for a user if not already granted.
/// </summary>
/// <param name="user">User</param>
/// <param name="permission">Permission</param>
public virtual async Task GrantPermissionAsync(TUser user, Permission permission)
{
await UserPermissionStore.RemovePermissionAsync(user, new PermissionGrantInfo(permission.Name, false));
if (await IsGrantedAsync(user.Id, permission))
{
return;
}
await UserPermissionStore.AddPermissionAsync(user, new PermissionGrantInfo(permission.Name, true));
}
/// <summary>
/// Prohibits a permission for a user if it's granted.
/// </summary>
/// <param name="user">User</param>
/// <param name="permission">Permission</param>
public virtual async Task ProhibitPermissionAsync(TUser user, Permission permission)
{
await UserPermissionStore.RemovePermissionAsync(user, new PermissionGrantInfo(permission.Name, true));
if (!await IsGrantedAsync(user.Id, permission))
{
return;
}
await UserPermissionStore.AddPermissionAsync(user, new PermissionGrantInfo(permission.Name, false));
}
public virtual async Task<TUser> FindByNameOrEmailAsync(string userNameOrEmailAddress)
{
return await AbpStore.FindByNameOrEmailAsync(userNameOrEmailAddress);
}
public virtual Task<List<TUser>> FindAllAsync(UserLoginInfo login)
{
return AbpStore.FindAllAsync(login);
}
/// <summary>
/// Gets a user by given id.
/// Throws exception if no user found with given id.
/// </summary>
/// <param name="userId">User id</param>
/// <returns>User</returns>
/// <exception cref="AbpException">Throws exception if no user found with given id</exception>
public virtual async Task<TUser> GetUserByIdAsync(long userId)
{
var user = await FindByIdAsync(userId);
if (user == null)
{
throw new AbpException("There is no user with id: " + userId);
}
return user;
}
public async override Task<ClaimsIdentity> CreateIdentityAsync(TUser user, string authenticationType)
{
var identity = await base.CreateIdentityAsync(user, authenticationType);
if (user.TenantId.HasValue)
{
identity.AddClaim(new Claim(AbpClaimTypes.TenantId, user.TenantId.Value.ToString(CultureInfo.InvariantCulture)));
}
return identity;
}
public async override Task<IdentityResult> UpdateAsync(TUser user)
{
var result = await CheckDuplicateUsernameOrEmailAddressAsync(user.Id, user.UserName, user.EmailAddress);
if (!result.Succeeded)
{
return result;
}
//Admin user's username can not be changed!
if (user.UserName != AbpUser<TUser>.AdminUserName)
{
if ((await GetOldUserNameAsync(user.Id)) == AbpUser<TUser>.AdminUserName)
{
return AbpIdentityResult.Failed(string.Format(L("CanNotRenameAdminUser"), AbpUser<TUser>.AdminUserName));
}
}
return await base.UpdateAsync(user);
}
public async override Task<IdentityResult> DeleteAsync(TUser user)
{
if (user.UserName == AbpUser<TUser>.AdminUserName)
{
return AbpIdentityResult.Failed(string.Format(L("CanNotDeleteAdminUser"), AbpUser<TUser>.AdminUserName));
}
return await base.DeleteAsync(user);
}
public virtual async Task<IdentityResult> ChangePasswordAsync(TUser user, string newPassword)
{
var result = await PasswordValidator.ValidateAsync(newPassword);
if (!result.Succeeded)
{
return result;
}
await AbpStore.SetPasswordHashAsync(user, PasswordHasher.HashPassword(newPassword));
return IdentityResult.Success;
}
public virtual async Task<IdentityResult> CheckDuplicateUsernameOrEmailAddressAsync(long? expectedUserId, string userName, string emailAddress)
{
var user = (await FindByNameAsync(userName));
if (user != null && user.Id != expectedUserId)
{
return AbpIdentityResult.Failed(string.Format(L("Identity.DuplicateUserName"), userName));
}
user = (await FindByEmailAsync(emailAddress));
if (user != null && user.Id != expectedUserId)
{
return AbpIdentityResult.Failed(string.Format(L("Identity.DuplicateEmail"), emailAddress));
}
return IdentityResult.Success;
}
public virtual async Task<IdentityResult> SetRoles(TUser user, string[] roleNames)
{
//Remove from removed roles
foreach (var userRole in user.Roles.ToList())
{
var role = await RoleManager.FindByIdAsync(userRole.RoleId);
if (roleNames.All(roleName => role.Name != roleName))
{
var result = await RemoveFromRoleAsync(user.Id, role.Name);
if (!result.Succeeded)
{
return result;
}
}
}
//Add to added roles
foreach (var roleName in roleNames)
{
var role = await RoleManager.GetRoleByNameAsync(roleName);
if (user.Roles.All(ur => ur.RoleId != role.Id))
{
var result = await AddToRoleAsync(user.Id, roleName);
if (!result.Succeeded)
{
return result;
}
}
}
return IdentityResult.Success;
}
public virtual async Task<bool> IsInOrganizationUnitAsync(long userId, long ouId)
{
return await IsInOrganizationUnitAsync(
await GetUserByIdAsync(userId),
await _organizationUnitRepository.GetAsync(ouId)
);
}
public virtual async Task<bool> IsInOrganizationUnitAsync(TUser user, OrganizationUnit ou)
{
return await _userOrganizationUnitRepository.CountAsync(uou =>
uou.UserId == user.Id && uou.OrganizationUnitId == ou.Id
) > 0;
}
public virtual async Task AddToOrganizationUnitAsync(long userId, long ouId)
{
await AddToOrganizationUnitAsync(
await GetUserByIdAsync(userId),
await _organizationUnitRepository.GetAsync(ouId)
);
}
public virtual async Task AddToOrganizationUnitAsync(TUser user, OrganizationUnit ou)
{
var currentOus = await GetOrganizationUnitsAsync(user);
if (currentOus.Any(cou => cou.Id == ou.Id))
{
return;
}
await CheckMaxUserOrganizationUnitMembershipCountAsync(user.TenantId, currentOus.Count + 1);
await _userOrganizationUnitRepository.InsertAsync(new UserOrganizationUnit(user.TenantId, user.Id, ou.Id));
}
public virtual async Task RemoveFromOrganizationUnitAsync(long userId, long ouId)
{
await RemoveFromOrganizationUnitAsync(
await GetUserByIdAsync(userId),
await _organizationUnitRepository.GetAsync(ouId)
);
}
public virtual async Task RemoveFromOrganizationUnitAsync(TUser user, OrganizationUnit ou)
{
await _userOrganizationUnitRepository.DeleteAsync(uou => uou.UserId == user.Id && uou.OrganizationUnitId == ou.Id);
}
public virtual async Task SetOrganizationUnitsAsync(long userId, params long[] organizationUnitIds)
{
await SetOrganizationUnitsAsync(
await GetUserByIdAsync(userId),
organizationUnitIds
);
}
private async Task CheckMaxUserOrganizationUnitMembershipCountAsync(int? tenantId, int requestedCount)
{
var maxCount = await _organizationUnitSettings.GetMaxUserMembershipCountAsync(tenantId);
if (requestedCount > maxCount)
{
throw new AbpException(string.Format("Can not set more than {0} organization unit for a user!", maxCount));
}
}
public virtual async Task SetOrganizationUnitsAsync(TUser user, params long[] organizationUnitIds)
{
if (organizationUnitIds == null)
{
organizationUnitIds = new long[0];
}
await CheckMaxUserOrganizationUnitMembershipCountAsync(user.TenantId, organizationUnitIds.Length);
var currentOus = await GetOrganizationUnitsAsync(user);
//Remove from removed OUs
foreach (var currentOu in currentOus)
{
if (!organizationUnitIds.Contains(currentOu.Id))
{
await RemoveFromOrganizationUnitAsync(user, currentOu);
}
}
//Add to added OUs
foreach (var organizationUnitId in organizationUnitIds)
{
if (currentOus.All(ou => ou.Id != organizationUnitId))
{
await AddToOrganizationUnitAsync(
user,
await _organizationUnitRepository.GetAsync(organizationUnitId)
);
}
}
}
[UnitOfWork]
public virtual Task<List<OrganizationUnit>> GetOrganizationUnitsAsync(TUser user)
{
var query = from uou in _userOrganizationUnitRepository.GetAll()
join ou in _organizationUnitRepository.GetAll() on uou.OrganizationUnitId equals ou.Id
where uou.UserId == user.Id
select ou;
return Task.FromResult(query.ToList());
}
[UnitOfWork]
public virtual Task<List<TUser>> GetUsersInOrganizationUnit(OrganizationUnit organizationUnit, bool includeChildren = false)
{
if (!includeChildren)
{
var query = from uou in _userOrganizationUnitRepository.GetAll()
join user in AbpStore.Users on uou.UserId equals user.Id
where uou.OrganizationUnitId == organizationUnit.Id
select user;
return Task.FromResult(query.ToList());
}
else
{
var query = from uou in _userOrganizationUnitRepository.GetAll()
join user in AbpStore.Users on uou.UserId equals user.Id
join ou in _organizationUnitRepository.GetAll() on uou.OrganizationUnitId equals ou.Id
where ou.Code.StartsWith(organizationUnit.Code)
select user;
return Task.FromResult(query.ToList());
}
}
public virtual void RegisterTwoFactorProviders(int? tenantId)
{
TwoFactorProviders.Clear();
if (!IsTrue(AbpZeroSettingNames.UserManagement.TwoFactorLogin.IsEnabled, tenantId))
{
return;
}
if (EmailService != null &&
IsTrue(AbpZeroSettingNames.UserManagement.TwoFactorLogin.IsEmailProviderEnabled, tenantId))
{
RegisterTwoFactorProvider(
L("Email"),
new EmailTokenProvider<TUser, long>
{
Subject = L("EmailSecurityCodeSubject"),
BodyFormat = L("EmailSecurityCodeBody")
}
);
}
if (SmsService != null &&
IsTrue(AbpZeroSettingNames.UserManagement.TwoFactorLogin.IsSmsProviderEnabled, tenantId))
{
RegisterTwoFactorProvider(
L("Sms"),
new PhoneNumberTokenProvider<TUser, long>
{
MessageFormat = L("SmsSecurityCodeMessage")
}
);
}
}
public virtual void InitializeLockoutSettings(int? tenantId)
{
UserLockoutEnabledByDefault = IsTrue(AbpZeroSettingNames.UserManagement.UserLockOut.IsEnabled, tenantId);
DefaultAccountLockoutTimeSpan = TimeSpan.FromSeconds(GetSettingValue<int>(AbpZeroSettingNames.UserManagement.UserLockOut.DefaultAccountLockoutSeconds, tenantId));
MaxFailedAccessAttemptsBeforeLockout = GetSettingValue<int>(AbpZeroSettingNames.UserManagement.UserLockOut.MaxFailedAccessAttemptsBeforeLockout, tenantId);
}
public override async Task<IList<string>> GetValidTwoFactorProvidersAsync(long userId)
{
var user = await GetUserByIdAsync(userId);
RegisterTwoFactorProviders(user.TenantId);
return await base.GetValidTwoFactorProvidersAsync(userId);
}
public override async Task<IdentityResult> NotifyTwoFactorTokenAsync(long userId, string twoFactorProvider, string token)
{
var user = await GetUserByIdAsync(userId);
RegisterTwoFactorProviders(user.TenantId);
return await base.NotifyTwoFactorTokenAsync(userId, twoFactorProvider, token);
}
public override async Task<string> GenerateTwoFactorTokenAsync(long userId, string twoFactorProvider)
{
var user = await GetUserByIdAsync(userId);
RegisterTwoFactorProviders(user.TenantId);
return await base.GenerateTwoFactorTokenAsync(userId, twoFactorProvider);
}
public override async Task<bool> VerifyTwoFactorTokenAsync(long userId, string twoFactorProvider, string token)
{
var user = await GetUserByIdAsync(userId);
RegisterTwoFactorProviders(user.TenantId);
return await base.VerifyTwoFactorTokenAsync(userId, twoFactorProvider, token);
}
protected virtual Task<string> GetOldUserNameAsync(long userId)
{
return AbpStore.GetUserNameFromDatabaseAsync(userId);
}
private async Task<UserPermissionCacheItem> GetUserPermissionCacheItemAsync(long userId)
{
var cacheKey = userId + "@" + (GetCurrentTenantId() ?? 0);
return await _cacheManager.GetUserPermissionCache().GetAsync(cacheKey, async () =>
{
var user = await FindByIdAsync(userId);
if (user == null)
{
return null;
}
var newCacheItem = new UserPermissionCacheItem(userId);
foreach (var roleName in await GetRolesAsync(userId))
{
newCacheItem.RoleIds.Add((await RoleManager.GetRoleByNameAsync(roleName)).Id);
}
foreach (var permissionInfo in await UserPermissionStore.GetPermissionsAsync(userId))
{
if (permissionInfo.IsGranted)
{
newCacheItem.GrantedPermissions.Add(permissionInfo.Name);
}
else
{
newCacheItem.ProhibitedPermissions.Add(permissionInfo.Name);
}
}
return newCacheItem;
});
}
private bool IsTrue(string settingName, int? tenantId)
{
return GetSettingValue<bool>(settingName, tenantId);
}
private T GetSettingValue<T>(string settingName, int? tenantId) where T : struct
{
return tenantId == null
? _settingManager.GetSettingValueForApplication<T>(settingName)
: _settingManager.GetSettingValueForTenant<T>(settingName, tenantId.Value);
}
private string L(string name)
{
return LocalizationManager.GetString(AbpZeroConsts.LocalizationSourceName, name);
}
private int? GetCurrentTenantId()
{
if (_unitOfWorkManager.Current != null)
{
return _unitOfWorkManager.Current.GetTenantId();
}
return AbpSession.TenantId;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Reactive.Linq;
using System.Reactive.Threading.Tasks;
using MS.Core;
namespace System.IO.IsolatedStorage
{
public static class __IsolatedStorageFileStream
{
public static IObservable<System.Reactive.Unit> Flush(
this IObservable<System.IO.IsolatedStorage.IsolatedStorageFileStream> IsolatedStorageFileStreamValue)
{
return
Observable.Do(IsolatedStorageFileStreamValue,
(IsolatedStorageFileStreamValueLambda) => IsolatedStorageFileStreamValueLambda.Flush()).ToUnit();
}
public static IObservable<System.Reactive.Unit> Flush(
this IObservable<System.IO.IsolatedStorage.IsolatedStorageFileStream> IsolatedStorageFileStreamValue,
IObservable<System.Boolean> flushToDisk)
{
return ObservableExt.ZipExecute(IsolatedStorageFileStreamValue, flushToDisk,
(IsolatedStorageFileStreamValueLambda, flushToDiskLambda) =>
IsolatedStorageFileStreamValueLambda.Flush(flushToDiskLambda));
}
public static IObservable<System.Reactive.Unit> SetLength(
this IObservable<System.IO.IsolatedStorage.IsolatedStorageFileStream> IsolatedStorageFileStreamValue,
IObservable<System.Int64> value)
{
return ObservableExt.ZipExecute(IsolatedStorageFileStreamValue, value,
(IsolatedStorageFileStreamValueLambda, valueLambda) =>
IsolatedStorageFileStreamValueLambda.SetLength(valueLambda));
}
public static IObservable<System.Reactive.Unit> Lock(
this IObservable<System.IO.IsolatedStorage.IsolatedStorageFileStream> IsolatedStorageFileStreamValue,
IObservable<System.Int64> position, IObservable<System.Int64> length)
{
return ObservableExt.ZipExecute(IsolatedStorageFileStreamValue, position, length,
(IsolatedStorageFileStreamValueLambda, positionLambda, lengthLambda) =>
IsolatedStorageFileStreamValueLambda.Lock(positionLambda, lengthLambda));
}
public static IObservable<System.Reactive.Unit> Unlock(
this IObservable<System.IO.IsolatedStorage.IsolatedStorageFileStream> IsolatedStorageFileStreamValue,
IObservable<System.Int64> position, IObservable<System.Int64> length)
{
return ObservableExt.ZipExecute(IsolatedStorageFileStreamValue, position, length,
(IsolatedStorageFileStreamValueLambda, positionLambda, lengthLambda) =>
IsolatedStorageFileStreamValueLambda.Unlock(positionLambda, lengthLambda));
}
public static IObservable<System.Int32> Read(
this IObservable<System.IO.IsolatedStorage.IsolatedStorageFileStream> IsolatedStorageFileStreamValue,
IObservable<System.Byte[]> buffer, IObservable<System.Int32> offset, IObservable<System.Int32> count)
{
return Observable.Zip(IsolatedStorageFileStreamValue, buffer, offset, count,
(IsolatedStorageFileStreamValueLambda, bufferLambda, offsetLambda, countLambda) =>
IsolatedStorageFileStreamValueLambda.Read(bufferLambda, offsetLambda, countLambda));
}
public static IObservable<System.Int32> ReadByte(
this IObservable<System.IO.IsolatedStorage.IsolatedStorageFileStream> IsolatedStorageFileStreamValue)
{
return Observable.Select(IsolatedStorageFileStreamValue,
(IsolatedStorageFileStreamValueLambda) => IsolatedStorageFileStreamValueLambda.ReadByte());
}
public static IObservable<System.Int64> Seek(
this IObservable<System.IO.IsolatedStorage.IsolatedStorageFileStream> IsolatedStorageFileStreamValue,
IObservable<System.Int64> offset, IObservable<System.IO.SeekOrigin> origin)
{
return Observable.Zip(IsolatedStorageFileStreamValue, offset, origin,
(IsolatedStorageFileStreamValueLambda, offsetLambda, originLambda) =>
IsolatedStorageFileStreamValueLambda.Seek(offsetLambda, originLambda));
}
public static IObservable<System.Reactive.Unit> Write(
this IObservable<System.IO.IsolatedStorage.IsolatedStorageFileStream> IsolatedStorageFileStreamValue,
IObservable<System.Byte[]> buffer, IObservable<System.Int32> offset, IObservable<System.Int32> count)
{
return ObservableExt.ZipExecute(IsolatedStorageFileStreamValue, buffer, offset, count,
(IsolatedStorageFileStreamValueLambda, bufferLambda, offsetLambda, countLambda) =>
IsolatedStorageFileStreamValueLambda.Write(bufferLambda, offsetLambda, countLambda));
}
public static IObservable<System.Reactive.Unit> WriteByte(
this IObservable<System.IO.IsolatedStorage.IsolatedStorageFileStream> IsolatedStorageFileStreamValue,
IObservable<System.Byte> value)
{
return ObservableExt.ZipExecute(IsolatedStorageFileStreamValue, value,
(IsolatedStorageFileStreamValueLambda, valueLambda) =>
IsolatedStorageFileStreamValueLambda.WriteByte(valueLambda));
}
public static IObservable<System.IAsyncResult> BeginRead(
this IObservable<System.IO.IsolatedStorage.IsolatedStorageFileStream> IsolatedStorageFileStreamValue,
IObservable<System.Byte[]> buffer, IObservable<System.Int32> offset, IObservable<System.Int32> numBytes,
IObservable<System.AsyncCallback> userCallback, IObservable<System.Object> stateObject)
{
return Observable.Zip(IsolatedStorageFileStreamValue, buffer, offset, numBytes, userCallback, stateObject,
(IsolatedStorageFileStreamValueLambda, bufferLambda, offsetLambda, numBytesLambda, userCallbackLambda,
stateObjectLambda) =>
IsolatedStorageFileStreamValueLambda.BeginRead(bufferLambda, offsetLambda, numBytesLambda,
userCallbackLambda, stateObjectLambda));
}
public static IObservable<System.Int32> EndRead(
this IObservable<System.IO.IsolatedStorage.IsolatedStorageFileStream> IsolatedStorageFileStreamValue,
IObservable<System.IAsyncResult> asyncResult)
{
return Observable.Zip(IsolatedStorageFileStreamValue, asyncResult,
(IsolatedStorageFileStreamValueLambda, asyncResultLambda) =>
IsolatedStorageFileStreamValueLambda.EndRead(asyncResultLambda));
}
public static IObservable<System.IAsyncResult> BeginWrite(
this IObservable<System.IO.IsolatedStorage.IsolatedStorageFileStream> IsolatedStorageFileStreamValue,
IObservable<System.Byte[]> buffer, IObservable<System.Int32> offset, IObservable<System.Int32> numBytes,
IObservable<System.AsyncCallback> userCallback, IObservable<System.Object> stateObject)
{
return Observable.Zip(IsolatedStorageFileStreamValue, buffer, offset, numBytes, userCallback, stateObject,
(IsolatedStorageFileStreamValueLambda, bufferLambda, offsetLambda, numBytesLambda, userCallbackLambda,
stateObjectLambda) =>
IsolatedStorageFileStreamValueLambda.BeginWrite(bufferLambda, offsetLambda, numBytesLambda,
userCallbackLambda, stateObjectLambda));
}
public static IObservable<System.Reactive.Unit> EndWrite(
this IObservable<System.IO.IsolatedStorage.IsolatedStorageFileStream> IsolatedStorageFileStreamValue,
IObservable<System.IAsyncResult> asyncResult)
{
return ObservableExt.ZipExecute(IsolatedStorageFileStreamValue, asyncResult,
(IsolatedStorageFileStreamValueLambda, asyncResultLambda) =>
IsolatedStorageFileStreamValueLambda.EndWrite(asyncResultLambda));
}
public static IObservable<System.Boolean> get_CanRead(
this IObservable<System.IO.IsolatedStorage.IsolatedStorageFileStream> IsolatedStorageFileStreamValue)
{
return Observable.Select(IsolatedStorageFileStreamValue,
(IsolatedStorageFileStreamValueLambda) => IsolatedStorageFileStreamValueLambda.CanRead);
}
public static IObservable<System.Boolean> get_CanWrite(
this IObservable<System.IO.IsolatedStorage.IsolatedStorageFileStream> IsolatedStorageFileStreamValue)
{
return Observable.Select(IsolatedStorageFileStreamValue,
(IsolatedStorageFileStreamValueLambda) => IsolatedStorageFileStreamValueLambda.CanWrite);
}
public static IObservable<System.Boolean> get_CanSeek(
this IObservable<System.IO.IsolatedStorage.IsolatedStorageFileStream> IsolatedStorageFileStreamValue)
{
return Observable.Select(IsolatedStorageFileStreamValue,
(IsolatedStorageFileStreamValueLambda) => IsolatedStorageFileStreamValueLambda.CanSeek);
}
public static IObservable<System.Boolean> get_IsAsync(
this IObservable<System.IO.IsolatedStorage.IsolatedStorageFileStream> IsolatedStorageFileStreamValue)
{
return Observable.Select(IsolatedStorageFileStreamValue,
(IsolatedStorageFileStreamValueLambda) => IsolatedStorageFileStreamValueLambda.IsAsync);
}
public static IObservable<System.Int64> get_Length(
this IObservable<System.IO.IsolatedStorage.IsolatedStorageFileStream> IsolatedStorageFileStreamValue)
{
return Observable.Select(IsolatedStorageFileStreamValue,
(IsolatedStorageFileStreamValueLambda) => IsolatedStorageFileStreamValueLambda.Length);
}
public static IObservable<System.Int64> get_Position(
this IObservable<System.IO.IsolatedStorage.IsolatedStorageFileStream> IsolatedStorageFileStreamValue)
{
return Observable.Select(IsolatedStorageFileStreamValue,
(IsolatedStorageFileStreamValueLambda) => IsolatedStorageFileStreamValueLambda.Position);
}
public static IObservable<System.IntPtr> get_Handle(
this IObservable<System.IO.IsolatedStorage.IsolatedStorageFileStream> IsolatedStorageFileStreamValue)
{
return Observable.Select(IsolatedStorageFileStreamValue,
(IsolatedStorageFileStreamValueLambda) => IsolatedStorageFileStreamValueLambda.Handle);
}
public static IObservable<Microsoft.Win32.SafeHandles.SafeFileHandle> get_SafeFileHandle(
this IObservable<System.IO.IsolatedStorage.IsolatedStorageFileStream> IsolatedStorageFileStreamValue)
{
return Observable.Select(IsolatedStorageFileStreamValue,
(IsolatedStorageFileStreamValueLambda) => IsolatedStorageFileStreamValueLambda.SafeFileHandle);
}
public static IObservable<System.Reactive.Unit> set_Position(
this IObservable<System.IO.IsolatedStorage.IsolatedStorageFileStream> IsolatedStorageFileStreamValue,
IObservable<System.Int64> value)
{
return ObservableExt.ZipExecute(IsolatedStorageFileStreamValue, value,
(IsolatedStorageFileStreamValueLambda, valueLambda) =>
IsolatedStorageFileStreamValueLambda.Position = valueLambda);
}
}
}
| |
// Copyright 2011 Microsoft Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace Microsoft.Data.OData
{
#region Namespaces
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
#if ODATALIB_ASYNC
using System.Threading.Tasks;
#endif
#endregion Namespaces
/// <summary>
/// Write-only stream which buffers all synchronous write operations until FlushAsync is called.
/// </summary>
internal sealed class AsyncBufferedStream : Stream
{
/// <summary>
/// The stream being wrapped.
/// </summary>
private readonly Stream innerStream;
/// <summary>
/// Queue of buffers to write.
/// </summary>
private Queue<DataBuffer> bufferQueue;
/// <summary>
/// The last buffer in the bufferQueue. This is the buffer we're writing into.
/// </summary>
private DataBuffer bufferToAppendTo;
/// <summary>
/// Constructor
/// </summary>
/// <param name="stream">The underlying async stream to wrap. Note that only asynchronous write operation will be invoked on this stream.</param>
internal AsyncBufferedStream(Stream stream)
{
DebugUtils.CheckNoExternalCallers();
Debug.Assert(stream != null, "stream != null");
this.innerStream = stream;
this.bufferQueue = new Queue<DataBuffer>();
}
/// <summary>
/// Determines if the stream can read - this one cannot
/// </summary>
public override bool CanRead
{
get { return false; }
}
/// <summary>
/// Determines if the stream can seek - this one cannot
/// </summary>
public override bool CanSeek
{
get { return false; }
}
/// <summary>
/// Determines if the stream can write - this one can
/// </summary>
public override bool CanWrite
{
get { return true; }
}
/// <summary>
/// Returns the length of the stream, which this implementation doesn't support.
/// </summary>
public override long Length
{
get
{
Debug.Assert(false, "Should never get here.");
throw new NotSupportedException();
}
}
/// <summary>
/// Gets or sets the position in the stream, this stream doesn't support seeking, so position is also unsupported.
/// </summary>
public override long Position
{
get
{
Debug.Assert(false, "Should never get here.");
throw new NotSupportedException();
}
set
{
Debug.Assert(false, "Should never get here.");
throw new NotSupportedException();
}
}
/// <summary>
/// Flush the stream to the underlying storage.
/// </summary>
public override void Flush()
{
// no-op
// This can be called from writers that are put on top of this stream when
// they are closed/disposed
}
/// <summary>
/// Reads data from the stream. This operation is not supported by this stream.
/// </summary>
/// <param name="buffer">The buffer to read the data to.</param>
/// <param name="offset">The offset in the buffer to write to.</param>
/// <param name="count">The number of bytes to read.</param>
/// <returns>The number of bytes actually read.</returns>
public override int Read(byte[] buffer, int offset, int count)
{
Debug.Assert(false, "Should never get here.");
throw new NotSupportedException();
}
/// <summary>
/// Seeks the stream. This operation is not supported by this stream.
/// </summary>
/// <param name="offset">The offset to seek to.</param>
/// <param name="origin">The origin of the seek operation.</param>
/// <returns>The new position in the stream.</returns>
public override long Seek(long offset, SeekOrigin origin)
{
Debug.Assert(false, "Should never get here.");
throw new NotSupportedException();
}
/// <summary>
/// Sets the length of the stream. This operation is not supported by this stream.
/// </summary>
/// <param name="value">The length in bytes to set.</param>
public override void SetLength(long value)
{
Debug.Assert(false, "Should never get here.");
throw new NotSupportedException();
}
/// <summary>
/// Writes to the stream.
/// </summary>
/// <param name="buffer">The buffer to get data from.</param>
/// <param name="offset">The offset in the buffer to start from.</param>
/// <param name="count">The number of bytes to write.</param>
public override void Write(byte[] buffer, int offset, int count)
{
if (count > 0)
{
if (this.bufferToAppendTo == null)
{
this.QueueNewBuffer();
}
while (count > 0)
{
int written = this.bufferToAppendTo.Write(buffer, offset, count);
if (written < count)
{
this.QueueNewBuffer();
}
count -= written;
offset += written;
}
}
}
#if ODATALIB_ASYNC
#endif
/// <summary>
/// Clears any internal buffers without writing them to the underlying stream.
/// </summary>
internal void Clear()
{
DebugUtils.CheckNoExternalCallers();
this.bufferQueue.Clear();
this.bufferToAppendTo = null;
}
/// <summary>
/// Synchronous flush operation. This will flush all buffered bytes to the underlying stream through synchronous writes.
/// </summary>
internal void FlushSync()
{
DebugUtils.CheckNoExternalCallers();
Queue<DataBuffer> buffers = this.PrepareFlushBuffers();
if (buffers == null)
{
return;
}
while (buffers.Count > 0)
{
DataBuffer buffer = buffers.Dequeue();
buffer.WriteToStream(this.innerStream);
}
}
#if ODATALIB_ASYNC
/// <summary>
/// Asynchronous flush operation. This will flush all buffered bytes to the underlying stream through asynchronous writes.
/// </summary>
/// <returns>The task representing the asynchronous flush operation.</returns>
internal Task FlushAsync()
{
DebugUtils.CheckNoExternalCallers();
return this.FlushAsyncInternal();
}
/// <summary>
/// Asynchronous flush operation. This will flush all buffered bytes to the underlying stream through asynchronous writes.
/// </summary>
/// <returns>The task representing the asynchronous flush operation.</returns>
internal Task FlushAsyncInternal()
{
DebugUtils.CheckNoExternalCallers();
Queue<DataBuffer> buffers = this.PrepareFlushBuffers();
if (buffers == null)
{
return TaskUtils.CompletedTask;
}
// Note that this relies on lazy eval of the enumerator
return Task.Factory.Iterate(this.FlushBuffersAsync(buffers));
}
#endif
/// <summary>
/// Disposes the object.
/// </summary>
/// <param name="disposing">True if called from Dispose; false if called from the finalizer.</param>
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (this.bufferQueue.Count > 0)
{
throw new ODataException(Strings.AsyncBufferedStream_WriterDisposedWithoutFlush);
}
}
// We do not dispose the innerStream so to allow writers on the current stream to be disposed
// without disposing the message stream. There should only be one place to dispose the message
// stream for the writers and that is ODataMessageWriter.Dispose().
base.Dispose(disposing);
}
/// <summary>
/// Queues a new buffer to the queue of buffers
/// </summary>
private void QueueNewBuffer()
{
this.bufferToAppendTo = new DataBuffer();
this.bufferQueue.Enqueue(this.bufferToAppendTo);
}
/// <summary>
/// Prepares all buffers for flushing and returns the queue of buffers to flush.
/// </summary>
/// <returns>The queue of buffer to flush.</returns>
private Queue<DataBuffer> PrepareFlushBuffers()
{
if (this.bufferQueue.Count == 0)
{
return null;
}
this.bufferToAppendTo = null;
// clear the buffer queue to leave the stream in a 'clean' state even if
// flushing fails
Queue<DataBuffer> buffers = this.bufferQueue;
this.bufferQueue = new Queue<DataBuffer>();
return buffers;
}
#if ODATALIB_ASYNC
/// <summary>
/// Returns enumeration of tasks to run to flush all pending buffers to the underlying stream.
/// </summary>
/// <param name="buffers">The queue of buffers that need to be flushed.</param>
/// <returns>Enumeration of tasks to run to flush all buffers.</returns>
/// <remarks>This method relies on lazy eval of the enumerator, never enumerate through it synchronously.</remarks>
private IEnumerable<Task> FlushBuffersAsync(Queue<DataBuffer> buffers)
{
while (buffers.Count > 0)
{
DataBuffer buffer = buffers.Dequeue();
yield return buffer.WriteToStreamAsync(this.innerStream);
}
}
#endif
/// <summary>
/// Class to wrap a byte buffer used to store portion of the buffered data.
/// </summary>
private sealed class DataBuffer
{
/// <summary>
/// The size of a buffer to allocate (80 KB is the limit for large object heap, so use 79 to be sure to avoid LOB)
/// </summary>
private const int BufferSize = 79 * 1024;
/// <summary>
/// The byte buffer used to store the data.
/// </summary>
private readonly byte[] buffer;
/// <summary>
/// Number of bytes being stored.
/// </summary>
private int storedCount;
/// <summary>
/// Constructor - creates a new buffer
/// </summary>
public DataBuffer()
{
this.buffer = new byte[BufferSize];
this.storedCount = 0;
}
/// <summary>
/// Writes data into the buffer.
/// </summary>
/// <param name="data">The buffer containing the data to write.</param>
/// <param name="index">The index to start at.</param>
/// <param name="count">Number of bytes to write.</param>
/// <returns>How many bytes were written.</returns>
public int Write(byte[] data, int index, int count)
{
int countToCopy = count;
if (countToCopy > (this.buffer.Length - this.storedCount))
{
countToCopy = this.buffer.Length - this.storedCount;
}
if (countToCopy > 0)
{
Array.Copy(data, index, this.buffer, this.storedCount, countToCopy);
this.storedCount += countToCopy;
}
return countToCopy;
}
/// <summary>
/// Writes the buffer to the specified stream.
/// </summary>
/// <param name="stream">The stream to write the data into.</param>
public void WriteToStream(Stream stream)
{
Debug.Assert(stream != null, "stream != null");
stream.Write(this.buffer, 0, this.storedCount);
}
#if ODATALIB_ASYNC
/// <summary>
/// Creates a task which writes the buffer to the specified stream.
/// </summary>
/// <param name="stream">The stream to write the data into.</param>
/// <returns>The task which represent the asynchronous write operation.</returns>
public Task WriteToStreamAsync(Stream stream)
{
Debug.Assert(stream != null, "stream != null");
return Task.Factory.FromAsync(
(callback, state) => stream.BeginWrite(this.buffer, 0, this.storedCount, callback, state),
stream.EndWrite,
null);
}
#endif
}
}
}
| |
// 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 Xunit;
namespace System.Linq.Expressions.Tests
{
public static class ArrayLengthTests
{
#region Bool tests
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckBoolArrayLengthTest(bool useInterpreter)
{
CheckBoolArrayLengthExpression(GenerateBoolArray(0), useInterpreter);
CheckBoolArrayLengthExpression(GenerateBoolArray(1), useInterpreter);
CheckBoolArrayLengthExpression(GenerateBoolArray(5), useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckExceptionBoolArrayLengthTest(bool useInterpreter)
{
Assert.Throws<NullReferenceException>(() => CheckBoolArrayLengthExpression(null, useInterpreter));
}
#endregion
#region Byte tests
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckByteArrayLengthTest(bool useInterpreter)
{
CheckByteArrayLengthExpression(GenerateByteArray(0), useInterpreter);
CheckByteArrayLengthExpression(GenerateByteArray(1), useInterpreter);
CheckByteArrayLengthExpression(GenerateByteArray(5), useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckExceptionByteArrayLengthTest(bool useInterpreter)
{
Assert.Throws<NullReferenceException>(() => CheckByteArrayLengthExpression(null, useInterpreter));
}
#endregion
#region Custom tests
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckCustomArrayLengthTest(bool useInterpreter)
{
CheckCustomArrayLengthExpression(GenerateCustomArray(0), useInterpreter);
CheckCustomArrayLengthExpression(GenerateCustomArray(1), useInterpreter);
CheckCustomArrayLengthExpression(GenerateCustomArray(5), useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckExceptionCustomArrayLengthTest(bool useInterpreter)
{
Assert.Throws<NullReferenceException>(() => CheckCustomArrayLengthExpression(null, useInterpreter));
}
#endregion
#region Char tests
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckCharArrayLengthTest(bool useInterpreter)
{
CheckCharArrayLengthExpression(GenerateCharArray(0), useInterpreter);
CheckCharArrayLengthExpression(GenerateCharArray(1), useInterpreter);
CheckCharArrayLengthExpression(GenerateCharArray(5), useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckExceptionCharArrayLengthTest(bool useInterpreter)
{
Assert.Throws<NullReferenceException>(() => CheckCharArrayLengthExpression(null, useInterpreter));
}
#endregion
#region Custom2 tests
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckCustom2ArrayLengthTest(bool useInterpreter)
{
CheckCustom2ArrayLengthExpression(GenerateCustom2Array(0), useInterpreter);
CheckCustom2ArrayLengthExpression(GenerateCustom2Array(1), useInterpreter);
CheckCustom2ArrayLengthExpression(GenerateCustom2Array(5), useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckExceptionCustom2ArrayLengthTest(bool useInterpreter)
{
Assert.Throws<NullReferenceException>(() => CheckCustom2ArrayLengthExpression(null, useInterpreter));
}
#endregion
#region Decimal tests
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckDecimalArrayLengthTest(bool useInterpreter)
{
CheckDecimalArrayLengthExpression(GenerateDecimalArray(0), useInterpreter);
CheckDecimalArrayLengthExpression(GenerateDecimalArray(1), useInterpreter);
CheckDecimalArrayLengthExpression(GenerateDecimalArray(5), useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckExceptionDecimalArrayLengthTest(bool useInterpreter)
{
Assert.Throws<NullReferenceException>(() => CheckDecimalArrayLengthExpression(null, useInterpreter));
}
#endregion
#region Delegate tests
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckDelegateArrayLengthTest(bool useInterpreter)
{
CheckDelegateArrayLengthExpression(GenerateDelegateArray(0), useInterpreter);
CheckDelegateArrayLengthExpression(GenerateDelegateArray(1), useInterpreter);
CheckDelegateArrayLengthExpression(GenerateDelegateArray(5), useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckExceptionDelegateArrayLengthTest(bool useInterpreter)
{
Assert.Throws<NullReferenceException>(() => CheckDelegateArrayLengthExpression(null, useInterpreter));
}
#endregion
#region double tests
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckdoubleArrayLengthTest(bool useInterpreter)
{
CheckDoubleArrayLengthExpression(GeneratedoubleArray(0), useInterpreter);
CheckDoubleArrayLengthExpression(GeneratedoubleArray(1), useInterpreter);
CheckDoubleArrayLengthExpression(GeneratedoubleArray(5), useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckExceptiondoubleArrayLengthTest(bool useInterpreter)
{
Assert.Throws<NullReferenceException>(() => CheckDoubleArrayLengthExpression(null, useInterpreter));
}
#endregion
#region Enum tests
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckEnumArrayLengthTest(bool useInterpreter)
{
CheckEnumArrayLengthExpression(GenerateEnumArray(0), useInterpreter);
CheckEnumArrayLengthExpression(GenerateEnumArray(1), useInterpreter);
CheckEnumArrayLengthExpression(GenerateEnumArray(5), useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckExceptionEnumArrayLengthTest(bool useInterpreter)
{
Assert.Throws<NullReferenceException>(() => CheckEnumArrayLengthExpression(null, useInterpreter));
}
#endregion
#region EnumLong tests
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckEnumLongArrayLengthTest(bool useInterpreter)
{
CheckEnumLongArrayLengthExpression(GenerateEnumLongArray(0), useInterpreter);
CheckEnumLongArrayLengthExpression(GenerateEnumLongArray(1), useInterpreter);
CheckEnumLongArrayLengthExpression(GenerateEnumLongArray(5), useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckExceptionEnumLongArrayLengthTest(bool useInterpreter)
{
Assert.Throws<NullReferenceException>(() => CheckEnumLongArrayLengthExpression(null, useInterpreter));
}
#endregion
#region Float tests
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckFloatArrayLengthTest(bool useInterpreter)
{
CheckFloatArrayLengthExpression(GenerateFloatArray(0), useInterpreter);
CheckFloatArrayLengthExpression(GenerateFloatArray(1), useInterpreter);
CheckFloatArrayLengthExpression(GenerateFloatArray(5), useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckExceptionFloatArrayLengthTest(bool useInterpreter)
{
Assert.Throws<NullReferenceException>(() => CheckFloatArrayLengthExpression(null, useInterpreter));
}
#endregion
#region Func tests
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckFuncArrayLengthTest(bool useInterpreter)
{
CheckFuncArrayLengthExpression(GenerateFuncArray(0), useInterpreter);
CheckFuncArrayLengthExpression(GenerateFuncArray(1), useInterpreter);
CheckFuncArrayLengthExpression(GenerateFuncArray(5), useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckExceptionFuncArrayLengthTest(bool useInterpreter)
{
Assert.Throws<NullReferenceException>(() => CheckFuncArrayLengthExpression(null, useInterpreter));
}
#endregion
#region Interface tests
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckInterfaceArrayLengthTest(bool useInterpreter)
{
CheckInterfaceArrayLengthExpression(GenerateInterfaceArray(0), useInterpreter);
CheckInterfaceArrayLengthExpression(GenerateInterfaceArray(1), useInterpreter);
CheckInterfaceArrayLengthExpression(GenerateInterfaceArray(5), useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckExceptionInterfaceArrayLengthTest(bool useInterpreter)
{
Assert.Throws<NullReferenceException>(() => CheckInterfaceArrayLengthExpression(null, useInterpreter));
}
#endregion
#region IEquatable tests
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckIEquatableArrayLengthTest(bool useInterpreter)
{
CheckIEquatableArrayLengthExpression(GenerateIEquatableArray(0), useInterpreter);
CheckIEquatableArrayLengthExpression(GenerateIEquatableArray(1), useInterpreter);
CheckIEquatableArrayLengthExpression(GenerateIEquatableArray(5), useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckExceptionIEquatableArrayLengthTest(bool useInterpreter)
{
Assert.Throws<NullReferenceException>(() => CheckIEquatableArrayLengthExpression(null, useInterpreter));
}
#endregion
#region IEquatable2 tests
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckIEquatable2ArrayLengthTest(bool useInterpreter)
{
CheckIEquatable2ArrayLengthExpression(GenerateIEquatable2Array(0), useInterpreter);
CheckIEquatable2ArrayLengthExpression(GenerateIEquatable2Array(1), useInterpreter);
CheckIEquatable2ArrayLengthExpression(GenerateIEquatable2Array(5), useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckExceptionIEquatable2ArrayLengthTest(bool useInterpreter)
{
Assert.Throws<NullReferenceException>(() => CheckIEquatable2ArrayLengthExpression(null, useInterpreter));
}
#endregion
#region Int tests
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckIntArrayLengthTest(bool useInterpreter)
{
CheckIntArrayLengthExpression(GenerateIntArray(0), useInterpreter);
CheckIntArrayLengthExpression(GenerateIntArray(1), useInterpreter);
CheckIntArrayLengthExpression(GenerateIntArray(5), useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckExceptionIntArrayLengthTest(bool useInterpreter)
{
Assert.Throws<NullReferenceException>(() => CheckIntArrayLengthExpression(null, useInterpreter));
}
#endregion
#region Long tests
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckLongArrayLengthTest(bool useInterpreter)
{
CheckLongArrayLengthExpression(GenerateLongArray(0), useInterpreter);
CheckLongArrayLengthExpression(GenerateLongArray(1), useInterpreter);
CheckLongArrayLengthExpression(GenerateLongArray(5), useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckExceptionLongArrayLengthTest(bool useInterpreter)
{
Assert.Throws<NullReferenceException>(() => CheckLongArrayLengthExpression(null, useInterpreter));
}
#endregion
#region Object tests
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckObjectArrayLengthTest(bool useInterpreter)
{
CheckObjectArrayLengthExpression(GenerateObjectArray(0), useInterpreter);
CheckObjectArrayLengthExpression(GenerateObjectArray(1), useInterpreter);
CheckObjectArrayLengthExpression(GenerateObjectArray(5), useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckExceptionObjectArrayLengthTest(bool useInterpreter)
{
Assert.Throws<NullReferenceException>(() => CheckObjectArrayLengthExpression(null, useInterpreter));
}
#endregion
#region Struct tests
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckStructArrayLengthTest(bool useInterpreter)
{
CheckStructArrayLengthExpression(GenerateStructArray(0), useInterpreter);
CheckStructArrayLengthExpression(GenerateStructArray(1), useInterpreter);
CheckStructArrayLengthExpression(GenerateStructArray(5), useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckExceptionStructArrayLengthTest(bool useInterpreter)
{
Assert.Throws<NullReferenceException>(() => CheckStructArrayLengthExpression(null, useInterpreter));
}
#endregion
#region SByte tests
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckSByteArrayLengthTest(bool useInterpreter)
{
CheckSByteArrayLengthExpression(GenerateSByteArray(0), useInterpreter);
CheckSByteArrayLengthExpression(GenerateSByteArray(1), useInterpreter);
CheckSByteArrayLengthExpression(GenerateSByteArray(5), useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckExceptionSByteArrayLengthTest(bool useInterpreter)
{
Assert.Throws<NullReferenceException>(() => CheckSByteArrayLengthExpression(null, useInterpreter));
}
#endregion
#region StructWithString tests
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckStructWithStringArrayLengthTest(bool useInterpreter)
{
CheckStructWithStringArrayLengthExpression(GenerateStructWithStringArray(0), useInterpreter);
CheckStructWithStringArrayLengthExpression(GenerateStructWithStringArray(1), useInterpreter);
CheckStructWithStringArrayLengthExpression(GenerateStructWithStringArray(5), useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckExceptionStructWithStringArrayLengthTest(bool useInterpreter)
{
Assert.Throws<NullReferenceException>(() => CheckStructWithStringArrayLengthExpression(null, useInterpreter));
}
#endregion
#region StructWithStringAndStruct tests
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckStructWithStringAndStructArrayLengthTest(bool useInterpreter)
{
CheckStructWithStringAndStructArrayLengthExpression(GenerateStructWithStringAndStructArray(0), useInterpreter);
CheckStructWithStringAndStructArrayLengthExpression(GenerateStructWithStringAndStructArray(1), useInterpreter);
CheckStructWithStringAndStructArrayLengthExpression(GenerateStructWithStringAndStructArray(5), useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckExceptionStructWithStringAndStructArrayLengthTest(bool useInterpreter)
{
Assert.Throws<NullReferenceException>(() => CheckStructWithStringAndStructArrayLengthExpression(null, useInterpreter));
}
#endregion
#region Short tests
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckShortArrayLengthTest(bool useInterpreter)
{
CheckShortArrayLengthExpression(GenerateShortArray(0), useInterpreter);
CheckShortArrayLengthExpression(GenerateShortArray(1), useInterpreter);
CheckShortArrayLengthExpression(GenerateShortArray(5), useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckExceptionShortArrayLengthTest(bool useInterpreter)
{
Assert.Throws<NullReferenceException>(() => CheckShortArrayLengthExpression(null, useInterpreter));
}
#endregion
#region StructWithTwoFields tests
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckStructWithTwoFieldsArrayLengthTest(bool useInterpreter)
{
CheckStructWithTwoFieldsArrayLengthExpression(GenerateStructWithTwoFieldsArray(0), useInterpreter);
CheckStructWithTwoFieldsArrayLengthExpression(GenerateStructWithTwoFieldsArray(1), useInterpreter);
CheckStructWithTwoFieldsArrayLengthExpression(GenerateStructWithTwoFieldsArray(5), useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckExceptionStructWithTwoFieldsArrayLengthTest(bool useInterpreter)
{
Assert.Throws<NullReferenceException>(() => CheckStructWithTwoFieldsArrayLengthExpression(null, useInterpreter));
}
#endregion
#region StructWithValue tests
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckStructWithValueArrayLengthTest(bool useInterpreter)
{
CheckStructWithValueArrayLengthExpression(GenerateStructWithValueArray(0), useInterpreter);
CheckStructWithValueArrayLengthExpression(GenerateStructWithValueArray(1), useInterpreter);
CheckStructWithValueArrayLengthExpression(GenerateStructWithValueArray(5), useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckExceptionStructWithValueArrayLengthTest(bool useInterpreter)
{
Assert.Throws<NullReferenceException>(() => CheckStructWithValueArrayLengthExpression(null, useInterpreter));
}
#endregion
#region String tests
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckStringArrayLengthTest(bool useInterpreter)
{
CheckStringArrayLengthExpression(GenerateStringArray(0), useInterpreter);
CheckStringArrayLengthExpression(GenerateStringArray(1), useInterpreter);
CheckStringArrayLengthExpression(GenerateStringArray(5), useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckExceptionStringArrayLengthTest(bool useInterpreter)
{
Assert.Throws<NullReferenceException>(() => CheckStringArrayLengthExpression(null, useInterpreter));
}
#endregion
#region UInt tests
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckUIntArrayLengthTest(bool useInterpreter)
{
CheckUIntArrayLengthExpression(GenerateUIntArray(0), useInterpreter);
CheckUIntArrayLengthExpression(GenerateUIntArray(1), useInterpreter);
CheckUIntArrayLengthExpression(GenerateUIntArray(5), useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckExceptionUIntArrayLengthTest(bool useInterpreter)
{
Assert.Throws<NullReferenceException>(() => CheckUIntArrayLengthExpression(null, useInterpreter));
}
#endregion
#region ULong tests
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckULongArrayLengthTest(bool useInterpreter)
{
CheckULongArrayLengthExpression(GenerateULongArray(0), useInterpreter);
CheckULongArrayLengthExpression(GenerateULongArray(1), useInterpreter);
CheckULongArrayLengthExpression(GenerateULongArray(5), useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckExceptionULongArrayLengthTest(bool useInterpreter)
{
Assert.Throws<NullReferenceException>(() => CheckULongArrayLengthExpression(null, useInterpreter));
}
#endregion
#region UShort tests
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckUShortArrayLengthTest(bool useInterpreter)
{
CheckUShortArrayLengthExpression(GenerateUShortArray(0), useInterpreter);
CheckUShortArrayLengthExpression(GenerateUShortArray(1), useInterpreter);
CheckUShortArrayLengthExpression(GenerateUShortArray(5), useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckExceptionUShortArrayLengthTest(bool useInterpreter)
{
Assert.Throws<NullReferenceException>(() => CheckUShortArrayLengthExpression(null, useInterpreter));
}
#endregion
#region Generic tests
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckGenericCustomArrayLengthTest(bool useInterpreter)
{
CheckGenericArrayLengthTestHelper<C>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckExceptionGenericCustomArrayLengthTest(bool useInterpreter)
{
CheckExceptionGenericArrayLengthTestHelper<C>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckGenericEnumArrayLengthTest(bool useInterpreter)
{
CheckGenericArrayLengthTestHelper<E>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckExceptionGenericEnumArrayLengthTest(bool useInterpreter)
{
CheckExceptionGenericArrayLengthTestHelper<E>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckGenericObjectArrayLengthTest(bool useInterpreter)
{
CheckGenericArrayLengthTestHelper<object>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckExceptionGenericObjectArrayLengthTest(bool useInterpreter)
{
CheckExceptionGenericArrayLengthTestHelper<object>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckGenericStructArrayLengthTest(bool useInterpreter)
{
CheckGenericArrayLengthTestHelper<S>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckExceptionGenericStructArrayLengthTest(bool useInterpreter)
{
CheckExceptionGenericArrayLengthTestHelper<S>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckGenericStructWithStringAndFieldArrayLengthTest(bool useInterpreter)
{
CheckGenericArrayLengthTestHelper<Scs>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckExceptionGenericStructWithStringAndFieldArrayLengthTest(bool useInterpreter)
{
CheckExceptionGenericArrayLengthTestHelper<Scs>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckGenericCustomWithClassRestrictionArrayLengthTest(bool useInterpreter)
{
CheckGenericWithClassRestrictionArrayLengthTestHelper<C>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckExceptionGenericCustomWithClassRestrictionArrayLengthTest(bool useInterpreter)
{
CheckExceptionGenericWithClassRestrictionArrayLengthTestHelper<C>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckGenericObjectWithClassRestrictionArrayLengthTest(bool useInterpreter)
{
CheckGenericWithClassRestrictionArrayLengthTestHelper<object>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckExceptionGenericObjectWithClassRestrictionArrayLengthTest(bool useInterpreter)
{
CheckExceptionGenericWithClassRestrictionArrayLengthTestHelper<object>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckGenericCustomWithClassAndNewRestrictionArrayLengthTest(bool useInterpreter)
{
CheckGenericWithClassAndNewRestrictionArrayLengthTestHelper<C>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckExceptionGenericCustomWithClassAndNewRestrictionArrayLengthTest(bool useInterpreter)
{
CheckExceptionGenericWithClassAndNewRestrictionArrayLengthTestHelper<C>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckGenericObjectWithClassAndNewRestrictionArrayLengthTest(bool useInterpreter)
{
CheckGenericWithClassAndNewRestrictionArrayLengthTestHelper<object>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckExceptionGenericObjectWithClassAndNewRestrictionArrayLengthTest(bool useInterpreter)
{
CheckExceptionGenericWithClassAndNewRestrictionArrayLengthTestHelper<object>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckGenericCustomWithSubClassRestrictionArrayLengthTest(bool useInterpreter)
{
CheckGenericWithSubClassRestrictionArrayLengthTestHelper<C>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckExceptionGenericCustomWithSubClassRestrictionArrayLengthTest(bool useInterpreter)
{
CheckExceptionGenericWithSubClassRestrictionArrayLengthTestHelper<C>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckGenericCustomWithSubClassAndNewRestrictionArrayLengthTest(bool useInterpreter)
{
CheckGenericWithSubClassAndNewRestrictionArrayLengthTestHelper<C>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckExceptionGenericCustomWithSubClassAndNewRestrictionArrayLengthTest(bool useInterpreter)
{
CheckExceptionGenericWithSubClassAndNewRestrictionArrayLengthTestHelper<C>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckGenericEnumWithStructRestrictionArrayLengthTest(bool useInterpreter)
{
CheckGenericWithStructRestrictionArrayLengthTestHelper<E>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckExceptionGenericEnumWithStructRestrictionArrayLengthTest(bool useInterpreter)
{
CheckExceptionGenericWithStructRestrictionArrayLengthTestHelper<E>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckGenericStructWithStructRestrictionArrayLengthTest(bool useInterpreter)
{
CheckGenericWithStructRestrictionArrayLengthTestHelper<S>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckExceptionGenericStructWithStructRestrictionArrayLengthTest(bool useInterpreter)
{
CheckExceptionGenericWithStructRestrictionArrayLengthTestHelper<S>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckGenericStructWithStringAndFieldWithStructRestrictionArrayLengthTest(bool useInterpreter)
{
CheckGenericWithStructRestrictionArrayLengthTestHelper<Scs>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckExceptionGenericStructWithStringAndFieldWithStructRestrictionArrayLengthTest(bool useInterpreter)
{
CheckExceptionGenericWithStructRestrictionArrayLengthTestHelper<Scs>(useInterpreter);
}
#endregion
#region Generic helpers
public static void CheckGenericArrayLengthTestHelper<T>(bool useInterpreter)
{
CheckGenericArrayLengthExpression<T>(GenerateGenericArray<T>(0), useInterpreter);
CheckGenericArrayLengthExpression<T>(GenerateGenericArray<T>(1), useInterpreter);
CheckGenericArrayLengthExpression<T>(GenerateGenericArray<T>(5), useInterpreter);
}
public static void CheckExceptionGenericArrayLengthTestHelper<T>(bool useInterpreter)
{
Assert.Throws<NullReferenceException>(() => CheckGenericArrayLengthExpression<T>(null, useInterpreter));
}
public static void CheckGenericWithClassRestrictionArrayLengthTestHelper<Tc>(bool useInterpreter) where Tc : class
{
CheckGenericWithClassRestrictionArrayLengthExpression<Tc>(GenerateGenericWithClassRestrictionArray<Tc>(0), useInterpreter);
CheckGenericWithClassRestrictionArrayLengthExpression<Tc>(GenerateGenericWithClassRestrictionArray<Tc>(1), useInterpreter);
CheckGenericWithClassRestrictionArrayLengthExpression<Tc>(GenerateGenericWithClassRestrictionArray<Tc>(5), useInterpreter);
}
public static void CheckExceptionGenericWithClassRestrictionArrayLengthTestHelper<Tc>(bool useInterpreter) where Tc : class
{
Assert.Throws<NullReferenceException>(() => CheckGenericWithClassRestrictionArrayLengthExpression<Tc>(null, useInterpreter));
}
public static void CheckGenericWithClassAndNewRestrictionArrayLengthTestHelper<Tcn>(bool useInterpreter) where Tcn : class, new()
{
CheckGenericWithClassAndNewRestrictionArrayLengthExpression<Tcn>(GenerateGenericWithClassAndNewRestrictionArray<Tcn>(0), useInterpreter);
CheckGenericWithClassAndNewRestrictionArrayLengthExpression<Tcn>(GenerateGenericWithClassAndNewRestrictionArray<Tcn>(1), useInterpreter);
CheckGenericWithClassAndNewRestrictionArrayLengthExpression<Tcn>(GenerateGenericWithClassAndNewRestrictionArray<Tcn>(5), useInterpreter);
}
public static void CheckExceptionGenericWithClassAndNewRestrictionArrayLengthTestHelper<Tcn>(bool useInterpreter) where Tcn : class, new()
{
Assert.Throws<NullReferenceException>(() => CheckGenericWithClassAndNewRestrictionArrayLengthExpression<Tcn>(null, useInterpreter));
}
public static void CheckGenericWithSubClassRestrictionArrayLengthTestHelper<TC>(bool useInterpreter) where TC : C
{
CheckGenericWithSubClassRestrictionArrayLengthExpression<TC>(GenerateGenericWithSubClassRestrictionArray<TC>(0), useInterpreter);
CheckGenericWithSubClassRestrictionArrayLengthExpression<TC>(GenerateGenericWithSubClassRestrictionArray<TC>(1), useInterpreter);
CheckGenericWithSubClassRestrictionArrayLengthExpression<TC>(GenerateGenericWithSubClassRestrictionArray<TC>(5), useInterpreter);
}
public static void CheckExceptionGenericWithSubClassRestrictionArrayLengthTestHelper<TC>(bool useInterpreter) where TC : C
{
Assert.Throws<NullReferenceException>(() => CheckGenericWithSubClassRestrictionArrayLengthExpression<TC>(null, useInterpreter));
}
public static void CheckGenericWithSubClassAndNewRestrictionArrayLengthTestHelper<TCn>(bool useInterpreter) where TCn : C, new()
{
CheckGenericWithSubClassAndNewRestrictionArrayLengthExpression<TCn>(GenerateGenericWithSubClassAndNewRestrictionArray<TCn>(0), useInterpreter);
CheckGenericWithSubClassAndNewRestrictionArrayLengthExpression<TCn>(GenerateGenericWithSubClassAndNewRestrictionArray<TCn>(1), useInterpreter);
CheckGenericWithSubClassAndNewRestrictionArrayLengthExpression<TCn>(GenerateGenericWithSubClassAndNewRestrictionArray<TCn>(5), useInterpreter);
}
public static void CheckExceptionGenericWithSubClassAndNewRestrictionArrayLengthTestHelper<TCn>(bool useInterpreter) where TCn : C, new()
{
Assert.Throws<NullReferenceException>(() => CheckGenericWithSubClassAndNewRestrictionArrayLengthExpression<TCn>(null, useInterpreter));
}
public static void CheckGenericWithStructRestrictionArrayLengthTestHelper<Ts>(bool useInterpreter) where Ts : struct
{
CheckGenericWithStructRestrictionArrayLengthExpression<Ts>(GenerateGenericWithStructRestrictionArray<Ts>(0), useInterpreter);
CheckGenericWithStructRestrictionArrayLengthExpression<Ts>(GenerateGenericWithStructRestrictionArray<Ts>(1), useInterpreter);
CheckGenericWithStructRestrictionArrayLengthExpression<Ts>(GenerateGenericWithStructRestrictionArray<Ts>(5), useInterpreter);
}
public static void CheckExceptionGenericWithStructRestrictionArrayLengthTestHelper<Ts>(bool useInterpreter) where Ts : struct
{
Assert.Throws<NullReferenceException>(() => CheckGenericWithStructRestrictionArrayLengthExpression<Ts>(null, useInterpreter));
}
#endregion
#region Generate array
private static bool[] GenerateBoolArray(int size)
{
bool[] array = new bool[] { true, false };
bool[] result = new bool[size];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static byte[] GenerateByteArray(int size)
{
byte[] array = new byte[] { 0, 1, byte.MaxValue };
byte[] result = new byte[size];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static C[] GenerateCustomArray(int size)
{
C[] array = new C[] { null, new C(), new D(), new D(0), new D(5) };
C[] result = new C[size];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static char[] GenerateCharArray(int size)
{
char[] array = new char[] { '\0', '\b', 'A', '\uffff' };
char[] result = new char[size];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static D[] GenerateCustom2Array(int size)
{
D[] array = new D[] { null, new D(), new D(0), new D(5) };
D[] result = new D[size];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static decimal[] GenerateDecimalArray(int size)
{
decimal[] array = new decimal[] { decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue };
decimal[] result = new decimal[size];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static Delegate[] GenerateDelegateArray(int size)
{
Delegate[] array = new Delegate[] { null, (Func<object>)delegate () { return null; }, (Func<int, int>)delegate (int i) { return i + 1; }, (Action<object>)delegate { } };
Delegate[] result = new Delegate[size];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static double[] GeneratedoubleArray(int size)
{
double[] array = new double[] { 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN };
double[] result = new double[size];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static E[] GenerateEnumArray(int size)
{
E[] array = new E[] { (E)0, E.A, E.B, (E)int.MaxValue, (E)int.MinValue };
E[] result = new E[size];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static El[] GenerateEnumLongArray(int size)
{
El[] array = new El[] { (El)0, El.A, El.B, (El)long.MaxValue, (El)long.MinValue };
El[] result = new El[size];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static float[] GenerateFloatArray(int size)
{
float[] array = new float[] { 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN };
float[] result = new float[size];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static Func<object>[] GenerateFuncArray(int size)
{
Func<object>[] array = new Func<object>[] { null, (Func<object>)delegate () { return null; } };
Func<object>[] result = new Func<object>[size];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static I[] GenerateInterfaceArray(int size)
{
I[] array = new I[] { null, new C(), new D(), new D(0), new D(5) };
I[] result = new I[size];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static IEquatable<C>[] GenerateIEquatableArray(int size)
{
IEquatable<C>[] array = new IEquatable<C>[] { null, new C(), new D(), new D(0), new D(5) };
IEquatable<C>[] result = new IEquatable<C>[size];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static IEquatable<D>[] GenerateIEquatable2Array(int size)
{
IEquatable<D>[] array = new IEquatable<D>[] { null, new D(), new D(0), new D(5) };
IEquatable<D>[] result = new IEquatable<D>[size];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static int[] GenerateIntArray(int size)
{
int[] array = new int[] { 0, 1, -1, int.MinValue, int.MaxValue };
int[] result = new int[size];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static long[] GenerateLongArray(int size)
{
long[] array = new long[] { 0, 1, -1, long.MinValue, long.MaxValue };
long[] result = new long[size];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static object[] GenerateObjectArray(int size)
{
object[] array = new object[] { null, new object(), new C(), new D(3) };
object[] result = new object[size];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static S[] GenerateStructArray(int size)
{
S[] array = new S[] { default(S), new S() };
S[] result = new S[size];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static sbyte[] GenerateSByteArray(int size)
{
sbyte[] array = new sbyte[] { 0, 1, -1, sbyte.MinValue, sbyte.MaxValue };
sbyte[] result = new sbyte[size];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static Sc[] GenerateStructWithStringArray(int size)
{
Sc[] array = new Sc[] { default(Sc), new Sc(), new Sc(null) };
Sc[] result = new Sc[size];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static Scs[] GenerateStructWithStringAndStructArray(int size)
{
Scs[] array = new Scs[] { default(Scs), new Scs(), new Scs(null, new S()) };
Scs[] result = new Scs[size];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static short[] GenerateShortArray(int size)
{
short[] array = new short[] { 0, 1, -1, short.MinValue, short.MaxValue };
short[] result = new short[size];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static Sp[] GenerateStructWithTwoFieldsArray(int size)
{
Sp[] array = new Sp[] { default(Sp), new Sp(), new Sp(5, 5.0) };
Sp[] result = new Sp[size];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static Ss[] GenerateStructWithValueArray(int size)
{
Ss[] array = new Ss[] { default(Ss), new Ss(), new Ss(new S()) };
Ss[] result = new Ss[size];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static string[] GenerateStringArray(int size)
{
string[] array = new string[] { null, "", "a", "foo" };
string[] result = new string[size];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static uint[] GenerateUIntArray(int size)
{
uint[] array = new uint[] { 0, 1, uint.MaxValue };
uint[] result = new uint[size];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static ulong[] GenerateULongArray(int size)
{
ulong[] array = new ulong[] { 0, 1, ulong.MaxValue };
ulong[] result = new ulong[size];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static ushort[] GenerateUShortArray(int size)
{
ushort[] array = new ushort[] { 0, 1, ushort.MaxValue };
ushort[] result = new ushort[size];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static T[] GenerateGenericArray<T>(int size)
{
T[] array = new T[] { default(T) };
T[] result = new T[size];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static Tc[] GenerateGenericWithClassRestrictionArray<Tc>(int size) where Tc : class
{
Tc[] array = new Tc[] { null, default(Tc) };
Tc[] result = new Tc[size];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static Tcn[] GenerateGenericWithClassAndNewRestrictionArray<Tcn>(int size) where Tcn : class, new()
{
Tcn[] array = new Tcn[] { null, default(Tcn), new Tcn() };
Tcn[] result = new Tcn[size];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static TC[] GenerateGenericWithSubClassRestrictionArray<TC>(int size) where TC : C
{
TC[] array = new TC[] { null, default(TC), (TC)new C() };
TC[] result = new TC[size];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static TCn[] GenerateGenericWithSubClassAndNewRestrictionArray<TCn>(int size) where TCn : C, new()
{
TCn[] array = new TCn[] { null, default(TCn), new TCn(), (TCn)new C() };
TCn[] result = new TCn[size];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static Ts[] GenerateGenericWithStructRestrictionArray<Ts>(int size) where Ts : struct
{
Ts[] array = new Ts[] { default(Ts), new Ts() };
Ts[] result = new Ts[size];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
#endregion
#region Check length expression
private static void CheckBoolArrayLengthExpression(bool[] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(bool[]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckByteArrayLengthExpression(byte[] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(byte[]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckCustomArrayLengthExpression(C[] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(C[]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckCharArrayLengthExpression(char[] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(char[]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckCustom2ArrayLengthExpression(D[] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(D[]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckDecimalArrayLengthExpression(decimal[] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(decimal[]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckDelegateArrayLengthExpression(Delegate[] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(Delegate[]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckDoubleArrayLengthExpression(double[] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(double[]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckEnumArrayLengthExpression(E[] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(E[]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckEnumLongArrayLengthExpression(El[] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(El[]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckFloatArrayLengthExpression(float[] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(float[]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckFuncArrayLengthExpression(Func<object>[] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(Func<object>[]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckInterfaceArrayLengthExpression(I[] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(I[]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckIEquatableArrayLengthExpression(IEquatable<C>[] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(IEquatable<C>[]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckIEquatable2ArrayLengthExpression(IEquatable<D>[] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(IEquatable<D>[]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckIntArrayLengthExpression(int[] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(int[]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckLongArrayLengthExpression(long[] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(long[]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckObjectArrayLengthExpression(object[] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(object[]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckStructArrayLengthExpression(S[] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(S[]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckSByteArrayLengthExpression(sbyte[] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(sbyte[]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckStructWithStringArrayLengthExpression(Sc[] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(Sc[]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckStructWithStringAndStructArrayLengthExpression(Scs[] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(Scs[]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckShortArrayLengthExpression(short[] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(short[]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckStructWithTwoFieldsArrayLengthExpression(Sp[] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(Sp[]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckStructWithValueArrayLengthExpression(Ss[] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(Ss[]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckStringArrayLengthExpression(string[] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(string[]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckUIntArrayLengthExpression(uint[] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(uint[]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckULongArrayLengthExpression(ulong[] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(ulong[]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckUShortArrayLengthExpression(ushort[] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(ushort[]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckGenericArrayLengthExpression<T>(T[] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(T[]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckGenericWithClassRestrictionArrayLengthExpression<Tc>(Tc[] array, bool useInterpreter) where Tc : class
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(Tc[]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckGenericWithClassAndNewRestrictionArrayLengthExpression<Tcn>(Tcn[] array, bool useInterpreter) where Tcn : class, new()
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(Tcn[]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckGenericWithSubClassRestrictionArrayLengthExpression<TC>(TC[] array, bool useInterpreter) where TC : C
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(TC[]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckGenericWithSubClassAndNewRestrictionArrayLengthExpression<TCn>(TCn[] array, bool useInterpreter) where TCn : C, new()
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(TCn[]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckGenericWithStructRestrictionArrayLengthExpression<Ts>(Ts[] array, bool useInterpreter) where Ts : struct
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(Ts[]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
#endregion
#region ToString
[Fact]
public static void ToStringTest()
{
var e = Expression.ArrayLength(Expression.Parameter(typeof(int[]), "xs"));
Assert.Equal("ArrayLength(xs)", e.ToString());
}
#endregion
}
}
| |
using System;
using System.Drawing;
using System.Collections;
using System.Windows.Forms;
using System.Data;
namespace Pong
{
/// <summary>
///
/// Ideas:
/// add spin abilities to be SpinPong
///
/// </summary>
///
public class Form1 : System.Windows.Forms.Form
{
// screen width and height
private int scrWidth=320, scrHeight=210;
private double ballPosX=-1, ballPosY=-1, ballVelX=-1, ballVelY=-1;
// 25 is default tail length
//private double[] ballPrevX = new double[25];
//private double[] ballPrevY = new double[25];
// even numbers only (due to some (pSize/2) in the code)
private int pSize = 28;
private double p1 = 105;
private double p2 = 105;
private double p1v = 0;
private double p2v = 0;
// 3 = default; pSpeed is the velocity when holding down a key; maximum velocity of a paddle
private double pSpeed = 3.2;
private int p1score = 0;
private int p2score = -1;
private bool W_DOWN = false;
private bool S_DOWN = false;
private bool UPARROW_DOWN = false;
private bool DOWNARROW_DOWN = false;
private bool paused = true;
private bool infoBox = true;
private int difficulty = 1;
private string[] difficultyNames = {"human","easy","medium","hard"};
private int[] upArrowX = {436,446,436};
private int[] upArrowY = {354,364,374};
private int[] downArrowX = {355,345,355};
private int[] downArrowY = {354,364,374};
private Random r = new Random();
Bitmap offScreenBmp;
Graphics offScreenDC;
private Timer t = new Timer();
public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
offScreenBmp = new Bitmap(scrWidth, scrWidth);
offScreenDC = Graphics.FromImage(offScreenBmp);
t.Interval = 1;
t.Enabled = true;
t.Tick += new EventHandler(t_Tick);
//
// TODO: Add any constructor code after InitializeComponent call
//
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
//
// Form1
//
this.BackColor = System.Drawing.Color.Black;
this.ClientSize = new System.Drawing.Size(314, 183);
this.Text = "Pong - by Chris Elwell";
this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.Form1_KeyDown);
this.KeyUp += new System.Windows.Forms.KeyEventHandler(this.Form1_KeyUp);
this.Paint += new System.Windows.Forms.PaintEventHandler(this.Form1_Paint);
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
Application.Run(new Form1());
}
protected override void OnPaintBackground(System.Windows.Forms.PaintEventArgs e)
{
}
private void Form1_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
{
Graphics g = e.Graphics;
//offScreenDC.FillRectangle(new SolidBrush(Color.Black), 0, 0, 320, 215);
offScreenDC.Clear(Color.Black);
offScreenDC.DrawRectangle(new Pen(Color.White),0,0,319,210);
offScreenDC.FillRectangle(new SolidBrush(Color.White), 5, (int)p1-pSize/2, 5, pSize);
offScreenDC.FillRectangle(new SolidBrush(Color.White), 310, (int)p2-pSize/2, 5, pSize);
offScreenDC.FillEllipse(new SolidBrush(Color.White), (int)ballPosX-3, (int)ballPosY-3, 6, 6);
// draw scores
offScreenDC.DrawString(""+p1score, new Font("Arial", 10, System.Drawing.FontStyle.Bold), new SolidBrush(Color.White), 60, 7);
offScreenDC.DrawString(""+p2score, new Font("Arial", 10, System.Drawing.FontStyle.Bold), new SolidBrush(Color.White), 260, 7);
if (infoBox)
{
offScreenDC.DrawString("P O N G", new Font("Arial", 10, System.Drawing.FontStyle.Bold), new SolidBrush(Color.White), 130, 80);
offScreenDC.DrawString(difficultyNames[difficulty], new Font("Arial", 10, System.Drawing.FontStyle.Bold), new SolidBrush(Color.White), 153-4*difficultyNames[difficulty].Length, 120);
}
else
{
offScreenDC.DrawString("press * to end game", new Font("Arial", 10, System.Drawing.FontStyle.Bold), new SolidBrush(Color.White), 92, 186);
}
g.DrawImage(offScreenBmp, 0, 0);
}
private void t_Tick(object sender, EventArgs e)
{
if (ballPosX < 0)
{
p2score++;
ballPosX = 10;
ballPosY = p1;
//for (int i=0; i<ballPrevX.Length; i++)
//{
// ballPrevX[i] = ballPosX;
// ballPrevY[i] = ballPosY;
//}
double angle = r.NextDouble()*(Math.PI/2)-(Math.PI/4);
ballVelX = Math.Cos(angle)*4.0;
ballVelY = Math.Sin(angle)*4.0;
paused = true;
}
else if (ballPosX > 320)
{
p1score++;
ballPosX = 310;
ballPosY = p2;
//for (int i=0; i<ballPrevX.Length; i++)
//{
// ballPrevX[i] = ballPosX;
// ballPrevY[i] = ballPosY;
//}
double angle = r.NextDouble()*(Math.PI/2)+(3*Math.PI/4);
ballVelX = Math.Cos(angle)*4.0;
ballVelY = Math.Sin(angle)*4.0;
paused = true;
}
if (UPARROW_DOWN)
p2v = -pSpeed;
else if (DOWNARROW_DOWN)
p2v = pSpeed;
if (difficulty != 0)
{
int skill=20;
if (difficulty == 1)
skill = 27;
else if (difficulty == 2)
skill = 17;
else if (difficulty == 3)
skill = 8;
if (ballPosX < (240+skill*ballVelX) && Math.Abs(ballPosY-p1) > pSize/2-3)
{
if (ballPosY < p1 )
p1v = -pSpeed;
else
p1v = pSpeed;
}
if (paused)
{
if (!(p1 > 95 && p1 < 115))
{
if (p1 > 105)
p1v = -pSpeed;
if (p1 < 105)
p1v = pSpeed;
}
}
}
else
{
if (W_DOWN)
p1v = -pSpeed;
else if (S_DOWN)
p1v = pSpeed;
}
p1 += p1v;
p2 += p2v;
// .95 = default; friction
p1v *= .70;
p2v *= .70;
if (!paused)
{
ballPosX += ballVelX;
ballPosY += ballVelY;
}
else
ballPosY = (ballPosX < 160) ? p1 : p2;
if (p1 < pSize/2)
p1 = pSize/2;
else if (p1 > scrHeight-pSize/2)
p1 = scrHeight-pSize/2;
if (p2 < pSize/2)
p2 = pSize/2;
else if (p2 > scrHeight-pSize/2)
p2 = scrHeight-pSize/2;
if (ballPosX < 10 && ballPosX > 1 && ballPosY > p1-pSize/2 && ballPosY < p1+pSize/2)
{
ballPosX = 8;
double angle = ((ballPosY-p1)/pSize)*Math.PI/5;
double tVel = Math.Sqrt(ballVelX*ballVelX+ballVelY*ballVelY) + Math.Abs(ballPosY-p1)*.05; // .02 = default
ballVelX = Math.Cos(angle)*tVel;
ballVelY = Math.Sin(angle)*tVel;
// collisionSoundLow.play();
}
else if (ballPosX > 310 && ballPosX < 319 && ballPosY > p2-pSize/2 && ballPosY < p2+pSize/2)
{
ballPosX = 310;
double angle = Math.PI-((ballPosY-p2)/pSize)*Math.PI/5;
double tVel = Math.Sqrt(ballVelX*ballVelX+ballVelY*ballVelY) + Math.Abs(ballPosY-p2)*.05; // .02 = default
ballVelX = Math.Cos(angle)*tVel;
ballVelY = Math.Sin(angle)*tVel;
// collisionSoundHigh.play();
}
if (ballPosY < 3)
{
ballPosY = 3;
ballVelY = Math.Abs(ballVelY);
// collisionSoundWall.play();
}
else if (ballPosY > 207)
{
ballPosY = 207;
ballVelY = -Math.Abs(ballVelY);
// collisionSoundWall.play();
}
Invalidate();
}
private void Form1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
if (e.KeyCode.ToString() == "Up" || e.KeyCode.ToString() == "D3")
UPARROW_DOWN = true;
else if (e.KeyCode.ToString() == "Down" || e.KeyCode.ToString() == "D9")
DOWNARROW_DOWN = true;
else if (e.KeyCode.ToString() == "W")
W_DOWN = true;
else if (e.KeyCode.ToString() == "Z")
S_DOWN = true;
else if (e.KeyCode.ToString() == "Left")
{
if (infoBox)
{
difficulty--;
if (difficulty < 0)
difficulty = difficultyNames.Length-1;
}
}
else if (e.KeyCode.ToString() == "Right")
{
if (infoBox)
{
difficulty++;
if (difficulty > difficultyNames.Length-1)
difficulty = 0;
}
}
else if (e.KeyCode.ToString() == "D0")
{
infoBox = false;
paused = false;
}
else if (e.KeyCode.ToString() == "Return")
{
infoBox = false;
paused = false;
}
else if (e.KeyCode.ToString() == "F8")
{
p1score = 0;
p2score = 0;
paused = true;
infoBox = true;
ballPosX = 7;
ballPosY = p1;
double angle = r.NextDouble()*(Math.PI/2)-(Math.PI/4);
ballVelX = Math.Cos(angle)*4.0;
ballVelY = Math.Sin(angle)*4.0;
}
else if (e.KeyCode.ToString() == "F9")
Application.Exit();
}
private void Form1_KeyUp(object sender, System.Windows.Forms.KeyEventArgs e)
{
if (e.KeyCode.ToString() == "Up" || e.KeyCode.ToString() == "D3")
UPARROW_DOWN = false;
else if (e.KeyCode.ToString() == "Down" || e.KeyCode.ToString() == "D9")
DOWNARROW_DOWN = false;
else if (e.KeyCode.ToString() == "W")
W_DOWN = false;
else if (e.KeyCode.ToString() == "Z")
S_DOWN = false;
}
}
}
| |
// Copyright (c) 2015, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Linq;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using WebsitePanel.EnterpriseServer;
using WebsitePanel.Providers;
using WebsitePanel.Providers.Web;
using WebsitePanel.Providers.Common;
using WebsitePanel.Portal.Code.Helpers;
using WebsitePanel.Providers.ResultObjects;
namespace WebsitePanel.Portal
{
public partial class WebSitesEditSite : WebsitePanelModuleBase
{
/// <summary>
/// Use this variable to define additional tabs to in the control
/// </summary>
private List<Tab> TabsList = new List<Tab>()
{
new Tab { Id = "home", ResourceKey = "Tab.HomeFolder", ViewId = "tabHomeFolder" },
new Tab { Id = "vdirs", ResourceKey = "Tab.VirtualDirs", Quota = Quotas.WEB_VIRTUALDIRS, ViewId = "tabVirtualDirs" },
new Tab { Id = "securedfolders", ResourceKey = "Tab.SecuredFolders", Quota = Quotas.WEB_SECUREDFOLDERS, ViewId = "tabSecuredFolders" },
new Tab { Id = "htaccessfolders", ResourceKey = "Tab.Htaccess", Quota = Quotas.WEB_HTACCESS, ViewId = "tabHeliconApe" },
new Tab { Id = "frontpage", ResourceKey = "Tab.FrontPage", Quota = Quotas.WEB_FRONTPAGE, ViewId = "tabFrontPage" },
new Tab { Id = "extensions", ResourceKey = "Tab.Extensions", ViewId = "tabExtensions" },
new Tab { Id = "HeliconZoo", ResourceKey = "Tab.HeliconZoo", Quota = Quotas.HELICON_ZOO, ResourceGroup = "HeliconZoo", ViewId = "tabHeliconZoo" },
new Tab { Id = "errors", ResourceKey = "Tab.CustomErrors", Quota = Quotas.WEB_ERRORS, ViewId = "tabErrors" },
new Tab { Id = "headers", ResourceKey = "Tab.CustomHeaders", Quota = Quotas.WEB_HEADERS, ViewId = "tabHeaders" },
new Tab { Id = "webpub", ResourceKey = "Tab.WebDeployPublishing", Quota = Quotas.WEB_REMOTEMANAGEMENT, ViewId = "tabWebDeployPublishing" },
new Tab { Id = "mime", ResourceKey = "Tab.MIMETypes", Quota = Quotas.WEB_MIME, ViewId = "tabMimes" },
new Tab { Id = "coldfusion", ResourceKey = "Tab.ColdFusion", Quota = Quotas.WEB_COLDFUSION, ViewId = "tabCF" },
new Tab { Id = "webman", ResourceKey = "Tab.WebManagement", Quota = Quotas.WEB_REMOTEMANAGEMENT, ViewId = "tabWebManagement" },
new Tab { Id = "SSL", ResourceKey = "Tab.SSL", Quota = Quotas.WEB_SSL, ViewId = "SSL" },
};
protected string SharedIdAddres { get; set; }
private int PackageId
{
get { return (int)ViewState["PackageId"]; }
set { ViewState["PackageId"] = value; }
}
private bool AllowSsl
{
get { return (bool)ViewState["AllowSsl"]; }
set { ViewState["AllowSsl"] = value; }
}
private bool IIs7
{
get { return (bool)ViewState["IIs7"]; }
set { ViewState["IIs7"] = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
// Retrieve localized tab names as per file resources
// and assign Web resource group by default if otherwise specified
TabsList.ForEach((x) =>
{
x.Name = GetLocalizedString(x.ResourceKey);
x.ResourceGroup = x.ResourceGroup ?? ResourceGroups.Web;
});
//
if (!IsPostBack)
{
BindWebSite();
if (GetLocalizedString("buttonPanel.OnSaveClientClick")!=null)
buttonPanel.OnSaveClientClick = GetLocalizedString("buttonPanel.OnSaveClientClick");
}
}
private void BindTabs()
{
var filteredTabs = TabsList.FilterTabsByHostingPlanQuotas(PackageId).ToList();
// remove "SSL" tab for a site with dynamic IP and not SNI enabled
var sslTab = filteredTabs.SingleOrDefault(t => t.Id == "SSL");
if (!AllowSsl && sslTab != null)
filteredTabs.Remove(sslTab);
var selectedValue = dlTabs.SelectedValue;
if (dlTabs.SelectedIndex == -1)
{
if (!IsPostBack && String.IsNullOrEmpty(Request["MenuID"]) == false)
{
// Find menu item requested
var st = filteredTabs.SingleOrDefault(x => x.Id.Equals(Request["MenuID"]));
//
if (st != null)
{
selectedValue = st.ViewId;
//
dlTabs.SelectedIndex = Array.IndexOf(filteredTabs.ToArray(), st);
}
}
else
{
// Select "Home Folder" tab by default
dlTabs.SelectedIndex = 0;
}
}
// Bind data to the view
dlTabs.DataSource = filteredTabs;
dlTabs.DataBind();
// Select active view corresponding to the tab selected
tabs.SetActiveViewById(selectedValue as string);
}
protected void dlTabs_SelectedIndexChanged(object sender, EventArgs e)
{
BindTabs();
}
private void BindWebSite()
{
WebSite site = null;
try
{
site = ES.Services.WebServers.GetWebSite(PanelRequest.ItemID);
}
catch (Exception ex)
{
ShowErrorMessage("WEB_GET_SITE", ex);
return;
}
if (site == null)
RedirectToBrowsePage();
// IIS 7.0 mode
IIs7 = site.IIs7;
PackageId = site.PackageId;
// bind site
lnkSiteName.Text = site.Name;
lnkSiteName.NavigateUrl = "http://" + site.Name;
// bind unassigned IP addresses
ddlIpAddresses.Items.Clear();
PackageIPAddress[] ips = ES.Services.Servers.GetPackageUnassignedIPAddresses(site.PackageId, 0, IPAddressPool.WebSites);
foreach (PackageIPAddress ip in ips)
{
string fullIP = ip.ExternalIP;
if (ip.InternalIP != null &&
ip.InternalIP != "" &&
ip.InternalIP != ip.ExternalIP)
fullIP += " (" + ip.InternalIP + ")";
ddlIpAddresses.Items.Add(new ListItem(fullIP, ip.PackageAddressID.ToString()));
}
if (site.IsDedicatedIP)
{
litIPAddress.Text = site.SiteIPAddress;
}
else
{
IPAddressInfo[] ipsGeneral = ES.Services.Servers.GetIPAddresses(IPAddressPool.General, PanelRequest.ServerId);
bool generalIPExists = ipsGeneral.Any() && !string.IsNullOrEmpty(ipsGeneral[0].ExternalIP);
if (generalIPExists)
{
lblSharedIP.Text = string.Format("({0})", ipsGeneral[0].ExternalIP);
}
lblSharedIP.Visible = generalIPExists;
}
dedicatedIP.Visible = site.IsDedicatedIP;
sharedIP.Visible = !site.IsDedicatedIP;
PackageContext cntx = PackagesHelper.GetCachedPackageContext(PanelSecurity.PackageId);
if (Utils.CheckQouta(Quotas.WEB_ALLOWIPADDRESSMODESWITCH, cntx))
cmdSwitchToDedicatedIP.Visible = (ddlIpAddresses.Items.Count > 0);
else
cmdSwitchToDedicatedIP.Visible = cmdSwitchToSharedIP.Visible = false;
litFrontPageUnavailable.Visible = false;
tblSharePoint.Visible = site.SharePointInstalled;
tblFrontPage.Visible = !site.SharePointInstalled;
if (!site.ColdFusionAvailable)
{
litCFUnavailable.Text = GetLocalizedString("Text.COLDFUSION_UNAVAILABLE");
litCFUnavailable.Visible = true;
rowCF.Visible = false;
rowVirtDir.Visible = false;
}
else
{
if (site.ColdFusionVersion.Equals("7"))
{
litCFUnavailable.Text = "ColdFusion 7.x is installed";
litCFUnavailable.Visible = true;
}
else
{
if (site.ColdFusionVersion.Equals("8"))
litCFUnavailable.Text = "ColdFusion 8.x is installed";
litCFUnavailable.Visible = true;
}
if (site.ColdFusionVersion.Equals("9"))
litCFUnavailable.Text = "ColdFusion 9.x is installed";
litCFUnavailable.Visible = true;
if (site.ColdFusionVersion.Equals("10"))
litCFUnavailable.Text = "ColdFusion 10.x is installed";
litCFUnavailable.Visible = true;
if (site.ColdFusionVersion.Equals("11"))
litCFUnavailable.Text = "ColdFusion 11.x is installed";
litCFUnavailable.Visible = true;
if (site.ColdFusionVersion.Equals("12"))
litCFUnavailable.Text = "ColdFusion 12.x is installed";
litCFUnavailable.Visible = true;
}
if (!PackagesHelper.CheckGroupQuotaEnabled(PackageId, ResourceGroups.Web, Quotas.WEB_CFVIRTUALDIRS))
{
//virtual directories are not implemented for IIS 7
rowVirtDir.Visible = false;
}
chkCfExt.Checked = site.ColdFusionInstalled;
chkVirtDir.Checked = site.CreateCFVirtualDirectories;
// bind FrontPage
if (!site.FrontPageAvailable)
{
litFrontPageUnavailable.Text = GetLocalizedString("Text.FPSE_UNAVAILABLE");
litFrontPageUnavailable.Visible = true;
tblFrontPage.Visible = false;
}
else
{
// set control policies
frontPageUsername.SetPackagePolicy(site.PackageId, UserSettings.WEB_POLICY, "FrontPageAccountPolicy");
frontPagePassword.SetPackagePolicy(site.PackageId, UserSettings.WEB_POLICY, "FrontPagePasswordPolicy");
// set default account name
frontPageUsername.Text = site.FrontPageAccount;
ToggleFrontPageControls(site.FrontPageInstalled);
}
AppPoolRestartPanel.Visible = Utils.CheckQouta(Quotas.WEB_APPPOOLSRESTART, cntx);
// bind controls
webSitesHomeFolderControl.BindWebItem(PackageId, site);
webSitesSecuredFoldersControl.BindSecuredFolders(site);
webSitesHeliconApeControl.BindHeliconApe(site);
webSitesExtensionsControl.BindWebItem(PackageId, site);
webSitesMimeTypesControl.BindWebItem(site);
webSitesCustomHeadersControl.BindWebItem(site);
webSitesCustomErrorsControl.BindWebItem(site);
webSitesHeliconZooControl.BindWebItem(site);
// If SNI is enabled on the server, we do allow for SSL even if site not has dedicated Ip
if (site.IsDedicatedIP || site.SniEnabled)
{
AllowSsl = true;
WebsitesSSLControl.Visible = true;
WebsitesSSLControl.BindWebItem(site);
}
else
{
AllowSsl = false;
WebsitesSSLControl.Visible = false;
}
BindVirtualDirectories();
// bind state
BindSiteState(site.SiteState);
// AppPool
AppPoolState appPoolState = ES.Services.WebServers.GetAppPoolState(PanelRequest.ItemID);
BindAppPoolState(appPoolState);
// bind pointers
BindPointers();
// save packageid
ViewState["PackageID"] = site.PackageId;
//
ToggleWmSvcControls(site);
//
if (!site.GetValue<bool>(WebVirtualDirectory.WmSvcSiteEnabled))
{
txtWmSvcAccountName.Text = AutoSuggestWmSvcAccontName(site, "_admin");
}
ToggleWmSvcConnectionHint(site);
// Web Deploy Publishing
ToggleWebDeployPublishingControls(site);
BindWebPublishingProfileDatabases();
BindWebPublishingProfileDatabaseUsers();
BindWebPublishingProfileFtpAccounts(site);
// bind tabs
BindTabs();
}
#region Web Deploy Publishing
protected void WDeployEnabePublishingButton_Click(object sender, EventArgs e)
{
if (!Page.IsValid)
return;
//
GrantWebDeployPublishingAccess(WDeployPublishingAccountTextBox.Text.Trim(), WDeployPublishingPasswordTextBox.Text);
//
BindWebSite();
}
protected void MyDatabaseList_SelectedIndexChanged(object sender, EventArgs e)
{
//
BindWebPublishingProfileDatabaseUsers();
}
private void GrantWebDeployPublishingAccess(string accountName, string accountPassword)
{
//
ResultObject result = ES.Services.WebServers.GrantWebDeployPublishingAccess(PanelRequest.ItemID, accountName, accountPassword);
//
if (!result.IsSuccess)
{
messageBox.ShowMessage(result, "WEB_PUB_ENABLE", "IIS7");
return;
}
//
messageBox.ShowSuccessMessage("WEB_PUB_ENABLE");
}
protected void WDeployChangePublishingPasswButton_Click(object sender, EventArgs e)
{
if (!Page.IsValid || WDeployPublishingPasswordTextBox.Text.Equals(PasswordControl.EMPTY_PASSWORD))
return;
//
ChangeWDeployAccountPassword(PanelRequest.ItemID, WDeployPublishingPasswordTextBox.Text);
}
private void ChangeWDeployAccountPassword(int siteItemId, string newAccountPassword)
{
try
{
//
var result = ES.Services.WebServers.ChangeWebDeployPublishingPassword(siteItemId, newAccountPassword);
//
if (result.IsSuccess == false)
{
messageBox.ShowErrorMessage("WPUB_PASSW_CHANGE");
return;
}
//
messageBox.ShowSuccessMessage("WPUB_PASSW_CHANGE");
}
catch (Exception ex)
{
messageBox.ShowErrorMessage("WPUB_PASSW_CHANGE", ex);
}
}
protected void WDeployDownloadPubProfileLink_Command(object sender, CommandEventArgs e)
{
DownloadWDeployPublishingProfile((string)e.CommandArgument);
}
private void DownloadWDeployPublishingProfile(string siteName)
{
// download file
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + String.Format("{0}.publishsettings", siteName));
Response.ContentType = "application/octet-stream";
var result = default(BytesResult);
try
{
// read remote content
result = ES.Services.WebServers.GetWebDeployPublishingProfile(PanelRequest.ItemID);
//
if (result.IsSuccess == false)
{
messageBox.ShowErrorMessage("WDEPLOY_GET_PROFILE");
//
return;
}
}
catch (Exception ex)
{
messageBox.ShowErrorMessage("FILES_READ_FILE", ex);
return;
}
// write to stream
Response.BinaryWrite(result.Value);
//
Response.End();
}
protected void WDeployDisablePublishingButton_Click(object sender, EventArgs e)
{
DisableWebDeployPublishing();
//
BindWebSite();
}
private void DisableWebDeployPublishing()
{
try
{
ES.Services.WebServers.RevokeWebDeployPublishingAccess(PanelRequest.ItemID);
//
messageBox.ShowSuccessMessage("WEB_PUB_DISABLE");
}
catch (Exception ex)
{
messageBox.ShowErrorMessage("WEB_PUB_DISABLE", ex);
}
}
protected void PubProfileWizardOkButton_Click(object sender, EventArgs e)
{
if (!Page.IsValid)
return;
//
SaveWebDeployPublishingProfile();
//
BindWebSite();
}
private void SaveWebDeployPublishingProfile()
{
var ids = new List<int>();
// Add FTP account to profile
if (String.IsNullOrEmpty(MyFtpAccountList.SelectedValue) != true)
{
ids.Add(Convert.ToInt32(MyFtpAccountList.SelectedValue));
}
// Add database to profile
if (String.IsNullOrEmpty(MyDatabaseList.SelectedValue) != true)
{
ids.Add(Convert.ToInt32(MyDatabaseList.SelectedValue));
}
// Add database user to profile
if (String.IsNullOrEmpty(MyDatabaseUserList.SelectedValue) != true)
{
ids.Add(Convert.ToInt32(MyDatabaseUserList.SelectedValue));
}
//
var result = ES.Services.WebServers.SaveWebDeployPublishingProfile(PanelRequest.ItemID, ids.ToArray());
//
if (!result.IsSuccess)
{
messageBox.ShowMessage(result, "WPUB_PROFILE_SAVE", "IIS7");
return;
}
//
messageBox.ShowSuccessMessage("WPUB_PROFILE_SAVE");
}
private void DisableChildControlsOfType(Control ctl, params Type[] ctlTypes)
{
foreach (Control cc in ctl.Controls)
{
if (Array.Exists(ctlTypes, x =>
{
return cc.GetType().Equals(x);
}))
{
cc.Visible = false;
}
// Disable child controls recursively if any
if (cc.Controls.Count > 0)
{
DisableChildControlsOfType(cc, ctlTypes);
}
}
}
private void EnableControlsInBulk(params Control[] ctls)
{
foreach (var item in ctls)
{
item.Visible = true;
}
}
private void ToggleWebDeployPublishingControls(WebVirtualDirectory item)
{
// Disable all child controls
DisableChildControlsOfType(tabWebDeployPublishing, typeof(PlaceHolder), typeof(Button), typeof(TextBox), typeof(Literal));
// Cleanup password text boxes
WDeployPublishingPasswordTextBox.Text = WDeployPublishingPasswordTextBox.Attributes["value"] = String.Empty;
WDeployPublishingConfirmPasswordTextBox.Text = WDeployPublishingConfirmPasswordTextBox.Attributes["value"] = String.Empty;
// Step 1: Web Deploy feature is not installed on the server
if (item.WebDeployPublishingAvailable == false)
{
// Enable panels
EnableControlsInBulk(PanelWDeployNotInstalled);
//
return;
}
// Step 2: Web Deploy feature is available but not publishing enabled for the web site yet
if (item.WebDeploySitePublishingEnabled == false)
{
// Enable controls
EnableControlsInBulk(
PanelWDeploySitePublishingDisabled,
PanelWDeployPublishingCredentials,
WDeployEnabePublishingButton,
WDeployPublishingAccountTextBox,
WDeployPublishingPasswordTextBox,
WDeployPublishingConfirmPasswordTextBox,
WDeployPublishingAccountRequiredFieldValidator);
WDeployPublishingAccountTextBox.Text = AutoSuggestWmSvcAccontName(item, "_dploy");
//
WDeployPublishingAccountRequiredFieldValidator.Enabled = true;
//
return;
}
// Step 3: Publishing has been enabled for the web site
if (item.WebDeploySitePublishingEnabled == true)
{
// Enable controls
EnableControlsInBulk(
PanelWDeployPublishingCredentials,
WDeployChangePublishingPasswButton,
WDeployDisablePublishingButton,
WDeployPublishingAccountLiteral,
WDeployPublishingPasswordTextBox,
WDeployPublishingConfirmPasswordTextBox);
// Disable user name validation
WDeployPublishingAccountRequiredFieldValidator.Enabled = false;
// Display plain-text publishing account name
WDeployPublishingAccountLiteral.Text = item.WebDeployPublishingAccount;
// Miscellaneous
// Enable empty publishing password for stylistic purposes
WDeployPublishingPasswordTextBox.Text = PasswordControl.EMPTY_PASSWORD;
WDeployPublishingPasswordTextBox.Attributes["value"] = PasswordControl.EMPTY_PASSWORD;
// Enable empty publishing password confirmation for stylistic purposes
WDeployPublishingConfirmPasswordTextBox.Text = PasswordControl.EMPTY_PASSWORD;
WDeployPublishingConfirmPasswordTextBox.Attributes["value"] = PasswordControl.EMPTY_PASSWORD;
}
// Step 4: Publishing has been enabled and publishing profile has been built
if (item.WebDeploySitePublishingEnabled == true)
{
// Enable controls
EnableControlsInBulk(PanelWDeployManagePublishingProfile);
// Save web site name as a command argument for the link
WDeployDownloadPubProfileLink.CommandArgument = item.Name;
}
}
private void BindWebPublishingProfileDatabases()
{
MyDatabaseList.DataSource = ES.Services.DatabaseServers.GetSqlDatabases(PanelSecurity.PackageId, null, false);
MyDatabaseList.DataBind();
//
MyDatabaseList.Items.Insert(0, new ListItem(GetLocalizedString("WebPublishing.ChooseDatabasePrompt"), String.Empty));
}
private void BindWebPublishingProfileDatabaseUsers()
{
//
if (String.IsNullOrEmpty(MyDatabaseList.SelectedValue) == false)
{
var dbItem = ES.Services.DatabaseServers.GetSqlDatabase(Convert.ToInt32(MyDatabaseList.SelectedValue));
//
var sqlUsers = ES.Services.DatabaseServers.GetSqlUsers(PanelSecurity.PackageId, dbItem.GroupName, false);
//
MyDatabaseUserList.DataSource = Array.FindAll(sqlUsers, x => Array.Exists(dbItem.Users, y => y.Equals(x.Name)));
MyDatabaseUserList.DataBind();
}
else
{
MyDatabaseUserList.Items.Clear();
}
//
MyDatabaseUserList.Items.Insert(0, new ListItem(GetLocalizedString("WebPublishing.ChooseDatabaseUserPrompt"), String.Empty));
}
private void BindWebPublishingProfileFtpAccounts(WebVirtualDirectory item)
{
var ftpAccounts = ES.Services.FtpServers.GetFtpAccounts(PanelSecurity.PackageId, false);
//
MyFtpAccountList.DataSource = Array.FindAll(ftpAccounts, x => x.Folder.Equals(item.ContentPath));
MyFtpAccountList.DataBind();
//
MyFtpAccountList.Items.Insert(0, new ListItem(GetLocalizedString("WebPublishing.ChooseFtpAccountPrompt"), String.Empty));
}
#endregion
#region WmSvc Management
private string AutoSuggestWmSvcAccontName(WebVirtualDirectory item, string suffix)
{
string autoSuggestedPart = item.Name;
//
if (autoSuggestedPart.Length > 14)
{
autoSuggestedPart = autoSuggestedPart.Substring(0, 14);
//
while (!String.IsNullOrEmpty(autoSuggestedPart) &&
!Char.IsLetterOrDigit(autoSuggestedPart[autoSuggestedPart.Length - 1]))
{
autoSuggestedPart = autoSuggestedPart.Substring(0, autoSuggestedPart.Length - 1);
}
}
//
return autoSuggestedPart + suffix;
}
private void ToggleWmSvcControls(WebVirtualDirectory item)
{
if (!item.GetValue<bool>(WebVirtualDirectory.WmSvcAvailable))
{
pnlWmcSvcManagement.Visible = false;
pnlNotInstalled.Visible = true;
//
return;
}
//
pnlWmcSvcManagement.Visible = true;
pnlNotInstalled.Visible = false;
//
string wmSvcAccountName = item.GetValue<string>(WebVirtualDirectory.WmSvcAccountName);
bool wmcSvcSiteEnabled = item.GetValue<bool>(WebVirtualDirectory.WmSvcSiteEnabled);
btnWmSvcSiteEnable.Visible = true;
txtWmSvcAccountName.Visible = true;
//
txtWmSvcAccountPassword.Text = txtWmSvcAccountPassword.Attributes["value"] = String.Empty;
//
txtWmSvcAccountPasswordC.Text = txtWmSvcAccountPasswordC.Attributes["value"] = String.Empty;
// Disable edit mode if WmSvc account name is set
if (wmcSvcSiteEnabled)
{
btnWmSvcSiteEnable.Visible = false;
txtWmSvcAccountName.Visible = false;
//
txtWmSvcAccountPassword.Text = PasswordControl.EMPTY_PASSWORD;
txtWmSvcAccountPassword.Attributes["value"] = PasswordControl.EMPTY_PASSWORD;
//
txtWmSvcAccountPasswordC.Text = PasswordControl.EMPTY_PASSWORD;
txtWmSvcAccountPasswordC.Attributes["value"] = PasswordControl.EMPTY_PASSWORD;
}
//
litWmSvcAccountName.Visible = wmcSvcSiteEnabled;
btnWmSvcSiteDisable.Visible = wmcSvcSiteEnabled;
btnWmSvcChangePassw.Visible = wmcSvcSiteEnabled;
pnlWmSvcSiteDisabled.Visible = !wmcSvcSiteEnabled;
pnlWmSvcSiteEnabled.Visible = wmcSvcSiteEnabled;
//
txtWmSvcAccountName.Text = wmSvcAccountName;
litWmSvcAccountName.Text = wmSvcAccountName;
}
private void ToggleWmSvcConnectionHint(WebVirtualDirectory item)
{
bool wmcSvcSiteEnabled = item.GetValue<bool>(WebSite.WmSvcSiteEnabled);
//
if (wmcSvcSiteEnabled)
{
//
string wmSvcServicePort = item.GetValue<String>(WebSite.WmSvcServicePort);
string wmSvcServiceUrl = item.GetValue<String>(WebSite.WmSvcServiceUrl);
//
if (!String.IsNullOrEmpty(wmSvcServiceUrl))
{
if (!String.IsNullOrEmpty(wmSvcServicePort)
&& !String.Equals(wmSvcServicePort, WebSite.WmSvcDefaultPort))
lclWmSvcConnectionHint.Text = String.Format(
lclWmSvcConnectionHint.Text, String.Format("{0}:{1}", wmSvcServiceUrl, wmSvcServicePort), item.Name);
else
lclWmSvcConnectionHint.Text = String.Format(
lclWmSvcConnectionHint.Text, wmSvcServiceUrl, item.Name);
}
else
lclWmSvcConnectionHint.Visible = false;
}
}
protected void btnWmSvcSiteEnable_Click(object sender, EventArgs e)
{
if (!Page.IsValid)
return;
//
string accountName = txtWmSvcAccountName.Text.Trim();
string accountPassword = txtWmSvcAccountPassword.Text;
//
ResultObject result = ES.Services.WebServers.GrantWebManagementAccess(PanelRequest.ItemID, accountName, accountPassword);
//
if (!result.IsSuccess)
{
messageBox.ShowMessage(result, "IIS7_WMSVC", "IIS7");
return;
}
//
messageBox.ShowSuccessMessage("Iis7WmSvc_Enabled");
//
BindWebSite();
}
protected void btnWmSvcChangePassw_Click(object sender, EventArgs e)
{
if (!Page.IsValid)
return;
//
string accountPassword = txtWmSvcAccountPassword.Text;
//
ResultObject result = ES.Services.WebServers.ChangeWebManagementAccessPassword(
PanelRequest.ItemID, accountPassword);
//
if (!result.IsSuccess)
{
messageBox.ShowMessage(result, "IIS7_WMSVC", "IIS7");
return;
}
//
messageBox.ShowSuccessMessage("Iis7WmSvc_PasswordChanged");
//
BindWebSite();
}
protected void btnWmSvcSiteDisable_Click(object sender, EventArgs e)
{
//
string accountName = txtWmSvcAccountName.Text.Trim();
//
ES.Services.WebServers.RevokeWebManagementAccess(PanelRequest.ItemID);
//
messageBox.ShowSuccessMessage("Iis7WmSvc_Disabled");
//
BindWebSite();
}
#endregion
#region FrontPage
private void ToggleFrontPageControls(bool installed)
{
// status
litFrontPageStatus.Text = installed ? GetLocalizedString("Text.FPSE_INSTALLED") : GetLocalizedString("Text.FPSE_NOT_INSTALLED");
if (!installed)
frontPageUsername.Text = "";
frontPageUsername.EditMode = installed;
// toggle buttons
btnInstallFrontPage.Visible = !installed;
btnUninstallFrontPage.Visible = installed;
btnChangeFrontPagePassword.Visible = installed;
pnlFrontPage.DefaultButton = installed ? "btnChangeFrontPagePassword" : "btnInstallFrontPage";
}
protected void btnInstallFrontPage_Click(object sender, EventArgs e)
{
try
{
int result = ES.Services.WebServers.InstallFrontPage(PanelRequest.ItemID,
frontPageUsername.Text, frontPagePassword.Password);
if (result < 0)
{
ShowResultMessage(result);
return;
}
ShowSuccessMessage("WEB_FP_INSTALL");
frontPagePassword.Password = "";
frontPageUsername.Text = frontPageUsername.Text;
ToggleFrontPageControls(true);
}
catch (Exception ex)
{
ShowErrorMessage("WEB_FP_INSTALL", ex);
return;
}
}
protected void btnChangeFrontPagePassword_Click(object sender, EventArgs e)
{
try
{
int result = ES.Services.WebServers.ChangeFrontPagePassword(PanelRequest.ItemID,
frontPagePassword.Password);
if (result < 0)
{
ShowResultMessage(result);
return;
}
ShowSuccessMessage("WEB_FP_CHANGE_PASSWORD");
}
catch (Exception ex)
{
ShowErrorMessage("WEB_FP_CHANGE_PASSWORD", ex);
return;
}
}
protected void btnUninstallFrontPage_Click(object sender, EventArgs e)
{
try
{
int result = ES.Services.WebServers.UninstallFrontPage(PanelRequest.ItemID);
if (result < 0)
{
ShowResultMessage(result);
return;
}
ShowSuccessMessage("WEB_FP_UNINSTALL");
ToggleFrontPageControls(false);
}
catch (Exception ex)
{
ShowErrorMessage("WEB_FP_UNINSTALL", ex);
return;
}
}
#endregion
private void BindVirtualDirectories()
{
gvVirtualDirectories.DataSource = ES.Services.WebServers.GetVirtualDirectories(PanelRequest.ItemID);
gvVirtualDirectories.DataBind();
}
private void BindPointers()
{
gvPointers.DataSource = ES.Services.WebServers.GetWebSitePointers(PanelRequest.ItemID);
gvPointers.DataBind();
}
private void SaveWebSite()
{
if (!Page.IsValid)
return;
// load original web site item
WebSite site = ES.Services.WebServers.GetWebSite(PanelRequest.ItemID);
// collect form data
site.FrontPageAccount = frontPageUsername.Text;
site.ColdFusionInstalled = chkCfExt.Checked;
site.CreateCFVirtualDirectories = chkVirtDir.Checked;
// other controls
webSitesExtensionsControl.SaveWebItem(site);
webSitesHomeFolderControl.SaveWebItem(site);
webSitesMimeTypesControl.SaveWebItem(site);
webSitesCustomHeadersControl.SaveWebItem(site);
webSitesCustomErrorsControl.SaveWebItem(site);
webSitesHeliconZooControl.SaveWebItem(site);
// update web site
try
{
int result = ES.Services.WebServers.UpdateWebSite(site);
if (result < 0)
{
ShowResultMessage(result);
return;
}
ShowSuccessMessage("WEB_UPDATE_SITE");
}
catch (Exception ex)
{
ShowErrorMessage("WEB_UPDATE_SITE", ex);
return;
}
}
private void DeleteWebSite()
{
try
{
int result = ES.Services.WebServers.DeleteWebSite(PanelRequest.ItemID, chkDeleteWebsiteDirectory.Checked);
if (result < 0)
{
ShowResultMessage(result);
return;
}
}
catch (Exception ex)
{
ShowErrorMessage("WEB_DELETE_SITE", ex);
return;
}
RedirectSpaceHomePage();
}
protected void btnSave_Click(object sender, EventArgs e)
{
SaveWebSite();
}
protected void btnSaveExit_Click(object sender, EventArgs e)
{
SaveWebSite();
RedirectSpaceHomePage();
}
protected void btnDelete_Click(object sender, EventArgs e)
{
DeleteWebSite();
}
protected void btnAddVirtualDirectory_Click(object sender, EventArgs e)
{
Response.Redirect(EditUrl("ItemID", PanelRequest.ItemID.ToString(), "add_vdir",
PortalUtils.SPACE_ID_PARAM + "=" + PanelSecurity.PackageId.ToString()));
}
#region Site State
private void BindSiteState(ServerState state)
{
if (state == ServerState.Continuing)
state = ServerState.Started;
litStatus.Text = GetLocalizedString("SiteState." + state.ToString());
cmdStart.Visible = (state == ServerState.Stopped);
cmdContinue.Visible = (state == ServerState.Paused);
cmdPause.Visible = (state == ServerState.Started);
cmdStop.Visible = (state == ServerState.Started || state == ServerState.Paused);
}
protected void cmdChangeState_Click(object sender, ImageClickEventArgs e)
{
string stateName = ((ImageButton)sender).CommandName;
ServerState state = (ServerState)Enum.Parse(typeof(ServerState), stateName, true);
try
{
int result = ES.Services.WebServers.ChangeSiteState(PanelRequest.ItemID, state);
if (result < 0)
{
ShowResultMessage(result);
return;
}
BindSiteState(state);
}
catch (Exception ex)
{
ShowErrorMessage("WEB_CHANGE_SITE_STATE", ex);
return;
}
}
// AppPool
private void BindAppPoolState(AppPoolState state)
{
litAppPoolStatus.Text = GetLocalizedString("SiteState." + state.ToString());
cmdAppPoolStart.Visible = (state == AppPoolState.Stopped || state == AppPoolState.Stopping);
cmdAppPoolStop.Visible = (state == AppPoolState.Started || state == AppPoolState.Starting);
cmdAppPoolRecycle.Visible = (state == AppPoolState.Started || state == AppPoolState.Starting);
}
protected void cmdAppPoolChangeState_Click(object sender, EventArgs e)
{
string stateName = ((ImageButton)sender).CommandName;
AppPoolState state = (AppPoolState)Enum.Parse(typeof(AppPoolState), stateName, true);
try
{
int result = ES.Services.WebServers.ChangeAppPoolState(PanelRequest.ItemID, state);
if (result < 0)
{
ShowResultMessage(result);
return;
}
state = ES.Services.WebServers.GetAppPoolState(PanelRequest.ItemID);
BindAppPoolState(state);
}
catch (Exception ex)
{
ShowErrorMessage("WEB_CHANGE_SITE_STATE", ex);
return;
}
}
#endregion
#region Pointers
protected void gvPointers_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int domainId = (int)gvPointers.DataKeys[e.RowIndex][0];
try
{
int result = ES.Services.WebServers.DeleteWebSitePointer(PanelRequest.ItemID, domainId);
if (result < 0)
{
ShowResultMessage(result);
return;
}
ShowSuccessMessage("WEB_DELETE_SITE_POINTER");
}
catch (Exception ex)
{
ShowErrorMessage("WEB_DELETE_SITE_POINTER", ex);
return;
}
// rebind pointers
BindPointers();
}
protected void btnAddPointer_Click(object sender, EventArgs e)
{
Response.Redirect(EditUrl("ItemID", PanelRequest.ItemID.ToString(), "add_pointer",
PortalUtils.SPACE_ID_PARAM + "=" + PanelSecurity.PackageId.ToString()));
}
#endregion
protected void cmdSwitchToDedicatedIP_Click(object sender, EventArgs e)
{
sharedIP.Visible = false;
switchToDedicatedIP.Visible = true;
WebsitesSSLControl.InstalledCert = null;
}
protected void cmdSwitchToSharedIP_Click(object sender, EventArgs e)
{
// call web service
try
{
int result = ES.Services.WebServers.SwitchWebSiteToSharedIP(PanelRequest.ItemID);
if (result < 0)
{
ShowResultMessage(result);
return;
}
ShowSuccessMessage("WEB_SWITCH_TO_SHARED_IP");
dlTabs.SelectedIndex = 0;
WebsitesSSLControl.InstalledCert = null;
}
catch (Exception ex)
{
ShowErrorMessage("WEB_SWITCH_TO_SHARED_IP", ex);
return;
}
// rebind
BindWebSite();
}
protected void cmdApplyDedicatedIP_Click(object sender, EventArgs e)
{
// call web service
try
{
int addressId = Int32.Parse(ddlIpAddresses.SelectedValue);
int result = ES.Services.WebServers.SwitchWebSiteToDedicatedIP(PanelRequest.ItemID, addressId);
if (result < 0)
{
ShowResultMessage(result);
return;
}
ShowSuccessMessage("WEB_SWITCH_TO_DEDICATED_IP");
}
catch (Exception ex)
{
ShowErrorMessage("WEB_SWITCH_TO_DEDICATED_IP", ex);
return;
}
// rebind
HideDedicatedIPPanel();
BindWebSite();
}
protected void cmdCancelDedicatedIP_Click(object sender, EventArgs e)
{
HideDedicatedIPPanel();
}
private void HideDedicatedIPPanel()
{
switchToDedicatedIP.Visible = false;
sharedIP.Visible = 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;
using System.Text;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.Protocols.TestTools;
using Microsoft.Protocols.TestTools.StackSdk;
using Microsoft.Protocols.TestTools.StackSdk.RemoteDesktop.Rdpbcgr;
namespace Microsoft.Protocols.TestSuites.Rdpbcgr
{
public partial class RdpbcgrTestSuite
{
[TestMethod]
[Priority(1)]
[TestCategory("RDP7.0")]
[TestCategory("RDPBCGR")]
[Description(@"This test case is used to verify
SUT drops the connection if the length field within tpktHeader in MCS Attach User Confirm PDU is not consistent with the received data.")]
public void S1_ConnectionTest_ChannelConnection_NegativeTest_MCSAttachUserConfirm_InvalidTPKTLength()
{
#region Test Description
//1. Trigger SUT to initiate a RDP connection and complete the Connection Initiation phase and Basic Setting Exchange phase.
//2. Test Suite expects SUT continue the connection with sending a Client MCS Erect Domain Request PDU and a Client MCS Attach User Request PDU.
//3. Test Suite responds a Server MCS Attach User Confirm PDU to SUT and set the length field of tpktHeader to an invalid value (less than 11).
//4. Test Suite expects SUT drop the connection.
#endregion
#region Test Implementation
//Start RDP listening.
this.TestSite.Log.Add(LogEntryKind.Comment, "Starting RDP listening with transport protocol: {0}", transportProtocol.ToString());
this.rdpbcgrAdapter.StartRDPListening(transportProtocol);
#region Trigger client to initiate a RDP connection
//Trigger client to initiate a RDP connection.
this.TestSite.Log.Add(LogEntryKind.Comment, "Triggering SUT to initiate a RDP connection to server.");
triggerClientRDPConnect(transportProtocol);
#endregion
//Expect the transport layer connection request.
this.TestSite.Log.Add(LogEntryKind.Comment, "Expecting SUT to start a transport layer connection request (TCP).");
this.rdpbcgrAdapter.ExpectTransportConnection(RDPSessionType.Normal);
#region Connection Initiation phase
//Expect SUT send a Client X.224 Connection Request PDU.
this.TestSite.Log.Add(LogEntryKind.Comment, "Expecting SUT to send a Client X.224 Connection Request PDU");
this.rdpbcgrAdapter.ExpectPacket<Client_X_224_Connection_Request_Pdu>(waitTime);
//Respond a Server X.224 Connection Confirm PDU and set the EXTENDED_CLIENT_DATA_SUPPORTED flag.
this.TestSite.Log.Add(LogEntryKind.Comment, "Sending Server X.224 Connection Confirm PDU to SUT. Selected protocol: {0}; Extended Client Data supported: true", selectedProtocol.ToString());
this.rdpbcgrAdapter.Server_X_224_Connection_Confirm(selectedProtocol, true, true, NegativeType.None);
#endregion
#region Basic Setting Exchange phase
//Expect SUT send Client MCS Connect Initial PDU.
this.TestSite.Log.Add(LogEntryKind.Comment, "Expecting SUT to send a Client MCS Connect Initial PDU.");
this.rdpbcgrAdapter.ExpectPacket<Client_MCS_Connect_Initial_Pdu_with_GCC_Conference_Create_Request>(waitTime);
//Respond a Server MCS Connect Response PDU with GCC Conference Create Response.
this.TestSite.Log.Add(LogEntryKind.Comment, "Sending Server MCS Connect Response PDU to SUT. Encryption Method {0}; Encryption Level: {1}; RDP Version Code: {2}.", enMethod.ToString(), enLevel.ToString(), TS_UD_SC_CORE_version_Values.V2.ToString());
this.rdpbcgrAdapter.Server_MCS_Connect_Response(enMethod, enLevel, TS_UD_SC_CORE_version_Values.V2, NegativeType.None);
#endregion
//Expect a Client MCS Erect Domain Request PDU.
this.TestSite.Log.Add(LogEntryKind.Comment, "Expecting SUT to send a Client MCS Erect Domain Request PDU.");
this.rdpbcgrAdapter.ExpectPacket<Client_MCS_Erect_Domain_Request>(waitTime);
//Expect a Client MCS Attach User Request PDU
this.TestSite.Log.Add(LogEntryKind.Comment, "Expecting SUT to send a Client MCS Attach User Request PDU.");
this.rdpbcgrAdapter.ExpectPacket<Client_MCS_Attach_User_Request>(waitTime);
//Respond a Server MCS Attach User Confirm PDU
this.TestSite.Log.Add(LogEntryKind.Comment, "Sending Server MCS Attach User Confirm PDU to SUT with invalid TPK header length");
this.rdpbcgrAdapter.MCSAttachUserConfirm(NegativeType.InvalidTPKLength);
//Expect SUT to drop the connection
this.TestSite.Log.Add(LogEntryKind.Comment, "Expect SUT to drop the connection");
bool bDisconnected = this.rdpbcgrAdapter.WaitForDisconnection(waitTime);
this.TestSite.Assert.IsTrue(bDisconnected, "SUT should drop the connection if the length field within tpktHeader in MCS Attach User Confirm PDU is not consistent with the received data.");
#endregion
}
[TestMethod]
[Priority(1)]
[TestCategory("RDP7.0")]
[TestCategory("RDPBCGR")]
[Description(@"This test case is used to verify
SUT drops the connection connection if the result field in MCS Attach User Confirm PDU is not set to rt-successful (0).")]
public void S1_ConnectionTest_ChannelConnection_NegativeTest_MCSAttachUserConfirm_Failure()
{
#region Test Description
//1. Trigger SUT to initiate a RDP connection and complete the Connection Initiation phase and Basic Setting Exchange phase.
//2. Test Suite expects SUT continue the connection with sending a Client MCS Erect Domain Request PDU and a Client MCS Attach User Request PDU.
//3. Test Suite responds a Server MCS Attach User Confirm PDU to SUT and set the result field in MCS Attach User Confirm PDU is not set to rt-successful (0).
//4. Test Suite expects SUT drop the connection.
#endregion
#region Test Implementation
//Start RDP listening.
this.TestSite.Log.Add(LogEntryKind.Comment, "Starting RDP listening with transport protocol: {0}", transportProtocol.ToString());
this.rdpbcgrAdapter.StartRDPListening(transportProtocol);
#region Trigger client to initiate a RDP connection
//Trigger client to initiate a RDP connection.
this.TestSite.Log.Add(LogEntryKind.Comment, "Triggering SUT to initiate a RDP connection to server.");
triggerClientRDPConnect(transportProtocol);
#endregion
//Expect the transport layer connection request.
this.TestSite.Log.Add(LogEntryKind.Comment, "Expecting SUT to start a transport layer connection request (TCP).");
this.rdpbcgrAdapter.ExpectTransportConnection(RDPSessionType.Normal);
#region Connection Initiation phase
//Expect SUT send a Client X.224 Connection Request PDU.
this.TestSite.Log.Add(LogEntryKind.Comment, "Expecting SUT to send a Client X.224 Connection Request PDU");
this.rdpbcgrAdapter.ExpectPacket<Client_X_224_Connection_Request_Pdu>(waitTime);
//Respond a Server X.224 Connection Confirm PDU and set the EXTENDED_CLIENT_DATA_SUPPORTED flag.
this.TestSite.Log.Add(LogEntryKind.Comment, "Sending Server X.224 Connection Confirm PDU to SUT. Selected protocol: {0}; Extended Client Data supported: true", selectedProtocol.ToString());
this.rdpbcgrAdapter.Server_X_224_Connection_Confirm(selectedProtocol, true, true, NegativeType.None);
#endregion
#region Basic Setting Exchange phase
//Expect SUT send Client MCS Connect Initial PDU.
this.TestSite.Log.Add(LogEntryKind.Comment, "Expecting SUT to send a Client MCS Connect Initial PDU.");
this.rdpbcgrAdapter.ExpectPacket<Client_MCS_Connect_Initial_Pdu_with_GCC_Conference_Create_Request>(waitTime);
//Respond a Server MCS Connect Response PDU with GCC Conference Create Response.
this.TestSite.Log.Add(LogEntryKind.Comment, "Sending Server MCS Connect Response PDU to SUT. Encryption Method {0}; Encryption Level: {1}; RDP Version Code: {2}.", enMethod.ToString(), enLevel.ToString(), TS_UD_SC_CORE_version_Values.V2.ToString());
this.rdpbcgrAdapter.Server_MCS_Connect_Response(enMethod, enLevel, TS_UD_SC_CORE_version_Values.V2, NegativeType.None);
#endregion
//Expect a Client MCS Erect Domain Request PDU.
this.TestSite.Log.Add(LogEntryKind.Comment, "Expecting SUT to send a Client MCS Erect Domain Request PDU.");
this.rdpbcgrAdapter.ExpectPacket<Client_MCS_Erect_Domain_Request>(waitTime);
//Expect a Client MCS Attach User Request PDU
this.TestSite.Log.Add(LogEntryKind.Comment, "Expecting SUT to send a Client MCS Attach User Request PDU.");
this.rdpbcgrAdapter.ExpectPacket<Client_MCS_Attach_User_Request>(waitTime);
//Respond a Server MCS Attach User Confirm PDU
this.TestSite.Log.Add(LogEntryKind.Comment, "Sending Server MCS Attach User Confirm PDU to SUT with invalid result value (not rt-successful)");
this.rdpbcgrAdapter.MCSAttachUserConfirm(NegativeType.InvalidResult);
//Expect SUT to drop the connection
this.TestSite.Log.Add(LogEntryKind.Comment, "Expect SUT to drop the connection");
bool bDisconnected = this.rdpbcgrAdapter.WaitForDisconnection(waitTime);
this.TestSite.Assert.IsTrue(bDisconnected, "SUT should drop the connection if the result field in MCS Attach User Confirm PDU is not set to rt-successful (0).");
#endregion
}
[TestMethod]
[Priority(1)]
[TestCategory("RDP7.0")]
[TestCategory("RDPBCGR")]
[Description(@"This test case is used to verify
SUT drops the connection connection if the initiator field in MCS Attach User Confirm PDU is not present")]
public void S1_ConnectionTest_ChannelConnection_NegativeTest_MCSAttachUserConfirm_InitiatorNotPresent()
{
#region Test Description
//1. Trigger SUT to initiate a RDP connection and complete the Connection Initiation phase and Basic Setting Exchange phase.
//2. Test Suite expects SUT continue the connection with sending a Client MCS Erect Domain Request PDU and a Client MCS Attach User Request PDU.
//3. Test Suite responds a Server MCS Attach User Confirm PDU to SUT and does not present initiator field.
//4. Test Suite expects SUT drop the connection.
#endregion
#region Test Implementation
//Start RDP listening.
this.TestSite.Log.Add(LogEntryKind.Comment, "Starting RDP listening with transport protocol: {0}", transportProtocol.ToString());
this.rdpbcgrAdapter.StartRDPListening(transportProtocol);
#region Trigger client to initiate a RDP connection
//Trigger client to initiate a RDP connection.
this.TestSite.Log.Add(LogEntryKind.Comment, "Triggering SUT to initiate a RDP connection to server.");
triggerClientRDPConnect(transportProtocol);
#endregion
//Expect the transport layer connection request.
this.TestSite.Log.Add(LogEntryKind.Comment, "Expecting SUT to start a transport layer connection request (TCP).");
this.rdpbcgrAdapter.ExpectTransportConnection(RDPSessionType.Normal);
#region Connection Initiation phase
//Expect SUT send a Client X.224 Connection Request PDU.
this.TestSite.Log.Add(LogEntryKind.Comment, "Expecting SUT to send a Client X.224 Connection Request PDU");
this.rdpbcgrAdapter.ExpectPacket<Client_X_224_Connection_Request_Pdu>(waitTime);
//Respond a Server X.224 Connection Confirm PDU and set the EXTENDED_CLIENT_DATA_SUPPORTED flag.
this.TestSite.Log.Add(LogEntryKind.Comment, "Sending Server X.224 Connection Confirm PDU to SUT. Selected protocol: {0}; Extended Client Data supported: true", selectedProtocol.ToString());
this.rdpbcgrAdapter.Server_X_224_Connection_Confirm(selectedProtocol, true, true, NegativeType.None);
#endregion
#region Basic Setting Exchange phase
//Expect SUT send Client MCS Connect Initial PDU.
this.TestSite.Log.Add(LogEntryKind.Comment, "Expecting SUT to send a Client MCS Connect Initial PDU.");
this.rdpbcgrAdapter.ExpectPacket<Client_MCS_Connect_Initial_Pdu_with_GCC_Conference_Create_Request>(waitTime);
//Respond a Server MCS Connect Response PDU with GCC Conference Create Response.
this.TestSite.Log.Add(LogEntryKind.Comment, "Sending Server MCS Connect Response PDU to SUT. Encryption Method {0}; Encryption Level: {1}; RDP Version Code: {2}.", enMethod.ToString(), enLevel.ToString(), TS_UD_SC_CORE_version_Values.V2.ToString());
this.rdpbcgrAdapter.Server_MCS_Connect_Response(enMethod, enLevel, TS_UD_SC_CORE_version_Values.V2, NegativeType.None);
#endregion
//Expect a Client MCS Erect Domain Request PDU.
this.TestSite.Log.Add(LogEntryKind.Comment, "Expecting SUT to send a Client MCS Erect Domain Request PDU.");
this.rdpbcgrAdapter.ExpectPacket<Client_MCS_Erect_Domain_Request>(waitTime);
//Expect a Client MCS Attach User Request PDU
this.TestSite.Log.Add(LogEntryKind.Comment, "Expecting SUT to send a Client MCS Attach User Request PDU.");
this.rdpbcgrAdapter.ExpectPacket<Client_MCS_Attach_User_Request>(waitTime);
//Respond a Server MCS Attach User Confirm PDU
this.TestSite.Log.Add(LogEntryKind.Comment, "Sending Server MCS Attach User Confirm PDU to SUT and does not present initiator field");
this.rdpbcgrAdapter.MCSAttachUserConfirm(NegativeType.InvalidInitiatorField);
//Expect SUT to drop the connection
this.TestSite.Log.Add(LogEntryKind.Comment, "Expect SUT to drop the connection");
bool bDisconnected = this.rdpbcgrAdapter.WaitForDisconnection(waitTime);
this.TestSite.Assert.IsTrue(bDisconnected, "SUT should drop the connection if the initiator field in MCS Attach User Confirm PDU is not present.");
#endregion
}
[TestMethod]
[Priority(1)]
[TestCategory("RDP7.0")]
[TestCategory("RDPBCGR")]
[Description(@"This test case is used to verify
SUT drops the connection if the length field within tpktHeader in MCS Channel Join Confirm PDU is not consistent with the received data.")]
public void S1_ConnectionTest_ChannelConnection_NegativeTest_MCSChannelJoinConfirm_InvalidTPKTLength()
{
#region Test Description
//1. Trigger SUT to initiate a RDP connection and complete the Connection Initiation phase and Basic Setting Exchange phase.
//2. Test Suite expects SUT continue the connection with sending a Client MCS Erect Domain Request PDU and a Client MCS Attach User Request PDU.
//3. Test Suite verifies the received Client MCS Erect Domain Request PDU and Client MCS Attach User Request PDU, and then responds a Server MCS Attach User Confirm PDU to SUT.
//4. Test Suite expects SUT starts the channel join sequence. SUT should use the MCS Channel Join Request PDU to join the user channel obtained from the Attach User Confirm PDU, the I/O channel and all of the static virtual channels obtained from the Server Network Data structure.
//5. After Test Suite received the first MCS Channel Join Request PDU, it responds a Server MCS Channel Join Confirm PDU and set the length field within tpktHeader to an invalid value (less than the actual value).
//6. Test Suite expects SUT drop the connection.
#endregion
#region Test Implementation
//Start RDP listening.
this.TestSite.Log.Add(LogEntryKind.Comment, "Starting RDP listening with transport protocol: {0}", transportProtocol.ToString());
this.rdpbcgrAdapter.StartRDPListening(transportProtocol);
#region Trigger client to initiate a RDP connection
//Trigger client to initiate a RDP connection.
this.TestSite.Log.Add(LogEntryKind.Comment, "Triggering SUT to initiate a RDP connection to server.");
triggerClientRDPConnect(transportProtocol);
#endregion
//Expect the transport layer connection request.
this.TestSite.Log.Add(LogEntryKind.Comment, "Expecting SUT to start a transport layer connection request (TCP).");
this.rdpbcgrAdapter.ExpectTransportConnection(RDPSessionType.Normal);
#region Connection Initiation phase
//Expect SUT send a Client X.224 Connection Request PDU.
this.TestSite.Log.Add(LogEntryKind.Comment, "Expecting SUT to send a Client X.224 Connection Request PDU");
this.rdpbcgrAdapter.ExpectPacket<Client_X_224_Connection_Request_Pdu>(waitTime);
//Respond a Server X.224 Connection Confirm PDU and set the EXTENDED_CLIENT_DATA_SUPPORTED flag.
this.TestSite.Log.Add(LogEntryKind.Comment, "Sending Server X.224 Connection Confirm PDU to SUT. Selected protocol: {0}; Extended Client Data supported: true", selectedProtocol.ToString());
this.rdpbcgrAdapter.Server_X_224_Connection_Confirm(selectedProtocol, true, true, NegativeType.None);
#endregion
#region Basic Setting Exchange phase
//Expect SUT send Client MCS Connect Initial PDU.
this.TestSite.Log.Add(LogEntryKind.Comment, "Expecting SUT to send a Client MCS Connect Initial PDU.");
this.rdpbcgrAdapter.ExpectPacket<Client_MCS_Connect_Initial_Pdu_with_GCC_Conference_Create_Request>(waitTime);
//Respond a Server MCS Connect Response PDU with GCC Conference Create Response.
this.TestSite.Log.Add(LogEntryKind.Comment, "Sending Server MCS Connect Response PDU to SUT. Encryption Method {0}; Encryption Level: {1}; RDP Version Code: {2}.", enMethod.ToString(), enLevel.ToString(), TS_UD_SC_CORE_version_Values.V2.ToString());
this.rdpbcgrAdapter.Server_MCS_Connect_Response(enMethod, enLevel, TS_UD_SC_CORE_version_Values.V2, NegativeType.None);
#endregion
//Expect a Client MCS Erect Domain Request PDU.
this.TestSite.Log.Add(LogEntryKind.Comment, "Expecting SUT to send a Client MCS Erect Domain Request PDU.");
this.rdpbcgrAdapter.ExpectPacket<Client_MCS_Erect_Domain_Request>(waitTime);
//Expect a Client MCS Attach User Request PDU
this.TestSite.Log.Add(LogEntryKind.Comment, "Expecting SUT to send a Client MCS Attach User Request PDU.");
this.rdpbcgrAdapter.ExpectPacket<Client_MCS_Attach_User_Request>(waitTime);
//Respond a Server MCS Attach User Confirm PDU
this.TestSite.Log.Add(LogEntryKind.Comment, "Sending Server MCS Attach User Confirm PDU to SUT");
this.rdpbcgrAdapter.MCSAttachUserConfirm(NegativeType.None);
//Expect SUT start a channel join sequence
this.TestSite.Log.Add(LogEntryKind.Comment, "Expect SUT to start the channel join request and respond a pdu with the length field within tpktHeader to an invalid value (less than the actual value) .");
this.rdpbcgrAdapter.ChannelJoinRequestAndConfirm(NegativeType.InvalidTPKLength);
#endregion
}
[TestMethod]
[Priority(1)]
[TestCategory("RDP7.0")]
[TestCategory("RDPBCGR")]
[Description(@"This test case is used to verify
SUT drops the connection if the channelId field is not present in MCS Channel Join Confirm PDU.")]
public void S1_ConnectionTest_ChannelConnection_NegativeTest_MCSChannelJoinConfirm_ChannelIdNotPresent()
{
#region Test Description
//1. Trigger SUT to initiate a RDP connection and complete the Connection Initiation phase and Basic Setting Exchange phase.
//2. Test Suite expects SUT continue the connection with sending a Client MCS Erect Domain Request PDU and a Client MCS Attach User Request PDU.
//3. Test Suite verifies the received Client MCS Erect Domain Request PDU and Client MCS Attach User Request PDU, and then responds a Server MCS Attach User Confirm PDU to SUT.
//4. Test Suite expects SUT starts the channel join sequence. SUT should use the MCS Channel Join Request PDU to join the user channel obtained from the Attach User Confirm PDU, the I/O channel and all of the static virtual channels obtained from the Server Network Data structure.
//5. After Test Suite received the first MCS Channel Join Request PDU, it responds a Server MCS Channel Join Confirm PDU and does not present the channelId field.
//6. Test Suite expects SUT drop the connection.
#endregion
#region Test Implementation
//Start RDP listening.
this.TestSite.Log.Add(LogEntryKind.Comment, "Starting RDP listening with transport protocol: {0}", transportProtocol.ToString());
this.rdpbcgrAdapter.StartRDPListening(transportProtocol);
#region Trigger client to initiate a RDP connection
//Trigger client to initiate a RDP connection.
this.TestSite.Log.Add(LogEntryKind.Comment, "Triggering SUT to initiate a RDP connection to server.");
triggerClientRDPConnect(transportProtocol);
#endregion
//Expect the transport layer connection request.
this.TestSite.Log.Add(LogEntryKind.Comment, "Expecting SUT to start a transport layer connection request (TCP).");
this.rdpbcgrAdapter.ExpectTransportConnection(RDPSessionType.Normal);
#region Connection Initiation phase
//Expect SUT send a Client X.224 Connection Request PDU.
this.TestSite.Log.Add(LogEntryKind.Comment, "Expecting SUT to send a Client X.224 Connection Request PDU");
this.rdpbcgrAdapter.ExpectPacket<Client_X_224_Connection_Request_Pdu>(waitTime);
//Respond a Server X.224 Connection Confirm PDU and set the EXTENDED_CLIENT_DATA_SUPPORTED flag.
this.TestSite.Log.Add(LogEntryKind.Comment, "Sending Server X.224 Connection Confirm PDU to SUT. Selected protocol: {0}; Extended Client Data supported: true", selectedProtocol.ToString());
this.rdpbcgrAdapter.Server_X_224_Connection_Confirm(selectedProtocol, true, true, NegativeType.None);
#endregion
#region Basic Setting Exchange phase
//Expect SUT send Client MCS Connect Initial PDU.
this.TestSite.Log.Add(LogEntryKind.Comment, "Expecting SUT to send a Client MCS Connect Initial PDU.");
this.rdpbcgrAdapter.ExpectPacket<Client_MCS_Connect_Initial_Pdu_with_GCC_Conference_Create_Request>(waitTime);
//Respond a Server MCS Connect Response PDU with GCC Conference Create Response.
this.TestSite.Log.Add(LogEntryKind.Comment, "Sending Server MCS Connect Response PDU to SUT. Encryption Method {0}; Encryption Level: {1}; RDP Version Code: {2}.", enMethod.ToString(), enLevel.ToString(), TS_UD_SC_CORE_version_Values.V2.ToString());
this.rdpbcgrAdapter.Server_MCS_Connect_Response(enMethod, enLevel, TS_UD_SC_CORE_version_Values.V2, NegativeType.None);
#endregion
//Expect a Client MCS Erect Domain Request PDU.
this.TestSite.Log.Add(LogEntryKind.Comment, "Expecting SUT to send a Client MCS Erect Domain Request PDU.");
this.rdpbcgrAdapter.ExpectPacket<Client_MCS_Erect_Domain_Request>(waitTime);
//Expect a Client MCS Attach User Request PDU
this.TestSite.Log.Add(LogEntryKind.Comment, "Expecting SUT to send a Client MCS Attach User Request PDU.");
this.rdpbcgrAdapter.ExpectPacket<Client_MCS_Attach_User_Request>(waitTime);
//Respond a Server MCS Attach User Confirm PDU
this.TestSite.Log.Add(LogEntryKind.Comment, "Sending Server MCS Attach User Confirm PDU to SUT");
this.rdpbcgrAdapter.MCSAttachUserConfirm(NegativeType.None);
//Expect SUT start a channel join sequence
this.TestSite.Log.Add(LogEntryKind.Comment, "Expect SUT to start the channel join request and respond a pdu without presenting the channelId field.");
this.rdpbcgrAdapter.ChannelJoinRequestAndConfirm(NegativeType.InvalidEmptyChannelIdField);
#endregion
}
[TestMethod]
[Priority(1)]
[TestCategory("RDP7.0")]
[TestCategory("RDPBCGR")]
[Description(@"This test case is used to verify
SUT drops the connection if the result field is not set to rt-successful (0) in MCS Channel Join Confirm PDU")]
public void S1_ConnectionTest_ChannelConnection_NegativeTest_MCSChannelJoinConfirm_Failure()
{
#region Test Description
//1. Trigger SUT to initiate a RDP connection and complete the Connection Initiation phase and Basic Setting Exchange phase.
//2. Test Suite expects SUT continue the connection with sending a Client MCS Erect Domain Request PDU and a Client MCS Attach User Request PDU.
//3. Test Suite verifies the received Client MCS Erect Domain Request PDU and Client MCS Attach User Request PDU, and then responds a Server MCS Attach User Confirm PDU to SUT.
//4. Test Suite expects SUT starts the channel join sequence. SUT should use the MCS Channel Join Request PDU to join the user channel obtained from the Attach User Confirm PDU, the I/O channel and all of the static virtual channels obtained from the Server Network Data structure.
//5. After Test Suite received the first MCS Channel Join Request PDU, it responds a Server MCS Channel Join Confirm PDU and does not set the result field to rt-successful (0).
//6. Test Suite expects SUT drop the connection.
#endregion
#region Test Implementation
//Start RDP listening.
this.TestSite.Log.Add(LogEntryKind.Comment, "Starting RDP listening with transport protocol: {0}", transportProtocol.ToString());
this.rdpbcgrAdapter.StartRDPListening(transportProtocol);
#region Trigger client to initiate a RDP connection
//Trigger client to initiate a RDP connection.
this.TestSite.Log.Add(LogEntryKind.Comment, "Triggering SUT to initiate a RDP connection to server.");
triggerClientRDPConnect(transportProtocol);
#endregion
//Expect the transport layer connection request.
this.TestSite.Log.Add(LogEntryKind.Comment, "Expecting SUT to start a transport layer connection request (TCP).");
this.rdpbcgrAdapter.ExpectTransportConnection(RDPSessionType.Normal);
#region Connection Initiation phase
//Expect SUT send a Client X.224 Connection Request PDU.
this.TestSite.Log.Add(LogEntryKind.Comment, "Expecting SUT to send a Client X.224 Connection Request PDU");
this.rdpbcgrAdapter.ExpectPacket<Client_X_224_Connection_Request_Pdu>(waitTime);
//Respond a Server X.224 Connection Confirm PDU and set the EXTENDED_CLIENT_DATA_SUPPORTED flag.
this.TestSite.Log.Add(LogEntryKind.Comment, "Sending Server X.224 Connection Confirm PDU to SUT. Selected protocol: {0}; Extended Client Data supported: true", selectedProtocol.ToString());
this.rdpbcgrAdapter.Server_X_224_Connection_Confirm(selectedProtocol, true, true, NegativeType.None);
#endregion
#region Basic Setting Exchange phase
//Expect SUT send Client MCS Connect Initial PDU.
this.TestSite.Log.Add(LogEntryKind.Comment, "Expecting SUT to send a Client MCS Connect Initial PDU.");
this.rdpbcgrAdapter.ExpectPacket<Client_MCS_Connect_Initial_Pdu_with_GCC_Conference_Create_Request>(waitTime);
//Respond a Server MCS Connect Response PDU with GCC Conference Create Response.
this.TestSite.Log.Add(LogEntryKind.Comment, "Sending Server MCS Connect Response PDU to SUT. Encryption Method {0}; Encryption Level: {1}; RDP Version Code: {2}.", enMethod.ToString(), enLevel.ToString(), TS_UD_SC_CORE_version_Values.V2.ToString());
this.rdpbcgrAdapter.Server_MCS_Connect_Response(enMethod, enLevel, TS_UD_SC_CORE_version_Values.V2, NegativeType.None);
#endregion
//Expect a Client MCS Erect Domain Request PDU.
this.TestSite.Log.Add(LogEntryKind.Comment, "Expecting SUT to send a Client MCS Erect Domain Request PDU.");
this.rdpbcgrAdapter.ExpectPacket<Client_MCS_Erect_Domain_Request>(waitTime);
//Expect a Client MCS Attach User Request PDU
this.TestSite.Log.Add(LogEntryKind.Comment, "Expecting SUT to send a Client MCS Attach User Request PDU.");
this.rdpbcgrAdapter.ExpectPacket<Client_MCS_Attach_User_Request>(waitTime);
//Respond a Server MCS Attach User Confirm PDU
this.TestSite.Log.Add(LogEntryKind.Comment, "Sending Server MCS Attach User Confirm PDU to SUT");
this.rdpbcgrAdapter.MCSAttachUserConfirm(NegativeType.None);
//Expect SUT start a channel join sequence
this.TestSite.Log.Add(LogEntryKind.Comment, "Expect SUT to start the channel join request and respond a pdu without setting result field to rt-successful.");
this.rdpbcgrAdapter.ChannelJoinRequestAndConfirm(NegativeType.InvalidResult);
#endregion
}
[TestMethod]
[Priority(1)]
[TestCategory("RDP7.0")]
[TestCategory("RDPBCGR")]
[Description(@"This test case is used to verify
SUT drops the connection if the channelId field is not valid in MCS Channel Join Confirm PDU.")]
public void S1_ConnectionTest_ChannelConnection_NegativeTest_MCSChannelJoinConfirm_InvalidChannelId()
{
#region Test Description
//1. Trigger SUT to initiate a RDP connection and complete the Connection Initiation phase and Basic Setting Exchange phase.
//2. Test Suite expects SUT continue the connection with sending a Client MCS Erect Domain Request PDU and a Client MCS Attach User Request PDU.
//3. Test Suite verifies the received Client MCS Erect Domain Request PDU and Client MCS Attach User Request PDU, and then responds a Server MCS Attach User Confirm PDU to SUT.
//4. Test Suite expects SUT starts the channel join sequence. SUT should use the MCS Channel Join Request PDU to join the user channel obtained from the Attach User Confirm PDU, the I/O channel and all of the static virtual channels obtained from the Server Network Data structure.
//5. After Test Suite received the first MCS Channel Join Request PDU, it responds a Server MCS Channel Join Confirm PDU and set the channelId field to an invalid value that not correspond with the value of the channelId field received in MCS Channel Join Request PDU.
//6. Test Suite expects SUT drop the connection.
#endregion
#region Test Implementation
//Start RDP listening.
this.TestSite.Log.Add(LogEntryKind.Comment, "Starting RDP listening with transport protocol: {0}", transportProtocol.ToString());
this.rdpbcgrAdapter.StartRDPListening(transportProtocol);
#region Trigger client to initiate a RDP connection
//Trigger client to initiate a RDP connection.
this.TestSite.Log.Add(LogEntryKind.Comment, "Triggering SUT to initiate a RDP connection to server.");
triggerClientRDPConnect(transportProtocol);
#endregion
//Expect the transport layer connection request.
this.TestSite.Log.Add(LogEntryKind.Comment, "Expecting SUT to start a transport layer connection request (TCP).");
this.rdpbcgrAdapter.ExpectTransportConnection(RDPSessionType.Normal);
#region Connection Initiation phase
//Expect SUT send a Client X.224 Connection Request PDU.
this.TestSite.Log.Add(LogEntryKind.Comment, "Expecting SUT to send a Client X.224 Connection Request PDU");
this.rdpbcgrAdapter.ExpectPacket<Client_X_224_Connection_Request_Pdu>(waitTime);
//Respond a Server X.224 Connection Confirm PDU and set the EXTENDED_CLIENT_DATA_SUPPORTED flag.
this.TestSite.Log.Add(LogEntryKind.Comment, "Sending Server X.224 Connection Confirm PDU to SUT. Selected protocol: {0}; Extended Client Data supported: true", selectedProtocol.ToString());
this.rdpbcgrAdapter.Server_X_224_Connection_Confirm(selectedProtocol, true, true, NegativeType.None);
#endregion
#region Basic Setting Exchange phase
//Expect SUT send Client MCS Connect Initial PDU.
this.TestSite.Log.Add(LogEntryKind.Comment, "Expecting SUT to send a Client MCS Connect Initial PDU.");
this.rdpbcgrAdapter.ExpectPacket<Client_MCS_Connect_Initial_Pdu_with_GCC_Conference_Create_Request>(waitTime);
//Respond a Server MCS Connect Response PDU with GCC Conference Create Response.
this.TestSite.Log.Add(LogEntryKind.Comment, "Sending Server MCS Connect Response PDU to SUT. Encryption Method {0}; Encryption Level: {1}; RDP Version Code: {2}.", enMethod.ToString(), enLevel.ToString(), TS_UD_SC_CORE_version_Values.V2.ToString());
this.rdpbcgrAdapter.Server_MCS_Connect_Response(enMethod, enLevel, TS_UD_SC_CORE_version_Values.V2, NegativeType.None);
#endregion
//Expect a Client MCS Erect Domain Request PDU.
this.TestSite.Log.Add(LogEntryKind.Comment, "Expecting SUT to send a Client MCS Erect Domain Request PDU.");
this.rdpbcgrAdapter.ExpectPacket<Client_MCS_Erect_Domain_Request>(waitTime);
//Expect a Client MCS Attach User Request PDU
this.TestSite.Log.Add(LogEntryKind.Comment, "Expecting SUT to send a Client MCS Attach User Request PDU.");
this.rdpbcgrAdapter.ExpectPacket<Client_MCS_Attach_User_Request>(waitTime);
//Respond a Server MCS Attach User Confirm PDU
this.TestSite.Log.Add(LogEntryKind.Comment, "Sending Server MCS Attach User Confirm PDU to SUT");
this.rdpbcgrAdapter.MCSAttachUserConfirm(NegativeType.None);
//Expect SUT start a channel join sequence
this.TestSite.Log.Add(LogEntryKind.Comment, "Expect SUT to start the channel join request and respond a pdu with the channelId field to an invalid value that not correspond with the value of the channelId field received in MCS Channel Join Request PDU..");
this.rdpbcgrAdapter.ChannelJoinRequestAndConfirm(NegativeType.InvalidMismatchChannelIdField);
#endregion
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.Commands;
using Microsoft.CodeAnalysis.Editor.CSharp.RenameTracking;
using Microsoft.CodeAnalysis.Editor.Implementation.RenameTracking;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Editor.VisualBasic.RenameTracking;
using Microsoft.CodeAnalysis.Notification;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.CodeAnalysis.UnitTests.Diagnostics;
using Microsoft.VisualStudio.Composition;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Operations;
using Microsoft.VisualStudio.Text.Tagging;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.RenameTracking
{
internal sealed class RenameTrackingTestState : IDisposable
{
private readonly ITagger<RenameTrackingTag> _tagger;
public readonly TestWorkspace Workspace;
private readonly IWpfTextView _view;
private readonly ITextUndoHistoryRegistry _historyRegistry;
private string _notificationMessage = null;
private readonly TestHostDocument _hostDocument;
public TestHostDocument HostDocument { get { return _hostDocument; } }
private readonly IEditorOperations _editorOperations;
public IEditorOperations EditorOperations { get { return _editorOperations; } }
private readonly MockRefactorNotifyService _mockRefactorNotifyService;
public MockRefactorNotifyService RefactorNotifyService { get { return _mockRefactorNotifyService; } }
private readonly CodeFixProvider _codeFixProvider;
private readonly RenameTrackingCancellationCommandHandler _commandHandler = new RenameTrackingCancellationCommandHandler();
public static async Task<RenameTrackingTestState> CreateAsync(
string markup,
string languageName,
bool onBeforeGlobalSymbolRenamedReturnValue = true,
bool onAfterGlobalSymbolRenamedReturnValue = true)
{
var workspace = await CreateTestWorkspaceAsync(markup, languageName, TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic());
return new RenameTrackingTestState(workspace, languageName, onBeforeGlobalSymbolRenamedReturnValue, onAfterGlobalSymbolRenamedReturnValue);
}
public RenameTrackingTestState(
TestWorkspace workspace,
string languageName,
bool onBeforeGlobalSymbolRenamedReturnValue = true,
bool onAfterGlobalSymbolRenamedReturnValue = true)
{
this.Workspace = workspace;
_hostDocument = Workspace.Documents.First();
_view = _hostDocument.GetTextView();
_view.Caret.MoveTo(new SnapshotPoint(_view.TextSnapshot, _hostDocument.CursorPosition.Value));
_editorOperations = Workspace.GetService<IEditorOperationsFactoryService>().GetEditorOperations(_view);
_historyRegistry = Workspace.ExportProvider.GetExport<ITextUndoHistoryRegistry>().Value;
_mockRefactorNotifyService = new MockRefactorNotifyService
{
OnBeforeSymbolRenamedReturnValue = onBeforeGlobalSymbolRenamedReturnValue,
OnAfterSymbolRenamedReturnValue = onAfterGlobalSymbolRenamedReturnValue
};
// Mock the action taken by the workspace INotificationService
var notificationService = Workspace.Services.GetService<INotificationService>() as INotificationServiceCallback;
var callback = new Action<string, string, NotificationSeverity>((message, title, severity) => _notificationMessage = message);
notificationService.NotificationCallback = callback;
var tracker = new RenameTrackingTaggerProvider(
_historyRegistry,
Workspace.ExportProvider.GetExport<Host.IWaitIndicator>().Value,
Workspace.ExportProvider.GetExport<IInlineRenameService>().Value,
Workspace.ExportProvider.GetExport<IDiagnosticAnalyzerService>().Value,
SpecializedCollections.SingletonEnumerable(_mockRefactorNotifyService),
Workspace.ExportProvider.GetExports<IAsynchronousOperationListener, FeatureMetadata>());
_tagger = tracker.CreateTagger<RenameTrackingTag>(_hostDocument.GetTextBuffer());
if (languageName == LanguageNames.CSharp)
{
_codeFixProvider = new CSharpRenameTrackingCodeFixProvider(
Workspace.ExportProvider.GetExport<Host.IWaitIndicator>().Value,
_historyRegistry,
SpecializedCollections.SingletonEnumerable(_mockRefactorNotifyService));
}
else if (languageName == LanguageNames.VisualBasic)
{
_codeFixProvider = new VisualBasicRenameTrackingCodeFixProvider(
Workspace.ExportProvider.GetExport<Host.IWaitIndicator>().Value,
_historyRegistry,
SpecializedCollections.SingletonEnumerable(_mockRefactorNotifyService));
}
else
{
throw new ArgumentException("Invalid language name: " + languageName, nameof(languageName));
}
}
private static Task<TestWorkspace> CreateTestWorkspaceAsync(string code, string languageName, ExportProvider exportProvider = null)
{
var xml = string.Format(@"
<Workspace>
<Project Language=""{0}"" CommonReferences=""true"">
<Document>{1}</Document>
</Project>
</Workspace>", languageName, code);
return TestWorkspace.CreateAsync(xml, exportProvider: exportProvider);
}
public void SendEscape()
{
_commandHandler.ExecuteCommand(new EscapeKeyCommandArgs(_view, _view.TextBuffer), () => { });
}
public void MoveCaret(int delta)
{
var position = _view.Caret.Position.BufferPosition.Position;
_view.Caret.MoveTo(new SnapshotPoint(_view.TextSnapshot, position + delta));
}
public void Undo(int count = 1)
{
var history = _historyRegistry.GetHistory(_view.TextBuffer);
history.Undo(count);
}
public void Redo(int count = 1)
{
var history = _historyRegistry.GetHistory(_view.TextBuffer);
history.Redo(count);
}
public async Task AssertNoTag()
{
await WaitForAsyncOperationsAsync();
var tags = _tagger.GetTags(_view.TextBuffer.CurrentSnapshot.GetSnapshotSpanCollection());
Assert.Equal(0, tags.Count());
}
public async Task<IList<Diagnostic>> GetDocumentDiagnosticsAsync(Document document = null)
{
document = document ?? this.Workspace.CurrentSolution.GetDocument(_hostDocument.Id);
var analyzer = new RenameTrackingDiagnosticAnalyzer();
return (await DiagnosticProviderTestUtilities.GetDocumentDiagnosticsAsync(analyzer, document,
(await document.GetSyntaxRootAsync()).FullSpan)).ToList();
}
public async Task AssertTag(string expectedFromName, string expectedToName, bool invokeAction = false)
{
await WaitForAsyncOperationsAsync();
var tags = _tagger.GetTags(_view.TextBuffer.CurrentSnapshot.GetSnapshotSpanCollection());
// There should only ever be one tag
Assert.Equal(1, tags.Count());
var tag = tags.Single();
var document = this.Workspace.CurrentSolution.GetDocument(_hostDocument.Id);
var diagnostics = await GetDocumentDiagnosticsAsync(document);
// There should be a single rename tracking diagnostic
Assert.Equal(1, diagnostics.Count);
Assert.Equal(RenameTrackingDiagnosticAnalyzer.DiagnosticId, diagnostics[0].Id);
var actions = new List<CodeAction>();
var context = new CodeFixContext(document, diagnostics[0], (a, d) => actions.Add(a), CancellationToken.None);
await _codeFixProvider.RegisterCodeFixesAsync(context);
// There should only be one code action
Assert.Equal(1, actions.Count);
Assert.Equal(string.Format(EditorFeaturesResources.RenameTo, expectedFromName, expectedToName), actions[0].Title);
if (invokeAction)
{
var operations = (await actions[0].GetOperationsAsync(CancellationToken.None)).ToArray();
Assert.Equal(1, operations.Length);
operations[0].Apply(this.Workspace, new ProgressTracker(), CancellationToken.None);
}
}
public void AssertNoNotificationMessage()
{
Assert.Null(_notificationMessage);
}
public void AssertNotificationMessage()
{
Assert.NotNull(_notificationMessage);
}
private async Task WaitForAsyncOperationsAsync()
{
var waiters = Workspace.ExportProvider.GetExportedValues<IAsynchronousOperationWaiter>();
await waiters.WaitAllAsync();
}
public void Dispose()
{
Workspace.Dispose();
}
}
}
| |
using System;
using System.Collections;
using Server;
using Server.Misc;
using Server.Items;
using Server.Spells;
namespace Server.Mobiles
{
[CorpseName( "a meer's corpse" )]
public class MeerMage : BaseCreature
{
[Constructable]
public MeerMage() : base( AIType.AI_Mage, FightMode.Evil, 10, 1, 0.2, 0.4 )
{
Name = "a meer mage";
Body = 770;
SetStr( 171, 200 );
SetDex( 126, 145 );
SetInt( 276, 305 );
SetHits( 103, 120 );
SetDamage( 24, 26 );
SetDamageType( ResistanceType.Physical, 100 );
SetResistance( ResistanceType.Physical, 45, 55 );
SetResistance( ResistanceType.Fire, 15, 25 );
SetResistance( ResistanceType.Cold, 50 );
SetResistance( ResistanceType.Poison, 25, 35 );
SetResistance( ResistanceType.Energy, 25, 35 );
SetSkill( SkillName.EvalInt, 100.0 );
SetSkill( SkillName.Magery, 70.1, 80.0 );
SetSkill( SkillName.Meditation, 85.1, 95.0 );
SetSkill( SkillName.MagicResist, 80.1, 100.0 );
SetSkill( SkillName.Tactics, 70.1, 90.0 );
SetSkill( SkillName.Wrestling, 60.1, 80.0 );
Fame = 8000;
Karma = 8000;
VirtualArmor = 16;
m_NextAbilityTime = DateTime.Now + TimeSpan.FromSeconds( Utility.RandomMinMax( 2, 5 ) );
}
public override void GenerateLoot()
{
AddLoot( LootPack.FilthyRich );
AddLoot( LootPack.MedScrolls, 2 );
// TODO: Daemon bone ...
}
public override bool AutoDispel{ get{ return true; } }
public override Poison PoisonImmune{ get{ return Poison.Lethal; } }
public override bool CanRummageCorpses{ get{ return true; } }
public override int TreasureMapLevel{ get{ return 3; } }
public override bool InitialInnocent{ get{ return true; } }
public override int GetHurtSound()
{
return 0x14D;
}
public override int GetDeathSound()
{
return 0x314;
}
public override int GetAttackSound()
{
return 0x75;
}
private DateTime m_NextAbilityTime;
public override void OnThink()
{
if (DateTime.Now >= m_NextAbilityTime)
{
Mobile combatant = this.Combatant;
if (combatant != null && combatant.Map == this.Map && combatant.InRange(this, 12) && IsEnemy(combatant) && !UnderEffect(combatant))
{
m_NextAbilityTime = DateTime.Now + TimeSpan.FromSeconds(Utility.RandomMinMax(20, 30));
if (combatant is BaseCreature)
{
BaseCreature bc = (BaseCreature)combatant;
if (bc.Controlled && bc.ControlMaster != null && !bc.ControlMaster.Deleted && bc.ControlMaster.Alive)
{
if (bc.ControlMaster.Map == this.Map && bc.ControlMaster.InRange(this, 12) && !UnderEffect(bc.ControlMaster))
{
Combatant = combatant = bc.ControlMaster;
}
}
}
if (Utility.RandomDouble() < .1)
{
int[][] coord =
{
new int[]{-4,-6}, new int[]{4,-6}, new int[]{0,-8}, new int[]{-5,5}, new int[]{5,5}
};
BaseCreature rabid;
for (int i = 0; i < 5; i++)
{
int x = combatant.X + coord[i][0];
int y = combatant.Y + coord[i][1];
Point3D loc = new Point3D(x, y, combatant.Map.GetAverageZ(x, y));
if (!combatant.Map.CanSpawnMobile(loc))
continue;
switch (i)
{
case 0: rabid = new EnragedRabbit(this); break;
case 1: rabid = new EnragedHind(this); break;
case 2: rabid = new EnragedHart(this); break;
case 3: rabid = new EnragedBlackBear(this); break;
default: rabid = new EnragedEagle(this); break;
}
rabid.FocusMob = combatant;
rabid.MoveToWorld(loc, combatant.Map);
}
this.Say(1071932); //Creatures of the forest, I call to thee! Aid me in the fight against all that is evil!
}
else if (combatant.Player)
{
this.Say(true, "I call a plague of insects to sting your flesh!");
m_Table[combatant] = Timer.DelayCall(TimeSpan.FromSeconds(0.5), TimeSpan.FromSeconds(7.0), new TimerStateCallback(DoEffect), new object[] { combatant, 0 });
}
}
}
base.OnThink();
}
private static Hashtable m_Table = new Hashtable();
public static bool UnderEffect(Mobile m)
{
return m_Table.Contains(m);
}
public static void StopEffect(Mobile m, bool message)
{
Timer t = (Timer)m_Table[m];
if (t != null)
{
if (message)
m.PublicOverheadMessage(Network.MessageType.Emote, m.SpeechHue, true, "* The open flame begins to scatter the swarm of insects *");
t.Stop();
m_Table.Remove(m);
}
}
public void DoEffect(object state)
{
object[] states = (object[])state;
Mobile m = (Mobile)states[0];
int count = (int)states[1];
if (!m.Alive)
{
StopEffect(m, false);
}
else
{
Torch torch = m.FindItemOnLayer(Layer.TwoHanded) as Torch;
if (torch != null && torch.Burning)
{
StopEffect(m, true);
}
else
{
if ((count % 4) == 0)
{
m.LocalOverheadMessage(Network.MessageType.Emote, m.SpeechHue, true, "* The swarm of insects bites and stings your flesh! *");
m.NonlocalOverheadMessage(Network.MessageType.Emote, m.SpeechHue, true, String.Format("* {0} is stung by a swarm of insects *", m.Name));
}
m.FixedParticles(0x91C, 10, 180, 9539, EffectLayer.Waist);
m.PlaySound(0x00E);
m.PlaySound(0x1BC);
AOS.Damage(m, this, Utility.RandomMinMax(30, 40) - (Core.AOS ? 0 : 10), 100, 0, 0, 0, 0);
states[1] = count + 1;
if (!m.Alive)
StopEffect(m, false);
}
}
}
public MeerMage(Serial serial)
: base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0);
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
}
| |
/*
* 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.Net;
using System.Reflection;
using Nini.Config;
using log4net;
using OpenSim.Framework;
using OpenSim.Framework.Console;
using OpenSim.Data;
using OpenSim.Server.Base;
using OpenSim.Services.Interfaces;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
using OpenMetaverse;
namespace OpenSim.Services.GridService
{
public class GridService : GridServiceBase, IGridService
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
private bool m_DeleteOnUnregister = true;
private static GridService m_RootInstance = null;
protected IConfigSource m_config;
protected static HypergridLinker m_HypergridLinker;
protected IAuthenticationService m_AuthenticationService = null;
protected bool m_AllowDuplicateNames = false;
protected bool m_AllowHypergridMapSearch = false;
public GridService(IConfigSource config)
: base(config)
{
m_log.DebugFormat("[GRID SERVICE]: Starting...");
m_config = config;
IConfig gridConfig = config.Configs["GridService"];
if (gridConfig != null)
{
m_DeleteOnUnregister = gridConfig.GetBoolean("DeleteOnUnregister", true);
string authService = gridConfig.GetString("AuthenticationService", String.Empty);
if (authService != String.Empty)
{
Object[] args = new Object[] { config };
m_AuthenticationService = ServerUtils.LoadPlugin<IAuthenticationService>(authService, args);
}
m_AllowDuplicateNames = gridConfig.GetBoolean("AllowDuplicateNames", m_AllowDuplicateNames);
m_AllowHypergridMapSearch = gridConfig.GetBoolean("AllowHypergridMapSearch", m_AllowHypergridMapSearch);
}
if (m_RootInstance == null)
{
m_RootInstance = this;
if (MainConsole.Instance != null)
{
MainConsole.Instance.Commands.AddCommand("grid", true,
"show region",
"show region <Region name>",
"Show details on a region",
String.Empty,
HandleShowRegion);
MainConsole.Instance.Commands.AddCommand("grid", true,
"set region flags",
"set region flags <Region name> <flags>",
"Set database flags for region",
String.Empty,
HandleSetFlags);
}
m_HypergridLinker = new HypergridLinker(m_config, this, m_Database);
}
}
#region IGridService
public string RegisterRegion(UUID scopeID, GridRegion regionInfos)
{
IConfig gridConfig = m_config.Configs["GridService"];
// This needs better sanity testing. What if regionInfo is registering in
// overlapping coords?
RegionData region = m_Database.Get(regionInfos.RegionLocX, regionInfos.RegionLocY, scopeID);
if (region != null)
{
// There is a preexisting record
//
// Get it's flags
//
OpenSim.Data.RegionFlags rflags = (OpenSim.Data.RegionFlags)Convert.ToInt32(region.Data["flags"]);
// Is this a reservation?
//
if ((rflags & OpenSim.Data.RegionFlags.Reservation) != 0)
{
// Regions reserved for the null key cannot be taken.
if ((string)region.Data["PrincipalID"] == UUID.Zero.ToString())
return "Region location is reserved";
// Treat it as an auth request
//
// NOTE: Fudging the flags value here, so these flags
// should not be used elsewhere. Don't optimize
// this with the later retrieval of the same flags!
rflags |= OpenSim.Data.RegionFlags.Authenticate;
}
if ((rflags & OpenSim.Data.RegionFlags.Authenticate) != 0)
{
// Can we authenticate at all?
//
if (m_AuthenticationService == null)
return "No authentication possible";
if (!m_AuthenticationService.Verify(new UUID(region.Data["PrincipalID"].ToString()), regionInfos.Token, 30))
return "Bad authentication";
}
}
if ((region != null) && (region.RegionID != regionInfos.RegionID))
{
m_log.WarnFormat("[GRID SERVICE]: Region {0} tried to register in coordinates {1}, {2} which are already in use in scope {3}.",
regionInfos.RegionID, regionInfos.RegionLocX, regionInfos.RegionLocY, scopeID);
return "Region overlaps another region";
}
if ((region != null) && (region.RegionID == regionInfos.RegionID) &&
((region.posX != regionInfos.RegionLocX) || (region.posY != regionInfos.RegionLocY)))
{
if ((Convert.ToInt32(region.Data["flags"]) & (int)OpenSim.Data.RegionFlags.NoMove) != 0)
return "Can't move this region";
// Region reregistering in other coordinates. Delete the old entry
m_log.DebugFormat("[GRID SERVICE]: Region {0} ({1}) was previously registered at {2}-{3}. Deleting old entry.",
regionInfos.RegionName, regionInfos.RegionID, regionInfos.RegionLocX, regionInfos.RegionLocY);
try
{
m_Database.Delete(regionInfos.RegionID);
}
catch (Exception e)
{
m_log.DebugFormat("[GRID SERVICE]: Database exception: {0}", e);
}
}
if (!m_AllowDuplicateNames)
{
List<RegionData> dupe = m_Database.Get(regionInfos.RegionName, scopeID);
if (dupe != null && dupe.Count > 0)
{
foreach (RegionData d in dupe)
{
if (d.RegionID != regionInfos.RegionID)
{
m_log.WarnFormat("[GRID SERVICE]: Region {0} tried to register duplicate name with ID {1}.",
regionInfos.RegionName, regionInfos.RegionID);
return "Duplicate region name";
}
}
}
}
// Everything is ok, let's register
RegionData rdata = RegionInfo2RegionData(regionInfos);
rdata.ScopeID = scopeID;
if (region != null)
{
int oldFlags = Convert.ToInt32(region.Data["flags"]);
if ((oldFlags & (int)OpenSim.Data.RegionFlags.LockedOut) != 0)
return "Region locked out";
oldFlags &= ~(int)OpenSim.Data.RegionFlags.Reservation;
rdata.Data["flags"] = oldFlags.ToString(); // Preserve flags
}
else
{
rdata.Data["flags"] = "0";
if ((gridConfig != null) && rdata.RegionName != string.Empty)
{
int newFlags = 0;
string regionName = rdata.RegionName.Trim().Replace(' ', '_');
newFlags = ParseFlags(newFlags, gridConfig.GetString("DefaultRegionFlags", String.Empty));
newFlags = ParseFlags(newFlags, gridConfig.GetString("Region_" + regionName, String.Empty));
newFlags = ParseFlags(newFlags, gridConfig.GetString("Region_" + rdata.RegionID.ToString(), String.Empty));
rdata.Data["flags"] = newFlags.ToString();
}
}
int flags = Convert.ToInt32(rdata.Data["flags"]);
flags |= (int)OpenSim.Data.RegionFlags.RegionOnline;
rdata.Data["flags"] = flags.ToString();
try
{
rdata.Data["last_seen"] = Util.UnixTimeSinceEpoch();
m_Database.Store(rdata);
}
catch (Exception e)
{
m_log.DebugFormat("[GRID SERVICE]: Database exception: {0}", e);
}
m_log.DebugFormat("[GRID SERVICE]: Region {0} ({1}) registered successfully at {2}-{3}",
regionInfos.RegionName, regionInfos.RegionID, regionInfos.RegionLocX, regionInfos.RegionLocY);
return String.Empty;
}
public bool DeregisterRegion(UUID regionID)
{
m_log.DebugFormat("[GRID SERVICE]: Region {0} deregistered", regionID);
RegionData region = m_Database.Get(regionID, UUID.Zero);
if (region == null)
return false;
int flags = Convert.ToInt32(region.Data["flags"]);
if (!m_DeleteOnUnregister || (flags & (int)OpenSim.Data.RegionFlags.Persistent) != 0)
{
flags &= ~(int)OpenSim.Data.RegionFlags.RegionOnline;
region.Data["flags"] = flags.ToString();
region.Data["last_seen"] = Util.UnixTimeSinceEpoch();
try
{
m_Database.Store(region);
}
catch (Exception e)
{
m_log.DebugFormat("[GRID SERVICE]: Database exception: {0}", e);
}
return true;
}
return m_Database.Delete(regionID);
}
public List<GridRegion> GetNeighbours(UUID scopeID, UUID regionID)
{
List<GridRegion> rinfos = new List<GridRegion>();
RegionData region = m_Database.Get(regionID, scopeID);
if (region != null)
{
// Not really? Maybe?
List<RegionData> rdatas = m_Database.Get(region.posX - (int)Constants.RegionSize - 1, region.posY - (int)Constants.RegionSize - 1,
region.posX + (int)Constants.RegionSize + 1, region.posY + (int)Constants.RegionSize + 1, scopeID);
foreach (RegionData rdata in rdatas)
if (rdata.RegionID != regionID)
{
int flags = Convert.ToInt32(rdata.Data["flags"]);
if ((flags & (int)Data.RegionFlags.Hyperlink) == 0) // no hyperlinks as neighbours
rinfos.Add(RegionData2RegionInfo(rdata));
}
}
m_log.DebugFormat("[GRID SERVICE]: region {0} has {1} neighours", region.RegionName, rinfos.Count);
return rinfos;
}
public GridRegion GetRegionByUUID(UUID scopeID, UUID regionID)
{
RegionData rdata = m_Database.Get(regionID, scopeID);
if (rdata != null)
return RegionData2RegionInfo(rdata);
return null;
}
public GridRegion GetRegionByPosition(UUID scopeID, int x, int y)
{
int snapX = (int)(x / Constants.RegionSize) * (int)Constants.RegionSize;
int snapY = (int)(y / Constants.RegionSize) * (int)Constants.RegionSize;
RegionData rdata = m_Database.Get(snapX, snapY, scopeID);
if (rdata != null)
return RegionData2RegionInfo(rdata);
return null;
}
public GridRegion GetRegionByName(UUID scopeID, string regionName)
{
List<RegionData> rdatas = m_Database.Get(regionName + "%", scopeID);
if ((rdatas != null) && (rdatas.Count > 0))
return RegionData2RegionInfo(rdatas[0]); // get the first
return null;
}
public List<GridRegion> GetRegionsByName(UUID scopeID, string name, int maxNumber)
{
m_log.DebugFormat("[GRID SERVICE]: GetRegionsByName {0}", name);
List<RegionData> rdatas = m_Database.Get("%" + name + "%", scopeID);
int count = 0;
List<GridRegion> rinfos = new List<GridRegion>();
if (rdatas != null)
{
m_log.DebugFormat("[GRID SERVICE]: Found {0} regions", rdatas.Count);
foreach (RegionData rdata in rdatas)
{
if (count++ < maxNumber)
rinfos.Add(RegionData2RegionInfo(rdata));
}
}
if (m_AllowHypergridMapSearch && (rdatas == null || (rdatas != null && rdatas.Count == 0)) && name.Contains("."))
{
GridRegion r = m_HypergridLinker.LinkRegion(scopeID, name);
if (r != null)
rinfos.Add(r);
}
return rinfos;
}
public List<GridRegion> GetRegionRange(UUID scopeID, int xmin, int xmax, int ymin, int ymax)
{
int xminSnap = (int)(xmin / Constants.RegionSize) * (int)Constants.RegionSize;
int xmaxSnap = (int)(xmax / Constants.RegionSize) * (int)Constants.RegionSize;
int yminSnap = (int)(ymin / Constants.RegionSize) * (int)Constants.RegionSize;
int ymaxSnap = (int)(ymax / Constants.RegionSize) * (int)Constants.RegionSize;
List<RegionData> rdatas = m_Database.Get(xminSnap, yminSnap, xmaxSnap, ymaxSnap, scopeID);
List<GridRegion> rinfos = new List<GridRegion>();
foreach (RegionData rdata in rdatas)
rinfos.Add(RegionData2RegionInfo(rdata));
return rinfos;
}
#endregion
#region Data structure conversions
public RegionData RegionInfo2RegionData(GridRegion rinfo)
{
RegionData rdata = new RegionData();
rdata.posX = (int)rinfo.RegionLocX;
rdata.posY = (int)rinfo.RegionLocY;
rdata.RegionID = rinfo.RegionID;
rdata.RegionName = rinfo.RegionName;
rdata.Data = rinfo.ToKeyValuePairs();
rdata.Data["regionHandle"] = Utils.UIntsToLong((uint)rdata.posX, (uint)rdata.posY);
rdata.Data["owner_uuid"] = rinfo.EstateOwner.ToString();
return rdata;
}
public GridRegion RegionData2RegionInfo(RegionData rdata)
{
GridRegion rinfo = new GridRegion(rdata.Data);
rinfo.RegionLocX = rdata.posX;
rinfo.RegionLocY = rdata.posY;
rinfo.RegionID = rdata.RegionID;
rinfo.RegionName = rdata.RegionName;
rinfo.ScopeID = rdata.ScopeID;
return rinfo;
}
#endregion
public List<GridRegion> GetDefaultRegions(UUID scopeID)
{
List<GridRegion> ret = new List<GridRegion>();
List<RegionData> regions = m_Database.GetDefaultRegions(scopeID);
foreach (RegionData r in regions)
{
if ((Convert.ToInt32(r.Data["flags"]) & (int)OpenSim.Data.RegionFlags.RegionOnline) != 0)
ret.Add(RegionData2RegionInfo(r));
}
m_log.DebugFormat("[GRID SERVICE]: GetDefaultRegions returning {0} regions", ret.Count);
return ret;
}
public List<GridRegion> GetFallbackRegions(UUID scopeID, int x, int y)
{
List<GridRegion> ret = new List<GridRegion>();
List<RegionData> regions = m_Database.GetFallbackRegions(scopeID, x, y);
foreach (RegionData r in regions)
{
if ((Convert.ToInt32(r.Data["flags"]) & (int)OpenSim.Data.RegionFlags.RegionOnline) != 0)
ret.Add(RegionData2RegionInfo(r));
}
m_log.DebugFormat("[GRID SERVICE]: Fallback returned {0} regions", ret.Count);
return ret;
}
public List<GridRegion> GetHyperlinks(UUID scopeID)
{
List<GridRegion> ret = new List<GridRegion>();
List<RegionData> regions = m_Database.GetHyperlinks(scopeID);
foreach (RegionData r in regions)
{
if ((Convert.ToInt32(r.Data["flags"]) & (int)OpenSim.Data.RegionFlags.RegionOnline) != 0)
ret.Add(RegionData2RegionInfo(r));
}
m_log.DebugFormat("[GRID SERVICE]: Hyperlinks returned {0} regions", ret.Count);
return ret;
}
public int GetRegionFlags(UUID scopeID, UUID regionID)
{
RegionData region = m_Database.Get(regionID, scopeID);
if (region != null)
{
int flags = Convert.ToInt32(region.Data["flags"]);
//m_log.DebugFormat("[GRID SERVICE]: Request for flags of {0}: {1}", regionID, flags);
return flags;
}
else
return -1;
}
private void HandleShowRegion(string module, string[] cmd)
{
if (cmd.Length != 3)
{
MainConsole.Instance.Output("Syntax: show region <region name>");
return;
}
List<RegionData> regions = m_Database.Get(cmd[2], UUID.Zero);
if (regions == null || regions.Count < 1)
{
MainConsole.Instance.Output("Region not found");
return;
}
MainConsole.Instance.Output("Region Name Region UUID");
MainConsole.Instance.Output("Location URI");
MainConsole.Instance.Output("Owner ID Flags");
MainConsole.Instance.Output("-------------------------------------------------------------------------------");
foreach (RegionData r in regions)
{
OpenSim.Data.RegionFlags flags = (OpenSim.Data.RegionFlags)Convert.ToInt32(r.Data["flags"]);
MainConsole.Instance.Output(String.Format("{0,-20} {1}\n{2,-20} {3}\n{4,-39} {5}\n\n",
r.RegionName, r.RegionID,
String.Format("{0},{1}", r.posX, r.posY), "http://" + r.Data["serverIP"].ToString() + ":" + r.Data["serverPort"].ToString(),
r.Data["owner_uuid"].ToString(), flags.ToString()));
}
return;
}
private int ParseFlags(int prev, string flags)
{
OpenSim.Data.RegionFlags f = (OpenSim.Data.RegionFlags)prev;
string[] parts = flags.Split(new char[] {',', ' '}, StringSplitOptions.RemoveEmptyEntries);
foreach (string p in parts)
{
int val;
try
{
if (p.StartsWith("+"))
{
val = (int)Enum.Parse(typeof(OpenSim.Data.RegionFlags), p.Substring(1));
f |= (OpenSim.Data.RegionFlags)val;
}
else if (p.StartsWith("-"))
{
val = (int)Enum.Parse(typeof(OpenSim.Data.RegionFlags), p.Substring(1));
f &= ~(OpenSim.Data.RegionFlags)val;
}
else
{
val = (int)Enum.Parse(typeof(OpenSim.Data.RegionFlags), p);
f |= (OpenSim.Data.RegionFlags)val;
}
}
catch (Exception)
{
MainConsole.Instance.Output("Error in flag specification: " + p);
}
}
return (int)f;
}
private void HandleSetFlags(string module, string[] cmd)
{
if (cmd.Length < 5)
{
MainConsole.Instance.Output("Syntax: set region flags <region name> <flags>");
return;
}
List<RegionData> regions = m_Database.Get(cmd[3], UUID.Zero);
if (regions == null || regions.Count < 1)
{
MainConsole.Instance.Output("Region not found");
return;
}
foreach (RegionData r in regions)
{
int flags = Convert.ToInt32(r.Data["flags"]);
flags = ParseFlags(flags, cmd[4]);
r.Data["flags"] = flags.ToString();
OpenSim.Data.RegionFlags f = (OpenSim.Data.RegionFlags)flags;
MainConsole.Instance.Output(String.Format("Set region {0} to {1}", r.RegionName, f));
m_Database.Store(r);
}
}
}
}
| |
// 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.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Security;
using System.Text;
using System.Threading;
namespace System.Diagnostics
{
/// <devdoc>
/// <para>
/// Provides access to local and remote
/// processes. Enables you to start and stop system processes.
/// </para>
/// </devdoc>
public partial class Process : Component
{
private bool _haveProcessId;
private int _processId;
private bool _haveProcessHandle;
private SafeProcessHandle _processHandle;
private bool _isRemoteMachine;
private string _machineName;
private ProcessInfo _processInfo;
private ProcessThreadCollection _threads;
private ProcessModuleCollection _modules;
private bool _haveWorkingSetLimits;
private IntPtr _minWorkingSet;
private IntPtr _maxWorkingSet;
private bool _haveProcessorAffinity;
private IntPtr _processorAffinity;
private bool _havePriorityClass;
private ProcessPriorityClass _priorityClass;
private ProcessStartInfo _startInfo;
private bool _watchForExit;
private bool _watchingForExit;
private EventHandler _onExited;
private bool _exited;
private int _exitCode;
private DateTime? _startTime;
private DateTime _exitTime;
private bool _haveExitTime;
private bool _priorityBoostEnabled;
private bool _havePriorityBoostEnabled;
private bool _raisedOnExited;
private RegisteredWaitHandle _registeredWaitHandle;
private WaitHandle _waitHandle;
private StreamReader _standardOutput;
private StreamWriter _standardInput;
private StreamReader _standardError;
private bool _disposed;
private bool _haveMainWindow;
private IntPtr _mainWindowHandle;
private string _mainWindowTitle;
private bool _haveResponding;
private bool _responding;
private static object s_createProcessLock = new object();
private StreamReadMode _outputStreamReadMode;
private StreamReadMode _errorStreamReadMode;
// Support for asynchronously reading streams
public event DataReceivedEventHandler OutputDataReceived;
public event DataReceivedEventHandler ErrorDataReceived;
// Abstract the stream details
internal AsyncStreamReader _output;
internal AsyncStreamReader _error;
internal bool _pendingOutputRead;
internal bool _pendingErrorRead;
#if FEATURE_TRACESWITCH
internal static TraceSwitch _processTracing =
#if DEBUG
new TraceSwitch("processTracing", "Controls debug output from Process component");
#else
null;
#endif
#endif
/// <devdoc>
/// <para>
/// Initializes a new instance of the <see cref='System.Diagnostics.Process'/> class.
/// </para>
/// </devdoc>
public Process()
{
// This class once inherited a finalizer. For backward compatibility it has one so that
// any derived class that depends on it will see the behaviour expected. Since it is
// not used by this class itself, suppress it immediately if this is not an instance
// of a derived class it doesn't suffer the GC burden of finalization.
if (GetType() == typeof(Process))
{
GC.SuppressFinalize(this);
}
_machineName = ".";
_outputStreamReadMode = StreamReadMode.Undefined;
_errorStreamReadMode = StreamReadMode.Undefined;
}
private Process(string machineName, bool isRemoteMachine, int processId, ProcessInfo processInfo)
{
GC.SuppressFinalize(this);
_processInfo = processInfo;
_machineName = machineName;
_isRemoteMachine = isRemoteMachine;
_processId = processId;
_haveProcessId = true;
_outputStreamReadMode = StreamReadMode.Undefined;
_errorStreamReadMode = StreamReadMode.Undefined;
}
public SafeProcessHandle SafeHandle
{
get
{
EnsureState(State.Associated);
return OpenProcessHandle();
}
}
public IntPtr Handle => SafeHandle.DangerousGetHandle();
/// <devdoc>
/// Returns whether this process component is associated with a real process.
/// </devdoc>
/// <internalonly/>
bool Associated
{
get { return _haveProcessId || _haveProcessHandle; }
}
/// <devdoc>
/// <para>
/// Gets the base priority of
/// the associated process.
/// </para>
/// </devdoc>
public int BasePriority
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.BasePriority;
}
}
/// <devdoc>
/// <para>
/// Gets
/// the
/// value that was specified by the associated process when it was terminated.
/// </para>
/// </devdoc>
public int ExitCode
{
get
{
EnsureState(State.Exited);
return _exitCode;
}
}
/// <devdoc>
/// <para>
/// Gets a
/// value indicating whether the associated process has been terminated.
/// </para>
/// </devdoc>
public bool HasExited
{
get
{
if (!_exited)
{
EnsureState(State.Associated);
UpdateHasExited();
if (_exited)
{
RaiseOnExited();
}
}
return _exited;
}
}
/// <summary>Gets the time the associated process was started.</summary>
public DateTime StartTime
{
get
{
if (!_startTime.HasValue)
{
_startTime = StartTimeCore;
}
return _startTime.Value;
}
}
/// <devdoc>
/// <para>
/// Gets the time that the associated process exited.
/// </para>
/// </devdoc>
public DateTime ExitTime
{
get
{
if (!_haveExitTime)
{
EnsureState(State.Exited);
_exitTime = ExitTimeCore;
_haveExitTime = true;
}
return _exitTime;
}
}
/// <devdoc>
/// <para>
/// Gets
/// the unique identifier for the associated process.
/// </para>
/// </devdoc>
public int Id
{
get
{
EnsureState(State.HaveId);
return _processId;
}
}
/// <devdoc>
/// <para>
/// Gets
/// the name of the computer on which the associated process is running.
/// </para>
/// </devdoc>
public string MachineName
{
get
{
EnsureState(State.Associated);
return _machineName;
}
}
/// <devdoc>
/// <para>
/// Gets or sets the maximum allowable working set for the associated
/// process.
/// </para>
/// </devdoc>
public IntPtr MaxWorkingSet
{
get
{
EnsureWorkingSetLimits();
return _maxWorkingSet;
}
set
{
SetWorkingSetLimits(null, value);
}
}
/// <devdoc>
/// <para>
/// Gets or sets the minimum allowable working set for the associated
/// process.
/// </para>
/// </devdoc>
public IntPtr MinWorkingSet
{
get
{
EnsureWorkingSetLimits();
return _minWorkingSet;
}
set
{
SetWorkingSetLimits(value, null);
}
}
public ProcessModuleCollection Modules
{
get
{
if (_modules == null)
{
EnsureState(State.HaveId | State.IsLocal);
_modules = ProcessManager.GetModules(_processId);
}
return _modules;
}
}
public long NonpagedSystemMemorySize64
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.PoolNonPagedBytes;
}
}
[ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.NonpagedSystemMemorySize64 instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public int NonpagedSystemMemorySize
{
get
{
EnsureState(State.HaveProcessInfo);
return unchecked((int)_processInfo.PoolNonPagedBytes);
}
}
public long PagedMemorySize64
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.PageFileBytes;
}
}
[ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.PagedMemorySize64 instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public int PagedMemorySize
{
get
{
EnsureState(State.HaveProcessInfo);
return unchecked((int)_processInfo.PageFileBytes);
}
}
public long PagedSystemMemorySize64
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.PoolPagedBytes;
}
}
[ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.PagedSystemMemorySize64 instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public int PagedSystemMemorySize
{
get
{
EnsureState(State.HaveProcessInfo);
return unchecked((int)_processInfo.PoolPagedBytes);
}
}
public long PeakPagedMemorySize64
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.PageFileBytesPeak;
}
}
[ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.PeakPagedMemorySize64 instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public int PeakPagedMemorySize
{
get
{
EnsureState(State.HaveProcessInfo);
return unchecked((int)_processInfo.PageFileBytesPeak);
}
}
public long PeakWorkingSet64
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.WorkingSetPeak;
}
}
[ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.PeakWorkingSet64 instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public int PeakWorkingSet
{
get
{
EnsureState(State.HaveProcessInfo);
return unchecked((int)_processInfo.WorkingSetPeak);
}
}
public long PeakVirtualMemorySize64
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.VirtualBytesPeak;
}
}
[ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.PeakVirtualMemorySize64 instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public int PeakVirtualMemorySize
{
get
{
EnsureState(State.HaveProcessInfo);
return unchecked((int)_processInfo.VirtualBytesPeak);
}
}
/// <devdoc>
/// <para>
/// Gets or sets a value indicating whether the associated process priority
/// should be temporarily boosted by the operating system when the main window
/// has focus.
/// </para>
/// </devdoc>
public bool PriorityBoostEnabled
{
get
{
if (!_havePriorityBoostEnabled)
{
_priorityBoostEnabled = PriorityBoostEnabledCore;
_havePriorityBoostEnabled = true;
}
return _priorityBoostEnabled;
}
set
{
PriorityBoostEnabledCore = value;
_priorityBoostEnabled = value;
_havePriorityBoostEnabled = true;
}
}
/// <devdoc>
/// <para>
/// Gets or sets the overall priority category for the
/// associated process.
/// </para>
/// </devdoc>
public ProcessPriorityClass PriorityClass
{
get
{
if (!_havePriorityClass)
{
_priorityClass = PriorityClassCore;
_havePriorityClass = true;
}
return _priorityClass;
}
set
{
if (!Enum.IsDefined(typeof(ProcessPriorityClass), value))
{
throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(ProcessPriorityClass));
}
PriorityClassCore = value;
_priorityClass = value;
_havePriorityClass = true;
}
}
public long PrivateMemorySize64
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.PrivateBytes;
}
}
[ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.PrivateMemorySize64 instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public int PrivateMemorySize
{
get
{
EnsureState(State.HaveProcessInfo);
return unchecked((int)_processInfo.PrivateBytes);
}
}
/// <devdoc>
/// <para>
/// Gets
/// the friendly name of the process.
/// </para>
/// </devdoc>
public string ProcessName
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.ProcessName;
}
}
/// <devdoc>
/// <para>
/// Gets
/// or sets which processors the threads in this process can be scheduled to run on.
/// </para>
/// </devdoc>
public IntPtr ProcessorAffinity
{
get
{
if (!_haveProcessorAffinity)
{
_processorAffinity = ProcessorAffinityCore;
_haveProcessorAffinity = true;
}
return _processorAffinity;
}
set
{
ProcessorAffinityCore = value;
_processorAffinity = value;
_haveProcessorAffinity = true;
}
}
public int SessionId
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.SessionId;
}
}
/// <devdoc>
/// <para>
/// Gets or sets the properties to pass into the <see cref='System.Diagnostics.Process.Start'/> method for the <see cref='System.Diagnostics.Process'/>
/// .
/// </para>
/// </devdoc>
public ProcessStartInfo StartInfo
{
get
{
if (_startInfo == null)
{
if (Associated)
{
throw new InvalidOperationException(SR.CantGetProcessStartInfo);
}
_startInfo = new ProcessStartInfo();
}
return _startInfo;
}
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
if (Associated)
{
throw new InvalidOperationException(SR.CantSetProcessStartInfo);
}
_startInfo = value;
}
}
/// <devdoc>
/// <para>
/// Gets the set of threads that are running in the associated
/// process.
/// </para>
/// </devdoc>
public ProcessThreadCollection Threads
{
get
{
if (_threads == null)
{
EnsureState(State.HaveProcessInfo);
int count = _processInfo._threadInfoList.Count;
ProcessThread[] newThreadsArray = new ProcessThread[count];
for (int i = 0; i < count; i++)
{
newThreadsArray[i] = new ProcessThread(_isRemoteMachine, _processId, (ThreadInfo)_processInfo._threadInfoList[i]);
}
ProcessThreadCollection newThreads = new ProcessThreadCollection(newThreadsArray);
_threads = newThreads;
}
return _threads;
}
}
public int HandleCount
{
get
{
EnsureState(State.HaveProcessInfo);
EnsureHandleCountPopulated();
return _processInfo.HandleCount;
}
}
partial void EnsureHandleCountPopulated();
[ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.VirtualMemorySize64 instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public long VirtualMemorySize64
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.VirtualBytes;
}
}
public int VirtualMemorySize
{
get
{
EnsureState(State.HaveProcessInfo);
return unchecked((int)_processInfo.VirtualBytes);
}
}
/// <devdoc>
/// <para>
/// Gets or sets whether the <see cref='System.Diagnostics.Process.Exited'/>
/// event is fired
/// when the process terminates.
/// </para>
/// </devdoc>
public bool EnableRaisingEvents
{
get
{
return _watchForExit;
}
set
{
if (value != _watchForExit)
{
if (Associated)
{
if (value)
{
OpenProcessHandle();
EnsureWatchingForExit();
}
else
{
StopWatchingForExit();
}
}
_watchForExit = value;
}
}
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public StreamWriter StandardInput
{
get
{
if (_standardInput == null)
{
throw new InvalidOperationException(SR.CantGetStandardIn);
}
return _standardInput;
}
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public StreamReader StandardOutput
{
get
{
if (_standardOutput == null)
{
throw new InvalidOperationException(SR.CantGetStandardOut);
}
if (_outputStreamReadMode == StreamReadMode.Undefined)
{
_outputStreamReadMode = StreamReadMode.SyncMode;
}
else if (_outputStreamReadMode != StreamReadMode.SyncMode)
{
throw new InvalidOperationException(SR.CantMixSyncAsyncOperation);
}
return _standardOutput;
}
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public StreamReader StandardError
{
get
{
if (_standardError == null)
{
throw new InvalidOperationException(SR.CantGetStandardError);
}
if (_errorStreamReadMode == StreamReadMode.Undefined)
{
_errorStreamReadMode = StreamReadMode.SyncMode;
}
else if (_errorStreamReadMode != StreamReadMode.SyncMode)
{
throw new InvalidOperationException(SR.CantMixSyncAsyncOperation);
}
return _standardError;
}
}
public long WorkingSet64
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.WorkingSet;
}
}
[ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.WorkingSet64 instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public int WorkingSet
{
get
{
EnsureState(State.HaveProcessInfo);
return unchecked((int)_processInfo.WorkingSet);
}
}
public event EventHandler Exited
{
add
{
_onExited += value;
}
remove
{
_onExited -= value;
}
}
/// <devdoc>
/// Release the temporary handle we used to get process information.
/// If we used the process handle stored in the process object (we have all access to the handle,) don't release it.
/// </devdoc>
/// <internalonly/>
private void ReleaseProcessHandle(SafeProcessHandle handle)
{
if (handle == null)
{
return;
}
if (_haveProcessHandle && handle == _processHandle)
{
return;
}
#if FEATURE_TRACESWITCH
Debug.WriteLineIf(_processTracing.TraceVerbose, "Process - CloseHandle(process)");
#endif
handle.Dispose();
}
/// <devdoc>
/// This is called from the threadpool when a process exits.
/// </devdoc>
/// <internalonly/>
private void CompletionCallback(object context, bool wasSignaled)
{
StopWatchingForExit();
RaiseOnExited();
}
/// <internalonly/>
/// <devdoc>
/// <para>
/// Free any resources associated with this component.
/// </para>
/// </devdoc>
protected override void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
//Dispose managed and unmanaged resources
Close();
}
_disposed = true;
}
}
public bool Responding
{
get
{
if (!_haveResponding)
{
_responding = IsRespondingCore();
_haveResponding = true;
}
return _responding;
}
}
public string MainWindowTitle
{
get
{
if (_mainWindowTitle == null)
{
_mainWindowTitle = GetMainWindowTitle();
}
return _mainWindowTitle;
}
}
public bool CloseMainWindow()
{
return CloseMainWindowCore();
}
public bool WaitForInputIdle()
{
return WaitForInputIdle(int.MaxValue);
}
public bool WaitForInputIdle(int milliseconds)
{
return WaitForInputIdleCore(milliseconds);
}
public IntPtr MainWindowHandle
{
get
{
if (!_haveMainWindow)
{
EnsureState(State.IsLocal | State.HaveId);
_mainWindowHandle = ProcessManager.GetMainWindowHandle(_processId);
_haveMainWindow = true;
}
return _mainWindowHandle;
}
}
public ISynchronizeInvoke SynchronizingObject { get; set; }
/// <devdoc>
/// <para>
/// Frees any resources associated with this component.
/// </para>
/// </devdoc>
public void Close()
{
if (Associated)
{
if (_haveProcessHandle)
{
StopWatchingForExit();
#if FEATURE_TRACESWITCH
Debug.WriteLineIf(_processTracing.TraceVerbose, "Process - CloseHandle(process) in Close()");
#endif
_processHandle.Dispose();
_processHandle = null;
_haveProcessHandle = false;
}
_haveProcessId = false;
_isRemoteMachine = false;
_machineName = ".";
_raisedOnExited = false;
//Don't call close on the Readers and writers
//since they might be referenced by somebody else while the
//process is still alive but this method called.
_standardOutput = null;
_standardInput = null;
_standardError = null;
_output = null;
_error = null;
CloseCore();
Refresh();
}
}
/// <devdoc>
/// Helper method for checking preconditions when accessing properties.
/// </devdoc>
/// <internalonly/>
private void EnsureState(State state)
{
if ((state & State.Associated) != (State)0)
if (!Associated)
throw new InvalidOperationException(SR.NoAssociatedProcess);
if ((state & State.HaveId) != (State)0)
{
if (!_haveProcessId)
{
if (_haveProcessHandle)
{
SetProcessId(ProcessManager.GetProcessIdFromHandle(_processHandle));
}
else
{
EnsureState(State.Associated);
throw new InvalidOperationException(SR.ProcessIdRequired);
}
}
}
if ((state & State.IsLocal) != (State)0 && _isRemoteMachine)
{
throw new NotSupportedException(SR.NotSupportedRemote);
}
if ((state & State.HaveProcessInfo) != (State)0)
{
if (_processInfo == null)
{
if ((state & State.HaveId) == (State)0) EnsureState(State.HaveId);
_processInfo = ProcessManager.GetProcessInfo(_processId, _machineName);
if (_processInfo == null)
{
throw new InvalidOperationException(SR.NoProcessInfo);
}
}
}
if ((state & State.Exited) != (State)0)
{
if (!HasExited)
{
throw new InvalidOperationException(SR.WaitTillExit);
}
if (!_haveProcessHandle)
{
throw new InvalidOperationException(SR.NoProcessHandle);
}
}
}
/// <devdoc>
/// Make sure we are watching for a process exit.
/// </devdoc>
/// <internalonly/>
private void EnsureWatchingForExit()
{
if (!_watchingForExit)
{
lock (this)
{
if (!_watchingForExit)
{
Debug.Assert(_haveProcessHandle, "Process.EnsureWatchingForExit called with no process handle");
Debug.Assert(Associated, "Process.EnsureWatchingForExit called with no associated process");
_watchingForExit = true;
try
{
_waitHandle = new ProcessWaitHandle(_processHandle);
_registeredWaitHandle = ThreadPool.RegisterWaitForSingleObject(_waitHandle,
new WaitOrTimerCallback(CompletionCallback), null, -1, true);
}
catch
{
_watchingForExit = false;
throw;
}
}
}
}
}
/// <devdoc>
/// Make sure we have obtained the min and max working set limits.
/// </devdoc>
/// <internalonly/>
private void EnsureWorkingSetLimits()
{
if (!_haveWorkingSetLimits)
{
GetWorkingSetLimits(out _minWorkingSet, out _maxWorkingSet);
_haveWorkingSetLimits = true;
}
}
/// <devdoc>
/// Helper to set minimum or maximum working set limits.
/// </devdoc>
/// <internalonly/>
private void SetWorkingSetLimits(IntPtr? min, IntPtr? max)
{
SetWorkingSetLimitsCore(min, max, out _minWorkingSet, out _maxWorkingSet);
_haveWorkingSetLimits = true;
}
/// <devdoc>
/// <para>
/// Returns a new <see cref='System.Diagnostics.Process'/> component given a process identifier and
/// the name of a computer in the network.
/// </para>
/// </devdoc>
public static Process GetProcessById(int processId, string machineName)
{
if (!ProcessManager.IsProcessRunning(processId, machineName))
{
throw new ArgumentException(SR.Format(SR.MissingProccess, processId.ToString(CultureInfo.CurrentCulture)));
}
return new Process(machineName, ProcessManager.IsRemoteMachine(machineName), processId, null);
}
/// <devdoc>
/// <para>
/// Returns a new <see cref='System.Diagnostics.Process'/> component given the
/// identifier of a process on the local computer.
/// </para>
/// </devdoc>
public static Process GetProcessById(int processId)
{
return GetProcessById(processId, ".");
}
/// <devdoc>
/// <para>
/// Creates an array of <see cref='System.Diagnostics.Process'/> components that are
/// associated
/// with process resources on the
/// local computer. These process resources share the specified process name.
/// </para>
/// </devdoc>
public static Process[] GetProcessesByName(string processName)
{
return GetProcessesByName(processName, ".");
}
/// <devdoc>
/// <para>
/// Creates a new <see cref='System.Diagnostics.Process'/>
/// component for each process resource on the local computer.
/// </para>
/// </devdoc>
public static Process[] GetProcesses()
{
return GetProcesses(".");
}
/// <devdoc>
/// <para>
/// Creates a new <see cref='System.Diagnostics.Process'/>
/// component for each
/// process resource on the specified computer.
/// </para>
/// </devdoc>
public static Process[] GetProcesses(string machineName)
{
bool isRemoteMachine = ProcessManager.IsRemoteMachine(machineName);
ProcessInfo[] processInfos = ProcessManager.GetProcessInfos(machineName);
Process[] processes = new Process[processInfos.Length];
for (int i = 0; i < processInfos.Length; i++)
{
ProcessInfo processInfo = processInfos[i];
processes[i] = new Process(machineName, isRemoteMachine, processInfo.ProcessId, processInfo);
}
#if FEATURE_TRACESWITCH
Debug.WriteLineIf(_processTracing.TraceVerbose, "Process.GetProcesses(" + machineName + ")");
#if DEBUG
if (_processTracing.TraceVerbose) {
Debug.Indent();
for (int i = 0; i < processInfos.Length; i++) {
Debug.WriteLine(processes[i].Id + ": " + processes[i].ProcessName);
}
Debug.Unindent();
}
#endif
#endif
return processes;
}
/// <devdoc>
/// <para>
/// Returns a new <see cref='System.Diagnostics.Process'/>
/// component and associates it with the current active process.
/// </para>
/// </devdoc>
public static Process GetCurrentProcess()
{
return new Process(".", false, GetCurrentProcessId(), null);
}
/// <devdoc>
/// <para>
/// Raises the <see cref='System.Diagnostics.Process.Exited'/> event.
/// </para>
/// </devdoc>
protected void OnExited()
{
EventHandler exited = _onExited;
if (exited != null)
{
exited(this, EventArgs.Empty);
}
}
/// <devdoc>
/// Raise the Exited event, but make sure we don't do it more than once.
/// </devdoc>
/// <internalonly/>
private void RaiseOnExited()
{
if (!_raisedOnExited)
{
lock (this)
{
if (!_raisedOnExited)
{
_raisedOnExited = true;
OnExited();
}
}
}
}
/// <devdoc>
/// <para>
/// Discards any information about the associated process
/// that has been cached inside the process component. After <see cref='System.Diagnostics.Process.Refresh'/> is called, the
/// first request for information for each property causes the process component
/// to obtain a new value from the associated process.
/// </para>
/// </devdoc>
public void Refresh()
{
_processInfo = null;
_threads = null;
_modules = null;
_exited = false;
_haveWorkingSetLimits = false;
_haveProcessorAffinity = false;
_havePriorityClass = false;
_haveExitTime = false;
_havePriorityBoostEnabled = false;
RefreshCore();
}
/// <summary>
/// Opens a long-term handle to the process, with all access. If a handle exists,
/// then it is reused. If the process has exited, it throws an exception.
/// </summary>
private SafeProcessHandle OpenProcessHandle()
{
if (!_haveProcessHandle)
{
//Cannot open a new process handle if the object has been disposed, since finalization has been suppressed.
if (_disposed)
{
throw new ObjectDisposedException(GetType().Name);
}
SetProcessHandle(GetProcessHandle());
}
return _processHandle;
}
/// <devdoc>
/// Helper to associate a process handle with this component.
/// </devdoc>
/// <internalonly/>
private void SetProcessHandle(SafeProcessHandle processHandle)
{
_processHandle = processHandle;
_haveProcessHandle = true;
if (_watchForExit)
{
EnsureWatchingForExit();
}
}
/// <devdoc>
/// Helper to associate a process id with this component.
/// </devdoc>
/// <internalonly/>
private void SetProcessId(int processId)
{
_processId = processId;
_haveProcessId = true;
ConfigureAfterProcessIdSet();
}
/// <summary>Additional optional configuration hook after a process ID is set.</summary>
partial void ConfigureAfterProcessIdSet();
/// <devdoc>
/// <para>
/// Starts a process specified by the <see cref='System.Diagnostics.Process.StartInfo'/> property of this <see cref='System.Diagnostics.Process'/>
/// component and associates it with the
/// <see cref='System.Diagnostics.Process'/> . If a process resource is reused
/// rather than started, the reused process is associated with this <see cref='System.Diagnostics.Process'/>
/// component.
/// </para>
/// </devdoc>
public bool Start()
{
Close();
ProcessStartInfo startInfo = StartInfo;
if (startInfo.FileName.Length == 0)
{
throw new InvalidOperationException(SR.FileNameMissing);
}
if (startInfo.StandardOutputEncoding != null && !startInfo.RedirectStandardOutput)
{
throw new InvalidOperationException(SR.StandardOutputEncodingNotAllowed);
}
if (startInfo.StandardErrorEncoding != null && !startInfo.RedirectStandardError)
{
throw new InvalidOperationException(SR.StandardErrorEncodingNotAllowed);
}
//Cannot start a new process and store its handle if the object has been disposed, since finalization has been suppressed.
if (_disposed)
{
throw new ObjectDisposedException(GetType().Name);
}
return StartCore(startInfo);
}
/// <devdoc>
/// <para>
/// Starts a process resource by specifying the name of a
/// document or application file. Associates the process resource with a new <see cref='System.Diagnostics.Process'/>
/// component.
/// </para>
/// </devdoc>
public static Process Start(string fileName)
{
return Start(new ProcessStartInfo(fileName));
}
/// <devdoc>
/// <para>
/// Starts a process resource by specifying the name of an
/// application and a set of command line arguments. Associates the process resource
/// with a new <see cref='System.Diagnostics.Process'/>
/// component.
/// </para>
/// </devdoc>
public static Process Start(string fileName, string arguments)
{
return Start(new ProcessStartInfo(fileName, arguments));
}
/// <devdoc>
/// <para>
/// Starts a process resource specified by the process start
/// information passed in, for example the file name of the process to start.
/// Associates the process resource with a new <see cref='System.Diagnostics.Process'/>
/// component.
/// </para>
/// </devdoc>
public static Process Start(ProcessStartInfo startInfo)
{
Process process = new Process();
if (startInfo == null)
throw new ArgumentNullException(nameof(startInfo));
process.StartInfo = startInfo;
return process.Start() ?
process :
null;
}
/// <devdoc>
/// Make sure we are not watching for process exit.
/// </devdoc>
/// <internalonly/>
private void StopWatchingForExit()
{
if (_watchingForExit)
{
RegisteredWaitHandle rwh = null;
WaitHandle wh = null;
lock (this)
{
if (_watchingForExit)
{
_watchingForExit = false;
wh = _waitHandle;
_waitHandle = null;
rwh = _registeredWaitHandle;
_registeredWaitHandle = null;
}
}
if (rwh != null)
{
rwh.Unregister(null);
}
if (wh != null)
{
wh.Dispose();
}
}
}
public override string ToString()
{
if (Associated)
{
string processName = ProcessName;
if (processName.Length != 0)
{
return String.Format(CultureInfo.CurrentCulture, "{0} ({1})", base.ToString(), processName);
}
}
return base.ToString();
}
/// <devdoc>
/// <para>
/// Instructs the <see cref='System.Diagnostics.Process'/> component to wait
/// indefinitely for the associated process to exit.
/// </para>
/// </devdoc>
public void WaitForExit()
{
WaitForExit(Timeout.Infinite);
}
/// <summary>
/// Instructs the Process component to wait the specified number of milliseconds for
/// the associated process to exit.
/// </summary>
public bool WaitForExit(int milliseconds)
{
bool exited = WaitForExitCore(milliseconds);
if (exited && _watchForExit)
{
RaiseOnExited();
}
return exited;
}
/// <devdoc>
/// <para>
/// Instructs the <see cref='System.Diagnostics.Process'/> component to start
/// reading the StandardOutput stream asynchronously. The user can register a callback
/// that will be called when a line of data terminated by \n,\r or \r\n is reached, or the end of stream is reached
/// then the remaining information is returned. The user can add an event handler to OutputDataReceived.
/// </para>
/// </devdoc>
public void BeginOutputReadLine()
{
if (_outputStreamReadMode == StreamReadMode.Undefined)
{
_outputStreamReadMode = StreamReadMode.AsyncMode;
}
else if (_outputStreamReadMode != StreamReadMode.AsyncMode)
{
throw new InvalidOperationException(SR.CantMixSyncAsyncOperation);
}
if (_pendingOutputRead)
throw new InvalidOperationException(SR.PendingAsyncOperation);
_pendingOutputRead = true;
// We can't detect if there's a pending synchronous read, stream also doesn't.
if (_output == null)
{
if (_standardOutput == null)
{
throw new InvalidOperationException(SR.CantGetStandardOut);
}
Stream s = _standardOutput.BaseStream;
_output = new AsyncStreamReader(s, OutputReadNotifyUser, _standardOutput.CurrentEncoding);
}
_output.BeginReadLine();
}
/// <devdoc>
/// <para>
/// Instructs the <see cref='System.Diagnostics.Process'/> component to start
/// reading the StandardError stream asynchronously. The user can register a callback
/// that will be called when a line of data terminated by \n,\r or \r\n is reached, or the end of stream is reached
/// then the remaining information is returned. The user can add an event handler to ErrorDataReceived.
/// </para>
/// </devdoc>
public void BeginErrorReadLine()
{
if (_errorStreamReadMode == StreamReadMode.Undefined)
{
_errorStreamReadMode = StreamReadMode.AsyncMode;
}
else if (_errorStreamReadMode != StreamReadMode.AsyncMode)
{
throw new InvalidOperationException(SR.CantMixSyncAsyncOperation);
}
if (_pendingErrorRead)
{
throw new InvalidOperationException(SR.PendingAsyncOperation);
}
_pendingErrorRead = true;
// We can't detect if there's a pending synchronous read, stream also doesn't.
if (_error == null)
{
if (_standardError == null)
{
throw new InvalidOperationException(SR.CantGetStandardError);
}
Stream s = _standardError.BaseStream;
_error = new AsyncStreamReader(s, ErrorReadNotifyUser, _standardError.CurrentEncoding);
}
_error.BeginReadLine();
}
/// <devdoc>
/// <para>
/// Instructs the <see cref='System.Diagnostics.Process'/> component to cancel the asynchronous operation
/// specified by BeginOutputReadLine().
/// </para>
/// </devdoc>
public void CancelOutputRead()
{
if (_output != null)
{
_output.CancelOperation();
}
else
{
throw new InvalidOperationException(SR.NoAsyncOperation);
}
_pendingOutputRead = false;
}
/// <devdoc>
/// <para>
/// Instructs the <see cref='System.Diagnostics.Process'/> component to cancel the asynchronous operation
/// specified by BeginErrorReadLine().
/// </para>
/// </devdoc>
public void CancelErrorRead()
{
if (_error != null)
{
_error.CancelOperation();
}
else
{
throw new InvalidOperationException(SR.NoAsyncOperation);
}
_pendingErrorRead = false;
}
internal void OutputReadNotifyUser(String data)
{
// To avoid race between remove handler and raising the event
DataReceivedEventHandler outputDataReceived = OutputDataReceived;
if (outputDataReceived != null)
{
DataReceivedEventArgs e = new DataReceivedEventArgs(data);
outputDataReceived(this, e); // Call back to user informing data is available
}
}
internal void ErrorReadNotifyUser(String data)
{
// To avoid race between remove handler and raising the event
DataReceivedEventHandler errorDataReceived = ErrorDataReceived;
if (errorDataReceived != null)
{
DataReceivedEventArgs e = new DataReceivedEventArgs(data);
errorDataReceived(this, e); // Call back to user informing data is available.
}
}
/// <summary>
/// This enum defines the operation mode for redirected process stream.
/// We don't support switching between synchronous mode and asynchronous mode.
/// </summary>
private enum StreamReadMode
{
Undefined,
SyncMode,
AsyncMode
}
/// <summary>A desired internal state.</summary>
private enum State
{
HaveId = 0x1,
IsLocal = 0x2,
HaveProcessInfo = 0x8,
Exited = 0x10,
Associated = 0x20,
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using DeOps.Interface;
using DeOps.Interface.Views;
using DeOps.Implementation;
using DeOps.Services.Trust;
namespace DeOps.Services.Chat
{
public partial class ChatView : ViewShell
{
public CoreUI UI;
ChatService Chat;
uint ProjectID;
public RoomView ViewHigh;
public RoomView ViewLow;
public ChatRoom Custom; // can also be used to set default room on init
bool WindowActivated;
bool FlashMe;
public ChatView(CoreUI ui, ChatService chat, uint project)
{
InitializeComponent();
UI = ui;
Chat = chat;
ProjectID = project;
Chat.Refresh += new RefreshHandler(Chat_Refresh);
GuiUtils.SetupToolstrip(toolStrip1, new OpusColorTable());
GuiUtils.FixMonoDropDownOpening(RoomsButton, RoomsButton_DropDownOpening);
RoomsButton.Visible = true;
RoomSeparator.Visible = true;
LocalButton.Visible = (Chat.Core.Trust != null);
LiveButton.Visible = (Chat.Core.Trust != null);
CustomButton.Visible = false;
JoinButton.Visible = false;
LeaveButton.Visible = false;
InviteButton.Visible = false;
}
public override void Init()
{
Chat_Refresh();
if (Custom != null) // set by invite form to open this by default
SetCustomRoom(Custom);
else if (RoomsActive(RoomKind.Command_High, RoomKind.Command_Low))
LocalButton.PerformClick();
else
{
Chat.RoomMap.LockReading(delegate()
{
foreach (ChatRoom room in Chat.RoomMap.Values)
if (room.Active && !ChatService.IsCommandRoom(room.Kind))
{
SetCustomRoom(room);
break;
}
});
}
if (External != null)
{
External.Activated += new EventHandler(External_Activated);
External.Deactivate += new EventHandler(External_Deactivate);
}
}
public override bool Fin()
{
Chat.Refresh -= new RefreshHandler(Chat_Refresh);
SetTopView(null, false);
SetBottomView(null);
if (External != null)
{
External.Activated -= new EventHandler(External_Activated);
External.Deactivate -= new EventHandler(External_Deactivate);
}
return true;
}
public override string GetTitle(bool small)
{
if (small)
return "Chat";
string title = "";
if (!CustomButton.Checked)
{
if(Chat.Core.Trust != null)
title += Chat.Core.Trust.GetProjectName(ProjectID) + " ";
if (LocalButton.Checked)
title += "Local ";
else if (LiveButton.Checked)
title += "Live ";
title += "Chat";
}
else if (Custom != null)
{
title = Custom.Title;
}
else
title = "Chat";
return title;
}
public override Size GetDefaultSize()
{
return new Size(600, 350);
}
public override Icon GetIcon()
{
return ChatRes.Icon;
}
void Chat_Refresh()
{
// set which buttons are visible/checked
if (LocalButton.Checked)
{
SetTopView( Chat.GetRoom(ProjectID, RoomKind.Command_High), false);
SetBottomView( Chat.GetRoom(ProjectID, RoomKind.Command_Low));
JoinButton.Visible = false;
LeaveButton.Visible = false;
InviteButton.Visible = false;
}
else if (LiveButton.Checked)
{
SetTopView(Chat.GetRoom(ProjectID, RoomKind.Live_High), false);
SetBottomView(Chat.GetRoom(ProjectID, RoomKind.Live_Low));
JoinButton.Visible = false;
LeaveButton.Visible = false;
InviteButton.Visible = false;
}
else if (CustomButton.Checked)
{
SetTopView(Custom, true);
SetBottomView(null);
JoinButton.Visible = !Custom.Active;
LeaveButton.Visible = Custom.Active;
InviteButton.Visible = (Custom.Active &&
(Custom.Kind == RoomKind.Private || Custom.Host == Chat.Core.UserID));
}
LocalButton.ForeColor = RoomsActive(RoomKind.Command_High, RoomKind.Command_Low) ? Color.Black : Color.DimGray;
LiveButton.ForeColor = RoomsActive(RoomKind.Live_High, RoomKind.Live_Low) ? Color.Black : Color.DimGray;
if(Custom != null)
CustomButton.ForeColor = Custom.Active ? Color.Black : Color.DimGray;
// collapse unused panels
if (ViewContainer.Panel1.Controls.Count == 0)
ViewContainer.Panel1Collapsed = true;
if (ViewContainer.Panel2.Controls.Count == 0)
ViewContainer.Panel2Collapsed = true;
if (External != null)
External.Text = GetTitle(false);
}
private bool RoomsActive(params RoomKind[] kinds)
{
foreach (RoomKind kind in kinds)
{
ChatRoom room = Chat.GetRoom(ProjectID, kind);
if (room != null && ChatService.IsCommandRoom(room.Kind))
{
// if more people in command room, even if not online then it is active
if (room.Members.SafeCount > 1)
return true;
}
}
return false;
}
void SetTopView(ChatRoom room, bool force)
{
if (ViewHigh != null)
{
if (ViewHigh.Room == room && (force || room.Members.SafeCount > 1))
return;
ViewHigh.Fin();
ViewContainer.Panel1.Controls.Clear();
ViewHigh = null;
}
if (room == null || (!force && room.Members.SafeCount <= 1))
return;
ViewHigh = new RoomView(this, Chat, room);
ViewHigh.Dock = DockStyle.Fill;
ViewContainer.Panel1.Controls.Add(ViewHigh);
ViewHigh.Init();
ViewContainer.Panel1Collapsed = false;
}
void SetBottomView(ChatRoom room)
{
if (ViewLow != null)
{
if (ViewLow.Room == room && room.Members.SafeCount > 1)
return;
ViewLow.Fin();
ViewContainer.Panel2.Controls.Clear();
ViewLow = null;
}
if (room == null || room.Members.SafeCount <= 1)
return;
ViewLow = new RoomView(this, Chat, room);
ViewLow.Dock = DockStyle.Fill;
ViewContainer.Panel2.Controls.Add(ViewLow);
ViewLow.Init();
ViewContainer.Panel2Collapsed = false;
}
private void LocalButton_Click(object sender, EventArgs e)
{
LocalButton.Checked = true;
LiveButton.Checked = false;
CustomButton.Checked = false;
Chat_Refresh();
}
private void LiveButton_Click(object sender, EventArgs e)
{
LocalButton.Checked = false;
LiveButton.Checked = true;
CustomButton.Checked = false;
Chat_Refresh();
}
private void CustomButton_Click(object sender, EventArgs e)
{
LocalButton.Checked = false;
LiveButton.Checked = false;
CustomButton.Checked = true;
Chat_Refresh();
}
private void JoinButton_Click(object sender, EventArgs e)
{
if (Custom == null)
return;
Chat.JoinRoom(Custom);
}
private void LeaveButton_Click(object sender, EventArgs e)
{
if (Custom == null)
return;
Chat.LeaveRoom(Custom);
}
private void RoomsButton_DropDownOpening(object sender, EventArgs e)
{
RoomsButton.DropDownItems.Clear();
ToolStripMenuItem recent = new ToolStripMenuItem("Recent");
Chat.RoomMap.LockReading(delegate()
{
foreach (ChatRoom room in Chat.RoomMap.Values)
if (!ChatService.IsCommandRoom(room.Kind))
{
ToolStripMenuItem item = new RoomItem(Chat, room, RoomMenu_Click);
if (room.Active)
RoomsButton.DropDownItems.Add(item);
else
recent.DropDownItems.Add(item);
}
});
if(RoomsButton.DropDownItems.Count > 0)
RoomsButton.DropDownItems.Add(new ToolStripSeparator());
RoomsButton.DropDownItems.Add(new ToolStripMenuItem("Join", null, RoomMenu_Join));
RoomsButton.DropDownItems.Add(new ToolStripMenuItem("Create", null, RoomMenu_Create));
if (recent.DropDownItems.Count > 0)
RoomsButton.DropDownItems.Add(recent);
}
private void RoomMenu_Click(object sender, EventArgs e)
{
RoomItem item = sender as RoomItem;
if (item == null)
return;
SetCustomRoom(item.Room);
}
private void RoomMenu_Create(object sender, EventArgs e)
{
CreateRoom form = new CreateRoom();
if (form.ShowDialog() == DialogResult.OK)
{
string name = form.TitleBox.Text.Trim(' ');
if (name == "")
return;
RoomKind kind = RoomKind.Public;
if (form.PrivateRadio.Checked) kind = RoomKind.Private;
if (form.SecretRadio.Checked) kind = RoomKind.Secret;
ChatRoom room = Chat.CreateRoom(name, kind);
SetCustomRoom(room);
}
}
private void RoomMenu_Join(object sender, EventArgs e)
{
GetTextDialog join = new GetTextDialog("Join Room", "Enter the name of the room", "");
if (join.ShowDialog() != DialogResult.OK)
return;
string name = join.ResultBox.Text;
if (name == "")
return;
ChatRoom room = Chat.CreateRoom(name, RoomKind.Public);
SetCustomRoom(room);
}
public void SetCustomRoom(ChatRoom room)
{
CustomButton.Visible = true;
CustomButton.Text = room.Title;
Custom = room;
CustomButton.PerformClick();
}
private void InviteButton_Click(object sender, EventArgs e)
{
if(Custom == null)
return;
AddUsersDialog add = new AddUsersDialog(UI, ProjectID);
add.Text = "Invite People";
add.AddButton.Text = "Invite";
if (add.ShowDialog(this) == DialogResult.OK)
foreach (ulong id in add.People)
Chat.SendInviteRequest(Custom, id);
}
public void MessageFlash()
{
if (External != null && !WindowActivated)
FlashMe = true;
}
void External_Deactivate(object sender, EventArgs e)
{
WindowActivated = false;
}
void External_Activated(object sender, EventArgs e)
{
WindowActivated = true;
FlashMe = false;
}
private void FlashTimer_Tick(object sender, EventArgs e)
{
if (External != null && !WindowActivated && FlashMe)
Win32.FlashWindow(External.Handle, true);
}
}
class RoomItem : ToolStripMenuItem
{
public ChatRoom Room;
public RoomItem(ChatService chat, ChatRoom room, EventHandler onClick)
: base(room.Title, null, onClick)
{
Room = room;
if (!room.Active)
ForeColor = Color.DimGray;
else
Text += " - " + room.GetActiveMembers(chat).ToString();
}
}
}
| |
namespace XenAdmin.SettingsPanels
{
partial class CPUMemoryEditPage
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(CPUMemoryEditPage));
this.lblSliderHighest = new System.Windows.Forms.Label();
this.lblSliderNormal = new System.Windows.Forms.Label();
this.lblSliderLowest = new System.Windows.Forms.Label();
this.lblPriority = new System.Windows.Forms.Label();
this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
this.comboBoxInitialVCPUs = new System.Windows.Forms.ComboBox();
this.labelInitialVCPUs = new System.Windows.Forms.Label();
this.labelInvalidVCPUWarning = new System.Windows.Forms.Label();
this.comboBoxTopology = new XenAdmin.Controls.CPUTopologyComboBox();
this.labelTopology = new System.Windows.Forms.Label();
this.MemWarningLabel = new System.Windows.Forms.Label();
this.panel2 = new System.Windows.Forms.Panel();
this.lblMB = new System.Windows.Forms.Label();
this.nudMemory = new System.Windows.Forms.NumericUpDown();
this.panel1 = new System.Windows.Forms.Panel();
this.transparentTrackBar1 = new XenAdmin.Controls.TransparentTrackBar();
this.lblVCPUs = new System.Windows.Forms.Label();
this.lblVcpuWarning = new System.Windows.Forms.LinkLabel();
this.lblMemory = new System.Windows.Forms.Label();
this.VCPUWarningLabel = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.comboBoxVCPUs = new System.Windows.Forms.ComboBox();
this.tableLayoutPanel1.SuspendLayout();
this.panel2.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.nudMemory)).BeginInit();
this.panel1.SuspendLayout();
this.SuspendLayout();
//
// lblSliderHighest
//
resources.ApplyResources(this.lblSliderHighest, "lblSliderHighest");
this.lblSliderHighest.Name = "lblSliderHighest";
//
// lblSliderNormal
//
resources.ApplyResources(this.lblSliderNormal, "lblSliderNormal");
this.lblSliderNormal.Name = "lblSliderNormal";
//
// lblSliderLowest
//
resources.ApplyResources(this.lblSliderLowest, "lblSliderLowest");
this.lblSliderLowest.Name = "lblSliderLowest";
//
// lblPriority
//
resources.ApplyResources(this.lblPriority, "lblPriority");
this.tableLayoutPanel1.SetColumnSpan(this.lblPriority, 2);
this.lblPriority.Name = "lblPriority";
//
// tableLayoutPanel1
//
this.tableLayoutPanel1.BackColor = System.Drawing.Color.Transparent;
resources.ApplyResources(this.tableLayoutPanel1, "tableLayoutPanel1");
this.tableLayoutPanel1.Controls.Add(this.comboBoxInitialVCPUs, 1, 6);
this.tableLayoutPanel1.Controls.Add(this.labelInitialVCPUs, 0, 6);
this.tableLayoutPanel1.Controls.Add(this.labelInvalidVCPUWarning, 1, 5);
this.tableLayoutPanel1.Controls.Add(this.comboBoxTopology, 1, 4);
this.tableLayoutPanel1.Controls.Add(this.labelTopology, 0, 4);
this.tableLayoutPanel1.Controls.Add(this.MemWarningLabel, 2, 9);
this.tableLayoutPanel1.Controls.Add(this.panel2, 1, 9);
this.tableLayoutPanel1.Controls.Add(this.panel1, 0, 8);
this.tableLayoutPanel1.Controls.Add(this.lblPriority, 0, 7);
this.tableLayoutPanel1.Controls.Add(this.lblVCPUs, 0, 2);
this.tableLayoutPanel1.Controls.Add(this.lblVcpuWarning, 0, 1);
this.tableLayoutPanel1.Controls.Add(this.lblMemory, 0, 9);
this.tableLayoutPanel1.Controls.Add(this.VCPUWarningLabel, 2, 2);
this.tableLayoutPanel1.Controls.Add(this.label1, 0, 0);
this.tableLayoutPanel1.Controls.Add(this.comboBoxVCPUs, 1, 2);
this.tableLayoutPanel1.Name = "tableLayoutPanel1";
//
// comboBoxInitialVCPUs
//
this.comboBoxInitialVCPUs.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBoxInitialVCPUs.FormattingEnabled = true;
resources.ApplyResources(this.comboBoxInitialVCPUs, "comboBoxInitialVCPUs");
this.comboBoxInitialVCPUs.Name = "comboBoxInitialVCPUs";
//
// labelInitialVCPUs
//
resources.ApplyResources(this.labelInitialVCPUs, "labelInitialVCPUs");
this.labelInitialVCPUs.Name = "labelInitialVCPUs";
//
// labelInvalidVCPUWarning
//
resources.ApplyResources(this.labelInvalidVCPUWarning, "labelInvalidVCPUWarning");
this.tableLayoutPanel1.SetColumnSpan(this.labelInvalidVCPUWarning, 2);
this.labelInvalidVCPUWarning.ForeColor = System.Drawing.Color.Red;
this.labelInvalidVCPUWarning.Name = "labelInvalidVCPUWarning";
//
// comboBoxTopology
//
this.tableLayoutPanel1.SetColumnSpan(this.comboBoxTopology, 2);
this.comboBoxTopology.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
resources.ApplyResources(this.comboBoxTopology, "comboBoxTopology");
this.comboBoxTopology.FormattingEnabled = true;
this.comboBoxTopology.Name = "comboBoxTopology";
this.comboBoxTopology.SelectedIndexChanged += new System.EventHandler(this.comboBoxTopology_SelectedIndexChanged);
//
// labelTopology
//
resources.ApplyResources(this.labelTopology, "labelTopology");
this.labelTopology.Name = "labelTopology";
//
// MemWarningLabel
//
resources.ApplyResources(this.MemWarningLabel, "MemWarningLabel");
this.MemWarningLabel.ForeColor = System.Drawing.Color.Red;
this.MemWarningLabel.Name = "MemWarningLabel";
this.tableLayoutPanel1.SetRowSpan(this.MemWarningLabel, 2);
//
// panel2
//
resources.ApplyResources(this.panel2, "panel2");
this.panel2.Controls.Add(this.lblMB);
this.panel2.Controls.Add(this.nudMemory);
this.panel2.Name = "panel2";
//
// lblMB
//
resources.ApplyResources(this.lblMB, "lblMB");
this.lblMB.Name = "lblMB";
//
// nudMemory
//
resources.ApplyResources(this.nudMemory, "nudMemory");
this.nudMemory.Maximum = new decimal(new int[] {
1048576,
0,
0,
0});
this.nudMemory.Minimum = new decimal(new int[] {
64,
0,
0,
0});
this.nudMemory.Name = "nudMemory";
this.nudMemory.Value = new decimal(new int[] {
64,
0,
0,
0});
this.nudMemory.ValueChanged += new System.EventHandler(this.nudMemory_ValueChanged);
//
// panel1
//
resources.ApplyResources(this.panel1, "panel1");
this.tableLayoutPanel1.SetColumnSpan(this.panel1, 3);
this.panel1.Controls.Add(this.lblSliderHighest);
this.panel1.Controls.Add(this.lblSliderNormal);
this.panel1.Controls.Add(this.lblSliderLowest);
this.panel1.Controls.Add(this.transparentTrackBar1);
this.panel1.Name = "panel1";
//
// transparentTrackBar1
//
resources.ApplyResources(this.transparentTrackBar1, "transparentTrackBar1");
this.transparentTrackBar1.BackColor = System.Drawing.Color.Transparent;
this.transparentTrackBar1.Name = "transparentTrackBar1";
this.transparentTrackBar1.TabStop = false;
//
// lblVCPUs
//
resources.ApplyResources(this.lblVCPUs, "lblVCPUs");
this.lblVCPUs.Name = "lblVCPUs";
//
// lblVcpuWarning
//
resources.ApplyResources(this.lblVcpuWarning, "lblVcpuWarning");
this.tableLayoutPanel1.SetColumnSpan(this.lblVcpuWarning, 2);
this.lblVcpuWarning.LinkColor = System.Drawing.SystemColors.ActiveCaption;
this.lblVcpuWarning.Name = "lblVcpuWarning";
this.lblVcpuWarning.TabStop = true;
this.lblVcpuWarning.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.lblVcpuWarning_LinkClicked);
//
// lblMemory
//
resources.ApplyResources(this.lblMemory, "lblMemory");
this.lblMemory.Name = "lblMemory";
//
// VCPUWarningLabel
//
resources.ApplyResources(this.VCPUWarningLabel, "VCPUWarningLabel");
this.VCPUWarningLabel.ForeColor = System.Drawing.Color.Red;
this.VCPUWarningLabel.Name = "VCPUWarningLabel";
this.tableLayoutPanel1.SetRowSpan(this.VCPUWarningLabel, 2);
//
// label1
//
resources.ApplyResources(this.label1, "label1");
this.tableLayoutPanel1.SetColumnSpan(this.label1, 3);
this.label1.Name = "label1";
//
// comboBoxVCPUs
//
this.comboBoxVCPUs.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBoxVCPUs.FormattingEnabled = true;
resources.ApplyResources(this.comboBoxVCPUs, "comboBoxVCPUs");
this.comboBoxVCPUs.Name = "comboBoxVCPUs";
this.comboBoxVCPUs.SelectedIndexChanged += new System.EventHandler(this.comboBoxVCPUs_SelectedIndexChanged);
//
// CPUMemoryEditPage
//
resources.ApplyResources(this, "$this");
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
this.BackColor = System.Drawing.SystemColors.Control;
this.Controls.Add(this.tableLayoutPanel1);
this.DoubleBuffered = true;
this.ForeColor = System.Drawing.SystemColors.ControlText;
this.Name = "CPUMemoryEditPage";
this.tableLayoutPanel1.ResumeLayout(false);
this.tableLayoutPanel1.PerformLayout();
this.panel2.ResumeLayout(false);
this.panel2.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.nudMemory)).EndInit();
this.panel1.ResumeLayout(false);
this.panel1.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1;
public System.Windows.Forms.NumericUpDown nudMemory;
private System.Windows.Forms.Label lblMB;
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.Label lblSliderHighest;
private System.Windows.Forms.Label lblSliderNormal;
private System.Windows.Forms.Label lblSliderLowest;
private System.Windows.Forms.Label lblPriority;
private System.Windows.Forms.Label lblVCPUs;
private System.Windows.Forms.Label lblMemory;
private System.Windows.Forms.LinkLabel lblVcpuWarning;
private XenAdmin.Controls.TransparentTrackBar transparentTrackBar1;
private System.Windows.Forms.Panel panel2;
private System.Windows.Forms.Label VCPUWarningLabel;
private System.Windows.Forms.Label MemWarningLabel;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label labelTopology;
private XenAdmin.Controls.CPUTopologyComboBox comboBoxTopology;
private System.Windows.Forms.Label labelInvalidVCPUWarning;
private System.Windows.Forms.ComboBox comboBoxVCPUs;
private System.Windows.Forms.ComboBox comboBoxInitialVCPUs;
private System.Windows.Forms.Label labelInitialVCPUs;
}
}
| |
// Authors: Robert Scheller, Melissa Lucash
using Landis.Core;
using Landis.SpatialModeling;
using Edu.Wisc.Forest.Flel.Util;
using Landis.Library.Succession;
using Landis.Library.LeafBiomassCohorts;
using System.Collections.Generic;
using System;
namespace Landis.Extension.Succession.NetEcosystemCN
{
/// <summary>
/// The pools of dead biomass for the landscape's sites.
/// </summary>
public static class SiteVars
{
// Time of last succession simulation:
private static ISiteVar<int> timeOfLast;
// Live biomass:
private static ISiteVar<Landis.Library.AgeOnlyCohorts.ISiteCohorts> baseCohortsSiteVar;
private static ISiteVar<Landis.Library.BiomassCohorts.ISiteCohorts> biomassCohortsSiteVar;
// Dead biomass:
private static ISiteVar<Layer> surfaceDeadWood;
private static ISiteVar<Layer> soilDeadWood;
private static ISiteVar<Layer> surfaceStructural;
private static ISiteVar<Layer> surfaceMetabolic;
private static ISiteVar<Layer> soilStructural;
private static ISiteVar<Layer> soilMetabolic;
// Soil layers
private static ISiteVar<Layer> som1surface;
private static ISiteVar<Layer> som1soil;
private static ISiteVar<Layer> som2;
private static ISiteVar<Layer> som3;
// Similar to soil layers with respect to their pools:
private static ISiteVar<Layer> stream;
private static ISiteVar<Layer> sourceSink;
// Other variables:
private static ISiteVar<double> mineralN;
private static ISiteVar<double> resorbedN;
private static ISiteVar<double> waterMovement;
private static ISiteVar<double> availableWater;
private static ISiteVar<double> soilWaterContent;
private static ISiteVar<double> liquidSnowPack;
private static ISiteVar<double> decayFactor;
private static ISiteVar<double> soilTemperature;
private static ISiteVar<double> anaerobicEffect;
// Annual accumulators
private static ISiteVar<double> grossMineralization;
private static ISiteVar<double> ag_nppC;
private static ISiteVar<double> bg_nppC;
private static ISiteVar<double> litterfallC;
private static ISiteVar<double> cohortLeafN;
private static ISiteVar<double> cohortFRootN;
private static ISiteVar<double> cohortLeafC;
private static ISiteVar<double> cohortFRootC;
private static ISiteVar<double> cohortWoodN;
private static ISiteVar<double> cohortCRootN;
private static ISiteVar<double> cohortWoodC;
private static ISiteVar<double> cohortCRootC;
private static ISiteVar<double[]> monthlyAGNPPC;
private static ISiteVar<double[]> monthlyBGNPPC;
private static ISiteVar<double[]> monthlyNEE;
private static ISiteVar<double[]> monthlyStreamN;
public static ISiteVar<double> AnnualNEE;
public static ISiteVar<double> FireCEfflux;
public static ISiteVar<double> FireNEfflux;
public static ISiteVar<double> Nvol;
private static ISiteVar<double[]> monthlyResp;
private static ISiteVar<double> totalNuptake;
private static ISiteVar<double[]> monthlymineralN;
private static ISiteVar<double> frassC;
private static ISiteVar<double> lai;
private static ISiteVar<double> annualPPT_AET; //Annual water budget calculation. I'm coppying LAI implementation
private static ISiteVar<double> annualSoilMoisture; //Annual soil moisture calculation, defined as pet - aet
public static ISiteVar<double> TotalWoodBiomass;
public static ISiteVar<int> PrevYearMortality;
public static ISiteVar<byte> FireSeverity;
public static ISiteVar<double> WoodMortality;
public static ISiteVar<string> HarvestPrescriptionName;
public static ISiteVar<Dictionary<int, Dictionary<int, double>>> CohortResorbedNallocation;
//---------------------------------------------------------------------
/// <summary>
/// Initializes the module.
/// </summary>
public static void Initialize()
{
cohorts = PlugIn.ModelCore.Landscape.NewSiteVar<Library.LeafBiomassCohorts.SiteCohorts>();
biomassCohortsSiteVar = Landis.Library.Succession.CohortSiteVar<Landis.Library.BiomassCohorts.ISiteCohorts>.Wrap(cohorts);
baseCohortsSiteVar = Landis.Library.Succession.CohortSiteVar<Landis.Library.AgeOnlyCohorts.ISiteCohorts>.Wrap(cohorts);
timeOfLast = PlugIn.ModelCore.Landscape.NewSiteVar<int>();
// Dead biomass:
surfaceDeadWood = PlugIn.ModelCore.Landscape.NewSiteVar<Layer>();
soilDeadWood = PlugIn.ModelCore.Landscape.NewSiteVar<Layer>();
surfaceStructural = PlugIn.ModelCore.Landscape.NewSiteVar<Layer>();
surfaceMetabolic = PlugIn.ModelCore.Landscape.NewSiteVar<Layer>();
soilStructural = PlugIn.ModelCore.Landscape.NewSiteVar<Layer>();
soilMetabolic = PlugIn.ModelCore.Landscape.NewSiteVar<Layer>();
// Soil Layers
som1surface = PlugIn.ModelCore.Landscape.NewSiteVar<Layer>();
som1soil = PlugIn.ModelCore.Landscape.NewSiteVar<Layer>();
som2 = PlugIn.ModelCore.Landscape.NewSiteVar<Layer>();
som3 = PlugIn.ModelCore.Landscape.NewSiteVar<Layer>();
// Other Layers
stream = PlugIn.ModelCore.Landscape.NewSiteVar<Layer>();
sourceSink = PlugIn.ModelCore.Landscape.NewSiteVar<Layer>();
// Other variables
mineralN = PlugIn.ModelCore.Landscape.NewSiteVar<double>();
resorbedN = PlugIn.ModelCore.Landscape.NewSiteVar<double>();
waterMovement = PlugIn.ModelCore.Landscape.NewSiteVar<double>();
availableWater = PlugIn.ModelCore.Landscape.NewSiteVar<double>();
liquidSnowPack = PlugIn.ModelCore.Landscape.NewSiteVar<double>();
soilWaterContent = PlugIn.ModelCore.Landscape.NewSiteVar<double>();
decayFactor = PlugIn.ModelCore.Landscape.NewSiteVar<double>();
soilTemperature = PlugIn.ModelCore.Landscape.NewSiteVar<double>();
anaerobicEffect = PlugIn.ModelCore.Landscape.NewSiteVar<double>();
// Annual accumulators
grossMineralization = PlugIn.ModelCore.Landscape.NewSiteVar<double>();
ag_nppC = PlugIn.ModelCore.Landscape.NewSiteVar<double>();
bg_nppC = PlugIn.ModelCore.Landscape.NewSiteVar<double>();
litterfallC = PlugIn.ModelCore.Landscape.NewSiteVar<double>();
monthlyAGNPPC = PlugIn.ModelCore.Landscape.NewSiteVar<double[]>();
monthlyBGNPPC = PlugIn.ModelCore.Landscape.NewSiteVar<double[]>();
monthlyNEE = PlugIn.ModelCore.Landscape.NewSiteVar<double[]>();
monthlyStreamN = PlugIn.ModelCore.Landscape.NewSiteVar<double[]>();
AnnualNEE = PlugIn.ModelCore.Landscape.NewSiteVar<double>();
FireCEfflux = PlugIn.ModelCore.Landscape.NewSiteVar<double>();
FireNEfflux = PlugIn.ModelCore.Landscape.NewSiteVar<double>();
monthlyResp = PlugIn.ModelCore.Landscape.NewSiteVar<double[]>();
cohortLeafN = PlugIn.ModelCore.Landscape.NewSiteVar<double>();
cohortFRootN = PlugIn.ModelCore.Landscape.NewSiteVar<double>();
cohortLeafC = PlugIn.ModelCore.Landscape.NewSiteVar<double>();
cohortFRootC = PlugIn.ModelCore.Landscape.NewSiteVar<double>();
cohortWoodN = PlugIn.ModelCore.Landscape.NewSiteVar<double>();
cohortCRootN = PlugIn.ModelCore.Landscape.NewSiteVar<double>();
cohortWoodC = PlugIn.ModelCore.Landscape.NewSiteVar<double>();
cohortCRootC = PlugIn.ModelCore.Landscape.NewSiteVar<double>();
TotalWoodBiomass = PlugIn.ModelCore.Landscape.NewSiteVar<double>();
WoodMortality = PlugIn.ModelCore.Landscape.NewSiteVar<double>();
Nvol = PlugIn.ModelCore.Landscape.NewSiteVar<double>();
PrevYearMortality = PlugIn.ModelCore.Landscape.NewSiteVar<int>();
totalNuptake = PlugIn.ModelCore.Landscape.NewSiteVar<double>();
monthlymineralN = PlugIn.ModelCore.Landscape.NewSiteVar<double[]>();
frassC = PlugIn.ModelCore.Landscape.NewSiteVar<double>();
lai = PlugIn.ModelCore.Landscape.NewSiteVar<double>();
annualPPT_AET = PlugIn.ModelCore.Landscape.NewSiteVar<double>();
annualSoilMoisture = PlugIn.ModelCore.Landscape.NewSiteVar<double>();
HarvestPrescriptionName = PlugIn.ModelCore.GetSiteVar<string>("Harvest.PrescriptionName");
CohortResorbedNallocation = PlugIn.ModelCore.Landscape.NewSiteVar<Dictionary<int, Dictionary<int, double>>>();
//PlugIn.ModelCore.RegisterSiteVar(cohorts, "Succession.LeafBiomassCohorts");
PlugIn.ModelCore.RegisterSiteVar(baseCohortsSiteVar, "Succession.AgeCohorts");
PlugIn.ModelCore.RegisterSiteVar(biomassCohortsSiteVar, "Succession.BiomassCohorts");
foreach (ActiveSite site in PlugIn.ModelCore.Landscape)
{
// site cohorts are initialized by the PlugIn.InitializeSite method
surfaceDeadWood[site] = new Layer(LayerName.Wood, LayerType.Surface);
soilDeadWood[site] = new Layer(LayerName.CoarseRoot, LayerType.Soil);
surfaceStructural[site] = new Layer(LayerName.Structural, LayerType.Surface);
surfaceMetabolic[site] = new Layer(LayerName.Metabolic, LayerType.Surface);
soilStructural[site] = new Layer(LayerName.Structural, LayerType.Soil);
soilMetabolic[site] = new Layer(LayerName.Metabolic, LayerType.Soil);
som1surface[site] = new Layer(LayerName.SOM1, LayerType.Surface);
som1soil[site] = new Layer(LayerName.SOM1, LayerType.Soil);
som2[site] = new Layer(LayerName.SOM2, LayerType.Soil);
som3[site] = new Layer(LayerName.SOM3, LayerType.Soil);
stream[site] = new Layer(LayerName.Other, LayerType.Other);
sourceSink[site] = new Layer(LayerName.Other, LayerType.Other);
monthlyAGNPPC[site] = new double[12];
monthlyBGNPPC[site] = new double[12];
monthlyNEE[site] = new double[12];
monthlyStreamN[site] = new double[12];
monthlyResp[site] = new double[12];
//monthlymineralN[site] = new double[12];
CohortResorbedNallocation[site] = new Dictionary<int, Dictionary<int, double>>();
}
}
//---------------------------------------------------------------------
/// <summary>
/// Initializes for disturbances.
/// </summary>
public static void InitializeDisturbances()
{
FireSeverity = PlugIn.ModelCore.GetSiteVar<byte>("Fire.Severity");
HarvestPrescriptionName = PlugIn.ModelCore.GetSiteVar<string>("Harvest.PrescriptionName");
//if(FireSeverity == null)
// throw new System.ApplicationException("TEST Error: Fire Severity NOT Initialized.");
}
//---------------------------------------------------------------------
/// <summary>
/// Biomass cohorts at each site.
/// </summary>
private static ISiteVar<SiteCohorts> cohorts;
public static ISiteVar<SiteCohorts> Cohorts
{
get
{
return cohorts;
}
set
{
cohorts = value;
}
}
//---------------------------------------------------------------------
/// <summary>
/// Computes the actual biomass at a site. The biomass is the total
/// of all the site's cohorts except young ones. The total is limited
/// to being no more than the site's maximum biomass less the previous
/// year's mortality at the site.
/// </summary>
public static double ActualSiteBiomass(ActiveSite site)
{
IEcoregion ecoregion = PlugIn.ModelCore.Ecoregion[site];
ISiteCohorts siteCohorts = SiteVars.Cohorts[site];
if(siteCohorts == null)
return 0.0;
int youngBiomass;
int totalBiomass = Library.LeafBiomassCohorts.Cohorts.ComputeBiomass(siteCohorts, out youngBiomass);
double B_ACT = totalBiomass - youngBiomass;
int lastMortality = SiteVars.PrevYearMortality[site];
B_ACT = System.Math.Min(EcoregionData.B_MAX[ecoregion] - lastMortality, B_ACT);
return B_ACT;
}
//---------------------------------------------------------------------
public static void ResetAnnualValues(Site site)
{
// Reset these accumulators to zero:
SiteVars.CohortLeafN[site] = 0.0;
SiteVars.CohortFRootN[site] = 0.0;
SiteVars.CohortLeafC[site] = 0.0;
SiteVars.CohortFRootC[site] = 0.0;
SiteVars.CohortWoodN[site] = 0.0;
SiteVars.CohortCRootN[site] = 0.0;
SiteVars.CohortWoodC[site] = 0.0;
SiteVars.CohortCRootC[site] = 0.0;
SiteVars.GrossMineralization[site] = 0.0;
SiteVars.AGNPPcarbon[site] = 0.0;
SiteVars.BGNPPcarbon[site] = 0.0;
SiteVars.LitterfallC[site] = 0.0;
SiteVars.Stream[site] = new Layer(LayerName.Other, LayerType.Other);
SiteVars.SourceSink[site] = new Layer(LayerName.Other, LayerType.Other);
SiteVars.SurfaceDeadWood[site].NetMineralization = 0.0;
SiteVars.SurfaceStructural[site].NetMineralization = 0.0;
SiteVars.SurfaceMetabolic[site].NetMineralization = 0.0;
SiteVars.SoilDeadWood[site].NetMineralization = 0.0;
SiteVars.SoilStructural[site].NetMineralization = 0.0;
SiteVars.SoilMetabolic[site].NetMineralization = 0.0;
SiteVars.SOM1surface[site].NetMineralization = 0.0;
SiteVars.SOM1soil[site].NetMineralization = 0.0;
SiteVars.SOM2[site].NetMineralization = 0.0;
SiteVars.SOM3[site].NetMineralization = 0.0;
SiteVars.AnnualNEE[site] = 0.0;
SiteVars.Nvol[site] = 0.0;
SiteVars.AnnualNEE[site] = 0.0;
SiteVars.TotalNuptake[site] = 0.0;
SiteVars.ResorbedN[site] = 0.0;
SiteVars.FrassC[site] = 0.0;
SiteVars.LAI[site] = 0.0;
SiteVars.WoodMortality[site] = 0.0;
SiteVars.AnnualPPT_AET[site] = 0.0;
SiteVars.AnnualSoilMoisture[site] = 0.0;
//SiteVars.FireEfflux[site] = 0.0;
}
//---------------------------------------------------------------------
public static ISiteVar<int> TimeOfLast
{
get {
return timeOfLast;
}
}
//---------------------------------------------------------------------
/// <summary>
/// The intact dead woody pools for the landscape's sites.
/// </summary>
public static ISiteVar<Layer> SurfaceDeadWood
{
get {
return surfaceDeadWood;
}
}
//---------------------------------------------------------------------
/// <summary>
/// The DEAD coarse root pool for the landscape's sites.
/// </summary>
public static ISiteVar<Layer> SoilDeadWood
{
get {
return soilDeadWood;
}
}
//---------------------------------------------------------------------
/// <summary>
/// The dead surface pool for the landscape's sites.
/// </summary>
public static ISiteVar<Layer> SurfaceStructural
{
get {
return surfaceStructural;
}
}
//---------------------------------------------------------------------
/// <summary>
/// The dead surface pool for the landscape's sites.
/// </summary>
public static ISiteVar<Layer> SurfaceMetabolic
{
get {
return surfaceMetabolic;
}
}
//---------------------------------------------------------------------
/// <summary>
/// The fine root pool for the landscape's sites.
/// </summary>
public static ISiteVar<Layer> SoilStructural
{
get {
return soilStructural;
}
}
//---------------------------------------------------------------------
/// <summary>
/// The fine root pool for the landscape's sites.
/// </summary>
public static ISiteVar<Layer> SoilMetabolic
{
get {
return soilMetabolic;
}
}
//---------------------------------------------------------------------
/// <summary>
/// The soil organic matter (SOM1-Surface) for the landscape's sites.
/// </summary>
public static ISiteVar<Layer> SOM1surface
{
get {
return som1surface;
}
}
//---------------------------------------------------------------------
/// <summary>
/// The soil organic matter (SOM1-Soil) for the landscape's sites.
/// </summary>
public static ISiteVar<Layer> SOM1soil
{
get {
return som1soil;
}
}
//---------------------------------------------------------------------
/// <summary>
/// The soil organic matter (SOM2) for the landscape's sites.
/// </summary>
public static ISiteVar<Layer> SOM2
{
get {
return som2;
}
}
//---------------------------------------------------------------------
/// <summary>
/// The soil organic matter (SOM3) for the landscape's sites.
/// </summary>
public static ISiteVar<Layer> SOM3
{
get {
return som3;
}
}
//---------------------------------------------------------------------
/// <summary>
/// Leaching to a stream - using the soil layer object is a cheat
/// </summary>
public static ISiteVar<Layer> Stream
{
get {
return stream;
}
}
//---------------------------------------------------------------------
/// <summary>
/// Water loss
/// </summary>
public static ISiteVar<double> WaterMovement
{
get {
return waterMovement;
}
set {
waterMovement = value;
}
}
//---------------------------------------------------------------------
/// <summary>
/// Water loss
/// </summary>
public static ISiteVar<double> AvailableWater
{
get {
return availableWater;
}
set {
availableWater = value;
}
}
//---------------------------------------------------------------------
/// <summary>
/// Water loss
/// </summary>
public static ISiteVar<double> SoilWaterContent
{
get {
return soilWaterContent;
}
set {
soilWaterContent = value;
}
}
/// <summary>
/// Liquid Snowpack
/// </summary>
public static ISiteVar<double> LiquidSnowPack
{
get
{
return liquidSnowPack;
}
set
{
liquidSnowPack = value;
}
}
//---------------------------------------------------------------------
/// <summary>
/// Available mineral Nitrogen
/// </summary>
public static ISiteVar<double> MineralN
{
get {
return mineralN;
}
set {
mineralN = value;
}
}
//---------------------------------------------------------------------
/// <summary>
/// The amount of N resorbed before leaf fall
/// </summary>
public static ISiteVar<double> ResorbedN
{
get
{
return resorbedN;
}
set
{
resorbedN = value;
}
}
//---------------------------------------------------------------------
/// <summary>
/// A generic decay factor determined by soil water and soil temperature.
/// </summary>
public static ISiteVar<double> DecayFactor
{
get {
return decayFactor;
}
set {
decayFactor = value;
}
}
//---------------------------------------------------------------------
/// <summary>
/// Soil temperature (C)
/// </summary>
public static ISiteVar<double> SoilTemperature
{
get {
return soilTemperature;
}
set {
soilTemperature = value;
}
}
//---------------------------------------------------------------------
/// <summary>
/// A generic decay factor determined by soil water and soil temperature.
/// </summary>
public static ISiteVar<double> AnaerobicEffect
{
get {
return anaerobicEffect;
}
set {
anaerobicEffect = value;
}
}
//---------------------------------------------------------------------
/// <summary>
/// A summary of all Leaf Nitrogen in the Cohorts.
/// </summary>
public static ISiteVar<double> CohortLeafN
{
get {
return cohortLeafN;
}
set {
cohortLeafN = value;
}
}
//---------------------------------------------------------------------
//---------------------------------------------------------------------
/// <summary>
/// A summary of all Fine Root Nitrogen in the Cohorts.
/// </summary>
public static ISiteVar<double> CohortFRootN
{
get
{
return cohortFRootN;
}
set
{
cohortFRootN = value;
}
}
//---------------------------------------------------------------------
/// <summary>
/// A summary of all Carbon in the Leaves
/// </summary>
public static ISiteVar<double> CohortLeafC
{
get {
return cohortLeafC;
}
set {
cohortLeafC = value;
}
}
/// <summary>
/// A summary of all Carbon in the Fine Roots
/// </summary>
public static ISiteVar<double> CohortFRootC
{
get
{
return cohortFRootC;
}
set
{
cohortFRootC = value;
}
}
//---------------------------------------------------------------------
/// <summary>
/// A summary of all Aboveground Wood Nitrogen in the Cohorts.
/// </summary>
public static ISiteVar<double> CohortWoodN
{
get {
return cohortWoodN;
}
set {
cohortWoodN = value;
}
}
//---------------------------------------------------------------------
//---------------------------------------------------------------------
/// <summary>
/// A summary of all Coarse Root Nitrogen in the Cohorts.
/// </summary>
public static ISiteVar<double> CohortCRootN
{
get
{
return cohortCRootN;
}
set
{
cohortCRootN = value;
}
}
/// <summary>
/// A summary of all Aboveground Wood Carbon in the Cohorts.
/// </summary>
public static ISiteVar<double> CohortWoodC
{
get {
return cohortWoodC;
}
set {
cohortWoodC = value;
}
}
//---------------------------------------------------------------------
/// <summary>
/// A summary of all Carbon in the Coarse Roots
/// </summary>
public static ISiteVar<double> CohortCRootC
{
get
{
return cohortCRootC;
}
set
{
cohortCRootC = value;
}
}
//-------------------------
/// <summary>
/// A summary of Gross Mineraliztion.
/// </summary>
public static ISiteVar<double> GrossMineralization
{
get {
return grossMineralization;
}
set {
grossMineralization = value;
}
}
//---------------------------------------------------------------------
/// <summary>
/// A summary of Aboveground Net Primary Productivity (g C/m2)
/// </summary>
public static ISiteVar<double> AGNPPcarbon
{
get {
return ag_nppC;
}
}
//---------------------------------------------------------------------
/// <summary>
/// A summary of Belowground Net Primary Productivity (g C/m2)
/// </summary>
public static ISiteVar<double> BGNPPcarbon
{
get {
return bg_nppC;
}
}
//---------------------------------------------------------------------
/// <summary>
/// A summary of Litter fall (g C/m2).
/// </summary>
public static ISiteVar<double> LitterfallC
{
get {
return litterfallC;
}
}
//---------------------------------------------------------------------
/// <summary>
/// A summary of Aboveground Net Primary Productivity (g C/m2)
/// </summary>
public static ISiteVar<double[]> MonthlyAGNPPcarbon
{
get {
return monthlyAGNPPC;
}
set {
monthlyAGNPPC = value;
}
}
//---------------------------------------------------------------------
/// <summary>
/// A summary of Belowground Net Primary Productivity (g C/m2)
/// </summary>
public static ISiteVar<double[]> MonthlyBGNPPcarbon
{
get {
return monthlyBGNPPC;
}
set {
monthlyBGNPPC = value;
}
}
//---------------------------------------------------------------------
/// <summary>
/// A summary of heterotrophic respiration, i.e. CO2 loss from decomposition (g C/m2)
/// </summary>
public static ISiteVar<double[]> MonthlyResp
{
get {
return monthlyResp;
}
set {
monthlyResp = value;
}
}
//---------------------------------------------------------------------
/// <summary>
/// A summary of Net Ecosystem Exchange (g C/m2), from a flux tower's perspective,
/// whereby positive values indicate terrestrial C loss, negative values indicate C gain.
/// Replace SourceSink?
/// </summary>
public static ISiteVar<double[]> MonthlyNEE
{
get {
return monthlyNEE;
}
set {
monthlyNEE = value;
}
}
//---------------------------------------------------------------------
/// <summary>
/// A summary of N leaching
/// </summary>
public static ISiteVar<double[]> MonthlyStreamN
{
get
{
return monthlyStreamN;
}
set
{
monthlyStreamN = value;
}
}
//---------------------------------------------------------------------
/// <summary>
/// Water loss
/// </summary>
public static ISiteVar<Layer> SourceSink
{
get {
return sourceSink;
}
set {
sourceSink = value;
}
}
//---------------------------------------------------------------------
/// <summary>
/// A summary of N uptake (g N/m2)
/// </summary>
public static ISiteVar<double> TotalNuptake
{
get
{
return totalNuptake;
}
set
{
totalNuptake = value;
}
}
//---------------------------------------------------------------------
/// <summary>
/// A summary of frass deposition (g C/m2)
/// </summary>
public static ISiteVar<double> FrassC
{
get
{
return frassC;
}
set
{
frassC = value;
}
}
//---------------------------------------------------------------------
/// <summary>
/// A summary of LAI (m2/m2)
/// </summary>
public static ISiteVar<double> LAI
{
get
{
return lai;
}
set
{
lai = value;
}
}
//---------------------------------------------------------------------
/// <summary>
/// A summary of Annual Water Budget (ppt - AET)
/// </summary>
public static ISiteVar<double> AnnualPPT_AET
{
get
{
return annualPPT_AET;
}
set
{
annualPPT_AET = value;
}
}
//---------------------------------------------------------------------
/// <summary>
/// A summary of Soil Moisture (PET - AET)
/// </summary>
public static ISiteVar<double> AnnualSoilMoisture
{
get
{
return annualSoilMoisture;
}
set
{
annualSoilMoisture = value;
}
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
// <OWNER>[....]</OWNER>
//
//
// BigInt.cs
//
// 11/06/2002
//
namespace System.Security.Cryptography
{
using System.Security.Cryptography.X509Certificates;
using System.Security.Cryptography.Xml;
using System.Text;
//
// This is a pretty "crude" implementation of BigInt arithmetic operations.
// This class is used in particular to convert certificate serial numbers from
// hexadecimal representation to decimal format and vice versa.
//
// We are not very concerned about the perf characterestics of this implementation
// for now. We perform all operations up to 128 bytes (which is enough for the current
// purposes although this constant can be increased). Any overflow bytes are going to be lost.
//
// A BigInt is represented as a little endian byte array of size 128 bytes. All
// arithmetic operations are performed in base 0x100 (256). The algorithms used
// are simply the common primary school techniques for doing operations in base 10.
//
internal sealed class BigInt {
private byte[] m_elements;
private const int m_maxbytes = 128; // 128 bytes is the maximum we can handle.
// This means any overflow bits beyond 128 bytes
// will be lost when doing arithmetic operations.
private const int m_base = 0x100;
private int m_size = 0;
internal BigInt () {
m_elements = new byte[m_maxbytes];
}
internal BigInt(byte b) {
m_elements = new byte[m_maxbytes];
SetDigit(0, b);
}
//
// Gets or sets the size of a BigInt.
//
internal int Size {
get {
return m_size;
}
set {
if (value > m_maxbytes)
m_size = m_maxbytes;
if (value < 0)
m_size = 0;
m_size = value;
}
}
//
// Gets the digit at the specified index.
//
internal byte GetDigit (int index) {
if (index < 0 || index >= m_size)
return 0;
return m_elements[index];
}
//
// Sets the digit at the specified index.
//
internal void SetDigit (int index, byte digit) {
if (index >= 0 && index < m_maxbytes) {
m_elements[index] = digit;
if (index >= m_size && digit != 0)
m_size = (index + 1);
if (index == m_size - 1 && digit == 0)
m_size--;
}
}
internal void SetDigit (int index, byte digit, ref int size) {
if (index >= 0 && index < m_maxbytes) {
m_elements[index] = digit;
if (index >= size && digit != 0)
size = (index + 1);
if (index == size - 1 && digit == 0)
size = (size - 1);
}
}
//
// overloaded operators.
//
public static bool operator < (BigInt value1, BigInt value2) {
if (value1 == null)
return true;
else if (value2 == null)
return false;
int Len1 = value1.Size;
int Len2 = value2.Size;
if (Len1 != Len2)
return (Len1 < Len2);
while (Len1-- > 0) {
if (value1.m_elements[Len1] != value2.m_elements[Len1])
return (value1.m_elements[Len1] < value2.m_elements[Len1]);
}
return false;
}
public static bool operator > (BigInt value1, BigInt value2) {
if (value1 == null)
return false;
else if (value2 == null)
return true;
int Len1 = value1.Size;
int Len2 = value2.Size;
if (Len1 != Len2)
return (Len1 > Len2);
while (Len1-- > 0) {
if (value1.m_elements[Len1] != value2.m_elements[Len1])
return (value1.m_elements[Len1] > value2.m_elements[Len1]);
}
return false;
}
public static bool operator == (BigInt value1, BigInt value2) {
if ((Object) value1 == null)
return ((Object) value2 == null);
else if ((Object) value2 == null)
return ((Object) value1 == null);
int Len1 = value1.Size;
int Len2 = value2.Size;
if (Len1 != Len2)
return false;
for (int index = 0; index < Len1; index++) {
if (value1.m_elements[index] != value2.m_elements[index])
return false;
}
return true;
}
public static bool operator != (BigInt value1, BigInt value2) {
return !(value1 == value2);
}
public override bool Equals (Object obj) {
if (obj is BigInt) {
return (this == (BigInt) obj);
}
return false;
}
public override int GetHashCode () {
int hash = 0;
for (int index = 0; index < m_size; index++) {
hash += GetDigit(index);
}
return hash;
}
//
// Adds a and b and outputs the result in c.
//
internal static void Add (BigInt a, byte b, ref BigInt c) {
byte carry = b;
int sum = 0;
int size = a.Size;
int newSize = 0;
for (int index = 0; index < size; index++) {
sum = a.GetDigit(index) + carry;
c.SetDigit(index, (byte) (sum & 0xFF), ref newSize);
carry = (byte) ((sum >> 8) & 0xFF);
}
if (carry != 0)
c.SetDigit(a.Size, carry, ref newSize);
c.Size = newSize;
}
//
// Negates a BigInt value. Each byte is complemented, then we add 1 to it.
//
internal static void Negate (ref BigInt a) {
int newSize = 0;
for (int index = 0; index < m_maxbytes; index++) {
a.SetDigit(index, (byte) (~a.GetDigit(index) & 0xFF), ref newSize);
}
for (int index = 0; index < m_maxbytes; index++) {
a.SetDigit(index, (byte) (a.GetDigit(index) + 1), ref newSize);
if ((a.GetDigit(index) & 0xFF) != 0) break;
a.SetDigit(index, (byte) (a.GetDigit(index) & 0xFF), ref newSize);
}
a.Size = newSize;
}
//
// Subtracts b from a and outputs the result in c.
//
internal static void Subtract (BigInt a, BigInt b, ref BigInt c) {
byte borrow = 0;
int diff = 0;
if (a < b) {
Subtract(b, a, ref c);
Negate(ref c);
return;
}
int index = 0;
int size = a.Size;
int newSize = 0;
for (index = 0; index < size; index++) {
diff = a.GetDigit(index) - b.GetDigit(index) - borrow;
borrow = 0;
if (diff < 0) {
diff += m_base;
borrow = 1;
}
c.SetDigit(index, (byte) (diff & 0xFF), ref newSize);
}
c.Size = newSize;
}
//
// multiplies a BigInt by an integer.
//
private void Multiply (int b) {
if (b == 0) {
Clear();
return;
}
int carry = 0, product = 0;
int size = this.Size;
int newSize = 0;
for (int index = 0; index < size; index++) {
product = b * GetDigit(index) + carry;
carry = product / m_base;
SetDigit(index, (byte) (product % m_base), ref newSize);
}
if (carry != 0) {
byte[] bytes = BitConverter.GetBytes(carry);
for (int index = 0; index < bytes.Length; index++) {
SetDigit(size + index, bytes[index], ref newSize);
}
}
this.Size = newSize;
}
private static void Multiply (BigInt a, int b, ref BigInt c) {
if (b == 0) {
c.Clear();
return;
}
int carry = 0, product = 0;
int size = a.Size;
int newSize = 0;
for (int index = 0; index < size; index++) {
product = b * a.GetDigit(index) + carry;
carry = product / m_base;
c.SetDigit(index, (byte) (product % m_base), ref newSize);
}
if (carry != 0) {
byte[] bytes = BitConverter.GetBytes(carry);
for (int index = 0; index < bytes.Length; index++) {
c.SetDigit(size + index, bytes[index], ref newSize);
}
}
c.Size = newSize;
}
//
// Divides a BigInt by a single byte.
//
private void Divide (int b) {
int carry = 0, quotient = 0;
int bLen = this.Size;
int newSize = 0;
while (bLen-- > 0) {
quotient = m_base * carry + GetDigit(bLen);
carry = quotient % b;
SetDigit(bLen, (byte) (quotient / b), ref newSize);
}
this.Size = newSize;
}
//
// Integer division of one BigInt by another.
//
internal static void Divide (BigInt numerator, BigInt denominator, ref BigInt quotient, ref BigInt remainder) {
// Avoid extra computations in special cases.
if (numerator < denominator) {
quotient.Clear();
remainder.CopyFrom(numerator);
return;
}
if (numerator == denominator) {
quotient.Clear(); quotient.SetDigit(0, 1);
remainder.Clear();
return;
}
BigInt dividend = new BigInt();
dividend.CopyFrom(numerator);
BigInt divisor = new BigInt();
divisor.CopyFrom(denominator);
uint zeroCount = 0;
// We pad the divisor with zeros until its size equals that of the dividend.
while (divisor.Size < dividend.Size) {
divisor.Multiply(m_base);
zeroCount++;
}
if (divisor > dividend) {
divisor.Divide(m_base);
zeroCount--;
}
// Use school division techniques, make a guess for how many times
// divisor goes into dividend, making adjustment if necessary.
int a = 0;
int b = 0;
int c = 0;
BigInt hold = new BigInt();
quotient.Clear();
for (int index = 0; index <= zeroCount; index++) {
a = dividend.Size == divisor.Size ? dividend.GetDigit(dividend.Size - 1) :
m_base * dividend.GetDigit(dividend.Size - 1) + dividend.GetDigit(dividend.Size - 2);
b = divisor.GetDigit(divisor.Size - 1);
c = a / b;
if (c >= m_base)
c = 0xFF;
Multiply(divisor, c, ref hold);
while (hold > dividend) {
c--;
Multiply(divisor, c, ref hold);
}
quotient.Multiply(m_base);
Add(quotient, (byte) c, ref quotient);
Subtract(dividend, hold, ref dividend);
divisor.Divide(m_base);
}
remainder.CopyFrom(dividend);
}
//
// copies a BigInt value.
//
internal void CopyFrom (BigInt a) {
Array.Copy(a.m_elements, m_elements, m_maxbytes);
m_size = a.m_size;
}
//
// This method returns true if the BigInt is equal to 0, false otherwise.
//
internal bool IsZero () {
for (int index = 0; index < m_size; index++) {
if (m_elements[index] != 0)
return false;
}
return true;
}
//
// returns the array in machine format, i.e. little endian format (as an integer).
//
internal byte[] ToByteArray() {
byte[] result = new byte[this.Size];
Array.Copy(m_elements, result, this.Size);
return result;
}
//
// zeroizes the content of the internal array.
//
internal void Clear () {
m_size = 0;
}
//
// Imports a hexadecimal string into a BigInt bit representation.
//
internal void FromHexadecimal (string hexNum) {
byte[] hex = X509Utils.DecodeHexString(hexNum);
Array.Reverse(hex);
int size = Utils.GetHexArraySize(hex);
Array.Copy(hex, m_elements, size);
this.Size = size;
}
//
// Imports a decimal string into a BigInt bit representation.
//
internal void FromDecimal (string decNum) {
BigInt c = new BigInt();
BigInt tmp = new BigInt();
int length = decNum.Length;
for (int index = 0; index < length; index++) {
// just ignore invalid characters. No need to raise an exception.
if (decNum[index] > '9' || decNum[index] < '0')
continue;
Multiply(c, 10, ref tmp);
Add(tmp, (byte) (decNum[index] - '0'), ref c);
}
CopyFrom(c);
}
//
// Exports the BigInt representation as a decimal string.
//
private static readonly char[] decValues = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
internal string ToDecimal ()
{
if (IsZero())
return "0";
BigInt ten = new BigInt(0xA);
BigInt numerator = new BigInt();
BigInt quotient = new BigInt();
BigInt remainder = new BigInt();
numerator.CopyFrom(this);
// Each hex digit can account for log(16) = 1.21 decimal digits. Times two hex digits in a byte
// and m_size bytes used in this BigInt, yields the maximum number of characters for the decimal
// representation of the BigInt.
char[] dec = new char[(int)Math.Ceiling(m_size * 2 * 1.21)];
int index = 0;
do
{
Divide(numerator, ten, ref quotient, ref remainder);
dec[index++] = decValues[remainder.IsZero() ? 0 : (int)remainder.m_elements[0]];
numerator.CopyFrom(quotient);
} while (quotient.IsZero() == false);
Array.Reverse(dec, 0, index);
return new String(dec, 0, index);
}
}
}
| |
// 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 Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public partial class IOperationTests : SemanticModelTestBase
{
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void AddEventHandler()
{
string source = @"
using System;
class Test
{
public event EventHandler MyEvent;
}
class C
{
void Handler(object sender, EventArgs e)
{
}
void M()
{
var t = new Test();
/*<bind>*/t.MyEvent += Handler/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IEventAssignmentOperation (EventAdd) (OperationKind.EventAssignment, Type: System.Void) (Syntax: 't.MyEvent += Handler')
Event Reference:
IEventReferenceOperation: event System.EventHandler Test.MyEvent (OperationKind.EventReference, Type: System.EventHandler) (Syntax: 't.MyEvent')
Instance Receiver:
ILocalReferenceOperation: t (OperationKind.LocalReference, Type: Test) (Syntax: 't')
Handler:
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.EventHandler, IsImplicit) (Syntax: 'Handler')
Target:
IMethodReferenceOperation: void C.Handler(System.Object sender, System.EventArgs e) (OperationKind.MethodReference, Type: null) (Syntax: 'Handler')
Instance Receiver:
IInstanceReferenceOperation (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'Handler')
";
var expectedDiagnostics = new[] {
// file.cs(6,31): warning CS0067: The event 'Test.MyEvent' is never used
// public event EventHandler MyEvent;
Diagnostic(ErrorCode.WRN_UnreferencedEvent, "MyEvent").WithArguments("Test.MyEvent").WithLocation(6, 31)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void AddEventHandler_JustHandlerReturnsMethodReference()
{
string source = @"
using System;
class Test
{
public event EventHandler MyEvent;
}
class C
{
void Handler(object sender, EventArgs e)
{
}
void M()
{
var t = new Test();
t.MyEvent += /*<bind>*/Handler/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IMethodReferenceOperation: void C.Handler(System.Object sender, System.EventArgs e) (OperationKind.MethodReference, Type: null) (Syntax: 'Handler')
Instance Receiver:
IInstanceReferenceOperation (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'Handler')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0067: The event 'Test.MyEvent' is never used
// public event EventHandler MyEvent;
Diagnostic(ErrorCode.WRN_UnreferencedEvent, "MyEvent").WithArguments("Test.MyEvent").WithLocation(6, 31)
};
VerifyOperationTreeAndDiagnosticsForTest<IdentifierNameSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void RemoveEventHandler()
{
string source = @"
using System;
class Test
{
public event EventHandler MyEvent;
}
class C
{
void M()
{
var t = new Test();
/*<bind>*/t.MyEvent -= null/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IEventAssignmentOperation (EventRemove) (OperationKind.EventAssignment, Type: System.Void) (Syntax: 't.MyEvent -= null')
Event Reference:
IEventReferenceOperation: event System.EventHandler Test.MyEvent (OperationKind.EventReference, Type: System.EventHandler) (Syntax: 't.MyEvent')
Instance Receiver:
ILocalReferenceOperation: t (OperationKind.LocalReference, Type: Test) (Syntax: 't')
Handler:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.EventHandler, Constant: null, IsImplicit) (Syntax: 'null')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
";
var expectedDiagnostics = new[] {
// file.cs(6,31): warning CS0067: The event 'Test.MyEvent' is never used
// public event EventHandler MyEvent;
Diagnostic(ErrorCode.WRN_UnreferencedEvent, "MyEvent").WithArguments("Test.MyEvent").WithLocation(6, 31)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void AddEventHandler_StaticEvent()
{
string source = @"
using System;
class Test
{
public static event EventHandler MyEvent;
}
class C
{
void Handler(object sender, EventArgs e)
{
}
void M()
{
/*<bind>*/Test.MyEvent += Handler/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IEventAssignmentOperation (EventAdd) (OperationKind.EventAssignment, Type: System.Void) (Syntax: 'Test.MyEvent += Handler')
Event Reference:
IEventReferenceOperation: event System.EventHandler Test.MyEvent (Static) (OperationKind.EventReference, Type: System.EventHandler) (Syntax: 'Test.MyEvent')
Instance Receiver:
null
Handler:
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.EventHandler, IsImplicit) (Syntax: 'Handler')
Target:
IMethodReferenceOperation: void C.Handler(System.Object sender, System.EventArgs e) (OperationKind.MethodReference, Type: null) (Syntax: 'Handler')
Instance Receiver:
IInstanceReferenceOperation (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'Handler')
";
var expectedDiagnostics = new[] {
// file.cs(6,38): warning CS0067: The event 'Test.MyEvent' is never used
// public static event EventHandler MyEvent;
Diagnostic(ErrorCode.WRN_UnreferencedEvent, "MyEvent").WithArguments("Test.MyEvent").WithLocation(6, 38)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void RemoveEventHandler_StaticEvent()
{
string source = @"
using System;
class Test
{
public static event EventHandler MyEvent;
}
class C
{
void Handler(object sender, EventArgs e)
{
}
void M()
{
/*<bind>*/Test.MyEvent -= Handler/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IEventAssignmentOperation (EventRemove) (OperationKind.EventAssignment, Type: System.Void) (Syntax: 'Test.MyEvent -= Handler')
Event Reference:
IEventReferenceOperation: event System.EventHandler Test.MyEvent (Static) (OperationKind.EventReference, Type: System.EventHandler) (Syntax: 'Test.MyEvent')
Instance Receiver:
null
Handler:
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.EventHandler, IsImplicit) (Syntax: 'Handler')
Target:
IMethodReferenceOperation: void C.Handler(System.Object sender, System.EventArgs e) (OperationKind.MethodReference, Type: null) (Syntax: 'Handler')
Instance Receiver:
IInstanceReferenceOperation (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'Handler')
";
var expectedDiagnostics = new[] {
// file.cs(6,38): warning CS0067: The event 'Test.MyEvent' is never used
// public static event EventHandler MyEvent;
Diagnostic(ErrorCode.WRN_UnreferencedEvent, "MyEvent").WithArguments("Test.MyEvent").WithLocation(6, 38)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void AddEventHandler_DelegateTypeMismatch()
{
string source = @"
using System;
class Test
{
public event EventHandler MyEvent;
}
class C
{
void Handler(object sender)
{
}
void M()
{
var t = new Test();
/*<bind>*/t.MyEvent += Handler/*<bind>*/;
}
}
";
string expectedOperationTree = @"
IEventAssignmentOperation (EventAdd) (OperationKind.EventAssignment, Type: System.Void, IsInvalid) (Syntax: 't.MyEvent += Handler')
Event Reference:
IEventReferenceOperation: event System.EventHandler Test.MyEvent (OperationKind.EventReference, Type: System.EventHandler, IsInvalid) (Syntax: 't.MyEvent')
Instance Receiver:
ILocalReferenceOperation: t (OperationKind.LocalReference, Type: Test, IsInvalid) (Syntax: 't')
Handler:
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.EventHandler, IsInvalid, IsImplicit) (Syntax: 'Handler')
Target:
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'Handler')
Children(1):
IInstanceReferenceOperation (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'Handler')
";
var expectedDiagnostics = new[] {
// file.cs(18,19): error CS0123: No overload for 'Handler' matches delegate 'EventHandler'
// /*<bind>*/t.MyEvent += Handler/*<bind>*/;
Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "t.MyEvent += Handler").WithArguments("Handler", "System.EventHandler").WithLocation(18, 19),
// file.cs(6,31): warning CS0067: The event 'Test.MyEvent' is never used
// public event EventHandler MyEvent;
Diagnostic(ErrorCode.WRN_UnreferencedEvent, "MyEvent").WithArguments("Test.MyEvent").WithLocation(6, 31)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void AddEventHandler_AssignToStaticEventOnInstance()
{
string source = @"
using System;
class Test
{
public static event EventHandler MyEvent;
}
class C
{
void Handler(object sender, EventArgs e)
{
}
void M()
{
var t = new Test();
/*<bind>*/t.MyEvent += Handler/*<bind>*/;
}
}
";
string expectedOperationTree = @"
IEventAssignmentOperation (EventAdd) (OperationKind.EventAssignment, Type: System.Void, IsInvalid) (Syntax: 't.MyEvent += Handler')
Event Reference:
IEventReferenceOperation: event System.EventHandler Test.MyEvent (Static) (OperationKind.EventReference, Type: System.EventHandler, IsInvalid) (Syntax: 't.MyEvent')
Instance Receiver:
ILocalReferenceOperation: t (OperationKind.LocalReference, Type: Test, IsInvalid) (Syntax: 't')
Handler:
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.EventHandler, IsImplicit) (Syntax: 'Handler')
Target:
IMethodReferenceOperation: void C.Handler(System.Object sender, System.EventArgs e) (OperationKind.MethodReference, Type: null) (Syntax: 'Handler')
Instance Receiver:
IInstanceReferenceOperation (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'Handler')
";
var expectedDiagnostics = new[] {
// file.cs(18,19): error CS0176: Member 'Test.MyEvent' cannot be accessed with an instance reference; qualify it with a type name instead
// /*<bind>*/t.MyEvent += Handler/*<bind>*/;
Diagnostic(ErrorCode.ERR_ObjectProhibited, "t.MyEvent").WithArguments("Test.MyEvent").WithLocation(18, 19),
// file.cs(6,38): warning CS0067: The event 'Test.MyEvent' is never used
// public static event EventHandler MyEvent;
Diagnostic(ErrorCode.WRN_UnreferencedEvent, "MyEvent").WithArguments("Test.MyEvent").WithLocation(6, 38)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
[WorkItem(8909, "https://github.com/dotnet/roslyn/issues/8909")]
public void AddEventHandler_AssignToNonStaticEventOnType()
{
string source = @"
using System;
class Test
{
public event EventHandler MyEvent;
}
class C
{
void Handler(object sender, EventArgs e)
{
}
void M()
{
/*<bind>*/Test.MyEvent += Handler/*<bind>*/;
}
}
";
string expectedOperationTree = @"
IEventAssignmentOperation (EventAdd) (OperationKind.EventAssignment, Type: System.Void, IsInvalid) (Syntax: 'Test.MyEvent += Handler')
Event Reference:
IEventReferenceOperation: event System.EventHandler Test.MyEvent (OperationKind.EventReference, Type: System.EventHandler, IsInvalid) (Syntax: 'Test.MyEvent')
Instance Receiver:
null
Handler:
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.EventHandler, IsImplicit) (Syntax: 'Handler')
Target:
IMethodReferenceOperation: void C.Handler(System.Object sender, System.EventArgs e) (OperationKind.MethodReference, Type: null) (Syntax: 'Handler')
Instance Receiver:
IInstanceReferenceOperation (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'Handler')
";
var expectedDiagnostics = new[] {
// file.cs(17,19): error CS0120: An object reference is required for the non-static field, method, or property 'Test.MyEvent'
// /*<bind>*/Test.MyEvent += Handler/*<bind>*/;
Diagnostic(ErrorCode.ERR_ObjectRequired, "Test.MyEvent").WithArguments("Test.MyEvent").WithLocation(17, 19),
// file.cs(6,31): warning CS0067: The event 'Test.MyEvent' is never used
// public event EventHandler MyEvent;
Diagnostic(ErrorCode.WRN_UnreferencedEvent, "MyEvent").WithArguments("Test.MyEvent").WithLocation(6, 31)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void AddEventHandler_AssignToEventWithoutExplicitReceiver()
{
string source = @"
using System;
class Test
{
public event EventHandler MyEvent;
void Handler(object sender, EventArgs e)
{
}
void M()
{
/*<bind>*/MyEvent += Handler/*<bind>*/;
}
}
";
string expectedOperationTree = @"
IEventAssignmentOperation (EventAdd) (OperationKind.EventAssignment, Type: System.Void) (Syntax: 'MyEvent += Handler')
Event Reference:
IEventReferenceOperation: event System.EventHandler Test.MyEvent (OperationKind.EventReference, Type: System.EventHandler) (Syntax: 'MyEvent')
Instance Receiver:
IInstanceReferenceOperation (OperationKind.InstanceReference, Type: Test, IsImplicit) (Syntax: 'MyEvent')
Handler:
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.EventHandler, IsImplicit) (Syntax: 'Handler')
Target:
IMethodReferenceOperation: void Test.Handler(System.Object sender, System.EventArgs e) (OperationKind.MethodReference, Type: null) (Syntax: 'Handler')
Instance Receiver:
IInstanceReferenceOperation (OperationKind.InstanceReference, Type: Test, IsImplicit) (Syntax: 'Handler')
";
var expectedDiagnostics = new[] {
// file.cs(6,31): warning CS0067: The event 'Test.MyEvent' is never used
// public event EventHandler MyEvent;
Diagnostic(ErrorCode.WRN_UnreferencedEvent, "MyEvent").WithArguments("Test.MyEvent").WithLocation(6, 31)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
}
}
| |
//---------------------------------------------------------------------------
//
// <copyright file="BlurEffect.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.Collections;
using MS.Internal.KnownBoxes;
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.Media3D;
using System.Windows.Media.Animation;
using System.Windows.Media.Composition;
using System.Windows.Media.Imaging;
using System.Windows.Markup;
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.Effects
{
sealed partial class BlurEffect : Effect
{
//------------------------------------------------------
//
// Public Methods
//
//------------------------------------------------------
#region Public Methods
/// <summary>
/// Shadows inherited Clone() with a strongly typed
/// version for convenience.
/// </summary>
public new BlurEffect Clone()
{
return (BlurEffect)base.Clone();
}
/// <summary>
/// Shadows inherited CloneCurrentValue() with a strongly typed
/// version for convenience.
/// </summary>
public new BlurEffect CloneCurrentValue()
{
return (BlurEffect)base.CloneCurrentValue();
}
#endregion Public Methods
//------------------------------------------------------
//
// Public Properties
//
//------------------------------------------------------
private static void RadiusPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
BlurEffect target = ((BlurEffect) d);
target.PropertyChanged(RadiusProperty);
}
private static void KernelTypePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
BlurEffect target = ((BlurEffect) d);
target.PropertyChanged(KernelTypeProperty);
}
private static void RenderingBiasPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
BlurEffect target = ((BlurEffect) d);
target.PropertyChanged(RenderingBiasProperty);
}
#region Public Properties
/// <summary>
/// Radius - double. Default value is 5.0.
/// </summary>
public double Radius
{
get
{
return (double) GetValue(RadiusProperty);
}
set
{
SetValueInternal(RadiusProperty, value);
}
}
/// <summary>
/// KernelType - KernelType. Default value is KernelType.Gaussian.
/// </summary>
public KernelType KernelType
{
get
{
return (KernelType) GetValue(KernelTypeProperty);
}
set
{
SetValueInternal(KernelTypeProperty, value);
}
}
/// <summary>
/// RenderingBias - RenderingBias. Default value is RenderingBias.Performance.
/// </summary>
public RenderingBias RenderingBias
{
get
{
return (RenderingBias) GetValue(RenderingBiasProperty);
}
set
{
SetValueInternal(RenderingBiasProperty, 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 BlurEffect();
}
#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);
// Obtain handles for animated properties
DUCE.ResourceHandle hRadiusAnimations = GetAnimationResourceHandle(RadiusProperty, channel);
// Pack & send command packet
DUCE.MILCMD_BLUREFFECT data;
unsafe
{
data.Type = MILCMD.MilCmdBlurEffect;
data.Handle = _duceResource.GetHandle(channel);
if (hRadiusAnimations.IsNull)
{
data.Radius = Radius;
}
data.hRadiusAnimations = hRadiusAnimations;
data.KernelType = KernelType;
data.RenderingBias = RenderingBias;
// Send packed command structure
channel.SendCommand(
(byte*)&data,
sizeof(DUCE.MILCMD_BLUREFFECT));
}
}
}
internal override DUCE.ResourceHandle AddRefOnChannelCore(DUCE.Channel channel)
{
if (_duceResource.CreateOrAddRefOnChannel(this, channel, System.Windows.Media.Composition.DUCE.ResourceType.TYPE_BLUREFFECT))
{
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))
{
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 BlurEffect.Radius property.
/// </summary>
public static readonly DependencyProperty RadiusProperty;
/// <summary>
/// The DependencyProperty for the BlurEffect.KernelType property.
/// </summary>
public static readonly DependencyProperty KernelTypeProperty;
/// <summary>
/// The DependencyProperty for the BlurEffect.RenderingBias property.
/// </summary>
public static readonly DependencyProperty RenderingBiasProperty;
#endregion Dependency Properties
//------------------------------------------------------
//
// Internal Fields
//
//------------------------------------------------------
#region Internal Fields
internal System.Windows.Media.Composition.DUCE.MultiChannelResource _duceResource = new System.Windows.Media.Composition.DUCE.MultiChannelResource();
internal const double c_Radius = 5.0;
internal const KernelType c_KernelType = KernelType.Gaussian;
internal const RenderingBias c_RenderingBias = RenderingBias.Performance;
#endregion Internal Fields
#region Constructors
//------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
static BlurEffect()
{
// 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(BlurEffect);
RadiusProperty =
RegisterProperty("Radius",
typeof(double),
typeofThis,
5.0,
new PropertyChangedCallback(RadiusPropertyChanged),
null,
/* isIndependentlyAnimated = */ true,
/* coerceValueCallback */ null);
KernelTypeProperty =
RegisterProperty("KernelType",
typeof(KernelType),
typeofThis,
KernelType.Gaussian,
new PropertyChangedCallback(KernelTypePropertyChanged),
new ValidateValueCallback(System.Windows.Media.Effects.ValidateEnums.IsKernelTypeValid),
/* isIndependentlyAnimated = */ false,
/* coerceValueCallback */ null);
RenderingBiasProperty =
RegisterProperty("RenderingBias",
typeof(RenderingBias),
typeofThis,
RenderingBias.Performance,
new PropertyChangedCallback(RenderingBiasPropertyChanged),
new ValidateValueCallback(System.Windows.Media.Effects.ValidateEnums.IsRenderingBiasValid),
/* isIndependentlyAnimated = */ false,
/* coerceValueCallback */ null);
}
#endregion Constructors
}
}
| |
/*
* 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.
*/
namespace Apache.Ignite.Core.Impl.Binary
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Cache.Affinity;
using Apache.Ignite.Core.Impl.Binary.IO;
using Apache.Ignite.Core.Impl.Binary.Metadata;
using Apache.Ignite.Core.Impl.Cache;
using Apache.Ignite.Core.Impl.Cache.Query.Continuous;
using Apache.Ignite.Core.Impl.Common;
using Apache.Ignite.Core.Impl.Compute;
using Apache.Ignite.Core.Impl.Compute.Closure;
using Apache.Ignite.Core.Impl.Datastream;
using Apache.Ignite.Core.Impl.Messaging;
/// <summary>
/// Marshaller implementation.
/// </summary>
internal class Marshaller
{
/** Binary configuration. */
private readonly BinaryConfiguration _cfg;
/** Type to descriptor map. */
private readonly IDictionary<Type, IBinaryTypeDescriptor> _typeToDesc =
new Dictionary<Type, IBinaryTypeDescriptor>();
/** Type name to descriptor map. */
private readonly IDictionary<string, IBinaryTypeDescriptor> _typeNameToDesc =
new Dictionary<string, IBinaryTypeDescriptor>();
/** ID to descriptor map. */
private readonly IDictionary<long, IBinaryTypeDescriptor> _idToDesc =
new Dictionary<long, IBinaryTypeDescriptor>();
/** Cached metadatas. */
private volatile IDictionary<int, BinaryTypeHolder> _metas =
new Dictionary<int, BinaryTypeHolder>();
/// <summary>
/// Constructor.
/// </summary>
/// <param name="cfg">Configurtaion.</param>
public Marshaller(BinaryConfiguration cfg)
{
// Validation.
if (cfg == null)
cfg = new BinaryConfiguration();
CompactFooter = cfg.CompactFooter;
if (cfg.TypeConfigurations == null)
cfg.TypeConfigurations = new List<BinaryTypeConfiguration>();
foreach (BinaryTypeConfiguration typeCfg in cfg.TypeConfigurations)
{
if (string.IsNullOrEmpty(typeCfg.TypeName))
throw new BinaryObjectException("Type name cannot be null or empty: " + typeCfg);
}
// Define system types. They use internal reflective stuff, so configuration doesn't affect them.
AddSystemTypes();
// 2. Define user types.
var typeResolver = new TypeResolver();
ICollection<BinaryTypeConfiguration> typeCfgs = cfg.TypeConfigurations;
if (typeCfgs != null)
foreach (BinaryTypeConfiguration typeCfg in typeCfgs)
AddUserType(cfg, typeCfg, typeResolver);
var typeNames = cfg.Types;
if (typeNames != null)
foreach (string typeName in typeNames)
AddUserType(cfg, new BinaryTypeConfiguration(typeName), typeResolver);
_cfg = cfg;
}
/// <summary>
/// Gets or sets the backing grid.
/// </summary>
public Ignite Ignite { get; set; }
/// <summary>
/// Gets the compact footer flag.
/// </summary>
public bool CompactFooter { get; set; }
/// <summary>
/// Marshal object.
/// </summary>
/// <param name="val">Value.</param>
/// <returns>Serialized data as byte array.</returns>
public byte[] Marshal<T>(T val)
{
using (var stream = new BinaryHeapStream(128))
{
Marshal(val, stream);
return stream.GetArrayCopy();
}
}
/// <summary>
/// Marshal object.
/// </summary>
/// <param name="val">Value.</param>
/// <param name="stream">Output stream.</param>
/// <returns>Collection of metadatas (if any).</returns>
private void Marshal<T>(T val, IBinaryStream stream)
{
BinaryWriter writer = StartMarshal(stream);
writer.Write(val);
FinishMarshal(writer);
}
/// <summary>
/// Start marshal session.
/// </summary>
/// <param name="stream">Stream.</param>
/// <returns>Writer.</returns>
public BinaryWriter StartMarshal(IBinaryStream stream)
{
return new BinaryWriter(this, stream);
}
/// <summary>
/// Finish marshal session.
/// </summary>
/// <param name="writer">Writer.</param>
/// <returns>Dictionary with metadata.</returns>
public void FinishMarshal(BinaryWriter writer)
{
var metas = writer.GetBinaryTypes();
var ignite = Ignite;
if (ignite != null && metas != null && metas.Count > 0)
ignite.PutBinaryTypes(metas);
}
/// <summary>
/// Unmarshal object.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="data">Data array.</param>
/// <param name="keepBinary">Whether to keep binarizable as binary.</param>
/// <returns>
/// Object.
/// </returns>
public T Unmarshal<T>(byte[] data, bool keepBinary)
{
using (var stream = new BinaryHeapStream(data))
{
return Unmarshal<T>(stream, keepBinary);
}
}
/// <summary>
/// Unmarshal object.
/// </summary>
/// <param name="data">Data array.</param>
/// <param name="mode">The mode.</param>
/// <returns>
/// Object.
/// </returns>
public T Unmarshal<T>(byte[] data, BinaryMode mode = BinaryMode.Deserialize)
{
using (var stream = new BinaryHeapStream(data))
{
return Unmarshal<T>(stream, mode);
}
}
/// <summary>
/// Unmarshal object.
/// </summary>
/// <param name="stream">Stream over underlying byte array with correct position.</param>
/// <param name="keepBinary">Whether to keep binary objects in binary form.</param>
/// <returns>
/// Object.
/// </returns>
public T Unmarshal<T>(IBinaryStream stream, bool keepBinary)
{
return Unmarshal<T>(stream, keepBinary ? BinaryMode.KeepBinary : BinaryMode.Deserialize, null);
}
/// <summary>
/// Unmarshal object.
/// </summary>
/// <param name="stream">Stream over underlying byte array with correct position.</param>
/// <param name="mode">The mode.</param>
/// <returns>
/// Object.
/// </returns>
public T Unmarshal<T>(IBinaryStream stream, BinaryMode mode = BinaryMode.Deserialize)
{
return Unmarshal<T>(stream, mode, null);
}
/// <summary>
/// Unmarshal object.
/// </summary>
/// <param name="stream">Stream over underlying byte array with correct position.</param>
/// <param name="mode">The mode.</param>
/// <param name="builder">Builder.</param>
/// <returns>
/// Object.
/// </returns>
public T Unmarshal<T>(IBinaryStream stream, BinaryMode mode, BinaryObjectBuilder builder)
{
return new BinaryReader(this, _idToDesc, stream, mode, builder).Deserialize<T>();
}
/// <summary>
/// Start unmarshal session.
/// </summary>
/// <param name="stream">Stream.</param>
/// <param name="keepBinary">Whether to keep binarizable as binary.</param>
/// <returns>
/// Reader.
/// </returns>
public BinaryReader StartUnmarshal(IBinaryStream stream, bool keepBinary)
{
return new BinaryReader(this, _idToDesc, stream,
keepBinary ? BinaryMode.KeepBinary : BinaryMode.Deserialize, null);
}
/// <summary>
/// Start unmarshal session.
/// </summary>
/// <param name="stream">Stream.</param>
/// <param name="mode">The mode.</param>
/// <returns>Reader.</returns>
public BinaryReader StartUnmarshal(IBinaryStream stream, BinaryMode mode = BinaryMode.Deserialize)
{
return new BinaryReader(this, _idToDesc, stream, mode, null);
}
/// <summary>
/// Gets metadata for the given type ID.
/// </summary>
/// <param name="typeId">Type ID.</param>
/// <returns>Metadata or null.</returns>
public IBinaryType GetBinaryType(int typeId)
{
if (Ignite != null)
{
IBinaryType meta = Ignite.GetBinaryType(typeId);
if (meta != null)
return meta;
}
return BinaryType.Empty;
}
/// <summary>
/// Puts the binary type metadata to Ignite.
/// </summary>
/// <param name="desc">Descriptor.</param>
public void PutBinaryType(IBinaryTypeDescriptor desc)
{
Debug.Assert(desc != null);
GetBinaryTypeHandler(desc); // ensure that handler exists
if (Ignite != null)
Ignite.PutBinaryTypes(new[] {new BinaryType(desc)});
}
/// <summary>
/// Gets binary type handler for the given type ID.
/// </summary>
/// <param name="desc">Type descriptor.</param>
/// <returns>Binary type handler.</returns>
public IBinaryTypeHandler GetBinaryTypeHandler(IBinaryTypeDescriptor desc)
{
BinaryTypeHolder holder;
if (!_metas.TryGetValue(desc.TypeId, out holder))
{
lock (this)
{
if (!_metas.TryGetValue(desc.TypeId, out holder))
{
IDictionary<int, BinaryTypeHolder> metas0 =
new Dictionary<int, BinaryTypeHolder>(_metas);
holder = new BinaryTypeHolder(desc.TypeId, desc.TypeName, desc.AffinityKeyFieldName, desc.IsEnum);
metas0[desc.TypeId] = holder;
_metas = metas0;
}
}
}
if (holder != null)
{
ICollection<int> ids = holder.GetFieldIds();
bool newType = ids.Count == 0 && !holder.Saved();
return new BinaryTypeHashsetHandler(ids, newType);
}
return null;
}
/// <summary>
/// Callback invoked when metadata has been sent to the server and acknowledged by it.
/// </summary>
/// <param name="newMetas">Binary types.</param>
public void OnBinaryTypesSent(IEnumerable<BinaryType> newMetas)
{
foreach (var meta in newMetas)
{
var mergeInfo = new Dictionary<int, Tuple<string, int>>(meta.GetFieldsMap().Count);
foreach (KeyValuePair<string, int> fieldMeta in meta.GetFieldsMap())
{
int fieldId = BinaryUtils.FieldId(meta.TypeId, fieldMeta.Key, null, null);
mergeInfo[fieldId] = new Tuple<string, int>(fieldMeta.Key, fieldMeta.Value);
}
_metas[meta.TypeId].Merge(mergeInfo);
}
}
/// <summary>
/// Gets descriptor for type.
/// </summary>
/// <param name="type">Type.</param>
/// <returns>Descriptor.</returns>
public IBinaryTypeDescriptor GetDescriptor(Type type)
{
IBinaryTypeDescriptor desc;
_typeToDesc.TryGetValue(type, out desc);
return desc;
}
/// <summary>
/// Gets descriptor for type name.
/// </summary>
/// <param name="typeName">Type name.</param>
/// <returns>Descriptor.</returns>
public IBinaryTypeDescriptor GetDescriptor(string typeName)
{
IBinaryTypeDescriptor desc;
return _typeNameToDesc.TryGetValue(typeName, out desc) ? desc :
new BinarySurrogateTypeDescriptor(_cfg, typeName);
}
/// <summary>
///
/// </summary>
/// <param name="userType"></param>
/// <param name="typeId"></param>
/// <returns></returns>
public IBinaryTypeDescriptor GetDescriptor(bool userType, int typeId)
{
IBinaryTypeDescriptor desc;
return _idToDesc.TryGetValue(BinaryUtils.TypeKey(userType, typeId), out desc) ? desc :
userType ? new BinarySurrogateTypeDescriptor(_cfg, typeId) : null;
}
/// <summary>
/// Add user type.
/// </summary>
/// <param name="cfg">Configuration.</param>
/// <param name="typeCfg">Type configuration.</param>
/// <param name="typeResolver">The type resolver.</param>
private void AddUserType(BinaryConfiguration cfg, BinaryTypeConfiguration typeCfg,
TypeResolver typeResolver)
{
// Get converter/mapper/serializer.
IBinaryNameMapper nameMapper = typeCfg.NameMapper ?? cfg.DefaultNameMapper;
IBinaryIdMapper idMapper = typeCfg.IdMapper ?? cfg.DefaultIdMapper;
bool keepDeserialized = typeCfg.KeepDeserialized ?? cfg.DefaultKeepDeserialized;
// Try resolving type.
Type type = typeResolver.ResolveType(typeCfg.TypeName);
if (type != null)
{
if (typeCfg.IsEnum != type.IsEnum)
throw new BinaryObjectException(
string.Format(
"Invalid IsEnum flag in binary type configuration. " +
"Configuration value: IsEnum={0}, actual type: IsEnum={1}",
typeCfg.IsEnum, type.IsEnum));
// Type is found.
var typeName = BinaryUtils.GetTypeName(type);
int typeId = BinaryUtils.TypeId(typeName, nameMapper, idMapper);
var affKeyFld = typeCfg.AffinityKeyFieldName ?? GetAffinityKeyFieldNameFromAttribute(type);
var serializer = GetSerializer(cfg, typeCfg, type, typeId, nameMapper, idMapper);
AddType(type, typeId, typeName, true, keepDeserialized, nameMapper, idMapper, serializer,
affKeyFld, type.IsEnum);
}
else
{
// Type is not found.
string typeName = BinaryUtils.SimpleTypeName(typeCfg.TypeName);
int typeId = BinaryUtils.TypeId(typeName, nameMapper, idMapper);
AddType(null, typeId, typeName, true, keepDeserialized, nameMapper, idMapper, null,
typeCfg.AffinityKeyFieldName, typeCfg.IsEnum);
}
}
/// <summary>
/// Gets the serializer.
/// </summary>
private static IBinarySerializerInternal GetSerializer(BinaryConfiguration cfg, BinaryTypeConfiguration typeCfg,
Type type, int typeId, IBinaryNameMapper nameMapper, IBinaryIdMapper idMapper)
{
var serializer = typeCfg.Serializer ?? cfg.DefaultSerializer;
if (serializer == null)
{
if (type.GetInterfaces().Contains(typeof(IBinarizable)))
return BinarizableSerializer.Instance;
serializer = new BinaryReflectiveSerializer();
}
var refSerializer = serializer as BinaryReflectiveSerializer;
return refSerializer != null
? refSerializer.Register(type, typeId, nameMapper, idMapper)
: new UserSerializerProxy(serializer);
}
/// <summary>
/// Gets the affinity key field name from attribute.
/// </summary>
private static string GetAffinityKeyFieldNameFromAttribute(Type type)
{
var res = type.GetMembers()
.Where(x => x.GetCustomAttributes(false).OfType<AffinityKeyMappedAttribute>().Any())
.Select(x => x.Name).ToArray();
if (res.Length > 1)
{
throw new BinaryObjectException(string.Format("Multiple '{0}' attributes found on type '{1}'. " +
"There can be only one affinity field.", typeof (AffinityKeyMappedAttribute).Name, type));
}
return res.SingleOrDefault();
}
/// <summary>
/// Add type.
/// </summary>
/// <param name="type">Type.</param>
/// <param name="typeId">Type ID.</param>
/// <param name="typeName">Type name.</param>
/// <param name="userType">User type flag.</param>
/// <param name="keepDeserialized">Whether to cache deserialized value in IBinaryObject</param>
/// <param name="nameMapper">Name mapper.</param>
/// <param name="idMapper">ID mapper.</param>
/// <param name="serializer">Serializer.</param>
/// <param name="affKeyFieldName">Affinity key field name.</param>
/// <param name="isEnum">Enum flag.</param>
private void AddType(Type type, int typeId, string typeName, bool userType,
bool keepDeserialized, IBinaryNameMapper nameMapper, IBinaryIdMapper idMapper,
IBinarySerializerInternal serializer, string affKeyFieldName, bool isEnum)
{
long typeKey = BinaryUtils.TypeKey(userType, typeId);
IBinaryTypeDescriptor conflictingType;
if (_idToDesc.TryGetValue(typeKey, out conflictingType))
{
var type1 = conflictingType.Type != null
? conflictingType.Type.AssemblyQualifiedName
: conflictingType.TypeName;
var type2 = type != null ? type.AssemblyQualifiedName : typeName;
throw new BinaryObjectException(string.Format("Conflicting type IDs [type1='{0}', " +
"type2='{1}', typeId={2}]", type1, type2, typeId));
}
if (userType && _typeNameToDesc.ContainsKey(typeName))
throw new BinaryObjectException("Conflicting type name: " + typeName);
var descriptor = new BinaryFullTypeDescriptor(type, typeId, typeName, userType, nameMapper, idMapper,
serializer, keepDeserialized, affKeyFieldName, isEnum);
if (type != null)
_typeToDesc[type] = descriptor;
if (userType)
_typeNameToDesc[typeName] = descriptor;
_idToDesc[typeKey] = descriptor;
}
/// <summary>
/// Adds a predefined system type.
/// </summary>
private void AddSystemType<T>(int typeId, Func<BinaryReader, T> ctor, string affKeyFldName = null,
IBinarySerializerInternal serializer = null)
where T : IBinaryWriteAware
{
var type = typeof(T);
serializer = serializer ?? new BinarySystemTypeSerializer<T>(ctor);
if (typeId == 0)
typeId = BinaryUtils.TypeId(type.Name, null, null);
AddType(type, typeId, BinaryUtils.GetTypeName(type), false, false, null, null, serializer, affKeyFldName,
false);
}
/// <summary>
/// Adds predefined system types.
/// </summary>
private void AddSystemTypes()
{
AddSystemType(BinaryUtils.TypeNativeJobHolder, w => new ComputeJobHolder(w));
AddSystemType(BinaryUtils.TypeComputeJobWrapper, w => new ComputeJobWrapper(w));
AddSystemType(BinaryUtils.TypeIgniteProxy, w => new IgniteProxy());
AddSystemType(BinaryUtils.TypeComputeOutFuncJob, w => new ComputeOutFuncJob(w));
AddSystemType(BinaryUtils.TypeComputeOutFuncWrapper, w => new ComputeOutFuncWrapper(w));
AddSystemType(BinaryUtils.TypeComputeFuncWrapper, w => new ComputeFuncWrapper(w));
AddSystemType(BinaryUtils.TypeComputeFuncJob, w => new ComputeFuncJob(w));
AddSystemType(BinaryUtils.TypeComputeActionJob, w => new ComputeActionJob(w));
AddSystemType(BinaryUtils.TypeContinuousQueryRemoteFilterHolder, w => new ContinuousQueryFilterHolder(w));
AddSystemType(BinaryUtils.TypeSerializableHolder, w => new SerializableObjectHolder(w),
serializer: new SerializableSerializer());
AddSystemType(BinaryUtils.TypeDateTimeHolder, w => new DateTimeHolder(w),
serializer: new DateTimeSerializer());
AddSystemType(BinaryUtils.TypeCacheEntryProcessorHolder, w => new CacheEntryProcessorHolder(w));
AddSystemType(BinaryUtils.TypeCacheEntryPredicateHolder, w => new CacheEntryFilterHolder(w));
AddSystemType(BinaryUtils.TypeMessageListenerHolder, w => new MessageListenerHolder(w));
AddSystemType(BinaryUtils.TypeStreamReceiverHolder, w => new StreamReceiverHolder(w));
AddSystemType(0, w => new AffinityKey(w), "affKey");
AddSystemType(BinaryUtils.TypePlatformJavaObjectFactoryProxy, w => new PlatformJavaObjectFactoryProxy());
AddSystemType(0, w => new ObjectInfoHolder(w));
}
}
}
| |
//
// Copyright (C) 2012-2014 DataStax Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
namespace Cassandra
{
/// <summary>
/// <para>Represents the options related to connection pooling.</para>
/// <para>
/// For each host selected by the load balancing policy, the driver keeps a core amount of
/// connections open at all times
/// (<see cref="PoolingOptions.GetCoreConnectionsPerHost(HostDistance)"/>).
/// If the use of those connections reaches a configurable threshold
/// (<see cref="PoolingOptions.GetMaxSimultaneousRequestsPerConnectionTreshold(HostDistance)"/>),
/// more connections are created up to the configurable maximum number of connections
/// (<see cref="PoolingOptions.GetMaxConnectionPerHost(HostDistance)"/>).
/// </para>
/// <para>
/// The driver uses connections in an asynchronous manner and multiple requests can be
/// submitted on the same connection at the same time without waiting for a response.
/// This means that the driver only needs to maintain a relatively small number of connections
/// to each Cassandra host. The <see cref="PoolingOptions"/> allows you to to control how many
/// connections are kept per host.
/// </para>
/// <para>
/// Each of these parameters can be separately set for <see cref="HostDistance.Local"/> and
/// <see cref="HostDistance.Remote"/> hosts. For <see cref="HostDistance.Ignored"/> hosts,
/// the default for all those settings is 0 and cannot be changed.
/// </para>
/// <para>
/// The default amount of connections depend on the Cassandra version of the Cluster, as newer
/// versions of Cassandra (2.1 and above) support a higher number of in-flight requests.
/// </para>
/// <para>For Cassandra 2.1 and above, the default amount of connections per host are:</para>
/// <list type="bullet">
/// <item>Local datacenter: 1 core connection per host, with 2 connections as maximum if the simultaneous requests threshold is reached.</item>
/// <item>Remote datacenter: 1 core connection per host (being 1 also max).</item>
/// </list>
/// <para>For older Cassandra versions (1.2 and 2.0), the default amount of connections per host are:</para>
/// <list type="bullet">
/// <item>Local datacenter: 2 core connection per host, with 8 connections as maximum if the simultaneous requests threshold is reached.</item>
/// <item>Remote datacenter: 1 core connection per host (being 2 the maximum).</item>
/// </list>
/// </summary>
public class PoolingOptions
{
//the defaults target small number concurrent requests (protocol 1 and 2) and multiple connections to a host
private const int DefaultMinRequests = 25;
private const int DefaultMaxRequests = 128;
private const int DefaultCorePoolLocal = 2;
private const int DefaultCorePoolRemote = 1;
private const int DefaultMaxPoolLocal = 8;
private const int DefaultMaxPoolRemote = 2;
/// <summary>
/// The default heartbeat interval in milliseconds: 30000.
/// </summary>
public const int DefaultHeartBeatInterval = 30000;
private int _coreConnectionsForLocal = DefaultCorePoolLocal;
private int _coreConnectionsForRemote = DefaultCorePoolRemote;
private int _maxConnectionsForLocal = DefaultMaxPoolLocal;
private int _maxConnectionsForRemote = DefaultMaxPoolRemote;
private int _maxSimultaneousRequestsForLocal = DefaultMaxRequests;
private int _maxSimultaneousRequestsForRemote = DefaultMaxRequests;
private int _minSimultaneousRequestsForLocal = DefaultMinRequests;
private int _minSimultaneousRequestsForRemote = DefaultMinRequests;
private int _heartBeatInterval = DefaultHeartBeatInterval;
/// <summary>
/// Number of simultaneous requests on a connection below which connections in
/// excess are reclaimed. <p> If an opened connection to an host at distance
/// <c>distance</c> handles less than this number of simultaneous requests
/// and there is more than <link>#GetCoreConnectionsPerHost</link> connections
/// open to this host, the connection is closed. </p><p> The default value for this
/// option is 25 for <c>Local</c> and <c>Remote</c> hosts.</p>
/// </summary>
/// <param name="distance"> the <c>HostDistance</c> for which to return this threshold.</param>
/// <returns>the configured threshold, or the default one if none have been set.</returns>
public int GetMinSimultaneousRequestsPerConnectionTreshold(HostDistance distance)
{
switch (distance)
{
case HostDistance.Local:
return _minSimultaneousRequestsForLocal;
case HostDistance.Remote:
return _minSimultaneousRequestsForRemote;
default:
return 0;
}
}
/// <summary>
/// Sets the number of simultaneous requests on a connection below which
/// connections in excess are reclaimed.
/// </summary>
/// <param name="distance"> the <see cref="HostDistance"/> for which to configure this
/// threshold. </param>
/// <param name="minSimultaneousRequests"> the value to set. </param>
///
/// <returns>this <c>PoolingOptions</c>. </returns>
public PoolingOptions SetMinSimultaneousRequestsPerConnectionTreshold(HostDistance distance, int minSimultaneousRequests)
{
switch (distance)
{
case HostDistance.Local:
_minSimultaneousRequestsForLocal = minSimultaneousRequests;
break;
case HostDistance.Remote:
_minSimultaneousRequestsForRemote = minSimultaneousRequests;
break;
default:
throw new ArgumentOutOfRangeException("Cannot set min streams per connection threshold for " + distance + " hosts");
}
return this;
}
/// <summary>
/// <para>
/// Number of simultaneous requests on all connections to an host after which more
/// connections are created.
/// </para>
/// <para>
/// If all the connections opened to an host at <see cref="HostDistance"/> connection are
/// handling more than this number of simultaneous requests and there is less than
/// <see cref="GetMaxConnectionPerHost"/> connections open to this host, a new connection
/// is open.
/// </para>
/// </summary>
/// <param name="distance"> the <see cref="HostDistance"/> for which to return this threshold.</param>
/// <returns>the configured threshold, or the default one if none have been set.</returns>
public int GetMaxSimultaneousRequestsPerConnectionTreshold(HostDistance distance)
{
switch (distance)
{
case HostDistance.Local:
return _maxSimultaneousRequestsForLocal;
case HostDistance.Remote:
return _maxSimultaneousRequestsForRemote;
default:
return 0;
}
}
/// <summary>
/// Sets number of simultaneous requests on all connections to an host after
/// which more connections are created.
/// </summary>
/// <param name="distance">The <see cref="HostDistance"/> for which to configure this
/// threshold. </param>
/// <param name="maxSimultaneousRequests"> the value to set. </param>
/// <returns>this <c>PoolingOptions</c>. </returns>
/// <throws name="IllegalArgumentException"> if <c>distance == HostDistance.Ignore</c>.</throws>
public PoolingOptions SetMaxSimultaneousRequestsPerConnectionTreshold(HostDistance distance, int maxSimultaneousRequests)
{
switch (distance)
{
case HostDistance.Local:
_maxSimultaneousRequestsForLocal = maxSimultaneousRequests;
break;
case HostDistance.Remote:
_maxSimultaneousRequestsForRemote = maxSimultaneousRequests;
break;
default:
throw new ArgumentOutOfRangeException("Cannot set max streams per connection threshold for " + distance + " hosts");
}
return this;
}
/// <summary>
/// <para>
/// The core number of connections per host.
/// </para>
/// <para>
/// For the provided <see cref="HostDistance"/>, this correspond to the number of
/// connections initially created and kept open to each host of that distance.
/// </para>
/// </summary>
/// <param name="distance">The <see cref="HostDistance"/> for which to return this threshold.</param>
/// <returns>the core number of connections per host at distance <see cref="HostDistance"/>.</returns>
public int GetCoreConnectionsPerHost(HostDistance distance)
{
switch (distance)
{
case HostDistance.Local:
return _coreConnectionsForLocal;
case HostDistance.Remote:
return _coreConnectionsForRemote;
default:
return 0;
}
}
/// <summary>
/// Sets the core number of connections per host.
/// </summary>
/// <param name="distance"> the <see cref="HostDistance"/> for which to set this threshold.</param>
/// <param name="coreConnections"> the value to set </param>
/// <returns>this <c>PoolingOptions</c>. </returns>
/// <throws name="IllegalArgumentException"> if <c>distance == HostDistance.Ignored</c>.</throws>
public PoolingOptions SetCoreConnectionsPerHost(HostDistance distance, int coreConnections)
{
switch (distance)
{
case HostDistance.Local:
_coreConnectionsForLocal = coreConnections;
break;
case HostDistance.Remote:
_coreConnectionsForRemote = coreConnections;
break;
default:
throw new ArgumentOutOfRangeException("Cannot set core connections per host for " + distance + " hosts");
}
return this;
}
/// <summary>
/// The maximum number of connections per host. <p> For the provided
/// <c>distance</c>, this correspond to the maximum number of connections
/// that can be created per host at that distance.</p>
/// </summary>
/// <param name="distance"> the <c>HostDistance</c> for which to return this threshold.
/// </param>
///
/// <returns>the maximum number of connections per host at distance
/// <c>distance</c>.</returns>
public int GetMaxConnectionPerHost(HostDistance distance)
{
switch (distance)
{
case HostDistance.Local:
return _maxConnectionsForLocal;
case HostDistance.Remote:
return _maxConnectionsForRemote;
default:
return 0;
}
}
/// <summary>
/// Sets the maximum number of connections per host.
/// </summary>
/// <param name="distance"> the <c>HostDistance</c> for which to set this threshold.
/// </param>
/// <param name="maxConnections"> the value to set </param>
///
/// <returns>this <c>PoolingOptions</c>. </returns>
public PoolingOptions SetMaxConnectionsPerHost(HostDistance distance, int maxConnections)
{
switch (distance)
{
case HostDistance.Local:
_maxConnectionsForLocal = maxConnections;
break;
case HostDistance.Remote:
_maxConnectionsForRemote = maxConnections;
break;
default:
throw new ArgumentOutOfRangeException("Cannot set max connections per host for " + distance + " hosts");
}
return this;
}
/// <summary>
/// Gets the amount of idle time in milliseconds that has to pass
/// before the driver issues a request on an active connection to avoid
/// idle time disconnections.
/// <remarks>
/// A value of <c>0</c> or <c>null</c> means that the heartbeat
/// functionality at connection level is disabled.
/// </remarks>
/// </summary>
public int? GetHeartBeatInterval()
{
return _heartBeatInterval;
}
/// <summary>
/// Sets the amount of idle time in milliseconds that has to pass
/// before the driver issues a request on an active connection to avoid
/// idle time disconnections.
/// <remarks>
/// When set to <c>0</c> the heartbeat functionality at connection
/// level is disabled.
/// </remarks>
/// </summary>
public PoolingOptions SetHeartBeatInterval(int value)
{
_heartBeatInterval = value;
return this;
}
/// <summary>
/// Gets the default protocol options by protocol version
/// </summary>
internal static PoolingOptions GetDefault(ProtocolVersion protocolVersion)
{
if (!protocolVersion.Uses2BytesStreamIds())
{
//New instance of pooling options with default values
return new PoolingOptions();
}
//New instance of pooling options with default values for high number of concurrent requests
return new PoolingOptions()
.SetCoreConnectionsPerHost(HostDistance.Local, 1)
.SetMaxConnectionsPerHost(HostDistance.Local, 2)
.SetCoreConnectionsPerHost(HostDistance.Remote, 1)
.SetMaxConnectionsPerHost(HostDistance.Remote, 1)
.SetMaxSimultaneousRequestsPerConnectionTreshold(HostDistance.Local, 1500)
.SetMaxSimultaneousRequestsPerConnectionTreshold(HostDistance.Remote, 1500);
}
}
}
| |
// 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.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.CSharp.UseAutoProperty;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.UseAutoProperty
{
public class UseAutoPropertyTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace)
=> (new UseAutoPropertyAnalyzer(), new UseAutoPropertyCodeFixProvider());
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestSingleGetterFromField()
{
await TestInRegularAndScriptAsync(
@"class Class
{
[|int i|];
int P
{
get
{
return i;
}
}
}",
@"class Class
{
int P { get; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestCSharp5_1()
{
await TestAsync(
@"class Class
{
[|int i|];
public int P
{
get
{
return i;
}
}
}",
@"class Class
{
public int P { get; private set; }
}",
CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp5));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestCSharp5_2()
{
await TestMissingAsync(
@"class Class
{
[|readonly int i|];
int P
{
get
{
return i;
}
}
}", new TestParameters(CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp5)));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestInitializer()
{
await TestInRegularAndScriptAsync(
@"class Class
{
[|int i = 1|];
int P
{
get
{
return i;
}
}
}",
@"class Class
{
int P { get; } = 1;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestInitializer_CSharp5()
{
await TestMissingAsync(
@"class Class
{
[|int i = 1|];
int P
{
get
{
return i;
}
}
}", new TestParameters(CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp5)));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestSingleGetterFromProperty()
{
await TestInRegularAndScriptAsync(
@"class Class
{
int i;
[|int P
{
get
{
return i;
}
}|]
}",
@"class Class
{
int P { get; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestSingleSetter()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
[|int i|];
int P
{
set
{
i = value;
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestGetterAndSetter()
{
await TestInRegularAndScriptAsync(
@"class Class
{
[|int i|];
int P
{
get
{
return i;
}
set
{
i = value;
}
}
}",
@"class Class
{
int P { get; set; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestSingleGetterWithThis()
{
await TestInRegularAndScriptAsync(
@"class Class
{
[|int i|];
int P
{
get
{
return this.i;
}
}
}",
@"class Class
{
int P { get; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestSingleSetterWithThis()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
[|int i|];
int P
{
set
{
this.i = value;
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestGetterAndSetterWithThis()
{
await TestInRegularAndScriptAsync(
@"class Class
{
[|int i|];
int P
{
get
{
return this.i;
}
set
{
this.i = value;
}
}
}",
@"class Class
{
int P { get; set; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestGetterWithMutipleStatements()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
[|int i|];
int P
{
get
{
;
return i;
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestSetterWithMutipleStatements()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
[|int i|];
int P
{
set
{
;
i = value;
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestSetterWithMultipleStatementsAndGetterWithSingleStatement()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
[|int i|];
int P
{
get
{
return i;
}
set
{
;
i = value;
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestGetterAndSetterUseDifferentFields()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
[|int i|];
int j;
int P
{
get
{
return i;
}
set
{
j = value;
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestFieldAndPropertyHaveDifferentStaticInstance()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
[|static int i|];
int P
{
get
{
return i;
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestFieldUseInRefArgument1()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
[|int i|];
int P
{
get
{
return i;
}
}
void M(ref int x)
{
M(ref i);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestFieldUseInRefArgument2()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
[|int i|];
int P
{
get
{
return i;
}
}
void M(ref int x)
{
M(ref this.i);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestFieldUseInOutArgument()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
[|int i|];
int P
{
get
{
return i;
}
}
void M(out x)
{
M(out i);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestNotWithVirtualProperty()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
[|int i|];
public virtual int P
{
get
{
return i;
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestNotWithConstField()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
[|const int i|];
int P
{
get
{
return i;
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestFieldWithMultipleDeclarators1()
{
await TestInRegularAndScriptAsync(
@"class Class
{
int [|i|], j, k;
int P
{
get
{
return i;
}
}
}",
@"class Class
{
int j, k;
int P { get; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestFieldWithMultipleDeclarators2()
{
await TestInRegularAndScriptAsync(
@"class Class
{
int i, [|j|], k;
int P
{
get
{
return j;
}
}
}",
@"class Class
{
int i, k;
int P { get; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestFieldWithMultipleDeclarators3()
{
await TestInRegularAndScriptAsync(
@"class Class
{
int i, j, [|k|];
int P
{
get
{
return k;
}
}
}",
@"class Class
{
int i, j;
int P { get; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestFieldAndPropertyInDifferentParts()
{
await TestInRegularAndScriptAsync(
@"partial class Class
{
[|int i|];
}
partial class Class
{
int P
{
get
{
return i;
}
}
}",
@"partial class Class
{
}
partial class Class
{
int P { get; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestNotWithFieldWithAttribute()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
[|[A]
int i|];
int P
{
get
{
return i;
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestUpdateReferences()
{
await TestInRegularAndScriptAsync(
@"class Class
{
[|int i|];
int P
{
get
{
return i;
}
}
public Class()
{
i = 1;
}
}",
@"class Class
{
int P { get; }
public Class()
{
P = 1;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestUpdateReferencesConflictResolution()
{
await TestInRegularAndScriptAsync(
@"class Class
{
[|int i|];
int P
{
get
{
return i;
}
}
public Class(int P)
{
i = 1;
}
}",
@"class Class
{
int P { get; }
public Class(int P)
{
this.P = 1;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestWriteInConstructor()
{
await TestInRegularAndScriptAsync(
@"class Class
{
[|int i|];
int P
{
get
{
return i;
}
}
public Class()
{
i = 1;
}
}",
@"class Class
{
int P { get; }
public Class()
{
P = 1;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestWriteInNotInConstructor1()
{
await TestInRegularAndScriptAsync(
@"class Class
{
[|int i|];
int P
{
get
{
return i;
}
}
public Foo()
{
i = 1;
}
}",
@"class Class
{
int P { get; set; }
public Foo()
{
P = 1;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestWriteInNotInConstructor2()
{
await TestInRegularAndScriptAsync(
@"class Class
{
[|int i|];
public int P
{
get
{
return i;
}
}
public Foo()
{
i = 1;
}
}",
@"class Class
{
public int P { get; private set; }
public Foo()
{
P = 1;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestAlreadyAutoPropertyWithGetterWithNoBody()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
public int [|P|] { get; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestAlreadyAutoPropertyWithGetterAndSetterWithNoBody()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
public int [|P|] { get; set; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestSingleLine1()
{
await TestInRegularAndScriptAsync(
@"class Class
{
[|int i|];
int P { get { return i; } }
}",
@"class Class
{
int P { get; }
}", ignoreTrivia: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestSingleLine2()
{
await TestInRegularAndScriptAsync(
@"class Class
{
[|int i|];
int P
{
get { return i; }
}
}",
@"class Class
{
int P { get; }
}", ignoreTrivia: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestSingleLine3()
{
await TestInRegularAndScriptAsync(
@"class Class
{
[|int i|];
int P
{
get { return i; }
set { i = value; }
}
}",
@"class Class
{
int P { get; set; }
}", ignoreTrivia: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task Tuple_SingleGetterFromField()
{
await TestInRegularAndScriptAsync(
@"class Class
{
[|(int, string) i|];
(int, string) P
{
get
{
return i;
}
}
}",
@"class Class
{
(int, string) P { get; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TupleWithNames_SingleGetterFromField()
{
await TestInRegularAndScriptAsync(
@"class Class
{
[|(int a, string b) i|];
(int a, string b) P
{
get
{
return i;
}
}
}",
@"class Class
{
(int a, string b) P { get; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TupleWithDifferentNames_SingleGetterFromField()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
[|(int a, string b) i|];
(int c, string d) P
{
get
{
return i;
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TupleWithOneName_SingleGetterFromField()
{
await TestInRegularAndScriptAsync(
@"class Class
{
[|(int a, string) i|];
(int a, string) P
{
get
{
return i;
}
}
}",
@"class Class
{
(int a, string) P { get; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task Tuple_Initializer()
{
await TestInRegularAndScriptAsync(
@"class Class
{
[|(int, string) i = (1, ""hello"")|];
(int, string) P
{
get
{
return i;
}
}
}",
@"class Class
{
(int, string) P { get; } = (1, ""hello"");
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task Tuple_GetterAndSetter()
{
await TestInRegularAndScriptAsync(
@"class Class
{
[|(int, string) i|];
(int, string) P
{
get
{
return i;
}
set
{
i = value;
}
}
}",
@"class Class
{
(int, string) P { get; set; }
}");
}
}
}
| |
#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.Xml;
using System.Collections;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Net;
using log4net.Appender;
using log4net.Util;
using log4net.Repository;
namespace log4net.Config
{
/// <summary>
/// Use this class to initialize the log4net environment using an Xml tree.
/// </summary>
/// <remarks>
/// <para>
/// Configures a <see cref="ILoggerRepository"/> using an Xml tree.
/// </para>
/// </remarks>
/// <author>Nicko Cadell</author>
/// <author>Gert Driesen</author>
public sealed class XmlConfigurator
{
#region Private Instance Constructors
/// <summary>
/// Private constructor
/// </summary>
private XmlConfigurator()
{
}
#endregion Protected Instance Constructors
#region Configure static methods
#if !NETCF
/// <summary>
/// Automatically configures the <see cref="ILoggerRepository"/> using settings
/// stored in the application's configuration file.
/// </summary>
/// <remarks>
/// <para>
/// Each application has a configuration file. This has the
/// same name as the application with '.config' appended.
/// This file is XML and calling this function prompts the
/// configurator to look in that file for a section called
/// <c>log4net</c> that contains the configuration data.
/// </para>
/// <para>
/// To use this method to configure log4net you must specify
/// the <see cref="Log4NetConfigurationSectionHandler"/> section
/// handler for the <c>log4net</c> configuration section. See the
/// <see cref="Log4NetConfigurationSectionHandler"/> for an example.
/// </para>
/// </remarks>
/// <param name="repository">The repository to configure.</param>
#else
/// <summary>
/// Automatically configures the <see cref="ILoggerRepository"/> using settings
/// stored in the application's configuration file.
/// </summary>
/// <remarks>
/// <para>
/// Each application has a configuration file. This has the
/// same name as the application with '.config' appended.
/// This file is XML and calling this function prompts the
/// configurator to look in that file for a section called
/// <c>log4net</c> that contains the configuration data.
/// </para>
/// </remarks>
/// <param name="repository">The repository to configure.</param>
#endif
static public ICollection Configure(ILoggerRepository repository)
{
ArrayList configurationMessages = new ArrayList();
using (new LogLog.LogReceivedAdapter(configurationMessages))
{
InternalConfigure(repository);
}
repository.ConfigurationMessages = configurationMessages;
return configurationMessages;
}
static private void InternalConfigure(ILoggerRepository repository)
{
LogLog.Debug(declaringType, "configuring repository [" + repository.Name + "] using .config file section");
try
{
LogLog.Debug(declaringType, "Application config file is [" + SystemInfo.ConfigurationFileLocation + "]");
}
catch
{
// ignore error
LogLog.Debug(declaringType, "Application config file location unknown");
}
#if NETCF || NETSTANDARD1_3
// No config file reading stuff. Just go straight for the file
Configure(repository, new FileInfo(SystemInfo.ConfigurationFileLocation));
#else
try
{
XmlElement configElement = null;
#if NET_2_0
configElement = System.Configuration.ConfigurationManager.GetSection("log4net") as XmlElement;
#else
configElement = System.Configuration.ConfigurationSettings.GetConfig("log4net") as XmlElement;
#endif
if (configElement == null)
{
// Failed to load the xml config using configuration settings handler
LogLog.Error(declaringType, "Failed to find configuration section 'log4net' in the application's .config file. Check your .config file for the <log4net> and <configSections> elements. The configuration section should look like: <section name=\"log4net\" type=\"log4net.Config.Log4NetConfigurationSectionHandler,log4net\" />");
}
else
{
// Configure using the xml loaded from the config file
InternalConfigureFromXml(repository, configElement);
}
}
catch(System.Configuration.ConfigurationException confEx)
{
if (confEx.BareMessage.IndexOf("Unrecognized element") >= 0)
{
// Looks like the XML file is not valid
LogLog.Error(declaringType, "Failed to parse config file. Check your .config file is well formed XML.", confEx);
}
else
{
// This exception is typically due to the assembly name not being correctly specified in the section type.
string configSectionStr = "<section name=\"log4net\" type=\"log4net.Config.Log4NetConfigurationSectionHandler," + Assembly.GetExecutingAssembly().FullName + "\" />";
LogLog.Error(declaringType, "Failed to parse config file. Is the <configSections> specified as: " + configSectionStr, confEx);
}
}
#endif
}
#if !NETSTANDARD1_3 // Excluded because GetCallingAssembly() is not available in CoreFX (https://github.com/dotnet/corefx/issues/2221).
#if !NETCF
/// <summary>
/// Automatically configures the log4net system based on the
/// application's configuration settings.
/// </summary>
/// <remarks>
/// <para>
/// Each application has a configuration file. This has the
/// same name as the application with '.config' appended.
/// This file is XML and calling this function prompts the
/// configurator to look in that file for a section called
/// <c>log4net</c> that contains the configuration data.
/// </para>
/// <para>
/// To use this method to configure log4net you must specify
/// the <see cref="Log4NetConfigurationSectionHandler"/> section
/// handler for the <c>log4net</c> configuration section. See the
/// <see cref="Log4NetConfigurationSectionHandler"/> for an example.
/// </para>
/// </remarks>
/// <seealso cref="Log4NetConfigurationSectionHandler"/>
#else
/// <summary>
/// Automatically configures the log4net system based on the
/// application's configuration settings.
/// </summary>
/// <remarks>
/// <para>
/// Each application has a configuration file. This has the
/// same name as the application with '.config' appended.
/// This file is XML and calling this function prompts the
/// configurator to look in that file for a section called
/// <c>log4net</c> that contains the configuration data.
/// </para>
/// </remarks>
#endif
static public ICollection Configure()
{
return Configure(LogManager.GetRepository(Assembly.GetCallingAssembly()));
}
/// <summary>
/// Configures log4net using a <c>log4net</c> element
/// </summary>
/// <remarks>
/// <para>
/// Loads the log4net configuration from the XML element
/// supplied as <paramref name="element"/>.
/// </para>
/// </remarks>
/// <param name="element">The element to parse.</param>
static public ICollection Configure(XmlElement element)
{
ArrayList configurationMessages = new ArrayList();
ILoggerRepository repository = LogManager.GetRepository(Assembly.GetCallingAssembly());
using (new LogLog.LogReceivedAdapter(configurationMessages))
{
InternalConfigureFromXml(repository, element);
}
repository.ConfigurationMessages = configurationMessages;
return configurationMessages;
}
#if !NETCF
/// <summary>
/// Configures log4net using the specified configuration file.
/// </summary>
/// <param name="configFile">The XML file to load the configuration from.</param>
/// <remarks>
/// <para>
/// The configuration file must be valid XML. It must contain
/// at least one element called <c>log4net</c> that holds
/// the log4net configuration data.
/// </para>
/// <para>
/// The log4net configuration file can possible be specified in the application's
/// configuration file (either <c>MyAppName.exe.config</c> for a
/// normal application on <c>Web.config</c> for an ASP.NET application).
/// </para>
/// <para>
/// The first element matching <c><configuration></c> will be read as the
/// configuration. If this file is also a .NET .config file then you must specify
/// a configuration section for the <c>log4net</c> element otherwise .NET will
/// complain. Set the type for the section handler to <see cref="System.Configuration.IgnoreSectionHandler"/>, for example:
/// <code lang="XML" escaped="true">
/// <configSections>
/// <section name="log4net" type="System.Configuration.IgnoreSectionHandler" />
/// </configSections>
/// </code>
/// </para>
/// <example>
/// The following example configures log4net using a configuration file, of which the
/// location is stored in the application's configuration file :
/// </example>
/// <code lang="C#">
/// using log4net.Config;
/// using System.IO;
/// using System.Configuration;
///
/// ...
///
/// XmlConfigurator.Configure(new FileInfo(ConfigurationSettings.AppSettings["log4net-config-file"]));
/// </code>
/// <para>
/// In the <c>.config</c> file, the path to the log4net can be specified like this :
/// </para>
/// <code lang="XML" escaped="true">
/// <configuration>
/// <appSettings>
/// <add key="log4net-config-file" value="log.config"/>
/// </appSettings>
/// </configuration>
/// </code>
/// </remarks>
#else
/// <summary>
/// Configures log4net using the specified configuration file.
/// </summary>
/// <param name="configFile">The XML file to load the configuration from.</param>
/// <remarks>
/// <para>
/// The configuration file must be valid XML. It must contain
/// at least one element called <c>log4net</c> that holds
/// the log4net configuration data.
/// </para>
/// <example>
/// The following example configures log4net using a configuration file, of which the
/// location is stored in the application's configuration file :
/// </example>
/// <code lang="C#">
/// using log4net.Config;
/// using System.IO;
/// using System.Configuration;
///
/// ...
///
/// XmlConfigurator.Configure(new FileInfo(ConfigurationSettings.AppSettings["log4net-config-file"]));
/// </code>
/// <para>
/// In the <c>.config</c> file, the path to the log4net can be specified like this :
/// </para>
/// <code lang="XML" escaped="true">
/// <configuration>
/// <appSettings>
/// <add key="log4net-config-file" value="log.config"/>
/// </appSettings>
/// </configuration>
/// </code>
/// </remarks>
#endif
static public ICollection Configure(FileInfo configFile)
{
ArrayList configurationMessages = new ArrayList();
using (new LogLog.LogReceivedAdapter(configurationMessages))
{
InternalConfigure(LogManager.GetRepository(Assembly.GetCallingAssembly()), configFile);
}
return configurationMessages;
}
/// <summary>
/// Configures log4net using the specified configuration URI.
/// </summary>
/// <param name="configUri">A URI to load the XML configuration from.</param>
/// <remarks>
/// <para>
/// The configuration data must be valid XML. It must contain
/// at least one element called <c>log4net</c> that holds
/// the log4net configuration data.
/// </para>
/// <para>
/// The <see cref="System.Net.WebRequest"/> must support the URI scheme specified.
/// </para>
/// </remarks>
static public ICollection Configure(Uri configUri)
{
ArrayList configurationMessages = new ArrayList();
ILoggerRepository repository = LogManager.GetRepository(Assembly.GetCallingAssembly());
using (new LogLog.LogReceivedAdapter(configurationMessages))
{
InternalConfigure(repository, configUri);
}
repository.ConfigurationMessages = configurationMessages;
return configurationMessages;
}
/// <summary>
/// Configures log4net using the specified configuration data stream.
/// </summary>
/// <param name="configStream">A stream to load the XML configuration from.</param>
/// <remarks>
/// <para>
/// The configuration data must be valid XML. It must contain
/// at least one element called <c>log4net</c> that holds
/// the log4net configuration data.
/// </para>
/// <para>
/// Note that this method will NOT close the stream parameter.
/// </para>
/// </remarks>
static public ICollection Configure(Stream configStream)
{
ArrayList configurationMessages = new ArrayList();
ILoggerRepository repository = LogManager.GetRepository(Assembly.GetCallingAssembly());
using (new LogLog.LogReceivedAdapter(configurationMessages))
{
InternalConfigure(repository, configStream);
}
repository.ConfigurationMessages = configurationMessages;
return configurationMessages;
}
#endif // !NETSTANDARD1_3
/// <summary>
/// Configures the <see cref="ILoggerRepository"/> using the specified XML
/// element.
/// </summary>
/// <remarks>
/// Loads the log4net configuration from the XML element
/// supplied as <paramref name="element"/>.
/// </remarks>
/// <param name="repository">The repository to configure.</param>
/// <param name="element">The element to parse.</param>
static public ICollection Configure(ILoggerRepository repository, XmlElement element)
{
ArrayList configurationMessages = new ArrayList();
using (new LogLog.LogReceivedAdapter(configurationMessages))
{
LogLog.Debug(declaringType, "configuring repository [" + repository.Name + "] using XML element");
InternalConfigureFromXml(repository, element);
}
repository.ConfigurationMessages = configurationMessages;
return configurationMessages;
}
#if !NETCF
/// <summary>
/// Configures the <see cref="ILoggerRepository"/> using the specified configuration
/// file.
/// </summary>
/// <param name="repository">The repository to configure.</param>
/// <param name="configFile">The XML file to load the configuration from.</param>
/// <remarks>
/// <para>
/// The configuration file must be valid XML. It must contain
/// at least one element called <c>log4net</c> that holds
/// the configuration data.
/// </para>
/// <para>
/// The log4net configuration file can possible be specified in the application's
/// configuration file (either <c>MyAppName.exe.config</c> for a
/// normal application on <c>Web.config</c> for an ASP.NET application).
/// </para>
/// <para>
/// The first element matching <c><configuration></c> will be read as the
/// configuration. If this file is also a .NET .config file then you must specify
/// a configuration section for the <c>log4net</c> element otherwise .NET will
/// complain. Set the type for the section handler to <see cref="System.Configuration.IgnoreSectionHandler"/>, for example:
/// <code lang="XML" escaped="true">
/// <configSections>
/// <section name="log4net" type="System.Configuration.IgnoreSectionHandler" />
/// </configSections>
/// </code>
/// </para>
/// <example>
/// The following example configures log4net using a configuration file, of which the
/// location is stored in the application's configuration file :
/// </example>
/// <code lang="C#">
/// using log4net.Config;
/// using System.IO;
/// using System.Configuration;
///
/// ...
///
/// XmlConfigurator.Configure(new FileInfo(ConfigurationSettings.AppSettings["log4net-config-file"]));
/// </code>
/// <para>
/// In the <c>.config</c> file, the path to the log4net can be specified like this :
/// </para>
/// <code lang="XML" escaped="true">
/// <configuration>
/// <appSettings>
/// <add key="log4net-config-file" value="log.config"/>
/// </appSettings>
/// </configuration>
/// </code>
/// </remarks>
#else
/// <summary>
/// Configures the <see cref="ILoggerRepository"/> using the specified configuration
/// file.
/// </summary>
/// <param name="repository">The repository to configure.</param>
/// <param name="configFile">The XML file to load the configuration from.</param>
/// <remarks>
/// <para>
/// The configuration file must be valid XML. It must contain
/// at least one element called <c>log4net</c> that holds
/// the configuration data.
/// </para>
/// <example>
/// The following example configures log4net using a configuration file, of which the
/// location is stored in the application's configuration file :
/// </example>
/// <code lang="C#">
/// using log4net.Config;
/// using System.IO;
/// using System.Configuration;
///
/// ...
///
/// XmlConfigurator.Configure(new FileInfo(ConfigurationSettings.AppSettings["log4net-config-file"]));
/// </code>
/// <para>
/// In the <c>.config</c> file, the path to the log4net can be specified like this :
/// </para>
/// <code lang="XML" escaped="true">
/// <configuration>
/// <appSettings>
/// <add key="log4net-config-file" value="log.config"/>
/// </appSettings>
/// </configuration>
/// </code>
/// </remarks>
#endif
static public ICollection Configure(ILoggerRepository repository, FileInfo configFile)
{
ArrayList configurationMessages = new ArrayList();
using (new LogLog.LogReceivedAdapter(configurationMessages))
{
InternalConfigure(repository, configFile);
}
repository.ConfigurationMessages = configurationMessages;
return configurationMessages;
}
static private void InternalConfigure(ILoggerRepository repository, FileInfo configFile)
{
LogLog.Debug(declaringType, "configuring repository [" + repository.Name + "] using file [" + configFile + "]");
if (configFile == null)
{
LogLog.Error(declaringType, "Configure called with null 'configFile' parameter");
}
else
{
// Have to use File.Exists() rather than configFile.Exists()
// because configFile.Exists() caches the value, not what we want.
if (File.Exists(configFile.FullName))
{
// Open the file for reading
FileStream fs = null;
// Try hard to open the file
for(int retry = 5; --retry >= 0; )
{
try
{
fs = configFile.Open(FileMode.Open, FileAccess.Read, FileShare.Read);
break;
}
catch(IOException ex)
{
if (retry == 0)
{
LogLog.Error(declaringType, "Failed to open XML config file [" + configFile.Name + "]", ex);
// The stream cannot be valid
fs = null;
}
System.Threading.Thread.Sleep(250);
}
}
if (fs != null)
{
try
{
// Load the configuration from the stream
InternalConfigure(repository, fs);
}
finally
{
// Force the file closed whatever happens
fs.Close();
}
}
}
else
{
LogLog.Debug(declaringType, "config file [" + configFile.FullName + "] not found. Configuration unchanged.");
}
}
}
/// <summary>
/// Configures the <see cref="ILoggerRepository"/> using the specified configuration
/// URI.
/// </summary>
/// <param name="repository">The repository to configure.</param>
/// <param name="configUri">A URI to load the XML configuration from.</param>
/// <remarks>
/// <para>
/// The configuration data must be valid XML. It must contain
/// at least one element called <c>log4net</c> that holds
/// the configuration data.
/// </para>
/// <para>
/// The <see cref="System.Net.WebRequest"/> must support the URI scheme specified.
/// </para>
/// </remarks>
static public ICollection Configure(ILoggerRepository repository, Uri configUri)
{
ArrayList configurationMessages = new ArrayList();
using (new LogLog.LogReceivedAdapter(configurationMessages))
{
InternalConfigure(repository, configUri);
}
repository.ConfigurationMessages = configurationMessages;
return configurationMessages;
}
static private void InternalConfigure(ILoggerRepository repository, Uri configUri)
{
LogLog.Debug(declaringType, "configuring repository [" + repository.Name + "] using URI ["+configUri+"]");
if (configUri == null)
{
LogLog.Error(declaringType, "Configure called with null 'configUri' parameter");
}
else
{
if (configUri.IsFile)
{
// If URI is local file then call Configure with FileInfo
InternalConfigure(repository, new FileInfo(configUri.LocalPath));
}
else
{
// NETCF dose not support WebClient
WebRequest configRequest = null;
try
{
configRequest = WebRequest.Create(configUri);
}
catch(Exception ex)
{
LogLog.Error(declaringType, "Failed to create WebRequest for URI ["+configUri+"]", ex);
}
if (configRequest != null)
{
#if !NETCF_1_0
// authentication may be required, set client to use default credentials
try
{
configRequest.Credentials = CredentialCache.DefaultCredentials;
}
catch
{
// ignore security exception
}
#endif
try
{
#if NETSTANDARD1_3
WebResponse response = configRequest.GetResponseAsync().GetAwaiter().GetResult();
#else
WebResponse response = configRequest.GetResponse();
#endif
if (response != null)
{
try
{
// Open stream on config URI
using(Stream configStream = response.GetResponseStream())
{
InternalConfigure(repository, configStream);
}
}
finally
{
response.Close();
}
}
}
catch(Exception ex)
{
LogLog.Error(declaringType, "Failed to request config from URI ["+configUri+"]", ex);
}
}
}
}
}
/// <summary>
/// Configures the <see cref="ILoggerRepository"/> using the specified configuration
/// file.
/// </summary>
/// <param name="repository">The repository to configure.</param>
/// <param name="configStream">The stream to load the XML configuration from.</param>
/// <remarks>
/// <para>
/// The configuration data must be valid XML. It must contain
/// at least one element called <c>log4net</c> that holds
/// the configuration data.
/// </para>
/// <para>
/// Note that this method will NOT close the stream parameter.
/// </para>
/// </remarks>
static public ICollection Configure(ILoggerRepository repository, Stream configStream)
{
ArrayList configurationMessages = new ArrayList();
using (new LogLog.LogReceivedAdapter(configurationMessages))
{
InternalConfigure(repository, configStream);
}
repository.ConfigurationMessages = configurationMessages;
return configurationMessages;
}
static private void InternalConfigure(ILoggerRepository repository, Stream configStream)
{
LogLog.Debug(declaringType, "configuring repository [" + repository.Name + "] using stream");
if (configStream == null)
{
LogLog.Error(declaringType, "Configure called with null 'configStream' parameter");
}
else
{
// Load the config file into a document
XmlDocument doc = new XmlDocument() { XmlResolver = null };
try
{
#if (NETCF)
// Create a text reader for the file stream
XmlTextReader xmlReader = new XmlTextReader(configStream);
#elif NET_2_0 || NETSTANDARD1_3
// Allow the DTD to specify entity includes
XmlReaderSettings settings = new XmlReaderSettings();
// .NET 4.0 warning CS0618: 'System.Xml.XmlReaderSettings.ProhibitDtd'
// is obsolete: 'Use XmlReaderSettings.DtdProcessing property instead.'
#if NETSTANDARD1_3 // TODO DtdProcessing.Parse not yet available (https://github.com/dotnet/corefx/issues/4376)
settings.DtdProcessing = DtdProcessing.Ignore;
#elif !NET_4_0 && !MONO_4_0
settings.ProhibitDtd = true;
#else
settings.XmlResolver = null;
settings.DtdProcessing = DtdProcessing.Prohibit;
#endif
// Create a reader over the input stream
XmlReader xmlReader = XmlReader.Create(configStream, settings);
#else
// Create a validating reader around a text reader for the file stream
XmlValidatingReader xmlReader = new XmlValidatingReader(new XmlTextReader(configStream));
// Specify that the reader should not perform validation, but that it should
// expand entity refs.
xmlReader.ValidationType = ValidationType.None;
xmlReader.EntityHandling = EntityHandling.ExpandEntities;
#endif
// load the data into the document
doc.Load(xmlReader);
}
catch(Exception ex)
{
LogLog.Error(declaringType, "Error while loading XML configuration", ex);
// The document is invalid
doc = null;
}
if (doc != null)
{
LogLog.Debug(declaringType, "loading XML configuration");
// Configure using the 'log4net' element
XmlNodeList configNodeList = doc.GetElementsByTagName("log4net");
if (configNodeList.Count == 0)
{
LogLog.Debug(declaringType, "XML configuration does not contain a <log4net> element. Configuration Aborted.");
}
else if (configNodeList.Count > 1)
{
LogLog.Error(declaringType, "XML configuration contains [" + configNodeList.Count + "] <log4net> elements. Only one is allowed. Configuration Aborted.");
}
else
{
InternalConfigureFromXml(repository, configNodeList[0] as XmlElement);
}
}
}
}
#endregion Configure static methods
#region ConfigureAndWatch static methods
#if (!NETCF && !SSCLI)
#if !NETSTANDARD1_3 // Excluded because GetCallingAssembly() is not available in CoreFX (https://github.com/dotnet/corefx/issues/2221).
/// <summary>
/// Configures log4net using the file specified, monitors the file for changes
/// and reloads the configuration if a change is detected.
/// </summary>
/// <param name="configFile">The XML file to load the configuration from.</param>
/// <remarks>
/// <para>
/// The configuration file must be valid XML. It must contain
/// at least one element called <c>log4net</c> that holds
/// the configuration data.
/// </para>
/// <para>
/// The configuration file will be monitored using a <see cref="FileSystemWatcher"/>
/// and depends on the behavior of that class.
/// </para>
/// <para>
/// For more information on how to configure log4net using
/// a separate configuration file, see <see cref="M:Configure(FileInfo)"/>.
/// </para>
/// </remarks>
/// <seealso cref="M:Configure(FileInfo)"/>
static public ICollection ConfigureAndWatch(FileInfo configFile)
{
ArrayList configurationMessages = new ArrayList();
ILoggerRepository repository = LogManager.GetRepository(Assembly.GetCallingAssembly());
using (new LogLog.LogReceivedAdapter(configurationMessages))
{
InternalConfigureAndWatch(repository, configFile);
}
repository.ConfigurationMessages = configurationMessages;
return configurationMessages;
}
#endif // !NETSTANDARD1_3
/// <summary>
/// Configures the <see cref="ILoggerRepository"/> using the file specified,
/// monitors the file for changes and reloads the configuration if a change
/// is detected.
/// </summary>
/// <param name="repository">The repository to configure.</param>
/// <param name="configFile">The XML file to load the configuration from.</param>
/// <remarks>
/// <para>
/// The configuration file must be valid XML. It must contain
/// at least one element called <c>log4net</c> that holds
/// the configuration data.
/// </para>
/// <para>
/// The configuration file will be monitored using a <see cref="FileSystemWatcher"/>
/// and depends on the behavior of that class.
/// </para>
/// <para>
/// For more information on how to configure log4net using
/// a separate configuration file, see <see cref="M:Configure(FileInfo)"/>.
/// </para>
/// </remarks>
/// <seealso cref="M:Configure(FileInfo)"/>
static public ICollection ConfigureAndWatch(ILoggerRepository repository, FileInfo configFile)
{
ArrayList configurationMessages = new ArrayList();
using (new LogLog.LogReceivedAdapter(configurationMessages))
{
InternalConfigureAndWatch(repository, configFile);
}
repository.ConfigurationMessages = configurationMessages;
return configurationMessages;
}
static private void InternalConfigureAndWatch(ILoggerRepository repository, FileInfo configFile)
{
LogLog.Debug(declaringType, "configuring repository [" + repository.Name + "] using file [" + configFile + "] watching for file updates");
if (configFile == null)
{
LogLog.Error(declaringType, "ConfigureAndWatch called with null 'configFile' parameter");
}
else
{
// Configure log4net now
InternalConfigure(repository, configFile);
try
{
lock (m_repositoryName2ConfigAndWatchHandler)
{
// support multiple repositories each having their own watcher
ConfigureAndWatchHandler handler =
(ConfigureAndWatchHandler)m_repositoryName2ConfigAndWatchHandler[configFile.FullName];
if (handler != null)
{
m_repositoryName2ConfigAndWatchHandler.Remove(configFile.FullName);
handler.Dispose();
}
// Create and start a watch handler that will reload the
// configuration whenever the config file is modified.
handler = new ConfigureAndWatchHandler(repository, configFile);
m_repositoryName2ConfigAndWatchHandler[configFile.FullName] = handler;
}
}
catch(Exception ex)
{
LogLog.Error(declaringType, "Failed to initialize configuration file watcher for file ["+configFile.FullName+"]", ex);
}
}
}
#endif
#endregion ConfigureAndWatch static methods
#region ConfigureAndWatchHandler
#if (!NETCF && !SSCLI)
/// <summary>
/// Class used to watch config files.
/// </summary>
/// <remarks>
/// <para>
/// Uses the <see cref="FileSystemWatcher"/> to monitor
/// changes to a specified file. Because multiple change notifications
/// may be raised when the file is modified, a timer is used to
/// compress the notifications into a single event. The timer
/// waits for <see cref="TimeoutMillis"/> time before delivering
/// the event notification. If any further <see cref="FileSystemWatcher"/>
/// change notifications arrive while the timer is waiting it
/// is reset and waits again for <see cref="TimeoutMillis"/> to
/// elapse.
/// </para>
/// </remarks>
private sealed class ConfigureAndWatchHandler : IDisposable
{
/// <summary>
/// Holds the FileInfo used to configure the XmlConfigurator
/// </summary>
private FileInfo m_configFile;
/// <summary>
/// Holds the repository being configured.
/// </summary>
private ILoggerRepository m_repository;
/// <summary>
/// The timer used to compress the notification events.
/// </summary>
private Timer m_timer;
/// <summary>
/// The default amount of time to wait after receiving notification
/// before reloading the config file.
/// </summary>
private const int TimeoutMillis = 500;
/// <summary>
/// Watches file for changes. This object should be disposed when no longer
/// needed to free system handles on the watched resources.
/// </summary>
private FileSystemWatcher m_watcher;
/// <summary>
/// Initializes a new instance of the <see cref="ConfigureAndWatchHandler" /> class to
/// watch a specified config file used to configure a repository.
/// </summary>
/// <param name="repository">The repository to configure.</param>
/// <param name="configFile">The configuration file to watch.</param>
/// <remarks>
/// <para>
/// Initializes a new instance of the <see cref="ConfigureAndWatchHandler" /> class.
/// </para>
/// </remarks>
#if NET_4_0 || MONO_4_0 || NETSTANDARD1_3
[System.Security.SecuritySafeCritical]
#endif
public ConfigureAndWatchHandler(ILoggerRepository repository, FileInfo configFile)
{
m_repository = repository;
m_configFile = configFile;
// Create a new FileSystemWatcher and set its properties.
m_watcher = new FileSystemWatcher();
m_watcher.Path = m_configFile.DirectoryName;
m_watcher.Filter = m_configFile.Name;
// Set the notification filters
m_watcher.NotifyFilter = NotifyFilters.CreationTime | NotifyFilters.LastWrite | NotifyFilters.FileName;
// Add event handlers. OnChanged will do for all event handlers that fire a FileSystemEventArgs
m_watcher.Changed += new FileSystemEventHandler(ConfigureAndWatchHandler_OnChanged);
m_watcher.Created += new FileSystemEventHandler(ConfigureAndWatchHandler_OnChanged);
m_watcher.Deleted += new FileSystemEventHandler(ConfigureAndWatchHandler_OnChanged);
m_watcher.Renamed += new RenamedEventHandler(ConfigureAndWatchHandler_OnRenamed);
// Begin watching.
m_watcher.EnableRaisingEvents = true;
// Create the timer that will be used to deliver events. Set as disabled
m_timer = new Timer(new TimerCallback(OnWatchedFileChange), null, Timeout.Infinite, Timeout.Infinite);
}
/// <summary>
/// Event handler used by <see cref="ConfigureAndWatchHandler"/>.
/// </summary>
/// <param name="source">The <see cref="FileSystemWatcher"/> firing the event.</param>
/// <param name="e">The argument indicates the file that caused the event to be fired.</param>
/// <remarks>
/// <para>
/// This handler reloads the configuration from the file when the event is fired.
/// </para>
/// </remarks>
private void ConfigureAndWatchHandler_OnChanged(object source, FileSystemEventArgs e)
{
LogLog.Debug(declaringType, "ConfigureAndWatchHandler: "+e.ChangeType+" [" + m_configFile.FullName + "]");
// Deliver the event in TimeoutMillis time
// timer will fire only once
m_timer.Change(TimeoutMillis, Timeout.Infinite);
}
/// <summary>
/// Event handler used by <see cref="ConfigureAndWatchHandler"/>.
/// </summary>
/// <param name="source">The <see cref="FileSystemWatcher"/> firing the event.</param>
/// <param name="e">The argument indicates the file that caused the event to be fired.</param>
/// <remarks>
/// <para>
/// This handler reloads the configuration from the file when the event is fired.
/// </para>
/// </remarks>
private void ConfigureAndWatchHandler_OnRenamed(object source, RenamedEventArgs e)
{
LogLog.Debug(declaringType, "ConfigureAndWatchHandler: " + e.ChangeType + " [" + m_configFile.FullName + "]");
// Deliver the event in TimeoutMillis time
// timer will fire only once
m_timer.Change(TimeoutMillis, Timeout.Infinite);
}
/// <summary>
/// Called by the timer when the configuration has been updated.
/// </summary>
/// <param name="state">null</param>
private void OnWatchedFileChange(object state)
{
XmlConfigurator.InternalConfigure(m_repository, m_configFile);
}
/// <summary>
/// Release the handles held by the watcher and timer.
/// </summary>
#if NET_4_0 || MONO_4_0 || NETSTANDARD1_3
[System.Security.SecuritySafeCritical]
#endif
public void Dispose()
{
m_watcher.EnableRaisingEvents = false;
m_watcher.Dispose();
m_timer.Dispose();
}
}
#endif
#endregion ConfigureAndWatchHandler
#region Private Static Methods
/// <summary>
/// Configures the specified repository using a <c>log4net</c> element.
/// </summary>
/// <param name="repository">The hierarchy to configure.</param>
/// <param name="element">The element to parse.</param>
/// <remarks>
/// <para>
/// Loads the log4net configuration from the XML element
/// supplied as <paramref name="element"/>.
/// </para>
/// <para>
/// This method is ultimately called by one of the Configure methods
/// to load the configuration from an <see cref="XmlElement"/>.
/// </para>
/// </remarks>
static private void InternalConfigureFromXml(ILoggerRepository repository, XmlElement element)
{
if (element == null)
{
LogLog.Error(declaringType, "ConfigureFromXml called with null 'element' parameter");
}
else if (repository == null)
{
LogLog.Error(declaringType, "ConfigureFromXml called with null 'repository' parameter");
}
else
{
LogLog.Debug(declaringType, "Configuring Repository [" + repository.Name + "]");
IXmlRepositoryConfigurator configurableRepository = repository as IXmlRepositoryConfigurator;
if (configurableRepository == null)
{
LogLog.Warn(declaringType, "Repository [" + repository + "] does not support the XmlConfigurator");
}
else
{
// Copy the xml data into the root of a new document
// this isolates the xml config data from the rest of
// the document
XmlDocument newDoc = new XmlDocument() { XmlResolver = null };
XmlElement newElement = (XmlElement)newDoc.AppendChild(newDoc.ImportNode(element, true));
// Pass the configurator the config element
configurableRepository.Configure(newElement);
}
}
}
#endregion Private Static Methods
#region Private Static Fields
/// <summary>
/// Maps repository names to ConfigAndWatchHandler instances to allow a particular
/// ConfigAndWatchHandler to dispose of its FileSystemWatcher when a repository is
/// reconfigured.
/// </summary>
private readonly static Hashtable m_repositoryName2ConfigAndWatchHandler = new Hashtable();
/// <summary>
/// The fully qualified type of the XmlConfigurator class.
/// </summary>
/// <remarks>
/// Used by the internal logger to record the Type of the
/// log message.
/// </remarks>
private readonly static Type declaringType = typeof(XmlConfigurator);
#endregion Private Static Fields
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Build.Execution;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Roslyn.Utilities;
using MSB = Microsoft.Build;
namespace Microsoft.CodeAnalysis.MSBuild
{
internal abstract class ProjectFile : IProjectFile
{
private readonly ProjectFileLoader _loader;
private readonly MSB.Evaluation.Project _loadedProject;
private readonly string _errorMessage;
public ProjectFile(ProjectFileLoader loader, MSB.Evaluation.Project loadedProject, string errorMessage)
{
_loader = loader;
_loadedProject = loadedProject;
_errorMessage = errorMessage;
}
~ProjectFile()
{
try
{
// unload project so collection will release global strings
_loadedProject.ProjectCollection.UnloadAllProjects();
}
catch
{
}
}
public virtual string FilePath
{
get { return _loadedProject.FullPath; }
}
public string ErrorMessage
{
get { return _errorMessage; }
}
public string GetPropertyValue(string name)
{
return _loadedProject.GetPropertyValue(name);
}
public abstract SourceCodeKind GetSourceCodeKind(string documentFileName);
public abstract string GetDocumentExtension(SourceCodeKind kind);
public abstract Task<ProjectFileInfo> GetProjectFileInfoAsync(CancellationToken cancellationToken);
public struct BuildInfo
{
public readonly ProjectInstance Project;
public readonly string ErrorMessage;
public BuildInfo(ProjectInstance project, string errorMessage)
{
this.Project = project;
this.ErrorMessage = errorMessage;
}
}
protected async Task<BuildInfo> BuildAsync(string taskName, MSB.Framework.ITaskHost taskHost, CancellationToken cancellationToken)
{
// create a project instance to be executed by build engine.
// The executed project will hold the final model of the project after execution via msbuild.
var executedProject = _loadedProject.CreateProjectInstance();
if (!executedProject.Targets.ContainsKey("Compile"))
{
return new BuildInfo(executedProject, null);
}
var hostServices = new Microsoft.Build.Execution.HostServices();
// connect the host "callback" object with the host services, so we get called back with the exact inputs to the compiler task.
hostServices.RegisterHostObject(_loadedProject.FullPath, "CoreCompile", taskName, taskHost);
var buildParameters = new MSB.Execution.BuildParameters(_loadedProject.ProjectCollection);
var buildRequestData = new MSB.Execution.BuildRequestData(executedProject, new string[] { "Compile" }, hostServices);
BuildResult result = await this.BuildAsync(buildParameters, buildRequestData, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
if (result.OverallResult == BuildResultCode.Failure)
{
return new BuildInfo(executedProject, result.Exception?.Message ?? "");
}
else
{
return new BuildInfo(executedProject, null);
}
}
// this lock is static because we are using the default build manager, and there is only one per process
private static readonly SemaphoreSlim s_buildManagerLock = new SemaphoreSlim(initialCount: 1);
private async Task<MSB.Execution.BuildResult> BuildAsync(MSB.Execution.BuildParameters parameters, MSB.Execution.BuildRequestData requestData, CancellationToken cancellationToken)
{
// only allow one build to use the default build manager at a time
using (await s_buildManagerLock.DisposableWaitAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false))
{
return await BuildAsync(MSB.Execution.BuildManager.DefaultBuildManager, parameters, requestData, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
}
}
private static Task<MSB.Execution.BuildResult> BuildAsync(MSB.Execution.BuildManager buildManager, MSB.Execution.BuildParameters parameters, MSB.Execution.BuildRequestData requestData, CancellationToken cancellationToken)
{
var taskSource = new TaskCompletionSource<MSB.Execution.BuildResult>();
buildManager.BeginBuild(parameters);
// enable cancellation of build
CancellationTokenRegistration registration = default(CancellationTokenRegistration);
if (cancellationToken.CanBeCanceled)
{
registration = cancellationToken.Register(() =>
{
try
{
buildManager.CancelAllSubmissions();
buildManager.EndBuild();
registration.Dispose();
}
finally
{
taskSource.TrySetCanceled();
}
});
}
// execute build async
try
{
buildManager.PendBuildRequest(requestData).ExecuteAsync(sub =>
{
// when finished
try
{
var result = sub.BuildResult;
buildManager.EndBuild();
registration.Dispose();
taskSource.TrySetResult(result);
}
catch (Exception e)
{
taskSource.TrySetException(e);
}
}, null);
}
catch (Exception e)
{
taskSource.SetException(e);
}
return taskSource.Task;
}
protected virtual string GetOutputDirectory()
{
var targetPath = _loadedProject.GetPropertyValue("TargetPath");
if (string.IsNullOrEmpty(targetPath))
{
targetPath = _loadedProject.DirectoryPath;
}
return Path.GetDirectoryName(this.GetAbsolutePath(targetPath));
}
protected virtual string GetAssemblyName()
{
var assemblyName = _loadedProject.GetPropertyValue("AssemblyName");
if (string.IsNullOrEmpty(assemblyName))
{
assemblyName = Path.GetFileNameWithoutExtension(_loadedProject.FullPath);
}
return PathUtilities.GetFileName(assemblyName);
}
protected bool IsProjectReferenceOutputAssembly(MSB.Framework.ITaskItem item)
{
return item.GetMetadata("ReferenceOutputAssembly") == "true";
}
protected IEnumerable<ProjectFileReference> GetProjectReferences(ProjectInstance executedProject)
{
return executedProject
.GetItems("ProjectReference")
.Where(i => !string.Equals(
i.GetMetadataValue("ReferenceOutputAssembly"),
bool.FalseString,
StringComparison.OrdinalIgnoreCase))
.Select(CreateProjectFileReference);
}
/// <summary>
/// Create a <see cref="ProjectFileReference"/> from a ProjectReference node in the MSBuild file.
/// </summary>
protected virtual ProjectFileReference CreateProjectFileReference(ProjectItemInstance reference)
{
return new ProjectFileReference(
path: reference.EvaluatedInclude,
aliases: ImmutableArray<string>.Empty);
}
protected virtual IEnumerable<MSB.Framework.ITaskItem> GetDocumentsFromModel(MSB.Execution.ProjectInstance executedProject)
{
return executedProject.GetItems("Compile");
}
protected virtual IEnumerable<MSB.Framework.ITaskItem> GetMetadataReferencesFromModel(MSB.Execution.ProjectInstance executedProject)
{
return executedProject.GetItems("ReferencePath");
}
protected virtual IEnumerable<MSB.Framework.ITaskItem> GetAnalyzerReferencesFromModel(MSB.Execution.ProjectInstance executedProject)
{
return executedProject.GetItems("Analyzer");
}
protected virtual IEnumerable<MSB.Framework.ITaskItem> GetAdditionalFilesFromModel(MSB.Execution.ProjectInstance executedProject)
{
return executedProject.GetItems("AdditionalFiles");
}
public MSB.Evaluation.ProjectProperty GetProperty(string name)
{
return _loadedProject.GetProperty(name);
}
protected IEnumerable<MSB.Framework.ITaskItem> GetTaskItems(MSB.Execution.ProjectInstance executedProject, string itemType)
{
return executedProject.GetItems(itemType);
}
protected string GetItemString(MSB.Execution.ProjectInstance executedProject, string itemType)
{
string text = "";
foreach (var item in executedProject.GetItems(itemType))
{
if (text.Length > 0)
{
text = text + " ";
}
text = text + item.EvaluatedInclude;
}
return text;
}
protected string ReadPropertyString(MSB.Execution.ProjectInstance executedProject, string propertyName)
{
return this.ReadPropertyString(executedProject, propertyName, propertyName);
}
protected string ReadPropertyString(MSB.Execution.ProjectInstance executedProject, string executedPropertyName, string evaluatedPropertyName)
{
var executedProperty = executedProject.GetProperty(executedPropertyName);
if (executedProperty != null)
{
return executedProperty.EvaluatedValue;
}
var evaluatedProperty = _loadedProject.GetProperty(evaluatedPropertyName);
if (evaluatedProperty != null)
{
return evaluatedProperty.EvaluatedValue;
}
return null;
}
protected bool ReadPropertyBool(MSB.Execution.ProjectInstance executedProject, string propertyName)
{
return ConvertToBool(ReadPropertyString(executedProject, propertyName));
}
protected bool ReadPropertyBool(MSB.Execution.ProjectInstance executedProject, string executedPropertyName, string evaluatedPropertyName)
{
return ConvertToBool(ReadPropertyString(executedProject, executedPropertyName, evaluatedPropertyName));
}
private static bool ConvertToBool(string value)
{
return value != null && (string.Equals("true", value, StringComparison.OrdinalIgnoreCase) ||
string.Equals("On", value, StringComparison.OrdinalIgnoreCase));
}
protected int ReadPropertyInt(MSB.Execution.ProjectInstance executedProject, string propertyName)
{
return ConvertToInt(ReadPropertyString(executedProject, propertyName));
}
protected int ReadPropertyInt(MSB.Execution.ProjectInstance executedProject, string executedPropertyName, string evaluatedPropertyName)
{
return ConvertToInt(ReadPropertyString(executedProject, executedPropertyName, evaluatedPropertyName));
}
private static int ConvertToInt(string value)
{
if (value == null)
{
return 0;
}
else
{
int.TryParse(value, out var result);
return result;
}
}
protected ulong ReadPropertyULong(MSB.Execution.ProjectInstance executedProject, string propertyName)
{
return ConvertToULong(ReadPropertyString(executedProject, propertyName));
}
protected ulong ReadPropertyULong(MSB.Execution.ProjectInstance executedProject, string executedPropertyName, string evaluatedPropertyName)
{
return ConvertToULong(this.ReadPropertyString(executedProject, executedPropertyName, evaluatedPropertyName));
}
private static ulong ConvertToULong(string value)
{
if (value == null)
{
return 0;
}
else
{
ulong.TryParse(value, out var result);
return result;
}
}
protected TEnum? ReadPropertyEnum<TEnum>(MSB.Execution.ProjectInstance executedProject, string propertyName)
where TEnum : struct
{
return ConvertToEnum<TEnum>(ReadPropertyString(executedProject, propertyName));
}
protected TEnum? ReadPropertyEnum<TEnum>(MSB.Execution.ProjectInstance executedProject, string executedPropertyName, string evaluatedPropertyName)
where TEnum : struct
{
return ConvertToEnum<TEnum>(ReadPropertyString(executedProject, executedPropertyName, evaluatedPropertyName));
}
private static TEnum? ConvertToEnum<TEnum>(string value)
where TEnum : struct
{
if (value == null)
{
return null;
}
else
{
if (Enum.TryParse<TEnum>(value, out var result))
{
return result;
}
else
{
return null;
}
}
}
/// <summary>
/// Resolves the given path that is possibly relative to the project directory.
/// </summary>
/// <remarks>
/// The resulting path is absolute but might not be normalized.
/// </remarks>
protected string GetAbsolutePath(string path)
{
// TODO (tomat): should we report an error when drive-relative path (e.g. "C:foo.cs") is encountered?
return Path.GetFullPath(FileUtilities.ResolveRelativePath(path, _loadedProject.DirectoryPath) ?? path);
}
protected string GetDocumentFilePath(MSB.Framework.ITaskItem documentItem)
{
return GetAbsolutePath(documentItem.ItemSpec);
}
protected static bool IsDocumentLinked(MSB.Framework.ITaskItem documentItem)
{
return !string.IsNullOrEmpty(documentItem.GetMetadata("Link"));
}
private IDictionary<string, MSB.Evaluation.ProjectItem> _documents;
protected bool IsDocumentGenerated(MSB.Framework.ITaskItem documentItem)
{
if (_documents == null)
{
_documents = new Dictionary<string, MSB.Evaluation.ProjectItem>();
foreach (var item in _loadedProject.GetItems("compile"))
{
_documents[GetAbsolutePath(item.EvaluatedInclude)] = item;
}
}
return !_documents.ContainsKey(GetAbsolutePath(documentItem.ItemSpec));
}
protected static string GetDocumentLogicalPath(MSB.Framework.ITaskItem documentItem, string projectDirectory)
{
var link = documentItem.GetMetadata("Link");
if (!string.IsNullOrEmpty(link))
{
// if a specific link is specified in the project file then use it to form the logical path.
return link;
}
else
{
var result = documentItem.ItemSpec;
if (Path.IsPathRooted(result))
{
// If we have an absolute path, there are two possibilities:
result = Path.GetFullPath(result);
// If the document is within the current project directory (or subdirectory), then the logical path is the relative path
// from the project's directory.
if (result.StartsWith(projectDirectory, StringComparison.OrdinalIgnoreCase))
{
result = result.Substring(projectDirectory.Length);
}
else
{
// if the document lies outside the project's directory (or subdirectory) then place it logically at the root of the project.
// if more than one document ends up with the same logical name then so be it (the workspace will survive.)
return Path.GetFileName(result);
}
}
return result;
}
}
protected string GetReferenceFilePath(ProjectItemInstance projectItem)
{
return GetAbsolutePath(projectItem.EvaluatedInclude);
}
public void AddDocument(string filePath, string logicalPath = null)
{
var relativePath = FilePathUtilities.GetRelativePath(_loadedProject.DirectoryPath, filePath);
Dictionary<string, string> metadata = null;
if (logicalPath != null && relativePath != logicalPath)
{
metadata = new Dictionary<string, string>();
metadata.Add("link", logicalPath);
relativePath = filePath; // link to full path
}
_loadedProject.AddItem("Compile", relativePath, metadata);
}
public void RemoveDocument(string filePath)
{
var relativePath = FilePathUtilities.GetRelativePath(_loadedProject.DirectoryPath, filePath);
var items = _loadedProject.GetItems("Compile");
var item = items.FirstOrDefault(it => FilePathUtilities.PathsEqual(it.EvaluatedInclude, relativePath)
|| FilePathUtilities.PathsEqual(it.EvaluatedInclude, filePath));
if (item != null)
{
_loadedProject.RemoveItem(item);
}
}
public void AddMetadataReference(MetadataReference reference, AssemblyIdentity identity)
{
var peRef = reference as PortableExecutableReference;
if (peRef != null && peRef.FilePath != null)
{
var metadata = new Dictionary<string, string>();
if (!peRef.Properties.Aliases.IsEmpty)
{
metadata.Add("Aliases", string.Join(",", peRef.Properties.Aliases));
}
if (IsInGAC(peRef.FilePath) && identity != null)
{
_loadedProject.AddItem("Reference", identity.GetDisplayName(), metadata);
}
else
{
string relativePath = FilePathUtilities.GetRelativePath(_loadedProject.DirectoryPath, peRef.FilePath);
_loadedProject.AddItem("Reference", relativePath, metadata);
}
}
}
private bool IsInGAC(string filePath)
{
return filePath.Contains(@"\GAC_MSIL\");
}
public void RemoveMetadataReference(MetadataReference reference, AssemblyIdentity identity)
{
var peRef = reference as PortableExecutableReference;
if (peRef != null && peRef.FilePath != null)
{
var item = FindReferenceItem(identity, peRef.FilePath);
if (item != null)
{
_loadedProject.RemoveItem(item);
}
}
}
private MSB.Evaluation.ProjectItem FindReferenceItem(AssemblyIdentity identity, string filePath)
{
var references = _loadedProject.GetItems("Reference");
MSB.Evaluation.ProjectItem item = null;
if (identity != null)
{
var shortAssemblyName = identity.Name;
var fullAssemblyName = identity.GetDisplayName();
// check for short name match
item = references.FirstOrDefault(it => string.Compare(it.EvaluatedInclude, shortAssemblyName, StringComparison.OrdinalIgnoreCase) == 0);
// check for full name match
if (item == null)
{
item = references.FirstOrDefault(it => string.Compare(it.EvaluatedInclude, fullAssemblyName, StringComparison.OrdinalIgnoreCase) == 0);
}
}
// check for file path match
if (item == null)
{
string relativePath = FilePathUtilities.GetRelativePath(_loadedProject.DirectoryPath, filePath);
item = references.FirstOrDefault(it => FilePathUtilities.PathsEqual(it.EvaluatedInclude, filePath)
|| FilePathUtilities.PathsEqual(it.EvaluatedInclude, relativePath));
}
// check for partial name match
if (item == null && identity != null)
{
var partialName = identity.Name + ",";
var items = references.Where(it => it.EvaluatedInclude.StartsWith(partialName, StringComparison.OrdinalIgnoreCase)).ToList();
if (items.Count == 1)
{
item = items[0];
}
}
return item;
}
public void AddProjectReference(string projectName, ProjectFileReference reference)
{
var metadata = new Dictionary<string, string>();
metadata.Add("Name", projectName);
if (!reference.Aliases.IsEmpty)
{
metadata.Add("Aliases", string.Join(",", reference.Aliases));
}
string relativePath = FilePathUtilities.GetRelativePath(_loadedProject.DirectoryPath, reference.Path);
_loadedProject.AddItem("ProjectReference", relativePath, metadata);
}
public void RemoveProjectReference(string projectName, string projectFilePath)
{
string relativePath = FilePathUtilities.GetRelativePath(_loadedProject.DirectoryPath, projectFilePath);
var item = FindProjectReferenceItem(projectName, projectFilePath);
if (item != null)
{
_loadedProject.RemoveItem(item);
}
}
private MSB.Evaluation.ProjectItem FindProjectReferenceItem(string projectName, string projectFilePath)
{
var references = _loadedProject.GetItems("ProjectReference");
string relativePath = FilePathUtilities.GetRelativePath(_loadedProject.DirectoryPath, projectFilePath);
MSB.Evaluation.ProjectItem item = null;
// find by project file path
item = references.First(it => FilePathUtilities.PathsEqual(it.EvaluatedInclude, relativePath)
|| FilePathUtilities.PathsEqual(it.EvaluatedInclude, projectFilePath));
// try to find by project name
if (item == null)
{
item = references.First(it => string.Compare(projectName, it.GetMetadataValue("Name"), StringComparison.OrdinalIgnoreCase) == 0);
}
return item;
}
public void AddAnalyzerReference(AnalyzerReference reference)
{
var fileRef = reference as AnalyzerFileReference;
if (fileRef != null)
{
string relativePath = FilePathUtilities.GetRelativePath(_loadedProject.DirectoryPath, fileRef.FullPath);
_loadedProject.AddItem("Analyzer", relativePath);
}
}
public void RemoveAnalyzerReference(AnalyzerReference reference)
{
var fileRef = reference as AnalyzerFileReference;
if (fileRef != null)
{
string relativePath = FilePathUtilities.GetRelativePath(_loadedProject.DirectoryPath, fileRef.FullPath);
var analyzers = _loadedProject.GetItems("Analyzer");
var item = analyzers.FirstOrDefault(it => FilePathUtilities.PathsEqual(it.EvaluatedInclude, relativePath)
|| FilePathUtilities.PathsEqual(it.EvaluatedInclude, fileRef.FullPath));
if (item != null)
{
_loadedProject.RemoveItem(item);
}
}
}
public void Save()
{
_loadedProject.Save();
}
internal static bool TryGetOutputKind(string outputKind, out OutputKind kind)
{
if (string.Equals(outputKind, "Library", StringComparison.OrdinalIgnoreCase))
{
kind = OutputKind.DynamicallyLinkedLibrary;
return true;
}
else if (string.Equals(outputKind, "Exe", StringComparison.OrdinalIgnoreCase))
{
kind = OutputKind.ConsoleApplication;
return true;
}
else if (string.Equals(outputKind, "WinExe", StringComparison.OrdinalIgnoreCase))
{
kind = OutputKind.WindowsApplication;
return true;
}
else if (string.Equals(outputKind, "Module", StringComparison.OrdinalIgnoreCase))
{
kind = OutputKind.NetModule;
return true;
}
else if (string.Equals(outputKind, "WinMDObj", StringComparison.OrdinalIgnoreCase))
{
kind = OutputKind.WindowsRuntimeMetadata;
return true;
}
else
{
kind = OutputKind.DynamicallyLinkedLibrary;
return false;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information.
//
// System.Drawing.carbonFunctions.cs
//
// Authors:
// Geoff Norton (gnorton@customerdna.com>
//
// 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.
//
#undef DEBUG_CLIPPING
using System.Collections;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security;
namespace System.Drawing
{
internal static class MacSupport
{
internal static Hashtable contextReference = new Hashtable();
internal static object lockobj = new object();
internal static Delegate hwnd_delegate;
#if DEBUG_CLIPPING
internal static float red = 1.0f;
internal static float green = 0.0f;
internal static float blue = 0.0f;
internal static int debug_threshold = 1;
#endif
static MacSupport()
{
#if !NETSTANDARD1_6
foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies())
{
if (String.Equals(asm.GetName().Name, "System.Windows.Forms"))
{
Type driver_type = asm.GetType("System.Windows.Forms.XplatUICarbon");
if (driver_type != null)
{
hwnd_delegate = (Delegate)driver_type.GetTypeInfo().GetField("HwndDelegate", BindingFlags.NonPublic | BindingFlags.Static).GetValue(null);
}
}
}
#endif
}
internal static CocoaContext GetCGContextForNSView(IntPtr handle)
{
IntPtr graphicsContext = objc_msgSend(objc_getClass("NSGraphicsContext"), sel_registerName("currentContext"));
IntPtr ctx = objc_msgSend(graphicsContext, sel_registerName("graphicsPort"));
Rect bounds = new Rect();
CGContextSaveGState(ctx);
objc_msgSend_stret(ref bounds, handle, sel_registerName("bounds"));
var isFlipped = bool_objc_msgSend(handle, sel_registerName("isFlipped"));
if (isFlipped)
{
CGContextTranslateCTM(ctx, bounds.origin.x, bounds.size.height);
CGContextScaleCTM(ctx, 1.0f, -1.0f);
}
return new CocoaContext(ctx, (int)bounds.size.width, (int)bounds.size.height);
}
internal static CarbonContext GetCGContextForView(IntPtr handle)
{
IntPtr context = IntPtr.Zero;
IntPtr port = IntPtr.Zero;
IntPtr window = IntPtr.Zero;
window = GetControlOwner(handle);
if (handle == IntPtr.Zero || window == IntPtr.Zero)
{
// FIXME: Can we actually get a CGContextRef for the desktop? this makes context IntPtr.Zero
port = GetQDGlobalsThePort();
CreateCGContextForPort(port, ref context);
Rect desktop_bounds = CGDisplayBounds(CGMainDisplayID());
return new CarbonContext(port, context, (int)desktop_bounds.size.width, (int)desktop_bounds.size.height);
}
QDRect window_bounds = new QDRect();
Rect view_bounds = new Rect();
port = GetWindowPort(window);
context = GetContext(port);
GetWindowBounds(window, 32, ref window_bounds);
HIViewGetBounds(handle, ref view_bounds);
HIViewConvertRect(ref view_bounds, handle, IntPtr.Zero);
if (view_bounds.size.height < 0)
view_bounds.size.height = 0;
if (view_bounds.size.width < 0)
view_bounds.size.width = 0;
CGContextTranslateCTM(context, view_bounds.origin.x, (window_bounds.bottom - window_bounds.top) - (view_bounds.origin.y + view_bounds.size.height));
// Create the original rect path and clip to it
Rect rc_clip = new Rect(0, 0, view_bounds.size.width, view_bounds.size.height);
CGContextSaveGState(context);
Rectangle[] clip_rectangles = (Rectangle[])hwnd_delegate.DynamicInvoke(new object[] { handle });
if (clip_rectangles != null && clip_rectangles.Length > 0)
{
int length = clip_rectangles.Length;
CGContextBeginPath(context);
CGContextAddRect(context, rc_clip);
for (int i = 0; i < length; i++)
{
CGContextAddRect(context, new Rect(clip_rectangles[i].X, view_bounds.size.height - clip_rectangles[i].Y - clip_rectangles[i].Height, clip_rectangles[i].Width, clip_rectangles[i].Height));
}
CGContextClosePath(context);
CGContextEOClip(context);
#if DEBUG_CLIPPING
if (clip_rectangles.Length >= debug_threshold) {
CGContextSetRGBFillColor (context, red, green, blue, 0.5f);
CGContextFillRect (context, rc_clip);
CGContextFlush (context);
System.Threading.Thread.Sleep (500);
if (red == 1.0f) { red = 0.0f; blue = 1.0f; }
else if (blue == 1.0f) { blue = 0.0f; green = 1.0f; }
else if (green == 1.0f) { green = 0.0f; red = 1.0f; }
}
#endif
}
else
{
CGContextBeginPath(context);
CGContextAddRect(context, rc_clip);
CGContextClosePath(context);
CGContextClip(context);
}
return new CarbonContext(port, context, (int)view_bounds.size.width, (int)view_bounds.size.height);
}
internal static IntPtr GetContext(IntPtr port)
{
IntPtr context = IntPtr.Zero;
lock (lockobj)
{
#if FALSE
if (contextReference [port] != null) {
CreateCGContextForPort (port, ref context);
} else {
QDBeginCGContext (port, ref context);
contextReference [port] = context;
}
#else
CreateCGContextForPort(port, ref context);
#endif
}
return context;
}
internal static void ReleaseContext(IntPtr port, IntPtr context)
{
CGContextRestoreGState(context);
lock (lockobj)
{
#if FALSE
if (contextReference [port] != null && context == (IntPtr) contextReference [port]) {
QDEndCGContext (port, ref context);
contextReference [port] = null;
} else {
CFRelease (context);
}
#else
CFRelease(context);
#endif
}
}
#region Cocoa Methods
[DllImport("libobjc.dylib")]
public static extern IntPtr objc_getClass(string className);
[DllImport("libobjc.dylib")]
public static extern IntPtr objc_msgSend(IntPtr basePtr, IntPtr selector, string argument);
[DllImport("libobjc.dylib")]
public static extern IntPtr objc_msgSend(IntPtr basePtr, IntPtr selector);
[DllImport("libobjc.dylib")]
public static extern void objc_msgSend_stret(ref Rect arect, IntPtr basePtr, IntPtr selector);
[DllImport("libobjc.dylib", EntryPoint = "objc_msgSend")]
public static extern bool bool_objc_msgSend(IntPtr handle, IntPtr selector);
[DllImport("libobjc.dylib")]
public static extern IntPtr sel_registerName(string selectorName);
#endregion
[DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
internal static extern IntPtr CGMainDisplayID();
[DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
internal static extern Rect CGDisplayBounds(IntPtr display);
[DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
internal static extern int HIViewGetBounds(IntPtr vHnd, ref Rect r);
[DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
internal static extern int HIViewConvertRect(ref Rect r, IntPtr a, IntPtr b);
[DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
internal static extern IntPtr GetControlOwner(IntPtr aView);
[DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
internal static extern int GetWindowBounds(IntPtr wHnd, uint reg, ref QDRect rect);
[DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
internal static extern IntPtr GetWindowPort(IntPtr hWnd);
[DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
internal static extern IntPtr GetQDGlobalsThePort();
[DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
internal static extern void CreateCGContextForPort(IntPtr port, ref IntPtr context);
[DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
internal static extern void CFRelease(IntPtr context);
[DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
internal static extern void QDBeginCGContext(IntPtr port, ref IntPtr context);
[DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
internal static extern void QDEndCGContext(IntPtr port, ref IntPtr context);
[DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
internal static extern int CGContextClipToRect(IntPtr context, Rect clip);
[DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
internal static extern int CGContextClipToRects(IntPtr context, Rect[] clip_rects, int count);
[DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
internal static extern void CGContextTranslateCTM(IntPtr context, float tx, float ty);
[DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
internal static extern void CGContextScaleCTM(IntPtr context, float x, float y);
[DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
internal static extern void CGContextFlush(IntPtr context);
[DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
internal static extern void CGContextSynchronize(IntPtr context);
[DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
internal static extern IntPtr CGPathCreateMutable();
[DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
internal static extern void CGPathAddRects(IntPtr path, IntPtr _void, Rect[] rects, int count);
[DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
internal static extern void CGPathAddRect(IntPtr path, IntPtr _void, Rect rect);
[DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
internal static extern void CGContextAddRects(IntPtr context, Rect[] rects, int count);
[DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
internal static extern void CGContextAddRect(IntPtr context, Rect rect);
[DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
internal static extern void CGContextBeginPath(IntPtr context);
[DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
internal static extern void CGContextClosePath(IntPtr context);
[DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
internal static extern void CGContextAddPath(IntPtr context, IntPtr path);
[DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
internal static extern void CGContextClip(IntPtr context);
[DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
internal static extern void CGContextEOClip(IntPtr context);
[DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
internal static extern void CGContextEOFillPath(IntPtr context);
[DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
internal static extern void CGContextSaveGState(IntPtr context);
[DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
internal static extern void CGContextRestoreGState(IntPtr context);
#if DEBUG_CLIPPING
[DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
internal static extern void CGContextSetRGBFillColor (IntPtr context, float red, float green, float blue, float alpha);
[DllImport ("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")]
internal static extern void CGContextFillRect (IntPtr context, Rect rect);
#endif
}
internal struct CGSize
{
public float width;
public float height;
}
internal struct CGPoint
{
public float x;
public float y;
}
internal struct Rect
{
public Rect(float x, float y, float width, float height)
{
this.origin.x = x;
this.origin.y = y;
this.size.width = width;
this.size.height = height;
}
public CGPoint origin;
public CGSize size;
}
internal struct QDRect
{
public short top;
public short left;
public short bottom;
public short right;
}
internal struct CarbonContext : IMacContext
{
public IntPtr port;
public IntPtr ctx;
public int width;
public int height;
public CarbonContext(IntPtr port, IntPtr ctx, int width, int height)
{
this.port = port;
this.ctx = ctx;
this.width = width;
this.height = height;
}
public void Synchronize()
{
MacSupport.CGContextSynchronize(ctx);
}
public void Release()
{
MacSupport.ReleaseContext(port, ctx);
}
}
internal struct CocoaContext : IMacContext
{
public IntPtr ctx;
public int width;
public int height;
public CocoaContext(IntPtr ctx, int width, int height)
{
this.ctx = ctx;
this.width = width;
this.height = height;
}
public void Synchronize()
{
MacSupport.CGContextSynchronize(ctx);
}
public void Release()
{
MacSupport.CGContextRestoreGState(ctx);
}
}
internal interface IMacContext
{
void Synchronize();
void Release();
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.RecoveryServices.Backup
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Azure.Management.RecoveryServices;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Microsoft.Rest.Azure.OData;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// BackupPoliciesOperations operations.
/// </summary>
internal partial class BackupPoliciesOperations : IServiceOperations<RecoveryServicesBackupClient>, IBackupPoliciesOperations
{
/// <summary>
/// Initializes a new instance of the BackupPoliciesOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal BackupPoliciesOperations(RecoveryServicesBackupClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the RecoveryServicesBackupClient
/// </summary>
public RecoveryServicesBackupClient Client { get; private set; }
/// <summary>
/// Lists of backup policies associated with Recovery Services Vault. API
/// provides pagination parameters to fetch scoped results.
/// </summary>
/// <param name='vaultName'>
/// The name of the recovery services vault.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group where the recovery services vault is
/// present.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<ProtectionPolicyResource>>> ListWithHttpMessagesAsync(string vaultName, string resourceGroupName, ODataQuery<ProtectionPolicyQueryObject> odataQuery = default(ODataQuery<ProtectionPolicyQueryObject>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (vaultName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "vaultName");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("odataQuery", odataQuery);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("vaultName", vaultName);
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}/backupPolicies").ToString();
_url = _url.Replace("{vaultName}", System.Uri.EscapeDataString(vaultName));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (odataQuery != null)
{
var _odataFilter = odataQuery.ToString();
if (!string.IsNullOrEmpty(_odataFilter))
{
_queryParameters.Add(_odataFilter);
}
}
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<ProtectionPolicyResource>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<ProtectionPolicyResource>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Lists of backup policies associated with Recovery Services Vault. API
/// provides pagination parameters to fetch scoped results.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<ProtectionPolicyResource>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<ProtectionPolicyResource>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<ProtectionPolicyResource>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
using System;
using System.Collections;
using BitManipulator;
using Obscur.Core.Cryptography.Support.Math.EllipticCurve.ABC;
using Obscur.Core.Cryptography.Support.Math.EllipticCurve.Endomorphism;
using Obscur.Core.Cryptography.Support.Math.EllipticCurve.Multiplier;
using Obscur.Core.Cryptography.Support.Math.Field;
namespace Obscur.Core.Cryptography.Support.Math.EllipticCurve
{
public abstract class ECCurve
{
public const int COORD_AFFINE = 0;
public const int COORD_HOMOGENEOUS = 1;
public const int COORD_JACOBIAN = 2;
public const int COORD_JACOBIAN_CHUDNOVSKY = 3;
public const int COORD_JACOBIAN_MODIFIED = 4;
public const int COORD_LAMBDA_AFFINE = 5;
public const int COORD_LAMBDA_PROJECTIVE = 6;
public const int COORD_SKEWED = 7;
public static int[] GetAllCoordinateSystems()
{
return new int[]{ COORD_AFFINE, COORD_HOMOGENEOUS, COORD_JACOBIAN, COORD_JACOBIAN_CHUDNOVSKY,
COORD_JACOBIAN_MODIFIED, COORD_LAMBDA_AFFINE, COORD_LAMBDA_PROJECTIVE, COORD_SKEWED };
}
public class Config
{
protected ECCurve outer;
protected int coord;
protected ECEndomorphism endomorphism;
protected ECMultiplier multiplier;
internal Config(ECCurve outer, int coord, ECEndomorphism endomorphism, ECMultiplier multiplier)
{
this.outer = outer;
this.coord = coord;
this.endomorphism = endomorphism;
this.multiplier = multiplier;
}
public Config SetCoordinateSystem(int coord)
{
this.coord = coord;
return this;
}
public Config SetEndomorphism(ECEndomorphism endomorphism)
{
this.endomorphism = endomorphism;
return this;
}
public Config SetMultiplier(ECMultiplier multiplier)
{
this.multiplier = multiplier;
return this;
}
public ECCurve Create()
{
if (!outer.SupportsCoordinateSystem(coord)) {
throw new InvalidOperationException("unsupported coordinate system");
}
ECCurve c = outer.CloneCurve();
if (c == outer) {
throw new InvalidOperationException("implementation returned current curve");
}
c.m_coord = coord;
c.m_endomorphism = endomorphism;
c.m_multiplier = multiplier;
return c;
}
}
protected readonly IFiniteField m_field;
protected ECFieldElement m_a, m_b;
protected BigInteger m_order, m_cofactor;
protected int m_coord = COORD_AFFINE;
protected ECEndomorphism m_endomorphism = null;
protected ECMultiplier m_multiplier = null;
protected ECCurve(IFiniteField field)
{
this.m_field = field;
}
public abstract int FieldSize { get; }
public abstract ECFieldElement FromBigInteger(BigInteger x);
public virtual Config Configure()
{
return new Config(this, this.m_coord, this.m_endomorphism, this.m_multiplier);
}
public virtual ECPoint ValidatePoint(BigInteger x, BigInteger y)
{
ECPoint p = CreatePoint(x, y);
if (!p.IsValid()) {
throw new ArgumentException("Invalid point coordinates");
}
return p;
}
[Obsolete("Per-point compression property will be removed")]
public virtual ECPoint ValidatePoint(BigInteger x, BigInteger y, bool withCompression)
{
ECPoint p = CreatePoint(x, y, withCompression);
if (!p.IsValid()) {
throw new ArgumentException("Invalid point coordinates");
}
return p;
}
public virtual ECPoint CreatePoint(BigInteger x, BigInteger y)
{
return CreatePoint(x, y, false);
}
[Obsolete("Per-point compression property will be removed")]
public virtual ECPoint CreatePoint(BigInteger x, BigInteger y, bool withCompression)
{
return CreateRawPoint(FromBigInteger(x), FromBigInteger(y), withCompression);
}
protected abstract ECCurve CloneCurve();
protected internal abstract ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, bool withCompression);
protected internal abstract ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression);
protected virtual ECMultiplier CreateDefaultMultiplier()
{
GlvEndomorphism glvEndomorphism = m_endomorphism as GlvEndomorphism;
if (glvEndomorphism != null) {
return new GlvMultiplier(this, glvEndomorphism);
}
return new WNafL2RMultiplier();
}
public virtual bool SupportsCoordinateSystem(int coord)
{
return coord == COORD_AFFINE;
}
public virtual PreCompInfo GetPreCompInfo(ECPoint point, string name)
{
CheckPoint(point);
lock (point) {
IDictionary table = point.m_preCompTable;
return table == null ? null : (PreCompInfo)table[name];
}
}
/**
* Adds <code>PreCompInfo</code> for a point on this curve, under a given name. Used by
* <code>ECMultiplier</code>s to save the precomputation for this <code>ECPoint</code> for use
* by subsequent multiplication.
*
* @param point
* The <code>ECPoint</code> to store precomputations for.
* @param name
* A <code>String</code> used to index precomputations of different types.
* @param preCompInfo
* The values precomputed by the <code>ECMultiplier</code>.
*/
public virtual void SetPreCompInfo(ECPoint point, string name, PreCompInfo preCompInfo)
{
CheckPoint(point);
lock (point) {
IDictionary table = point.m_preCompTable;
if (null == table) {
point.m_preCompTable = table = new Hashtable(4);
}
table[name] = preCompInfo;
}
}
public virtual ECPoint ImportPoint(ECPoint p)
{
if (this == p.Curve) {
return p;
}
if (p.IsInfinity) {
return Infinity;
}
// TODO Default behaviour could be improved if the two curves have the same coordinate system by copying any Z coordinates.
p = p.Normalize();
return ValidatePoint(p.XCoord.ToBigInteger(), p.YCoord.ToBigInteger(), p.IsCompressed);
}
/**
* Normalization ensures that any projective coordinate is 1, and therefore that the x, y
* coordinates reflect those of the equivalent point in an affine coordinate system. Where more
* than one point is to be normalized, this method will generally be more efficient than
* normalizing each point separately.
*
* @param points
* An array of points that will be updated in place with their normalized versions,
* where necessary
*/
public virtual void NormalizeAll(ECPoint[] points)
{
CheckPoints(points);
if (this.CoordinateSystem == ECCurve.COORD_AFFINE) {
return;
}
/*
* Figure out which of the points actually need to be normalized
*/
ECFieldElement[] zs = new ECFieldElement[points.Length];
int[] indices = new int[points.Length];
int count = 0;
for (int i = 0; i < points.Length; ++i) {
ECPoint p = points[i];
if (null != p && !p.IsNormalized()) {
zs[count] = p.GetZCoord(0);
indices[count++] = i;
}
}
if (count == 0) {
return;
}
ECAlgorithms.MontgomeryTrick(zs, 0, count);
for (int j = 0; j < count; ++j) {
int index = indices[j];
points[index] = points[index].Normalize(zs[j]);
}
}
public abstract ECPoint Infinity { get; }
public virtual IFiniteField Field
{
get { return m_field; }
}
public virtual ECFieldElement A
{
get { return m_a; }
}
public virtual ECFieldElement B
{
get { return m_b; }
}
public virtual BigInteger Order
{
get { return m_order; }
}
public virtual BigInteger Cofactor
{
get { return m_cofactor; }
}
public virtual int CoordinateSystem
{
get { return m_coord; }
}
protected virtual void CheckPoint(ECPoint point)
{
if (null == point || (this != point.Curve))
throw new ArgumentException("must be non-null and on this curve", "point");
}
protected virtual void CheckPoints(ECPoint[] points)
{
if (points == null)
throw new ArgumentNullException("points");
for (int i = 0; i < points.Length; ++i) {
ECPoint point = points[i];
if (null != point && this != point.Curve)
throw new ArgumentException("entries must be null or on this curve", "points");
}
}
public virtual bool Equals(ECCurve other)
{
if (this == other)
return true;
if (null == other)
return false;
return Field.Equals(other.Field)
&& A.ToBigInteger().Equals(other.A.ToBigInteger())
&& B.ToBigInteger().Equals(other.B.ToBigInteger());
}
public override bool Equals(object obj)
{
return Equals(obj as ECCurve);
}
public override int GetHashCode()
{
return Field.GetHashCode()
^ A.ToBigInteger().GetHashCode().RotateLeft(8)
^ B.ToBigInteger().GetHashCode().RotateLeft(16);
}
protected abstract ECPoint DecompressPoint(int yTilde, BigInteger X1);
public virtual ECEndomorphism GetEndomorphism()
{
return m_endomorphism;
}
/**
* Sets the default <code>ECMultiplier</code>, unless already set.
*/
public virtual ECMultiplier GetMultiplier()
{
lock (this) {
if (this.m_multiplier == null) {
this.m_multiplier = CreateDefaultMultiplier();
}
return this.m_multiplier;
}
}
/**
* Decode a point on this curve from its ASN.1 encoding. The different
* encodings are taken account of, including point compression for
* <code>F<sub>p</sub></code> (X9.62 s 4.2.1 pg 17).
* @return The decoded point.
*/
public virtual ECPoint DecodePoint(byte[] encoded)
{
ECPoint p = null;
int expectedLength = (FieldSize + 7) / 8;
byte type = encoded[0];
switch (type) {
case 0x00: // infinity
{
if (encoded.Length != 1)
throw new ArgumentException("Incorrect length for infinity encoding", "encoded");
p = Infinity;
break;
}
case 0x02: // compressed
case 0x03: // compressed
{
if (encoded.Length != (expectedLength + 1))
throw new ArgumentException("Incorrect length for compressed encoding", "encoded");
int yTilde = type & 1;
BigInteger X = new BigInteger(1, encoded, 1, expectedLength);
p = DecompressPoint(yTilde, X);
break;
}
case 0x04: // uncompressed
{
if (encoded.Length != (2 * expectedLength + 1))
throw new ArgumentException("Incorrect length for uncompressed encoding", "encoded");
BigInteger X = new BigInteger(1, encoded, 1, expectedLength);
BigInteger Y = new BigInteger(1, encoded, 1 + expectedLength, expectedLength);
p = ValidatePoint(X, Y);
break;
}
case 0x06: // hybrid
case 0x07: // hybrid
{
if (encoded.Length != (2 * expectedLength + 1))
throw new ArgumentException("Incorrect length for hybrid encoding", "encoded");
BigInteger X = new BigInteger(1, encoded, 1, expectedLength);
BigInteger Y = new BigInteger(1, encoded, 1 + expectedLength, expectedLength);
if (Y.TestBit(0) != (type == 0x07))
throw new ArgumentException("Inconsistent Y coordinate in hybrid encoding", "encoded");
p = ValidatePoint(X, Y);
break;
}
default:
throw new FormatException("Invalid point encoding " + type);
}
if (type != 0x00 && p.IsInfinity)
throw new ArgumentException("Invalid infinity encoding", "encoded");
return p;
}
}
public abstract class AbstractFpCurve
: ECCurve
{
protected AbstractFpCurve(BigInteger q)
: base(FiniteFields.GetPrimeField(q))
{
}
protected override ECPoint DecompressPoint(int yTilde, BigInteger X1)
{
ECFieldElement x = FromBigInteger(X1);
ECFieldElement rhs = x.Square().Add(A).Multiply(x).Add(B);
ECFieldElement y = rhs.Sqrt();
/*
* If y is not a square, then we haven't got a point on the curve
*/
if (y == null)
throw new ArgumentException("Invalid point compression");
if (y.TestBitZero() != (yTilde == 1)) {
// Use the other root
y = y.Negate();
}
return CreateRawPoint(x, y, true);
}
}
/**
* Elliptic curve over Fp
*/
public class FpCurve
: AbstractFpCurve
{
private const int FP_DEFAULT_COORDS = COORD_JACOBIAN_MODIFIED;
protected readonly BigInteger m_q, m_r;
protected readonly FpPoint m_infinity;
public FpCurve(BigInteger q, BigInteger a, BigInteger b)
: this(q, a, b, null, null)
{
}
public FpCurve(BigInteger q, BigInteger a, BigInteger b, BigInteger order, BigInteger cofactor)
: base(q)
{
this.m_q = q;
this.m_r = FpFieldElement.CalculateResidue(q);
this.m_infinity = new FpPoint(this, null, null);
this.m_a = FromBigInteger_Fp(a);
this.m_b = FromBigInteger_Fp(b);
this.m_order = order;
this.m_cofactor = cofactor;
this.m_coord = FP_DEFAULT_COORDS;
}
protected FpCurve(BigInteger q, BigInteger r, ECFieldElement a, ECFieldElement b)
: this(q, r, a, b, null, null)
{
}
protected FpCurve(BigInteger q, BigInteger r, ECFieldElement a, ECFieldElement b, BigInteger order, BigInteger cofactor)
: base(q)
{
this.m_q = q;
this.m_r = r;
this.m_infinity = new FpPoint(this, null, null);
this.m_a = a;
this.m_b = b;
this.m_order = order;
this.m_cofactor = cofactor;
this.m_coord = FP_DEFAULT_COORDS;
}
protected override ECCurve CloneCurve()
{
return new FpCurve(m_q, m_r, m_a, m_b, m_order, m_cofactor);
}
public override bool SupportsCoordinateSystem(int coord)
{
switch (coord) {
case COORD_AFFINE:
case COORD_HOMOGENEOUS:
case COORD_JACOBIAN:
case COORD_JACOBIAN_MODIFIED:
return true;
default:
return false;
}
}
public virtual BigInteger Q
{
get { return m_q; }
}
public override ECPoint Infinity
{
get { return m_infinity; }
}
public override int FieldSize
{
get { return m_q.BitLength; }
}
public override ECFieldElement FromBigInteger(BigInteger x)
{
return FromBigInteger_Fp(x);
}
protected ECFieldElement FromBigInteger_Fp(BigInteger x)
{
return new FpFieldElement(this.m_q, this.m_r, x);
}
protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, bool withCompression)
{
return new FpPoint(this, x, y, withCompression);
}
protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression)
{
return new FpPoint(this, x, y, zs, withCompression);
}
public override ECPoint ImportPoint(ECPoint p)
{
if (this != p.Curve && this.CoordinateSystem == COORD_JACOBIAN && !p.IsInfinity) {
switch (p.Curve.CoordinateSystem) {
case COORD_JACOBIAN:
case COORD_JACOBIAN_CHUDNOVSKY:
case COORD_JACOBIAN_MODIFIED:
return new FpPoint(this,
FromBigInteger(p.RawXCoord.ToBigInteger()),
FromBigInteger(p.RawYCoord.ToBigInteger()),
new ECFieldElement[] { FromBigInteger(p.GetZCoord(0).ToBigInteger()) },
p.IsCompressed);
default:
break;
}
}
return base.ImportPoint(p);
}
}
public abstract class AbstractF2mCurve
: ECCurve
{
private static IFiniteField BuildField(int m, int k1, int k2, int k3)
{
if (k1 == 0) {
throw new ArgumentException("k1 must be > 0");
}
if (k2 == 0) {
if (k3 != 0) {
throw new ArgumentException("k3 must be 0 if k2 == 0");
}
return FiniteFields.GetBinaryExtensionField(new int[] { 0, k1, m });
}
if (k2 <= k1) {
throw new ArgumentException("k2 must be > k1");
}
if (k3 <= k2) {
throw new ArgumentException("k3 must be > k2");
}
return FiniteFields.GetBinaryExtensionField(new int[] { 0, k1, k2, k3, m });
}
protected AbstractF2mCurve(int m, int k1, int k2, int k3)
: base(BuildField(m, k1, k2, k3))
{
}
}
/**
* Elliptic curves over F2m. The Weierstrass equation is given by
* <code>y<sup>2</sup> + xy = x<sup>3</sup> + ax<sup>2</sup> + b</code>.
*/
public class F2mCurve
: AbstractF2mCurve
{
private const int F2M_DEFAULT_COORDS = COORD_LAMBDA_PROJECTIVE;
/**
* The exponent <code>m</code> of <code>F<sub>2<sup>m</sup></sub></code>.
*/
private readonly int m;
/**
* TPB: The integer <code>k</code> where <code>x<sup>m</sup> +
* x<sup>k</sup> + 1</code> represents the reduction polynomial
* <code>f(z)</code>.<br/>
* PPB: The integer <code>k1</code> where <code>x<sup>m</sup> +
* x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
* represents the reduction polynomial <code>f(z)</code>.<br/>
*/
private readonly int k1;
/**
* TPB: Always set to <code>0</code><br/>
* PPB: The integer <code>k2</code> where <code>x<sup>m</sup> +
* x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
* represents the reduction polynomial <code>f(z)</code>.<br/>
*/
private readonly int k2;
/**
* TPB: Always set to <code>0</code><br/>
* PPB: The integer <code>k3</code> where <code>x<sup>m</sup> +
* x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
* represents the reduction polynomial <code>f(z)</code>.<br/>
*/
private readonly int k3;
/**
* The point at infinity on this curve.
*/
protected readonly F2mPoint m_infinity;
/**
* The parameter <code>μ</code> of the elliptic curve if this is
* a Koblitz curve.
*/
private sbyte mu = 0;
/**
* The auxiliary values <code>s<sub>0</sub></code> and
* <code>s<sub>1</sub></code> used for partial modular reduction for
* Koblitz curves.
*/
private BigInteger[] si = null;
/**
* Constructor for Trinomial Polynomial Basis (TPB).
* @param m The exponent <code>m</code> of
* <code>F<sub>2<sup>m</sup></sub></code>.
* @param k The integer <code>k</code> where <code>x<sup>m</sup> +
* x<sup>k</sup> + 1</code> represents the reduction
* polynomial <code>f(z)</code>.
* @param a The coefficient <code>a</code> in the Weierstrass equation
* for non-supersingular elliptic curves over
* <code>F<sub>2<sup>m</sup></sub></code>.
* @param b The coefficient <code>b</code> in the Weierstrass equation
* for non-supersingular elliptic curves over
* <code>F<sub>2<sup>m</sup></sub></code>.
*/
public F2mCurve(
int m,
int k,
BigInteger a,
BigInteger b)
: this(m, k, 0, 0, a, b, null, null)
{
}
/**
* Constructor for Trinomial Polynomial Basis (TPB).
* @param m The exponent <code>m</code> of
* <code>F<sub>2<sup>m</sup></sub></code>.
* @param k The integer <code>k</code> where <code>x<sup>m</sup> +
* x<sup>k</sup> + 1</code> represents the reduction
* polynomial <code>f(z)</code>.
* @param a The coefficient <code>a</code> in the Weierstrass equation
* for non-supersingular elliptic curves over
* <code>F<sub>2<sup>m</sup></sub></code>.
* @param b The coefficient <code>b</code> in the Weierstrass equation
* for non-supersingular elliptic curves over
* <code>F<sub>2<sup>m</sup></sub></code>.
* @param order The order of the main subgroup of the elliptic curve.
* @param cofactor The cofactor of the elliptic curve, i.e.
* <code>#E<sub>a</sub>(F<sub>2<sup>m</sup></sub>) = h * n</code>.
*/
public F2mCurve(
int m,
int k,
BigInteger a,
BigInteger b,
BigInteger order,
BigInteger cofactor)
: this(m, k, 0, 0, a, b, order, cofactor)
{
}
/**
* Constructor for Pentanomial Polynomial Basis (PPB).
* @param m The exponent <code>m</code> of
* <code>F<sub>2<sup>m</sup></sub></code>.
* @param k1 The integer <code>k1</code> where <code>x<sup>m</sup> +
* x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
* represents the reduction polynomial <code>f(z)</code>.
* @param k2 The integer <code>k2</code> where <code>x<sup>m</sup> +
* x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
* represents the reduction polynomial <code>f(z)</code>.
* @param k3 The integer <code>k3</code> where <code>x<sup>m</sup> +
* x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
* represents the reduction polynomial <code>f(z)</code>.
* @param a The coefficient <code>a</code> in the Weierstrass equation
* for non-supersingular elliptic curves over
* <code>F<sub>2<sup>m</sup></sub></code>.
* @param b The coefficient <code>b</code> in the Weierstrass equation
* for non-supersingular elliptic curves over
* <code>F<sub>2<sup>m</sup></sub></code>.
*/
public F2mCurve(
int m,
int k1,
int k2,
int k3,
BigInteger a,
BigInteger b)
: this(m, k1, k2, k3, a, b, null, null)
{
}
/**
* Constructor for Pentanomial Polynomial Basis (PPB).
* @param m The exponent <code>m</code> of
* <code>F<sub>2<sup>m</sup></sub></code>.
* @param k1 The integer <code>k1</code> where <code>x<sup>m</sup> +
* x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
* represents the reduction polynomial <code>f(z)</code>.
* @param k2 The integer <code>k2</code> where <code>x<sup>m</sup> +
* x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
* represents the reduction polynomial <code>f(z)</code>.
* @param k3 The integer <code>k3</code> where <code>x<sup>m</sup> +
* x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
* represents the reduction polynomial <code>f(z)</code>.
* @param a The coefficient <code>a</code> in the Weierstrass equation
* for non-supersingular elliptic curves over
* <code>F<sub>2<sup>m</sup></sub></code>.
* @param b The coefficient <code>b</code> in the Weierstrass equation
* for non-supersingular elliptic curves over
* <code>F<sub>2<sup>m</sup></sub></code>.
* @param order The order of the main subgroup of the elliptic curve.
* @param cofactor The cofactor of the elliptic curve, i.e.
* <code>#E<sub>a</sub>(F<sub>2<sup>m</sup></sub>) = h * n</code>.
*/
public F2mCurve(
int m,
int k1,
int k2,
int k3,
BigInteger a,
BigInteger b,
BigInteger order,
BigInteger cofactor)
: base(m, k1, k2, k3)
{
this.m = m;
this.k1 = k1;
this.k2 = k2;
this.k3 = k3;
this.m_order = order;
this.m_cofactor = cofactor;
this.m_infinity = new F2mPoint(this, null, null);
if (k1 == 0)
throw new ArgumentException("k1 must be > 0");
if (k2 == 0) {
if (k3 != 0)
throw new ArgumentException("k3 must be 0 if k2 == 0");
} else {
if (k2 <= k1)
throw new ArgumentException("k2 must be > k1");
if (k3 <= k2)
throw new ArgumentException("k3 must be > k2");
}
this.m_a = FromBigInteger(a);
this.m_b = FromBigInteger(b);
this.m_coord = F2M_DEFAULT_COORDS;
}
protected F2mCurve(int m, int k1, int k2, int k3, ECFieldElement a, ECFieldElement b, BigInteger order, BigInteger cofactor)
: base(m, k1, k2, k3)
{
this.m = m;
this.k1 = k1;
this.k2 = k2;
this.k3 = k3;
this.m_order = order;
this.m_cofactor = cofactor;
this.m_infinity = new F2mPoint(this, null, null);
this.m_a = a;
this.m_b = b;
this.m_coord = F2M_DEFAULT_COORDS;
}
protected override ECCurve CloneCurve()
{
return new F2mCurve(m, k1, k2, k3, m_a, m_b, m_order, m_cofactor);
}
public override bool SupportsCoordinateSystem(int coord)
{
switch (coord) {
case COORD_AFFINE:
case COORD_HOMOGENEOUS:
case COORD_LAMBDA_PROJECTIVE:
return true;
default:
return false;
}
}
protected override ECMultiplier CreateDefaultMultiplier()
{
if (IsKoblitz) {
return new WTauNafMultiplier();
}
return base.CreateDefaultMultiplier();
}
public override int FieldSize
{
get { return m; }
}
public override ECFieldElement FromBigInteger(BigInteger x)
{
return new F2mFieldElement(this.m, this.k1, this.k2, this.k3, x);
}
[Obsolete("Per-point compression property will be removed")]
public override ECPoint CreatePoint(BigInteger x, BigInteger y, bool withCompression)
{
ECFieldElement X = FromBigInteger(x), Y = FromBigInteger(y);
switch (this.CoordinateSystem) {
case COORD_LAMBDA_AFFINE:
case COORD_LAMBDA_PROJECTIVE: {
if (X.IsZero) {
if (!Y.Square().Equals(B))
throw new ArgumentException();
} else {
// Y becomes Lambda (X + Y/X) here
Y = Y.Divide(X).Add(X);
}
break;
}
default: {
break;
}
}
return CreateRawPoint(X, Y, withCompression);
}
protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, bool withCompression)
{
return new F2mPoint(this, x, y, withCompression);
}
protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression)
{
return new F2mPoint(this, x, y, zs, withCompression);
}
public override ECPoint Infinity
{
get { return m_infinity; }
}
/**
* Returns true if this is a Koblitz curve (ABC curve).
* @return true if this is a Koblitz curve (ABC curve), false otherwise
*/
public virtual bool IsKoblitz
{
get
{
return m_order != null && m_cofactor != null && m_b.IsOne && (m_a.IsZero || m_a.IsOne);
}
}
/**
* Returns the parameter <code>μ</code> of the elliptic curve.
* @return <code>μ</code> of the elliptic curve.
* @throws ArgumentException if the given ECCurve is not a
* Koblitz curve.
*/
internal virtual sbyte GetMu()
{
if (mu == 0) {
lock (this) {
if (mu == 0) {
mu = Tnaf.GetMu(this);
}
}
}
return mu;
}
/**
* @return the auxiliary values <code>s<sub>0</sub></code> and
* <code>s<sub>1</sub></code> used for partial modular reduction for
* Koblitz curves.
*/
internal virtual BigInteger[] GetSi()
{
if (si == null) {
lock (this) {
if (si == null) {
si = Tnaf.GetSi(this);
}
}
}
return si;
}
protected override ECPoint DecompressPoint(int yTilde, BigInteger X1)
{
ECFieldElement xp = FromBigInteger(X1), yp = null;
if (xp.IsZero) {
yp = m_b.Sqrt();
} else {
ECFieldElement beta = xp.Square().Invert().Multiply(B).Add(A).Add(xp);
ECFieldElement z = SolveQuadradicEquation(beta);
if (z != null) {
if (z.TestBitZero() != (yTilde == 1)) {
z = z.AddOne();
}
switch (this.CoordinateSystem) {
case COORD_LAMBDA_AFFINE:
case COORD_LAMBDA_PROJECTIVE: {
yp = z.Add(xp);
break;
}
default: {
yp = z.Multiply(xp);
break;
}
}
}
}
if (yp == null)
throw new ArgumentException("Invalid point compression");
return CreateRawPoint(xp, yp, true);
}
/**
* Solves a quadratic equation <code>z<sup>2</sup> + z = beta</code>(X9.62
* D.1.6) The other solution is <code>z + 1</code>.
*
* @param beta
* The value to solve the qradratic equation for.
* @return the solution for <code>z<sup>2</sup> + z = beta</code> or
* <code>null</code> if no solution exists.
*/
private ECFieldElement SolveQuadradicEquation(ECFieldElement beta)
{
if (beta.IsZero) {
return beta;
}
ECFieldElement zeroElement = FromBigInteger(BigInteger.Zero);
ECFieldElement z = null;
ECFieldElement gamma = null;
Random rand = new Random();
do {
ECFieldElement t = FromBigInteger(new BigInteger(m, rand));
z = zeroElement;
ECFieldElement w = beta;
for (int i = 1; i <= m - 1; i++) {
ECFieldElement w2 = w.Square();
z = z.Square().Add(w2.Multiply(t));
w = w2.Add(beta);
}
if (!w.IsZero) {
return null;
}
gamma = z.Square().Add(z);
}
while (gamma.IsZero);
return z;
}
public int M
{
get { return m; }
}
/**
* Return true if curve uses a Trinomial basis.
*
* @return true if curve Trinomial, false otherwise.
*/
public bool IsTrinomial()
{
return k2 == 0 && k3 == 0;
}
public int K1
{
get { return k1; }
}
public int K2
{
get { return k2; }
}
public int K3
{
get { return k3; }
}
[Obsolete("Use 'Order' property instead")]
public BigInteger N
{
get { return m_order; }
}
[Obsolete("Use 'Cofactor' property instead")]
public BigInteger H
{
get { return m_cofactor; }
}
}
}
| |
//---------------------------------------------------------------------------
//
// <copyright file="DashStyle.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 DashStyle : Animatable, DUCE.IResource
{
//------------------------------------------------------
//
// Public Methods
//
//------------------------------------------------------
#region Public Methods
/// <summary>
/// Shadows inherited Clone() with a strongly typed
/// version for convenience.
/// </summary>
public new DashStyle Clone()
{
return (DashStyle)base.Clone();
}
/// <summary>
/// Shadows inherited CloneCurrentValue() with a strongly typed
/// version for convenience.
/// </summary>
public new DashStyle CloneCurrentValue()
{
return (DashStyle)base.CloneCurrentValue();
}
#endregion Public Methods
//------------------------------------------------------
//
// Public Properties
//
//------------------------------------------------------
private static void OffsetPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
DashStyle target = ((DashStyle) d);
target.PropertyChanged(OffsetProperty);
}
private static void DashesPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
DashStyle target = ((DashStyle) d);
target.PropertyChanged(DashesProperty);
}
#region Public Properties
/// <summary>
/// Offset - double. Default value is 0.0.
/// </summary>
public double Offset
{
get
{
return (double) GetValue(OffsetProperty);
}
set
{
SetValueInternal(OffsetProperty, value);
}
}
/// <summary>
/// Dashes - DoubleCollection. Default value is new FreezableDefaultValueFactory(DoubleCollection.Empty).
/// </summary>
public DoubleCollection Dashes
{
get
{
return (DoubleCollection) GetValue(DashesProperty);
}
set
{
SetValueInternal(DashesProperty, 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 DashStyle();
}
#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
DoubleCollection vDashes = Dashes;
// Obtain handles for animated properties
DUCE.ResourceHandle hOffsetAnimations = GetAnimationResourceHandle(OffsetProperty, channel);
// Store the count of this resource's contained collections in local variables.
int DashesCount = (vDashes == null) ? 0 : vDashes.Count;
// Pack & send command packet
DUCE.MILCMD_DASHSTYLE data;
unsafe
{
data.Type = MILCMD.MilCmdDashStyle;
data.Handle = _duceResource.GetHandle(channel);
if (hOffsetAnimations.IsNull)
{
data.Offset = Offset;
}
data.hOffsetAnimations = hOffsetAnimations;
data.DashesSize = (uint)(sizeof(Double) * DashesCount);
channel.BeginCommand(
(byte*)&data,
sizeof(DUCE.MILCMD_DASHSTYLE),
(int)(data.DashesSize)
);
// Copy this collection's elements (or their handles) to reserved data
for(int i = 0; i < DashesCount; i++)
{
Double resource = vDashes.Internal_GetItem(i);
channel.AppendCommandData(
(byte*)&resource,
sizeof(Double)
);
}
channel.EndCommand();
}
}
}
DUCE.ResourceHandle DUCE.IResource.AddRefOnChannel(DUCE.Channel channel)
{
using (CompositionEngineLock.Acquire())
{
if (_duceResource.CreateOrAddRefOnChannel(this, channel, System.Windows.Media.Composition.DUCE.ResourceType.TYPE_DASHSTYLE))
{
AddRefOnChannelAnimations(channel);
UpdateResource(channel, true /* skip "on channel" check - we already know that we're on channel */ );
}
return _duceResource.GetHandle(channel);
}
}
void DUCE.IResource.ReleaseOnChannel(DUCE.Channel channel)
{
using (CompositionEngineLock.Acquire())
{
Debug.Assert(_duceResource.IsOnChannel(channel));
if (_duceResource.ReleaseOnChannel(channel))
{
ReleaseOnChannelAnimations(channel);
}
}
}
DUCE.ResourceHandle DUCE.IResource.GetHandle(DUCE.Channel channel)
{
DUCE.ResourceHandle h;
// Reconsider the need for this lock when removing the MultiChannelResource.
using (CompositionEngineLock.Acquire())
{
h = _duceResource.GetHandle(channel);
}
return h;
}
int DUCE.IResource.GetChannelCount()
{
// must already be in composition lock here
return _duceResource.GetChannelCount();
}
DUCE.Channel DUCE.IResource.GetChannel(int index)
{
// in a lock already
return _duceResource.GetChannel(index);
}
#endregion Internal Methods
//------------------------------------------------------
//
// Internal Properties
//
//------------------------------------------------------
#region Internal Properties
//
// This property finds the correct initial size for the _effectiveValues store on the
// current DependencyObject as a performance optimization
//
// This includes:
// Dashes
//
internal override int EffectiveValuesInitialSize
{
get
{
return 1;
}
}
#endregion Internal Properties
//------------------------------------------------------
//
// Dependency Properties
//
//------------------------------------------------------
#region Dependency Properties
/// <summary>
/// The DependencyProperty for the DashStyle.Offset property.
/// </summary>
public static readonly DependencyProperty OffsetProperty;
/// <summary>
/// The DependencyProperty for the DashStyle.Dashes property.
/// </summary>
public static readonly DependencyProperty DashesProperty;
#endregion Dependency Properties
//------------------------------------------------------
//
// Internal Fields
//
//------------------------------------------------------
#region Internal Fields
internal System.Windows.Media.Composition.DUCE.MultiChannelResource _duceResource = new System.Windows.Media.Composition.DUCE.MultiChannelResource();
internal const double c_Offset = 0.0;
internal static DoubleCollection s_Dashes = DoubleCollection.Empty;
#endregion Internal Fields
#region Constructors
//------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
static DashStyle()
{
// 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)
//
Debug.Assert(s_Dashes == null || s_Dashes.IsFrozen,
"Detected context bound default value DashStyle.s_Dashes (See OS Bug #947272).");
// Initializations
Type typeofThis = typeof(DashStyle);
OffsetProperty =
RegisterProperty("Offset",
typeof(double),
typeofThis,
0.0,
new PropertyChangedCallback(OffsetPropertyChanged),
null,
/* isIndependentlyAnimated = */ true,
/* coerceValueCallback */ null);
DashesProperty =
RegisterProperty("Dashes",
typeof(DoubleCollection),
typeofThis,
new FreezableDefaultValueFactory(DoubleCollection.Empty),
new PropertyChangedCallback(DashesPropertyChanged),
null,
/* isIndependentlyAnimated = */ false,
/* coerceValueCallback */ null);
}
#endregion Constructors
}
}
| |
using Bridge.Contract;
using Bridge.Contract.Constants;
using ICSharpCode.NRefactory.CSharp;
using ICSharpCode.NRefactory.TypeSystem;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Object.Net.Utilities;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace Bridge.Translator
{
public class EmitBlock : AbstractEmitterBlock
{
protected FileHelper FileHelper
{
get; set;
}
public EmitBlock(IEmitter emitter)
: base(emitter, null)
{
this.Emitter = emitter;
this.FileHelper = new FileHelper();
}
protected virtual StringBuilder GetOutputForType(ITypeInfo typeInfo, string name, bool isMeta = false)
{
Module module = null;
if (typeInfo != null && typeInfo.Module != null)
{
module = typeInfo.Module;
}
else if (this.Emitter.AssemblyInfo.Module != null)
{
module = this.Emitter.AssemblyInfo.Module;
}
var fileName = typeInfo != null ? typeInfo.FileName : name;
if (fileName.IsEmpty() && this.Emitter.AssemblyInfo.OutputBy != OutputBy.Project)
{
switch (this.Emitter.AssemblyInfo.OutputBy)
{
case OutputBy.ClassPath:
fileName = typeInfo.Type.FullName;
break;
case OutputBy.Class:
fileName = this.GetIteractiveClassPath(typeInfo);
break;
case OutputBy.Module:
fileName = module != null ? module.Name : null;
break;
case OutputBy.NamespacePath:
case OutputBy.Namespace:
fileName = typeInfo.GetNamespace(this.Emitter);
break;
default:
break;
}
var isPathRelated = this.Emitter.AssemblyInfo.OutputBy == OutputBy.ClassPath ||
this.Emitter.AssemblyInfo.OutputBy == OutputBy.NamespacePath;
if (fileName.IsNotEmpty() && isPathRelated)
{
fileName = fileName.Replace('.', System.IO.Path.DirectorySeparatorChar);
if (this.Emitter.AssemblyInfo.StartIndexInName > 0)
{
fileName = fileName.Substring(this.Emitter.AssemblyInfo.StartIndexInName);
}
}
}
if (fileName.IsEmpty() && this.Emitter.AssemblyInfo.FileName != null)
{
fileName = this.Emitter.AssemblyInfo.FileName;
}
if (fileName.IsEmpty() && this.Emitter.Translator.ProjectProperties.AssemblyName != null)
{
fileName = this.Emitter.Translator.ProjectProperties.AssemblyName;
}
if (fileName.IsEmpty())
{
fileName = AssemblyInfo.DEFAULT_FILENAME;
}
// Apply lowerCamelCase to filename if set up in bridge.json (or left default)
if (this.Emitter.AssemblyInfo.FileNameCasing == FileNameCaseConvert.CamelCase)
{
var sepList = new string[] { ".", System.IO.Path.DirectorySeparatorChar.ToString(), "\\", "/" };
// Populate list only with needed separators, as usually we will never have all four of them
var neededSepList = new List<string>();
foreach (var separator in sepList)
{
if (fileName.Contains(separator.ToString()) && !neededSepList.Contains(separator))
{
neededSepList.Add(separator);
}
}
// now, separating the filename string only by the used separators, apply lowerCamelCase
if (neededSepList.Count > 0)
{
foreach (var separator in neededSepList)
{
var stringList = new List<string>();
foreach (var str in fileName.Split(separator[0]))
{
stringList.Add(str.ToLowerCamelCase());
}
fileName = stringList.Join(separator);
}
}
else
{
fileName = fileName.ToLowerCamelCase();
}
}
// Append '.js' extension to file name at translator.Outputs level: this aids in code grouping on files
// when filesystem is not case sensitive.
if (!FileHelper.IsJS(fileName))
{
fileName += Contract.Constants.Files.Extensions.JS;
}
switch (this.Emitter.AssemblyInfo.FileNameCasing)
{
case FileNameCaseConvert.Lowercase:
fileName = fileName.ToLower();
break;
default:
var lcFileName = fileName.ToLower();
// Find a file name that matches (case-insensitive) and use it as file name (if found)
// The used file name will use the same casing of the existing one.
foreach (var existingFile in this.Emitter.Outputs.Keys)
{
if (lcFileName == existingFile.ToLower())
{
fileName = existingFile;
}
}
break;
}
IEmitterOutput output = null;
if (this.Emitter.Outputs.ContainsKey(fileName))
{
output = this.Emitter.Outputs[fileName];
}
else
{
output = new EmitterOutput(fileName) { IsMetadata = isMeta };
this.Emitter.Outputs.Add(fileName, output);
}
this.Emitter.EmitterOutput = output;
if (module == null)
{
if (output.NonModuleDependencies == null)
{
output.NonModuleDependencies = new List<IPluginDependency>();
}
this.Emitter.CurrentDependencies = output.NonModuleDependencies;
return output.NonModuletOutput;
}
if (module.Name == "")
{
module.Name = Bridge.Translator.AssemblyInfo.DEFAULT_FILENAME;
}
if (output.ModuleOutput.ContainsKey(module))
{
this.Emitter.CurrentDependencies = output.ModuleDependencies[module.Name];
return output.ModuleOutput[module];
}
StringBuilder moduleOutput = new StringBuilder();
output.ModuleOutput.Add(module, moduleOutput);
var dependencies = new List<IPluginDependency>();
output.ModuleDependencies.Add(module.Name, dependencies);
if (typeInfo != null && typeInfo.Dependencies.Count > 0)
{
dependencies.AddRange(typeInfo.Dependencies);
}
this.Emitter.CurrentDependencies = dependencies;
return moduleOutput;
}
/// <summary>
/// Gets class path iterating until its root class, writing something like this on a 3-level nested class:
/// RootClass.Lv1ParentClass.Lv2ParentClass.Lv3NestedClass
/// </summary>
/// <param name="typeInfo"></param>
/// <returns></returns>
private string GetIteractiveClassPath(ITypeInfo typeInfo)
{
var fullClassName = typeInfo.Name;
var maxIterations = 100;
var curIterations = 0;
var parent = typeInfo.ParentType;
while (parent != null && curIterations++ < maxIterations)
{
fullClassName = parent.Name + "." + fullClassName;
parent = parent.ParentType;
}
// This should never happen but, just to be sure...
if (curIterations >= maxIterations)
{
throw new EmitterException(typeInfo.TypeDeclaration, "Iteration count for class '" + typeInfo.Type.FullName + "' exceeded " +
maxIterations + " depth iterations until root class!");
}
return fullClassName;
}
private string GetDefaultFileName()
{
var defaultFileName = this.Emitter.Translator.AssemblyInfo.FileName;
if (string.IsNullOrEmpty(defaultFileName))
{
return AssemblyInfo.DEFAULT_FILENAME;
}
return Path.GetFileNameWithoutExtension(defaultFileName);
}
protected override void DoEmit()
{
this.Emitter.Tag = "JS";
this.Emitter.Writers = new Stack<IWriter>();
this.Emitter.Outputs = new EmitterOutputs();
var metas = new Dictionary<IType, JObject>();
var metasOutput = new Dictionary<string, Dictionary<IType, JObject>>();
var nsCache = new Dictionary<string, Dictionary<string, int>>();
this.Emitter.Translator.Plugins.BeforeTypesEmit(this.Emitter, this.Emitter.Types);
this.Emitter.ReflectableTypes = this.GetReflectableTypes();
var reflectedTypes = this.Emitter.ReflectableTypes;
var tmpBuffer = new StringBuilder();
StringBuilder currentOutput = null;
this.Emitter.NamedBoxedFunctions = new Dictionary<IType, Dictionary<string, string>>();
this.Emitter.HasModules = this.Emitter.Types.Any(t => t.Module != null);
foreach (var type in this.Emitter.Types)
{
this.Emitter.Translator.Plugins.BeforeTypeEmit(this.Emitter, type);
this.Emitter.Translator.EmitNode = type.TypeDeclaration;
var typeDef = type.Type.GetDefinition();
this.Emitter.Rules = Rules.Get(this.Emitter, typeDef);
bool isNative;
if (typeDef.Kind == TypeKind.Interface && this.Emitter.Validator.IsExternalInterface(typeDef, out isNative))
{
this.Emitter.Translator.Plugins.AfterTypeEmit(this.Emitter, type);
continue;
}
if (type.IsObjectLiteral)
{
var mode = this.Emitter.Validator.GetObjectCreateMode(this.Emitter.GetTypeDefinition(type.Type));
var ignore = mode == 0 && !type.Type.GetMethods(null, GetMemberOptions.IgnoreInheritedMembers).Any(m => !m.IsConstructor && !m.IsAccessor);
if (this.Emitter.Validator.IsExternalType(typeDef) || ignore)
{
this.Emitter.Translator.Plugins.AfterTypeEmit(this.Emitter, type);
continue;
}
}
this.Emitter.InitEmitter();
ITypeInfo typeInfo;
if (this.Emitter.TypeInfoDefinitions.ContainsKey(type.Key))
{
typeInfo = this.Emitter.TypeInfoDefinitions[type.Key];
type.Module = typeInfo.Module;
type.FileName = typeInfo.FileName;
type.Dependencies = typeInfo.Dependencies;
typeInfo = type;
}
else
{
typeInfo = type;
}
this.Emitter.SourceFileName = type.TypeDeclaration.GetParent<SyntaxTree>().FileName;
this.Emitter.SourceFileNameIndex = this.Emitter.SourceFiles.IndexOf(this.Emitter.SourceFileName);
this.Emitter.Output = this.GetOutputForType(typeInfo, null);
this.Emitter.TypeInfo = type;
type.JsName = BridgeTypes.ToJsName(type.Type, this.Emitter, true, removeScope: false);
if (this.Emitter.Output.Length > 0)
{
this.WriteNewLine();
}
tmpBuffer.Length = 0;
currentOutput = this.Emitter.Output;
this.Emitter.Output = tmpBuffer;
if (this.Emitter.TypeInfo.Module != null)
{
this.Indent();
}
var name = BridgeTypes.ToJsName(type.Type, this.Emitter, true, true, true);
if (type.Type.DeclaringType != null && JS.Reserved.StaticNames.Any(n => String.Equals(name, n, StringComparison.InvariantCulture)))
{
throw new EmitterException(type.TypeDeclaration, "Nested class cannot have such name: " + name + ". Please rename it.");
}
new ClassBlock(this.Emitter, this.Emitter.TypeInfo).Emit();
this.Emitter.Translator.Plugins.AfterTypeEmit(this.Emitter, type);
currentOutput.Append(tmpBuffer.ToString());
this.Emitter.Output = currentOutput;
}
this.Emitter.DisableDependencyTracking = true;
this.EmitNamedBoxedFunctions();
var oldDependencies = this.Emitter.CurrentDependencies;
var oldEmitterOutput = this.Emitter.EmitterOutput;
this.Emitter.NamespacesCache = new Dictionary<string, int>();
if (!this.Emitter.HasModules && this.Emitter.AssemblyInfo.Reflection.Target != MetadataTarget.Type)
{
foreach (var type in this.Emitter.Types)
{
var typeDef = type.Type.GetDefinition();
bool isGlobal = false;
if (typeDef != null)
{
isGlobal = typeDef.Attributes.Any(a => a.AttributeType.FullName == "Bridge.GlobalMethodsAttribute" || a.AttributeType.FullName == "Bridge.MixinAttribute");
}
if (typeDef.FullName != "System.Object")
{
var name = BridgeTypes.ToJsName(typeDef, this.Emitter);
if (name == "Object")
{
continue;
}
}
var isObjectLiteral = this.Emitter.Validator.IsObjectLiteral(typeDef);
var isPlainMode = isObjectLiteral && this.Emitter.Validator.GetObjectCreateMode(this.Emitter.BridgeTypes.Get(type.Key).TypeDefinition) == 0;
if (isPlainMode)
{
continue;
}
if (isGlobal || this.Emitter.TypeInfo.Module != null || reflectedTypes.Any(t => t == type.Type))
{
continue;
}
this.GetOutputForType(type, null);
var fn = Path.GetFileNameWithoutExtension(this.Emitter.EmitterOutput.FileName);
if (!metasOutput.ContainsKey(fn))
{
metasOutput.Add(fn, new Dictionary<IType, JObject>());
}
if (this.Emitter.AssemblyInfo.Reflection.Target == MetadataTarget.File)
{
if (!nsCache.ContainsKey(fn))
{
nsCache.Add(fn, new Dictionary<string, int>());
}
this.Emitter.NamespacesCache = nsCache[fn];
}
var meta = MetadataUtils.ConstructTypeMetadata(typeDef, this.Emitter, true, type.TypeDeclaration.GetParent<SyntaxTree>());
if (meta != null)
{
metas.Add(type.Type, meta);
metasOutput[fn].Add(type.Type, meta);
}
}
}
var defaultFileName = this.GetDefaultFileName();
foreach (var reflectedType in reflectedTypes)
{
var typeDef = reflectedType.GetDefinition();
JObject meta = null;
var bridgeType = this.Emitter.BridgeTypes.Get(reflectedType, true);
string fileName = defaultFileName;
if (bridgeType != null && bridgeType.TypeInfo != null)
{
this.GetOutputForType(bridgeType.TypeInfo, null);
fileName = this.Emitter.EmitterOutput.FileName;
}
fileName = Path.GetFileNameWithoutExtension(fileName);
if (!metasOutput.ContainsKey(fileName))
{
metasOutput.Add(fileName, new Dictionary<IType, JObject>());
}
if (this.Emitter.AssemblyInfo.Reflection.Target == MetadataTarget.File)
{
if (!nsCache.ContainsKey(fileName))
{
nsCache.Add(fileName, new Dictionary<string, int>());
}
this.Emitter.NamespacesCache = nsCache[fileName];
}
if (typeDef != null)
{
var tInfo = this.Emitter.Types.FirstOrDefault(t => t.Type == reflectedType);
SyntaxTree tree = null;
if (tInfo != null && tInfo.TypeDeclaration != null)
{
tree = tInfo.TypeDeclaration.GetParent<SyntaxTree>();
}
if (tInfo != null && tInfo.Module != null || this.Emitter.HasModules || this.Emitter.AssemblyInfo.Reflection.Target == MetadataTarget.Type)
{
continue;
}
meta = MetadataUtils.ConstructTypeMetadata(reflectedType.GetDefinition(), this.Emitter, false, tree);
}
else
{
meta = MetadataUtils.ConstructITypeMetadata(reflectedType, this.Emitter);
}
if (meta != null)
{
metas.Add(reflectedType, meta);
metasOutput[fileName].Add(reflectedType, meta);
}
}
this.Emitter.CurrentDependencies = oldDependencies;
this.Emitter.EmitterOutput = oldEmitterOutput;
var lastOutput = this.Emitter.Output;
var output = this.Emitter.AssemblyInfo.Reflection.Output;
if ((this.Emitter.AssemblyInfo.Reflection.Target == MetadataTarget.File || this.Emitter.AssemblyInfo.Reflection.Target == MetadataTarget.Assembly) && this.Emitter.AssemblyInfo.Module == null)
{
if (string.IsNullOrEmpty(output))
{
if (!string.IsNullOrWhiteSpace(this.Emitter.AssemblyInfo.FileName) &&
this.Emitter.AssemblyInfo.FileName != AssemblyInfo.DEFAULT_FILENAME)
{
output = System.IO.Path.GetFileNameWithoutExtension(this.Emitter.AssemblyInfo.FileName) + ".meta.js";
}
else
{
output = this.Emitter.Translator.ProjectProperties.AssemblyName + ".meta.js";
}
}
this.Emitter.Output = this.GetOutputForType(null, output, true);
this.Emitter.MetaDataOutputName = this.Emitter.EmitterOutput.FileName;
}
var scriptableAttributes = MetadataUtils.GetScriptableAttributes(this.Emitter.Resolver.Compilation.MainAssembly.AssemblyAttributes, this.Emitter, null).ToList();
bool hasMeta = metas.Count > 0 || scriptableAttributes.Count > 0;
if (hasMeta)
{
if (this.Emitter.AssemblyInfo.Reflection.Target == MetadataTarget.Assembly)
{
metasOutput = new Dictionary<string, Dictionary<IType, JObject>>();
metasOutput.Add(defaultFileName, metas);
}
foreach (var metaInfo in metasOutput)
{
if (this.Emitter.AssemblyInfo.Reflection.Target == MetadataTarget.File && this.Emitter.AssemblyInfo.Module == null)
{
var outputName = metaInfo.Key;//Path.GetFileNameWithoutExtension(metaInfo.Key);
if (outputName == defaultFileName)
{
outputName = this.Emitter.MetaDataOutputName;
}
else
{
outputName = outputName + ".meta.js";
}
this.Emitter.Output = this.GetOutputForType(null, outputName, true);
if (nsCache.ContainsKey(metaInfo.Key))
{
this.Emitter.NamespacesCache = nsCache[metaInfo.Key];
} else
{
this.Emitter.NamespacesCache = null;
}
}
this.WriteNewLine();
int pos = 0;
if (metaInfo.Value.Count > 0)
{
this.Write("var $m = " + JS.Types.Bridge.SET_METADATA + ",");
this.WriteNewLine();
this.Write(Bridge.Translator.Emitter.INDENT + "$n = ");
pos = this.Emitter.Output.Length;
this.Write(";");
this.WriteNewLine();
}
foreach (var meta in metaInfo.Value)
{
var metaData = meta.Value;
string typeArgs = "";
if (meta.Key.TypeArguments.Count > 0 && !Helpers.IsIgnoreGeneric(meta.Key, this.Emitter))
{
StringBuilder arr_sb = new StringBuilder();
var comma = false;
foreach (var typeArgument in meta.Key.TypeArguments)
{
if (comma)
{
arr_sb.Append(", ");
}
arr_sb.Append(typeArgument.Name);
comma = true;
}
typeArgs = arr_sb.ToString();
}
this.Write(string.Format("$m(\"{0}\", function ({2}) {{ return {1}; }}, $n);", MetadataUtils.GetTypeName(meta.Key, this.Emitter, false, true, false), metaData.ToString(Formatting.None), typeArgs));
this.WriteNewLine();
}
if (pos > 0)
{
var cache = this.Emitter.NamespacesCache ?? new Dictionary<string, int>();
this.Emitter.Output.Insert(pos, this.Emitter.ToJavaScript(cache.OrderBy(key => key.Value).Select(item => item.Key).ToArray()));
}
}
}
this.Emitter.Output = lastOutput;
if (scriptableAttributes.Count > 0)
{
JArray attrArr = new JArray();
foreach (var a in scriptableAttributes)
{
attrArr.Add(MetadataUtils.ConstructAttribute(a, null, this.Emitter));
}
this.Write(string.Format("$asm.attr= {0};", attrArr.ToString(Formatting.None)));
this.WriteNewLine();
}
//this.RemovePenultimateEmptyLines(true);
this.Emitter.Translator.Plugins.AfterTypesEmit(this.Emitter, this.Emitter.Types);
}
protected virtual void EmitNamedBoxedFunctions()
{
if (this.Emitter.NamedBoxedFunctions.Count > 0)
{
this.Emitter.Comma = false;
this.WriteNewLine();
this.Write("var " + JS.Vars.DBOX_ + " = { };");
this.WriteNewLine();
foreach (var boxedFunction in this.Emitter.NamedBoxedFunctions)
{
var name = BridgeTypes.ToJsName(boxedFunction.Key, this.Emitter, true);
this.WriteNewLine();
this.Write(JS.Funcs.BRIDGE_NS);
this.WriteOpenParentheses();
this.WriteScript(name);
this.Write(", " + JS.Vars.DBOX_ + ")");
this.WriteSemiColon();
this.WriteNewLine();
this.WriteNewLine();
this.Write(JS.Types.Bridge.APPLY + "(" + JS.Vars.DBOX_ + ".");
this.Write(name);
this.Write(", ");
this.BeginBlock();
this.Emitter.Comma = false;
foreach (KeyValuePair<string, string> namedFunction in boxedFunction.Value)
{
this.EnsureComma();
this.Write(namedFunction.Key.ToLowerCamelCase() + ": " + namedFunction.Value);
this.Emitter.Comma = true;
}
this.WriteNewLine();
this.EndBlock();
this.WriteCloseParentheses();
this.WriteSemiColon();
this.WriteNewLine();
}
}
}
private bool SkipFromReflection(ITypeDefinition typeDef, BridgeType bridgeType)
{
var isObjectLiteral = this.Emitter.Validator.IsObjectLiteral(typeDef);
var isPlainMode = isObjectLiteral && this.Emitter.Validator.GetObjectCreateMode(bridgeType.TypeDefinition) == 0;
if (isPlainMode)
{
return true;
}
var skip = typeDef.Attributes.Any(a =>
a.AttributeType.FullName == "Bridge.GlobalMethodsAttribute" ||
a.AttributeType.FullName == "Bridge.NonScriptableAttribute" ||
a.AttributeType.FullName == "Bridge.MixinAttribute");
if (!skip && typeDef.FullName != "System.Object")
{
var name = BridgeTypes.ToJsName(typeDef, this.Emitter);
if (name == "Object" || name == "System.Object" || name == "Function")
{
return true;
}
}
return skip;
}
public IType[] GetReflectableTypes()
{
var config = this.Emitter.AssemblyInfo.Reflection;
var configInternal = ((AssemblyInfo)this.Emitter.AssemblyInfo).ReflectionInternal;
//bool? enable = config.Disabled.HasValue ? !config.Disabled : (configInternal.Disabled.HasValue ? !configInternal.Disabled : true);
bool? enable = null;
if (config.Disabled.HasValue && !config.Disabled.Value)
{
enable = true;
}
else if (configInternal.Disabled.HasValue)
{
enable = !configInternal.Disabled.Value;
}
else if (!config.Disabled.HasValue)
{
enable = true;
}
TypeAccessibility? typeAccessibility = config.TypeAccessibility.HasValue ? config.TypeAccessibility : (configInternal.TypeAccessibility.HasValue ? configInternal.TypeAccessibility : null);
string filter = !string.IsNullOrEmpty(config.Filter) ? config.Filter : (!string.IsNullOrEmpty(configInternal.Filter) ? configInternal.Filter : null);
var hasSettings = !string.IsNullOrEmpty(config.Filter) ||
config.MemberAccessibility != null ||
config.TypeAccessibility.HasValue ||
!string.IsNullOrEmpty(configInternal.Filter) ||
configInternal.MemberAccessibility != null ||
configInternal.TypeAccessibility.HasValue;
if (enable.HasValue && !enable.Value)
{
return new IType[0];
}
if (enable.HasValue && enable.Value && !hasSettings)
{
this.Emitter.IsAnonymousReflectable = true;
}
if (typeAccessibility.HasValue)
{
this.Emitter.IsAnonymousReflectable = typeAccessibility.Value.HasFlag(TypeAccessibility.Anonymous);
}
List<IType> reflectTypes = new List<IType>();
var thisAssemblyDef = this.Emitter.Translator.AssemblyDefinition;
foreach (var bridgeType in this.Emitter.BridgeTypes)
{
var result = false;
var type = bridgeType.Value.Type;
var typeDef = type.GetDefinition();
//var thisAssembly = bridgeType.Value.TypeInfo != null;
var thisAssembly = bridgeType.Value.TypeDefinition?.Module.Assembly.Equals(thisAssemblyDef) ?? false;
var external = typeDef != null && this.Emitter.Validator.IsExternalType(typeDef);
if (enable.HasValue && enable.Value && !hasSettings && thisAssembly)
{
result = true;
}
if (typeDef != null)
{
var skip = this.SkipFromReflection(typeDef, bridgeType.Value);
if (skip)
{
continue;
}
var attr = typeDef.Attributes.FirstOrDefault(a => a.AttributeType.FullName == "Bridge.ReflectableAttribute");
if (attr == null)
{
attr = Helpers.GetInheritedAttribute(typeDef, "Bridge.ReflectableAttribute");
if (attr != null)
{
if (attr.NamedArguments.Count > 0 && attr.NamedArguments.Any(arg => arg.Key.Name == "Inherits"))
{
var inherits = attr.NamedArguments.First(arg => arg.Key.Name == "Inherits");
if (!(bool) inherits.Value.ConstantValue)
{
attr = null;
}
}
else
{
attr = null;
}
}
}
if (attr != null)
{
if (attr.PositionalArguments.Count == 0)
{
if (thisAssembly)
{
reflectTypes.Add(type);
continue;
}
}
else
{
var value = attr.PositionalArguments.First().ConstantValue;
if ((!(value is bool) || (bool)value) && thisAssembly)
{
reflectTypes.Add(type);
}
continue;
}
}
if (external && attr == null)
{
if (!string.IsNullOrWhiteSpace(filter) && EmitBlock.MatchFilter(type, filter, thisAssembly, result))
{
reflectTypes.Add(type);
}
continue;
}
}
if (typeAccessibility.HasValue && thisAssembly)
{
result = false;
if (typeAccessibility.Value.HasFlag(TypeAccessibility.All))
{
result = true;
}
if (typeAccessibility.Value.HasFlag(TypeAccessibility.Anonymous) && type.Kind == TypeKind.Anonymous)
{
result = true;
}
if (typeAccessibility.Value.HasFlag(TypeAccessibility.NonAnonymous) && type.Kind != TypeKind.Anonymous)
{
result = true;
}
if (typeAccessibility.Value.HasFlag(TypeAccessibility.NonPrivate) && (typeDef == null || !typeDef.IsPrivate))
{
result = true;
}
if (typeAccessibility.Value.HasFlag(TypeAccessibility.Public) && (typeDef == null || typeDef.IsPublic || typeDef.IsInternal))
{
result = true;
}
if (typeAccessibility.Value.HasFlag(TypeAccessibility.None))
{
continue;
}
}
if (!string.IsNullOrEmpty(filter))
{
result = EmitBlock.MatchFilter(type, filter, thisAssembly, result);
if (!result)
{
continue;
}
}
if (result)
{
reflectTypes.Add(type);
}
}
return reflectTypes.ToArray();
}
private static bool MatchFilter(IType type, string filters, bool thisAssembly, bool def)
{
var fullName = type.FullName;
var parts = filters.Split(new char[] {';'}, StringSplitOptions.RemoveEmptyEntries);
var result = def;
foreach (var part in parts)
{
string pattern;
string filter = part;
bool exclude = filter.StartsWith("!");
if (exclude)
{
filter = filter.Substring(1);
}
if (filter == "this")
{
result = !exclude && thisAssembly;
}
else
{
if (filter.StartsWith("regex:"))
{
pattern = filter.Substring(6);
}
else
{
pattern = "^" + Regex.Escape(filter).Replace("\\*", ".*").Replace("\\?", ".") + "$";
}
if (Regex.IsMatch(fullName, pattern))
{
result = !exclude;
}
}
}
return result;
}
}
}
| |
// <copyright file="File.cs" company="Adrian Mos">
// Copyright (c) Adrian Mos with all rights reserved. Part of the IX Framework.
// </copyright>
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using IX.StandardExtensions.Contracts;
using IX.StandardExtensions.Threading;
using JetBrains.Annotations;
using FSFile = System.IO.File;
// ReSharper disable once CheckNamespace
namespace IX.System.IO
{
/// <summary>
/// A class for implementing <see cref="IFile" /> with <see cref="System.IO.File" />.
/// </summary>
/// <seealso cref="IX.System.IO.IFile" />
/// <seealso cref="System.IO.File" />
[PublicAPI]
[SuppressMessage(
"Performance",
"HAA0603:Delegate allocation from a method group",
Justification = "We're doing multithreaded, so this can't really be done in any other way.")]
public class File : IFile
{
/// <summary>
/// Appends lines of text to a specified file path.
/// </summary>
/// <param name="path">The path of the file.</param>
/// <param name="contents">The contents.</param>
/// <param name="encoding">The encoding to use.</param>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="path" /> or <paramref name="contents" /> is <see langword="null" /> (<see langword="Nothing" /> in
/// Visual Basic).
/// </exception>
/// <remarks>
/// This operation always requires an encoding to be used. If <paramref name="encoding" /> is set to
/// <see langword="null" />, an implementation-specific
/// encoding will be used.
/// </remarks>
public void AppendAllLines(
string path,
IEnumerable<string> contents,
Encoding encoding = null)
{
Contract.RequiresNotNullOrWhitespace(
path,
nameof(path));
Contract.RequiresNotNull(
in contents,
nameof(contents));
if (encoding == null)
{
FSFile.AppendAllLines(
path,
contents);
}
else
{
FSFile.AppendAllLines(
path,
contents,
encoding);
}
}
/// <summary>
/// Asynchronously appends lines of text to a specified file path.
/// </summary>
/// <param name="path">The path of the file.</param>
/// <param name="contents">The contents.</param>
/// <param name="encoding">The encoding to use.</param>
/// <param name="cancellationToken">The cancellation token to stop this operation.</param>
/// <returns>A task representing the current operation.</returns>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="path" /> or <paramref name="contents" /> is
/// <see langword="null" /> (<see langword="Nothing" /> in Visual Basic).
/// </exception>
/// <remarks>
/// This operation always requires an encoding to be used. If <paramref name="encoding" /> is set to
/// <see langword="null" />, an implementation-specific
/// encoding will be used.
/// </remarks>
public Task AppendAllLinesAsync(
string path,
IEnumerable<string> contents,
Encoding encoding = null,
CancellationToken cancellationToken = default)
{
Contract.RequiresNotNullOrWhitespace(
path,
nameof(path));
Contract.RequiresNotNull(
in contents,
nameof(contents));
return encoding == null
? Fire.OnThreadPool(
FSFile.AppendAllLines,
path,
contents,
cancellationToken)
: Fire.OnThreadPool(
FSFile.AppendAllLines,
path,
contents,
encoding,
cancellationToken);
}
/// <summary>
/// Appends text to a specified file path.
/// </summary>
/// <param name="path">The path of the file.</param>
/// <param name="contents">The contents.</param>
/// <param name="encoding">The encoding to use.</param>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="path" /> or <paramref name="contents" /> is <see langword="null" /> (<see langword="Nothing" /> in
/// Visual Basic).
/// </exception>
/// <remarks>
/// This operation always requires an encoding to be used. If <paramref name="encoding" /> is set to
/// <see langword="null" />, an implementation-specific
/// encoding will be used.
/// </remarks>
public void AppendAllText(
string path,
string contents,
Encoding encoding = null)
{
Contract.RequiresNotNullOrWhitespace(
path,
nameof(path));
Contract.RequiresNotNullOrWhitespace(
contents,
nameof(contents));
if (encoding == null)
{
FSFile.AppendAllText(
path,
contents);
}
else
{
FSFile.AppendAllText(
path,
contents,
encoding);
}
}
/// <summary>
/// Asynchronously appends text to a specified file path.
/// </summary>
/// <param name="path">The path of the file.</param>
/// <param name="contents">The contents.</param>
/// <param name="encoding">The encoding to use.</param>
/// <param name="cancellationToken">The cancellation token to stop this operation.</param>
/// <returns>A task representing the current operation.</returns>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="path" /> or <paramref name="contents" /> is <see langword="null" /> (<see langword="Nothing" /> in
/// Visual Basic).
/// </exception>
/// <remarks>
/// This operation always requires an encoding to be used. If <paramref name="encoding" /> is set to
/// <see langword="null" />, an implementation-specific
/// encoding will be used.
/// </remarks>
public Task AppendAllTextAsync(
string path,
string contents,
Encoding encoding = null,
CancellationToken cancellationToken = default)
{
Contract.RequiresNotNullOrWhitespace(
path,
nameof(path));
Contract.RequiresNotNullOrWhitespace(
contents,
nameof(contents));
return encoding == null
? Fire.OnThreadPool(
FSFile.AppendAllText,
path,
contents,
cancellationToken)
: Fire.OnThreadPool(
FSFile.AppendAllText,
path,
contents,
encoding,
cancellationToken);
}
/// <summary>
/// Opens a <see cref="T:System.IO.StreamWriter" /> to append text to a file.
/// </summary>
/// <param name="path">The path of the file.</param>
/// <returns>
/// A <see cref="T:System.IO.StreamWriter" /> that can write to a file.
/// </returns>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="path" /> is <see langword="null" /> (<see langword="Nothing" /> in Visual Basic).
/// </exception>
public StreamWriter AppendText(string path)
{
Contract.RequiresNotNullOrWhitespace(
path,
nameof(path));
return FSFile.AppendText(path);
}
/// <summary>
/// Copies a file to another.
/// </summary>
/// <param name="sourceFileName">The source file.</param>
/// <param name="destFileName">The destination file.</param>
/// <param name="overwrite">
/// If <see langword="true" />, overwrites the destination file, if one exists, otherwise throws an exception. If a
/// destination file doesn't
/// exist, this parameter is ignored.
/// </param>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="sourceFileName" /> or <paramref name="destFileName" /> is <see langword="null" /> (
/// <see langword="Nothing" /> in Visual Basic).
/// </exception>
public void Copy(
string sourceFileName,
string destFileName,
bool overwrite = false)
{
Contract.RequiresNotNullOrWhitespace(
sourceFileName,
nameof(sourceFileName));
Contract.RequiresNotNullOrWhitespace(
destFileName,
nameof(destFileName));
FSFile.Copy(
sourceFileName,
destFileName,
overwrite);
}
/// <summary>
/// Asynchronously copies a file to another.
/// </summary>
/// <param name="sourceFileName">The source file.</param>
/// <param name="destinationFileName">The destination file.</param>
/// <param name="overwrite">
/// If <see langword="true" />, overwrites the destination file, if one exists, otherwise throws an exception. If a
/// destination file doesn't
/// exist, this parameter is ignored.
/// </param>
/// <param name="cancellationToken">The cancellation token to stop this operation.</param>
/// <returns>A task representing the current operation.</returns>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="sourceFileName" /> or <paramref name="destinationFileName" /> is <see langword="null" /> (
/// <see langword="Nothing" /> in Visual Basic).
/// </exception>
public Task CopyAsync(
string sourceFileName,
string destinationFileName,
bool overwrite = false,
CancellationToken cancellationToken = default)
{
Contract.RequiresNotNullOrWhitespace(
sourceFileName,
nameof(sourceFileName));
Contract.RequiresNotNullOrWhitespace(
destinationFileName,
nameof(destinationFileName));
return Fire.OnThreadPool(
FSFile.Copy,
sourceFileName,
destinationFileName,
overwrite,
cancellationToken);
}
/// <summary>
/// Creates a file.
/// </summary>
/// <param name="path">The path of the file.</param>
/// <param name="bufferSize">The buffer size to use. Default is 4 kilobytes.</param>
/// <returns>
/// A <see cref="T:System.IO.Stream" /> that can read from and write to a file.
/// </returns>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="path" /> is <see langword="null" /> (<see langword="Nothing" /> in Visual Basic).
/// </exception>
/// <exception cref="T:System.ArgumentOutOfRangeException">
/// <paramref name="bufferSize" /> is less than or equal to 0.
/// </exception>
public Stream Create(
string path,
int bufferSize = 4096)
{
Contract.RequiresNotNullOrWhitespace(
path,
nameof(path));
Contract.RequiresPositive(
in bufferSize,
nameof(bufferSize));
return FSFile.Create(
path,
bufferSize);
}
/// <summary>
/// Opens a <see cref="T:System.IO.StreamWriter" /> to write text to a file.
/// </summary>
/// <param name="path">The path of the file.</param>
/// <returns>
/// A <see cref="T:System.IO.StreamWriter" /> that can write to a file.
/// </returns>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="path" /> is <see langword="null" /> (<see langword="Nothing" /> in Visual Basic).
/// </exception>
public StreamWriter CreateText(string path)
{
Contract.RequiresNotNullOrWhitespace(
path,
nameof(path));
return FSFile.CreateText(path);
}
/// <summary>
/// Deletes a file.
/// </summary>
/// <param name="path">The path of the file.</param>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="path" /> is <see langword="null" /> (<see langword="Nothing" /> in Visual Basic).
/// </exception>
public void Delete(string path)
{
Contract.RequiresNotNullOrWhitespace(
path,
nameof(path));
FSFile.Delete(path);
}
/// <summary>
/// Asynchronously deletes a file.
/// </summary>
/// <param name="path">The path of the file.</param>
/// <param name="cancellationToken">The cancellation token to stop this operation.</param>
/// <returns>A task representing the current operation.</returns>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="path" /> is <see langword="null" /> (<see langword="Nothing" /> in Visual Basic).
/// </exception>
public Task DeleteAsync(
string path,
CancellationToken cancellationToken = default)
{
Contract.RequiresNotNullOrWhitespace(
path,
nameof(path));
return Fire.OnThreadPool(
FSFile.Delete,
path,
cancellationToken);
}
/// <summary>
/// Checks whether a file exists and is accessible.
/// </summary>
/// <param name="path">The path of the file.</param>
/// <returns>
/// Returns <see langword="true" /> if the specified file exists and is accessible, <see langword="false" /> otherwise.
/// </returns>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="path" /> is <see langword="null" /> (<see langword="Nothing" /> in Visual Basic).
/// </exception>
public bool Exists(string path)
{
Contract.RequiresNotNullOrWhitespace(
path,
nameof(path));
return FSFile.Exists(path);
}
/// <summary>
/// Asynchronously checks whether a file exists and is accessible.
/// </summary>
/// <param name="path">The path of the file.</param>
/// <param name="cancellationToken">The cancellation token to stop this operation.</param>
/// <returns>
/// Returns <see langword="true" /> if the specified file exists and is accessible, <see langword="false" /> otherwise.
/// </returns>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="path" /> is <see langword="null" /> (<see langword="Nothing" /> in Visual Basic).
/// </exception>
public Task<bool> ExistsAsync(
string path,
CancellationToken cancellationToken = default)
{
Contract.RequiresNotNullOrWhitespace(
path,
nameof(path));
return Fire.OnThreadPool(
FSFile.Exists,
path,
cancellationToken);
}
/// <summary>
/// Gets a specific file's creation time, in UTC.
/// </summary>
/// <param name="path">The path of the file.</param>
/// <returns>
/// A <see cref="T:System.DateTime" /> in UTC.
/// </returns>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="path" /> is <see langword="null" /> (<see langword="Nothing" /> in Visual Basic).
/// </exception>
public DateTime GetCreationTime(string path)
{
Contract.RequiresNotNullOrWhitespace(
path,
nameof(path));
return FSFile.GetCreationTimeUtc(path);
}
/// <summary>
/// Asynchronously gets a specific file's creation time, in UTC.
/// </summary>
/// <param name="path">The path of the file.</param>
/// <param name="cancellationToken">The cancellation token to stop this operation.</param>
/// <returns>
/// A <see cref="T:System.DateTime" /> in UTC.
/// </returns>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="path" /> is <see langword="null" /> (<see langword="Nothing" /> in Visual Basic).
/// </exception>
public Task<DateTime> GetCreationTimeAsync(
string path,
CancellationToken cancellationToken = default)
{
Contract.RequiresNotNullOrWhitespace(
path,
nameof(path));
return Fire.OnThreadPool(
FSFile.GetCreationTimeUtc,
path,
cancellationToken);
}
/// <summary>
/// Gets a specific file's last access time, in UTC.
/// </summary>
/// <param name="path">The path of the file.</param>
/// <returns>
/// A <see cref="T:System.DateTime" /> in UTC.
/// </returns>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="path" /> is <see langword="null" /> (<see langword="Nothing" /> in Visual Basic).
/// </exception>
public DateTime GetLastAccessTime(string path)
{
Contract.RequiresNotNullOrWhitespace(
path,
nameof(path));
return FSFile.GetLastAccessTimeUtc(path);
}
/// <summary>
/// Asynchronously gets a specific file's last access time, in UTC.
/// </summary>
/// <param name="path">The path of the file.</param>
/// <param name="cancellationToken">The cancellation token to stop this operation.</param>
/// <returns>
/// A <see cref="T:System.DateTime" /> in UTC.
/// </returns>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="path" /> is <see langword="null" /> (<see langword="Nothing" /> in Visual Basic).
/// </exception>
public Task<DateTime> GetLastAccessTimeAsync(
string path,
CancellationToken cancellationToken = default)
{
Contract.RequiresNotNullOrWhitespace(
path,
nameof(path));
return Fire.OnThreadPool(
FSFile.GetLastAccessTimeUtc,
path,
cancellationToken);
}
/// <summary>
/// Gets a specific file's last write time, in UTC.
/// </summary>
/// <param name="path">The path of the file.</param>
/// <returns>
/// A <see cref="T:System.DateTime" /> in UTC.
/// </returns>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="path" /> is <see langword="null" /> (<see langword="Nothing" /> in Visual Basic).
/// </exception>
public DateTime GetLastWriteTime(string path)
{
Contract.RequiresNotNullOrWhitespace(
path,
nameof(path));
return FSFile.GetLastWriteTimeUtc(path);
}
/// <summary>
/// Asynchronously gets a specific file's last write time, in UTC.
/// </summary>
/// <param name="path">The path of the file.</param>
/// <param name="cancellationToken">The cancellation token to stop this operation.</param>
/// <returns>
/// A <see cref="T:System.DateTime" /> in UTC.
/// </returns>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="path" /> is <see langword="null" /> (<see langword="Nothing" /> in Visual Basic).
/// </exception>
public Task<DateTime> GetLastWriteTimeAsync(
string path,
CancellationToken cancellationToken = default)
{
Contract.RequiresNotNullOrWhitespace(
path,
nameof(path));
return Fire.OnThreadPool(
FSFile.GetLastWriteTimeUtc,
path,
cancellationToken);
}
/// <summary>
/// Move a file.
/// </summary>
/// <param name="sourceFileName">The source file name.</param>
/// <param name="destFileName">The destination file name.</param>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="sourceFileName" /> or <paramref name="destFileName" /> is <see langword="null" /> (
/// <see langword="Nothing" /> in Visual Basic).
/// </exception>
public void Move(
string sourceFileName,
string destFileName)
{
Contract.RequiresNotNullOrWhitespace(
sourceFileName,
nameof(sourceFileName));
Contract.RequiresNotNullOrWhitespace(
destFileName,
nameof(destFileName));
FSFile.Move(
sourceFileName,
destFileName);
}
/// <summary>
/// Asynchronously move a file.
/// </summary>
/// <param name="sourceFileName">The source file name.</param>
/// <param name="destinationFileName">The destination file name.</param>
/// <param name="cancellationToken">The cancellation token to stop this operation.</param>
/// <returns>A task representing the current operation.</returns>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="sourceFileName" /> or <paramref name="destinationFileName" /> is <see langword="null" /> (
/// <see langword="Nothing" /> in Visual Basic).
/// </exception>
public Task MoveAsync(
string sourceFileName,
string destinationFileName,
CancellationToken cancellationToken = default)
{
Contract.RequiresNotNullOrWhitespace(
sourceFileName,
nameof(sourceFileName));
Contract.RequiresNotNullOrWhitespace(
destinationFileName,
nameof(destinationFileName));
return Fire.OnThreadPool(
FSFile.Move,
sourceFileName,
destinationFileName,
cancellationToken);
}
/// <summary>
/// Opens a <see cref="T:System.IO.Stream" /> to read from a file.
/// </summary>
/// <param name="path">The path of the file.</param>
/// <returns>
/// A <see cref="T:System.IO.Stream" /> that can read from a file.
/// </returns>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="path" /> is <see langword="null" /> (<see langword="Nothing" /> in Visual Basic).
/// </exception>
public Stream OpenRead(string path)
{
Contract.RequiresNotNullOrWhitespace(
path,
nameof(path));
return FSFile.OpenRead(path);
}
/// <summary>
/// Opens a <see cref="T:System.IO.StreamReader" /> to read text from a file.
/// </summary>
/// <param name="path">The path of the file.</param>
/// <returns>
/// A <see cref="T:System.IO.StreamReader" /> that can read from a file.
/// </returns>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="path" /> is <see langword="null" /> (<see langword="Nothing" /> in Visual Basic).
/// </exception>
public StreamReader OpenText(string path)
{
Contract.RequiresNotNullOrWhitespace(
path,
nameof(path));
return FSFile.OpenText(path);
}
/// <summary>
/// Opens a <see cref="T:System.IO.Stream" /> to write to a file.
/// </summary>
/// <param name="path">The path of the file.</param>
/// <returns>
/// A <see cref="T:System.IO.Stream" /> that can write to a file.
/// </returns>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="path" /> is <see langword="null" /> (<see langword="Nothing" /> in Visual Basic).
/// </exception>
public Stream OpenWrite(string path)
{
Contract.RequiresNotNullOrWhitespace(
path,
nameof(path));
return FSFile.OpenWrite(path);
}
/// <summary>
/// Reads the entire contents of a file.
/// </summary>
/// <param name="path">The path of the file.</param>
/// <returns>
/// The contents of a file, in binary.
/// </returns>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="path" /> is <see langword="null" /> (<see langword="Nothing" /> in Visual Basic).
/// </exception>
public byte[] ReadAllBytes(string path)
{
Contract.RequiresNotNullOrWhitespace(
path,
nameof(path));
return FSFile.ReadAllBytes(path);
}
/// <summary>
/// Asynchronously reads the entire contents of a file.
/// </summary>
/// <param name="path">The path of the file.</param>
/// <param name="cancellationToken">The cancellation token to stop this operation.</param>
/// <returns>
/// The contents of a file, in binary.
/// </returns>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="path" /> is <see langword="null" /> (<see langword="Nothing" /> in Visual Basic).
/// </exception>
public Task<byte[]> ReadAllBytesAsync(
string path,
CancellationToken cancellationToken = default)
{
Contract.RequiresNotNullOrWhitespace(
path,
nameof(path));
return Fire.OnThreadPool(
FSFile.ReadAllBytes,
path,
cancellationToken);
}
/// <summary>
/// Reads the entire contents of a file and splits them by end-of-line markers.
/// </summary>
/// <param name="path">The path of the file.</param>
/// <param name="encoding">The encoding to use.</param>
/// <returns>
/// An array of <see cref="T:System.String" />.
/// </returns>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="path" /> is <see langword="null" /> (<see langword="Nothing" /> in Visual Basic).
/// </exception>
/// <remarks>
/// This operation always requires an encoding to be used. If <paramref name="encoding" /> is set to
/// <see langword="null" />, an implementation-specific
/// encoding will be used.
/// </remarks>
public string[] ReadAllLines(
string path,
Encoding encoding = null)
{
Contract.RequiresNotNullOrWhitespace(
path,
nameof(path));
return encoding == null
? FSFile.ReadAllLines(path)
: FSFile.ReadAllLines(
path,
encoding);
}
/// <summary>
/// Asynchronously reads the entire contents of a file and splits them by end-of-line markers.
/// </summary>
/// <param name="path">The path of the file.</param>
/// <param name="encoding">The encoding to use.</param>
/// <param name="cancellationToken">The cancellation token to stop this operation.</param>
/// <returns>
/// An array of <see cref="T:System.String" />.
/// </returns>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="path" /> is <see langword="null" /> (<see langword="Nothing" /> in Visual Basic).
/// </exception>
/// <remarks>
/// This operation always requires an encoding to be used. If <paramref name="encoding" /> is set to
/// <see langword="null" />, an implementation-specific
/// encoding will be used.
/// </remarks>
public Task<string[]> ReadAllLinesAsync(
string path,
Encoding encoding = null,
CancellationToken cancellationToken = default)
{
Contract.RequiresNotNullOrWhitespace(
path,
nameof(path));
return encoding == null
? Fire.OnThreadPool(
FSFile.ReadAllLines,
path,
cancellationToken)
: Fire.OnThreadPool(
FSFile.ReadAllLines,
path,
encoding,
cancellationToken);
}
/// <summary>
/// Reads the entire contents of a file as text.
/// </summary>
/// <param name="path">The path of the file.</param>
/// <param name="encoding">The encoding to use.</param>
/// <returns>
/// The entire file contents as a string.
/// </returns>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="path" /> is <see langword="null" /> (<see langword="Nothing" /> in Visual Basic).
/// </exception>
/// <remarks>
/// This operation always requires an encoding to be used. If <paramref name="encoding" /> is set to
/// <see langword="null" />, an implementation-specific
/// encoding will be used.
/// </remarks>
public string ReadAllText(
string path,
Encoding encoding = null)
{
Contract.RequiresNotNullOrWhitespace(
path,
nameof(path));
return encoding == null
? FSFile.ReadAllText(path)
: FSFile.ReadAllText(
path,
encoding);
}
/// <summary>
/// Asynchronously reads the entire contents of a file as text.
/// </summary>
/// <param name="path">The path of the file.</param>
/// <param name="encoding">The encoding to use.</param>
/// <param name="cancellationToken">The cancellation token to stop this operation.</param>
/// <returns>
/// The entire file contents as a string.
/// </returns>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="path" /> is <see langword="null" /> (<see langword="Nothing" /> in Visual Basic).
/// </exception>
/// <remarks>
/// This operation always requires an encoding to be used. If <paramref name="encoding" /> is set to
/// <see langword="null" />, an implementation-specific
/// encoding will be used.
/// </remarks>
public Task<string> ReadAllTextAsync(
string path,
Encoding encoding = null,
CancellationToken cancellationToken = default)
{
Contract.RequiresNotNullOrWhitespace(
path,
nameof(path));
return encoding == null
? Fire.OnThreadPool(
FSFile.ReadAllText,
path,
cancellationToken)
: Fire.OnThreadPool(
FSFile.ReadAllText,
path,
encoding,
cancellationToken);
}
/// <summary>
/// Reads file contents as text line by line.
/// </summary>
/// <param name="path">The path of the file.</param>
/// <param name="encoding">The encoding to use.</param>
/// <returns>
/// An enumerable of strings, each representing one line of text.
/// </returns>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="path" /> is <see langword="null" /> (<see langword="Nothing" /> in Visual Basic).
/// </exception>
/// <remarks>
/// This operation always requires an encoding to be used. If <paramref name="encoding" /> is set to
/// <see langword="null" />, an implementation-specific
/// encoding will be used.
/// </remarks>
public IEnumerable<string> ReadLines(
string path,
Encoding encoding = null)
{
Contract.RequiresNotNullOrWhitespace(
path,
nameof(path));
return encoding == null
? FSFile.ReadLines(path)
: FSFile.ReadLines(
path,
encoding);
}
/// <summary>
/// Sets the file's creation time.
/// </summary>
/// <param name="path">The path of the file.</param>
/// <param name="creationTime">A <see cref="T:System.DateTime" /> with the file attribute to set.</param>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="path" /> is <see langword="null" /> (<see langword="Nothing" /> in Visual Basic).
/// </exception>
public void SetCreationTime(
string path,
DateTime creationTime)
{
Contract.RequiresNotNullOrWhitespace(
path,
nameof(path));
FSFile.SetCreationTimeUtc(
path,
creationTime);
}
/// <summary>
/// Asynchronously sets the file's creation time.
/// </summary>
/// <param name="path">The path of the file.</param>
/// <param name="creationTime">A <see cref="T:System.DateTime" /> with the file attribute to set.</param>
/// <param name="cancellationToken">The cancellation token to stop this operation.</param>
/// <returns>A task representing the current operation.</returns>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="path" /> is <see langword="null" /> (<see langword="Nothing" /> in Visual Basic).
/// </exception>
public Task SetCreationTimeAsync(
string path,
DateTime creationTime,
CancellationToken cancellationToken = default)
{
Contract.RequiresNotNullOrWhitespace(
path,
nameof(path));
return Fire.OnThreadPool(
FSFile.SetCreationTimeUtc,
path,
creationTime,
cancellationToken);
}
/// <summary>
/// Sets the file's last access time.
/// </summary>
/// <param name="path">The path of the file.</param>
/// <param name="lastAccessTime">A <see cref="T:System.DateTime" /> with the file attribute to set.</param>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="path" /> is <see langword="null" /> (<see langword="Nothing" /> in Visual Basic).
/// </exception>
public void SetLastAccessTime(
string path,
DateTime lastAccessTime)
{
Contract.RequiresNotNullOrWhitespace(
path,
nameof(path));
FSFile.SetLastAccessTimeUtc(
path,
lastAccessTime);
}
/// <summary>
/// Asynchronously sets the file's last access time.
/// </summary>
/// <param name="path">The path of the file.</param>
/// <param name="lastAccessTime">A <see cref="T:System.DateTime" /> with the file attribute to set.</param>
/// <param name="cancellationToken">The cancellation token to stop this operation.</param>
/// <returns>A task representing the current operation.</returns>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="path" /> is <see langword="null" /> (<see langword="Nothing" /> in Visual Basic).
/// </exception>
public Task SetLastAccessTimeAsync(
string path,
DateTime lastAccessTime,
CancellationToken cancellationToken = default)
{
Contract.RequiresNotNullOrWhitespace(
path,
nameof(path));
return Fire.OnThreadPool(
FSFile.SetLastAccessTimeUtc,
path,
lastAccessTime,
cancellationToken);
}
/// <summary>
/// Sets the file's last write time.
/// </summary>
/// <param name="path">The path of the file.</param>
/// <param name="lastWriteTime">A <see cref="T:System.DateTime" /> with the file attribute to set.</param>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="path" /> is <see langword="null" /> (<see langword="Nothing" /> in Visual Basic).
/// </exception>
public void SetLastWriteTime(
string path,
DateTime lastWriteTime)
{
Contract.RequiresNotNullOrWhitespace(
path,
nameof(path));
FSFile.SetLastWriteTimeUtc(
path,
lastWriteTime);
}
/// <summary>
/// Asynchronously sets the file's last write time.
/// </summary>
/// <param name="path">The path of the file.</param>
/// <param name="lastWriteTime">A <see cref="T:System.DateTime" /> with the file attribute to set.</param>
/// <param name="cancellationToken">The cancellation token to stop this operation.</param>
/// <returns>A task representing the current operation.</returns>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="path" /> is <see langword="null" /> (<see langword="Nothing" /> in Visual Basic).
/// </exception>
public Task SetLastWriteTimeAsync(
string path,
DateTime lastWriteTime,
CancellationToken cancellationToken = default)
{
Contract.RequiresNotNullOrWhitespace(
path,
nameof(path));
return Fire.OnThreadPool(
FSFile.SetLastWriteTimeUtc,
path,
lastWriteTime,
cancellationToken);
}
/// <summary>
/// Writes binary contents to a file.
/// </summary>
/// <param name="path">The path of the file.</param>
/// <param name="bytes">The contents to write.</param>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="path" /> or <paramref name="bytes" /> is <see langword="null" /> (<see langword="Nothing" /> in
/// Visual Basic).
/// </exception>
public void WriteAllBytes(
string path,
byte[] bytes)
{
Contract.RequiresNotNullOrWhitespace(
path,
nameof(path));
Contract.RequiresNotNullOrEmpty(
bytes,
nameof(bytes));
FSFile.WriteAllBytes(
path,
bytes);
}
/// <summary>
/// Asynchronously writes binary contents to a file.
/// </summary>
/// <param name="path">The path of the file.</param>
/// <param name="bytes">The contents to write.</param>
/// <param name="cancellationToken">The cancellation token to stop this operation.</param>
/// <returns>A task representing the current operation.</returns>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="path" /> or <paramref name="bytes" /> is <see langword="null" /> (<see langword="Nothing" /> in
/// Visual Basic).
/// </exception>
public Task WriteAllBytesAsync(
string path,
byte[] bytes,
CancellationToken cancellationToken = default)
{
Contract.RequiresNotNullOrWhitespace(
path,
nameof(path));
Contract.RequiresNotNullOrEmpty(
bytes,
nameof(bytes));
return Fire.OnThreadPool(
FSFile.WriteAllBytes,
path,
bytes,
cancellationToken);
}
/// <summary>
/// Writes lines of text to a file.
/// </summary>
/// <param name="path">The path of the file.</param>
/// <param name="contents">The contents to write.</param>
/// <param name="encoding">The encoding to use.</param>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="path" /> or <paramref name="contents" /> is <see langword="null" /> (<see langword="Nothing" /> in
/// Visual Basic).
/// </exception>
/// <remarks>
/// This operation always requires an encoding to be used. If <paramref name="encoding" /> is set to
/// <see langword="null" />, an implementation-specific
/// encoding will be used.
/// </remarks>
public void WriteAllLines(
string path,
IEnumerable<string> contents,
Encoding encoding = null)
{
Contract.RequiresNotNullOrWhitespace(
path,
nameof(path));
Contract.RequiresNotNull(
in contents,
nameof(contents));
if (encoding == null)
{
FSFile.WriteAllLines(
path,
contents);
}
else
{
FSFile.WriteAllLines(
path,
contents,
encoding);
}
}
/// <summary>
/// Asynchronously writes lines of text to a file.
/// </summary>
/// <param name="path">The path of the file.</param>
/// <param name="contents">The contents to write.</param>
/// <param name="encoding">The encoding to use.</param>
/// <param name="cancellationToken">The cancellation token to stop this operation.</param>
/// <returns>A task representing the current operation.</returns>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="path" /> or <paramref name="contents" /> is <see langword="null" /> (<see langword="Nothing" /> in
/// Visual Basic).
/// </exception>
/// <remarks>
/// This operation always requires an encoding to be used. If <paramref name="encoding" /> is set to
/// <see langword="null" />, an implementation-specific
/// encoding will be used.
/// </remarks>
public Task WriteAllLinesAsync(
string path,
IEnumerable<string> contents,
Encoding encoding = null,
CancellationToken cancellationToken = default)
{
Contract.RequiresNotNullOrWhitespace(
path,
nameof(path));
Contract.RequiresNotNull(
in contents,
nameof(contents));
return encoding == null
? Fire.OnThreadPool(
FSFile.WriteAllLines,
path,
contents,
cancellationToken)
: Fire.OnThreadPool(
FSFile.WriteAllLines,
path,
contents,
encoding,
cancellationToken);
}
/// <summary>
/// Writes text to a file.
/// </summary>
/// <param name="path">The path of the file.</param>
/// <param name="contents">The contents to write.</param>
/// <param name="encoding">The encoding to use.</param>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="path" /> or <paramref name="contents" /> is <see langword="null" /> (<see langword="Nothing" /> in
/// Visual Basic).
/// </exception>
/// <remarks>
/// This operation always requires an encoding to be used. If <paramref name="encoding" /> is set to
/// <see langword="null" />, an implementation-specific
/// encoding will be used.
/// </remarks>
public void WriteAllText(
string path,
string contents,
Encoding encoding = null)
{
Contract.RequiresNotNullOrWhitespace(
path,
nameof(path));
Contract.RequiresNotNullOrWhitespace(
contents,
nameof(contents));
if (encoding == null)
{
FSFile.WriteAllText(
path,
contents);
}
else
{
FSFile.WriteAllText(
path,
contents,
encoding);
}
}
/// <summary>
/// Asynchronously writes text to a file.
/// </summary>
/// <param name="path">The path of the file.</param>
/// <param name="contents">The contents to write.</param>
/// <param name="encoding">The encoding to use.</param>
/// <param name="cancellationToken">The cancellation token to stop this operation.</param>
/// <returns>A task representing the current operation.</returns>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="path" /> or <paramref name="contents" /> is <see langword="null" /> (<see langword="Nothing" /> in
/// Visual Basic).
/// </exception>
/// <remarks>
/// This operation always requires an encoding to be used. If <paramref name="encoding" /> is set to
/// <see langword="null" />, an implementation-specific
/// encoding will be used.
/// </remarks>
public Task WriteAllTextAsync(
string path,
string contents,
Encoding encoding = null,
CancellationToken cancellationToken = default)
{
Contract.RequiresNotNullOrWhitespace(
path,
nameof(path));
Contract.RequiresNotNullOrWhitespace(
contents,
nameof(contents));
return encoding == null
? Fire.OnThreadPool(
FSFile.WriteAllText,
path,
contents,
cancellationToken)
: Fire.OnThreadPool(
FSFile.WriteAllText,
path,
contents,
encoding,
cancellationToken);
}
}
}
| |
// 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.Collections.Generic;
using System.ComponentModel.Composition.Hosting;
using Microsoft.CodeAnalysis.Editor.CSharp.SignatureHelp;
using Microsoft.CodeAnalysis.Editor.UnitTests.SignatureHelp;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SignatureHelp
{
public class GenericNamePartiallyWrittenSignatureHelpProviderTests : AbstractCSharpSignatureHelpProviderTests
{
internal override ISignatureHelpProvider CreateSignatureHelpProvider()
{
return new GenericNamePartiallyWrittenSignatureHelpProvider();
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void NestedGenericUnterminated()
{
var markup = @"
class G<T> { };
class C
{
void Foo()
{
G<G<int>$$
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("G<T>", string.Empty, string.Empty, currentParameterIndex: 0));
Test(markup, expectedOrderedItems);
}
[WorkItem(544088)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void DeclaringGenericTypeWith1ParameterUnterminated()
{
var markup = @"
class G<T> { };
class C
{
void Foo()
{
[|G<$$
|]}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("G<T>", string.Empty, string.Empty, currentParameterIndex: 0));
Test(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void CallingGenericAsyncMethod()
{
var markup = @"
using System.Threading.Tasks;
class Program
{
void Main(string[] args)
{
Foo<$$
}
Task<int> Foo<T>()
{
return Foo<T>();
}
}
";
var documentation = @"
Usage:
int x = await Foo();";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("(awaitable) Task<int> Program.Foo<T>()", documentation, string.Empty, currentParameterIndex: 0));
// TODO: Enable the script case when we have support for extension methods in scripts
Test(markup, expectedOrderedItems, usePreviousCharAsTrigger: false, sourceCodeKind: Microsoft.CodeAnalysis.SourceCodeKind.Regular);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void EditorBrowsable_GenericMethod_BrowsableAlways()
{
var markup = @"
class Program
{
void M()
{
new C().Foo<$$
}
}
";
var referencedCode = @"
public class C
{
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)]
public void Foo<T>(T x)
{ }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo<T>(T x)", string.Empty, string.Empty, currentParameterIndex: 0));
TestSignatureHelpInEditorBrowsableContexts(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItems,
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void EditorBrowsable_GenericMethod_BrowsableNever()
{
var markup = @"
class Program
{
void M()
{
new C().Foo<$$
}
}
";
var referencedCode = @"
public class C
{
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public void Foo<T>(T x)
{ }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo<T>(T x)", string.Empty, string.Empty, currentParameterIndex: 0));
TestSignatureHelpInEditorBrowsableContexts(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(),
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void EditorBrowsable_GenericMethod_BrowsableAdvanced()
{
var markup = @"
class Program
{
void M()
{
new C().Foo<$$
}
}
";
var referencedCode = @"
public class C
{
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)]
public void Foo<T>(T x)
{ }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo<T>(T x)", string.Empty, string.Empty, currentParameterIndex: 0));
TestSignatureHelpInEditorBrowsableContexts(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItems,
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: false);
TestSignatureHelpInEditorBrowsableContexts(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(),
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: true);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void EditorBrowsable_GenericMethod_BrowsableMixed()
{
var markup = @"
class Program
{
void M()
{
new C().Foo<$$
}
}
";
var referencedCode = @"
public class C
{
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)]
public void Foo<T>(T x)
{ }
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public void Foo<T, U>(T x, U y)
{ }
}";
var expectedOrderedItemsMetadataReference = new List<SignatureHelpTestItem>();
expectedOrderedItemsMetadataReference.Add(new SignatureHelpTestItem("void C.Foo<T>(T x)", string.Empty, string.Empty, currentParameterIndex: 0));
var expectedOrderedItemsSameSolution = new List<SignatureHelpTestItem>();
expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void C.Foo<T>(T x)", string.Empty, string.Empty, currentParameterIndex: 0));
expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void C.Foo<T, U>(T x, U y)", string.Empty, string.Empty, currentParameterIndex: 0));
TestSignatureHelpInEditorBrowsableContexts(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItemsMetadataReference,
expectedOrderedItemsSameSolution: expectedOrderedItemsSameSolution,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void GenericExtensionMethod()
{
var markup = @"
interface IFoo
{
void Bar<T>();
}
static class FooExtensions
{
public static void Bar<T1, T2>(this IFoo foo) { }
}
class Program
{
static void Main()
{
IFoo f = null;
f.[|Bar<$$
|]}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem("void IFoo.Bar<T>()", currentParameterIndex: 0),
new SignatureHelpTestItem("(extension) void IFoo.Bar<T1, T2>()", currentParameterIndex: 0),
};
// Extension methods are supported in Interactive/Script (yet).
Test(markup, expectedOrderedItems, sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(544088)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void InvokingGenericMethodWith1ParameterUnterminated()
{
var markup = @"
class C
{
/// <summary>
/// Method Foo
/// </summary>
/// <typeparam name=""T"">Method type parameter</typeparam>
void Foo<T>() { }
void Bar()
{
[|Foo<$$
|]}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo<T>()",
"Method Foo", "Method type parameter", currentParameterIndex: 0));
Test(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationOnTriggerBracket()
{
var markup = @"
class G<S, T> { };
class C
{
void Foo()
{
[|G<$$
|]}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("G<S, T>", string.Empty, string.Empty, currentParameterIndex: 0));
Test(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationOnTriggerComma()
{
var markup = @"
class G<S, T> { };
class C
{
void Foo()
{
[|G<int,$$
|]}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("G<S, T>", string.Empty, string.Empty, currentParameterIndex: 1));
Test(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
}
[WorkItem(1067933)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void InvokedWithNoToken()
{
var markup = @"
// foo<$$";
Test(markup);
}
}
}
| |
/*
* Copyright 2002-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections;
using Common.Logging;
using Quartz;
using Quartz.Xml;
using Spring.Collections;
using Spring.Context;
using Spring.Core.IO;
using Spring.Transaction;
using Spring.Transaction.Support;
namespace Spring.Scheduling.Quartz
{
/// <summary>
/// Common base class for accessing a Quartz Scheduler, i.e. for registering jobs,
/// triggers and listeners on a <see cref="IScheduler" /> instance.
/// </summary>
/// <remarks>
/// For concrete usage, check out the <see cref="SchedulerFactoryObject" /> and
/// <see cref="SchedulerAccessorObject" /> classes.
///</remarks>
/// <author>Juergen Hoeller</author>
/// <author>Marko Lahma (.NET)</author>
public abstract class SchedulerAccessor : IResourceLoaderAware
{
/// <summary>
/// Logger instance.
/// </summary>
protected readonly ILog logger;
private bool overwriteExistingJobs;
private string[] jobSchedulingDataLocations;
private IList jobDetails;
private IDictionary calendars;
private IList triggers;
private ISchedulerListener[] schedulerListeners;
private IJobListener[] globalJobListeners;
private IJobListener[] jobListeners;
private ITriggerListener[] globalTriggerListeners;
private ITriggerListener[] triggerListeners;
private IPlatformTransactionManager transactionManager;
/// <summary>
/// Resource loader instance for sub-classes
/// </summary>
protected IResourceLoader resourceLoader;
/// <summary>
/// Initializes a new instance of the <see cref="SchedulerAccessor"/> class.
/// </summary>
protected SchedulerAccessor()
{
logger = LogManager.GetLogger(GetType());
}
/// <summary>
/// Set whether any jobs defined on this SchedulerFactoryObject should overwrite
/// existing job definitions. Default is "false", to not overwrite already
/// registered jobs that have been read in from a persistent job store.
/// </summary>
public virtual bool OverwriteExistingJobs
{
set { overwriteExistingJobs = value; }
}
/// <summary>
/// Set the locations of Quartz job definition XML files that follow the
/// "job_scheduling_data_1_5" XSD. Can be specified to automatically
/// register jobs that are defined in such files, possibly in addition
/// to jobs defined directly on this SchedulerFactoryObject.
/// </summary>
/// <seealso cref="JobSchedulingDataProcessor" />
public virtual string[] JobSchedulingDataLocations
{
set { jobSchedulingDataLocations = value; }
}
/// <summary>
/// Set the location of a Quartz job definition XML file that follows the
/// "job_scheduling_data" XSD. Can be specified to automatically
/// register jobs that are defined in such a file, possibly in addition
/// to jobs defined directly on this SchedulerFactoryObject.
/// </summary>
/// <seealso cref="ResourceJobSchedulingDataProcessor" />
/// <seealso cref="JobSchedulingDataProcessor" />
public virtual string JobSchedulingDataLocation
{
set { jobSchedulingDataLocations = new string[] {value}; }
}
/// <summary>
/// Register a list of JobDetail objects with the Scheduler that
/// this FactoryObject creates, to be referenced by Triggers.
/// This is not necessary when a Trigger determines the JobDetail
/// itself: In this case, the JobDetail will be implicitly registered
/// in combination with the Trigger.
/// </summary>
/// <seealso cref="Triggers" />
/// <seealso cref="JobDetail" />
/// <seealso cref="JobDetailObject" />
/// <seealso cref="IJobDetailAwareTrigger" />
/// <seealso cref="Trigger.JobName" />
public virtual JobDetail[] JobDetails
{
set
{
// Use modifiable ArrayList here, to allow for further adding of
// JobDetail objects during autodetection of JobDetailAwareTriggers.
jobDetails = new ArrayList(value);
}
}
/// <summary>
/// Register a list of Quartz ICalendar objects with the Scheduler
/// that this FactoryObject creates, to be referenced by Triggers.
/// </summary>
/// <value>Map with calendar names as keys as Calendar objects as values</value>
/// <seealso cref="ICalendar" />
/// <seealso cref="Trigger.CalendarName" />
public virtual IDictionary Calendars
{
set { calendars = value; }
}
/// <summary>
/// Register a list of Trigger objects with the Scheduler that
/// this FactoryObject creates.
/// </summary>
/// <remarks>
/// If the Trigger determines the corresponding JobDetail itself,
/// the job will be automatically registered with the Scheduler.
/// Else, the respective JobDetail needs to be registered via the
/// "jobDetails" property of this FactoryObject.
/// </remarks>
/// <seealso cref="JobDetails" />
/// <seealso cref="JobDetail" />
/// <seealso cref="IJobDetailAwareTrigger" />
/// <seealso cref="CronTriggerObject" />
/// <seealso cref="SimpleTriggerObject" />
public virtual Trigger[] Triggers
{
set { triggers = new ArrayList(value); }
}
/// <summary>
/// Specify Quartz SchedulerListeners to be registered with the Scheduler.
/// </summary>
public virtual ISchedulerListener[] SchedulerListeners
{
set { schedulerListeners = value; }
}
/// <summary>
/// Specify global Quartz JobListeners to be registered with the Scheduler.
/// Such JobListeners will apply to all Jobs in the Scheduler.
/// </summary>
public virtual IJobListener[] GlobalJobListeners
{
set { globalJobListeners = value; }
}
/// <summary>
/// Specify named Quartz JobListeners to be registered with the Scheduler.
/// Such JobListeners will only apply to Jobs that explicitly activate
/// them via their name.
/// </summary>
/// <seealso cref="IJobListener.Name" />
/// <seealso cref="JobDetail.AddJobListener" />
/// <seealso cref="JobDetail.JobListenerNames" />
public virtual IJobListener[] JobListeners
{
set { jobListeners = value; }
}
/// <summary>
/// Specify global Quartz TriggerListeners to be registered with the Scheduler.
/// Such TriggerListeners will apply to all Triggers in the Scheduler.
/// </summary>
public virtual ITriggerListener[] GlobalTriggerListeners
{
set { globalTriggerListeners = value; }
}
/// <summary>
/// Specify named Quartz TriggerListeners to be registered with the Scheduler.
/// Such TriggerListeners will only apply to Triggers that explicitly activate
/// them via their name.
/// </summary>
/// <seealso cref="ITriggerListener.Name" />
/// <seealso cref="Trigger.AddTriggerListener" />
/// <seealso cref="Trigger.TriggerListenerNames" />
public virtual ITriggerListener[] TriggerListeners
{
set { triggerListeners = value; }
}
/// <summary>
/// Set the transaction manager to be used for registering jobs and triggers
/// that are defined by this SchedulerFactoryObject. Default is none; setting
/// this only makes sense when specifying a DataSource for the Scheduler.
/// </summary>
public virtual IPlatformTransactionManager TransactionManager
{
set { transactionManager = value; }
}
/// <summary>
/// Sets the <see cref="Spring.Core.IO.IResourceLoader"/>
/// that this object runs in.
/// </summary>
/// <value></value>
/// <remarks>
/// Invoked <b>after</b> population of normal objects properties but
/// before an init callback such as
/// <see cref="Spring.Objects.Factory.IInitializingObject"/>'s
/// <see cref="Spring.Objects.Factory.IInitializingObject.AfterPropertiesSet()"/>
/// or a custom init-method. Invoked <b>before</b> setting
/// <see cref="Spring.Context.IApplicationContextAware"/>'s
/// <see cref="Spring.Context.IApplicationContextAware.ApplicationContext"/>
/// property.
/// </remarks>
public virtual IResourceLoader ResourceLoader
{
set { resourceLoader = value; }
}
/// <summary>
/// Register jobs and triggers (within a transaction, if possible).
/// </summary>
protected virtual void RegisterJobsAndTriggers()
{
ITransactionStatus transactionStatus = null;
if (transactionManager != null)
{
transactionStatus = transactionManager.GetTransaction(new DefaultTransactionDefinition());
}
try
{
if (jobSchedulingDataLocations != null)
{
JobSchedulingDataProcessor dataProcessor = new JobSchedulingDataProcessor(true, true);
for (int i = 0; i < this.jobSchedulingDataLocations.Length; i++)
{
dataProcessor.ProcessFileAndScheduleJobs(
jobSchedulingDataLocations[i], GetScheduler(), overwriteExistingJobs);
}
}
// Register JobDetails.
if (jobDetails != null)
{
foreach (JobDetail jobDetail in jobDetails)
{
AddJobToScheduler(jobDetail);
}
}
else
{
// Create empty list for easier checks when registering triggers.
jobDetails = new LinkedList();
}
// Register Calendars.
if (calendars != null)
{
foreach (DictionaryEntry entry in calendars)
{
string calendarName = (string) entry.Key;
ICalendar calendar = (ICalendar) entry.Value;
GetScheduler().AddCalendar(calendarName, calendar, true, true);
}
}
// Register Triggers.
if (triggers != null)
{
foreach (Trigger trigger in triggers)
{
AddTriggerToScheduler(trigger);
}
}
}
catch (Exception ex)
{
if (transactionStatus != null)
{
try
{
transactionManager.Rollback(transactionStatus);
}
catch (TransactionException)
{
logger.Error("Job registration exception overridden by rollback exception", ex);
throw;
}
}
if (ex is SchedulerException)
{
throw;
}
throw new SchedulerException("Registration of jobs and triggers failed: " + ex.Message);
}
if (transactionStatus != null)
{
transactionManager.Commit(transactionStatus);
}
}
/// <summary>
/// Add the given job to the Scheduler, if it doesn't already exist.
/// Overwrites the job in any case if "overwriteExistingJobs" is set.
/// </summary>
/// <param name="jobDetail">the job to add</param>
/// <returns><code>true</code> if the job was actually added, <code>false</code> if it already existed before</returns>
private bool AddJobToScheduler(JobDetail jobDetail)
{
if (overwriteExistingJobs ||
GetScheduler().GetJobDetail(jobDetail.Name, jobDetail.Group) == null)
{
GetScheduler().AddJob(jobDetail, true);
return true;
}
else
{
return false;
}
}
/// <summary>
/// Add the given trigger to the Scheduler, if it doesn't already exist.
/// Overwrites the trigger in any case if "overwriteExistingJobs" is set.
/// </summary>
/// <param name="trigger">the trigger to add</param>
/// <returns><code>true</code> if the trigger was actually added, <code>false</code> if it already existed before</returns>
private bool AddTriggerToScheduler(Trigger trigger)
{
bool triggerExists = (GetScheduler().GetTrigger(trigger.Name, trigger.Group) != null);
if (!triggerExists || this.overwriteExistingJobs)
{
// Check if the Trigger is aware of an associated JobDetail.
if (trigger is IJobDetailAwareTrigger)
{
JobDetail jobDetail = ((IJobDetailAwareTrigger) trigger).JobDetail;
// Automatically register the JobDetail too.
if (!jobDetails.Contains(jobDetail) && AddJobToScheduler(jobDetail))
{
jobDetails.Add(jobDetail);
}
}
if (!triggerExists)
{
try
{
GetScheduler().ScheduleJob(trigger);
}
catch (ObjectAlreadyExistsException ex)
{
if (logger.IsDebugEnabled)
{
logger.Debug(
"Unexpectedly found existing trigger, assumably due to cluster race condition: " +
ex.Message + " - can safely be ignored");
}
if (overwriteExistingJobs)
{
GetScheduler().RescheduleJob(trigger.Name, trigger.Group, trigger);
}
}
}
else
{
GetScheduler().RescheduleJob(trigger.Name, trigger.Group, trigger);
}
return true;
}
else
{
return false;
}
}
/// <summary>
/// Register all specified listeners with the Scheduler.
/// </summary>
protected virtual void RegisterListeners()
{
if (schedulerListeners != null)
{
for (int i = 0; i < schedulerListeners.Length; i++)
{
GetScheduler().AddSchedulerListener(schedulerListeners[i]);
}
}
if (globalJobListeners != null)
{
for (int i = 0; i < globalJobListeners.Length; i++)
{
GetScheduler().AddGlobalJobListener(globalJobListeners[i]);
}
}
if (jobListeners != null)
{
for (int i = 0; i < jobListeners.Length; i++)
{
GetScheduler().AddJobListener(jobListeners[i]);
}
}
if (globalTriggerListeners != null)
{
for (int i = 0; i < globalTriggerListeners.Length; i++)
{
GetScheduler().AddGlobalTriggerListener(globalTriggerListeners[i]);
}
}
if (triggerListeners != null)
{
for (int i = 0; i < triggerListeners.Length; i++)
{
GetScheduler().AddTriggerListener(triggerListeners[i]);
}
}
}
/// <summary>
/// Template method that determines the Scheduler to operate on.
/// To be implemented by subclasses.
/// </summary>
/// <returns></returns>
protected abstract IScheduler GetScheduler();
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Reflection;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Data;
using MySql.Data.MySqlClient;
namespace OpenSim.Data.MySQL
{
public class MySqlRegionData : MySqlFramework, IRegionData
{
private string m_Realm;
private List<string> m_ColumnNames;
//private string m_connectionString;
protected virtual Assembly Assembly
{
get { return GetType().Assembly; }
}
public MySqlRegionData(string connectionString, string realm)
: base(connectionString)
{
m_Realm = realm;
m_connectionString = connectionString;
using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
{
dbcon.Open();
Migration m = new Migration(dbcon, Assembly, "GridStore");
m.Update();
}
}
public List<RegionData> Get(string regionName, UUID scopeID)
{
string command = "select * from `"+m_Realm+"` where regionName like ?regionName";
if (scopeID != UUID.Zero)
command += " and ScopeID = ?scopeID";
command += " order by regionName";
using (MySqlCommand cmd = new MySqlCommand(command))
{
cmd.Parameters.AddWithValue("?regionName", regionName);
cmd.Parameters.AddWithValue("?scopeID", scopeID.ToString());
return RunCommand(cmd);
}
}
public RegionData Get(int posX, int posY, UUID scopeID)
{
string command = "select * from `"+m_Realm+"` where locX = ?posX and locY = ?posY";
if (scopeID != UUID.Zero)
command += " and ScopeID = ?scopeID";
using (MySqlCommand cmd = new MySqlCommand(command))
{
cmd.Parameters.AddWithValue("?posX", posX.ToString());
cmd.Parameters.AddWithValue("?posY", posY.ToString());
cmd.Parameters.AddWithValue("?scopeID", scopeID.ToString());
List<RegionData> ret = RunCommand(cmd);
if (ret.Count == 0)
return null;
return ret[0];
}
}
public RegionData Get(UUID regionID, UUID scopeID)
{
string command = "select * from `"+m_Realm+"` where uuid = ?regionID";
if (scopeID != UUID.Zero)
command += " and ScopeID = ?scopeID";
using (MySqlCommand cmd = new MySqlCommand(command))
{
cmd.Parameters.AddWithValue("?regionID", regionID.ToString());
cmd.Parameters.AddWithValue("?scopeID", scopeID.ToString());
List<RegionData> ret = RunCommand(cmd);
if (ret.Count == 0)
return null;
return ret[0];
}
}
public List<RegionData> Get(int startX, int startY, int endX, int endY, UUID scopeID)
{
string command = "select * from `"+m_Realm+"` where locX between ?startX and ?endX and locY between ?startY and ?endY";
if (scopeID != UUID.Zero)
command += " and ScopeID = ?scopeID";
using (MySqlCommand cmd = new MySqlCommand(command))
{
cmd.Parameters.AddWithValue("?startX", startX.ToString());
cmd.Parameters.AddWithValue("?startY", startY.ToString());
cmd.Parameters.AddWithValue("?endX", endX.ToString());
cmd.Parameters.AddWithValue("?endY", endY.ToString());
cmd.Parameters.AddWithValue("?scopeID", scopeID.ToString());
return RunCommand(cmd);
}
}
public List<RegionData> RunCommand(MySqlCommand cmd)
{
List<RegionData> retList = new List<RegionData>();
using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
{
dbcon.Open();
cmd.Connection = dbcon;
using (IDataReader result = cmd.ExecuteReader())
{
while (result.Read())
{
RegionData ret = new RegionData();
ret.Data = new Dictionary<string, object>();
ret.RegionID = DBGuid.FromDB(result["uuid"]);
ret.ScopeID = DBGuid.FromDB(result["ScopeID"]);
ret.RegionName = result["regionName"].ToString();
ret.posX = Convert.ToInt32(result["locX"]);
ret.posY = Convert.ToInt32(result["locY"]);
ret.sizeX = Convert.ToInt32(result["sizeX"]);
ret.sizeY = Convert.ToInt32(result["sizeY"]);
if (m_ColumnNames == null)
{
m_ColumnNames = new List<string>();
DataTable schemaTable = result.GetSchemaTable();
foreach (DataRow row in schemaTable.Rows)
{
if (row["ColumnName"] != null)
m_ColumnNames.Add(row["ColumnName"].ToString());
}
}
foreach (string s in m_ColumnNames)
{
if (s == "uuid")
continue;
if (s == "ScopeID")
continue;
if (s == "regionName")
continue;
if (s == "locX")
continue;
if (s == "locY")
continue;
ret.Data[s] = result[s].ToString();
}
retList.Add(ret);
}
}
}
return retList;
}
public bool Store(RegionData data)
{
if (data.Data.ContainsKey("uuid"))
data.Data.Remove("uuid");
if (data.Data.ContainsKey("ScopeID"))
data.Data.Remove("ScopeID");
if (data.Data.ContainsKey("regionName"))
data.Data.Remove("regionName");
if (data.Data.ContainsKey("posX"))
data.Data.Remove("posX");
if (data.Data.ContainsKey("posY"))
data.Data.Remove("posY");
if (data.Data.ContainsKey("sizeX"))
data.Data.Remove("sizeX");
if (data.Data.ContainsKey("sizeY"))
data.Data.Remove("sizeY");
if (data.Data.ContainsKey("locX"))
data.Data.Remove("locX");
if (data.Data.ContainsKey("locY"))
data.Data.Remove("locY");
if (data.RegionName.Length > 128)
data.RegionName = data.RegionName.Substring(0, 128);
string[] fields = new List<string>(data.Data.Keys).ToArray();
using (MySqlCommand cmd = new MySqlCommand())
{
string update = "update `" + m_Realm + "` set locX=?posX, locY=?posY, sizeX=?sizeX, sizeY=?sizeY";
foreach (string field in fields)
{
update += ", ";
update += "`" + field + "` = ?" + field;
cmd.Parameters.AddWithValue("?" + field, data.Data[field]);
}
update += " where uuid = ?regionID";
if (data.ScopeID != UUID.Zero)
update += " and ScopeID = ?scopeID";
cmd.CommandText = update;
cmd.Parameters.AddWithValue("?regionID", data.RegionID.ToString());
cmd.Parameters.AddWithValue("?regionName", data.RegionName);
cmd.Parameters.AddWithValue("?scopeID", data.ScopeID.ToString());
cmd.Parameters.AddWithValue("?posX", data.posX.ToString());
cmd.Parameters.AddWithValue("?posY", data.posY.ToString());
cmd.Parameters.AddWithValue("?sizeX", data.sizeX.ToString());
cmd.Parameters.AddWithValue("?sizeY", data.sizeY.ToString());
if (ExecuteNonQuery(cmd) < 1)
{
string insert = "insert into `" + m_Realm + "` (`uuid`, `ScopeID`, `locX`, `locY`, `sizeX`, `sizeY`, `regionName`, `" +
String.Join("`, `", fields) +
"`) values ( ?regionID, ?scopeID, ?posX, ?posY, ?sizeX, ?sizeY, ?regionName, ?" + String.Join(", ?", fields) + ")";
cmd.CommandText = insert;
if (ExecuteNonQuery(cmd) < 1)
{
return false;
}
}
}
return true;
}
public bool SetDataItem(UUID regionID, string item, string value)
{
using (MySqlCommand cmd = new MySqlCommand("update `" + m_Realm + "` set `" + item + "` = ?" + item + " where uuid = ?UUID"))
{
cmd.Parameters.AddWithValue("?" + item, value);
cmd.Parameters.AddWithValue("?UUID", regionID.ToString());
if (ExecuteNonQuery(cmd) > 0)
return true;
}
return false;
}
public bool Delete(UUID regionID)
{
using (MySqlCommand cmd = new MySqlCommand("delete from `" + m_Realm + "` where uuid = ?UUID"))
{
cmd.Parameters.AddWithValue("?UUID", regionID.ToString());
if (ExecuteNonQuery(cmd) > 0)
return true;
}
return false;
}
public List<RegionData> GetDefaultRegions(UUID scopeID)
{
return Get((int)RegionFlags.DefaultRegion, scopeID);
}
public List<RegionData> GetFallbackRegions(UUID scopeID, int x, int y)
{
List<RegionData> regions = Get((int)RegionFlags.FallbackRegion, scopeID);
RegionDataDistanceCompare distanceComparer = new RegionDataDistanceCompare(x, y);
regions.Sort(distanceComparer);
return regions;
}
public List<RegionData> GetHyperlinks(UUID scopeID)
{
return Get((int)RegionFlags.Hyperlink, scopeID);
}
private List<RegionData> Get(int regionFlags, UUID scopeID)
{
string command = "select * from `" + m_Realm + "` where (flags & " + regionFlags.ToString() + ") <> 0";
if (scopeID != UUID.Zero)
command += " and ScopeID = ?scopeID";
MySqlCommand cmd = new MySqlCommand(command);
cmd.Parameters.AddWithValue("?scopeID", scopeID.ToString());
return RunCommand(cmd);
}
}
}
| |
using System.Reflection;
using System.Text.Json;
using JetBrains.Annotations;
using JsonApiDotNetCore.Configuration;
using JsonApiDotNetCore.Resources;
using JsonApiDotNetCore.Resources.Annotations;
using JsonApiDotNetCore.Serialization.Objects;
using JsonApiDotNetCore.Serialization.Request;
namespace JsonApiDotNetCore.Serialization.JsonConverters;
/// <summary>
/// Converts <see cref="ResourceObject" /> to/from JSON.
/// </summary>
[UsedImplicitly(ImplicitUseKindFlags.InstantiatedNoFixedConstructorSignature)]
public sealed class ResourceObjectConverter : JsonObjectConverter<ResourceObject>
{
private static readonly JsonEncodedText TypeText = JsonEncodedText.Encode("type");
private static readonly JsonEncodedText IdText = JsonEncodedText.Encode("id");
private static readonly JsonEncodedText LidText = JsonEncodedText.Encode("lid");
private static readonly JsonEncodedText MetaText = JsonEncodedText.Encode("meta");
private static readonly JsonEncodedText AttributesText = JsonEncodedText.Encode("attributes");
private static readonly JsonEncodedText RelationshipsText = JsonEncodedText.Encode("relationships");
private static readonly JsonEncodedText LinksText = JsonEncodedText.Encode("links");
private readonly IResourceGraph _resourceGraph;
public ResourceObjectConverter(IResourceGraph resourceGraph)
{
ArgumentGuard.NotNull(resourceGraph, nameof(resourceGraph));
_resourceGraph = resourceGraph;
}
/// <summary>
/// Resolves the resource type and attributes against the resource graph. Because attribute values in <see cref="ResourceObject" /> are typed as
/// <see cref="object" />, we must lookup and supply the target type to the serializer.
/// </summary>
public override ResourceObject Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
// Inside a JsonConverter there is no way to know where in the JSON object tree we are. And the serializer is unable to provide
// the correct position either. So we avoid an exception on missing/invalid 'type' element and postpone producing an error response
// to the post-processing phase.
var resourceObject = new ResourceObject
{
// The 'attributes' element may occur before 'type', but we need to know the resource type before we can deserialize attributes
// into their corresponding CLR types.
Type = PeekType(ref reader)
};
ResourceType? resourceType = resourceObject.Type != null ? _resourceGraph.FindResourceType(resourceObject.Type) : null;
while (reader.Read())
{
switch (reader.TokenType)
{
case JsonTokenType.EndObject:
{
return resourceObject;
}
case JsonTokenType.PropertyName:
{
string? propertyName = reader.GetString();
reader.Read();
switch (propertyName)
{
case "id":
{
if (reader.TokenType != JsonTokenType.String)
{
// Newtonsoft.Json used to auto-convert number to strings, while System.Text.Json does not. This is so likely
// to hit users during upgrade that we special-case for this and produce a helpful error message.
var jsonElement = ReadSubTree<JsonElement>(ref reader, options);
throw new JsonException($"Failed to convert ID '{jsonElement}' of type '{jsonElement.ValueKind}' to type 'String'.");
}
resourceObject.Id = reader.GetString();
break;
}
case "lid":
{
resourceObject.Lid = reader.GetString();
break;
}
case "attributes":
{
if (resourceType != null)
{
resourceObject.Attributes = ReadAttributes(ref reader, options, resourceType);
}
else
{
reader.Skip();
}
break;
}
case "relationships":
{
resourceObject.Relationships = ReadSubTree<IDictionary<string, RelationshipObject?>>(ref reader, options);
break;
}
case "links":
{
resourceObject.Links = ReadSubTree<ResourceLinks>(ref reader, options);
break;
}
case "meta":
{
resourceObject.Meta = ReadSubTree<IDictionary<string, object?>>(ref reader, options);
break;
}
default:
{
reader.Skip();
break;
}
}
break;
}
}
}
throw GetEndOfStreamError();
}
private static string? PeekType(ref Utf8JsonReader reader)
{
// https://docs.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-converters-how-to?pivots=dotnet-5-0#an-alternative-way-to-do-polymorphic-deserialization
Utf8JsonReader readerClone = reader;
while (readerClone.Read())
{
if (readerClone.TokenType == JsonTokenType.PropertyName)
{
string? propertyName = readerClone.GetString();
readerClone.Read();
switch (propertyName)
{
case "type":
{
return readerClone.GetString();
}
default:
{
readerClone.Skip();
break;
}
}
}
}
return null;
}
private static IDictionary<string, object?> ReadAttributes(ref Utf8JsonReader reader, JsonSerializerOptions options, ResourceType resourceType)
{
var attributes = new Dictionary<string, object?>();
while (reader.Read())
{
switch (reader.TokenType)
{
case JsonTokenType.EndObject:
{
return attributes;
}
case JsonTokenType.PropertyName:
{
string attributeName = reader.GetString() ?? string.Empty;
reader.Read();
AttrAttribute? attribute = resourceType.FindAttributeByPublicName(attributeName);
PropertyInfo? property = attribute?.Property;
if (property != null)
{
object? attributeValue;
if (property.Name == nameof(Identifiable<object>.Id))
{
attributeValue = JsonInvalidAttributeInfo.Id;
}
else
{
try
{
attributeValue = JsonSerializer.Deserialize(ref reader, property.PropertyType, options);
}
catch (JsonException)
{
// Inside a JsonConverter there is no way to know where in the JSON object tree we are. And the serializer
// is unable to provide the correct position either. So we avoid an exception and postpone producing an error
// response to the post-processing phase, by setting a sentinel value.
var jsonElement = ReadSubTree<JsonElement>(ref reader, options);
attributeValue = new JsonInvalidAttributeInfo(attributeName, property.PropertyType, jsonElement.ToString(),
jsonElement.ValueKind);
}
}
attributes.Add(attributeName, attributeValue);
}
else
{
attributes.Add(attributeName, null);
reader.Skip();
}
break;
}
}
}
throw GetEndOfStreamError();
}
/// <summary>
/// Ensures that attribute values are not wrapped in <see cref="JsonElement" />s.
/// </summary>
public override void Write(Utf8JsonWriter writer, ResourceObject value, JsonSerializerOptions options)
{
writer.WriteStartObject();
writer.WriteString(TypeText, value.Type);
if (value.Id != null)
{
writer.WriteString(IdText, value.Id);
}
if (value.Lid != null)
{
writer.WriteString(LidText, value.Lid);
}
if (!value.Attributes.IsNullOrEmpty())
{
writer.WritePropertyName(AttributesText);
WriteSubTree(writer, value.Attributes, options);
}
if (!value.Relationships.IsNullOrEmpty())
{
writer.WritePropertyName(RelationshipsText);
WriteSubTree(writer, value.Relationships, options);
}
if (value.Links != null && value.Links.HasValue())
{
writer.WritePropertyName(LinksText);
WriteSubTree(writer, value.Links, options);
}
if (!value.Meta.IsNullOrEmpty())
{
writer.WritePropertyName(MetaText);
WriteSubTree(writer, value.Meta, options);
}
writer.WriteEndObject();
}
}
| |
#region License
//-----------------------------------------------------------------------
// <copyright>
// The MIT License (MIT)
//
// Copyright (c) 2014 Kirk S Woll
//
// 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>
//-----------------------------------------------------------------------
#endregion
using System;
using System.Linq;
using System.Runtime.WootzJs;
using WootzJs.Testing;
namespace WootzJs.Compiler.Tests
{
public class StringTests : TestFixture
{
[Test]
public void ToUpper()
{
var s = "foo";
s = s.ToUpper();
AssertEquals(s, "FOO");
}
[Test]
public void ToLower()
{
var s = "FOO";
s = s.ToLower();
AssertEquals(s, "foo");
}
[Test]
public void Length()
{
var s = "FOO";
int length = s.Length;
AssertEquals(length, 3);
}
[Test]
public void EndsWith()
{
var s = "HelloWorld";
AssertTrue(s.EndsWith("World"));
}
[Test]
public void StartsWith()
{
var s = "HelloWorld";
AssertTrue(s.StartsWith("Hello"));
}
[Test]
public void Compare()
{
AssertEquals(string.Compare("a", "b"), -1);
AssertEquals(string.Compare("b", "a"), 1);
AssertEquals(string.Compare("a", "a"), 0);
}
[Test]
public void IndexOf()
{
var s = "12341234";
String two = "2";
AssertEquals(s.IndexOf(two), 1);
AssertEquals(s.IndexOf("2", 4), 5);
AssertEquals(s.IndexOf('2'), 1);
AssertEquals(s.IndexOf('2', 4), 5);
}
[Test]
public void LastIndexOf()
{
var s = "12341234";
AssertEquals(s.LastIndexOf("2"), 5);
AssertEquals(s.LastIndexOf("2", 4), 1);
AssertEquals(s.LastIndexOf('2'), 5);
AssertEquals(s.LastIndexOf('2', 4), 1);
}
[Test]
public void Substring()
{
var s = "12341234";
AssertEquals(s.Substring(4, 2), "12");
AssertEquals(s.Substring(6), "34");
}
[Test]
public void SplitCharArray()
{
var s = "12a34b56c78";
var parts = s.Split('a', 'b', 'c');
AssertEquals(parts.Length, 4);
AssertEquals(parts[0], "12");
AssertEquals(parts[1], "34");
AssertEquals(parts[2], "56");
AssertEquals(parts[3], "78");
}
[Test]
public void SplitCharArrayWithCount()
{
var s = "12a34b56c78";
var parts = s.Split(new[] { 'a', 'b', 'c' }, 3);
AssertEquals(parts.Length, 3);
AssertEquals(parts[0], "12");
AssertEquals(parts[1], "34");
AssertEquals(parts[2], "56");
}
[Test]
public void CharCode()
{
char b = 'b';
char a = 'a';
int i = b - a;
AssertEquals(i, 1);
}
[Test]
public void PreIncrementCharacter()
{
char b = 'b';
var c = ++b;
AssertEquals(b, 'c');
AssertEquals(c, 'c');
}
[Test]
public void PostIncrementCharacter()
{
char b = 'b';
var stillB = b++;
AssertEquals(b, 'c');
AssertEquals(stillB, 'b');
}
[Test]
public void StringFormat()
{
var s = "1) {0} 2) {1}";
var result = string.Format(s, 1, 2);
AssertEquals(result, "1) 1 2) 2");
}
[Test]
public void Foreach()
{
var s = "1234";
var chars = s.ToArray();
AssertEquals(chars[0], '1');
AssertEquals(chars[1], '2');
AssertEquals(chars[2], '3');
AssertEquals(chars[3], '4');
}
[Test]
public void Contains()
{
var s = "hello world";
AssertTrue(s.Contains("world"));
}
[Test]
public void IsWhiteSpace()
{
AssertTrue(char.IsWhiteSpace(' '));
AssertTrue(char.IsWhiteSpace('\t'));
AssertTrue(char.IsWhiteSpace('\r'));
AssertTrue(char.IsWhiteSpace('\n'));
AssertTrue((!char.IsWhiteSpace('a')));
}
[Test]
public void IsDigit()
{
AssertTrue(char.IsDigit('0'));
AssertTrue(char.IsDigit('3'));
AssertTrue(char.IsDigit('9'));
AssertTrue((!char.IsDigit('a')));
}
[Test]
public void ToStringOnNull()
{
object o = null;
var s = "foo" + o;
AssertEquals(s, "foo");
}
[Test]
public void SingleQuotesInsideStringAreNotEscaped()
{
var s = "'foo'";
AssertEquals(s.Length, 5);
}
[Test]
public void Interpolation()
{
var number = 54;
var str = "hello";
var s = $"Output: {str}: {number}";
AssertEquals(s, "Output: hello: 54");
}
[Test]
public void InterpolationOneValueIsString()
{
var number = 54;
var str = $"{number}";
AssertTrue(str is string);
AssertEquals(str, "54");
}
[Test]
public void InterpolatedStringImplicitConversion()
{
var number = 54;
ImplicitString str = $"{number}";
AssertTrue(str is ImplicitString);
}
public class ImplicitString
{
public string Value;
public ImplicitString(string value)
{
Value = value;
}
public static implicit operator ImplicitString(string s)
{
return new ImplicitString(s);
}
}
[Test]
public void Split5()
{
var s = "5";
var parts = s.Split('.');
AssertEquals(parts.Length, 1);
AssertEquals(parts[0], "5");
}
}
}
| |
/*
* Copyright (c) Contributors, http://aurora-sim.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Aurora-Sim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using Aurora.Framework;
using Nini.Config;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using OpenSim.Services.Interfaces;
namespace Aurora.Services.DataService
{
public class LocalInventoryConnector : IInventoryData
{
protected IGenericData GD;
protected IRegistryCore m_registry;
protected string m_foldersrealm = "inventoryfolders";
protected string m_itemsrealm = "inventoryitems";
#region IInventoryData Members
public virtual void Initialize(IGenericData GenericData, IConfigSource source, IRegistryCore simBase,
string defaultConnectionString)
{
if (source.Configs["AuroraConnectors"].GetString("InventoryConnector", "LocalConnector") == "LocalConnector")
{
GD = GenericData;
string connectionString = defaultConnectionString;
if (source.Configs[Name] != null)
connectionString = source.Configs[Name].GetString("ConnectionString", defaultConnectionString);
GD.ConnectToDatabase(connectionString, "Inventory",
source.Configs["AuroraConnectors"].GetBoolean("ValidateTables", true));
DataManager.DataManager.RegisterPlugin(this);
}
m_registry = simBase;
}
public string Name
{
get { return "IInventoryData"; }
}
public virtual List<InventoryFolderBase> GetFolders(string[] fields, string[] vals)
{
Dictionary<string, List<string>> retVal = GD.QueryNames(fields, vals, m_foldersrealm, "*");
return ParseInventoryFolders(ref retVal);
}
public virtual List<InventoryItemBase> GetItems(string[] fields, string[] vals)
{
string query = "";
for (int i = 0; i < fields.Length; i++)
{
query += String.Format("where {0} = '{1}' and ", fields[i], vals[i]);
i++;
}
query = query.Remove(query.Length - 5);
using (IDataReader reader = GD.QueryData(query, m_itemsrealm, "*"))
{
try
{
return ParseInventoryItems(reader);
}
catch
{
}
finally
{
GD.CloseDatabase();
}
}
return null;
}
public virtual OSDArray GetLLSDItems(string[] fields, string[] vals)
{
string query = "";
for (int i = 0; i < fields.Length; i++)
{
query += String.Format("where {0} = '{1}' and ", fields[i], vals[i]);
i++;
}
query = query.Remove(query.Length - 5);
using (IDataReader reader = GD.QueryData(query, m_itemsrealm, "*"))
{
try
{
return ParseLLSDInventoryItems(reader);
}
catch
{
}
finally
{
GD.CloseDatabase();
}
}
return null;
}
public virtual bool HasAssetForUser(UUID userID, UUID assetID)
{
QueryFilter filter = new QueryFilter();
filter.andFilters["assetID"] = assetID;
filter.andFilters["avatarID"] = userID;
List<string> q = GD.Query(new[] { "*" }, m_itemsrealm, filter, null, null, null);
return !(q != null && q.Count > 0);
}
public virtual string GetItemNameByAsset(UUID assetID)
{
QueryFilter filter = new QueryFilter();
filter.andFilters["assetID"] = assetID;
List<string> q = GD.Query(new[] { "inventoryName" }, m_itemsrealm, filter, null, null, null);
return (q != null && q.Count > 0) ? q[0] : "";
}
public virtual byte[] FetchInventoryReply(OSDArray fetchRequest, UUID AgentID, UUID forceOwnerID, UUID libraryOwnerID)
{
LLSDSerializationDictionary contents = new LLSDSerializationDictionary();
contents.WriteStartMap("llsd"); //Start llsd
contents.WriteKey("folders"); //Start array items
contents.WriteStartArray("folders"); //Start array folders
foreach (OSD m in fetchRequest)
{
contents.WriteStartMap("internalContents"); //Start internalContents kvp
OSDMap invFetch = (OSDMap) m;
//UUID agent_id = invFetch["agent_id"].AsUUID();
UUID owner_id = invFetch["owner_id"].AsUUID();
UUID folder_id = invFetch["folder_id"].AsUUID();
//bool fetch_folders = invFetch["fetch_folders"].AsBoolean();
//bool fetch_items = invFetch["fetch_items"].AsBoolean();
//int sort_order = invFetch["sort_order"].AsInteger();
//Set the normal stuff
contents["agent_id"] = AgentID;
contents["owner_id"] = owner_id;
contents["folder_id"] = folder_id;
contents.WriteKey("items"); //Start array items
contents.WriteStartArray("items");
List<UUID> moreLinkedItems = new List<UUID>();
int count = 0;
bool addToCount = true;
string query = String.Format("where {0} = '{1}'", "parentFolderID", folder_id);
redoQuery:
using (IDataReader retVal = GD.QueryData(query, m_itemsrealm, "*"))
{
try
{
while (retVal.Read())
{
contents.WriteStartMap("item"); //Start item kvp
UUID assetID = UUID.Parse(retVal["assetID"].ToString());
contents["asset_id"] = assetID;
contents["name"] = retVal["inventoryName"].ToString();
contents["desc"] = retVal["inventoryDescription"].ToString();
contents.WriteKey("permissions"); //Start permissions kvp
contents.WriteStartMap("permissions");
contents["group_id"] = UUID.Parse(retVal["groupID"].ToString());
contents["is_owner_group"] = int.Parse(retVal["groupOwned"].ToString()) == 1;
contents["group_mask"] = uint.Parse(retVal["inventoryGroupPermissions"].ToString());
contents["owner_id"] = forceOwnerID == UUID.Zero
? UUID.Parse(retVal["avatarID"].ToString())
: forceOwnerID;
contents["last_owner_id"] = UUID.Parse(retVal["avatarID"].ToString());
contents["next_owner_mask"] = uint.Parse(retVal["inventoryNextPermissions"].ToString());
contents["owner_mask"] = uint.Parse(retVal["inventoryCurrentPermissions"].ToString());
UUID creator;
if (UUID.TryParse(retVal["creatorID"].ToString(), out creator))
contents["creator_id"] = creator;
else
contents["creator_id"] = UUID.Zero;
contents["base_mask"] = uint.Parse(retVal["inventoryBasePermissions"].ToString());
contents["everyone_mask"] = uint.Parse(retVal["inventoryEveryOnePermissions"].ToString());
contents.WriteEndMap( /*Permissions*/);
contents.WriteKey("sale_info"); //Start permissions kvp
contents.WriteStartMap("sale_info"); //Start sale_info kvp
contents["sale_price"] = int.Parse(retVal["salePrice"].ToString());
switch (byte.Parse(retVal["saleType"].ToString()))
{
default:
contents["sale_type"] = "not";
break;
case 1:
contents["sale_type"] = "original";
break;
case 2:
contents["sale_type"] = "copy";
break;
case 3:
contents["sale_type"] = "contents";
break;
}
contents.WriteEndMap( /*sale_info*/);
contents["created_at"] = int.Parse(retVal["creationDate"].ToString());
contents["flags"] = uint.Parse(retVal["flags"].ToString());
UUID inventoryID = UUID.Parse(retVal["inventoryID"].ToString());
contents["item_id"] = inventoryID;
contents["parent_id"] = UUID.Parse(retVal["parentFolderID"].ToString());
UUID avatarID = forceOwnerID == UUID.Zero
? UUID.Parse(retVal["avatarID"].ToString())
: forceOwnerID;
contents["agent_id"] = avatarID;
AssetType assetType = (AssetType) int.Parse(retVal["assetType"].ToString());
if (assetType == AssetType.Link)
moreLinkedItems.Add(assetID);
contents["type"] = Utils.AssetTypeToString((AssetType) Util.CheckMeshType((sbyte) assetType));
InventoryType invType = (InventoryType) int.Parse(retVal["invType"].ToString());
contents["inv_type"] = Utils.InventoryTypeToString(invType);
if (addToCount)
count++;
contents.WriteEndMap( /*"item"*/); //end array items
}
}
catch
{
}
finally
{
GD.CloseDatabase();
}
}
if (moreLinkedItems.Count > 0)
{
addToCount = false;
query = String.Format("where {0} = '{1}' and (", "avatarID", AgentID);
#if (!ISWIN)
foreach (UUID item in moreLinkedItems)
query = query + String.Format("{0} = '{1}' or ", "inventoryID", item);
#else
query = moreLinkedItems.Aggregate(query, (current, t) => current + String.Format("{0} = '{1}' or ", "inventoryID", t));
#endif
query = query.Remove(query.Length - 4, 4);
query += ")";
moreLinkedItems.Clear();
goto redoQuery;
}
contents.WriteEndArray( /*"items"*/); //end array items
contents.WriteStartArray("categories"); //We don't send any folders
int version = 0;
QueryFilter filter = new QueryFilter();
filter.andFilters["folderID"] = folder_id;
List<string> versionRetVal = GD.Query(new[]{
"version",
"type"
}, m_foldersrealm, filter, null, null, null);
if (versionRetVal.Count > 0)
{
version = int.Parse(versionRetVal[0]);
if (int.Parse(versionRetVal[1]) == (int) AssetType.TrashFolder ||
int.Parse(versionRetVal[1]) == (int) AssetType.CurrentOutfitFolder ||
int.Parse(versionRetVal[1]) == (int) AssetType.LinkFolder)
{
//If it is the trash folder, we need to send its descendents, because the viewer wants it
query = String.Format("where {0} = '{1}' and {2} = '{3}'", "parentFolderID", folder_id,
"agentID", AgentID);
using (IDataReader retVal = GD.QueryData(query, m_foldersrealm, "*"))
{
try
{
while (retVal.Read())
{
contents.WriteStartMap("folder"); //Start item kvp
contents["folder_id"] = UUID.Parse(retVal["folderID"].ToString());
contents["parent_id"] = UUID.Parse(retVal["parentFolderID"].ToString());
contents["name"] = retVal["folderName"].ToString();
int type = int.Parse(retVal["type"].ToString());
contents["type"] = type;
contents["preferred_type"] = type;
count++;
contents.WriteEndMap( /*"folder"*/); //end array items
}
}
catch
{
}
finally
{
GD.CloseDatabase();
}
}
}
}
contents.WriteEndArray( /*"categories"*/);
contents["descendents"] = count;
contents["version"] = version;
//Now add it to the folder array
contents.WriteEndMap(); //end array internalContents
}
contents.WriteEndArray(); //end array folders
contents.WriteEndMap( /*"llsd"*/); //end llsd
try
{
return contents.GetSerializer();
}
finally
{
contents = null;
}
}
public virtual bool StoreFolder(InventoryFolderBase folder)
{
QueryFilter filter = new QueryFilter();
filter.andFilters["folderID"] = folder.ID;
GD.Delete(m_foldersrealm, filter);
Dictionary<string, object> row = new Dictionary<string, object>(6);
row["folderName"] = folder.Name.MySqlEscape(64);
row["type"] = folder.Type;
row["version"] = folder.Version;
row["folderID"] = folder.ID;
row["agentID"] = folder.Owner;
row["parentFolderID"] = folder.ParentID;
return GD.Insert(m_foldersrealm, row);
}
public virtual bool StoreItem(InventoryItemBase item)
{
QueryFilter filter = new QueryFilter();
filter.andFilters["inventoryID"] = item.ID;
GD.Delete(m_itemsrealm, filter);
Dictionary<string, object> row = new Dictionary<string, object>(20);
row["assetID"] = item.AssetID;
row["assetType"] = item.AssetType;
row["inventoryName"] = item.Name.MySqlEscape(64);
row["inventoryDescription"] = item.Description.MySqlEscape(128);
row["inventoryNextPermissions"] = item.NextPermissions;
row["inventoryCurrentPermissions"] = item.CurrentPermissions;
row["invType"] = item.InvType;
row["creatorID"] = item.CreatorIdentification;
row["inventoryBasePermissions"] = item.BasePermissions;
row["inventoryEveryOnePermissions"] = item.EveryOnePermissions;
row["salePrice"] = item.SalePrice;
row["saleType"] = item.SaleType;
row["creationDate"] = item.CreationDate;
row["groupID"] = item.GroupID;
row["groupOwned"] = item.GroupOwned ? "1" : "0";
row["flags"] = item.Flags;
row["inventoryID"] = item.ID;
row["avatarID"] = item.Owner;
row["parentFolderID"] = item.Folder;
row["inventoryGroupPermissions"] = item.GroupPermissions;
return GD.Insert(m_itemsrealm, row);
}
public virtual bool UpdateAssetIDForItem(UUID itemID, UUID assetID)
{
Dictionary<string, object> values = new Dictionary<string, object>(1);
values["assetID"] = assetID;
QueryFilter filter = new QueryFilter();
filter.andFilters["inventoryID"] = itemID;
return GD.Update(m_itemsrealm, values, null, filter, null, null);
}
public virtual bool DeleteFolders(string field, string val, bool safe)
{
QueryFilter filter = new QueryFilter();
filter.andFilters[field] = val;
if (safe)
{
filter.andFilters["type"] = "-1";
}
return GD.Delete(m_foldersrealm, filter);
}
public virtual bool DeleteItems(string field, string val)
{
QueryFilter filter = new QueryFilter();
filter.andFilters[field] = val;
return GD.Delete(m_itemsrealm, filter);
}
public virtual bool MoveItem(string id, string newParent)
{
Dictionary<string, object> values = new Dictionary<string, object>(1);
values["parentFolderID"] = newParent;
QueryFilter filter = new QueryFilter();
filter.andFilters["inventoryID"] = id;
return GD.Update(m_itemsrealm, values, null, filter, null, null);
}
public virtual void IncrementFolder(UUID folderID)
{
Dictionary<string, int> incrementValues = new Dictionary<string, int>(1);
incrementValues["version"] = 1;
QueryFilter filter = new QueryFilter();
filter.andFilters["folderID"] = folderID.ToString();
GD.Update(m_foldersrealm, new Dictionary<string, object>(0), incrementValues, filter, null, null);
}
public virtual void IncrementFolderByItem(UUID itemID)
{
QueryFilter filter = new QueryFilter();
filter.andFilters["inventoryID"] = itemID;
List<string> values = GD.Query(new string[] { "parentFolderID" }, m_itemsrealm, filter, null, null, null);
if (values.Count > 0)
{
IncrementFolder(UUID.Parse(values[0]));
}
}
public virtual InventoryItemBase[] GetActiveGestures(UUID principalID)
{
string query = String.Format("where {0} = '{1}' and {2} = '{3}'", "avatarID", principalID, "assetType",
(int) AssetType.Gesture);
using (IDataReader reader = GD.QueryData(query, m_itemsrealm, "*"))
{
List<InventoryItemBase> items = new List<InventoryItemBase>();
try
{
items = ParseInventoryItems(reader);
#if (!ISWIN)
items.RemoveAll(delegate(InventoryItemBase item)
{
return (item.Flags & 1) != 1; //1 means that it is active, so remove all ones that do not have a 1
});
#else
items.RemoveAll(
item => (item.Flags & 1) != 1);
#endif
}
catch
{
}
finally
{
GD.CloseDatabase();
}
return items.ToArray();
}
}
#endregion
public void Dispose()
{
}
private OSDArray ParseLLSDInventoryItems(IDataReader retVal)
{
OSDArray array = new OSDArray();
while (retVal.Read())
{
OSDMap item = new OSDMap();
OSDMap permissions = new OSDMap();
item["asset_id"] = UUID.Parse(retVal["assetID"].ToString());
item["name"] = retVal["inventoryName"].ToString();
item["desc"] = retVal["inventoryDescription"].ToString();
permissions["next_owner_mask"] = uint.Parse(retVal["inventoryNextPermissions"].ToString());
permissions["owner_mask"] = uint.Parse(retVal["inventoryCurrentPermissions"].ToString());
UUID creator;
if (UUID.TryParse(retVal["creatorID"].ToString(), out creator))
permissions["creator_id"] = creator;
else
permissions["creator_id"] = UUID.Zero;
permissions["base_mask"] = uint.Parse(retVal["inventoryBasePermissions"].ToString());
permissions["everyone_mask"] = uint.Parse(retVal["inventoryEveryOnePermissions"].ToString());
OSDMap sale_info = new OSDMap();
sale_info["sale_price"] = int.Parse(retVal["salePrice"].ToString());
switch (byte.Parse(retVal["saleType"].ToString()))
{
default:
sale_info["sale_type"] = "not";
break;
case 1:
sale_info["sale_type"] = "original";
break;
case 2:
sale_info["sale_type"] = "copy";
break;
case 3:
sale_info["sale_type"] = "contents";
break;
}
item["sale_info"] = sale_info;
item["created_at"] = int.Parse(retVal["creationDate"].ToString());
permissions["group_id"] = UUID.Parse(retVal["groupID"].ToString());
permissions["is_owner_group"] = int.Parse(retVal["groupOwned"].ToString()) == 1;
item["flags"] = uint.Parse(retVal["flags"].ToString());
item["item_id"] = UUID.Parse(retVal["inventoryID"].ToString());
item["parent_id"] = UUID.Parse(retVal["parentFolderID"].ToString());
permissions["group_mask"] = uint.Parse(retVal["inventoryGroupPermissions"].ToString());
item["agent_id"] = UUID.Parse(retVal["avatarID"].ToString());
permissions["owner_id"] = item["agent_id"];
permissions["last_owner_id"] = item["agent_id"];
item["type"] = Utils.AssetTypeToString((AssetType) int.Parse(retVal["assetType"].ToString()));
item["inv_type"] = Utils.InventoryTypeToString((InventoryType) int.Parse(retVal["invType"].ToString()));
item["permissions"] = permissions;
array.Add(item);
}
//retVal.Close();
return array;
}
private List<InventoryFolderBase> ParseInventoryFolders(ref Dictionary<string, List<string>> retVal)
{
List<InventoryFolderBase> folders = new List<InventoryFolderBase>();
if (retVal.Count == 0)
return folders;
for (int i = 0; i < retVal.ElementAt(0).Value.Count; i++)
{
InventoryFolderBase folder = new InventoryFolderBase
{
Name = retVal["folderName"][i],
Type = short.Parse(retVal["type"][i]),
Version = (ushort) int.Parse(retVal["version"][i]),
ID = UUID.Parse(retVal["folderID"][i]),
Owner = UUID.Parse(retVal["agentID"][i]),
ParentID = UUID.Parse(retVal["parentFolderID"][i])
};
folders.Add(folder);
}
//retVal.Clear();
return folders;
}
private List<InventoryItemBase> ParseInventoryItems(IDataReader retVal)
{
List<InventoryItemBase> items = new List<InventoryItemBase>();
while (retVal.Read())
{
InventoryItemBase item = new InventoryItemBase
{
AssetID = UUID.Parse(retVal["assetID"].ToString()),
AssetType = int.Parse(retVal["assetType"].ToString()),
Name = retVal["inventoryName"].ToString(),
Description = retVal["inventoryDescription"].ToString(),
NextPermissions =
uint.Parse(retVal["inventoryNextPermissions"].ToString()),
CurrentPermissions =
uint.Parse(retVal["inventoryCurrentPermissions"].ToString()),
InvType = int.Parse(retVal["invType"].ToString()),
CreatorIdentification = retVal["creatorID"].ToString(),
BasePermissions =
uint.Parse(retVal["inventoryBasePermissions"].ToString()),
EveryOnePermissions =
uint.Parse(retVal["inventoryEveryOnePermissions"].ToString()),
SalePrice = int.Parse(retVal["salePrice"].ToString()),
SaleType = byte.Parse(retVal["saleType"].ToString()),
CreationDate = int.Parse(retVal["creationDate"].ToString()),
GroupID = UUID.Parse(retVal["groupID"].ToString()),
GroupOwned = int.Parse(retVal["groupOwned"].ToString()) == 1,
Flags = uint.Parse(retVal["flags"].ToString()),
ID = UUID.Parse(retVal["inventoryID"].ToString()),
Owner = UUID.Parse(retVal["avatarID"].ToString()),
Folder = UUID.Parse(retVal["parentFolderID"].ToString()),
GroupPermissions =
uint.Parse(retVal["inventoryGroupPermissions"].ToString())
};
items.Add(item);
}
//retVal.Close();
return items;
}
#region Nested type: LLSDSerializationDictionary
public class LLSDSerializationDictionary
{
private readonly MemoryStream sw = new MemoryStream();
private readonly XmlTextWriter writer;
public LLSDSerializationDictionary()
{
writer = new XmlTextWriter(sw, Encoding.UTF8);
writer.WriteStartElement(String.Empty, "llsd", String.Empty);
}
public object this[string name]
{
set
{
writer.WriteStartElement(String.Empty, "key", String.Empty);
writer.WriteString(name);
writer.WriteEndElement();
Type t = value.GetType();
if (t == typeof (bool))
{
writer.WriteStartElement(String.Empty, "boolean", String.Empty);
writer.WriteValue(value);
writer.WriteEndElement();
}
else if (t == typeof (int))
{
writer.WriteStartElement(String.Empty, "integer", String.Empty);
writer.WriteValue(value);
writer.WriteEndElement();
}
else if (t == typeof (uint))
{
writer.WriteStartElement(String.Empty, "integer", String.Empty);
writer.WriteValue(value.ToString());
writer.WriteEndElement();
}
else if (t == typeof (float))
{
writer.WriteStartElement(String.Empty, "real", String.Empty);
writer.WriteValue(value);
writer.WriteEndElement();
}
else if (t == typeof (double))
{
writer.WriteStartElement(String.Empty, "real", String.Empty);
writer.WriteValue(value);
writer.WriteEndElement();
}
else if (t == typeof (string))
{
writer.WriteStartElement(String.Empty, "string", String.Empty);
writer.WriteValue(value);
writer.WriteEndElement();
}
else if (t == typeof (UUID))
{
writer.WriteStartElement(String.Empty, "uuid", String.Empty);
writer.WriteValue(value.ToString()); //UUID has to be string!
writer.WriteEndElement();
}
else if (t == typeof (DateTime))
{
writer.WriteStartElement(String.Empty, "date", String.Empty);
writer.WriteValue(AsString((DateTime) value));
writer.WriteEndElement();
}
else if (t == typeof (Uri))
{
writer.WriteStartElement(String.Empty, "uri", String.Empty);
writer.WriteValue((value).ToString()); //URI has to be string
writer.WriteEndElement();
}
else if (t == typeof (byte[]))
{
writer.WriteStartElement(String.Empty, "binary", String.Empty);
writer.WriteStartAttribute(String.Empty, "encoding", String.Empty);
writer.WriteString("base64");
writer.WriteEndAttribute();
writer.WriteValue(Convert.ToBase64String((byte[]) value)); //Has to be base64
writer.WriteEndElement();
}
t = null;
}
}
public void WriteStartMap(string name)
{
writer.WriteStartElement(String.Empty, "map", String.Empty);
}
public void WriteEndMap()
{
writer.WriteEndElement();
}
public void WriteStartArray(string name)
{
writer.WriteStartElement(String.Empty, "array", String.Empty);
}
public void WriteEndArray()
{
writer.WriteEndElement();
}
public void WriteKey(string key)
{
writer.WriteStartElement(String.Empty, "key", String.Empty);
writer.WriteString(key);
writer.WriteEndElement();
}
public void WriteElement(object value)
{
Type t = value.GetType();
if (t == typeof (bool))
{
writer.WriteStartElement(String.Empty, "boolean", String.Empty);
writer.WriteValue(value);
writer.WriteEndElement();
}
else if (t == typeof (int))
{
writer.WriteStartElement(String.Empty, "integer", String.Empty);
writer.WriteValue(value);
writer.WriteEndElement();
}
else if (t == typeof (uint))
{
writer.WriteStartElement(String.Empty, "integer", String.Empty);
writer.WriteValue(value.ToString());
writer.WriteEndElement();
}
else if (t == typeof (float))
{
writer.WriteStartElement(String.Empty, "real", String.Empty);
writer.WriteValue(value);
writer.WriteEndElement();
}
else if (t == typeof (double))
{
writer.WriteStartElement(String.Empty, "real", String.Empty);
writer.WriteValue(value);
writer.WriteEndElement();
}
else if (t == typeof (string))
{
writer.WriteStartElement(String.Empty, "string", String.Empty);
writer.WriteValue(value);
writer.WriteEndElement();
}
else if (t == typeof (UUID))
{
writer.WriteStartElement(String.Empty, "uuid", String.Empty);
writer.WriteValue(value.ToString()); //UUID has to be string!
writer.WriteEndElement();
}
else if (t == typeof (DateTime))
{
writer.WriteStartElement(String.Empty, "date", String.Empty);
writer.WriteValue(AsString((DateTime) value));
writer.WriteEndElement();
}
else if (t == typeof (Uri))
{
writer.WriteStartElement(String.Empty, "uri", String.Empty);
writer.WriteValue((value).ToString()); //URI has to be string
writer.WriteEndElement();
}
else if (t == typeof (byte[]))
{
writer.WriteStartElement(String.Empty, "binary", String.Empty);
writer.WriteStartAttribute(String.Empty, "encoding", String.Empty);
writer.WriteString("base64");
writer.WriteEndAttribute();
writer.WriteValue(Convert.ToBase64String((byte[]) value)); //Has to be base64
writer.WriteEndElement();
}
t = null;
}
public byte[] GetSerializer()
{
writer.WriteEndElement();
writer.Close();
byte[] array = sw.ToArray();
/*byte[] newarr = new byte[array.Length - 3];
Array.Copy(array, 3, newarr, 0, newarr.Length);
writer = null;
sw = null;
array = null;*/
return array;
}
private string AsString(DateTime value)
{
string format = value.Millisecond > 0 ? "yyyy-MM-ddTHH:mm:ss.ffZ" : "yyyy-MM-ddTHH:mm:ssZ";
return value.ToUniversalTime().ToString(format);
}
}
#endregion
}
}
| |
/*
The MIT License (MIT)
Copyright (c) 2016 GuyQuad
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.
You can contact me by email at guyquad27@gmail.com or on Reddit at https://www.reddit.com/user/GuyQuad
*/
using UnityEngine;
using UnityEditor;
using System.Collections;
[CustomEditor (typeof(BezierCurveCollider2D))]
public class BezierCurveCollider_Editor : Editor {
BezierCurveCollider2D bc;
void OnEnable()
{
bc = (BezierCurveCollider2D)target;
if (!bc.initialized) bc.Init();
}
public override void OnInspectorGUI()
{
GUI.changed = false;
DrawDefaultInspector();
if (!bc.edge.offset.Equals(Vector2.zero)) bc.edge.offset = Vector2.zero; // prevent changes to offset
EditorGUILayout.BeginHorizontal();
if (GUILayout.Button("Add Point"))
{
bc.addControlPoint();
}
if (bc.controlPoints.Count > 2) // minimum 2 control points are always required
{
if (GUILayout.Button("Remove Point"))
{
bc.removeControlPoint();
}
}
EditorGUILayout.EndHorizontal();
if (GUILayout.Button("Reset"))
{
bc.initialized = false;
bc.Init();
}
if (GUI.changed)
{
bc.drawCurve();
}
}
void OnSceneGUI()
{
GUI.changed = false;
Handles.color = Color.yellow;
// manage control points
for (int i = 0; i < bc.controlPoints.Count; i++)
{
Vector3 start = bc.controlPoints[i];
Vector3 newPos = Handles.FreeMoveHandle(bc.controlPoints[i], Quaternion.identity, .25f, Vector3.zero, Handles.ConeCap);
bc.controlPoints[i] = newPos;
// if the control point was moved.. offset the joining handler points
if (!start.Equals(newPos))
{
Vector2 offset = newPos - start;
// if there are only 2 control points
if(bc.controlPoints.Count == 2)
{
bc.handlerPoints[i] += offset;
}
// if there are more than 2 control points
else if (bc.controlPoints.Count > 2)
{
// if you moved the first control point
if(i == 0)
{
bc.handlerPoints[0] += offset; // offset the handle
}
// if you moved the last control point
else if (i == bc.controlPoints.Count - 1)
{
bc.handlerPoints[bc.handlerPoints.Count-1] += offset; // offset the handle
}
// if you moved one of the other control points in the middle
else
{
int ind= (i * 2) - 1;
bc.handlerPoints[ind] += offset; // offset the top handle
bc.handlerPoints[++ind] += offset; // offset the bottom handle
}
}
}
}
// manage handler points
// when using continous curves
if (!bc.continous)
{
for (int i = 0; i < bc.handlerPoints.Count; i++)
{
bc.handlerPoints[i] = Handles.FreeMoveHandle(bc.handlerPoints[i], Quaternion.identity, .5f, Vector3.zero, Handles.ConeCap);
}
}
else
// when using non-continous curves
{
for (int i = 0; i < bc.handlerPoints.Count; i++)
{
// if there are only 2 control points
if (bc.controlPoints.Count == 2)
{
bc.handlerPoints[i] = Handles.FreeMoveHandle(bc.handlerPoints[i], Quaternion.identity, .5f, Vector3.zero, Handles.ConeCap);
}
// if there are more than 2 control points
else if (bc.controlPoints.Count > 2)
{
// no additional calculations required for the first and last handler points
if (i == 0 || i == bc.handlerPoints.Count - 1)
{
bc.handlerPoints[i] = Handles.FreeMoveHandle(bc.handlerPoints[i], Quaternion.identity, .5f, Vector3.zero, Handles.ConeCap);
}
else
{
// changes for the rest of the handler points in the middle
Vector3 start = bc.handlerPoints[i];
Vector3 newPos = Handles.FreeMoveHandle(bc.handlerPoints[i], Quaternion.identity, .5f, Vector3.zero, Handles.ConeCap);
bc.handlerPoints[i] = newPos;
if (!start.Equals(newPos))
{
bool movedTop = (i % 2 == 1) ? true : false;
// if we are moving the top handle
if (movedTop)
{
int cp = (i + 1) / 2; // get the control point for this handle
// calc angle of the top handle
Vector2 dir = bc.handlerPoints[i] - bc.controlPoints[cp];
float angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
angle = (angle + 360) % 360;
// adjust the angle of the bottom handle
float magH2 = Vector2.Distance(bc.controlPoints[cp], bc.handlerPoints[i + 1]);
angle = 270 - angle;
float x = bc.controlPoints[cp].x + magH2 * Mathf.Sin(angle * Mathf.Deg2Rad);
float y = bc.controlPoints[cp].y + magH2 * Mathf.Cos(angle * Mathf.Deg2Rad);
bc.handlerPoints[i + 1] = new Vector2(x, y);
}
else
//if we are moving the bottom handle
{
int cp = i / 2; // get the control point for this handle
// calc the angle of the bottom angle
Vector2 dir = bc.controlPoints[cp] - bc.handlerPoints[i];
float angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
angle = (angle + 360) % 360;
// adjust the angle of top handle
float magH2 = Vector2.Distance(bc.controlPoints[cp], bc.handlerPoints[i - 1]);
angle = 360 - angle + 90;
float x = bc.controlPoints[cp].x + magH2 * Mathf.Sin(angle * Mathf.Deg2Rad);
float y = bc.controlPoints[cp].y + magH2 * Mathf.Cos(angle * Mathf.Deg2Rad);
bc.handlerPoints[i - 1] = new Vector2(x, y);
}
}
}
}
}
}
// draw a line from the control point to handler points
if (bc.handlerPoints.Count == 2)
{
Handles.DrawLine(bc.handlerPoints[0], bc.controlPoints[0]);
Handles.DrawLine(bc.handlerPoints[1], bc.controlPoints[1]);
}
else
{
int c = 0;
for (int i = 0; i < bc.handlerPoints.Count; i = i+2)
{
Handles.DrawLine(bc.handlerPoints[i], bc.controlPoints[c]);
Handles.DrawLine(bc.handlerPoints[i+1], bc.controlPoints[c+1]);
c++;
}
}
if (GUI.changed)
{
bc.drawCurve();
}
}
}
| |
// 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.IO;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace System.IO.Tests
{
public partial class StreamReaderTests
{
protected virtual Stream CreateStream()
{
return new MemoryStream();
}
protected virtual Stream GetSmallStream()
{
byte[] testData = new byte[] { 72, 69, 76, 76, 79 };
return new MemoryStream(testData);
}
protected virtual Stream GetLargeStream()
{
byte[] testData = new byte[] { 72, 69, 76, 76, 79 };
// System.Collections.Generic.
List<byte> data = new List<byte>();
for (int i = 0; i < 1000; i++)
{
data.AddRange(testData);
}
return new MemoryStream(data.ToArray());
}
protected Tuple<char[], StreamReader> GetCharArrayStream()
{
var chArr = new char[]{
char.MinValue
,char.MaxValue
,'\t'
,' '
,'$'
,'@'
,'#'
,'\0'
,'\v'
,'\''
,'\u3190'
,'\uC3A0'
,'A'
,'5'
,'\r'
,'\uFE70'
,'-'
,';'
,'\r'
,'\n'
,'T'
,'3'
,'\n'
,'K'
,'\u00E6'
};
var ms = CreateStream();
var sw = new StreamWriter(ms);
for (int i = 0; i < chArr.Length; i++)
sw.Write(chArr[i]);
sw.Flush();
ms.Position = 0;
return new Tuple<char[], StreamReader>(chArr, new StreamReader(ms));
}
[Fact]
public void EndOfStream()
{
var sw = new StreamReader(GetSmallStream());
var result = sw.ReadToEnd();
Assert.Equal("HELLO", result);
Assert.True(sw.EndOfStream, "End of Stream was not true after ReadToEnd");
}
[Fact]
public void EndOfStreamSmallDataLargeBuffer()
{
var sw = new StreamReader(GetSmallStream(), Encoding.UTF8, true, 1024);
var result = sw.ReadToEnd();
Assert.Equal("HELLO", result);
Assert.True(sw.EndOfStream, "End of Stream was not true after ReadToEnd");
}
[Fact]
public void EndOfStreamLargeDataSmallBuffer()
{
var sw = new StreamReader(GetLargeStream(), Encoding.UTF8, true, 1);
var result = sw.ReadToEnd();
Assert.Equal(5000, result.Length);
Assert.True(sw.EndOfStream, "End of Stream was not true after ReadToEnd");
}
[Fact]
public void EndOfStreamLargeDataLargeBuffer()
{
var sw = new StreamReader(GetLargeStream(), Encoding.UTF8, true, 1 << 16);
var result = sw.ReadToEnd();
Assert.Equal(5000, result.Length);
Assert.True(sw.EndOfStream, "End of Stream was not true after ReadToEnd");
}
[Fact]
public async Task ReadToEndAsync()
{
var sw = new StreamReader(GetLargeStream());
var result = await sw.ReadToEndAsync();
Assert.Equal(5000, result.Length);
}
[Fact]
public void GetBaseStream()
{
var ms = GetSmallStream();
var sw = new StreamReader(ms);
Assert.Same(sw.BaseStream, ms);
}
[Fact]
public void TestRead()
{
var baseInfo = GetCharArrayStream();
var sr = baseInfo.Item2;
for (int i = 0; i < baseInfo.Item1.Length; i++)
{
int tmp = sr.Read();
Assert.Equal((int)baseInfo.Item1[i], tmp);
}
sr.Dispose();
}
[Fact]
public void TestPeek()
{
var baseInfo = GetCharArrayStream();
var sr = baseInfo.Item2;
for (int i = 0; i < baseInfo.Item1.Length; i++)
{
var peek = sr.Peek();
Assert.Equal((int)baseInfo.Item1[i], peek);
sr.Read();
}
}
[Fact]
public void ArgumentNullOnNullArray()
{
var baseInfo = GetCharArrayStream();
var sr = baseInfo.Item2;
Assert.Throws<ArgumentNullException>(() => sr.Read(null, 0, 0));
}
[Fact]
public void ArgumentOutOfRangeOnInvalidOffset()
{
var sr = GetCharArrayStream().Item2;
Assert.Throws<ArgumentOutOfRangeException>(() => sr.Read(new char[0], -1, 0));
}
[Fact]
public void ArgumentOutOfRangeOnNegativCount()
{
var sr = GetCharArrayStream().Item2;
Assert.Throws<ArgumentException>(() => sr.Read(new char[0], 0, 1));
}
[Fact]
public void ArgumentExceptionOffsetAndCount()
{
var sr = GetCharArrayStream().Item2;
Assert.Throws<ArgumentException>(() => sr.Read(new char[0], 2, 0));
}
[Fact]
public void ObjectDisposedExceptionDisposedStream()
{
var sr = GetCharArrayStream().Item2;
sr.Dispose();
Assert.Throws<ObjectDisposedException>(() => sr.Read(new char[1], 0, 1));
}
[Fact]
public void ObjectDisposedExceptionDisposedBaseStream()
{
var ms = GetSmallStream();
var sr = new StreamReader(ms);
ms.Dispose();
Assert.Throws<ObjectDisposedException>(() => sr.Read(new char[1], 0, 1));
}
[Fact]
public void EmptyStream()
{
var ms = CreateStream();
var sr = new StreamReader(ms);
var buffer = new char[10];
int read = sr.Read(buffer, 0, 1);
Assert.Equal(0, read);
}
[Fact]
public void VanillaReads1()
{
var baseInfo = GetCharArrayStream();
var sr = baseInfo.Item2;
var chArr = new char[baseInfo.Item1.Length];
var read = sr.Read(chArr, 0, chArr.Length);
Assert.Equal(chArr.Length, read);
for (int i = 0; i < baseInfo.Item1.Length; i++)
{
Assert.Equal(baseInfo.Item1[i], chArr[i]);
}
}
[Fact]
public async Task VanillaReads2WithAsync()
{
var baseInfo = GetCharArrayStream();
var sr = baseInfo.Item2;
var chArr = new char[baseInfo.Item1.Length];
var read = await sr.ReadAsync(chArr, 4, 3);
Assert.Equal(read, 3);
for (int i = 0; i < 3; i++)
{
Assert.Equal(baseInfo.Item1[i], chArr[i + 4]);
}
}
[Fact]
public void ObjectDisposedReadLine()
{
var baseInfo = GetCharArrayStream();
var sr = baseInfo.Item2;
sr.Dispose();
Assert.Throws<ObjectDisposedException>(() => sr.ReadLine());
}
[Fact]
public void ObjectDisposedReadLineBaseStream()
{
var ms = GetLargeStream();
var sr = new StreamReader(ms);
ms.Dispose();
Assert.Throws<ObjectDisposedException>(() => sr.ReadLine());
}
[Fact]
public void VanillaReadLines()
{
var baseInfo = GetCharArrayStream();
var sr = baseInfo.Item2;
string valueString = new string(baseInfo.Item1);
var data = sr.ReadLine();
Assert.Equal(valueString.Substring(0, valueString.IndexOf('\r')), data);
data = sr.ReadLine();
Assert.Equal(valueString.Substring(valueString.IndexOf('\r') + 1, 3), data);
data = sr.ReadLine();
Assert.Equal(valueString.Substring(valueString.IndexOf('\n') + 1, 2), data);
data = sr.ReadLine();
Assert.Equal((valueString.Substring(valueString.LastIndexOf('\n') + 1)), data);
}
[Fact]
public void VanillaReadLines2()
{
var baseInfo = GetCharArrayStream();
var sr = baseInfo.Item2;
string valueString = new string(baseInfo.Item1);
var temp = new char[10];
sr.Read(temp, 0, 1);
var data = sr.ReadLine();
Assert.Equal(valueString.Substring(1, valueString.IndexOf('\r') - 1), data);
}
[Fact]
public async Task ContinuousNewLinesAndTabsAsync()
{
var ms = CreateStream();
var sw = new StreamWriter(ms);
sw.Write("\n\n\r\r\n");
sw.Flush();
ms.Position = 0;
var sr = new StreamReader(ms);
for (int i = 0; i < 4; i++)
{
var data = await sr.ReadLineAsync();
Assert.Equal(string.Empty, data);
}
var eol = await sr.ReadLineAsync();
Assert.Null(eol);
}
[Fact]
public void CurrentEncoding()
{
var ms = CreateStream();
var sr = new StreamReader(ms);
Assert.Equal(Encoding.UTF8, sr.CurrentEncoding);
sr = new StreamReader(ms, Encoding.Unicode);
Assert.Equal(Encoding.Unicode, sr.CurrentEncoding);
}
}
}
| |
/* ====================================================================
Copyright 2002-2004 Apache Software Foundation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace NPOI.HSSF.UserModel
{
using System.Collections;
using NPOI.SS.UserModel;
using NPOI.HSSF.Record;
/// <summary>
/// Excel can Get cranky if you give it files containing too
/// many (especially duplicate) objects, and this class can
/// help to avoid those.
/// In general, it's much better to make sure you don't
/// duplicate the objects in your code, as this is likely
/// to be much faster than creating lots and lots of
/// excel objects+records, only to optimise them down to
/// many fewer at a later stage.
/// However, sometimes this is too hard / tricky to do, which
/// is where the use of this class comes in.
/// </summary>
public class HSSFOptimiser
{
/// <summary>
/// Goes through the Workbook, optimising the fonts by
/// removing duplicate ones.
/// For now, only works on fonts used in HSSFCellStyle
/// and HSSFRichTextString. Any other font uses
/// (eg charts, pictures) may well end up broken!
/// This can be a slow operation, especially if you have
/// lots of cells, cell styles or rich text strings
/// </summary>
/// <param name="workbook">The workbook in which to optimise the fonts</param>
public static void OptimiseFonts(HSSFWorkbook workbook)
{
// Where each font has ended up, and if we need to
// delete the record for it. Start off with no change
short[] newPos =
new short[workbook.Workbook.NumberOfFontRecords + 1];
bool[] zapRecords = new bool[newPos.Length];
for (int i = 0; i < newPos.Length; i++)
{
newPos[i] = (short)i;
zapRecords[i] = false;
}
// Get each font record, so we can do deletes
// without Getting confused
FontRecord[] frecs = new FontRecord[newPos.Length];
for (int i = 0; i < newPos.Length; i++)
{
// There is no 4!
if (i == 4) continue;
frecs[i] = workbook.Workbook.GetFontRecordAt(i);
}
// Loop over each font, seeing if it is the same
// as an earlier one. If it is, point users of the
// later duplicate copy to the earlier one, and
// mark the later one as needing deleting
// Note - don't change built in fonts (those before 5)
for (int i = 5; i < newPos.Length; i++)
{
// Check this one for being a duplicate
// of an earlier one
int earlierDuplicate = -1;
for (int j = 0; j < i && earlierDuplicate == -1; j++)
{
if (j == 4) continue;
FontRecord frCheck = workbook.Workbook.GetFontRecordAt(j);
if (frCheck.SameProperties(frecs[i]))
{
earlierDuplicate = j;
}
}
// If we got a duplicate, mark it as such
if (earlierDuplicate != -1)
{
newPos[i] = (short)earlierDuplicate;
zapRecords[i] = true;
}
}
// Update the new positions based on
// deletes that have occurred between
// the start and them
// Only need to worry about user fonts
for (int i = 5; i < newPos.Length; i++)
{
// Find the number deleted to that
// point, and adjust
short preDeletePos = newPos[i];
short newPosition = preDeletePos;
for (int j = 0; j < preDeletePos; j++)
{
if (zapRecords[j]) newPosition--;
}
// Update the new position
newPos[i] = newPosition;
}
// Zap the un-needed user font records
for (int i = 5; i < newPos.Length; i++)
{
if (zapRecords[i])
{
workbook.Workbook.RemoveFontRecord(
frecs[i]
);
}
}
// Tell HSSFWorkbook that it needs to
// re-start its HSSFFontCache
workbook.ResetFontCache();
// Update the cell styles to point at the
// new locations of the fonts
for (int i = 0; i < workbook.Workbook.NumExFormats; i++)
{
ExtendedFormatRecord xfr = workbook.Workbook.GetExFormatAt(i);
xfr.FontIndex = (
newPos[xfr.FontIndex]
);
}
// Update the rich text strings to point at
// the new locations of the fonts
// Remember that one underlying unicode string
// may be shared by multiple RichTextStrings!
ArrayList doneUnicodeStrings = new ArrayList();
for (int sheetNum = 0; sheetNum < workbook.NumberOfSheets; sheetNum++)
{
NPOI.SS.UserModel.ISheet s = workbook.GetSheetAt(sheetNum);
//IEnumerator rIt = s.GetRowEnumerator();
//while (rIt.MoveNext())
foreach (IRow row in s)
{
//HSSFRow row = (HSSFRow)rIt.Current;
//IEnumerator cIt = row.GetEnumerator();
//while (cIt.MoveNext())
foreach (ICell cell in row)
{
//ICell cell = (HSSFCell)cIt.Current;
if (cell.CellType == NPOI.SS.UserModel.CellType.String)
{
HSSFRichTextString rtr = (HSSFRichTextString)cell.RichStringCellValue;
UnicodeString u = rtr.RawUnicodeString;
// Have we done this string already?
if (!doneUnicodeStrings.Contains(u))
{
// Update for each new position
for (short i = 5; i < newPos.Length; i++)
{
if (i != newPos[i])
{
u.SwapFontUse(i, newPos[i]);
}
}
// Mark as done
doneUnicodeStrings.Add(u);
}
}
}
}
}
}
/// <summary>
/// Goes through the Wokrbook, optimising the cell styles
/// by removing duplicate ones and ones that aren't used.
/// For best results, optimise the fonts via a call to
/// OptimiseFonts(HSSFWorkbook) first
/// </summary>
/// <param name="workbook">The workbook in which to optimise the cell styles</param>
public static void OptimiseCellStyles(HSSFWorkbook workbook)
{
// Where each style has ended up, and if we need to
// delete the record for it. Start off with no change
short[] newPos =
new short[workbook.Workbook.NumExFormats];
bool[] isUsed = new bool[newPos.Length];
bool[] zapRecords = new bool[newPos.Length];
for (int i = 0; i < newPos.Length; i++)
{
isUsed[i] = false;
newPos[i] = (short)i;
zapRecords[i] = false;
}
// Get each style record, so we can do deletes
// without Getting confused
ExtendedFormatRecord[] xfrs = new ExtendedFormatRecord[newPos.Length];
for (int i = 0; i < newPos.Length; i++)
{
xfrs[i] = workbook.Workbook.GetExFormatAt(i);
}
// Loop over each style, seeing if it is the same
// as an earlier one. If it is, point users of the
// later duplicate copy to the earlier one, and
// mark the later one as needing deleting
// Only work on user added ones, which come after 20
for (int i = 21; i < newPos.Length; i++)
{
// Check this one for being a duplicate
// of an earlier one
int earlierDuplicate = -1;
for (int j = 0; j < i && earlierDuplicate == -1; j++)
{
ExtendedFormatRecord xfCheck = workbook.Workbook.GetExFormatAt(j);
if (xfCheck.Equals(xfrs[i]))
{
earlierDuplicate = j;
}
}
// If we got a duplicate, mark it as such
if (earlierDuplicate != -1)
{
newPos[i] = (short)earlierDuplicate;
zapRecords[i] = true;
}
}
// Loop over all the cells in the file, and identify any user defined
// styles aren't actually being used (don't touch built-in ones)
for (int sheetNum = 0; sheetNum < workbook.NumberOfSheets; sheetNum++)
{
HSSFSheet s = (HSSFSheet)workbook.GetSheetAt(sheetNum);
foreach (IRow row in s)
{
foreach (ICell cellI in row)
{
HSSFCell cell = (HSSFCell)cellI;
short oldXf = cell.CellValueRecord.XFIndex;
isUsed[oldXf] = true;
}
}
}
// Mark any that aren't used as needing zapping
for (int i = 21; i < isUsed.Length; i++)
{
if (!isUsed[i])
{
// Un-used style, can be removed
zapRecords[i] = true;
newPos[i] = 0;
}
}
// Update the new positions based on
// deletes that have occurred between
// the start and them
// Only work on user added ones, which come after 20
for (int i = 21; i < newPos.Length; i++)
{
// Find the number deleted to that
// point, and adjust
short preDeletePos = newPos[i];
short newPosition = preDeletePos;
for (int j = 0; j < preDeletePos; j++)
{
if (zapRecords[j]) newPosition--;
}
// Update the new position
newPos[i] = newPosition;
}
// Zap the un-needed user style records
// removing by index, because removing by object may delete
// styles we did not intend to (the ones that _were_ duplicated and not the duplicates)
int max = newPos.Length;
int removed = 0; // to adjust index after deletion
for (int i = 21; i < max; i++)
{
if (zapRecords[i + removed])
{
workbook.Workbook.RemoveExFormatRecord(i);
i--;
max--;
removed++;
}
}
// Finally, update the cells to point at their new extended format records
for (int sheetNum = 0; sheetNum < workbook.NumberOfSheets; sheetNum++)
{
HSSFSheet s = (HSSFSheet)workbook.GetSheetAt(sheetNum);
//IEnumerator rIt = s.GetRowEnumerator();
//while (rIt.MoveNext())
foreach(IRow row in s)
{
//HSSFRow row = (HSSFRow)rIt.Current;
//IEnumerator cIt = row.GetEnumerator();
//while (cIt.MoveNext())
foreach (ICell cell in row)
{
//ICell cell = (HSSFCell)cIt.Current;
short oldXf = ((HSSFCell)cell).CellValueRecord.XFIndex;
NPOI.SS.UserModel.ICellStyle newStyle = workbook.GetCellStyleAt(
newPos[oldXf]
);
cell.CellStyle = (newStyle);
}
}
}
}
}
}
| |
// Copyright (c) 2015 Alachisoft
//
// 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.Data;
using System.Collections;
using System.Globalization;
using System.Net;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Http;
using System.Runtime.Remoting.Channels.Tcp;
using System.Xml.Schema;
using Alachisoft.NCache.Config;
using Alachisoft.NCache.Caching;
using Alachisoft.NCache.Management;
using Alachisoft.NCache.ServiceControl;
using Alachisoft.NCache.Common;
using Alachisoft.NCache.Runtime.Exceptions;
using Alachisoft.NCache.Management.ServiceControl;
using Alachisoft.NCache.Tools.Common;
using System.Configuration;
using Alachisoft.NCache.Config.Dom;
namespace Alachisoft.NCache.Tools.StartCache
{
/// <summary>
/// Main application class
/// </summary>
class Application
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
try
{
StartCacheTool.Run(args);
}
catch(Exception e)
{
Console.Error.WriteLine(e);
}
}
}
public class StartCacheToolParam:Alachisoft.NCache.Tools.Common.CommandLineParamsBase
{
private string _cacheId = "";
private ArrayList caches = new ArrayList();
private string _server = string.Empty;
private int port = -1;
public ArrayList CacheIdArray
{
get { return caches; }
set { caches = value; }
}
[ArgumentAttribute(@"", @"")]
public string CacheId
{
get { return _cacheId; }
set { caches.Add(value); }
}
[ArgumentAttribute(@"/s", @"/server")]
public string Server
{
get { return _server; }
set { _server = value; }
}
[ArgumentAttribute(@"/p", @"/port")]
public int Port
{
get { return port; }
set { port = value; }
}
}
/// <summary>
/// Summary description for StartCacheTool.
/// </summary>
sealed class StartCacheTool
{
/// <summary> NCache service controller. </summary>
static private NCacheRPCService NCache;
static private StartCacheToolParam cParam = new StartCacheToolParam();
/// <summary> Cache ids specified at the command line. </summary>
static private ArrayList s_cacheId = new ArrayList();
/// <summary>
/// Sets the application level parameters to those specified at the command line.
/// </summary>
/// <param name="args">array of command line parameters</param>
static private bool ApplyParameters(string[] args)
{
if (cParam.Server != null && cParam.Server != string.Empty)
NCache.ServerName = cParam.Server;
else
{
NCache.ServerName=System.Environment.MachineName;
}
NCache.Port = cParam.Port;
if(cParam.Port == -1) NCache.Port = NCache.UseTcp ? CacheConfigManager.NCacheTcpPort:CacheConfigManager.HttpPort;
s_cacheId = cParam.CacheIdArray;
if(s_cacheId.Count == 0)
{
Console.Error.WriteLine("Error: cache name not specified.");
return false;
}
AssemblyUsage.PrintLogo(cParam.IsLogo);
return true;
}
/// <summary>
/// The main entry point for the tool.
/// </summary>
static public void Run(string[] args)
{
NCache = new NCacheRPCService("");
string cacheIp = string.Empty;
try
{
object param = new StartCacheToolParam();
CommandLineArgumentParser.CommandLineParser(ref param, args);
cParam = (StartCacheToolParam)param;
if (cParam.IsUsage)
{
AssemblyUsage.PrintLogo(cParam.IsLogo);
AssemblyUsage.PrintUsage();
return;
}
if (!ApplyParameters(args)) return;
ICacheServer m = NCache.GetCacheServer(new TimeSpan(0, 0, 0, 30));
CacheServerConfig config = null;
cacheIp = m.GetClusterIP();
if (m != null)
{
foreach (string cache in s_cacheId)
{
try
{
config = m.GetCacheConfiguration((string)cache);
if (config != null && config.InProc)
{
throw new Exception("InProc caches cannot be started explicitly.");
}
Console.WriteLine("\nStarting cache '{0}' on server {1}:{2}.", cache, cacheIp, NCache.Port);
m.StartCache(cache, string.Empty);
Console.WriteLine("'{0}' successfully started on server {1}:{2}.\n", cache, cacheIp,
NCache.Port);
}
catch (Exception e)
{
Console.Error.WriteLine("Failed to start '{0}' on server {1}.", cache,
cacheIp);
Console.Error.WriteLine();
Console.Error.WriteLine(e.ToString() + "\n");
}
}
}
}
catch (ManagementException ex)
{
Console.Error.WriteLine("Error : {0}", "NCache service could not be contacted on server.");
Console.Error.WriteLine();
Console.Error.WriteLine(ex.ToString());
}
catch (Exception e)
{
Console.Error.WriteLine("Error : {0}", e.Message);
Console.Error.WriteLine();
Console.Error.WriteLine(e.ToString());
}
finally
{
NCache.Dispose();
}
}
}
}
| |
// 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.RegularExpressions;
using System.Threading;
using Microsoft.Build.Framework;
using Microsoft.Build.BackEnd;
using Microsoft.Build.Execution;
using Microsoft.Build.Internal;
using Microsoft.Build.Shared;
using Microsoft.Build.Unittest;
using Shouldly;
using Xunit;
namespace Microsoft.Build.UnitTests.BackEnd
{
public class ResultsCache_Tests
{
[Fact]
public void TestConstructor()
{
ResultsCache cache = new ResultsCache();
}
[Fact]
public void TestAddAndRetrieveResults()
{
ResultsCache cache = new ResultsCache();
BuildRequest request = new BuildRequest(1 /* submissionId */, 0, 1, new string[1] { "testTarget" }, null, BuildEventContext.Invalid, null); BuildResult result = new BuildResult(request);
result.AddResultsForTarget("testTarget", BuildResultUtilities.GetEmptyFailingTargetResult());
cache.AddResult(result);
BuildResult retrievedResult = cache.GetResultForRequest(request);
Assert.True(AreResultsIdentical(result, retrievedResult));
}
[Fact]
public void TestAddAndRetrieveResultsByConfiguration()
{
ResultsCache cache = new ResultsCache();
BuildRequest request = new BuildRequest(1 /* submissionId */, 0, 1, new string[1] { "testTarget" }, null, BuildEventContext.Invalid, null);
BuildResult result = new BuildResult(request);
result.AddResultsForTarget("testTarget", BuildResultUtilities.GetEmptyFailingTargetResult());
cache.AddResult(result);
request = new BuildRequest(1 /* submissionId */, 0, 1, new string[1] { "otherTarget" }, null, BuildEventContext.Invalid, null);
result = new BuildResult(request);
result.AddResultsForTarget("otherTarget", BuildResultUtilities.GetEmptySucceedingTargetResult());
cache.AddResult(result);
BuildResult retrievedResult = cache.GetResultsForConfiguration(1);
Assert.True(retrievedResult.HasResultsForTarget("testTarget"));
Assert.True(retrievedResult.HasResultsForTarget("otherTarget"));
}
[Fact]
public void CacheCanBeEnumerated()
{
ResultsCache cache = new ResultsCache();
BuildRequest request = new BuildRequest(submissionId: 1, nodeRequestId: 0, configurationId: 1, new string[1] { "testTarget" }, null, BuildEventContext.Invalid, null);
BuildResult result = new BuildResult(request);
result.AddResultsForTarget("result1target1", BuildResultUtilities.GetEmptyFailingTargetResult());
cache.AddResult(result);
request = new BuildRequest(1 /* submissionId */, 0, 1, new string[1] { "otherTarget" }, null, BuildEventContext.Invalid, null);
result = new BuildResult(request);
result.AddResultsForTarget("result1target2", BuildResultUtilities.GetEmptySucceedingTargetResult());
cache.AddResult(result);
BuildResult result2 = new BuildResult(new BuildRequest(submissionId: 1, nodeRequestId: 0, configurationId: 2, new string[1] { "testTarget" }, null, BuildEventContext.Invalid, null));
result2.AddResultsForTarget("result2target1", BuildResultUtilities.GetEmptyFailingTargetResult());
cache.AddResult(result2);
var results = cache.GetEnumerator().ToArray();
results.Length.ShouldBe(2);
Assert.True(results[0].HasResultsForTarget("result1target1"));
Assert.True(results[0].HasResultsForTarget("result1target2"));
Assert.True(results[1].HasResultsForTarget("result2target1"));
}
[Fact]
public void TestMissingResults()
{
ResultsCache cache = new ResultsCache();
BuildRequest request = new BuildRequest(1 /* submissionId */, 0, 1, new string[1] { "testTarget" }, null, BuildEventContext.Invalid, null);
BuildResult retrievedResult = cache.GetResultForRequest(request);
Assert.Null(retrievedResult);
}
[Fact]
public void TestRetrieveMergedResults()
{
ResultsCache cache = new ResultsCache();
BuildRequest request = new BuildRequest(1 /* submissionId */, 0, 1, new string[2] { "testTarget", "testTarget2" }, null, BuildEventContext.Invalid, null);
BuildResult result = new BuildResult(request);
result.AddResultsForTarget("testTarget", BuildResultUtilities.GetEmptyFailingTargetResult());
cache.AddResult(result);
BuildResult result2 = new BuildResult(request);
result2.AddResultsForTarget("testTarget2", BuildResultUtilities.GetEmptySucceedingTargetResult());
cache.AddResult(result2);
BuildResult retrievedResult = cache.GetResultForRequest(request);
Assert.True(AreResultsIdenticalForTarget(result, retrievedResult, "testTarget"));
Assert.True(AreResultsIdenticalForTarget(result2, retrievedResult, "testTarget2"));
}
[Fact]
public void TestMergeResultsWithException()
{
ResultsCache cache = new ResultsCache();
BuildRequest request = new BuildRequest(1 /* submissionId */, 0, 1, new string[] { "testTarget" }, null, BuildEventContext.Invalid, null);
BuildResult result = new BuildResult(request);
result.AddResultsForTarget("testTarget", BuildResultUtilities.GetEmptyFailingTargetResult());
cache.AddResult(result);
BuildResult result2 = new BuildResult(request, new Exception("Test exception"));
cache.AddResult(result2);
BuildResult retrievedResult = cache.GetResultForRequest(request);
Assert.NotNull(retrievedResult.Exception);
}
[Fact]
public void TestRetrieveIncompleteResults()
{
Assert.Throws<InternalErrorException>(() =>
{
ResultsCache cache = new ResultsCache();
BuildRequest request = new BuildRequest(1 /* submissionId */, 0, 1, new string[2] { "testTarget", "testTarget2" }, null, BuildEventContext.Invalid, null);
BuildResult result = new BuildResult(request);
result.AddResultsForTarget("testTarget", BuildResultUtilities.GetEmptyFailingTargetResult());
cache.AddResult(result);
cache.GetResultForRequest(request);
}
);
}
[Fact]
public void TestRetrieveSubsetResults()
{
ResultsCache cache = new ResultsCache();
BuildRequest request = new BuildRequest(1 /* submissionId */, 0, 1, new string[1] { "testTarget2" }, null, BuildEventContext.Invalid, null);
BuildResult result = new BuildResult(request);
result.AddResultsForTarget("testTarget", BuildResultUtilities.GetEmptyFailingTargetResult());
cache.AddResult(result);
BuildResult result2 = new BuildResult(request);
result2.AddResultsForTarget("testTarget2", BuildResultUtilities.GetEmptySucceedingTargetResult());
cache.AddResult(result2);
BuildResult retrievedResult = cache.GetResultForRequest(request);
Assert.True(AreResultsIdenticalForTarget(result2, retrievedResult, "testTarget2"));
}
/// <summary>
/// If a result had multiple targets associated with it and we only requested some of their
/// results, the returned result should only contain the targets we asked for, BUT the overall
/// status of the result should remain the same.
/// </summary>
[Fact]
public void TestRetrieveSubsetTargetsFromResult()
{
ResultsCache cache = new ResultsCache();
BuildRequest request = new BuildRequest(1 /* submissionId */, 0, 1, new string[1] { "testTarget2" }, null, BuildEventContext.Invalid, null);
BuildResult result = new BuildResult(request);
result.AddResultsForTarget("testTarget", BuildResultUtilities.GetEmptyFailingTargetResult());
result.AddResultsForTarget("testTarget2", BuildResultUtilities.GetEmptySucceedingTargetResult());
cache.AddResult(result);
ResultsCacheResponse response = cache.SatisfyRequest(request, new List<string>(), new List<string>(new string[] { "testTarget2" }), new List<string>(new string[] { "testTarget" }), skippedResultsDoNotCauseCacheMiss: false);
Assert.Equal(ResultsCacheResponseType.Satisfied, response.Type);
Assert.True(AreResultsIdenticalForTarget(result, response.Results, "testTarget2"));
Assert.False(response.Results.HasResultsForTarget("testTarget"));
Assert.Equal(BuildResultCode.Failure, response.Results.OverallResult);
}
[Fact]
public void TestClearResultsCache()
{
ResultsCache cache = new ResultsCache();
cache.ClearResults();
BuildRequest request = new BuildRequest(1 /* submissionId */, 0, 1, new string[1] { "testTarget2" }, null, BuildEventContext.Invalid, null);
BuildResult result = new BuildResult(request);
result.AddResultsForTarget("testTarget", BuildResultUtilities.GetEmptyFailingTargetResult());
cache.AddResult(result);
cache.ClearResults();
Assert.Null(cache.GetResultForRequest(request));
}
public static IEnumerable<object[]> CacheSerializationTestData
{
get
{
yield return new[] {new ResultsCache()};
var request1 = new BuildRequest(1, 2, 3, new[] {"target1"}, null, BuildEventContext.Invalid, null);
var request2 = new BuildRequest(4, 5, 6, new[] {"target2"}, null, BuildEventContext.Invalid, null);
var br1 = new BuildResult(request1);
br1.AddResultsForTarget("target1", BuildResultUtilities.GetEmptySucceedingTargetResult());
var resultsCache = new ResultsCache();
resultsCache.AddResult(br1.Clone());
yield return new[] {resultsCache};
var br2 = new BuildResult(request2);
br2.AddResultsForTarget("target2", BuildResultUtilities.GetEmptyFailingTargetResult());
var resultsCache2 = new ResultsCache();
resultsCache2.AddResult(br1.Clone());
resultsCache2.AddResult(br2.Clone());
yield return new[] {resultsCache2};
}
}
[Theory]
[MemberData(nameof(CacheSerializationTestData))]
public void TestResultsCacheTranslation(object obj)
{
var resultsCache = (ResultsCache)obj;
resultsCache.Translate(TranslationHelpers.GetWriteTranslator());
var copy = new ResultsCache(TranslationHelpers.GetReadTranslator());
copy.ResultsDictionary.Keys.ToHashSet().SetEquals(resultsCache.ResultsDictionary.Keys.ToHashSet()).ShouldBeTrue();
foreach (var configId in copy.ResultsDictionary.Keys)
{
var copiedBuildResult = copy.ResultsDictionary[configId];
var initialBuildResult = resultsCache.ResultsDictionary[configId];
copiedBuildResult.SubmissionId.ShouldBe(initialBuildResult.SubmissionId);
copiedBuildResult.ConfigurationId.ShouldBe(initialBuildResult.ConfigurationId);
copiedBuildResult.ResultsByTarget.Keys.ToHashSet().SetEquals(initialBuildResult.ResultsByTarget.Keys.ToHashSet()).ShouldBeTrue();
foreach (var targetKey in copiedBuildResult.ResultsByTarget.Keys)
{
var copiedTargetResult = copiedBuildResult.ResultsByTarget[targetKey];
var initialTargetResult = initialBuildResult.ResultsByTarget[targetKey];
copiedTargetResult.WorkUnitResult.ResultCode.ShouldBe(initialTargetResult.WorkUnitResult.ResultCode);
copiedTargetResult.WorkUnitResult.ActionCode.ShouldBe(initialTargetResult.WorkUnitResult.ActionCode);
}
}
}
#region Helper Methods
static internal bool AreResultsIdentical(BuildResult a, BuildResult b)
{
if (a.ConfigurationId != b.ConfigurationId)
{
return false;
}
if ((a.Exception == null) ^ (b.Exception == null))
{
return false;
}
if (a.Exception != null)
{
if (a.Exception.GetType() != b.Exception.GetType())
{
return false;
}
}
if (a.OverallResult != b.OverallResult)
{
return false;
}
foreach (KeyValuePair<string, TargetResult> targetResult in a.ResultsByTarget)
{
if (!AreResultsIdenticalForTarget(a, b, targetResult.Key))
{
return false;
}
}
foreach (KeyValuePair<string, TargetResult> targetResult in b.ResultsByTarget)
{
if (!AreResultsIdenticalForTarget(a, b, targetResult.Key))
{
return false;
}
}
return true;
}
static internal bool AreResultsIdenticalForTargets(BuildResult a, BuildResult b, string[] targets)
{
foreach (string target in targets)
{
if (!AreResultsIdenticalForTarget(a, b, target))
{
return false;
}
}
return true;
}
static private bool AreResultsIdenticalForTarget(BuildResult a, BuildResult b, string target)
{
if (!a.HasResultsForTarget(target) || !b.HasResultsForTarget(target))
{
return false;
}
if (a[target].ResultCode != b[target].ResultCode)
{
return false;
}
if (!AreItemsIdentical(a[target].Items, b[target].Items))
{
return false;
}
return true;
}
static private bool AreItemsIdentical(IList<ITaskItem> a, IList<ITaskItem> b)
{
// Exhaustive comparison of items should not be necessary since we don't merge on the item level.
return a.Count == b.Count;
}
#endregion
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
namespace DalSic
{
/// <summary>
/// Strongly-typed collection for the PnCredito class.
/// </summary>
[Serializable]
public partial class PnCreditoCollection : ActiveList<PnCredito, PnCreditoCollection>
{
public PnCreditoCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>PnCreditoCollection</returns>
public PnCreditoCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
PnCredito o = this[i];
foreach (SubSonic.Where w in this.wheres)
{
bool remove = false;
System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName);
if (pi.CanRead)
{
object val = pi.GetValue(o, null);
switch (w.Comparison)
{
case SubSonic.Comparison.Equals:
if (!val.Equals(w.ParameterValue))
{
remove = true;
}
break;
}
}
if (remove)
{
this.Remove(o);
break;
}
}
}
return this;
}
}
/// <summary>
/// This is an ActiveRecord class which wraps the PN_credito table.
/// </summary>
[Serializable]
public partial class PnCredito : ActiveRecord<PnCredito>, IActiveRecord
{
#region .ctors and Default Settings
public PnCredito()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public PnCredito(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public PnCredito(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public PnCredito(string columnName, object columnValue)
{
SetSQLProps();
InitSetDefaults();
LoadByParam(columnName,columnValue);
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
SetSQLProps();
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("PN_credito", TableType.Table, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarIdCredito = new TableSchema.TableColumn(schema);
colvarIdCredito.ColumnName = "id_credito";
colvarIdCredito.DataType = DbType.Int32;
colvarIdCredito.MaxLength = 0;
colvarIdCredito.AutoIncrement = true;
colvarIdCredito.IsNullable = false;
colvarIdCredito.IsPrimaryKey = true;
colvarIdCredito.IsForeignKey = false;
colvarIdCredito.IsReadOnly = false;
colvarIdCredito.DefaultSetting = @"";
colvarIdCredito.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdCredito);
TableSchema.TableColumn colvarCantidad = new TableSchema.TableColumn(schema);
colvarCantidad.ColumnName = "cantidad";
colvarCantidad.DataType = DbType.Decimal;
colvarCantidad.MaxLength = 0;
colvarCantidad.AutoIncrement = false;
colvarCantidad.IsNullable = true;
colvarCantidad.IsPrimaryKey = false;
colvarCantidad.IsForeignKey = false;
colvarCantidad.IsReadOnly = false;
colvarCantidad.DefaultSetting = @"";
colvarCantidad.ForeignKeyTableName = "";
schema.Columns.Add(colvarCantidad);
TableSchema.TableColumn colvarIdFactura = new TableSchema.TableColumn(schema);
colvarIdFactura.ColumnName = "id_factura";
colvarIdFactura.DataType = DbType.Int32;
colvarIdFactura.MaxLength = 0;
colvarIdFactura.AutoIncrement = false;
colvarIdFactura.IsNullable = false;
colvarIdFactura.IsPrimaryKey = false;
colvarIdFactura.IsForeignKey = false;
colvarIdFactura.IsReadOnly = false;
colvarIdFactura.DefaultSetting = @"";
colvarIdFactura.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdFactura);
TableSchema.TableColumn colvarIdNomenclador = new TableSchema.TableColumn(schema);
colvarIdNomenclador.ColumnName = "id_nomenclador";
colvarIdNomenclador.DataType = DbType.Int32;
colvarIdNomenclador.MaxLength = 0;
colvarIdNomenclador.AutoIncrement = false;
colvarIdNomenclador.IsNullable = false;
colvarIdNomenclador.IsPrimaryKey = false;
colvarIdNomenclador.IsForeignKey = false;
colvarIdNomenclador.IsReadOnly = false;
colvarIdNomenclador.DefaultSetting = @"";
colvarIdNomenclador.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdNomenclador);
TableSchema.TableColumn colvarIdMotivoD = new TableSchema.TableColumn(schema);
colvarIdMotivoD.ColumnName = "id_motivo_d";
colvarIdMotivoD.DataType = DbType.Int32;
colvarIdMotivoD.MaxLength = 0;
colvarIdMotivoD.AutoIncrement = false;
colvarIdMotivoD.IsNullable = false;
colvarIdMotivoD.IsPrimaryKey = false;
colvarIdMotivoD.IsForeignKey = false;
colvarIdMotivoD.IsReadOnly = false;
colvarIdMotivoD.DefaultSetting = @"";
colvarIdMotivoD.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdMotivoD);
TableSchema.TableColumn colvarMonto = new TableSchema.TableColumn(schema);
colvarMonto.ColumnName = "monto";
colvarMonto.DataType = DbType.Decimal;
colvarMonto.MaxLength = 0;
colvarMonto.AutoIncrement = false;
colvarMonto.IsNullable = true;
colvarMonto.IsPrimaryKey = false;
colvarMonto.IsForeignKey = false;
colvarMonto.IsReadOnly = false;
colvarMonto.DefaultSetting = @"";
colvarMonto.ForeignKeyTableName = "";
schema.Columns.Add(colvarMonto);
TableSchema.TableColumn colvarCodigoCred = new TableSchema.TableColumn(schema);
colvarCodigoCred.ColumnName = "codigo_cred";
colvarCodigoCred.DataType = DbType.AnsiString;
colvarCodigoCred.MaxLength = -1;
colvarCodigoCred.AutoIncrement = false;
colvarCodigoCred.IsNullable = true;
colvarCodigoCred.IsPrimaryKey = false;
colvarCodigoCred.IsForeignKey = false;
colvarCodigoCred.IsReadOnly = false;
colvarCodigoCred.DefaultSetting = @"";
colvarCodigoCred.ForeignKeyTableName = "";
schema.Columns.Add(colvarCodigoCred);
TableSchema.TableColumn colvarObservacionesCred = new TableSchema.TableColumn(schema);
colvarObservacionesCred.ColumnName = "observaciones_cred";
colvarObservacionesCred.DataType = DbType.AnsiString;
colvarObservacionesCred.MaxLength = -1;
colvarObservacionesCred.AutoIncrement = false;
colvarObservacionesCred.IsNullable = true;
colvarObservacionesCred.IsPrimaryKey = false;
colvarObservacionesCred.IsForeignKey = false;
colvarObservacionesCred.IsReadOnly = false;
colvarObservacionesCred.DefaultSetting = @"";
colvarObservacionesCred.ForeignKeyTableName = "";
schema.Columns.Add(colvarObservacionesCred);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("PN_credito",schema);
}
}
#endregion
#region Props
[XmlAttribute("IdCredito")]
[Bindable(true)]
public int IdCredito
{
get { return GetColumnValue<int>(Columns.IdCredito); }
set { SetColumnValue(Columns.IdCredito, value); }
}
[XmlAttribute("Cantidad")]
[Bindable(true)]
public decimal? Cantidad
{
get { return GetColumnValue<decimal?>(Columns.Cantidad); }
set { SetColumnValue(Columns.Cantidad, value); }
}
[XmlAttribute("IdFactura")]
[Bindable(true)]
public int IdFactura
{
get { return GetColumnValue<int>(Columns.IdFactura); }
set { SetColumnValue(Columns.IdFactura, value); }
}
[XmlAttribute("IdNomenclador")]
[Bindable(true)]
public int IdNomenclador
{
get { return GetColumnValue<int>(Columns.IdNomenclador); }
set { SetColumnValue(Columns.IdNomenclador, value); }
}
[XmlAttribute("IdMotivoD")]
[Bindable(true)]
public int IdMotivoD
{
get { return GetColumnValue<int>(Columns.IdMotivoD); }
set { SetColumnValue(Columns.IdMotivoD, value); }
}
[XmlAttribute("Monto")]
[Bindable(true)]
public decimal? Monto
{
get { return GetColumnValue<decimal?>(Columns.Monto); }
set { SetColumnValue(Columns.Monto, value); }
}
[XmlAttribute("CodigoCred")]
[Bindable(true)]
public string CodigoCred
{
get { return GetColumnValue<string>(Columns.CodigoCred); }
set { SetColumnValue(Columns.CodigoCred, value); }
}
[XmlAttribute("ObservacionesCred")]
[Bindable(true)]
public string ObservacionesCred
{
get { return GetColumnValue<string>(Columns.ObservacionesCred); }
set { SetColumnValue(Columns.ObservacionesCred, value); }
}
#endregion
//no foreign key tables defined (0)
//no ManyToMany tables defined (0)
#region ObjectDataSource support
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
public static void Insert(decimal? varCantidad,int varIdFactura,int varIdNomenclador,int varIdMotivoD,decimal? varMonto,string varCodigoCred,string varObservacionesCred)
{
PnCredito item = new PnCredito();
item.Cantidad = varCantidad;
item.IdFactura = varIdFactura;
item.IdNomenclador = varIdNomenclador;
item.IdMotivoD = varIdMotivoD;
item.Monto = varMonto;
item.CodigoCred = varCodigoCred;
item.ObservacionesCred = varObservacionesCred;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
public static void Update(int varIdCredito,decimal? varCantidad,int varIdFactura,int varIdNomenclador,int varIdMotivoD,decimal? varMonto,string varCodigoCred,string varObservacionesCred)
{
PnCredito item = new PnCredito();
item.IdCredito = varIdCredito;
item.Cantidad = varCantidad;
item.IdFactura = varIdFactura;
item.IdNomenclador = varIdNomenclador;
item.IdMotivoD = varIdMotivoD;
item.Monto = varMonto;
item.CodigoCred = varCodigoCred;
item.ObservacionesCred = varObservacionesCred;
item.IsNew = false;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
#endregion
#region Typed Columns
public static TableSchema.TableColumn IdCreditoColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn CantidadColumn
{
get { return Schema.Columns[1]; }
}
public static TableSchema.TableColumn IdFacturaColumn
{
get { return Schema.Columns[2]; }
}
public static TableSchema.TableColumn IdNomencladorColumn
{
get { return Schema.Columns[3]; }
}
public static TableSchema.TableColumn IdMotivoDColumn
{
get { return Schema.Columns[4]; }
}
public static TableSchema.TableColumn MontoColumn
{
get { return Schema.Columns[5]; }
}
public static TableSchema.TableColumn CodigoCredColumn
{
get { return Schema.Columns[6]; }
}
public static TableSchema.TableColumn ObservacionesCredColumn
{
get { return Schema.Columns[7]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string IdCredito = @"id_credito";
public static string Cantidad = @"cantidad";
public static string IdFactura = @"id_factura";
public static string IdNomenclador = @"id_nomenclador";
public static string IdMotivoD = @"id_motivo_d";
public static string Monto = @"monto";
public static string CodigoCred = @"codigo_cred";
public static string ObservacionesCred = @"observaciones_cred";
}
#endregion
#region Update PK Collections
#endregion
#region Deep Save
#endregion
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="LocalDB.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">antonam</owner>
//------------------------------------------------------------------------------
namespace System.Data
{
using System.Configuration;
using System.Threading;
using System.Runtime.InteropServices;
using System.Data.Common;
using System.Globalization;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Text;
using System.Diagnostics;
using System.Security;
using System.Security.Permissions;
internal static class LocalDBAPI
{
const string const_localDbPrefix = @"(localdb)\";
const string const_partialTrustFlagKey = "ALLOW_LOCALDB_IN_PARTIAL_TRUST";
static PermissionSet _fullTrust = null;
static bool _partialTrustFlagChecked = false;
static bool _partialTrustAllowed = false;
// check if name is in format (localdb)\<InstanceName - not empty> and return instance name if it is
internal static string GetLocalDbInstanceNameFromServerName(string serverName)
{
if (serverName == null)
return null;
serverName = serverName.TrimStart(); // it can start with spaces if specified in quotes
if (!serverName.StartsWith(const_localDbPrefix, StringComparison.OrdinalIgnoreCase))
return null;
string instanceName = serverName.Substring(const_localDbPrefix.Length).Trim();
if (instanceName.Length == 0)
return null;
else
return instanceName;
}
#if !MONO
internal static void ReleaseDLLHandles()
{
s_userInstanceDLLHandle = IntPtr.Zero;
s_localDBFormatMessage = null;
s_localDBCreateInstance = null;
}
//This is copy of handle that SNI maintains, so we are responsible for freeing it - therefore there we are not using SafeHandle
static IntPtr s_userInstanceDLLHandle = IntPtr.Zero;
static object s_dllLock = new object();
static IntPtr UserInstanceDLLHandle
{
get
{
if (s_userInstanceDLLHandle==IntPtr.Zero)
{
bool lockTaken = false;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
Monitor.Enter(s_dllLock, ref lockTaken);
if (s_userInstanceDLLHandle == IntPtr.Zero)
{
SNINativeMethodWrapper.SNIQueryInfo(SNINativeMethodWrapper.QTypes.SNI_QUERY_LOCALDB_HMODULE, ref s_userInstanceDLLHandle);
if (s_userInstanceDLLHandle != IntPtr.Zero)
{
Bid.Trace("<sc.LocalDBAPI.UserInstanceDLLHandle> LocalDB - handle obtained");
}
else
{
SNINativeMethodWrapper.SNI_Error sniError = new SNINativeMethodWrapper.SNI_Error();
SNINativeMethodWrapper.SNIGetLastError(sniError);
throw CreateLocalDBException(errorMessage: Res.GetString("LocalDB_FailedGetDLLHandle"), sniError: (int)sniError.sniError);
}
}
}
finally
{
if (lockTaken)
Monitor.Exit(s_dllLock);
}
}
return s_userInstanceDLLHandle;
}
}
[SuppressUnmanagedCodeSecurity]
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate int LocalDBCreateInstanceDelegate([MarshalAs(UnmanagedType.LPWStr)] string version, [MarshalAs(UnmanagedType.LPWStr)] string instance, UInt32 flags);
static LocalDBCreateInstanceDelegate s_localDBCreateInstance = null;
static LocalDBCreateInstanceDelegate LocalDBCreateInstance
{
get
{
if (s_localDBCreateInstance==null)
{
bool lockTaken = false;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
Monitor.Enter(s_dllLock, ref lockTaken);
if (s_localDBCreateInstance == null)
{
IntPtr functionAddr = SafeNativeMethods.GetProcAddress(UserInstanceDLLHandle, "LocalDBCreateInstance");
if (functionAddr == IntPtr.Zero)
{
int hResult=Marshal.GetLastWin32Error();
Bid.Trace("<sc.LocalDBAPI.LocalDBCreateInstance> GetProcAddress for LocalDBCreateInstance error 0x{%X}",hResult);
throw CreateLocalDBException(errorMessage: Res.GetString("LocalDB_MethodNotFound"));
}
s_localDBCreateInstance = (LocalDBCreateInstanceDelegate)Marshal.GetDelegateForFunctionPointer(functionAddr, typeof(LocalDBCreateInstanceDelegate));
}
}
finally
{
if (lockTaken)
Monitor.Exit(s_dllLock);
}
}
return s_localDBCreateInstance;
}
}
[SuppressUnmanagedCodeSecurity]
[UnmanagedFunctionPointer(CallingConvention.Cdecl,CharSet=CharSet.Unicode)]
private delegate int LocalDBFormatMessageDelegate(int hrLocalDB, UInt32 dwFlags, UInt32 dwLanguageId, StringBuilder buffer, ref UInt32 buflen);
static LocalDBFormatMessageDelegate s_localDBFormatMessage = null;
static LocalDBFormatMessageDelegate LocalDBFormatMessage
{
get
{
if (s_localDBFormatMessage==null)
{
bool lockTaken = false;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
Monitor.Enter(s_dllLock, ref lockTaken);
if (s_localDBFormatMessage == null)
{
IntPtr functionAddr = SafeNativeMethods.GetProcAddress(UserInstanceDLLHandle, "LocalDBFormatMessage");
if (functionAddr == IntPtr.Zero)
{
// SNI checks for LocalDBFormatMessage during DLL loading, so it is practically impossibe to get this error.
int hResult=Marshal.GetLastWin32Error();
Bid.Trace("<sc.LocalDBAPI.LocalDBFormatMessage> GetProcAddress for LocalDBFormatMessage error 0x{%X}", hResult);
throw CreateLocalDBException(errorMessage: Res.GetString("LocalDB_MethodNotFound"));
}
s_localDBFormatMessage = (LocalDBFormatMessageDelegate)Marshal.GetDelegateForFunctionPointer(functionAddr, typeof(LocalDBFormatMessageDelegate));
}
}
finally
{
if (lockTaken)
Monitor.Exit(s_dllLock);
}
}
return s_localDBFormatMessage;
}
}
const UInt32 const_LOCALDB_TRUNCATE_ERR_MESSAGE = 1;// flag for LocalDBFormatMessage that indicates that message can be truncated if it does not fit in the buffer
const int const_ErrorMessageBufferSize = 1024; // Buffer size for Local DB error message, according to Serverless team, 1K will be enough for all messages
internal static string GetLocalDBMessage(int hrCode)
{
Debug.Assert(hrCode < 0, "HRCode does not indicate error");
try
{
StringBuilder buffer = new StringBuilder((int)const_ErrorMessageBufferSize);
UInt32 len = (UInt32)buffer.Capacity;
// First try for current culture
int hResult=LocalDBFormatMessage(hrLocalDB: hrCode, dwFlags: const_LOCALDB_TRUNCATE_ERR_MESSAGE, dwLanguageId: (UInt32)CultureInfo.CurrentCulture.LCID,
buffer: buffer, buflen: ref len);
if (hResult>=0)
return buffer.ToString();
else
{
// Message is not available for current culture, try default
buffer = new StringBuilder((int)const_ErrorMessageBufferSize);
len = (UInt32) buffer.Capacity;
hResult=LocalDBFormatMessage(hrLocalDB: hrCode, dwFlags: const_LOCALDB_TRUNCATE_ERR_MESSAGE, dwLanguageId: 0 /* thread locale with fallback to English */,
buffer: buffer, buflen: ref len);
if (hResult >= 0)
return buffer.ToString();
else
return string.Format(CultureInfo.CurrentCulture, "{0} (0x{1:X}).", Res.GetString("LocalDB_UnobtainableMessage"), hResult);
}
}
catch (SqlException exc)
{
return string.Format(CultureInfo.CurrentCulture, "{0} ({1}).", Res.GetString("LocalDB_UnobtainableMessage"), exc.Message);
}
}
static SqlException CreateLocalDBException(string errorMessage, string instance = null, int localDbError = 0, int sniError = 0)
{
Debug.Assert((localDbError == 0) || (sniError == 0), "LocalDB error and SNI error cannot be specified simultaneously");
Debug.Assert(!string.IsNullOrEmpty(errorMessage), "Error message should not be null or empty");
SqlErrorCollection collection = new SqlErrorCollection();
int errorCode = (localDbError == 0) ? sniError : localDbError;
if (sniError!=0)
{
string sniErrorMessage = SQL.GetSNIErrorMessage(sniError);
errorMessage = String.Format((IFormatProvider)null, "{0} (error: {1} - {2})",
errorMessage, sniError, sniErrorMessage);
}
collection.Add(new SqlError(errorCode, 0, TdsEnums.FATAL_ERROR_CLASS, instance, errorMessage, null, 0));
if (localDbError != 0)
collection.Add(new SqlError(errorCode, 0, TdsEnums.FATAL_ERROR_CLASS, instance, GetLocalDBMessage(localDbError), null, 0));
SqlException exc = SqlException.CreateException(collection, null);
exc._doNotReconnect = true;
return exc;
}
private class InstanceInfo
{
internal InstanceInfo(string version)
{
this.version = version;
this.created = false;
}
internal readonly string version;
internal bool created;
}
static object s_configLock=new object();
static Dictionary<string, InstanceInfo> s_configurableInstances = null;
internal static void DemandLocalDBPermissions()
{
if (!_partialTrustAllowed)
{
if (!_partialTrustFlagChecked)
{
object partialTrustFlagValue = AppDomain.CurrentDomain.GetData(const_partialTrustFlagKey);
if (partialTrustFlagValue != null && partialTrustFlagValue is bool)
{
_partialTrustAllowed = (bool)partialTrustFlagValue;
}
_partialTrustFlagChecked = true;
if (_partialTrustAllowed)
{
return;
}
}
if (_fullTrust == null)
{
_fullTrust = new NamedPermissionSet("FullTrust");
}
_fullTrust.Demand();
}
}
internal static void AssertLocalDBPermissions()
{
_partialTrustAllowed = true;
}
internal static void CreateLocalDBInstance(string instance)
{
DemandLocalDBPermissions();
if (s_configurableInstances == null)
{
// load list of instances from configuration, mark them as not created
bool lockTaken = false;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
Monitor.Enter(s_configLock, ref lockTaken);
if (s_configurableInstances == null)
{
Dictionary<string, InstanceInfo> tempConfigurableInstances = new Dictionary<string, InstanceInfo>(StringComparer.OrdinalIgnoreCase);
#if !NO_CONFIGURATION
object section = PrivilegedConfigurationManager.GetSection("system.data.localdb");
if (section != null) // if no section just skip creation
{
// validate section type
LocalDBConfigurationSection configSection = section as LocalDBConfigurationSection;
if (configSection == null)
throw CreateLocalDBException(errorMessage: Res.GetString("LocalDB_BadConfigSectionType"));
foreach (LocalDBInstanceElement confElement in configSection.LocalDbInstances)
{
Debug.Assert(confElement.Name != null && confElement.Version != null, "Both name and version should not be null");
tempConfigurableInstances.Add(confElement.Name.Trim(), new InstanceInfo(confElement.Version.Trim()));
}
}
else
#endif
Bid.Trace( "<sc.LocalDBAPI.CreateLocalDBInstance> No system.data.localdb section found in configuration");
s_configurableInstances = tempConfigurableInstances;
}
}
finally
{
if (lockTaken)
Monitor.Exit(s_configLock);
}
}
InstanceInfo instanceInfo = null;
if (!s_configurableInstances.TryGetValue(instance,out instanceInfo))
return; // instance name was not in the config
if (instanceInfo.created)
return; // instance has already been created
Debug.Assert(!instance.Contains("\0"), "Instance name should contain embedded nulls");
if (instanceInfo.version.Contains("\0"))
throw CreateLocalDBException(errorMessage: Res.GetString("LocalDB_InvalidVersion"), instance: instance);
// LocalDBCreateInstance is thread- and cross-process safe method, it is OK to call from two threads simultaneously
int hr = LocalDBCreateInstance(instanceInfo.version, instance, flags: 0);
Bid.Trace("<sc.LocalDBAPI.CreateLocalDBInstance> Starting creation of instance %ls version %ls", instance, instanceInfo.version);
if (hr < 0)
throw CreateLocalDBException(errorMessage: Res.GetString("LocalDB_CreateFailed"), instance: instance, localDbError: hr);
Bid.Trace("<sc.LocalDBAPI.CreateLocalDBInstance> Finished creation of instance %ls", instance);
instanceInfo.created=true; // mark instance as created
} // CreateLocalDbInstance
#endif
}
}
| |
using System;
using UnityEngine;
using System.Collections.Generic;
namespace Pathfinding {
/** Floods the area completely for easy computation of any path to a single point.
* This path is a bit special, because it does not do anything useful by itself. What it does is that it calculates paths to all nodes it can reach, it floods the graph.
* This data will remain stored in the path. Then you can call a FloodPathTracer path, that path will trace the path from it's starting point all the way to where this path started flooding and thus generating a path extremely quickly.\n
* It is very useful in for example TD (Tower Defence) games where all your AIs will walk to the same point, but from different places, and you do not update the graph or change the target point very often,
* what changes is their positions and new AIs spawn all the time (which makes it hard to use the MultiTargetPath).\n
*
* With this path type, it can all be handled easily.
* - At start, you simply start ONE FloodPath and save the reference (it will be needed later).
* - Then when a unit is spawned or needs its path recalculated, start a FloodPathTracer path from it's position.
* It will then find the shortest path to the point specified when you called the FloodPath extremely quickly.
* - If you update the graph (for example place a tower in a TD game) or need to change the target point, you simply call a new FloodPath (and store it's reference).
*
* \version From 3.2 and up, path traversal data is now stored in the path class.
* So you can now use other path types in parallel with this one.
*
* Here follows some example code of the above list of steps:
* \code
* public static FloodPath fpath;
*
* public void Start () {
* fpath = FloodPath.Construct (someTargetPosition, null);
* AstarPath.StartPath (fpath);
* }
* \endcode
*
* When searching for a new path to \a someTargetPosition from let's say \a transform.position, you do
* \code
* FloodPathTracer fpathTrace = FloodPathTracer.Construct (transform.position,fpath,null);
* seeker.StartPath (fpathTrace,OnPathComplete);
* \endcode
* Where OnPathComplete is your callback function.
* \n
* Another thing to note is that if you are using NNConstraints on the FloodPathTracer, they must always inherit from Pathfinding.PathIDConstraint.\n
* The easiest is to just modify the instance of PathIDConstraint which is created as the default one.
*
* \astarpro
*
* \shadowimage{floodPathExample.png}
*
* \ingroup paths
*
*/
public class FloodPath : Path {
public Vector3 originalStartPoint;
public Vector3 startPoint;
public GraphNode startNode;
/** If false, will not save any information.
* Used by some internal parts of the system which doesn't need it.
*/
public bool saveParents = true;
protected Dictionary<GraphNode, GraphNode> parents;
internal override bool FloodingPath {
get {
return true;
}
}
public bool HasPathTo (GraphNode node) {
return parents != null && parents.ContainsKey (node);
}
public GraphNode GetParent (GraphNode node) {
return parents[node];
}
/** Default constructor.
* Do not use this. Instead use the static Construct method which can handle path pooling.
*/
public FloodPath () {}
public static FloodPath Construct (Vector3 start, OnPathDelegate callback = null) {
var p = PathPool.GetPath<FloodPath>();
p.Setup(start, callback);
return p;
}
public static FloodPath Construct (GraphNode start, OnPathDelegate callback = null) {
if (start == null) throw new ArgumentNullException("start");
var p = PathPool.GetPath<FloodPath>();
p.Setup(start, callback);
return p;
}
protected void Setup (Vector3 start, OnPathDelegate callback) {
this.callback = callback;
originalStartPoint = start;
startPoint = start;
heuristic = Heuristic.None;
}
protected void Setup (GraphNode start, OnPathDelegate callback) {
this.callback = callback;
originalStartPoint = (Vector3)start.position;
startNode = start;
startPoint = (Vector3)start.position;
heuristic = Heuristic.None;
}
protected override void Reset () {
base.Reset();
originalStartPoint = Vector3.zero;
startPoint = Vector3.zero;
startNode = null;
/** \todo Avoid this allocation */
parents = new Dictionary<GraphNode, GraphNode>();
saveParents = true;
}
protected override void Prepare () {
AstarProfiler.StartProfile("Get Nearest");
if (startNode == null) {
//Initialize the NNConstraint
nnConstraint.tags = enabledTags;
var startNNInfo = AstarPath.active.GetNearest(originalStartPoint, nnConstraint);
startPoint = startNNInfo.position;
startNode = startNNInfo.node;
} else {
startPoint = (Vector3)startNode.position;
}
AstarProfiler.EndProfile();
#if ASTARDEBUG
Debug.DrawLine((Vector3)startNode.position, startPoint, Color.blue);
#endif
if (startNode == null) {
FailWithError("Couldn't find a close node to the start point");
return;
}
if (!CanTraverse(startNode)) {
FailWithError("The node closest to the start point could not be traversed");
return;
}
}
protected override void Initialize () {
PathNode startRNode = pathHandler.GetPathNode(startNode);
startRNode.node = startNode;
startRNode.pathID = pathHandler.PathID;
startRNode.parent = null;
startRNode.cost = 0;
startRNode.G = GetTraversalCost(startNode);
startRNode.H = CalculateHScore(startNode);
parents[startNode] = null;
startNode.Open(this, startRNode, pathHandler);
searchedNodes++;
// Any nodes left to search?
if (pathHandler.heap.isEmpty) {
CompleteState = PathCompleteState.Complete;
}
currentR = pathHandler.heap.Remove();
}
/** Opens nodes until there are none left to search (or until the max time limit has been exceeded) */
protected override void CalculateStep (long targetTick) {
int counter = 0;
//Continue to search as long as we haven't encountered an error and we haven't found the target
while (CompleteState == PathCompleteState.NotCalculated) {
searchedNodes++;
AstarProfiler.StartFastProfile(4);
//Debug.DrawRay ((Vector3)currentR.node.Position, Vector3.up*2,Color.red);
//Loop through all walkable neighbours of the node and add them to the open list.
currentR.node.Open(this, currentR, pathHandler);
// Insert into internal search tree
if (saveParents) parents[currentR.node] = currentR.parent.node;
AstarProfiler.EndFastProfile(4);
//any nodes left to search?
if (pathHandler.heap.isEmpty) {
CompleteState = PathCompleteState.Complete;
break;
}
//Select the node with the lowest F score and remove it from the open list
AstarProfiler.StartFastProfile(7);
currentR = pathHandler.heap.Remove();
AstarProfiler.EndFastProfile(7);
//Check for time every 500 nodes, roughly every 0.5 ms usually
if (counter > 500) {
//Have we exceded the maxFrameTime, if so we should wait one frame before continuing the search since we don't want the game to lag
if (DateTime.UtcNow.Ticks >= targetTick) {
//Return instead of yield'ing, a separate function handles the yield (CalculatePaths)
return;
}
counter = 0;
if (searchedNodes > 1000000) {
throw new Exception("Probable infinite loop. Over 1,000,000 nodes searched");
}
}
counter++;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Hjerpbakk.Profilebot.Commands;
using Hjerpbakk.Profilebot.Contracts;
using Hjerpbakk.Profilebot.FaceDetection;
using Hjerpbakk.Profilebot.FaceDetection.Report;
using NLog;
using SlackConnector.Models;
namespace Hjerpbakk.Profilebot {
/// <summary>
/// A Slack-bot which verifies user profiles. The bot get its commands
/// from direct messages. If the bot doesn't understand, it will list
/// its available commands.
/// </summary>
public sealed class ProfilebotImplmentation : IDisposable {
static readonly Logger logger;
readonly SlackUser adminUser;
readonly IFaceWhitelist faceWhitelist;
readonly ISlackIntegration slackIntegration;
readonly ISlackProfileValidator slackProfileValidator;
/// <summary>
/// Gets the logger for this class.
/// </summary>
static ProfilebotImplmentation() {
logger = LogManager.GetCurrentClassLogger();
}
/// <summary>
/// Creates the Slack-bot.
/// </summary>
/// <param name="slackIntegration">Used for talking to the Slack APIs.</param>
/// <param name="slackProfileValidator">Used for checking user profiles for completeness.</param>
/// <param name="adminUser">Used for sending the results to the Slack admin.</param>
/// <param name="faceWhitelist">Knows about whitelisted users.</param>
public ProfilebotImplmentation(ISlackIntegration slackIntegration, ISlackProfileValidator slackProfileValidator, SlackUser adminUser, IFaceWhitelist faceWhitelist) {
this.slackIntegration = slackIntegration ?? throw new ArgumentNullException(nameof(slackIntegration));
this.slackProfileValidator = slackProfileValidator ?? throw new ArgumentNullException(nameof(slackProfileValidator));
if (string.IsNullOrEmpty(adminUser.Id)) {
throw new ArgumentException(nameof(adminUser.Id));
}
this.adminUser = new SlackUser {Id = adminUser.Id};
this.faceWhitelist = faceWhitelist ?? throw new ArgumentNullException(nameof(faceWhitelist));
}
/// <summary>
/// Disconnects the bot from Slack.
/// </summary>
public void Dispose() {
slackIntegration.MessageReceived -= MessageReceived;
}
/// <summary>
/// Connects the bot to Slack.
/// </summary>
/// <returns>No object or value is returned by this method when it completes.</returns>
public async Task Connect() {
await slackIntegration.Connect();
slackIntegration.MessageReceived += MessageReceived;
}
/// <summary>
/// Parses the messages sent to the bot and answers to the best of its abilities.
/// Extend this method to include more commands.
/// </summary>
/// <param name="message">The message sent to the bot.</param>
/// <returns>No object or value is returned by this method when it completes.</returns>
async Task MessageReceived(SlackMessage message) {
try {
VerifyMessageIsComplete(message);
if (message.ChatHub.Type != SlackChatHubType.DM) {
return;
}
var command = MessageParser.ParseCommand(message, adminUser);
switch (command) {
case AnswerRegularUserCommand _:
await AnswerRegularUser(message.User);
break;
case ValidateAllProfilesCommand _:
await ValidateAllProfiles();
break;
case NotifyAllProfilesCommand _:
await ValidateAllProfiles(true);
break;
case ValidateSingleProfileCommand c:
await ValidateSingleProfile(message.User, c.Payload);
break;
case NotifySingleProfileCommand c:
await ValidateSingleProfile(message.User, c.Payload, true);
break;
case WhitelistSingleProfileCommand c:
await WhitelistProfile(c.Payload);
break;
case ShowVersionNumberCommand _:
await SendVersionNumber();
break;
case ShowWhitelistedUsersCommand _:
await SendWhitelistedUsers();
break;
default:
await slackIntegration.SendDirectMessage(message.User,
$"Available commands are:{Environment.NewLine}- validate all users{Environment.NewLine}- notify all users{Environment.NewLine}- validate @user{Environment.NewLine}- notify @user{Environment.NewLine}- whitelist{Environment.NewLine}- whitelist @user{Environment.NewLine}- version");
break;
}
}
catch (Exception e) {
logger.Error(e);
try {
await slackIntegration.SendDirectMessage(adminUser, $"I crashed:{Environment.NewLine}{e}");
}
catch (Exception exception) {
logger.Fatal(exception);
throw;
}
}
}
static void VerifyMessageIsComplete(SlackMessage message) {
if (message == null) {
throw new ArgumentNullException(nameof(message));
}
if (message.User == null) {
throw new ArgumentNullException(nameof(message.User));
}
if (string.IsNullOrEmpty(message.User.Id)) {
throw new ArgumentException(nameof(message.User.Id));
}
if (string.IsNullOrEmpty(message.Text)) {
throw new ArgumentException(nameof(message.Text));
}
if (message.ChatHub == null) {
throw new ArgumentNullException(nameof(message.ChatHub));
}
}
async Task AnswerRegularUser(SlackUser user) {
await slackIntegration.SendDirectMessage(user, "Checking your profile");
var verificationResult = await slackProfileValidator.ValidateProfile(user);
if (verificationResult.IsValid) {
await slackIntegration.SendDirectMessage(user,
$"Well done <@{user.Id}>, your profile is complete");
}
else {
await slackIntegration.SendDirectMessage(user, verificationResult.Errors);
}
}
async Task ValidateAllProfiles(bool informUsers = false) {
if (informUsers) {
await slackIntegration.SendDirectMessage(adminUser, "Notifying all users");
}
else {
await slackIntegration.SendDirectMessage(adminUser, "Validating all users");
}
async Task<string> ValidateAllProfiles() {
var usersWithIncompleteProfiles = new List<ProfileValidationResult>();
foreach (var user in await slackIntegration.GetAllUsers()) {
await slackIntegration.IndicateTyping(adminUser);
var verificationResult = await slackProfileValidator.ValidateProfile(user);
if (verificationResult.IsValid) {
continue;
}
usersWithIncompleteProfiles.Add(verificationResult);
if (!informUsers) {
continue;
}
await slackIntegration.SendDirectMessage(verificationResult.User, verificationResult.Errors);
await slackIntegration.SendDirectMessage(adminUser, verificationResult.Errors);
}
var validationReport = new ValidationReport(usersWithIncompleteProfiles.ToArray());
await faceWhitelist.UploadReport(validationReport);
return validationReport.ToString();
}
await slackIntegration.SendDirectMessage(adminUser, await ValidateAllProfiles());
}
async Task ValidateSingleProfile(SlackUser sender, SlackUser user, bool notify = false) {
var verb = notify ? "Notifying" : "Validating";
await slackIntegration.SendDirectMessage(sender, $"{verb} {user.FormattedUserId}");
var userToCheck = await slackIntegration.GetUser(user.Id);
var validationResult = await slackProfileValidator.ValidateProfile(userToCheck);
if (validationResult.IsValid) {
await slackIntegration.SendDirectMessage(sender, $"{user.FormattedUserId} has a complete profile");
return;
}
await slackIntegration.SendDirectMessage(sender, validationResult.Errors);
if (notify) {
await slackIntegration.SendDirectMessage(validationResult.User, validationResult.Errors);
}
}
async Task WhitelistProfile(SlackUser user) {
await slackIntegration.IndicateTyping(adminUser);
await faceWhitelist.WhitelistUser(user);
await slackIntegration.SendDirectMessage(adminUser, $"Whitelisted {user.FormattedUserId}");
}
async Task SendVersionNumber() {
await slackIntegration.IndicateTyping(adminUser);
var version = Assembly.GetAssembly(typeof(ProfilebotImplmentation)).GetName().Version.ToString();
await slackIntegration.SendDirectMessage(adminUser, version);
}
async Task SendWhitelistedUsers() {
await slackIntegration.IndicateTyping(adminUser);
var whitelistedUsers = await faceWhitelist.GetWhitelistedUsers();
var message = "Whitelist: " + string.Join(", ", whitelistedUsers.Select(u => u.FormattedUserId));
await slackIntegration.SendDirectMessage(adminUser, message);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Buffers;
using System.Buffers.Pools;
using System.Buffers.Text;
using System.Collections.Generic;
using System.Collections.Sequences;
using System.Globalization;
using System.IO.Pipelines.Testing;
using System.IO.Pipelines.Text.Primitives;
using System.Linq;
using System.Text;
using System.Text.Formatting;
using System.Threading.Tasks;
using Xunit;
namespace System.IO.Pipelines.Tests
{
public class ReadableBufferFacts: IDisposable
{
const int BlockSize = 4032;
private IPipe _pipe;
private MemoryPool _pool;
public ReadableBufferFacts()
{
_pool = new MemoryPool();
_pipe = new Pipe(new PipeOptions(_pool));
}
public void Dispose()
{
_pipe.Writer.Complete();
_pipe.Reader.Complete();
_pool?.Dispose();
}
[Fact]
public void ReadableBufferSequenceWorks()
{
var readable = BufferUtilities.CreateBuffer(new byte[] { 1 }, new byte[] { 2, 2 }, new byte[] { 3, 3, 3 }).AsSequence();
var position = Position.First;
ReadOnlyMemory<byte> memory;
int spanCount = 0;
while (readable.TryGet(ref position, out memory))
{
spanCount++;
Assert.Equal(spanCount, memory.Length);
}
Assert.Equal(3, spanCount);
}
[Fact]
public void CanUseArrayBasedReadableBuffers()
{
var data = Encoding.ASCII.GetBytes("***abc|def|ghijk****"); // note sthe padding here - verifying that it is omitted correctly
var buffer = ReadableBuffer.Create(data, 3, data.Length - 7);
Assert.Equal(13, buffer.Length);
var split = buffer.Split((byte)'|');
Assert.Equal(3, split.Count());
using (var iter = split.GetEnumerator())
{
Assert.True(iter.MoveNext());
var current = iter.Current;
Assert.Equal("abc", current.GetAsciiString());
using (var preserved = iter.Current.Preserve())
{
Assert.Equal("abc", preserved.Buffer.GetAsciiString());
}
Assert.True(iter.MoveNext());
current = iter.Current;
Assert.Equal("def", current.GetAsciiString());
using (var preserved = iter.Current.Preserve())
{
Assert.Equal("def", preserved.Buffer.GetAsciiString());
}
Assert.True(iter.MoveNext());
current = iter.Current;
Assert.Equal("ghijk", current.GetAsciiString());
using (var preserved = iter.Current.Preserve())
{
Assert.Equal("ghijk", preserved.Buffer.GetAsciiString());
}
Assert.False(iter.MoveNext());
}
}
[Fact]
public void CanUseOwnedBufferBasedReadableBuffers()
{
var data = Encoding.ASCII.GetBytes("***abc|def|ghijk****"); // note sthe padding here - verifying that it is omitted correctly
OwnedMemory<byte> owned = new OwnedArray<byte>(data);
var buffer = ReadableBuffer.Create(owned, 3, data.Length - 7);
Assert.Equal(13, buffer.Length);
var split = buffer.Split((byte)'|');
Assert.Equal(3, split.Count());
using (var iter = split.GetEnumerator())
{
Assert.True(iter.MoveNext());
var current = iter.Current;
Assert.Equal("abc", current.GetAsciiString());
using (var preserved = iter.Current.Preserve())
{
Assert.Equal("abc", preserved.Buffer.GetAsciiString());
}
Assert.True(iter.MoveNext());
current = iter.Current;
Assert.Equal("def", current.GetAsciiString());
using (var preserved = iter.Current.Preserve())
{
Assert.Equal("def", preserved.Buffer.GetAsciiString());
}
Assert.True(iter.MoveNext());
current = iter.Current;
Assert.Equal("ghijk", current.GetAsciiString());
using (var preserved = iter.Current.Preserve())
{
Assert.Equal("ghijk", preserved.Buffer.GetAsciiString());
}
Assert.False(iter.MoveNext());
}
}
[Fact]
public async Task CopyToAsyncNativeMemory()
{
var output = _pipe.Writer.Alloc();
output.AsOutput().Append("Hello World", SymbolTable.InvariantUtf8);
await output.FlushAsync();
var ms = new MemoryStream();
var result = await _pipe.Reader.ReadAsync();
var rb = result.Buffer;
await rb.CopyToAsync(ms);
ms.Position = 0;
Assert.Equal(11, rb.Length);
Assert.Equal(11, ms.Length);
Assert.Equal(rb.ToArray(), ms.ToArray());
Assert.Equal("Hello World", Encoding.ASCII.GetString(ms.ToArray()));
_pipe.Reader.Advance(rb.End);
}
[Fact]
public async Task TestIndexOfWorksForAllLocations()
{
const int Size = 5 * BlockSize; // multiple blocks
// populate with a pile of dummy data
byte[] data = new byte[512];
for (int i = 0; i < data.Length; i++) data[i] = 42;
int totalBytes = 0;
var writeBuffer = _pipe.Writer.Alloc();
for (int i = 0; i < Size / data.Length; i++)
{
writeBuffer.Write(data);
totalBytes += data.Length;
}
await writeBuffer.FlushAsync();
// now read it back
var result = await _pipe.Reader.ReadAsync();
var readBuffer = result.Buffer;
Assert.False(readBuffer.IsSingleSpan);
Assert.Equal(totalBytes, readBuffer.Length);
TestIndexOfWorksForAllLocations(ref readBuffer, 42);
_pipe.Reader.Advance(readBuffer.End);
}
[Fact]
public async Task EqualsDetectsDeltaForAllLocations()
{
// populate with dummy data
const int DataSize = 10000;
byte[] data = new byte[DataSize];
var rand = new Random(12345);
rand.NextBytes(data);
var writeBuffer = _pipe.Writer.Alloc();
writeBuffer.Write(data);
await writeBuffer.FlushAsync();
// now read it back
var result = await _pipe.Reader.ReadAsync();
var readBuffer = result.Buffer;
Assert.False(readBuffer.IsSingleSpan);
Assert.Equal(data.Length, readBuffer.Length);
// check the entire buffer
EqualsDetectsDeltaForAllLocations(readBuffer, data, 0, data.Length);
// check the first 32 sub-lengths
for (int i = 0; i <= 32; i++)
{
var slice = readBuffer.Slice(0, i);
EqualsDetectsDeltaForAllLocations(slice, data, 0, i);
}
// check the last 32 sub-lengths
for (int i = 0; i <= 32; i++)
{
var slice = readBuffer.Slice(data.Length - i, i);
EqualsDetectsDeltaForAllLocations(slice, data, data.Length - i, i);
}
_pipe.Reader.Advance(readBuffer.End);
}
private void EqualsDetectsDeltaForAllLocations(ReadableBuffer slice, byte[] expected, int offset, int length)
{
Assert.Equal(length, slice.Length);
Assert.True(slice.EqualsTo(new Span<byte>(expected, offset, length)));
// change one byte in buffer, for every position
for (int i = 0; i < length; i++)
{
expected[offset + i] ^= 42;
Assert.False(slice.EqualsTo(new Span<byte>(expected, offset, length)));
expected[offset + i] ^= 42;
}
}
[Fact]
public async Task GetUInt64GivesExpectedValues()
{
var writeBuffer = _pipe.Writer.Alloc();
writeBuffer.Ensure(50);
writeBuffer.Advance(50); // not even going to pretend to write data here - we're going to cheat
await writeBuffer.FlushAsync(); // by overwriting the buffer in-situ
// now read it back
var result = await _pipe.Reader.ReadAsync();
var readBuffer = result.Buffer;
ReadUInt64GivesExpectedValues(ref readBuffer);
_pipe.Reader.Advance(readBuffer.End);
}
[Theory]
[InlineData(" hello", "hello")]
[InlineData(" hello", "hello")]
[InlineData("\r\n hello", "hello")]
[InlineData("\rhe llo", "he llo")]
[InlineData("\thell o ", "hell o ")]
public async Task TrimStartTrimsWhitespaceAtStart(string input, string expected)
{
var writeBuffer = _pipe.Writer.Alloc();
var bytes = Encoding.ASCII.GetBytes(input);
writeBuffer.Write(bytes);
await writeBuffer.FlushAsync();
var result = await _pipe.Reader.ReadAsync();
var buffer = result.Buffer;
var trimmed = buffer.TrimStart();
var outputBytes = trimmed.ToArray();
Assert.Equal(expected, Encoding.ASCII.GetString(outputBytes));
_pipe.Reader.Advance(buffer.End);
}
[Theory]
[InlineData("hello ", "hello")]
[InlineData("hello ", "hello")]
[InlineData("hello \r\n", "hello")]
[InlineData("he llo\r", "he llo")]
[InlineData(" hell o\t", " hell o")]
public async Task TrimEndTrimsWhitespaceAtEnd(string input, string expected)
{
var writeBuffer = _pipe.Writer.Alloc();
var bytes = Encoding.ASCII.GetBytes(input);
writeBuffer.Write(bytes);
await writeBuffer.FlushAsync();
var result = await _pipe.Reader.ReadAsync();
var buffer = result.Buffer;
var trimmed = buffer.TrimEnd();
var outputBytes = trimmed.ToArray();
_pipe.Reader.Advance(buffer.End);
Assert.Equal(expected, Encoding.ASCII.GetString(outputBytes));
}
[Theory]
[InlineData("foo\rbar\r\n", "\r\n", "foo\rbar")]
[InlineData("foo\rbar\r\n", "\rbar", "foo")]
[InlineData("/pathpath/", "path/", "/path")]
[InlineData("hellzhello", "hell", null)]
public async Task TrySliceToSpan(string input, string sliceTo, string expected)
{
var sliceToBytes = Encoding.UTF8.GetBytes(sliceTo);
var writeBuffer = _pipe.Writer.Alloc();
var bytes = Encoding.UTF8.GetBytes(input);
writeBuffer.Write(bytes);
await writeBuffer.FlushAsync();
var result = await _pipe.Reader.ReadAsync();
var buffer = result.Buffer;
ReadableBuffer slice;
ReadCursor cursor;
Assert.True(buffer.TrySliceTo(sliceToBytes, out slice, out cursor));
Assert.Equal(expected, slice.GetUtf8String());
_pipe.Reader.Advance(buffer.End);
}
private unsafe void TestIndexOfWorksForAllLocations(ref ReadableBuffer readBuffer, byte emptyValue)
{
byte huntValue = (byte)~emptyValue;
var handles = new List<MemoryHandle>();
// we're going to fully index the final locations of the buffer, so that we
// can mutate etc in constant time
var addresses = BuildPointerIndex(ref readBuffer, handles);
// check it isn't there to start with
ReadableBuffer slice;
ReadCursor cursor;
var found = readBuffer.TrySliceTo(huntValue, out slice, out cursor);
Assert.False(found);
// correctness test all values
for (int i = 0; i < readBuffer.Length; i++)
{
*addresses[i] = huntValue;
found = readBuffer.TrySliceTo(huntValue, out slice, out cursor);
*addresses[i] = emptyValue;
Assert.True(found);
var remaining = readBuffer.Slice(cursor);
var handle = remaining.First.Retain(pin: true);
Assert.True(handle.PinnedPointer != null);
if (i % BlockSize == 0)
{
Assert.True((byte*)handle.PinnedPointer == addresses[i]);
}
handle.Dispose();
}
// free up memory handles
foreach (var handle in handles)
{
handle.Dispose();
}
handles.Clear();
}
private static unsafe byte*[] BuildPointerIndex(ref ReadableBuffer readBuffer, List<MemoryHandle> handles)
{
byte*[] addresses = new byte*[readBuffer.Length];
int index = 0;
foreach (var memory in readBuffer)
{
var handle = memory.Retain(pin: true);
handles.Add(handle);
var ptr = (byte*)handle.PinnedPointer;
for (int i = 0; i < memory.Length; i++)
{
addresses[index++] = ptr++;
}
}
return addresses;
}
private unsafe void ReadUInt64GivesExpectedValues(ref ReadableBuffer readBuffer)
{
Assert.True(readBuffer.IsSingleSpan);
for (ulong i = 0; i < 1024; i++)
{
TestValue(ref readBuffer, i);
}
TestValue(ref readBuffer, ulong.MinValue);
TestValue(ref readBuffer, ulong.MaxValue);
var rand = new Random(41234);
// low numbers
for (int i = 0; i < 10000; i++)
{
TestValue(ref readBuffer, (ulong)rand.Next());
}
// wider range of numbers
for (int i = 0; i < 10000; i++)
{
ulong x = (ulong)rand.Next(), y = (ulong)rand.Next();
TestValue(ref readBuffer, (x << 32) | y);
TestValue(ref readBuffer, (y << 32) | x);
}
}
private unsafe void TestValue(ref ReadableBuffer readBuffer, ulong value)
{
fixed (byte* ptr = &readBuffer.First.Span.DangerousGetPinnableReference())
{
string s = value.ToString(CultureInfo.InvariantCulture);
int written;
fixed (char* c = s)
{
// We are able to cast because test arguments are in range of int
written = Encoding.ASCII.GetBytes(c, s.Length, ptr, (int)readBuffer.Length);
}
var slice = readBuffer.Slice(0, written);
Assert.Equal(value, slice.GetUInt64());
}
}
[Theory]
[InlineData("abc,def,ghi", ',')]
[InlineData("a;b;c;d", ';')]
[InlineData("a;b;c;d", ',')]
[InlineData("", ',')]
public async Task Split(string input, char delimiter)
{
// note: different expectation to string.Split; empty has 0 outputs
var expected = input == "" ? new string[0] : input.Split(delimiter);
var output = _pipe.Writer.Alloc();
output.AsOutput().Append(input, SymbolTable.InvariantUtf8);
var readable = BufferUtilities.CreateBuffer(input);
// via struct API
var iter = readable.Split((byte)delimiter);
Assert.Equal(expected.Length, iter.Count());
int i = 0;
foreach (var item in iter)
{
Assert.Equal(expected[i++], item.GetUtf8String());
}
Assert.Equal(expected.Length, i);
// via objects/LINQ etc
IEnumerable<ReadableBuffer> asObject = iter;
Assert.Equal(expected.Length, asObject.Count());
i = 0;
foreach (var item in asObject)
{
Assert.Equal(expected[i++], item.GetUtf8String());
}
Assert.Equal(expected.Length, i);
await output.FlushAsync();
}
[Fact]
public void ReadTWorksAgainstSimpleBuffers()
{
var readable = BufferUtilities.CreateBuffer(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7 });
var span = readable.First.Span;
Assert.True(readable.IsSingleSpan);
Assert.Equal(span.Read<byte>(), readable.ReadLittleEndian<byte>());
Assert.Equal(span.Read<sbyte>(), readable.ReadLittleEndian<sbyte>());
Assert.Equal(span.Read<short>(), readable.ReadLittleEndian<short>());
Assert.Equal(span.Read<ushort>(), readable.ReadLittleEndian<ushort>());
Assert.Equal(span.Read<int>(), readable.ReadLittleEndian<int>());
Assert.Equal(span.Read<uint>(), readable.ReadLittleEndian<uint>());
Assert.Equal(span.Read<long>(), readable.ReadLittleEndian<long>());
Assert.Equal(span.Read<ulong>(), readable.ReadLittleEndian<ulong>());
Assert.Equal(span.Read<float>(), readable.ReadLittleEndian<float>());
Assert.Equal(span.Read<double>(), readable.ReadLittleEndian<double>());
}
[Fact]
public void ReadTWorksAgainstMultipleBuffers()
{
var readable = BufferUtilities.CreateBuffer(new byte[] { 0, 1, 2 }, new byte[] { 3, 4, 5 }, new byte[] { 6, 7, 9 });
Assert.Equal(9, readable.Length);
int spanCount = 0;
foreach (var _ in readable)
{
spanCount++;
}
Assert.Equal(3, spanCount);
Assert.False(readable.IsSingleSpan);
Span<byte> span = readable.ToArray();
Assert.Equal(span.Read<byte>(), readable.ReadLittleEndian<byte>());
Assert.Equal(span.Read<sbyte>(), readable.ReadLittleEndian<sbyte>());
Assert.Equal(span.Read<short>(), readable.ReadLittleEndian<short>());
Assert.Equal(span.Read<ushort>(), readable.ReadLittleEndian<ushort>());
Assert.Equal(span.Read<int>(), readable.ReadLittleEndian<int>());
Assert.Equal(span.Read<uint>(), readable.ReadLittleEndian<uint>());
Assert.Equal(span.Read<long>(), readable.ReadLittleEndian<long>());
Assert.Equal(span.Read<ulong>(), readable.ReadLittleEndian<ulong>());
Assert.Equal(span.Read<float>(), readable.ReadLittleEndian<float>());
Assert.Equal(span.Read<double>(), readable.ReadLittleEndian<double>());
}
[Fact]
public async Task CopyToAsync()
{
using (var pool = new MemoryPool())
{
var readerWriter = new Pipe(new PipeOptions(pool));
var output = readerWriter.Writer.Alloc();
output.AsOutput().Append("Hello World", SymbolTable.InvariantUtf8);
await output.FlushAsync();
var ms = new MemoryStream();
var result = await readerWriter.Reader.ReadAsync();
var rb = result.Buffer;
await rb.CopyToAsync(ms);
ms.Position = 0;
Assert.Equal(11, rb.Length);
Assert.Equal(11, ms.Length);
Assert.Equal(rb.ToArray(), ms.ToArray());
Assert.Equal("Hello World", Encoding.ASCII.GetString(ms.ToArray()));
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
namespace Pinball
{
public struct ZunePadState
{
GamePadState state;
Vector2 flick;
bool tapped;
/// <summary>
/// Has the pad been touched or pressed at all?
/// </summary>
public bool IsTouchedorPressed
{
get
{
if (TouchablePad)
{
return state.Buttons.LeftStick == ButtonState.Pressed;
}
else
{
return false;
}
}
}
/// <summary>
/// Has the pad been tapped?
/// </summary>
public bool IsTapped
{
get { return tapped; }
}
//tells if the zune's pad has been clicked at any point
/// <summary>
/// Has the pad been clicked anywhere?
/// </summary>
public ButtonState IsClickedAnywhere
{
get { return state.Buttons.LeftShoulder; }
}
/// <summary>
/// Tells if this zune has a touchable pad.
/// </summary>
public static bool TouchablePad
{
get
{
return GamePad.GetCapabilities(PlayerIndex.One).HasLeftXThumbStick;
}
}
/// <summary>
/// Tells if this zune has a flickable pad (Same as TouchablePad).
/// </summary>
public static bool FlickablePad
{
get
{
return TouchablePad;
}
}
public static bool ClickableCenterPad
{
get
{
return GamePad.GetCapabilities(PlayerIndex.One).HasAButton;
}
}
/// <summary>
/// Was the pad flicked?
/// </summary>
public Vector2 Flick
{
get
{
if (tapped == true)
{
return Vector2.Zero;
}
else
{
return flick;
}
}
}
/// <summary>
/// The position the finger is on the pad (thumbstick).
/// </summary>
public Vector2 TouchPosition
{
get
{
if (TouchablePad)
{
return state.ThumbSticks.Left;
}
else
{
return Vector2.Zero;
}
}
}
/// <summary>
/// The back button.
/// </summary>
public ButtonState BackButton
{
get { return state.Buttons.Back; }
}
/// <summary>
/// The play button (B).
/// </summary>
public ButtonState PlayButton
{
get { return state.Buttons.B; }
}
//used when the zune's pad is clicked in the center
/// <summary>
/// The center of the pad clicked (A).
/// </summary>
public ButtonState PadCenterPressed
{
get
{
if (ClickableCenterPad)
{
return state.Buttons.A;
}
else
{
return ButtonState.Released;
}
}
}
/// <summary>
/// The pad with only 4 directions.
/// </summary>
public GamePadDPad DPad
{
get { return state.DPad; }
}
public ZunePadState(GamePadState state, Vector2 flick, bool tapped)
{
this.state = state;
this.flick = flick;
this.tapped = tapped;
}
}
public static class ZunePad
{
static ZunePadState zps;
static float flickStartTime;
static Vector2 flickStart;
/// <summary>
/// Gets the state of the Zune input allowing for flicks and taps.
/// </summary>
/// <param name="gameTime">The current time snapshot</param>
/// <returns>The new ZunePadState object.</returns>
public static ZunePadState GetState(GameTime gameTime)
{
GamePadState gps = GamePad.GetState(PlayerIndex.One, GamePadDeadZone.None);
Vector2 flick = Vector2.Zero;
bool tapped = false;
if (GamePad.GetCapabilities(PlayerIndex.One).HasLeftXThumbStick)
{
if (gps.Buttons.LeftStick == ButtonState.Pressed && !zps.IsTouchedorPressed)
{
flickStart = gps.ThumbSticks.Left;
flickStartTime = (float)gameTime.TotalGameTime.TotalSeconds;
}
else if (gps.Buttons.LeftStick == ButtonState.Released && zps.IsTouchedorPressed)
{
flick = zps.TouchPosition - flickStart;
float elapsed = (float)(gameTime.TotalGameTime.TotalSeconds - flickStartTime);
//scale the flick based on how long it took
flick /= (float)elapsed;
//adjust the .5 and .3 to fit your sensitivity needs. .5 and .3 seem
//to be pretty decent, but they might need tweaking for some situations
tapped = (flick.Length() < .5f && elapsed < .3f);
flickStart = Vector2.Zero;
}
}
zps = new ZunePadState(gps, flick, tapped);
return zps;
}
/// <summary>
/// Gets the state of the Zune input without flicks or taps.
/// </summary>
/// <returns>The new ZunePadState object.</returns>
public static ZunePadState GetState()
{
GamePadState gps = GamePad.GetState(PlayerIndex.One, GamePadDeadZone.None);
zps = new ZunePadState(gps, Vector2.Zero, false);
return zps;
}
}
}
| |
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.IO;
using PhysFS_NET;
namespace TestApp
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class TestAppForm : System.Windows.Forms.Form
{
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Button RefreshCDsButton;
private System.Windows.Forms.ListBox CDDrivesList;
private System.Windows.Forms.ListBox SearchPathList;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox EnumFilesPath;
private System.Windows.Forms.ListBox EnumList;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.TextBox NewSearchPathText;
private System.Windows.Forms.Button AddSearchPathButton;
private System.Windows.Forms.Button RemovePathButton;
private System.Windows.Forms.Button RefreshEnumList;
private System.Windows.Forms.Button RefreshSearchPathButton;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public TestAppForm()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
}
/// <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 Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.label2 = new System.Windows.Forms.Label();
this.RefreshCDsButton = new System.Windows.Forms.Button();
this.CDDrivesList = new System.Windows.Forms.ListBox();
this.SearchPathList = new System.Windows.Forms.ListBox();
this.label1 = new System.Windows.Forms.Label();
this.EnumFilesPath = new System.Windows.Forms.TextBox();
this.EnumList = new System.Windows.Forms.ListBox();
this.label3 = new System.Windows.Forms.Label();
this.RefreshEnumList = new System.Windows.Forms.Button();
this.NewSearchPathText = new System.Windows.Forms.TextBox();
this.AddSearchPathButton = new System.Windows.Forms.Button();
this.RemovePathButton = new System.Windows.Forms.Button();
this.RefreshSearchPathButton = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// label2
//
this.label2.Location = new System.Drawing.Point(8, 8);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(136, 16);
this.label2.TabIndex = 2;
this.label2.Text = "Available CD-ROM Drives";
//
// RefreshCDsButton
//
this.RefreshCDsButton.Location = new System.Drawing.Point(8, 152);
this.RefreshCDsButton.Name = "RefreshCDsButton";
this.RefreshCDsButton.Size = new System.Drawing.Size(72, 24);
this.RefreshCDsButton.TabIndex = 4;
this.RefreshCDsButton.Text = "Refresh";
this.RefreshCDsButton.Click += new System.EventHandler(this.RefreshCDsButton_Click);
//
// CDDrivesList
//
this.CDDrivesList.Location = new System.Drawing.Point(8, 24);
this.CDDrivesList.Name = "CDDrivesList";
this.CDDrivesList.Size = new System.Drawing.Size(136, 121);
this.CDDrivesList.TabIndex = 7;
//
// SearchPathList
//
this.SearchPathList.Location = new System.Drawing.Point(152, 24);
this.SearchPathList.Name = "SearchPathList";
this.SearchPathList.Size = new System.Drawing.Size(248, 95);
this.SearchPathList.TabIndex = 8;
//
// label1
//
this.label1.Location = new System.Drawing.Point(152, 8);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(136, 16);
this.label1.TabIndex = 10;
this.label1.Text = "Search Path";
//
// EnumFilesPath
//
this.EnumFilesPath.Location = new System.Drawing.Point(408, 128);
this.EnumFilesPath.Name = "EnumFilesPath";
this.EnumFilesPath.Size = new System.Drawing.Size(208, 20);
this.EnumFilesPath.TabIndex = 11;
this.EnumFilesPath.Text = "";
//
// EnumList
//
this.EnumList.Location = new System.Drawing.Point(408, 24);
this.EnumList.Name = "EnumList";
this.EnumList.Size = new System.Drawing.Size(208, 95);
this.EnumList.TabIndex = 12;
//
// label3
//
this.label3.Location = new System.Drawing.Point(408, 8);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(136, 16);
this.label3.TabIndex = 13;
this.label3.Text = "Enumerate Files";
//
// RefreshEnumList
//
this.RefreshEnumList.Location = new System.Drawing.Point(544, 152);
this.RefreshEnumList.Name = "RefreshEnumList";
this.RefreshEnumList.Size = new System.Drawing.Size(72, 24);
this.RefreshEnumList.TabIndex = 14;
this.RefreshEnumList.Text = "Refresh";
this.RefreshEnumList.Click += new System.EventHandler(this.RefreshEnumList_Click);
//
// NewSearchPathText
//
this.NewSearchPathText.Location = new System.Drawing.Point(152, 128);
this.NewSearchPathText.Name = "NewSearchPathText";
this.NewSearchPathText.Size = new System.Drawing.Size(248, 20);
this.NewSearchPathText.TabIndex = 15;
this.NewSearchPathText.Text = "";
//
// AddSearchPathButton
//
this.AddSearchPathButton.Location = new System.Drawing.Point(152, 152);
this.AddSearchPathButton.Name = "AddSearchPathButton";
this.AddSearchPathButton.Size = new System.Drawing.Size(72, 24);
this.AddSearchPathButton.TabIndex = 9;
this.AddSearchPathButton.Text = "Add Path";
this.AddSearchPathButton.Click += new System.EventHandler(this.AddSearchPathButton_Click);
//
// RemovePathButton
//
this.RemovePathButton.Location = new System.Drawing.Point(232, 152);
this.RemovePathButton.Name = "RemovePathButton";
this.RemovePathButton.Size = new System.Drawing.Size(88, 24);
this.RemovePathButton.TabIndex = 16;
this.RemovePathButton.Text = "Remove Path";
this.RemovePathButton.Click += new System.EventHandler(this.RemovePathButton_Click);
//
// RefreshSearchPathButton
//
this.RefreshSearchPathButton.Location = new System.Drawing.Point(328, 152);
this.RefreshSearchPathButton.Name = "RefreshSearchPathButton";
this.RefreshSearchPathButton.Size = new System.Drawing.Size(72, 24);
this.RefreshSearchPathButton.TabIndex = 17;
this.RefreshSearchPathButton.Text = "Refresh";
this.RefreshSearchPathButton.Click += new System.EventHandler(this.RefreshSearchPathButton_Click);
//
// TestAppForm
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(624, 309);
this.Controls.AddRange(new System.Windows.Forms.Control[] {
this.RefreshSearchPathButton,
this.RemovePathButton,
this.NewSearchPathText,
this.RefreshEnumList,
this.label3,
this.EnumList,
this.EnumFilesPath,
this.label1,
this.SearchPathList,
this.CDDrivesList,
this.RefreshCDsButton,
this.label2,
this.AddSearchPathButton});
this.Name = "TestAppForm";
this.Text = "PhysFS Test Application";
this.Load += new System.EventHandler(this.TestAppForm_Load);
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new TestAppForm());
}
private void TestAppForm_Load(object sender, System.EventArgs e)
{
}
private void RefreshCDsButton_Click(object sender, System.EventArgs e)
{
// Clear ths listbox if it contains any items
CDDrivesList.Items.Clear();
// Add the items to the list
CDDrivesList.Items.AddRange(PhysFS.GetCDROMDrives());
}
private void RefreshSearchPathButton_Click(object sender, System.EventArgs e)
{
// Clear ths listbox if it contains any items
SearchPathList.Items.Clear();
// Add the items to the list
SearchPathList.Items.AddRange(PhysFS.GetSearchPath());
}
private void AddSearchPathButton_Click(object sender, System.EventArgs e)
{
// Add search path
PhysFS.AddToSearchPath(NewSearchPathText.Text, false);
// Clear ths listbox if it contains any items
SearchPathList.Items.Clear();
// Add the items to the list
SearchPathList.Items.AddRange(PhysFS.GetSearchPath());
}
private void RemovePathButton_Click(object sender, System.EventArgs e)
{
if(SearchPathList.SelectedItem != null)
{
PhysFS.RemoveFromSearchPath(SearchPathList.SelectedItem.ToString());
// Clear ths listbox if it contains any items
SearchPathList.Items.Clear();
// Add the items to the list
SearchPathList.Items.AddRange(PhysFS.GetSearchPath());
}
}
private void RefreshEnumList_Click(object sender, System.EventArgs e)
{
EnumList.Items.Clear();
EnumList.Items.AddRange(PhysFS.EnumerateFiles(EnumFilesPath.Text));
}
}
}
| |
//---------------------------------------------------------------------
// This file is part of the CLR Managed Debugger (mdbg) Sample.
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//---------------------------------------------------------------------
using System;
using System.Reflection;
using System.Collections;
using System.Collections.Specialized;
using System.Resources;
using System.Diagnostics;
namespace Microsoft.Samples.Tools.Mdbg
{
/// <summary>
/// This attribute describes the command.
/// </summary>
[
AttributeUsage(
AttributeTargets.Method,
AllowMultiple = true,
Inherited = false
)
]
public sealed class CommandDescriptionAttribute : Attribute
{
/// <summary>
/// Returns the command name.
/// </summary>
/// <value>Name of the command.</value>
public string CommandName
{
get
{
return m_commandName;
}
set
{
m_commandName = value;
m_minimumAbbrev = m_commandName.Length;
}
}
/// <summary>
/// Returns the minimum number of characters you must use to invoke this command.
/// </summary>
/// <value>The minimum number of characters.</value>
public int MinimumAbbrev
{
get
{
return m_minimumAbbrev;
}
set
{
m_minimumAbbrev = value;
}
}
/// <summary>
/// Returns a brief help message for the command.
/// </summary>
/// <value>The help message.</value>
public string ShortHelp
{
get
{
if (m_resourceMgrKey != null)
{
ResourceManager rm = (ResourceManager)m_resources[m_resourceMgrKey];
if (rm == null)
{
return m_shortHelp;
}
string key = (UseHelpFrom != null) ? UseHelpFrom : m_commandName;
return rm.GetString(key + "_ShortHelp", System.Globalization.CultureInfo.CurrentUICulture);
}
else
{
return m_shortHelp;
}
}
set
{
m_shortHelp = value;
}
}
/// <summary>
/// Returns a more detailed help message for the command.
/// </summary>
/// <value>The help message.</value>
public string LongHelp
{
get
{
if (m_resourceMgrKey != null)
{
ResourceManager rm = (ResourceManager)m_resources[m_resourceMgrKey];
string key = UseHelpFrom != null ? UseHelpFrom : m_commandName;
return rm.GetString(key + "_LongHelp", System.Globalization.CultureInfo.CurrentUICulture);
}
else
{
return m_longHelp == null ? "usage: \n" + m_shortHelp : m_longHelp;
}
}
set
{
m_longHelp = value;
}
}
/// <summary>
/// Returns if the command is repeatable (hitting enter again will repeat these commands)
/// </summary>
/// <value>true if the command is repeatable</value>
public bool IsRepeatable
{
get
{
return m_isRepeatable;
}
set
{
m_isRepeatable = value;
}
}
/// <summary>
/// Gets or sets the Resource Manager Key.
/// </summary>
/// <value>The Resource Manager Key.</value>
public Type ResourceManagerKey
{
get
{
return m_resourceMgrKey;
}
set
{
Debug.Assert(value != null);
m_resourceMgrKey = value;
}
}
/// <summary>
/// Gets or sets where to get the help from.
/// </summary>
/// <value>Where to get the help from.</value>
public string UseHelpFrom
{
get
{
return m_useHelpFrom;
}
set
{
m_useHelpFrom = value;
}
}
/// <summary>
/// Registers the Resource Manager.
/// </summary>
/// <param name="key">Whet Type to use.</param>
/// <param name="resourceManager">Which Resource Manager to register.</param>
public static void RegisterResourceMgr(Type key, System.Resources.ResourceManager resourceManager)
{
Debug.Assert(resourceManager != null && key != null);
if (key == null || resourceManager == null)
{
throw new ArgumentException();
}
if (m_resources == null)
{
m_resources = new Hashtable();
}
if (m_resources.ContainsKey(key))
{
throw new ArgumentException("key already registered");
}
m_resources.Add(key, resourceManager);
}
private static Hashtable m_resources;
private string m_commandName;
private int m_minimumAbbrev;
private string m_shortHelp;
private string m_longHelp;
private bool m_isRepeatable = true;
private Type m_resourceMgrKey = null;
private string m_useHelpFrom = null;
}
/// <summary>
/// This class defines MDbg Attribute Defined Commands.
/// </summary>
public sealed class MDbgAttributeDefinedCommand : IMDbgCommand, IEquatable<IMDbgCommand>
{
private MDbgAttributeDefinedCommand(MethodInfo methodInfo, CommandDescriptionAttribute descriptionAttribute)
{
m_mi = methodInfo;
m_cmdDescr = descriptionAttribute;
if (!g_extensions.Contains(LoadedFrom))
{
g_extensions.Add(LoadedFrom, g_freeAssemblySeqNumber++);
}
}
/// <summary>
/// Adds commands from type.
/// </summary>
/// <param name="commandSet">Command Set to add.</param>
/// <param name="type">Type to add commands for.</param>
public static void AddCommandsFromType(IMDbgCommandCollection commandSet, Type type)
{
foreach (MethodInfo mi in type.GetMethods())
{
object[] attribs = mi.GetCustomAttributes(typeof(CommandDescriptionAttribute), false);
if (attribs != null)
{
foreach (object o in attribs)
{
if (o is CommandDescriptionAttribute)
{
MDbgAttributeDefinedCommand cmd =
new MDbgAttributeDefinedCommand(mi, (CommandDescriptionAttribute)o);
Debug.Assert(cmd != null);
commandSet.Add(cmd);
}
}
}
}
}
/// <summary>
/// Removes commands from type
/// </summary>
/// <param name="commandSet">Command Set to remove.</param>
/// <param name="type">Type to remove commands for.</param>
public static void RemoveCommandsFromType(IMDbgCommandCollection commandSet, Type type)
{
foreach (MethodInfo mi in type.GetMethods())
{
object[] attribs = mi.GetCustomAttributes(typeof(CommandDescriptionAttribute), false);
if (attribs != null)
{
foreach (object o in attribs)
{
if (o is CommandDescriptionAttribute)
{
MDbgAttributeDefinedCommand cmd =
new MDbgAttributeDefinedCommand(mi, (CommandDescriptionAttribute)o);
Debug.Assert(cmd != null);
commandSet.Remove(cmd);
}
}
}
}
}
/// <summary>
/// Returns the command name.
/// </summary>
/// <value>Name of the command.</value>
public string CommandName
{
get
{
return m_cmdDescr.CommandName;
}
}
/// <summary>
/// Returns the minimum number of characters you must use to invoke this command.
/// </summary>
/// <value>The minimum number of characters.</value>
public int MinimumAbbrev
{
get
{
return m_cmdDescr.MinimumAbbrev;
}
}
/// <summary>
/// Executes the command.
/// </summary>
/// <param name="arguments">Arguments to pass to the command.</param>
public void Execute(string arguments)
{
m_mi.Invoke(null, new object[] { arguments });
}
/// <summary>
/// Returns a brief help message for the command.
/// </summary>
/// <value>The help message.</value>
public string ShortHelp
{
get
{
return m_cmdDescr.ShortHelp;
}
}
/// <summary>
/// Returns a more detailed help message for the command.
/// </summary>
/// <value>The help message.</value>
public string LongHelp
{
get
{
return m_cmdDescr.LongHelp;
}
}
/// <summary>
/// Assembly the command was loaded from
/// </summary>
/// <value>The Assembly.</value>
public Assembly LoadedFrom
{
get
{
return m_mi.DeclaringType.Assembly;
}
}
/// <summary>
/// Returns if the command is repeatable (hitting enter again will repeat these commands)
/// </summary>
/// <value>true if the command is repeatable</value>
public bool IsRepeatable
{
get
{
return m_cmdDescr.IsRepeatable;
}
}
int IComparable.CompareTo(object obj)
{
// we'll sort the commands first by extensions by which they were loaded
// and then by it's name.
if (!(obj is IMDbgCommand))
{
return 1; // unknown types always at the start of the list
}
IMDbgCommand other = obj as IMDbgCommand;
if (this.LoadedFrom != other.LoadedFrom)
{
return (int)g_extensions[this.LoadedFrom] - (int)g_extensions[other.LoadedFrom];
}
// commands are from same extension
return String.Compare(CommandName, (obj as IMDbgCommand).CommandName);
}
public bool Equals(IMDbgCommand cmd)
{
// We could be a little more thorough in our equivalence checks, but LoadedFrom and CommandName
// are the most telling
if (this.CommandName != cmd.CommandName || this.LoadedFrom != cmd.LoadedFrom)
{
return false;
}
return true;
}
private readonly MethodInfo m_mi;
private readonly CommandDescriptionAttribute m_cmdDescr;
private static int g_freeAssemblySeqNumber = 0;
private static readonly ListDictionary g_extensions = new ListDictionary();
}
}
| |
namespace NArrange.Tests.Core
{
using System;
using System.IO;
using System.Reflection;
using System.Text;
using NArrange.Core;
using NArrange.Core.Configuration;
using NArrange.Tests.CSharp;
using NUnit.Framework;
/// <summary>
/// Test fixture for the FileArranger class.
/// </summary>
[TestFixture]
public class FileArrangerTests
{
#region Fields
/// <summary>
/// Test filtered file name.
/// </summary>
private string _testFilteredFile;
/// <summary>
/// Test filtered project file name.
/// </summary>
private string _testFilteredProjectFile;
/// <summary>
/// Test invalid extension file name.
/// </summary>
private string _testInvalidExtensionFile;
/// <summary>
/// Test invalid source file name.
/// </summary>
private string _testInvalidSourceFile;
/// <summary>
/// Test project file name.
/// </summary>
private string _testProjectFile;
/// <summary>
/// Test solution file name.
/// </summary>
private string _testSolutionFile;
/// <summary>
/// Test UTF8 encoding file name.
/// </summary>
private string _testUTF8File;
/// <summary>
/// Test valid source file name.
/// </summary>
private string _testValidSourceFile1;
/// <summary>
/// Test valid source file name.
/// </summary>
private string _testValidSourceFile2;
#endregion Fields
#region Methods
/// <summary>
/// Tests arranging all files in a directory.
/// </summary>
[Test]
public void ArrangeDirectoryTest()
{
string testSourceParentDirectory = Path.Combine(Path.GetTempPath(), "TestSource");
string testSourceChildDirectory = Path.Combine(testSourceParentDirectory, "Child");
try
{
try
{
Directory.CreateDirectory(testSourceParentDirectory);
}
catch
{
}
try
{
Directory.CreateDirectory(testSourceChildDirectory);
}
catch
{
}
File.Copy(
_testValidSourceFile1,
Path.Combine(testSourceParentDirectory, Path.GetFileName(_testValidSourceFile1)),
true);
File.Copy(
_testValidSourceFile2,
Path.Combine(testSourceParentDirectory, Path.GetFileName(_testValidSourceFile2)),
true);
File.Copy(
_testValidSourceFile1,
Path.Combine(testSourceChildDirectory, Path.GetFileName(_testValidSourceFile1)),
true);
File.Copy(
_testValidSourceFile2,
Path.Combine(testSourceChildDirectory, Path.GetFileName(_testValidSourceFile2)),
true);
TestLogger logger = new TestLogger();
FileArranger fileArranger = new FileArranger(null, logger);
bool success = fileArranger.Arrange(testSourceParentDirectory, null);
string log = logger.ToString();
Assert.IsTrue(success, "Expected directory to be arranged succesfully - " + log);
Assert.IsTrue(
logger.HasMessage(LogLevel.Verbose, "4 files written."),
"Expected 4 files to be written - " + log);
}
finally
{
try
{
Directory.Delete(testSourceParentDirectory, true);
}
catch
{
}
}
}
/// <summary>
/// Tests arranging an empty project file.
/// </summary>
[Test]
public void ArrangeEmptyProjectTest()
{
TestLogger logger = new TestLogger();
FileArranger fileArranger = new FileArranger(null, logger);
string emptyProjectFile = Path.Combine(
Path.GetTempPath(),
Guid.NewGuid().ToString().Replace('-', '_') + ".csproj");
File.WriteAllText(emptyProjectFile, "<Project></Project>");
try
{
bool success = fileArranger.Arrange(emptyProjectFile, null);
Assert.IsTrue(success, "Expected file to be arranged succesfully.");
Assert.IsTrue(
logger.HasPartialMessage(LogLevel.Warning, "does not contain any supported source files"));
}
finally
{
try
{
File.Delete(emptyProjectFile);
}
catch
{
}
}
}
/// <summary>
/// Tests arranging a single source file with an invalid configuration.
/// </summary>
[Test]
public void ArrangeInvalidConfigurationTest()
{
string testConfiguration = Path.GetTempFileName();
File.WriteAllText(testConfiguration, "<xml");
try
{
TestLogger logger = new TestLogger();
FileArranger fileArranger = new FileArranger(testConfiguration, logger);
bool success = fileArranger.Arrange(_testValidSourceFile1, null);
Assert.IsFalse(success, "Expected file to not be arranged succesfully.");
Assert.IsTrue(logger.HasPartialMessage(LogLevel.Error, "Unable to load configuration file"));
}
finally
{
try
{
File.Delete(testConfiguration);
}
catch
{
}
}
}
/// <summary>
/// Tests arranging a single source file with an invalid configuration.
/// </summary>
[Test]
public void ArrangeInvalidExtensionAssemblyTest()
{
string xml =
@"<CodeConfiguration xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema'>
<Handlers>
<ProjectHandler Parser='NArrange.Core.MSBuildProjectParser'>
<ProjectExtensions>
<Extension Name='csproj'/>
</ProjectExtensions>
</ProjectHandler>
<SourceHandler Assembly='NArrange.BlahBlahBlahBlah, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'>
<SourceExtensions>
<Extension Name='cs'/>
</SourceExtensions>
</SourceHandler>
</Handlers>
</CodeConfiguration>";
string testConfiguration = Path.GetTempFileName();
File.WriteAllText(testConfiguration, xml);
try
{
TestLogger logger = new TestLogger();
FileArranger fileArranger = new FileArranger(testConfiguration, logger);
bool success = fileArranger.Arrange(_testValidSourceFile1, null);
Assert.IsFalse(success, "Expected file to not be arranged succesfully.");
Assert.IsTrue(logger.HasPartialMessage(LogLevel.Error, "Unable to load configuration file"));
}
finally
{
try
{
File.Delete(testConfiguration);
}
catch
{
}
}
}
/// <summary>
/// Tests arranging a single source file with an invalid extension.
/// </summary>
[Test]
public void ArrangeInvalidExtensionTest()
{
TestLogger logger = new TestLogger();
FileArranger fileArranger = new FileArranger(null, logger);
bool success = fileArranger.Arrange(_testInvalidExtensionFile, null);
Assert.IsFalse(success, "Expected file to not be arranged succesfully.");
Assert.IsTrue(logger.HasPartialMessage(LogLevel.Warning, "No assembly is registered to handle file"));
}
/// <summary>
/// Tests arranging a single invalid source file.
/// </summary>
[Test]
public void ArrangeInvalidSourceFileTest()
{
TestLogger logger = new TestLogger();
FileArranger fileArranger = new FileArranger(null, logger);
bool success = fileArranger.Arrange(_testInvalidSourceFile, null);
Assert.IsFalse(success, "Expected file to not be arranged succesfully.");
Assert.IsTrue(logger.HasMessage(LogLevel.Verbose, "0 files written."));
}
/// <summary>
/// Tests arranging a single source file with an invalid configuration.
/// </summary>
[Test]
public void ArrangeNonExistantConfigurationTest()
{
TestLogger logger = new TestLogger();
FileArranger fileArranger = new FileArranger("blahblahblahblah.xml", logger);
bool success = fileArranger.Arrange(_testValidSourceFile1, null);
Assert.IsFalse(success, "Expected file to not be arranged succesfully.");
Assert.IsTrue(logger.HasPartialMessage(LogLevel.Error, "Unable to load configuration file"));
}
/// <summary>
/// Tests arranging a project file that is excluded in the configuration.
/// </summary>
[Test]
public void ArrangeProjectFilteredTest()
{
CodeConfiguration filterProjectConfig = CodeConfiguration.Default.Clone() as CodeConfiguration;
// Set up the filter
FilterBy filter = new FilterBy();
filter.Condition = "!($(File.Path) : '.Filtered.')";
((ProjectHandlerConfiguration)filterProjectConfig.Handlers[0]).ProjectExtensions[0].FilterBy = filter;
string filterProjectConfigFile = Path.Combine(Path.GetTempPath(), "FilterProjectConfig.xml");
try
{
filterProjectConfig.Save(filterProjectConfigFile);
TestLogger logger = new TestLogger();
FileArranger fileArranger = new FileArranger(filterProjectConfigFile, logger);
bool success = fileArranger.Arrange(_testFilteredProjectFile, null);
Assert.IsTrue(success, "Expected file to be arranged succesfully.");
Assert.IsTrue(
logger.HasMessage(LogLevel.Verbose, "0 files written."),
"Expected 0 files to be written - " + logger.ToString());
}
finally
{
try
{
File.Delete(filterProjectConfigFile);
}
catch
{
}
}
}
/// <summary>
/// Tests arranging a project file.
/// </summary>
[Test]
public void ArrangeProjectTest()
{
TestLogger logger = new TestLogger();
FileArranger fileArranger = new FileArranger(null, logger);
bool success = fileArranger.Arrange(_testProjectFile, null);
Assert.IsTrue(success, "Expected file to be arranged succesfully.");
Assert.IsTrue(
logger.HasMessage(LogLevel.Verbose, "2 files written."),
"Expected 2 files to be written - " + logger.ToString());
}
/// <summary>
/// Tests arranging a read-only source file.
/// </summary>
[Test]
public void ArrangeReadOnlySourceFileTest()
{
TestLogger logger = new TestLogger();
FileArranger fileArranger = new FileArranger(null, logger);
File.SetAttributes(_testValidSourceFile1, FileAttributes.ReadOnly);
try
{
bool success = fileArranger.Arrange(_testValidSourceFile1, null);
Assert.IsFalse(success, "Expected file to not be arranged succesfully.");
Assert.IsTrue(logger.HasMessage(LogLevel.Verbose, "0 files written."));
}
finally
{
File.SetAttributes(_testValidSourceFile1, FileAttributes.Normal);
}
}
/// <summary>
/// Tests arranging a single source file.
/// </summary>
[Test]
public void ArrangeSingleSourceFileTest()
{
TestLogger logger = new TestLogger();
FileArranger fileArranger = new FileArranger(null, logger);
bool success = fileArranger.Arrange(_testValidSourceFile1, null);
Assert.IsTrue(success, "Expected file to be arranged succesfully.");
Assert.IsTrue(
logger.HasMessage(LogLevel.Verbose, "1 files written."),
"Expected 1 file to be written. - " + logger.ToString());
}
/// <summary>
/// Tests arranging a solution file.
/// </summary>
[Test]
public void ArrangeSolutionTest()
{
TestLogger logger = new TestLogger();
FileArranger fileArranger = new FileArranger(null, logger);
bool success = fileArranger.Arrange(_testSolutionFile, null);
Assert.IsTrue(success, "Expected file to be arranged succesfully.");
Assert.IsTrue(
logger.HasMessage(LogLevel.Verbose, "2 files written."),
"Expected 2 files to be written. - " + logger.ToString());
}
/// <summary>
/// Tests arranging a UTF8 encoded source file.
/// </summary>
[Test]
public void ArrangeUTF8EncodedSourceFileTest()
{
TestLogger logger = new TestLogger();
FileArranger fileArranger = new FileArranger(null, logger);
bool success = fileArranger.Arrange(_testUTF8File, null);
Assert.IsTrue(success, "Expected file to be arranged succesfully. - " + logger.ToString());
Assert.IsTrue(
logger.HasMessage(LogLevel.Verbose, "1 files written."),
"Expected 1 file to be written. - " + logger.ToString());
string originalContents = GetTestFileContents("UTF8.cs", Encoding.UTF8);
originalContents = originalContents.Replace("#endregion", "#endregion Fields");
Assert.AreEqual(originalContents, File.ReadAllText(_testUTF8File, Encoding.UTF8), "File contents should have been preserved.");
}
/// <summary>
/// Performs test setup.
/// </summary>
[SetUp]
public void TestSetup()
{
Assembly assembly = Assembly.GetExecutingAssembly();
string contents = GetTestFileContents("ClassMembers.cs", Encoding.Default);
_testValidSourceFile1 = Path.Combine(Path.GetTempPath(), "ClassMembers.cs");
File.WriteAllText(_testValidSourceFile1, contents);
contents = GetTestFileContents("ClassMembers.cs", Encoding.Default);
_testValidSourceFile2 = Path.Combine(Path.GetTempPath(), "ClassMembers.cs");
File.WriteAllText(_testValidSourceFile2, contents);
contents = GetTestFileContents("UTF8.cs", Encoding.UTF8);
_testUTF8File = Path.Combine(Path.GetTempPath(), "UTF8.cs");
File.WriteAllText(_testUTF8File, contents, Encoding.UTF8);
_testFilteredFile = Path.Combine(Path.GetTempPath(), "Test.Designer.cs");
File.WriteAllText(_testFilteredFile, "//This file should be excluded\r\n" + contents);
_testProjectFile = Path.Combine(Path.GetTempPath(), "TestProject.csproj");
MSBuildProjectParserTests.WriteTestProject(_testProjectFile);
_testFilteredProjectFile = Path.Combine(Path.GetTempPath(), "Test.Filtered.csproj");
MSBuildProjectParserTests.WriteTestProject(_testFilteredProjectFile);
_testSolutionFile = Path.Combine(Path.GetTempPath(), "TestSolution.sln");
MSBuildSolutionParserTests.WriteTestSolution(_testSolutionFile);
contents = GetTestFileContents("ClassDefinition.cs", Encoding.Default);
_testValidSourceFile2 = Path.Combine(Path.GetTempPath(), "ClassDefinition.cs");
File.WriteAllText(_testValidSourceFile2, contents);
_testInvalidSourceFile = Path.GetTempFileName() + ".cs";
File.WriteAllText(_testInvalidSourceFile, "namespace SampleNamespace\r\n{");
contents = GetTestFileContents("ClassMembers.cs", Encoding.Default);
_testInvalidExtensionFile = Path.GetTempFileName() + ".zzz";
File.WriteAllText(_testInvalidExtensionFile, contents);
}
/// <summary>
/// Performs test fixture cleanup.
/// </summary>
[TearDown]
public void TestTearDown()
{
try
{
if (_testValidSourceFile1 != null)
{
File.Delete(_testValidSourceFile1);
File.Delete(_testInvalidExtensionFile);
File.Delete(_testInvalidSourceFile);
File.Delete(_testValidSourceFile2);
File.Delete(_testProjectFile);
File.Delete(_testSolutionFile);
File.Delete(_testFilteredFile);
File.Delete(_testFilteredProjectFile);
}
}
catch
{
}
}
/// <summary>
/// Gets the test file contents.
/// </summary>
/// <param name="fileName">Name of the file.</param>
/// <param name="encoding">The encoding.</param>
/// <returns>Test file contents as text.</returns>
private static string GetTestFileContents(string fileName, Encoding encoding)
{
string contents = null;
using (Stream stream = CSharpTestFile.GetTestFileStream(fileName))
{
Assert.IsNotNull(stream, "Test stream could not be retrieved.");
StreamReader reader = new StreamReader(stream, encoding);
contents = reader.ReadToEnd();
}
return contents;
}
#endregion Methods
}
}
| |
// 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.Buffers;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using EditorBrowsableAttribute = System.ComponentModel.EditorBrowsableAttribute;
using EditorBrowsableState = System.ComponentModel.EditorBrowsableState;
#if !FEATURE_PORTABLE_SPAN
using Internal.Runtime.CompilerServices;
#endif // FEATURE_PORTABLE_SPAN
namespace System
{
/// <summary>
/// Memory represents a contiguous region of arbitrary memory similar to <see cref="Span{T}"/>.
/// Unlike <see cref="Span{T}"/>, it is not a byref-like type.
/// </summary>
[DebuggerDisplay("{DebuggerDisplay,nq}")]
[DebuggerTypeProxy(typeof(MemoryDebugView<>))]
public readonly struct Memory<T>
{
// NOTE: With the current implementation, Memory<T> and ReadOnlyMemory<T> must have the same layout,
// as code uses Unsafe.As to cast between them.
// The highest order bit of _index is used to discern whether _object is an array/string or an owned memory
// if (_index >> 31) == 1, object _object is an OwnedMemory<T>
// else, object _object is a T[] or a string. It can only be a string if the Memory<T> was created by
// using unsafe / marshaling code to reinterpret a ReadOnlyMemory<char> wrapped around a string as
// a Memory<T>.
private readonly object _object;
private readonly int _index;
private readonly int _length;
private const int RemoveOwnedFlagBitMask = 0x7FFFFFFF;
/// <summary>
/// Creates a new memory over the entirety of the target array.
/// </summary>
/// <param name="array">The target array.</param>
/// <remarks>Returns default when <paramref name="array"/> is null.</remarks>
/// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Memory(T[] array)
{
if (array == null)
{
this = default;
return; // returns default
}
if (default(T) == null && array.GetType() != typeof(T[]))
ThrowHelper.ThrowArrayTypeMismatchException();
_object = array;
_index = 0;
_length = array.Length;
}
/// <summary>
/// Creates a new memory over the portion of the target array beginning
/// at 'start' index and ending at 'end' index (exclusive).
/// </summary>
/// <param name="array">The target array.</param>
/// <param name="start">The index at which to begin the memory.</param>
/// <param name="length">The number of items in the memory.</param>
/// <remarks>Returns default when <paramref name="array"/> is null.</remarks>
/// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> or end index is not in the range (<0 or >=Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Memory(T[] array, int start, int length)
{
if (array == null)
{
if (start != 0 || length != 0)
ThrowHelper.ThrowArgumentOutOfRangeException();
this = default;
return; // returns default
}
if (default(T) == null && array.GetType() != typeof(T[]))
ThrowHelper.ThrowArrayTypeMismatchException();
if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start))
ThrowHelper.ThrowArgumentOutOfRangeException();
_object = array;
_index = start;
_length = length;
}
// Constructor for internal use only.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal Memory(OwnedMemory<T> owner, int index, int length)
{
// No validation performed; caller must provide any necessary validation.
_object = owner;
_index = index | (1 << 31); // Before using _index, check if _index < 0, then 'and' it with RemoveOwnedFlagBitMask
_length = length;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private Memory(object obj, int index, int length)
{
// No validation performed; caller must provide any necessary validation.
_object = obj;
_index = index;
_length = length;
}
/// <summary>
/// Defines an implicit conversion of an array to a <see cref="Memory{T}"/>
/// </summary>
public static implicit operator Memory<T>(T[] array) => new Memory<T>(array);
/// <summary>
/// Defines an implicit conversion of a <see cref="ArraySegment{T}"/> to a <see cref="Memory{T}"/>
/// </summary>
public static implicit operator Memory<T>(ArraySegment<T> arraySegment) => new Memory<T>(arraySegment.Array, arraySegment.Offset, arraySegment.Count);
/// <summary>
/// Defines an implicit conversion of a <see cref="Memory{T}"/> to a <see cref="ReadOnlyMemory{T}"/>
/// </summary>
public static implicit operator ReadOnlyMemory<T>(Memory<T> memory) =>
Unsafe.As<Memory<T>, ReadOnlyMemory<T>>(ref memory);
//Debugger Display = {T[length]}
private string DebuggerDisplay => string.Format("{{{0}[{1}]}}", typeof(T).Name, _length);
/// <summary>
/// Returns an empty <see cref="Memory{T}"/>
/// </summary>
public static Memory<T> Empty => default;
/// <summary>
/// The number of items in the memory.
/// </summary>
public int Length => _length;
/// <summary>
/// Returns true if Length is 0.
/// </summary>
public bool IsEmpty => _length == 0;
/// <summary>
/// Forms a slice out of the given memory, beginning at 'start'.
/// </summary>
/// <param name="start">The index at which to begin this slice.</param>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> index is not in range (<0 or >=Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Memory<T> Slice(int start)
{
if ((uint)start > (uint)_length)
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
}
return new Memory<T>(_object, _index + start, _length - start);
}
/// <summary>
/// Forms a slice out of the given memory, beginning at 'start', of given length
/// </summary>
/// <param name="start">The index at which to begin this slice.</param>
/// <param name="length">The desired length for the slice (exclusive).</param>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> or end index is not in range (<0 or >=Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Memory<T> Slice(int start, int length)
{
if ((uint)start > (uint)_length || (uint)length > (uint)(_length - start))
{
ThrowHelper.ThrowArgumentOutOfRangeException();
}
return new Memory<T>(_object, _index + start, length);
}
/// <summary>
/// Returns a span from the memory.
/// </summary>
public Span<T> Span
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
if (_index < 0)
{
return ((OwnedMemory<T>)_object).Span.Slice(_index & RemoveOwnedFlagBitMask, _length);
}
else if (typeof(T) == typeof(char) && _object is string s)
{
// This is dangerous, returning a writable span for a string that should be immutable.
// However, we need to handle the case where a ReadOnlyMemory<char> was created from a string
// and then cast to a Memory<T>. Such a cast can only be done with unsafe or marshaling code,
// in which case that's the dangerous operation performed by the dev, and we're just following
// suit here to make it work as best as possible.
#if FEATURE_PORTABLE_SPAN
return new Span<T>(Unsafe.As<Pinnable<T>>(s), MemoryExtensions.StringAdjustment, s.Length).Slice(_index, _length);
#else
return new Span<T>(ref Unsafe.As<char, T>(ref s.GetRawStringData()), s.Length).Slice(_index, _length);
#endif // FEATURE_PORTABLE_SPAN
}
else if (_object != null)
{
return new Span<T>((T[])_object, _index, _length);
}
else
{
return default;
}
}
}
/// <summary>
/// Copies the contents of the memory into the destination. If the source
/// and destination overlap, this method behaves as if the original values are in
/// a temporary location before the destination is overwritten.
///
/// <param name="destination">The Memory to copy items into.</param>
/// <exception cref="System.ArgumentException">
/// Thrown when the destination is shorter than the source.
/// </exception>
/// </summary>
public void CopyTo(Memory<T> destination) => Span.CopyTo(destination.Span);
/// <summary>
/// Copies the contents of the memory into the destination. If the source
/// and destination overlap, this method behaves as if the original values are in
/// a temporary location before the destination is overwritten.
///
/// <returns>If the destination is shorter than the source, this method
/// return false and no data is written to the destination.</returns>
/// </summary>
/// <param name="destination">The span to copy items into.</param>
public bool TryCopyTo(Memory<T> destination) => Span.TryCopyTo(destination.Span);
/// <summary>
/// Returns a handle for the array.
/// <param name="pin">If pin is true, the GC will not move the array and hence its address can be taken</param>
/// </summary>
public unsafe MemoryHandle Retain(bool pin = false)
{
MemoryHandle memoryHandle = default;
if (pin)
{
if (_index < 0)
{
memoryHandle = ((OwnedMemory<T>)_object).Pin((_index & RemoveOwnedFlagBitMask) * Unsafe.SizeOf<T>());
}
else if (typeof(T) == typeof(char) && _object is string s)
{
// This case can only happen if a ReadOnlyMemory<char> was created around a string
// and then that was cast to a Memory<char> using unsafe / marshaling code. This needs
// to work, however, so that code that uses a single Memory<char> field to store either
// a readable ReadOnlyMemory<char> or a writable Memory<char> can still be pinned and
// used for interop purposes.
GCHandle handle = GCHandle.Alloc(s, GCHandleType.Pinned);
#if FEATURE_PORTABLE_SPAN
void* pointer = Unsafe.Add<T>((void*)handle.AddrOfPinnedObject(), _index);
#else
void* pointer = Unsafe.Add<T>(Unsafe.AsPointer(ref s.GetRawStringData()), _index);
#endif // FEATURE_PORTABLE_SPAN
memoryHandle = new MemoryHandle(null, pointer, handle);
}
else if (_object is T[] array)
{
var handle = GCHandle.Alloc(array, GCHandleType.Pinned);
#if FEATURE_PORTABLE_SPAN
void* pointer = Unsafe.Add<T>((void*)handle.AddrOfPinnedObject(), _index);
#else
void* pointer = Unsafe.Add<T>(Unsafe.AsPointer(ref array.GetRawSzArrayData()), _index);
#endif // FEATURE_PORTABLE_SPAN
memoryHandle = new MemoryHandle(null, pointer, handle);
}
}
else
{
if (_index < 0)
{
((OwnedMemory<T>)_object).Retain();
memoryHandle = new MemoryHandle((OwnedMemory<T>)_object);
}
}
return memoryHandle;
}
/// <summary>
/// Get an array segment from the underlying memory.
/// If unable to get the array segment, return false with a default array segment.
/// </summary>
public bool TryGetArray(out ArraySegment<T> arraySegment)
{
if (_index < 0)
{
if (((OwnedMemory<T>)_object).TryGetArray(out var segment))
{
arraySegment = new ArraySegment<T>(segment.Array, segment.Offset + (_index & RemoveOwnedFlagBitMask), _length);
return true;
}
}
else if (_object is T[] arr)
{
arraySegment = new ArraySegment<T>(arr, _index, _length);
return true;
}
arraySegment = default(ArraySegment<T>);
return false;
}
/// <summary>
/// Copies the contents from the memory into a new array. This heap
/// allocates, so should generally be avoided, however it is sometimes
/// necessary to bridge the gap with APIs written in terms of arrays.
/// </summary>
public T[] ToArray() => Span.ToArray();
/// <summary>
/// Determines whether the specified object is equal to the current object.
/// Returns true if the object is Memory or ReadOnlyMemory and if both objects point to the same array and have the same length.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object obj)
{
if (obj is ReadOnlyMemory<T>)
{
return ((ReadOnlyMemory<T>)obj).Equals(this);
}
else if (obj is Memory<T> memory)
{
return Equals(memory);
}
else
{
return false;
}
}
/// <summary>
/// Returns true if the memory points to the same array and has the same length. Note that
/// this does *not* check to see if the *contents* are equal.
/// </summary>
public bool Equals(Memory<T> other)
{
return
_object == other._object &&
_index == other._index &&
_length == other._length;
}
/// <summary>
/// Serves as the default hash function.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode()
{
return _object != null ? CombineHashCodes(_object.GetHashCode(), _index.GetHashCode(), _length.GetHashCode()) : 0;
}
private static int CombineHashCodes(int left, int right)
{
return ((left << 5) + left) ^ right;
}
private static int CombineHashCodes(int h1, int h2, int h3)
{
return CombineHashCodes(CombineHashCodes(h1, h2), h3);
}
}
}
| |
namespace HomeCinema.Data.Migrations
{
using HomeCinema.Entities;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
internal sealed class Configuration : DbMigrationsConfiguration<HomeCinemaContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
}
protected override void Seed(HomeCinemaContext context)
{
// create genres
context.GenreSet.AddOrUpdate(g => g.Name, GenerateGenres());
// create movies
context.MovieSet.AddOrUpdate(m => m.Title, GenerateMovies());
//// create stocks
context.StockSet.AddOrUpdate(GenerateStocks());
// create customers
context.CustomerSet.AddOrUpdate(GenerateCustomers());
// create roles
context.RoleSet.AddOrUpdate(r => r.Name, GenerateRoles());
// username: rahul, password: homecinema
context.UserSet.AddOrUpdate(u => u.Email, new User[]{
new User()
{
Email="rahmodi1@yahoo.com",
Username="rahul",
HashedPassword ="XwAQoiq84p1RUzhAyPfaMDKVgSwnn80NCtsE8dNv3XI=",
Salt = "mNKLRbEFCH8y1xIyTXP4qA==",
IsLocked = false,
DateCreated = DateTime.Now
}
});
// // create user-admin for rahul
context.UserRoleSet.AddOrUpdate(new UserRole[] {
new UserRole() {
RoleId = 1, // admin
UserId = 1 // rahul
}
});
}
private Genre[] GenerateGenres()
{
Genre[] genres = new Genre[] {
new Genre() { Name = "Comedy" },
new Genre() { Name = "Sci-fi" },
new Genre() { Name = "Action" },
new Genre() { Name = "Horror" },
new Genre() { Name = "Romance" },
new Genre() { Name = "Comedy" },
new Genre() { Name = "Crime" },
};
return genres;
}
private Movie[] GenerateMovies()
{
Movie[] movies = new Movie[] {
new Movie()
{ Title="Minions",
Image ="minions.jpg",
GenreId = 1,
Director ="Kyle Bald",
Writer="Brian Lynch",
Producer="Janet Healy",
ReleaseDate = new DateTime(2015, 7, 10),
Rating = 3,
Description = "Minions Stuart, Kevin and Bob are recruited by Scarlet Overkill, a super-villain who, alongside her inventor husband Herb, hatches a plot to take over the world.",
TrailerURI = "https://www.youtube.com/watch?v=Wfql_DoHRKc"
},
new Movie()
{ Title="Ted 2",
Image ="ted2.jpg",
GenreId = 1,
Director ="Seth MacFarlane",
Writer="Seth MacFarlane",
Producer="Jason Clark",
ReleaseDate = new DateTime(2015, 6, 27),
Rating = 4,
Description = "Newlywed couple Ted and Tami-Lynn want to have a baby, but in order to qualify to be a parent, Ted will have to prove he's a person in a court of law.",
TrailerURI = "https://www.youtube.com/watch?v=S3AVcCggRnU"
},
new Movie()
{ Title="Trainwreck",
Image ="trainwreck.jpg",
GenreId = 2,
Director ="Judd Apatow",
Writer="Amy Schumer",
Producer="Judd Apatow",
ReleaseDate = new DateTime(2015, 7, 17),
Rating = 5,
Description = "Having thought that monogamy was never possible, a commitment-phobic career woman may have to face her fears when she meets a good guy.",
TrailerURI = "https://www.youtube.com/watch?v=2MxnhBPoIx4"
},
new Movie()
{ Title="Inside Out",
Image ="insideout.jpg",
GenreId = 1,
Director ="Pete Docter",
Writer="Pete Docter",
Producer="John Lasseter",
ReleaseDate = new DateTime(2015, 6, 19),
Rating = 4,
Description = "After young Riley is uprooted from her Midwest life and moved to San Francisco, her emotions - Joy, Fear, Anger, Disgust and Sadness - conflict on how best to navigate a new city, house, and school.",
TrailerURI = "https://www.youtube.com/watch?v=seMwpP0yeu4"
},
new Movie()
{ Title="Home",
Image ="home.jpg",
GenreId = 1,
Director ="Tim Johnson",
Writer="Tom J. Astle",
Producer="Suzanne Buirgy",
ReleaseDate = new DateTime(2015, 5, 27),
Rating = 4,
Description = "Oh, an alien on the run from his own people, lands on Earth and makes friends with the adventurous Tip, who is on a quest of her own.",
TrailerURI = "https://www.youtube.com/watch?v=MyqZf8LiWvM"
},
new Movie()
{ Title="Batman v Superman: Dawn of Justice",
Image ="batmanvssuperman.jpg",
GenreId = 2,
Director ="Zack Snyder",
Writer="Chris Terrio",
Producer="Wesley Coller",
ReleaseDate = new DateTime(2015, 3, 25),
Rating = 4,
Description = "Fearing the actions of a god-like Super Hero left unchecked, Gotham City's own formidable, forceful vigilante takes on Metropolis most revered, modern-day savior, while the world wrestles with what sort of hero it really needs. And with Batman and Superman at war with one another, a new threat quickly arises, putting mankind in greater danger than it's ever known before.",
TrailerURI = "https://www.youtube.com/watch?v=0WWzgGyAH6Y"
},
new Movie()
{ Title="Ant-Man",
Image ="antman.jpg",
GenreId = 2,
Director ="Payton Reed",
Writer="Edgar Wright",
Producer="Victoria Alonso",
ReleaseDate = new DateTime(2015, 7, 17),
Rating = 5,
Description = "Armed with a super-suit with the astonishing ability to shrink in scale but increase in strength, cat burglar Scott Lang must embrace his inner hero and help his mentor, Dr. Hank Pym, plan and pull off a heist that will save the world.",
TrailerURI = "https://www.youtube.com/watch?v=1HpZevFifuo"
},
new Movie()
{ Title="Jurassic World",
Image ="jurassicworld.jpg",
GenreId = 2,
Director ="Colin Trevorrow",
Writer="Rick Jaffa",
Producer="Patrick Crowley",
ReleaseDate = new DateTime(2015, 6, 12),
Rating = 4,
Description = "A new theme park is built on the original site of Jurassic Park. Everything is going well until the park's newest attraction--a genetically modified giant stealth killing machine--escapes containment and goes on a killing spree.",
TrailerURI = "https://www.youtube.com/watch?v=RFinNxS5KN4"
},
new Movie()
{ Title="Fantastic Four",
Image ="fantasticfour.jpg",
GenreId = 2,
Director ="Josh Trank",
Writer="Simon Kinberg",
Producer="Avi Arad",
ReleaseDate = new DateTime(2015, 8, 7),
Rating = 2,
Description = "Four young outsiders teleport to an alternate and dangerous universe which alters their physical form in shocking ways. The four must learn to harness their new abilities and work together to save Earth from a former friend turned enemy.",
TrailerURI = "https://www.youtube.com/watch?v=AAgnQdiZFsQ"
},
new Movie()
{ Title="Mad Max: Fury Road",
Image ="madmax.jpg",
GenreId = 2,
Director ="George Miller",
Writer="George Miller",
Producer="Bruce Berman",
ReleaseDate = new DateTime(2015, 5, 15),
Rating = 3,
Description = "In a stark desert landscape where humanity is broken, two rebels just might be able to restore order: Max, a man of action and of few words, and Furiosa, a woman of action who is looking to make it back to her childhood homeland.",
TrailerURI = "https://www.youtube.com/watch?v=hEJnMQG9ev8"
},
new Movie()
{ Title="True Detective",
Image ="truedetective.jpg",
GenreId = 6,
Director ="Nic Pizzolatto",
Writer="Bill Bannerman",
Producer="Richard Brown",
ReleaseDate = new DateTime(2015, 5, 15),
Rating = 4,
Description = "An anthology series in which police investigations unearth the personal and professional secrets of those involved, both within and outside the law.",
TrailerURI = "https://www.youtube.com/watch?v=TXwCoNwBSkQ"
},
new Movie()
{ Title="The Longest Ride",
Image ="thelongestride.jpg",
GenreId = 5,
Director ="Nic Pizzolatto",
Writer="George Tillman Jr.",
Producer="Marty Bowen",
ReleaseDate = new DateTime(2015, 5, 15),
Rating = 5,
Description = "After an automobile crash, the lives of a young couple intertwine with a much older man, as he reflects back on a past love.",
TrailerURI = "https://www.youtube.com/watch?v=FUS_Q7FsfqU"
},
new Movie()
{ Title="The Walking Dead",
Image ="thewalkingdead.jpg",
GenreId = 4,
Director ="Frank Darabont",
Writer="David Alpert",
Producer="Gale Anne Hurd",
ReleaseDate = new DateTime(2015, 3, 28),
Rating = 5,
Description = "Sheriff's Deputy Rick Grimes leads a group of survivors in a world overrun by zombies.",
TrailerURI = "https://www.youtube.com/watch?v=R1v0uFms68U"
},
new Movie()
{ Title="Southpaw",
Image ="southpaw.jpg",
GenreId = 3,
Director ="Antoine Fuqua",
Writer="Kurt Sutter",
Producer="Todd Black",
ReleaseDate = new DateTime(2015, 8, 17),
Rating = 4,
Description = "Boxer Billy Hope turns to trainer Tick Willis to help him get his life back on track after losing his wife in a tragic accident and his daughter to child protection services.",
TrailerURI = "https://www.youtube.com/watch?v=Mh2ebPxhoLs"
},
new Movie()
{ Title="Specter",
Image ="spectre.jpg",
GenreId = 3,
Director ="Sam Mendes",
Writer="Ian Fleming",
Producer="Zakaria Alaoui",
ReleaseDate = new DateTime(2015, 11, 5),
Rating = 5,
Description = "A cryptic message from Bond's past sends him on a trail to uncover a sinister organization. While M battles political forces to keep the secret service alive, Bond peels back the layers of deceit to reveal the terrible truth behind SPECTRE.",
TrailerURI = "https://www.youtube.com/watch?v=LTDaET-JweU"
},
};
return movies;
}
private Stock[] GenerateStocks()
{
List<Stock> stocks = new List<Stock>();
for (int i = 1; i <= 15; i++)
{
// Three stocks for each movie
for (int j = 0; j < 3; j++)
{
Stock stock = new Stock()
{
MovieId = i,
UniqueKey = Guid.NewGuid(),
IsAvailable = true
};
stocks.Add(stock);
}
}
return stocks.ToArray();
}
private Customer[] GenerateCustomers()
{
List<Customer> _customers = new List<Customer>();
// Create 100 customers
for (int i = 0; i < 100; i++)
{
Customer customer = new Customer()
{
FirstName = MockData.Person.FirstName(),
LastName = MockData.Person.Surname(),
IdentityCard = Guid.NewGuid().ToString(),
UniqueKey = Guid.NewGuid(),
Email = MockData.Internet.Email(),
DateOfBirth = new DateTime(1985, 10, 20).AddMonths(i).AddDays(10),
RegistrationDate = DateTime.Now.AddDays(i),
Mobile = "1234567890"
};
_customers.Add(customer);
}
return _customers.ToArray();
}
private Role[] GenerateRoles()
{
Role[] _roles = new Role[]{
new Role()
{
Name="Admin"
}
};
return _roles;
}
/*private Rental[] GenerateRentals()
{
for (int i = 1; i <= 45; i++)
{
for (int j = 1; j <= 5; j++)
{
Random r = new Random();
int customerId = r.Next(1, 99);
Rental _rental = new Rental()
{
CustomerId = 1,
StockId = 1,
Status = "Returned",
RentalDate = DateTime.Now.AddDays(j),
ReturnedDate = DateTime.Now.AddDays(j + 1)
};
_rentals.Add(_rental);
}
}
//return _rentals.ToArray();
}*/
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using Xunit;
namespace System.Numerics.Matrices.Tests
{
/// <summary>
/// Tests for the Matrix3x2 structure.
/// </summary>
public class Test3x2
{
const int Epsilon = 10;
[Fact]
public void ConstructorValuesAreAccessibleByIndexer()
{
Matrix3x2 matrix3x2;
matrix3x2 = new Matrix3x2();
for (int x = 0; x < matrix3x2.Columns; x++)
{
for (int y = 0; y < matrix3x2.Rows; y++)
{
Assert.Equal(0, matrix3x2[x, y], Epsilon);
}
}
double value = 33.33;
matrix3x2 = new Matrix3x2(value);
for (int x = 0; x < matrix3x2.Columns; x++)
{
for (int y = 0; y < matrix3x2.Rows; y++)
{
Assert.Equal(value, matrix3x2[x, y], Epsilon);
}
}
GenerateFilledMatrixWithValues(out matrix3x2);
for (int y = 0; y < matrix3x2.Rows; y++)
{
for (int x = 0; x < matrix3x2.Columns; x++)
{
Assert.Equal(y * matrix3x2.Columns + x, matrix3x2[x, y], Epsilon);
}
}
}
[Fact]
public void IndexerGetAndSetValuesCorrectly()
{
Matrix3x2 matrix3x2 = new Matrix3x2();
for (int x = 0; x < matrix3x2.Columns; x++)
{
for (int y = 0; y < matrix3x2.Rows; y++)
{
matrix3x2[x, y] = y * matrix3x2.Columns + x;
}
}
for (int y = 0; y < matrix3x2.Rows; y++)
{
for (int x = 0; x < matrix3x2.Columns; x++)
{
Assert.Equal(y * matrix3x2.Columns + x, matrix3x2[x, y], Epsilon);
}
}
}
[Fact]
public void ConstantValuesAreCorrect()
{
Matrix3x2 matrix3x2 = new Matrix3x2();
Assert.Equal(3, matrix3x2.Columns);
Assert.Equal(2, matrix3x2.Rows);
Assert.Equal(Matrix3x2.ColumnCount, matrix3x2.Columns);
Assert.Equal(Matrix3x2.RowCount, matrix3x2.Rows);
}
[Fact]
public void ScalarMultiplicationIsCorrect()
{
Matrix3x2 matrix3x2;
GenerateFilledMatrixWithValues(out matrix3x2);
for (double c = -10; c <= 10; c += 0.5)
{
Matrix3x2 result = matrix3x2 * c;
for (int y = 0; y < matrix3x2.Rows; y++)
{
for (int x = 0; x < matrix3x2.Columns; x++)
{
Assert.Equal(matrix3x2[x, y] * c, result[x, y], Epsilon);
}
}
}
}
[Fact]
public void MemberGetAndSetValuesCorrectly()
{
Matrix3x2 matrix3x2 = new Matrix3x2();
matrix3x2.M11 = 0;
matrix3x2.M21 = 1;
matrix3x2.M31 = 2;
matrix3x2.M12 = 3;
matrix3x2.M22 = 4;
matrix3x2.M32 = 5;
Assert.Equal(0, matrix3x2.M11, Epsilon);
Assert.Equal(1, matrix3x2.M21, Epsilon);
Assert.Equal(2, matrix3x2.M31, Epsilon);
Assert.Equal(3, matrix3x2.M12, Epsilon);
Assert.Equal(4, matrix3x2.M22, Epsilon);
Assert.Equal(5, matrix3x2.M32, Epsilon);
Assert.Equal(matrix3x2[0, 0], matrix3x2.M11, Epsilon);
Assert.Equal(matrix3x2[1, 0], matrix3x2.M21, Epsilon);
Assert.Equal(matrix3x2[2, 0], matrix3x2.M31, Epsilon);
Assert.Equal(matrix3x2[0, 1], matrix3x2.M12, Epsilon);
Assert.Equal(matrix3x2[1, 1], matrix3x2.M22, Epsilon);
Assert.Equal(matrix3x2[2, 1], matrix3x2.M32, Epsilon);
}
[Fact]
public void ColumnAccessorAreCorrect()
{
Matrix3x2 value;
GenerateFilledMatrixWithValues(out value);
Matrix1x2 column1 = value.Column1;
for (int y = 0; y < value.Rows; y++)
{
Assert.Equal(value[0, y], column1[0, y]);
}
Matrix1x2 column2 = value.Column2;
for (int y = 0; y < value.Rows; y++)
{
Assert.Equal(value[1, y], column2[0, y]);
}
}
[Fact]
public void RowAccessorAreCorrect()
{
Matrix3x2 value;
GenerateFilledMatrixWithValues(out value);
Matrix3x1 row1 = value.Row1;
for (int x = 0; x < value.Columns; x++)
{
Assert.Equal(value[x, 0], row1[x, 0]);
}
}
[Fact]
public void HashCodeGenerationWorksCorrectly()
{
HashSet<int> hashCodes = new HashSet<int>();
Matrix3x2 value = new Matrix3x2(1);
for (int i = 2; i <= 100; i++)
{
Assert.True(hashCodes.Add(value.GetHashCode()), "Unique hash code generation failure.");
value *= i;
}
}
[Fact]
public void SimpleAdditionGeneratesCorrectValues()
{
Matrix3x2 value1 = new Matrix3x2(1);
Matrix3x2 value2 = new Matrix3x2(99);
Matrix3x2 result = value1 + value2;
for (int y = 0; y < Matrix3x2.RowCount; y++)
{
for (int x = 0; x < Matrix3x2.ColumnCount; x++)
{
Assert.Equal(1 + 99, result[x, y], Epsilon);
}
}
}
[Fact]
public void SimpleSubtractionGeneratesCorrectValues()
{
Matrix3x2 value1 = new Matrix3x2(100);
Matrix3x2 value2 = new Matrix3x2(1);
Matrix3x2 result = value1 - value2;
for (int y = 0; y < Matrix3x2.RowCount; y++)
{
for (int x = 0; x < Matrix3x2.ColumnCount; x++)
{
Assert.Equal(100 - 1, result[x, y], Epsilon);
}
}
}
[Fact]
public void EqualityOperatorWorksCorrectly()
{
Matrix3x2 value1 = new Matrix3x2(100);
Matrix3x2 value2 = new Matrix3x2(50) * 2;
Assert.Equal(value1, value2);
Assert.True(value1 == value2, "Equality operator failed.");
}
[Fact]
public void AccessorThrowsWhenOutOfBounds()
{
Matrix3x2 matrix3x2 = new Matrix3x2();
Assert.Throws<ArgumentOutOfRangeException>(() => { matrix3x2[-1, 0] = 0; });
Assert.Throws<ArgumentOutOfRangeException>(() => { matrix3x2[0, -1] = 0; });
Assert.Throws<ArgumentOutOfRangeException>(() => { matrix3x2[3, 0] = 0; });
Assert.Throws<ArgumentOutOfRangeException>(() => { matrix3x2[0, 2] = 0; });
}
[Fact]
public void MuliplyByMatrix1x3ProducesMatrix1x2()
{
Matrix3x2 matrix1 = new Matrix3x2(3);
Matrix1x3 matrix2 = new Matrix1x3(2);
Matrix1x2 result = matrix1 * matrix2;
Matrix1x2 expected = new Matrix1x2(18,
18);
Assert.Equal(expected, result);
}
[Fact]
public void MuliplyByMatrix2x3ProducesMatrix2x2()
{
Matrix3x2 matrix1 = new Matrix3x2(3);
Matrix2x3 matrix2 = new Matrix2x3(2);
Matrix2x2 result = matrix1 * matrix2;
Matrix2x2 expected = new Matrix2x2(18, 18,
18, 18);
Assert.Equal(expected, result);
}
[Fact]
public void MuliplyByMatrix3x3ProducesMatrix3x2()
{
Matrix3x2 matrix1 = new Matrix3x2(3);
Matrix3x3 matrix2 = new Matrix3x3(2);
Matrix3x2 result = matrix1 * matrix2;
Matrix3x2 expected = new Matrix3x2(18, 18, 18,
18, 18, 18);
Assert.Equal(expected, result);
}
[Fact]
public void MuliplyByMatrix4x3ProducesMatrix4x2()
{
Matrix3x2 matrix1 = new Matrix3x2(3);
Matrix4x3 matrix2 = new Matrix4x3(2);
Matrix4x2 result = matrix1 * matrix2;
Matrix4x2 expected = new Matrix4x2(18, 18, 18, 18,
18, 18, 18, 18);
Assert.Equal(expected, result);
}
private void GenerateFilledMatrixWithValues(out Matrix3x2 matrix)
{
matrix = new Matrix3x2(0, 1, 2,
3, 4, 5);
}
}
}
| |
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
namespace Jovian.Tools.Support
{
/// <summary>
/// Summary description for rtfFindBar.
/// </summary>
public class rtfFindBar : System.Windows.Forms.UserControl
{
private System.ComponentModel.IContainer components;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.ImageList imgList;
private System.Windows.Forms.Label clkCancel;
private System.Windows.Forms.TextBox txtSearch;
private System.Windows.Forms.Button btnNext;
private System.Windows.Forms.Button btnPrevious;
private System.Windows.Forms.CheckBox chkMatch;
private System.Windows.Forms.Button btnReplace;
JovianEdit Owner;
public rtfFindBar(JovianEdit JE)
{
InitializeComponent();
Owner = JE;
this.Cursor = System.Windows.Forms.Cursors.Default;
Down();
}
public void goodFocus()
{
this.Focus();
txtSearch.Focus();
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(rtfFindBar));
this.txtSearch = new System.Windows.Forms.TextBox();
this.btnNext = new System.Windows.Forms.Button();
this.btnPrevious = new System.Windows.Forms.Button();
this.chkMatch = new System.Windows.Forms.CheckBox();
this.label1 = new System.Windows.Forms.Label();
this.imgList = new System.Windows.Forms.ImageList(this.components);
this.clkCancel = new System.Windows.Forms.Label();
this.btnReplace = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// txtSearch
//
this.txtSearch.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.txtSearch.Location = new System.Drawing.Point(58, 4);
this.txtSearch.Name = "txtSearch";
this.txtSearch.Size = new System.Drawing.Size(176, 20);
this.txtSearch.TabIndex = 1;
this.txtSearch.Text = "";
this.txtSearch.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.txtSearch_KeyPress);
this.txtSearch.TextChanged += new System.EventHandler(this.txtSearch_TextChanged);
//
// btnNext
//
this.btnNext.Cursor = System.Windows.Forms.Cursors.Hand;
this.btnNext.FlatStyle = System.Windows.Forms.FlatStyle.Popup;
this.btnNext.Location = new System.Drawing.Point(238, 4);
this.btnNext.Name = "btnNext";
this.btnNext.Size = new System.Drawing.Size(58, 20);
this.btnNext.TabIndex = 2;
this.btnNext.Text = "Next";
this.btnNext.Click += new System.EventHandler(this.btnNext_Click);
//
// btnPrevious
//
this.btnPrevious.Cursor = System.Windows.Forms.Cursors.Hand;
this.btnPrevious.FlatStyle = System.Windows.Forms.FlatStyle.Popup;
this.btnPrevious.Location = new System.Drawing.Point(300, 4);
this.btnPrevious.Name = "btnPrevious";
this.btnPrevious.Size = new System.Drawing.Size(64, 20);
this.btnPrevious.TabIndex = 3;
this.btnPrevious.Text = "Previous";
this.btnPrevious.Click += new System.EventHandler(this.btnPrevious_Click);
//
// chkMatch
//
this.chkMatch.Location = new System.Drawing.Point(368, 2);
this.chkMatch.Name = "chkMatch";
this.chkMatch.Size = new System.Drawing.Size(90, 24);
this.chkMatch.TabIndex = 4;
this.chkMatch.Text = "Match case";
this.chkMatch.CheckedChanged += new System.EventHandler(this.chkMatch_CheckedChanged);
//
// label1
//
this.label1.Location = new System.Drawing.Point(26, 6);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(30, 20);
this.label1.TabIndex = 6;
this.label1.Text = "Find:";
//
// imgList
//
this.imgList.ImageSize = new System.Drawing.Size(16, 16);
this.imgList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imgList.ImageStream")));
this.imgList.TransparentColor = System.Drawing.Color.Olive;
//
// clkCancel
//
this.clkCancel.Cursor = System.Windows.Forms.Cursors.Hand;
this.clkCancel.ImageIndex = 0;
this.clkCancel.ImageList = this.imgList;
this.clkCancel.Location = new System.Drawing.Point(4, 4);
this.clkCancel.Name = "clkCancel";
this.clkCancel.Size = new System.Drawing.Size(18, 16);
this.clkCancel.TabIndex = 7;
this.clkCancel.Click += new System.EventHandler(this.clkCancel_Click);
this.clkCancel.MouseEnter += new System.EventHandler(this.clkCancel_MouseEnter);
this.clkCancel.MouseLeave += new System.EventHandler(this.clkCancel_MouseLeave);
//
// btnReplace
//
this.btnReplace.Cursor = System.Windows.Forms.Cursors.Hand;
this.btnReplace.FlatStyle = System.Windows.Forms.FlatStyle.Popup;
this.btnReplace.Location = new System.Drawing.Point(450, 4);
this.btnReplace.Name = "btnReplace";
this.btnReplace.Size = new System.Drawing.Size(106, 20);
this.btnReplace.TabIndex = 8;
this.btnReplace.Text = "Replace + Filter";
this.btnReplace.Click += new System.EventHandler(this.btnReplace_Click);
//
// rtfFindBar
//
this.Controls.Add(this.btnReplace);
this.Controls.Add(this.clkCancel);
this.Controls.Add(this.label1);
this.Controls.Add(this.chkMatch);
this.Controls.Add(this.btnPrevious);
this.Controls.Add(this.btnNext);
this.Controls.Add(this.txtSearch);
this.Name = "rtfFindBar";
this.Size = new System.Drawing.Size(606, 28);
this.ResumeLayout(false);
}
#endregion
private void clkCancel_MouseEnter(object sender, System.EventArgs e)
{
clkCancel.ImageIndex = 1;
}
private void clkCancel_MouseLeave(object sender, System.EventArgs e)
{
clkCancel.ImageIndex = 0;
}
private void clkCancel_Click(object sender, System.EventArgs e)
{
Owner.KillFindBar();
}
private void txtSearch_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
if(!Owner.Focused)
{
if(e.KeyChar < 32)
{
// MessageBox.Show("" + (int)e.KeyChar);
}
if(e.KeyChar == 18)
{
e.Handled = true;
btnReplace_Click(null,null);
}
if(e.KeyChar == 6)
{
e.Handled = true;
Owner.KillFindBar();
}
if(e.KeyChar == 16)
{
e.Handled = true;
Owner.ExecuteSearchPrev();
}
if(e.KeyChar == 14)
{
e.Handled = true;
Owner.ExecuteSearchNext();
}
if(e.KeyChar == 3)
{
e.Handled = true;
chkMatch.Checked = ! chkMatch.Checked;
}
if(e.KeyChar == 13)
{
e.Handled = true;
Owner.ExecuteSearchNext();
}
}
}
private void Down()
{
txtSearch.Text = Owner.GetKey().KeyWord;
chkMatch.Checked = Owner.GetKey().MatchCase;
}
private void Exec()
{
int num = Owner.ExecuteSearch();
if(num > 0)
{
txtSearch.BackColor = Color.White;
}
else
{
txtSearch.BackColor = Color.Red;
}
}
private void txtSearch_TextChanged(object sender, System.EventArgs e)
{
string old = Owner.GetKey().KeyWord;
Owner.GetKey().KeyWord = txtSearch.Text;
if(!old.Equals(Owner.GetKey().KeyWord))
{
Exec();
}
else
{
}
}
private void chkMatch_CheckedChanged(object sender, System.EventArgs e)
{
Owner.GetKey().MatchCase = chkMatch.Checked;
Exec();
}
private void btnReplace_Click(object sender, System.EventArgs e)
{
Owner.InstallReplaceBar();
}
private void btnNext_Click(object sender, System.EventArgs e)
{
Owner.ExecuteSearchNext();
}
private void btnPrevious_Click(object sender, System.EventArgs e)
{
Owner.ExecuteSearchPrev();
}
}
}
| |
//
// 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.UnitTests.Layouts
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using NUnit.Framework;
#if !NUNIT
using SetUp = Microsoft.VisualStudio.TestTools.UnitTesting.TestInitializeAttribute;
using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute;
using TearDown = Microsoft.VisualStudio.TestTools.UnitTesting.TestCleanupAttribute;
#endif
using NLog.Layouts;
[TestFixture]
public class CsvLayoutTests : NLogTestBase
{
#if !SILVERLIGHT
[Test]
public void EndToEndTest()
{
try
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='f' type='File' fileName='CSVLayoutEndToEnd1.txt'>
<layout type='CSVLayout'>
<column name='level' layout='${level}' />
<column name='message' layout='${message}' />
<column name='counter' layout='${counter}' />
<delimiter>Comma</delimiter>
</layout>
</target>
</targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='f' />
</rules>
</nlog>");
Logger logger = LogManager.GetLogger("A");
logger.Debug("msg");
logger.Info("msg2");
logger.Warn("Message with, a comma");
using (StreamReader sr = File.OpenText("CSVLayoutEndToEnd1.txt"))
{
Assert.AreEqual("level,message,counter", sr.ReadLine());
Assert.AreEqual("Debug,msg,1", sr.ReadLine());
Assert.AreEqual("Info,msg2,2", sr.ReadLine());
Assert.AreEqual("Warn,\"Message with, a comma\",3", sr.ReadLine());
}
}
finally
{
if (File.Exists("CSVLayoutEndToEnd1.txt"))
{
File.Delete("CSVLayoutEndToEnd1.txt");
}
}
}
[Test]
public void NoHeadersTest()
{
try
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='f' type='File' fileName='CSVLayoutEndToEnd2.txt'>
<layout type='CSVLayout' withHeader='false'>
<delimiter>Comma</delimiter>
<column name='level' layout='${level}' />
<column name='message' layout='${message}' />
<column name='counter' layout='${counter}' />
</layout>
</target>
</targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='f' />
</rules>
</nlog>");
Logger logger = LogManager.GetLogger("A");
logger.Debug("msg");
logger.Info("msg2");
logger.Warn("Message with, a comma");
using (StreamReader sr = File.OpenText("CSVLayoutEndToEnd2.txt"))
{
Assert.AreEqual("Debug,msg,1", sr.ReadLine());
Assert.AreEqual("Info,msg2,2", sr.ReadLine());
Assert.AreEqual("Warn,\"Message with, a comma\",3", sr.ReadLine());
}
}
finally
{
if (File.Exists("CSVLayoutEndToEnd2.txt"))
{
File.Delete("CSVLayoutEndToEnd2.txt");
}
}
}
#endif
[Test]
public void CsvLayoutRenderingNoQuoting()
{
var delimiters = new Dictionary<CsvColumnDelimiterMode, string>
{
{ CsvColumnDelimiterMode.Auto, CultureInfo.CurrentCulture.TextInfo.ListSeparator },
{ CsvColumnDelimiterMode.Comma, "," },
{ CsvColumnDelimiterMode.Semicolon, ";" },
{ CsvColumnDelimiterMode.Space, " " },
{ CsvColumnDelimiterMode.Tab, "\t" },
{ CsvColumnDelimiterMode.Pipe, "|" },
{ CsvColumnDelimiterMode.Custom, "zzz" },
};
foreach (var delim in delimiters)
{
var csvLayout = new CsvLayout()
{
Quoting = CsvQuotingMode.Nothing,
Columns =
{
new CsvColumn("date", "${longdate}"),
new CsvColumn("level", "${level}"),
new CsvColumn("message;text", "${message}"),
},
Delimiter = delim.Key,
CustomColumnDelimiter = "zzz",
};
var ev = new LogEventInfo();
ev.TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56);
ev.Level = LogLevel.Info;
ev.Message = "hello, world";
string sep = delim.Value;
Assert.AreEqual("2010-01-01 12:34:56.0000" + sep + "Info" + sep + "hello, world", csvLayout.Render(ev));
Assert.AreEqual("date" + sep + "level" + sep + "message;text", csvLayout.Header.Render(ev));
}
}
[Test]
public void CsvLayoutRenderingFullQuoting()
{
var delimiters = new Dictionary<CsvColumnDelimiterMode, string>
{
{ CsvColumnDelimiterMode.Auto, CultureInfo.CurrentCulture.TextInfo.ListSeparator },
{ CsvColumnDelimiterMode.Comma, "," },
{ CsvColumnDelimiterMode.Semicolon, ";" },
{ CsvColumnDelimiterMode.Space, " " },
{ CsvColumnDelimiterMode.Tab, "\t" },
{ CsvColumnDelimiterMode.Pipe, "|" },
{ CsvColumnDelimiterMode.Custom, "zzz" },
};
foreach (var delim in delimiters)
{
var csvLayout = new CsvLayout()
{
Quoting = CsvQuotingMode.All,
Columns =
{
new CsvColumn("date", "${longdate}"),
new CsvColumn("level", "${level}"),
new CsvColumn("message;text", "${message}"),
},
QuoteChar = "'",
Delimiter = delim.Key,
CustomColumnDelimiter = "zzz",
};
var ev = new LogEventInfo();
ev.TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56);
ev.Level = LogLevel.Info;
ev.Message = "hello, world";
string sep = delim.Value;
Assert.AreEqual("'2010-01-01 12:34:56.0000'" + sep + "'Info'" + sep + "'hello, world'", csvLayout.Render(ev));
Assert.AreEqual("'date'" + sep + "'level'" + sep + "'message;text'", csvLayout.Header.Render(ev));
}
}
[Test]
public void CsvLayoutRenderingAutoQuoting()
{
var csvLayout = new CsvLayout()
{
Quoting = CsvQuotingMode.Auto,
Columns =
{
new CsvColumn("date", "${longdate}"),
new CsvColumn("level", "${level}"),
new CsvColumn("message;text", "${message}"),
},
QuoteChar = "'",
Delimiter = CsvColumnDelimiterMode.Semicolon,
};
// no quoting
Assert.AreEqual(
"2010-01-01 12:34:56.0000;Info;hello, world",
csvLayout.Render(new LogEventInfo
{
TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56),
Level = LogLevel.Info,
Message = "hello, world"
}));
// multi-line string - requires quoting
Assert.AreEqual(
"2010-01-01 12:34:56.0000;Info;'hello\rworld'",
csvLayout.Render(new LogEventInfo
{
TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56),
Level = LogLevel.Info,
Message = "hello\rworld"
}));
// multi-line string - requires quoting
Assert.AreEqual(
"2010-01-01 12:34:56.0000;Info;'hello\nworld'",
csvLayout.Render(new LogEventInfo
{
TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56),
Level = LogLevel.Info,
Message = "hello\nworld"
}));
// quote character used in string, will be quoted and doubled
Assert.AreEqual(
"2010-01-01 12:34:56.0000;Info;'hello''world'",
csvLayout.Render(new LogEventInfo
{
TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56),
Level = LogLevel.Info,
Message = "hello'world"
}));
Assert.AreEqual("date;level;'message;text'", csvLayout.Header.Render(LogEventInfo.CreateNullEvent()));
}
[Test]
public void CsvLayoutCachingTest()
{
var csvLayout = new CsvLayout()
{
Quoting = CsvQuotingMode.Auto,
Columns =
{
new CsvColumn("date", "${longdate}"),
new CsvColumn("level", "${level}"),
new CsvColumn("message", "${message}"),
},
QuoteChar = "'",
Delimiter = CsvColumnDelimiterMode.Semicolon,
};
var e1 = new LogEventInfo
{
TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56),
Level = LogLevel.Info,
Message = "hello, world"
};
var e2 = new LogEventInfo
{
TimeStamp = new DateTime(2010, 01, 01, 12, 34, 57),
Level = LogLevel.Info,
Message = "hello, world"
};
var r11 = csvLayout.Render(e1);
var r12 = csvLayout.Render(e1);
var r21 = csvLayout.Render(e2);
var r22 = csvLayout.Render(e2);
var h11 = csvLayout.Header.Render(e1);
var h12 = csvLayout.Header.Render(e1);
var h21 = csvLayout.Header.Render(e2);
var h22 = csvLayout.Header.Render(e2);
Assert.AreSame(r11, r12);
Assert.AreSame(r21, r22);
Assert.AreNotSame(r11, r21);
Assert.AreNotSame(r12, r22);
Assert.AreSame(h11, h12);
Assert.AreSame(h21, h22);
Assert.AreNotSame(h11, h21);
Assert.AreNotSame(h12, h22);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Reflection;
using System.Security.Permissions;
using System.Windows.Forms;
using Medo.Text;
using System.ComponentModel;
using System.Threading;
using Summae.HashAlgorithms;
using Medo.Configuration;
namespace Summae {
internal partial class MainForm : Form {
public MainForm(IEnumerable<FileInfo> files) {
InitializeComponent();
this.Font = SystemFonts.MessageBoxFont;
mnu.Renderer = Helper.ToolstripRenderer;
Helper.ScaleToolstrip(mnu);
mnuCalculate.DropDown.Items.Add(new HashMenuItem("crc16", "CRC-16", Config.Read("crc16", false)));
mnuCalculate.DropDown.Items.Add(new HashMenuItem("crc32", "CRC-32", Config.Read("crc32", false)));
mnuCalculate.DropDown.Items.Add(new HashMenuItem("md5", "MD-5", Config.Read("md5", false)));
mnuCalculate.DropDown.Items.Add(new HashMenuItem("ripemd160", "RIPE MD-160", Config.Read("ripemd160", false)));
mnuCalculate.DropDown.Items.Add(new HashMenuItem("sha1", "SHA-1", Config.Read("sha1", true)));
mnuCalculate.DropDown.Items.Add(new HashMenuItem("sha256", "SHA-256", Config.Read("sha256", false)));
mnuCalculate.DropDown.Items.Add(new HashMenuItem("sha384", "SHA-384", Config.Read("sha384", false)));
mnuCalculate.DropDown.Items.Add(new HashMenuItem("sha512", "SHA-512", Config.Read("sha512", false)));
foreach (var file in files) {
AddFileToListView(file.FullName);
}
RefreshEnableDisable();
}
[SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {
switch (keyData) {
case Keys.Alt | Keys.O: {
mnuAppOptions_Click(null, null);
}
return true;
case Keys.Control | Keys.N: {
mnuNew_Click(null, null);
}
return true;
case Keys.Control | Keys.O: {
mnuOpen_Click(null, null);
}
return true;
case Keys.F5: {
mnuCalculate.PerformButtonClick();
}
return true;
default: {
}
return base.ProcessCmdKey(ref msg, keyData);
}
}
private void Form_Load(object sender, EventArgs e) {
Medo.Windows.Forms.State.Load(this, lsvFiles);
mnuOnTop.Checked = Settings.OnTop;
this.TopMost = Settings.OnTop;
}
private void Form_FormClosing(object sender, FormClosingEventArgs e) {
Medo.Windows.Forms.State.Save(this, lsvFiles);
foreach (HashMenuItem iItem in mnuCalculate.DropDown.Items) {
Config.Write(iItem.Key, iItem.Checked);
}
}
private void Form_FormClosed(object sender, FormClosedEventArgs e) {
bwCheckForUpgrade.CancelAsync();
Application.Exit();
}
private void Form_Shown(object sender, EventArgs e) {
var version = Assembly.GetExecutingAssembly().GetName().Version; //don't auto-check for development builds
if ((version.Major != 0) || (version.Minor != 0)) { bwCheckForUpgrade.RunWorkerAsync(); }
}
#region Menu
private void mnuNew_Click(object sender, EventArgs e) {
lsvFiles.Items.Clear();
RefreshEnableDisable();
}
private void mnuOpen_Click(object sender, EventArgs e) {
if (ofd.ShowDialog(this) == System.Windows.Forms.DialogResult.OK) {
lsvFiles.BeginUpdate();
foreach (var iFileName in ofd.FileNames) {
AddFileToListView(iFileName);
}
lsvFiles.EndUpdate();
RefreshEnableDisable();
}
}
private void AddFileToListView(string fileName) {
var file = new FileInfo(fileName);
foreach (ListViewItem iItem in lsvFiles.Items) {
string otherFileName = ((FileInfo)iItem.Tag).FullName;
if (string.Compare(fileName, otherFileName, StringComparison.OrdinalIgnoreCase) == 0) {
iItem.Focused = true;
iItem.Selected = true;
return;
}
}
var lvi = new ListViewItem {
Tag = file,
Text = file.Name
};
lvi.SubItems.Add(file.DirectoryName);
lsvFiles.Items.Add(lvi);
lvi.Selected = true;
lvi.Focused = true;
}
private void mnuCalculate_ButtonClick(object sender, EventArgs e) {
if (lsvFiles.Items.Count > 0) {
try {
this.Cursor = Cursors.WaitCursor;
var hashMethods = new List<string>();
foreach (HashMenuItem item in mnuCalculate.DropDown.Items) {
if (item.Checked) { hashMethods.Add(item.Key); }
}
foreach (ListViewItem iItem in lsvFiles.Items) {
var file = (FileInfo)iItem.Tag;
var items = new List<SumItem>();
foreach (var method in hashMethods) {
var item = new SumItem(SumAlgorithmBase.GetAlgorithmByName(method));
item.ExpectedResult = SumItem.GetExpectedResult(file, item.Algorithm);
items.Add(item);
}
var form = new CalculateForm(file, items.AsReadOnly()) {
Owner = this
};
form.Show();
}
lsvFiles.Items.Clear();
} finally {
this.Cursor = Cursors.Default;
}
}
}
private void mnuOnTop_Click(object sender, EventArgs e) {
this.TopMost = mnuOnTop.Checked;
Settings.OnTop = this.TopMost;
}
private void mnuAppOptions_Click(object sender, EventArgs e) {
using (var form = new SettingsForm()) {
form.ShowDialog(this);
}
}
private void mnuAppFeedback_Click(object sender, EventArgs e) {
Medo.Diagnostics.ErrorReport.ShowDialog(this, null, new Uri("https://medo64.com/feedback/"));
}
private void mnuAppUpgrade_Click(object sender, EventArgs e) {
Medo.Services.Upgrade.ShowDialog(this, new Uri("https://medo64.com/upgrade/"));
}
private void mnuAppAbout_Click(object sender, EventArgs e) {
Medo.Windows.Forms.AboutBox.ShowDialog(this, new Uri("https://www.medo64.com/summae/"));
}
#endregion
private void RefreshEnableDisable() {
var state = (lsvFiles.Items.Count > 0);
if (mnuCalculate.Enabled != state) { mnuCalculate.Enabled = state; }
}
private void lsvFiles_KeyDown(object sender, KeyEventArgs e) {
switch (e.KeyData) {
case Keys.Insert: {
e.SuppressKeyPress = true;
mnuOpen_Click(sender, null);
}
break;
case Keys.Delete: {
e.SuppressKeyPress = true;
if (lsvFiles.SelectedItems.Count > 0) {
var items = new List<ListViewItem>();
foreach (ListViewItem iItem in lsvFiles.SelectedItems) {
items.Add(iItem);
}
lsvFiles.BeginUpdate();
foreach (var iItem in items) {
lsvFiles.Items.Remove(iItem);
}
if (lsvFiles.FocusedItem != null) { lsvFiles.FocusedItem.Selected = true; }
lsvFiles.EndUpdate();
RefreshEnableDisable();
}
}
break;
}
}
private void lsvFiles_DragEnter(object sender, DragEventArgs e) {
if (e.Data.GetDataPresent("FileDrop")) {
e.Effect = DragDropEffects.Link;
} else {
e.Effect = DragDropEffects.None;
}
}
private void lsvFiles_DragDrop(object sender, DragEventArgs e) {
foreach (var iFormat in e.Data.GetFormats()) {
Debug.WriteLine(iFormat);
}
if (e.Data.GetData("FileDrop") is string[] files) {
lsvFiles.BeginUpdate();
foreach (var iFile in files) {
AddFileToListView(iFile);
}
lsvFiles.EndUpdate();
}
RefreshEnableDisable();
this.Activate();
}
private void bwCheckForUpgrade_DoWork(object sender, DoWorkEventArgs e) {
e.Cancel = true;
var sw = Stopwatch.StartNew();
while (sw.ElapsedMilliseconds < 3000) { //wait for three seconds
Thread.Sleep(100);
if (bwCheckForUpgrade.CancellationPending) { return; }
}
var file = Medo.Services.Upgrade.GetUpgradeFile(new Uri("https://medo64.com/upgrade/"));
if (file != null) {
if (bwCheckForUpgrade.CancellationPending) { return; }
e.Cancel = false;
}
}
private void bwCheckForUpgrade_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) {
if (!e.Cancelled && (e.Error == null)) {
Helper.ScaleToolstripItem(mnuApp, "mnuAppUpgrade");
mnuAppUpgrade.Text = "Upgrade is available";
}
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
function EWCreatorWindow::init( %this )
{
// Just so we can recall this method for testing changes
// without restarting.
if ( isObject( %this.array ) )
%this.array.delete();
%this.array = new ArrayObject();
%this.array.caseSensitive = true;
%this.setListView( true );
%this.beginGroup( "Environment" );
// Removed Prefab as there doesn't really seem to be a point in creating a blank one
//%this.registerMissionObject( "Prefab", "Prefab" );
%this.registerMissionObject( "SkyBox", "Sky Box" );
%this.registerMissionObject( "CloudLayer", "Cloud Layer" );
%this.registerMissionObject( "BasicClouds", "Basic Clouds" );
%this.registerMissionObject( "ScatterSky", "Scatter Sky" );
%this.registerMissionObject( "Sun", "Basic Sun" );
%this.registerMissionObject( "Lightning" );
%this.registerMissionObject( "WaterBlock", "Water Block" );
%this.registerMissionObject( "SFXEmitter", "Sound Emitter" );
%this.registerMissionObject( "Precipitation" );
%this.registerMissionObject( "ParticleEmitterNode", "Particle Emitter" );
%this.registerMissionObject( "VolumetricFog", "Volumetric Fog" );
%this.registerMissionObject( "RibbonNode", "Ribbon" );
// Legacy features. Users should use Ground Cover and the Forest Editor.
//%this.registerMissionObject( "fxShapeReplicator", "Shape Replicator" );
//%this.registerMissionObject( "fxFoliageReplicator", "Foliage Replicator" );
%this.registerMissionObject( "PointLight", "Point Light" );
%this.registerMissionObject( "SpotLight", "Spot Light" );
%this.registerMissionObject( "GroundCover", "Ground Cover" );
%this.registerMissionObject( "TerrainBlock", "Terrain Block" );
%this.registerMissionObject( "GroundPlane", "Ground Plane" );
%this.registerMissionObject( "WaterPlane", "Water Plane" );
%this.registerMissionObject( "PxCloth", "Cloth" );
%this.registerMissionObject( "ForestWindEmitter", "Wind Emitter" );
%this.registerMissionObject( "DustEmitter", "Dust Emitter" );
%this.registerMissionObject( "DustSimulation", "Dust Simulation" );
%this.registerMissionObject( "DustEffecter", "Dust Effecter" );
%this.endGroup();
%this.beginGroup( "Level" );
%this.registerMissionObject( "MissionArea", "Mission Area" );
%this.registerMissionObject( "Path" );
%this.registerMissionObject( "Marker", "Path Node" );
%this.registerMissionObject( "Trigger" );
%this.registerMissionObject( "PhysicalZone", "Physical Zone" );
%this.registerMissionObject( "Camera" );
%this.registerMissionObject( "LevelInfo", "Level Info" );
%this.registerMissionObject( "TimeOfDay", "Time of Day" );
%this.registerMissionObject( "Zone", "Zone" );
%this.registerMissionObject( "Portal", "Zone Portal" );
%this.registerMissionObject( "SpawnSphere", "Player Spawn Sphere", "PlayerDropPoint" );
%this.registerMissionObject( "SpawnSphere", "Observer Spawn Sphere", "ObserverDropPoint" );
%this.registerMissionObject( "SFXSpace", "Sound Space" );
%this.registerMissionObject( "OcclusionVolume", "Occlusion Volume" );
%this.registerMissionObject( "AccumulationVolume", "Accumulation Volume" );
%this.registerMissionObject( "Entity", "Entity" );
%this.endGroup();
%this.beginGroup( "System" );
%this.registerMissionObject( "SimGroup" );
%this.endGroup();
%this.beginGroup( "ExampleObjects" );
%this.registerMissionObject( "RenderObjectExample" );
%this.registerMissionObject( "RenderMeshExample" );
%this.registerMissionObject( "RenderShapeExample" );
%this.endGroup();
}
function EWCreatorWindow::onWake( %this )
{
CreatorTabBook.selectPage( 0 );
CreatorTabBook.onTabSelected( "Scripted" );
}
function EWCreatorWindow::beginGroup( %this, %group )
{
%this.currentGroup = %group;
}
function EWCreatorWindow::endGroup( %this, %group )
{
%this.currentGroup = "";
}
function EWCreatorWindow::getCreateObjectPosition()
{
%focusPoint = LocalClientConnection.getControlObject().getLookAtPoint();
if( %focusPoint $= "" )
return "0 0 0";
else
return getWord( %focusPoint, 1 ) SPC getWord( %focusPoint, 2 ) SPC getWord( %focusPoint, 3 );
}
function EWCreatorWindow::registerMissionObject( %this, %class, %name, %buildfunc, %group )
{
if( !isClass(%class) )
return;
if ( %name $= "" )
%name = %class;
if ( %this.currentGroup !$= "" && %group $= "" )
%group = %this.currentGroup;
if ( %class $= "" || %group $= "" )
{
warn( "EWCreatorWindow::registerMissionObject, invalid parameters!" );
return;
}
%args = new ScriptObject();
%args.val[0] = %class;
%args.val[1] = %name;
%args.val[2] = %buildfunc;
%this.array.push_back( %group, %args );
}
function EWCreatorWindow::getNewObjectGroup( %this )
{
return %this.objectGroup;
}
function EWCreatorWindow::setNewObjectGroup( %this, %group )
{
if( %this.objectGroup )
{
%oldItemId = EditorTree.findItemByObjectId( %this.objectGroup );
if( %oldItemId > 0 )
EditorTree.markItem( %oldItemId, false );
}
%group = %group.getID();
%this.objectGroup = %group;
%itemId = EditorTree.findItemByObjectId( %group );
EditorTree.markItem( %itemId );
}
function EWCreatorWindow::createStatic( %this, %file )
{
if ( !$missionRunning )
return;
if( !isObject(%this.objectGroup) )
%this.setNewObjectGroup( MissionGroup );
%objId = new TSStatic()
{
shapeName = %file;
position = %this.getCreateObjectPosition();
parentGroup = %this.objectGroup;
};
%this.onObjectCreated( %objId );
}
function EWCreatorWindow::createPrefab( %this, %file )
{
if ( !$missionRunning )
return;
if( !isObject(%this.objectGroup) )
%this.setNewObjectGroup( MissionGroup );
%objId = new Prefab()
{
filename = %file;
position = %this.getCreateObjectPosition();
parentGroup = %this.objectGroup;
};
%this.onObjectCreated( %objId );
}
function EWCreatorWindow::createObject( %this, %cmd )
{
if ( !$missionRunning )
return;
if( !isObject(%this.objectGroup) )
%this.setNewObjectGroup( MissionGroup );
pushInstantGroup();
%objId = eval(%cmd);
popInstantGroup();
if( isObject( %objId ) )
%this.onFinishCreateObject( %objId );
return %objId;
}
function EWCreatorWindow::onFinishCreateObject( %this, %objId )
{
%this.objectGroup.add( %objId );
if( %objId.isMemberOfClass( "SceneObject" ) )
{
%objId.position = %this.getCreateObjectPosition();
//flush new position
%objId.setTransform( %objId.getTransform() );
}
%this.onObjectCreated( %objId );
}
function EWCreatorWindow::onObjectCreated( %this, %objId )
{
// Can we submit an undo action?
if ( isObject( %objId ) )
MECreateUndoAction::submit( %objId );
EditorTree.clearSelection();
EWorldEditor.clearSelection();
EWorldEditor.selectObject( %objId );
// When we drop the selection don't store undo
// state for it... the creation deals with it.
EWorldEditor.dropSelection( true );
}
function CreatorTabBook::onTabSelected( %this, %text, %idx )
{
if ( %this.isAwake() )
{
EWCreatorWindow.tab = %text;
EWCreatorWindow.navigate( "" );
}
}
function EWCreatorWindow::navigate( %this, %address )
{
CreatorIconArray.frozen = true;
CreatorIconArray.clear();
CreatorPopupMenu.clear();
if ( %this.tab $= "Scripted" )
{
%category = getWord( %address, 1 );
%dataGroup = "DataBlockGroup";
for ( %i = 0; %i < %dataGroup.getCount(); %i++ )
{
%obj = %dataGroup.getObject(%i);
// echo ("Obj: " @ %obj.getName() @ " - " @ %obj.category );
if ( %obj.category $= "" && %obj.category == 0 )
continue;
// Add category to popup menu if not there already
if ( CreatorPopupMenu.findText( %obj.category ) == -1 )
CreatorPopupMenu.add( %obj.category );
if ( %address $= "" )
{
%ctrl = %this.findIconCtrl( %obj.category );
if ( %ctrl == -1 )
{
%this.addFolderIcon( %obj.category );
}
}
else if ( %address $= %obj.category )
{
%ctrl = %this.findIconCtrl( %obj.getName() );
if ( %ctrl == -1 )
%this.addShapeIcon( %obj );
}
}
}
if ( %this.tab $= "Meshes" )
{
%fullPath = findFirstFileMultiExpr( getFormatExtensions() );
while ( %fullPath !$= "" )
{
if (strstr(%fullPath, "cached.dts") != -1)
{
%fullPath = findNextFileMultiExpr( getFormatExtensions() );
continue;
}
%fullPath = makeRelativePath( %fullPath, getMainDotCSDir() );
%splitPath = strreplace( %fullPath, " ", "_" );
%splitPath = strreplace( %splitPath, "/", " " );
if( getWord(%splitPath, 0) $= "tools" )
{
%fullPath = findNextFileMultiExpr( getFormatExtensions() );
continue;
}
%dirCount = getWordCount( %splitPath ) - 1;
%pathFolders = getWords( %splitPath, 0, %dirCount - 1 );
// Add this file's path (parent folders) to the
// popup menu if it isn't there yet.
%temp = strreplace( %pathFolders, " ", "/" );
%temp = strreplace( %temp, "_", " " );
%r = CreatorPopupMenu.findText( %temp );
if ( %r == -1 )
{
CreatorPopupMenu.add( %temp );
}
// Is this file in the current folder?
if ( stricmp( %pathFolders, %address ) == 0 )
{
%this.addStaticIcon( %fullPath );
}
// Then is this file in a subfolder we need to add
// a folder icon for?
else
{
%wordIdx = 0;
%add = false;
if ( %address $= "" )
{
%add = true;
%wordIdx = 0;
}
else
{
for ( ; %wordIdx < %dirCount; %wordIdx++ )
{
%temp = getWords( %splitPath, 0, %wordIdx );
if ( stricmp( %temp, %address ) == 0 )
{
%add = true;
%wordIdx++;
break;
}
}
}
if ( %add == true )
{
%folder = getWord( %splitPath, %wordIdx );
%ctrl = %this.findIconCtrl( %folder );
if ( %ctrl == -1 )
%this.addFolderIcon( %folder );
}
}
%fullPath = findNextFileMultiExpr( getFormatExtensions() );
}
}
if ( %this.tab $= "Level" )
{
// Add groups to popup menu
%array = %this.array;
%array.sortk();
%count = %array.count();
if ( %count > 0 )
{
%lastGroup = "";
for ( %i = 0; %i < %count; %i++ )
{
%group = %array.getKey( %i );
if ( %group !$= %lastGroup )
{
CreatorPopupMenu.add( %group );
if ( %address $= "" )
%this.addFolderIcon( %group );
}
if ( %address $= %group )
{
%args = %array.getValue( %i );
%class = %args.val[0];
%name = %args.val[1];
%func = %args.val[2];
%this.addMissionObjectIcon( %class, %name, %func );
}
%lastGroup = %group;
}
}
}
if ( %this.tab $= "Prefabs" )
{
%expr = "*.prefab";
%fullPath = findFirstFile( %expr );
while ( %fullPath !$= "" )
{
%fullPath = makeRelativePath( %fullPath, getMainDotCSDir() );
%splitPath = strreplace( %fullPath, " ", "_" );
%splitPath = strreplace( %splitPath, "/", " " );
if( getWord(%splitPath, 0) $= "tools" )
{
%fullPath = findNextFile( %expr );
continue;
}
%dirCount = getWordCount( %splitPath ) - 1;
%pathFolders = getWords( %splitPath, 0, %dirCount - 1 );
// Add this file's path (parent folders) to the
// popup menu if it isn't there yet.
%temp = strreplace( %pathFolders, " ", "/" );
%temp = strreplace( %temp, "_", " " );
%r = CreatorPopupMenu.findText( %temp );
if ( %r == -1 )
{
CreatorPopupMenu.add( %temp );
}
// Is this file in the current folder?
if ( (%dirCount == 0 && %address $= "") || stricmp( %pathFolders, %address ) == 0 )
{
%this.addPrefabIcon( %fullPath );
}
// Then is this file in a subfolder we need to add
// a folder icon for?
else
{
%wordIdx = 0;
%add = false;
if ( %address $= "" )
{
%add = true;
%wordIdx = 0;
}
else
{
for ( ; %wordIdx < %dirCount; %wordIdx++ )
{
%temp = getWords( %splitPath, 0, %wordIdx );
if ( stricmp( %temp, %address ) == 0 )
{
%add = true;
%wordIdx++;
break;
}
}
}
if ( %add == true )
{
%folder = getWord( %splitPath, %wordIdx );
%ctrl = %this.findIconCtrl( %folder );
if ( %ctrl == -1 )
%this.addFolderIcon( %folder );
}
}
%fullPath = findNextFile( %expr );
}
}
CreatorIconArray.sort( "alphaIconCompare" );
for ( %i = 0; %i < CreatorIconArray.getCount(); %i++ )
{
CreatorIconArray.getObject(%i).autoSize = false;
}
CreatorIconArray.frozen = false;
CreatorIconArray.refresh();
// Recalculate the array for the parent guiScrollCtrl
CreatorIconArray.getParent().computeSizes();
%this.address = %address;
CreatorPopupMenu.sort();
%str = strreplace( %address, " ", "/" );
%r = CreatorPopupMenu.findText( %str );
if ( %r != -1 )
CreatorPopupMenu.setSelected( %r, false );
else
CreatorPopupMenu.setText( %str );
CreatorPopupMenu.tooltip = %str;
}
function EWCreatorWindow::navigateDown( %this, %folder )
{
if ( %this.address $= "" )
%address = %folder;
else
%address = %this.address SPC %folder;
// Because this is called from an IconButton::onClick command
// we have to wait a tick before actually calling navigate, else
// we would delete the button out from under itself.
%this.schedule( 1, "navigate", %address );
}
function EWCreatorWindow::navigateUp( %this )
{
%count = getWordCount( %this.address );
if ( %count == 0 )
return;
if ( %count == 1 )
%address = "";
else
%address = getWords( %this.address, 0, %count - 2 );
%this.navigate( %address );
}
function EWCreatorWindow::setListView( %this, %noupdate )
{
//CreatorIconArray.clear();
//CreatorIconArray.setVisible( false );
CreatorIconArray.setVisible( true );
%this.contentCtrl = CreatorIconArray;
%this.isList = true;
if ( %noupdate == true )
%this.navigate( %this.address );
}
//function EWCreatorWindow::setIconView( %this )
//{
//echo( "setIconView" );
//
//CreatorIconStack.clear();
//CreatorIconStack.setVisible( false );
//
//CreatorIconArray.setVisible( true );
//%this.contentCtrl = CreatorIconArray;
//%this.isList = false;
//
//%this.navigate( %this.address );
//}
function EWCreatorWindow::findIconCtrl( %this, %name )
{
for ( %i = 0; %i < %this.contentCtrl.getCount(); %i++ )
{
%ctrl = %this.contentCtrl.getObject( %i );
if ( %ctrl.text $= %name )
return %ctrl;
}
return -1;
}
function EWCreatorWindow::createIcon( %this )
{
%ctrl = new GuiIconButtonCtrl()
{
profile = "GuiCreatorIconButtonProfile";
buttonType = "radioButton";
groupNum = "-1";
};
if ( %this.isList )
{
%ctrl.iconLocation = "Left";
%ctrl.textLocation = "Right";
%ctrl.extent = "348 19";
%ctrl.textMargin = 8;
%ctrl.buttonMargin = "2 2";
%ctrl.autoSize = true;
}
else
{
%ctrl.iconLocation = "Center";
%ctrl.textLocation = "Bottom";
%ctrl.extent = "40 40";
}
return %ctrl;
}
function EWCreatorWindow::addFolderIcon( %this, %text )
{
%ctrl = %this.createIcon();
%ctrl.altCommand = "EWCreatorWindow.navigateDown(\"" @ %text @ "\");";
%ctrl.iconBitmap = "tools/gui/images/folder.png";
%ctrl.text = %text;
%ctrl.tooltip = %text;
%ctrl.class = "CreatorFolderIconBtn";
%ctrl.buttonType = "radioButton";
%ctrl.groupNum = "-1";
%this.contentCtrl.addGuiControl( %ctrl );
}
function EWCreatorWindow::addMissionObjectIcon( %this, %class, %name, %buildfunc )
{
%ctrl = %this.createIcon();
// If we don't find a specific function for building an
// object then fall back to the stock one
%method = "build" @ %buildfunc;
if( !ObjectBuilderGui.isMethod( %method ) )
%method = "build" @ %class;
if( !ObjectBuilderGui.isMethod( %method ) )
%cmd = "return new " @ %class @ "();";
else
%cmd = "ObjectBuilderGui." @ %method @ "();";
%ctrl.altCommand = "ObjectBuilderGui.newObjectCallback = \"EWCreatorWindow.onFinishCreateObject\"; EWCreatorWindow.createObject( \"" @ %cmd @ "\" );";
%ctrl.iconBitmap = EditorIconRegistry::findIconByClassName( %class );
%ctrl.text = %name;
%ctrl.class = "CreatorMissionObjectIconBtn";
%ctrl.tooltip = %class;
%ctrl.buttonType = "radioButton";
%ctrl.groupNum = "-1";
%this.contentCtrl.addGuiControl( %ctrl );
}
function EWCreatorWindow::addShapeIcon( %this, %datablock )
{
%ctrl = %this.createIcon();
%name = %datablock.getName();
%class = %datablock.getClassName();
%cmd = %class @ "::create(" @ %name @ ");";
%shapePath = ( %datablock.shapeFile !$= "" ) ? %datablock.shapeFile : %datablock.shapeName;
%createCmd = "EWCreatorWindow.createObject( \\\"" @ %cmd @ "\\\" );";
%ctrl.altCommand = "ColladaImportDlg.showDialog( \"" @ %shapePath @ "\", \"" @ %createCmd @ "\" );";
%ctrl.iconBitmap = EditorIconRegistry::findIconByClassName( %class );
%ctrl.text = %name;
%ctrl.class = "CreatorShapeIconBtn";
%ctrl.tooltip = %name;
%ctrl.buttonType = "radioButton";
%ctrl.groupNum = "-1";
%this.contentCtrl.addGuiControl( %ctrl );
}
function EWCreatorWindow::addStaticIcon( %this, %fullPath )
{
%ctrl = %this.createIcon();
%ext = fileExt( %fullPath );
%file = fileBase( %fullPath );
%fileLong = %file @ %ext;
%tip = %fileLong NL
"Size: " @ fileSize( %fullPath ) / 1000.0 SPC "KB" NL
"Date Created: " @ fileCreatedTime( %fullPath ) NL
"Last Modified: " @ fileModifiedTime( %fullPath );
%createCmd = "EWCreatorWindow.createStatic( \\\"" @ %fullPath @ "\\\" );";
%ctrl.altCommand = "ColladaImportDlg.showDialog( \"" @ %fullPath @ "\", \"" @ %createCmd @ "\" );";
%ctrl.iconBitmap = ( ( %ext $= ".dts" ) ? EditorIconRegistry::findIconByClassName( "TSStatic" ) : "tools/gui/images/iconCollada" );
%ctrl.text = %file;
%ctrl.class = "CreatorStaticIconBtn";
%ctrl.tooltip = %tip;
%ctrl.buttonType = "radioButton";
%ctrl.groupNum = "-1";
%this.contentCtrl.addGuiControl( %ctrl );
}
function EWCreatorWindow::addPrefabIcon( %this, %fullPath )
{
%ctrl = %this.createIcon();
%ext = fileExt( %fullPath );
%file = fileBase( %fullPath );
%fileLong = %file @ %ext;
%tip = %fileLong NL
"Size: " @ fileSize( %fullPath ) / 1000.0 SPC "KB" NL
"Date Created: " @ fileCreatedTime( %fullPath ) NL
"Last Modified: " @ fileModifiedTime( %fullPath );
%ctrl.altCommand = "EWCreatorWindow.createPrefab( \"" @ %fullPath @ "\" );";
%ctrl.iconBitmap = EditorIconRegistry::findIconByClassName( "Prefab" );
%ctrl.text = %file;
%ctrl.class = "CreatorPrefabIconBtn";
%ctrl.tooltip = %tip;
%ctrl.buttonType = "radioButton";
%ctrl.groupNum = "-1";
%this.contentCtrl.addGuiControl( %ctrl );
}
function CreatorPopupMenu::onSelect( %this, %id, %text )
{
%split = strreplace( %text, "/", " " );
EWCreatorWindow.navigate( %split );
}
function alphaIconCompare( %a, %b )
{
if ( %a.class $= "CreatorFolderIconBtn" )
if ( %b.class !$= "CreatorFolderIconBtn" )
return -1;
if ( %b.class $= "CreatorFolderIconBtn" )
if ( %a.class !$= "CreatorFolderIconBtn" )
return 1;
%result = stricmp( %a.text, %b.text );
return %result;
}
// Generic create object helper for use from the console.
function genericCreateObject( %class )
{
if ( !isClass( %class ) )
{
warn( "createObject( " @ %class @ " ) - Was not a valid class." );
return;
}
%cmd = "return new " @ %class @ "();";
%obj = EWCreatorWindow.createObject( %cmd );
// In case the caller wants it.
return %obj;
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ComponentFactory.Krypton.Toolkit;
using Kemel.Orm.Providers;
using System.Reflection;
using Kemel.Orm.Starter;
using Kemel.Orm.Data;
using Kemel.Orm.DataBase;
using Kemel.Orm.Providers.Oracle;
using Kemel.Orm.Providers.SqlServer;
using Kemel.Orm.DataBase.CodeDom;
namespace Kemel.Tools.Orm
{
public partial class FrmProviderSettings : ComponentFactory.Krypton.Toolkit.KryptonForm
{
public static Languages SelectedLanguage { get; set; }
public static string OrmNameSpace { get; set; }
public static bool NewQuery { get; set; }
public FrmProviderSettings()
{
InitializeComponent();
this.LoadProviders();
this.rdbNewQuery.Checked = NewQuery;
this.rdbOldQuery.Checked = !NewQuery;
}
public List<Type> Providers { get; set; }
private void LoadProviders()
{
Type tp = typeof(Kemel.Orm.Providers.Oracle.OracleProviderMs);
tp = typeof(Kemel.Orm.Providers.Oracle.OracleProviderx32);
tp = typeof(Kemel.Orm.Providers.Oracle.OracleProviderx64);
tp = typeof(Kemel.Orm.Providers.SqlServer.SqlServerProvider);
tp = typeof(Kemel.Orm.Providers.MySQL.MySQLProvider);
tp = typeof(Kemel.Orm.Providers.Postgres.PostgresProvider);
this.Providers = new List<Type>();
Type providerType = typeof(Provider);
this.cboProviderType.ValueMember = "FullName";
this.cboProviderType.DisplayMember = "Name";
foreach (AssemblyName asmName in Assembly.GetExecutingAssembly().GetReferencedAssemblies())
{
FindProviderTypes(providerType, Assembly.Load(asmName).GetExportedTypes());
}
this.cboProviderType.DataSource = this.Providers;
}
private void FindProviderTypes(Type providerType, Type[] types)
{
foreach (Type type in types)
{
if (type.IsSubclassOf(providerType))
{
this.Providers.Add(type);
}
}
}
public OrmStarter GetInstanceOfStarter()
{
new ToolsOrmStarter(cboProviderType.SelectedItem as Type).Initialize();
return Provider.Starter;
}
private void btnTest_Click(object sender, EventArgs e)
{
Provider.Clear();
GetInstanceOfStarter();
Credential credential = Provider.Starter.Credential;
credential.DataSource = txtDataSource.Text;
credential.User = txtLogin.Text;
credential.Password = txtPassword.Text;
if ((cboProviderType.SelectedItem as Type).Name.Contains("Oracle"))
{
credential.DataSource = txtDataSource.Text.Substring(0, txtDataSource.Text.IndexOf("@"));
credential.Catalog = txtDataSource.Text.Substring(txtDataSource.Text.IndexOf("@") + 1);
credential.Port = (txtPort.Text == "" ? 0 : int.Parse(txtPort.Text));
}
else if ((cboProviderType.SelectedItem as Type).Name.Contains("MySQL"))
{
credential.Port = (txtPort.Text == "" ? 0 : int.Parse(txtPort.Text));
}
else if ((cboProviderType.SelectedItem as Type).Name.Contains("Postgres"))
{
credential.Port = (txtPort.Text == "" ? 0 : int.Parse(txtPort.Text));
}
if (Provider.HasProvider)
{
Provider.FirstInstance.ResetConnections();
}
Provider.Create();
OrmConnection connection = Provider.FirstInstance.GetConnection();
try
{
connection.Open();
connection.Close();
lblStatus.Text = "OK";
lblStatus.ForeColor = System.Drawing.Color.Green;
this.ChangeDataBaseControls();
}
catch(Exception expErro)
{
lblStatus.Text = "Error";
lblStatus.ForeColor = System.Drawing.Color.Red;
MessageBox.Show(expErro.Message);
}
}
private void ChangeDataBaseControls()
{
nudConnectionTimeout.Enabled = true;
txtPort.Enabled = true;
btnSave.Enabled = true;
if (!(cboProviderType.SelectedItem as Type).Name.Contains("Oracle"))
{
cboDataBase.Enabled = true;
using (BusinessDataBase objNgDataBase = new BusinessDataBase())
{
cboDataBase.DataSource = objNgDataBase.GetAllDataBase();
}
}
}
private void btnSave_Click(object sender, EventArgs e)
{
Provider.FirstInstance.ResetConnections();
Credential credential = Provider.Starter.Credential;
credential.DataSource = txtDataSource.Text;
credential.User = txtLogin.Text;
credential.Password = txtPassword.Text;
if ((cboProviderType.SelectedItem as Type).Name.Contains("Oracle"))
{
credential.DataSource = txtDataSource.Text.Substring(0, txtDataSource.Text.IndexOf("@"));
credential.Catalog = txtDataSource.Text.Substring(txtDataSource.Text.IndexOf("@") + 1);
credential.Port = (txtPort.Text == "" ? 0 : int.Parse(txtPort.Text));
}
else if ((cboProviderType.SelectedItem as Type).Name.Contains("MySQL"))
{
credential.Catalog = cboDataBase.SelectedItem.ToString();
credential.Port = (txtPort.Text == "" ? 0 : int.Parse(txtPort.Text));
}
else if ((cboProviderType.SelectedItem as Type).Name.Contains("Postgres"))
{
credential.Catalog = cboDataBase.SelectedItem.ToString();
credential.Port = (txtPort.Text == "" ? 0 : int.Parse(txtPort.Text));
}
else
{
credential.Catalog = cboDataBase.SelectedItem.ToString();
}
credential.ConnectionTimeOut = Convert.ToInt32(nudConnectionTimeout.Value);
credential.Port = Convert.ToInt32(txtPort.Text);
credential.AuthenticationMode = AuthenticationMode.SqlUser;
credential.ApplicationName = "Kemel.Framework.Tools";
FrmProviderSettings.SelectedLanguage = (cboLanguage.SelectedIndex == 0) ? Languages.CSharp : Languages.VBNet;
FrmProviderSettings.OrmNameSpace = txtOrmNameSpace.Text;
FrmProviderSettings.NewQuery = rdbNewQuery.Checked;
this.Close();
}
private void cboProviderType_SelectedIndexChanged(object sender, EventArgs e)
{
if ((cboProviderType.SelectedItem as Type).Name.Contains("Oracle"))
{
txtDataSource.Text = "vmsdigiora01@vmsdigiora01";
txtPort.Enabled = true;
txtPort.Text = "1521";
}
else if ((cboProviderType.SelectedItem as Type).Name.Contains("MySQL"))
{
txtPort.Enabled = true;
txtPort.Text = "3306";
}
else if ((cboProviderType.SelectedItem as Type).Name.Contains("Postgres"))
{
txtPort.Enabled = true;
txtPort.Text = "5432";
}
else
{
txtPort.Enabled = false;
}
}
}
}
| |
/*
* 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.
*/
namespace NVelocity.Runtime
{
using System.IO;
using App.Event;
using Commons.Collections;
using Context;
using Directive;
using NVelocity.Util.Introspection;
using Parser.Node;
using Resource;
/// <summary> Interface for internal runtime services that are needed by the
/// various components w/in Velocity. This was taken from the old
/// Runtime singleton, and anything not necessary was removed.
///
/// Currently implemented by RuntimeInstance.
///
/// </summary>
/// <author> <a href="mailto:geirm@optonline.net">Geir Magusson Jr.</a>
/// </author>
/// <version> $Id: RuntimeServices.java 685724 2008-08-13 23:12:12Z nbubna $
/// </version>
public interface IRuntimeServices
{
/// <summary> Return the velocity runtime configuration object.
///
/// </summary>
/// <returns> ExtendedProperties configuration object which houses
/// the velocity runtime properties.
/// </returns>
/// <summary> Allow an external system to set an ExtendedProperties
/// object to use. This is useful where the external
/// system also uses the ExtendedProperties class and
/// the velocity configuration is a subset of
/// parent application's configuration. This is
/// the case with Turbine.
///
/// </summary>
/// <param name="configuration">
/// </param>
ExtendedProperties Configuration
{
get;
set;
}
/// <summary> Returns the configured class introspection/reflection
/// implementation.
/// </summary>
/// <returns> The current Uberspect object.
/// </returns>
IUberspect Uberspect
{
get;
}
/// <summary> Returns a convenient LogMessage instance that wraps the current LogChute.</summary>
/// <returns> A Log object.
/// </returns>
Log.Log Log
{
get;
}
/// <summary> Returns the event handlers for the application.</summary>
/// <returns> The event handlers for the application.
/// </returns>
EventCartridge ApplicationEventCartridge
{
get;
}
/// <summary> Returns the configured method introspection/reflection
/// implementation.
/// </summary>
/// <returns> The configured method introspection/reflection
/// implementation.
/// </returns>
Introspector Introspector
{
get;
}
/// <summary> Returns true if the RuntimeInstance has been successfully initialized.</summary>
/// <returns> True if the RuntimeInstance has been successfully initialized.
/// </returns>
bool Initialized
{
get;
}
/// <summary> This is the primary initialization method in the Velocity
/// Runtime. The systems that are setup/initialized here are
/// as follows:
///
/// <ul>
/// <li>Logging System</li>
/// <li>ResourceManager</li>
/// <li>Parser Pool</li>
/// <li>Global Cache</li>
/// <li>Static Content Include System</li>
/// <li>Velocimacro System</li>
/// </ul>
/// </summary>
/// <throws> Exception </throws>
void Init();
/// <summary> Allows an external system to set a property in
/// the Velocity Runtime.
///
/// </summary>
/// <param name="key">property key
/// </param>
/// <param name="value">property value
/// </param>
void SetProperty(string key, object value);
/// <summary> Add a property to the configuration. If it already
/// exists then the value stated here will be added
/// to the configuration entry. For example, if
///
/// resource.loader = file
///
/// is already present in the configuration and you
///
/// addProperty("resource.loader", "classpath")
///
/// Then you will end up with a Vector like the
/// following:
///
/// ["file", "classpath"]
///
/// </summary>
/// <param name="key">
/// </param>
/// <param name="value">
/// </param>
void AddProperty(string key, object value);
/// <summary> Clear the values pertaining to a particular
/// property.
///
/// </summary>
/// <param name="key">of property to clear
/// </param>
void ClearProperty(string key);
/// <summary> Allows an external caller to Get a property. The calling
/// routine is required to know the type, as this routine
/// will return an Object, as that is what properties can be.
///
/// </summary>
/// <param name="key">property to return
/// </param>
/// <returns> The value.
/// </returns>
object GetProperty(string key);
/// <summary> Initialize the Velocity Runtime with a Properties
/// object.
///
/// </summary>
/// <param name="p">
/// </param>
/// <throws> Exception </throws>
void Init(ExtendedProperties p);
/// <summary> Initialize the Velocity Runtime with the name of
/// ExtendedProperties object.
///
/// </summary>
/// <param name="configurationFile">
/// </param>
/// <throws> Exception </throws>
void Init(string configurationFile);
/// <summary> Wraps the String in a StringReader and passes it off to
/// {@link #parse(Reader,String)}.
/// </summary>
/// <since> 1.6
/// </since>
SimpleNode Parse(string string_Renamed, string templateName);
/// <summary> Parse the input and return the root of
/// AST node structure.
/// <br><br>
/// In the event that it runs out of parsers in the
/// pool, it will create and let them be GC'd
/// dynamically, logging that it has to do that. This
/// is considered an exceptional condition. It is
/// expected that the user will set the
/// PARSER_POOL_SIZE property appropriately for their
/// application. We will revisit this.
///
/// </summary>
/// <param name="reader">inputstream retrieved by a resource loader
/// </param>
/// <param name="templateName">name of the template being parsed
/// </param>
/// <returns> The AST representing the template.
/// </returns>
/// <throws> ParseException </throws>
SimpleNode Parse(TextReader reader, string templateName);
/// <summary> Parse the input and return the root of the AST node structure.
///
/// </summary>
/// <param name="reader">inputstream retrieved by a resource loader
/// </param>
/// <param name="templateName">name of the template being parsed
/// </param>
/// <param name="dumpNamespace">flag to dump the Velocimacro namespace for this template
/// </param>
/// <returns> The AST representing the template.
/// </returns>
/// <throws> ParseException </throws>
SimpleNode Parse(TextReader reader, string templateName, bool dumpNamespace);
/// <summary> Renders the input string using the context into the output writer.
/// To be used when a template is dynamically constructed, or want to use
/// Velocity as a token replacer.
///
/// </summary>
/// <param name="context">context to use in rendering input string
/// </param>
/// <param name="out"> Writer in which to render the output
/// </param>
/// <param name="logTag"> string to be used as the template name for Log
/// messages in case of Error
/// </param>
/// <param name="instring">input string containing the VTL to be rendered
///
/// </param>
/// <returns> true if successful, false otherwise. If false, see
/// Velocity runtime Log
/// </returns>
/// <throws> ParseErrorException The template could not be parsed. </throws>
/// <throws> MethodInvocationException A method on a context object could not be invoked. </throws>
/// <throws> ResourceNotFoundException A referenced resource could not be loaded. </throws>
/// <throws> IOException While rendering to the writer, an I/O problem occured. </throws>
/// <since> Velocity 1.6
/// </since>
bool Evaluate(IContext context, TextWriter out_Renamed, string logTag, string instring);
/// <summary> Renders the input reader using the context into the output writer.
/// To be used when a template is dynamically constructed, or want to
/// use Velocity as a token replacer.
///
/// </summary>
/// <param name="context">context to use in rendering input string
/// </param>
/// <param name="writer"> Writer in which to render the output
/// </param>
/// <param name="logTag"> string to be used as the template name for Log messages
/// in case of Error
/// </param>
/// <param name="reader">Reader containing the VTL to be rendered
///
/// </param>
/// <returns> true if successful, false otherwise. If false, see
/// Velocity runtime Log
/// </returns>
/// <throws> ParseErrorException The template could not be parsed. </throws>
/// <throws> MethodInvocationException A method on a context object could not be invoked. </throws>
/// <throws> ResourceNotFoundException A referenced resource could not be loaded. </throws>
/// <throws> IOException While reading from the reader or rendering to the writer, </throws>
/// <summary> an I/O problem occured.
/// </summary>
/// <since> Velocity 1.6
/// </since>
bool Evaluate(IContext context, TextWriter writer, string logTag, TextReader reader);
/// <summary> Invokes a currently registered Velocimacro with the params provided
/// and places the rendered stream into the writer.
/// <br>
/// Note : currently only accepts args to the VM if they are in the context.
///
/// </summary>
/// <param name="vmName">name of Velocimacro to call
/// </param>
/// <param name="logTag">string to be used for template name in case of Error. if null,
/// the vmName will be used
/// </param>
/// <param name="params">keys for args used to invoke Velocimacro, in java format
/// rather than VTL (eg "foo" or "bar" rather than "$foo" or "$bar")
/// </param>
/// <param name="context">Context object containing data/objects used for rendering.
/// </param>
/// <param name="writer"> Writer for output stream
/// </param>
/// <returns> true if Velocimacro exists and successfully invoked, false otherwise.
/// </returns>
/// <throws> IOException While rendering to the writer, an I/O problem occured. </throws>
/// <since> 1.6
/// </since>
bool InvokeVelocimacro(string vmName, string logTag, string[] params_Renamed, IContext context, TextWriter writer);
/// <summary> Returns a <code>Template</code> from the resource manager.
/// This method assumes that the character encoding of the
/// template is set by the <code>input.encoding</code>
/// property. The default is "ISO-8859-1"
///
/// </summary>
/// <param name="name">The file name of the desired template.
/// </param>
/// <returns> The template.
/// </returns>
/// <throws> ResourceNotFoundException if template not found </throws>
/// <summary> from any available source.
/// </summary>
/// <throws> ParseErrorException if template cannot be parsed due </throws>
/// <summary> to syntax (or other) Error.
/// </summary>
/// <throws> Exception if an Error occurs in template initialization </throws>
Template GetTemplate(string name);
/// <summary> Returns a <code>Template</code> from the resource manager
///
/// </summary>
/// <param name="name">The name of the desired template.
/// </param>
/// <param name="encoding">Character encoding of the template
/// </param>
/// <returns> The template.
/// </returns>
/// <throws> ResourceNotFoundException if template not found </throws>
/// <summary> from any available source.
/// </summary>
/// <throws> ParseErrorException if template cannot be parsed due </throws>
/// <summary> to syntax (or other) Error.
/// </summary>
/// <throws> Exception if an Error occurs in template initialization </throws>
Template GetTemplate(string name, string encoding);
/// <summary> Returns a static content resource from the
/// resource manager. Uses the current value
/// if INPUT_ENCODING as the character encoding.
///
/// </summary>
/// <param name="name">Name of content resource to Get
/// </param>
/// <returns> parsed ContentResource object ready for use
/// </returns>
/// <throws> ResourceNotFoundException if template not found </throws>
/// <summary> from any available source.
/// </summary>
/// <throws> ParseErrorException </throws>
/// <throws> Exception </throws>
ContentResource GetContent(string name);
/// <summary> Returns a static content resource from the
/// resource manager.
///
/// </summary>
/// <param name="name">Name of content resource to Get
/// </param>
/// <param name="encoding">Character encoding to use
/// </param>
/// <returns> parsed ContentResource object ready for use
/// </returns>
/// <throws> ResourceNotFoundException if template not found </throws>
/// <summary> from any available source.
/// </summary>
/// <throws> ParseErrorException </throws>
/// <throws> Exception </throws>
ContentResource GetContent(string name, string encoding);
/// <summary> Determines is a template exists, and returns name of the loader that
/// provides it. This is a slightly less hokey way to support
/// the Velocity.TemplateExists() utility method, which was broken
/// when per-template encoding was introduced. We can revisit this.
///
/// </summary>
/// <param name="resourceName">Name of template or content resource
/// </param>
/// <returns> class name of loader than can provide it
/// </returns>
string GetLoaderNameForResource(string resourceName);
/// <summary> String property accessor method with default to hide the
/// configuration implementation.
///
/// </summary>
/// <param name="key">property key
/// </param>
/// <param name="defaultValue"> default value to return if key not
/// found in resource manager.
/// </param>
/// <returns> String value of key or default
/// </returns>
string GetString(string key, string defaultValue);
/// <summary> Returns the appropriate VelocimacroProxy object if strVMname
/// is a valid current Velocimacro.
///
/// </summary>
/// <param name="vmName"> Name of velocimacro requested
/// </param>
/// <param name="templateName">Name of the namespace.
/// </param>
/// <returns> VelocimacroProxy
/// </returns>
Directive.Directive GetVelocimacro(string vmName, string templateName);
/// <summary> Returns the appropriate VelocimacroProxy object if strVMname
/// is a valid current Velocimacro.
///
/// </summary>
/// <param name="vmName"> Name of velocimacro requested
/// </param>
/// <param name="templateName">Name of the namespace.
/// </param>
/// <param name="renderingTemplate">Name of the template we are currently rendering. This
/// information is needed when VM_PERM_ALLOW_INLINE_REPLACE_GLOBAL setting is true
/// and template contains a macro with the same name as the global macro library.
///
/// </param>
/// <since> Velocity 1.6
///
/// </since>
/// <returns> VelocimacroProxy
/// </returns>
Directive.Directive GetVelocimacro(string vmName, string templateName, string renderingTemplate);
/// <summary> Adds a new Velocimacro. Usually called by Macro only while parsing.
///
/// </summary>
/// <param name="name"> Name of velocimacro
/// </param>
/// <param name="macro"> root AST node of the parsed macro
/// </param>
/// <param name="argArray"> Array of strings, containing the
/// #macro() arguments. the 0th is the name.
/// </param>
/// <param name="sourceTemplate">
/// </param>
/// <since> Velocity 1.6
///
/// </since>
/// <returns> boolean True if added, false if rejected for some
/// reason (either parameters or permission settings)
/// </returns>
bool AddVelocimacro(string name, INode macro, string[] argArray, string sourceTemplate);
/// <summary> Checks to see if a VM exists
///
/// </summary>
/// <param name="vmName"> Name of velocimacro
/// </param>
/// <param name="templateName">
/// </param>
/// <returns> boolean True if VM by that name exists, false if not
/// </returns>
bool IsVelocimacro(string vmName, string templateName);
/// <summary> tells the vmFactory to dump the specified namespace. This is to support
/// clearing the VM list when in inline-VM-local-scope mode
/// </summary>
/// <param name="namespace">
/// </param>
/// <returns> True if the Namespace was dumped.
/// </returns>
bool DumpVMNamespace(string namespace_Renamed);
/// <summary> String property accessor method to hide the configuration implementation</summary>
/// <param name="key"> property key
/// </param>
/// <returns> value of key or null
/// </returns>
string GetString(string key);
/// <summary> Int property accessor method to hide the configuration implementation.
///
/// </summary>
/// <param name="key">property key
/// </param>
/// <returns> int value
/// </returns>
int GetInt(string key);
/// <summary> Int property accessor method to hide the configuration implementation.
///
/// </summary>
/// <param name="key"> property key
/// </param>
/// <param name="defaultValue">default value
/// </param>
/// <returns> int value
/// </returns>
int GetInt(string key, int defaultValue);
/// <summary> Boolean property accessor method to hide the configuration implementation.
///
/// </summary>
/// <param name="key"> property key
/// </param>
/// <param name="def">default default value if property not found
/// </param>
/// <returns> boolean value of key or default value
/// </returns>
bool GetBoolean(string key, bool def);
/// <summary> Return the specified application attribute.
///
/// </summary>
/// <param name="key">The name of the attribute to retrieve.
/// </param>
/// <returns> The value of the attribute.
/// </returns>
object GetApplicationAttribute(object key);
/// <summary> Set the specified application attribute.
///
/// </summary>
/// <param name="key">The name of the attribute to set.
/// </param>
/// <param name="value">The attribute value to set.
/// </param>
/// <returns> the displaced attribute value
/// </returns>
object SetApplicationAttribute(object key, object value);
/// <summary> Create a new parser instance.</summary>
/// <returns> A new parser instance.
/// </returns>
Parser.Parser CreateNewParser();
/// <summary> Retrieve a previously instantiated directive.</summary>
/// <param name="name">name of the directive
/// </param>
/// <returns> the directive with that name, if any
/// </returns>
/// <since> 1.6
/// </since>
Directive.Directive GetDirective(string name);
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/datastore/v1beta3/entity.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Google.Cloud.Datastore.V1Beta3 {
/// <summary>Holder for reflection information generated from google/datastore/v1beta3/entity.proto</summary>
public static partial class EntityReflection {
#region Descriptor
/// <summary>File descriptor for google/datastore/v1beta3/entity.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static EntityReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CiVnb29nbGUvZGF0YXN0b3JlL3YxYmV0YTMvZW50aXR5LnByb3RvEhhnb29n",
"bGUuZGF0YXN0b3JlLnYxYmV0YTMaHGdvb2dsZS9hcGkvYW5ub3RhdGlvbnMu",
"cHJvdG8aHGdvb2dsZS9wcm90b2J1Zi9zdHJ1Y3QucHJvdG8aH2dvb2dsZS9w",
"cm90b2J1Zi90aW1lc3RhbXAucHJvdG8aGGdvb2dsZS90eXBlL2xhdGxuZy5w",
"cm90byI3CgtQYXJ0aXRpb25JZBISCgpwcm9qZWN0X2lkGAIgASgJEhQKDG5h",
"bWVzcGFjZV9pZBgEIAEoCSLBAQoDS2V5EjsKDHBhcnRpdGlvbl9pZBgBIAEo",
"CzIlLmdvb2dsZS5kYXRhc3RvcmUudjFiZXRhMy5QYXJ0aXRpb25JZBI3CgRw",
"YXRoGAIgAygLMikuZ29vZ2xlLmRhdGFzdG9yZS52MWJldGEzLktleS5QYXRo",
"RWxlbWVudBpECgtQYXRoRWxlbWVudBIMCgRraW5kGAEgASgJEgwKAmlkGAIg",
"ASgDSAASDgoEbmFtZRgDIAEoCUgAQgkKB2lkX3R5cGUiPQoKQXJyYXlWYWx1",
"ZRIvCgZ2YWx1ZXMYASADKAsyHy5nb29nbGUuZGF0YXN0b3JlLnYxYmV0YTMu",
"VmFsdWUigAQKBVZhbHVlEjAKCm51bGxfdmFsdWUYCyABKA4yGi5nb29nbGUu",
"cHJvdG9idWYuTnVsbFZhbHVlSAASFwoNYm9vbGVhbl92YWx1ZRgBIAEoCEgA",
"EhcKDWludGVnZXJfdmFsdWUYAiABKANIABIWCgxkb3VibGVfdmFsdWUYAyAB",
"KAFIABI1Cg90aW1lc3RhbXBfdmFsdWUYCiABKAsyGi5nb29nbGUucHJvdG9i",
"dWYuVGltZXN0YW1wSAASMgoJa2V5X3ZhbHVlGAUgASgLMh0uZ29vZ2xlLmRh",
"dGFzdG9yZS52MWJldGEzLktleUgAEhYKDHN0cmluZ192YWx1ZRgRIAEoCUgA",
"EhQKCmJsb2JfdmFsdWUYEiABKAxIABIuCg9nZW9fcG9pbnRfdmFsdWUYCCAB",
"KAsyEy5nb29nbGUudHlwZS5MYXRMbmdIABI4CgxlbnRpdHlfdmFsdWUYBiAB",
"KAsyIC5nb29nbGUuZGF0YXN0b3JlLnYxYmV0YTMuRW50aXR5SAASOwoLYXJy",
"YXlfdmFsdWUYCSABKAsyJC5nb29nbGUuZGF0YXN0b3JlLnYxYmV0YTMuQXJy",
"YXlWYWx1ZUgAEg8KB21lYW5pbmcYDiABKAUSHAoUZXhjbHVkZV9mcm9tX2lu",
"ZGV4ZXMYEyABKAhCDAoKdmFsdWVfdHlwZSLOAQoGRW50aXR5EioKA2tleRgB",
"IAEoCzIdLmdvb2dsZS5kYXRhc3RvcmUudjFiZXRhMy5LZXkSRAoKcHJvcGVy",
"dGllcxgDIAMoCzIwLmdvb2dsZS5kYXRhc3RvcmUudjFiZXRhMy5FbnRpdHku",
"UHJvcGVydGllc0VudHJ5GlIKD1Byb3BlcnRpZXNFbnRyeRILCgNrZXkYASAB",
"KAkSLgoFdmFsdWUYAiABKAsyHy5nb29nbGUuZGF0YXN0b3JlLnYxYmV0YTMu",
"VmFsdWU6AjgBQpEBChxjb20uZ29vZ2xlLmRhdGFzdG9yZS52MWJldGEzQgtF",
"bnRpdHlQcm90b1ABWkFnb29nbGUuZ29sYW5nLm9yZy9nZW5wcm90by9nb29n",
"bGVhcGlzL2RhdGFzdG9yZS92MWJldGEzO2RhdGFzdG9yZaoCHkdvb2dsZS5D",
"bG91ZC5EYXRhc3RvcmUuVjFCZXRhM2IGcHJvdG8z"));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::Google.Api.AnnotationsReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.StructReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.TimestampReflection.Descriptor, global::Google.Type.LatlngReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Datastore.V1Beta3.PartitionId), global::Google.Cloud.Datastore.V1Beta3.PartitionId.Parser, new[]{ "ProjectId", "NamespaceId" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Datastore.V1Beta3.Key), global::Google.Cloud.Datastore.V1Beta3.Key.Parser, new[]{ "PartitionId", "Path" }, null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Datastore.V1Beta3.Key.Types.PathElement), global::Google.Cloud.Datastore.V1Beta3.Key.Types.PathElement.Parser, new[]{ "Kind", "Id", "Name" }, new[]{ "IdType" }, null, null)}),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Datastore.V1Beta3.ArrayValue), global::Google.Cloud.Datastore.V1Beta3.ArrayValue.Parser, new[]{ "Values" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Datastore.V1Beta3.Value), global::Google.Cloud.Datastore.V1Beta3.Value.Parser, new[]{ "NullValue", "BooleanValue", "IntegerValue", "DoubleValue", "TimestampValue", "KeyValue", "StringValue", "BlobValue", "GeoPointValue", "EntityValue", "ArrayValue", "Meaning", "ExcludeFromIndexes" }, new[]{ "ValueType" }, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Datastore.V1Beta3.Entity), global::Google.Cloud.Datastore.V1Beta3.Entity.Parser, new[]{ "Key", "Properties" }, null, null, new pbr::GeneratedClrTypeInfo[] { null, })
}));
}
#endregion
}
#region Messages
/// <summary>
/// A partition ID identifies a grouping of entities. The grouping is always
/// by project and namespace, however the namespace ID may be empty.
///
/// A partition ID contains several dimensions:
/// project ID and namespace ID.
///
/// Partition dimensions:
///
/// - May be `""`.
/// - Must be valid UTF-8 bytes.
/// - Must have values that match regex `[A-Za-z\d\.\-_]{1,100}`
/// If the value of any dimension matches regex `__.*__`, the partition is
/// reserved/read-only.
/// A reserved/read-only partition ID is forbidden in certain documented
/// contexts.
///
/// Foreign partition IDs (in which the project ID does
/// not match the context project ID ) are discouraged.
/// Reads and writes of foreign partition IDs may fail if the project is not in an active state.
/// </summary>
public sealed partial class PartitionId : pb::IMessage<PartitionId> {
private static readonly pb::MessageParser<PartitionId> _parser = new pb::MessageParser<PartitionId>(() => new PartitionId());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<PartitionId> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.Datastore.V1Beta3.EntityReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PartitionId() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PartitionId(PartitionId other) : this() {
projectId_ = other.projectId_;
namespaceId_ = other.namespaceId_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PartitionId Clone() {
return new PartitionId(this);
}
/// <summary>Field number for the "project_id" field.</summary>
public const int ProjectIdFieldNumber = 2;
private string projectId_ = "";
/// <summary>
/// The ID of the project to which the entities belong.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string ProjectId {
get { return projectId_; }
set {
projectId_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "namespace_id" field.</summary>
public const int NamespaceIdFieldNumber = 4;
private string namespaceId_ = "";
/// <summary>
/// If not empty, the ID of the namespace to which the entities belong.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string NamespaceId {
get { return namespaceId_; }
set {
namespaceId_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as PartitionId);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(PartitionId other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (ProjectId != other.ProjectId) return false;
if (NamespaceId != other.NamespaceId) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (ProjectId.Length != 0) hash ^= ProjectId.GetHashCode();
if (NamespaceId.Length != 0) hash ^= NamespaceId.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (ProjectId.Length != 0) {
output.WriteRawTag(18);
output.WriteString(ProjectId);
}
if (NamespaceId.Length != 0) {
output.WriteRawTag(34);
output.WriteString(NamespaceId);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (ProjectId.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(ProjectId);
}
if (NamespaceId.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(NamespaceId);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(PartitionId other) {
if (other == null) {
return;
}
if (other.ProjectId.Length != 0) {
ProjectId = other.ProjectId;
}
if (other.NamespaceId.Length != 0) {
NamespaceId = other.NamespaceId;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 18: {
ProjectId = input.ReadString();
break;
}
case 34: {
NamespaceId = input.ReadString();
break;
}
}
}
}
}
/// <summary>
/// A unique identifier for an entity.
/// If a key's partition ID or any of its path kinds or names are
/// reserved/read-only, the key is reserved/read-only.
/// A reserved/read-only key is forbidden in certain documented contexts.
/// </summary>
public sealed partial class Key : pb::IMessage<Key> {
private static readonly pb::MessageParser<Key> _parser = new pb::MessageParser<Key>(() => new Key());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<Key> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.Datastore.V1Beta3.EntityReflection.Descriptor.MessageTypes[1]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Key() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Key(Key other) : this() {
PartitionId = other.partitionId_ != null ? other.PartitionId.Clone() : null;
path_ = other.path_.Clone();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Key Clone() {
return new Key(this);
}
/// <summary>Field number for the "partition_id" field.</summary>
public const int PartitionIdFieldNumber = 1;
private global::Google.Cloud.Datastore.V1Beta3.PartitionId partitionId_;
/// <summary>
/// Entities are partitioned into subsets, currently identified by a project
/// ID and namespace ID.
/// Queries are scoped to a single partition.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Cloud.Datastore.V1Beta3.PartitionId PartitionId {
get { return partitionId_; }
set {
partitionId_ = value;
}
}
/// <summary>Field number for the "path" field.</summary>
public const int PathFieldNumber = 2;
private static readonly pb::FieldCodec<global::Google.Cloud.Datastore.V1Beta3.Key.Types.PathElement> _repeated_path_codec
= pb::FieldCodec.ForMessage(18, global::Google.Cloud.Datastore.V1Beta3.Key.Types.PathElement.Parser);
private readonly pbc::RepeatedField<global::Google.Cloud.Datastore.V1Beta3.Key.Types.PathElement> path_ = new pbc::RepeatedField<global::Google.Cloud.Datastore.V1Beta3.Key.Types.PathElement>();
/// <summary>
/// The entity path.
/// An entity path consists of one or more elements composed of a kind and a
/// string or numerical identifier, which identify entities. The first
/// element identifies a _root entity_, the second element identifies
/// a _child_ of the root entity, the third element identifies a child of the
/// second entity, and so forth. The entities identified by all prefixes of
/// the path are called the element's _ancestors_.
///
/// An entity path is always fully complete: *all* of the entity's ancestors
/// are required to be in the path along with the entity identifier itself.
/// The only exception is that in some documented cases, the identifier in the
/// last path element (for the entity) itself may be omitted. For example,
/// the last path element of the key of `Mutation.insert` may have no
/// identifier.
///
/// A path can never be empty, and a path can have at most 100 elements.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::Google.Cloud.Datastore.V1Beta3.Key.Types.PathElement> Path {
get { return path_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as Key);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(Key other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(PartitionId, other.PartitionId)) return false;
if(!path_.Equals(other.path_)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (partitionId_ != null) hash ^= PartitionId.GetHashCode();
hash ^= path_.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (partitionId_ != null) {
output.WriteRawTag(10);
output.WriteMessage(PartitionId);
}
path_.WriteTo(output, _repeated_path_codec);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (partitionId_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(PartitionId);
}
size += path_.CalculateSize(_repeated_path_codec);
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(Key other) {
if (other == null) {
return;
}
if (other.partitionId_ != null) {
if (partitionId_ == null) {
partitionId_ = new global::Google.Cloud.Datastore.V1Beta3.PartitionId();
}
PartitionId.MergeFrom(other.PartitionId);
}
path_.Add(other.path_);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
if (partitionId_ == null) {
partitionId_ = new global::Google.Cloud.Datastore.V1Beta3.PartitionId();
}
input.ReadMessage(partitionId_);
break;
}
case 18: {
path_.AddEntriesFrom(input, _repeated_path_codec);
break;
}
}
}
}
#region Nested types
/// <summary>Container for nested types declared in the Key message type.</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static partial class Types {
/// <summary>
/// A (kind, ID/name) pair used to construct a key path.
///
/// If either name or ID is set, the element is complete.
/// If neither is set, the element is incomplete.
/// </summary>
public sealed partial class PathElement : pb::IMessage<PathElement> {
private static readonly pb::MessageParser<PathElement> _parser = new pb::MessageParser<PathElement>(() => new PathElement());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<PathElement> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.Datastore.V1Beta3.Key.Descriptor.NestedTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PathElement() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PathElement(PathElement other) : this() {
kind_ = other.kind_;
switch (other.IdTypeCase) {
case IdTypeOneofCase.Id:
Id = other.Id;
break;
case IdTypeOneofCase.Name:
Name = other.Name;
break;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PathElement Clone() {
return new PathElement(this);
}
/// <summary>Field number for the "kind" field.</summary>
public const int KindFieldNumber = 1;
private string kind_ = "";
/// <summary>
/// The kind of the entity.
/// A kind matching regex `__.*__` is reserved/read-only.
/// A kind must not contain more than 1500 bytes when UTF-8 encoded.
/// Cannot be `""`.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Kind {
get { return kind_; }
set {
kind_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "id" field.</summary>
public const int IdFieldNumber = 2;
/// <summary>
/// The auto-allocated ID of the entity.
/// Never equal to zero. Values less than zero are discouraged and may not
/// be supported in the future.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public long Id {
get { return idTypeCase_ == IdTypeOneofCase.Id ? (long) idType_ : 0L; }
set {
idType_ = value;
idTypeCase_ = IdTypeOneofCase.Id;
}
}
/// <summary>Field number for the "name" field.</summary>
public const int NameFieldNumber = 3;
/// <summary>
/// The name of the entity.
/// A name matching regex `__.*__` is reserved/read-only.
/// A name must not be more than 1500 bytes when UTF-8 encoded.
/// Cannot be `""`.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Name {
get { return idTypeCase_ == IdTypeOneofCase.Name ? (string) idType_ : ""; }
set {
idType_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
idTypeCase_ = IdTypeOneofCase.Name;
}
}
private object idType_;
/// <summary>Enum of possible cases for the "id_type" oneof.</summary>
public enum IdTypeOneofCase {
None = 0,
Id = 2,
Name = 3,
}
private IdTypeOneofCase idTypeCase_ = IdTypeOneofCase.None;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public IdTypeOneofCase IdTypeCase {
get { return idTypeCase_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void ClearIdType() {
idTypeCase_ = IdTypeOneofCase.None;
idType_ = null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as PathElement);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(PathElement other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Kind != other.Kind) return false;
if (Id != other.Id) return false;
if (Name != other.Name) return false;
if (IdTypeCase != other.IdTypeCase) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Kind.Length != 0) hash ^= Kind.GetHashCode();
if (idTypeCase_ == IdTypeOneofCase.Id) hash ^= Id.GetHashCode();
if (idTypeCase_ == IdTypeOneofCase.Name) hash ^= Name.GetHashCode();
hash ^= (int) idTypeCase_;
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Kind.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Kind);
}
if (idTypeCase_ == IdTypeOneofCase.Id) {
output.WriteRawTag(16);
output.WriteInt64(Id);
}
if (idTypeCase_ == IdTypeOneofCase.Name) {
output.WriteRawTag(26);
output.WriteString(Name);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Kind.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Kind);
}
if (idTypeCase_ == IdTypeOneofCase.Id) {
size += 1 + pb::CodedOutputStream.ComputeInt64Size(Id);
}
if (idTypeCase_ == IdTypeOneofCase.Name) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Name);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(PathElement other) {
if (other == null) {
return;
}
if (other.Kind.Length != 0) {
Kind = other.Kind;
}
switch (other.IdTypeCase) {
case IdTypeOneofCase.Id:
Id = other.Id;
break;
case IdTypeOneofCase.Name:
Name = other.Name;
break;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
Kind = input.ReadString();
break;
}
case 16: {
Id = input.ReadInt64();
break;
}
case 26: {
Name = input.ReadString();
break;
}
}
}
}
}
}
#endregion
}
/// <summary>
/// An array value.
/// </summary>
public sealed partial class ArrayValue : pb::IMessage<ArrayValue> {
private static readonly pb::MessageParser<ArrayValue> _parser = new pb::MessageParser<ArrayValue>(() => new ArrayValue());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<ArrayValue> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.Datastore.V1Beta3.EntityReflection.Descriptor.MessageTypes[2]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ArrayValue() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ArrayValue(ArrayValue other) : this() {
values_ = other.values_.Clone();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ArrayValue Clone() {
return new ArrayValue(this);
}
/// <summary>Field number for the "values" field.</summary>
public const int ValuesFieldNumber = 1;
private static readonly pb::FieldCodec<global::Google.Cloud.Datastore.V1Beta3.Value> _repeated_values_codec
= pb::FieldCodec.ForMessage(10, global::Google.Cloud.Datastore.V1Beta3.Value.Parser);
private readonly pbc::RepeatedField<global::Google.Cloud.Datastore.V1Beta3.Value> values_ = new pbc::RepeatedField<global::Google.Cloud.Datastore.V1Beta3.Value>();
/// <summary>
/// Values in the array.
/// The order of this array may not be preserved if it contains a mix of
/// indexed and unindexed values.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::Google.Cloud.Datastore.V1Beta3.Value> Values {
get { return values_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as ArrayValue);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(ArrayValue other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if(!values_.Equals(other.values_)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
hash ^= values_.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
values_.WriteTo(output, _repeated_values_codec);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
size += values_.CalculateSize(_repeated_values_codec);
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(ArrayValue other) {
if (other == null) {
return;
}
values_.Add(other.values_);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
values_.AddEntriesFrom(input, _repeated_values_codec);
break;
}
}
}
}
}
/// <summary>
/// A message that can hold any of the supported value types and associated
/// metadata.
/// </summary>
public sealed partial class Value : pb::IMessage<Value> {
private static readonly pb::MessageParser<Value> _parser = new pb::MessageParser<Value>(() => new Value());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<Value> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.Datastore.V1Beta3.EntityReflection.Descriptor.MessageTypes[3]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Value() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Value(Value other) : this() {
meaning_ = other.meaning_;
excludeFromIndexes_ = other.excludeFromIndexes_;
switch (other.ValueTypeCase) {
case ValueTypeOneofCase.NullValue:
NullValue = other.NullValue;
break;
case ValueTypeOneofCase.BooleanValue:
BooleanValue = other.BooleanValue;
break;
case ValueTypeOneofCase.IntegerValue:
IntegerValue = other.IntegerValue;
break;
case ValueTypeOneofCase.DoubleValue:
DoubleValue = other.DoubleValue;
break;
case ValueTypeOneofCase.TimestampValue:
TimestampValue = other.TimestampValue.Clone();
break;
case ValueTypeOneofCase.KeyValue:
KeyValue = other.KeyValue.Clone();
break;
case ValueTypeOneofCase.StringValue:
StringValue = other.StringValue;
break;
case ValueTypeOneofCase.BlobValue:
BlobValue = other.BlobValue;
break;
case ValueTypeOneofCase.GeoPointValue:
GeoPointValue = other.GeoPointValue.Clone();
break;
case ValueTypeOneofCase.EntityValue:
EntityValue = other.EntityValue.Clone();
break;
case ValueTypeOneofCase.ArrayValue:
ArrayValue = other.ArrayValue.Clone();
break;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Value Clone() {
return new Value(this);
}
/// <summary>Field number for the "null_value" field.</summary>
public const int NullValueFieldNumber = 11;
/// <summary>
/// A null value.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Protobuf.WellKnownTypes.NullValue NullValue {
get { return valueTypeCase_ == ValueTypeOneofCase.NullValue ? (global::Google.Protobuf.WellKnownTypes.NullValue) valueType_ : 0; }
set {
valueType_ = value;
valueTypeCase_ = ValueTypeOneofCase.NullValue;
}
}
/// <summary>Field number for the "boolean_value" field.</summary>
public const int BooleanValueFieldNumber = 1;
/// <summary>
/// A boolean value.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool BooleanValue {
get { return valueTypeCase_ == ValueTypeOneofCase.BooleanValue ? (bool) valueType_ : false; }
set {
valueType_ = value;
valueTypeCase_ = ValueTypeOneofCase.BooleanValue;
}
}
/// <summary>Field number for the "integer_value" field.</summary>
public const int IntegerValueFieldNumber = 2;
/// <summary>
/// An integer value.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public long IntegerValue {
get { return valueTypeCase_ == ValueTypeOneofCase.IntegerValue ? (long) valueType_ : 0L; }
set {
valueType_ = value;
valueTypeCase_ = ValueTypeOneofCase.IntegerValue;
}
}
/// <summary>Field number for the "double_value" field.</summary>
public const int DoubleValueFieldNumber = 3;
/// <summary>
/// A double value.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public double DoubleValue {
get { return valueTypeCase_ == ValueTypeOneofCase.DoubleValue ? (double) valueType_ : 0D; }
set {
valueType_ = value;
valueTypeCase_ = ValueTypeOneofCase.DoubleValue;
}
}
/// <summary>Field number for the "timestamp_value" field.</summary>
public const int TimestampValueFieldNumber = 10;
/// <summary>
/// A timestamp value.
/// When stored in the Datastore, precise only to microseconds;
/// any additional precision is rounded down.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Protobuf.WellKnownTypes.Timestamp TimestampValue {
get { return valueTypeCase_ == ValueTypeOneofCase.TimestampValue ? (global::Google.Protobuf.WellKnownTypes.Timestamp) valueType_ : null; }
set {
valueType_ = value;
valueTypeCase_ = value == null ? ValueTypeOneofCase.None : ValueTypeOneofCase.TimestampValue;
}
}
/// <summary>Field number for the "key_value" field.</summary>
public const int KeyValueFieldNumber = 5;
/// <summary>
/// A key value.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Cloud.Datastore.V1Beta3.Key KeyValue {
get { return valueTypeCase_ == ValueTypeOneofCase.KeyValue ? (global::Google.Cloud.Datastore.V1Beta3.Key) valueType_ : null; }
set {
valueType_ = value;
valueTypeCase_ = value == null ? ValueTypeOneofCase.None : ValueTypeOneofCase.KeyValue;
}
}
/// <summary>Field number for the "string_value" field.</summary>
public const int StringValueFieldNumber = 17;
/// <summary>
/// A UTF-8 encoded string value.
/// When `exclude_from_indexes` is false (it is indexed) , may have at most 1500 bytes.
/// Otherwise, may be set to at least 1,000,000 bytes.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string StringValue {
get { return valueTypeCase_ == ValueTypeOneofCase.StringValue ? (string) valueType_ : ""; }
set {
valueType_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
valueTypeCase_ = ValueTypeOneofCase.StringValue;
}
}
/// <summary>Field number for the "blob_value" field.</summary>
public const int BlobValueFieldNumber = 18;
/// <summary>
/// A blob value.
/// May have at most 1,000,000 bytes.
/// When `exclude_from_indexes` is false, may have at most 1500 bytes.
/// In JSON requests, must be base64-encoded.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pb::ByteString BlobValue {
get { return valueTypeCase_ == ValueTypeOneofCase.BlobValue ? (pb::ByteString) valueType_ : pb::ByteString.Empty; }
set {
valueType_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
valueTypeCase_ = ValueTypeOneofCase.BlobValue;
}
}
/// <summary>Field number for the "geo_point_value" field.</summary>
public const int GeoPointValueFieldNumber = 8;
/// <summary>
/// A geo point value representing a point on the surface of Earth.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Type.LatLng GeoPointValue {
get { return valueTypeCase_ == ValueTypeOneofCase.GeoPointValue ? (global::Google.Type.LatLng) valueType_ : null; }
set {
valueType_ = value;
valueTypeCase_ = value == null ? ValueTypeOneofCase.None : ValueTypeOneofCase.GeoPointValue;
}
}
/// <summary>Field number for the "entity_value" field.</summary>
public const int EntityValueFieldNumber = 6;
/// <summary>
/// An entity value.
///
/// - May have no key.
/// - May have a key with an incomplete key path.
/// - May have a reserved/read-only key.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Cloud.Datastore.V1Beta3.Entity EntityValue {
get { return valueTypeCase_ == ValueTypeOneofCase.EntityValue ? (global::Google.Cloud.Datastore.V1Beta3.Entity) valueType_ : null; }
set {
valueType_ = value;
valueTypeCase_ = value == null ? ValueTypeOneofCase.None : ValueTypeOneofCase.EntityValue;
}
}
/// <summary>Field number for the "array_value" field.</summary>
public const int ArrayValueFieldNumber = 9;
/// <summary>
/// An array value.
/// Cannot contain another array value.
/// A `Value` instance that sets field `array_value` must not set fields
/// `meaning` or `exclude_from_indexes`.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Cloud.Datastore.V1Beta3.ArrayValue ArrayValue {
get { return valueTypeCase_ == ValueTypeOneofCase.ArrayValue ? (global::Google.Cloud.Datastore.V1Beta3.ArrayValue) valueType_ : null; }
set {
valueType_ = value;
valueTypeCase_ = value == null ? ValueTypeOneofCase.None : ValueTypeOneofCase.ArrayValue;
}
}
/// <summary>Field number for the "meaning" field.</summary>
public const int MeaningFieldNumber = 14;
private int meaning_;
/// <summary>
/// The `meaning` field should only be populated for backwards compatibility.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int Meaning {
get { return meaning_; }
set {
meaning_ = value;
}
}
/// <summary>Field number for the "exclude_from_indexes" field.</summary>
public const int ExcludeFromIndexesFieldNumber = 19;
private bool excludeFromIndexes_;
/// <summary>
/// If the value should be excluded from all indexes including those defined
/// explicitly.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool ExcludeFromIndexes {
get { return excludeFromIndexes_; }
set {
excludeFromIndexes_ = value;
}
}
private object valueType_;
/// <summary>Enum of possible cases for the "value_type" oneof.</summary>
public enum ValueTypeOneofCase {
None = 0,
NullValue = 11,
BooleanValue = 1,
IntegerValue = 2,
DoubleValue = 3,
TimestampValue = 10,
KeyValue = 5,
StringValue = 17,
BlobValue = 18,
GeoPointValue = 8,
EntityValue = 6,
ArrayValue = 9,
}
private ValueTypeOneofCase valueTypeCase_ = ValueTypeOneofCase.None;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ValueTypeOneofCase ValueTypeCase {
get { return valueTypeCase_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void ClearValueType() {
valueTypeCase_ = ValueTypeOneofCase.None;
valueType_ = null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as Value);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(Value other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (NullValue != other.NullValue) return false;
if (BooleanValue != other.BooleanValue) return false;
if (IntegerValue != other.IntegerValue) return false;
if (DoubleValue != other.DoubleValue) return false;
if (!object.Equals(TimestampValue, other.TimestampValue)) return false;
if (!object.Equals(KeyValue, other.KeyValue)) return false;
if (StringValue != other.StringValue) return false;
if (BlobValue != other.BlobValue) return false;
if (!object.Equals(GeoPointValue, other.GeoPointValue)) return false;
if (!object.Equals(EntityValue, other.EntityValue)) return false;
if (!object.Equals(ArrayValue, other.ArrayValue)) return false;
if (Meaning != other.Meaning) return false;
if (ExcludeFromIndexes != other.ExcludeFromIndexes) return false;
if (ValueTypeCase != other.ValueTypeCase) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (valueTypeCase_ == ValueTypeOneofCase.NullValue) hash ^= NullValue.GetHashCode();
if (valueTypeCase_ == ValueTypeOneofCase.BooleanValue) hash ^= BooleanValue.GetHashCode();
if (valueTypeCase_ == ValueTypeOneofCase.IntegerValue) hash ^= IntegerValue.GetHashCode();
if (valueTypeCase_ == ValueTypeOneofCase.DoubleValue) hash ^= DoubleValue.GetHashCode();
if (valueTypeCase_ == ValueTypeOneofCase.TimestampValue) hash ^= TimestampValue.GetHashCode();
if (valueTypeCase_ == ValueTypeOneofCase.KeyValue) hash ^= KeyValue.GetHashCode();
if (valueTypeCase_ == ValueTypeOneofCase.StringValue) hash ^= StringValue.GetHashCode();
if (valueTypeCase_ == ValueTypeOneofCase.BlobValue) hash ^= BlobValue.GetHashCode();
if (valueTypeCase_ == ValueTypeOneofCase.GeoPointValue) hash ^= GeoPointValue.GetHashCode();
if (valueTypeCase_ == ValueTypeOneofCase.EntityValue) hash ^= EntityValue.GetHashCode();
if (valueTypeCase_ == ValueTypeOneofCase.ArrayValue) hash ^= ArrayValue.GetHashCode();
if (Meaning != 0) hash ^= Meaning.GetHashCode();
if (ExcludeFromIndexes != false) hash ^= ExcludeFromIndexes.GetHashCode();
hash ^= (int) valueTypeCase_;
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (valueTypeCase_ == ValueTypeOneofCase.BooleanValue) {
output.WriteRawTag(8);
output.WriteBool(BooleanValue);
}
if (valueTypeCase_ == ValueTypeOneofCase.IntegerValue) {
output.WriteRawTag(16);
output.WriteInt64(IntegerValue);
}
if (valueTypeCase_ == ValueTypeOneofCase.DoubleValue) {
output.WriteRawTag(25);
output.WriteDouble(DoubleValue);
}
if (valueTypeCase_ == ValueTypeOneofCase.KeyValue) {
output.WriteRawTag(42);
output.WriteMessage(KeyValue);
}
if (valueTypeCase_ == ValueTypeOneofCase.EntityValue) {
output.WriteRawTag(50);
output.WriteMessage(EntityValue);
}
if (valueTypeCase_ == ValueTypeOneofCase.GeoPointValue) {
output.WriteRawTag(66);
output.WriteMessage(GeoPointValue);
}
if (valueTypeCase_ == ValueTypeOneofCase.ArrayValue) {
output.WriteRawTag(74);
output.WriteMessage(ArrayValue);
}
if (valueTypeCase_ == ValueTypeOneofCase.TimestampValue) {
output.WriteRawTag(82);
output.WriteMessage(TimestampValue);
}
if (valueTypeCase_ == ValueTypeOneofCase.NullValue) {
output.WriteRawTag(88);
output.WriteEnum((int) NullValue);
}
if (Meaning != 0) {
output.WriteRawTag(112);
output.WriteInt32(Meaning);
}
if (valueTypeCase_ == ValueTypeOneofCase.StringValue) {
output.WriteRawTag(138, 1);
output.WriteString(StringValue);
}
if (valueTypeCase_ == ValueTypeOneofCase.BlobValue) {
output.WriteRawTag(146, 1);
output.WriteBytes(BlobValue);
}
if (ExcludeFromIndexes != false) {
output.WriteRawTag(152, 1);
output.WriteBool(ExcludeFromIndexes);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (valueTypeCase_ == ValueTypeOneofCase.NullValue) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) NullValue);
}
if (valueTypeCase_ == ValueTypeOneofCase.BooleanValue) {
size += 1 + 1;
}
if (valueTypeCase_ == ValueTypeOneofCase.IntegerValue) {
size += 1 + pb::CodedOutputStream.ComputeInt64Size(IntegerValue);
}
if (valueTypeCase_ == ValueTypeOneofCase.DoubleValue) {
size += 1 + 8;
}
if (valueTypeCase_ == ValueTypeOneofCase.TimestampValue) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(TimestampValue);
}
if (valueTypeCase_ == ValueTypeOneofCase.KeyValue) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(KeyValue);
}
if (valueTypeCase_ == ValueTypeOneofCase.StringValue) {
size += 2 + pb::CodedOutputStream.ComputeStringSize(StringValue);
}
if (valueTypeCase_ == ValueTypeOneofCase.BlobValue) {
size += 2 + pb::CodedOutputStream.ComputeBytesSize(BlobValue);
}
if (valueTypeCase_ == ValueTypeOneofCase.GeoPointValue) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(GeoPointValue);
}
if (valueTypeCase_ == ValueTypeOneofCase.EntityValue) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(EntityValue);
}
if (valueTypeCase_ == ValueTypeOneofCase.ArrayValue) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(ArrayValue);
}
if (Meaning != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(Meaning);
}
if (ExcludeFromIndexes != false) {
size += 2 + 1;
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(Value other) {
if (other == null) {
return;
}
if (other.Meaning != 0) {
Meaning = other.Meaning;
}
if (other.ExcludeFromIndexes != false) {
ExcludeFromIndexes = other.ExcludeFromIndexes;
}
switch (other.ValueTypeCase) {
case ValueTypeOneofCase.NullValue:
NullValue = other.NullValue;
break;
case ValueTypeOneofCase.BooleanValue:
BooleanValue = other.BooleanValue;
break;
case ValueTypeOneofCase.IntegerValue:
IntegerValue = other.IntegerValue;
break;
case ValueTypeOneofCase.DoubleValue:
DoubleValue = other.DoubleValue;
break;
case ValueTypeOneofCase.TimestampValue:
TimestampValue = other.TimestampValue;
break;
case ValueTypeOneofCase.KeyValue:
KeyValue = other.KeyValue;
break;
case ValueTypeOneofCase.StringValue:
StringValue = other.StringValue;
break;
case ValueTypeOneofCase.BlobValue:
BlobValue = other.BlobValue;
break;
case ValueTypeOneofCase.GeoPointValue:
GeoPointValue = other.GeoPointValue;
break;
case ValueTypeOneofCase.EntityValue:
EntityValue = other.EntityValue;
break;
case ValueTypeOneofCase.ArrayValue:
ArrayValue = other.ArrayValue;
break;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
BooleanValue = input.ReadBool();
break;
}
case 16: {
IntegerValue = input.ReadInt64();
break;
}
case 25: {
DoubleValue = input.ReadDouble();
break;
}
case 42: {
global::Google.Cloud.Datastore.V1Beta3.Key subBuilder = new global::Google.Cloud.Datastore.V1Beta3.Key();
if (valueTypeCase_ == ValueTypeOneofCase.KeyValue) {
subBuilder.MergeFrom(KeyValue);
}
input.ReadMessage(subBuilder);
KeyValue = subBuilder;
break;
}
case 50: {
global::Google.Cloud.Datastore.V1Beta3.Entity subBuilder = new global::Google.Cloud.Datastore.V1Beta3.Entity();
if (valueTypeCase_ == ValueTypeOneofCase.EntityValue) {
subBuilder.MergeFrom(EntityValue);
}
input.ReadMessage(subBuilder);
EntityValue = subBuilder;
break;
}
case 66: {
global::Google.Type.LatLng subBuilder = new global::Google.Type.LatLng();
if (valueTypeCase_ == ValueTypeOneofCase.GeoPointValue) {
subBuilder.MergeFrom(GeoPointValue);
}
input.ReadMessage(subBuilder);
GeoPointValue = subBuilder;
break;
}
case 74: {
global::Google.Cloud.Datastore.V1Beta3.ArrayValue subBuilder = new global::Google.Cloud.Datastore.V1Beta3.ArrayValue();
if (valueTypeCase_ == ValueTypeOneofCase.ArrayValue) {
subBuilder.MergeFrom(ArrayValue);
}
input.ReadMessage(subBuilder);
ArrayValue = subBuilder;
break;
}
case 82: {
global::Google.Protobuf.WellKnownTypes.Timestamp subBuilder = new global::Google.Protobuf.WellKnownTypes.Timestamp();
if (valueTypeCase_ == ValueTypeOneofCase.TimestampValue) {
subBuilder.MergeFrom(TimestampValue);
}
input.ReadMessage(subBuilder);
TimestampValue = subBuilder;
break;
}
case 88: {
valueType_ = input.ReadEnum();
valueTypeCase_ = ValueTypeOneofCase.NullValue;
break;
}
case 112: {
Meaning = input.ReadInt32();
break;
}
case 138: {
StringValue = input.ReadString();
break;
}
case 146: {
BlobValue = input.ReadBytes();
break;
}
case 152: {
ExcludeFromIndexes = input.ReadBool();
break;
}
}
}
}
}
/// <summary>
/// A Datastore data object.
///
/// An entity is limited to 1 megabyte when stored. That _roughly_
/// corresponds to a limit of 1 megabyte for the serialized form of this
/// message.
/// </summary>
public sealed partial class Entity : pb::IMessage<Entity> {
private static readonly pb::MessageParser<Entity> _parser = new pb::MessageParser<Entity>(() => new Entity());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<Entity> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.Datastore.V1Beta3.EntityReflection.Descriptor.MessageTypes[4]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Entity() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Entity(Entity other) : this() {
Key = other.key_ != null ? other.Key.Clone() : null;
properties_ = other.properties_.Clone();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Entity Clone() {
return new Entity(this);
}
/// <summary>Field number for the "key" field.</summary>
public const int KeyFieldNumber = 1;
private global::Google.Cloud.Datastore.V1Beta3.Key key_;
/// <summary>
/// The entity's key.
///
/// An entity must have a key, unless otherwise documented (for example,
/// an entity in `Value.entity_value` may have no key).
/// An entity's kind is its key path's last element's kind,
/// or null if it has no key.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Cloud.Datastore.V1Beta3.Key Key {
get { return key_; }
set {
key_ = value;
}
}
/// <summary>Field number for the "properties" field.</summary>
public const int PropertiesFieldNumber = 3;
private static readonly pbc::MapField<string, global::Google.Cloud.Datastore.V1Beta3.Value>.Codec _map_properties_codec
= new pbc::MapField<string, global::Google.Cloud.Datastore.V1Beta3.Value>.Codec(pb::FieldCodec.ForString(10), pb::FieldCodec.ForMessage(18, global::Google.Cloud.Datastore.V1Beta3.Value.Parser), 26);
private readonly pbc::MapField<string, global::Google.Cloud.Datastore.V1Beta3.Value> properties_ = new pbc::MapField<string, global::Google.Cloud.Datastore.V1Beta3.Value>();
/// <summary>
/// The entity's properties.
/// The map's keys are property names.
/// A property name matching regex `__.*__` is reserved.
/// A reserved property name is forbidden in certain documented contexts.
/// The name must not contain more than 500 characters.
/// The name cannot be `""`.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::MapField<string, global::Google.Cloud.Datastore.V1Beta3.Value> Properties {
get { return properties_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as Entity);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(Entity other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(Key, other.Key)) return false;
if (!Properties.Equals(other.Properties)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (key_ != null) hash ^= Key.GetHashCode();
hash ^= Properties.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (key_ != null) {
output.WriteRawTag(10);
output.WriteMessage(Key);
}
properties_.WriteTo(output, _map_properties_codec);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (key_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Key);
}
size += properties_.CalculateSize(_map_properties_codec);
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(Entity other) {
if (other == null) {
return;
}
if (other.key_ != null) {
if (key_ == null) {
key_ = new global::Google.Cloud.Datastore.V1Beta3.Key();
}
Key.MergeFrom(other.Key);
}
properties_.Add(other.properties_);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
if (key_ == null) {
key_ = new global::Google.Cloud.Datastore.V1Beta3.Key();
}
input.ReadMessage(key_);
break;
}
case 26: {
properties_.AddEntriesFrom(input, _map_properties_codec);
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using RRLab.PhysiologyWorkbench.Data;
namespace RRLab.PhysiologyWorkbench.Data
{
public class DataSetBackedCell : Cell
{
private PhysiologyData _BackingDataSet;
public PhysiologyData BackingDataSet
{
get { return _BackingDataSet; }
set { _BackingDataSet = value; }
}
public int CellID
{
get {
if (BackingDataSet == null) throw new Exception("Underlying dataset must not be null.");
return BackingRow.CellID;
}
set {
if (BackingDataSet == null) throw new Exception("Underlying dataset must not be null.");
BackingRow = BackingDataSet.Cells.FindByCellID(value) as PhysiologyData.CellsRow;
}
}
public event EventHandler BackingRowChanged;
private PhysiologyData.CellsRow _BackingRow;
public PhysiologyData.CellsRow BackingRow
{
get {
return _BackingRow;
}
set {
if (value.Table.DataSet is PhysiologyData) BackingDataSet = value.Table.DataSet as PhysiologyData;
else throw new Exception("DataSet must be PhysiologyData.");
_BackingRow = value;
if (BackingRowChanged != null) BackingRowChanged(this, EventArgs.Empty);
}
}
// Overridden properties
public override DateTime BreakInTime
{
get
{
if (BackingDataSet == null) throw new Exception("Underlying dataset must not be null.");
if (BackingRow.IsBreakInTimeNull()) return DateTime.MinValue;
else return BackingRow.BreakInTime;
}
set
{
if (BackingDataSet == null) throw new Exception("Underlying dataset must not be null.");
if (value == DateTime.MinValue)
BackingRow.SetBreakInTimeNull();
else BackingRow.BreakInTime = value;
OnBreakInTimeChanged(EventArgs.Empty);
}
}
public override float CellCapacitance
{
get
{
if (BackingDataSet == null) throw new Exception("Underlying dataset must not be null.");
if (BackingRow.IsCellCapacitanceNull())
return 0f;
return BackingRow.CellCapacitance;
}
set
{
if (BackingDataSet == null) throw new Exception("Underlying dataset must not be null.");
BackingRow.CellCapacitance = value;
OnCellCapacitanceChanged(EventArgs.Empty);
}
}
public override DateTime Created
{
get
{
if (BackingDataSet == null) throw new Exception("Underlying dataset must not be null.");
return BackingRow.Created;
}
set
{
if (BackingDataSet == null) throw new Exception("Underlying dataset must not be null.");
BackingRow.Created = value;
OnCreatedChanged(EventArgs.Empty);
}
}
public override string Description
{
get
{
if (BackingDataSet == null) throw new Exception("Underlying dataset must not be null.");
if (BackingRow.IsDescriptionNull())
return null;
return BackingRow.Description;
}
set
{
if (BackingDataSet == null) throw new Exception("Underlying dataset must not be null.");
BackingRow.Description = value;
OnDescriptionChanged(EventArgs.Empty);
}
}
public override string Genotype
{
get
{
if (BackingDataSet == null) throw new Exception("Underlying dataset must not be null.");
return BackingRow.GenotypesRow.Genotype;
}
set
{
if (BackingDataSet == null) throw new Exception("Underlying dataset must not be null.");
PhysiologyData.GenotypesRow[] matches = BackingDataSet.Genotypes.Select("Genotype = '" + (value ?? "Unknown") + "'") as PhysiologyData.GenotypesRow[];
if (matches == null || matches.Length == 0)
{
PhysiologyData.GenotypesRow row = BackingDataSet.Genotypes.NewGenotypesRow();
row.Genotype = value ?? "Unknown";
BackingDataSet.Genotypes.AddGenotypesRow(row);
BackingRow.GenotypesRow = row;
BackingDataSet.Genotypes.AddGenotypesRow(row);
}
else
{
BackingRow.GenotypesRow = matches[0];
}
OnGenotypeChanged(EventArgs.Empty);
}
}
public override float MembranePotential
{
get
{
if (BackingRow.IsMembranePotentialNull())
return 0f;
return BackingRow.MembranePotential;
}
set
{
BackingRow.MembranePotential = Convert.ToInt16(value);
OnMembranePotentialChanged(EventArgs.Empty);
}
}
public override float MembraneResistance
{
get
{
if (BackingDataSet == null) throw new Exception("Underlying dataset must not be null.");
if (BackingRow.IsMembraneResistanceNull())
return 0f;
return BackingRow.MembraneResistance;
}
set
{
if (BackingDataSet == null) throw new Exception("Underlying dataset must not be null.");
BackingRow.MembraneResistance = value;
OnMembraneResistanceChanged(EventArgs.Empty);
}
}
public override float PipetteResistance
{
get
{
if (BackingDataSet == null) throw new Exception("Underlying dataset must not be null.");
if (BackingRow.IsPipetteResistanceNull())
return 0f;
return BackingRow.PipetteResistance;
}
set
{
if (BackingDataSet == null) throw new Exception("Underlying dataset must not be null.");
BackingRow.PipetteResistance = value;
OnPipetteResistanceChanged(EventArgs.Empty);
}
}
public override ICollection<Recording> Recordings
{
get
{
if (BackingDataSet == null) throw new Exception("Underlying dataset must not be null.");
PhysiologyData.RecordingsRow[] rows = BackingRow.GetRecordingsRows();
List<Recording> recordings = new List<Recording>(rows.Length);
foreach (PhysiologyData.RecordingsRow row in rows)
recordings.Add(new DataSetBackedRecording(BackingDataSet, row.RecordingID));
return recordings;
}
}
public override float SealResistance
{
get
{
if (BackingDataSet == null) throw new Exception("Underlying dataset must not be null.");
if (BackingRow.IsSealResistanceNull())
return 0f;
return BackingRow.SealResistance;
}
set
{
if (BackingDataSet == null) throw new Exception("Underlying dataset must not be null.");
BackingRow.SealResistance = value;
OnSealResistanceChanged(EventArgs.Empty);
}
}
public override float SeriesResistance
{
get
{
if (BackingDataSet == null) throw new Exception("Underlying dataset must not be null.");
if (BackingRow.IsSeriesResistanceNull())
return 0f;
return BackingRow.SeriesResistance;
}
set
{
if (BackingDataSet == null) throw new Exception("Underlying dataset must not be null.");
BackingRow.SeriesResistance = value;
OnSeriesResistanceChanged(EventArgs.Empty);
}
}
public short UserID
{
get
{
if (BackingRow == null) throw new Exception("No backing row.");
return BackingRow.UserID;
}
set
{
if (BackingRow == null) throw new Exception("No backing row.");
BackingRow.UserID = value;
OnUserNameChanged(EventArgs.Empty);
}
}
public override string UserName
{
get
{
if (BackingRow == null) throw new Exception("No backing row.");
return BackingRow.UsersRow.Name;
}
set
{
if (BackingRow == null) throw new Exception("No backing row.");
PhysiologyData.UsersRow[] rows = BackingDataSet.Users.Select(
String.Format("Name = '{0}'", value)) as PhysiologyData.UsersRow[];
if (rows != null && rows.Length > 0)
BackingRow.UsersRow = rows[0];
else
{
PhysiologyData.UsersRow row = BackingDataSet.Users.AddUsersRow(value);
BackingRow.UsersRow = row;
}
OnUserNameChanged(EventArgs.Empty);
}
}
public DataSetBackedCell()
{
BackingDataSet = new PhysiologyData();
CreateNewCellEntryInDataSet();
}
public DataSetBackedCell(PhysiologyData dataSet)
{
BackingDataSet = dataSet;
CreateNewCellEntryInDataSet();
}
public DataSetBackedCell(PhysiologyData dataSet, int cellID)
{
BackingDataSet = dataSet;
CellID = cellID;
}
public DataSetBackedCell(PhysiologyData dataSet, Cell cell)
{
BackingDataSet = dataSet;
CreateNewCellEntryInDataSet();
LoadDataFromCell(cell);
}
protected virtual void CreateNewCellEntryInDataSet()
{
if (BackingDataSet == null) throw new Exception("No backing DataSet.");
PhysiologyData.CellsRow row = BackingDataSet.Cells.NewCellsRow();
// Deal with null values
row.BeginEdit();
row.Created = DateTime.Now;
PhysiologyData.GenotypesRow genotypesRow;
if (BackingDataSet.Genotypes.Select("Genotype = 'Unknown'").Length == 0)
{
genotypesRow = BackingDataSet.Genotypes.NewGenotypesRow();
genotypesRow.Genotype = "Unknown";
BackingDataSet.Genotypes.AddGenotypesRow(genotypesRow);
}
else
{
PhysiologyData.GenotypesRow[] rows = BackingDataSet.Genotypes.Select("Genotype = 'Unknown'") as PhysiologyData.GenotypesRow[];
genotypesRow = rows[0];
}
row.GenotypesRow = genotypesRow;
PhysiologyData.UsersRow[] users = BackingDataSet.Users.Select("Name = 'Unknown'") as PhysiologyData.UsersRow[];
if (users != null && users.Length > 0)
row.UsersRow = users[0];
else row.UsersRow = BackingDataSet.Users.AddUsersRow("Unknown");
row.EndEdit();
BackingDataSet.Cells.AddCellsRow(row);
CellID = row.CellID;
}
public virtual void LoadDataFromCell(Cell cell)
{
this.BreakInTime = cell.BreakInTime;
this.Created = cell.Created;
this.Description = cell.Description;
this.Genotype = cell.Genotype;
this.CellCapacitance = cell.CellCapacitance;
this.MembranePotential = cell.MembranePotential;
this.MembraneResistance = cell.MembraneResistance;
this.PipetteResistance = cell.PipetteResistance;
this.SealResistance = cell.SealResistance;
this.SeriesResistance = cell.SeriesResistance;
this.RoughAppearanceRating = cell.RoughAppearanceRating;
this.LengthAppearanceRating = cell.LengthAppearanceRating;
this.ShapeAppearanceRating = cell.ShapeAppearanceRating;
this.UserName = cell.UserName;
foreach (Recording recording in cell.Recordings)
new DataSetBackedRecording(this, recording);
foreach (Annotation annotation in cell.Annotations)
AddAnnotation(annotation);
}
public override void AddRecording(Recording recording)
{
if (recording is DataSetBackedRecording)
{
DataSetBackedRecording dataSetRecording = recording as DataSetBackedRecording;
if (dataSetRecording.BackingDataSet == BackingDataSet)
dataSetRecording.Cell = this;
else
{
dataSetRecording.StoreInDataSet(BackingDataSet);
dataSetRecording.Cell = this;
}
}
else recording.Cell = this;
}
public override void RemoveRecording(Recording recording)
{
recording.Cell = null;
}
public override void AddAnnotation(Annotation annotation)
{
if (BackingRow == null) throw new Exception("No backing row.");
PhysiologyData.Cells_AnnotationsRow row = BackingDataSet.Cells_Annotations.NewCells_AnnotationsRow();
row.CellsRow = BackingRow;
if (annotation.User != null)
{
PhysiologyData.UsersRow[] users = BackingDataSet.Users.Select(
String.Format("Name = {0}", annotation.User)) as PhysiologyData.UsersRow[];
if (users != null && users.Length > 0)
row.UsersRow = users[0];
else row.UsersRow = BackingRow.UsersRow;
}
else row.UsersRow = BackingRow.UsersRow;
row.Entered = annotation.Time;
row.Text = annotation.Text;
BackingDataSet.Cells_Annotations.AddCells_AnnotationsRow(row);
OnAnnotationsChanged(EventArgs.Empty);
}
public override void RemoveAnnotation(Annotation annotation)
{
if (BackingRow == null) throw new Exception("No backin row.");
PhysiologyData.Cells_AnnotationsRow[] rows = BackingDataSet.Cells_Annotations.Select(
String.Format("CellID = {0}, Time = {1}, Text = '{2}'", BackingRow.CellID, annotation.Time, @annotation.Text))
as PhysiologyData.Cells_AnnotationsRow[];
foreach (PhysiologyData.Cells_AnnotationsRow row in rows)
row.Delete();
OnAnnotationsChanged(EventArgs.Empty);
}
public override ICollection<Annotation> Annotations
{
get
{
PhysiologyData.Cells_AnnotationsRow[] rows = BackingDataSet.Cells_Annotations.Select(
String.Format("CellID = {0}", BackingRow.CellID)) as PhysiologyData.Cells_AnnotationsRow[];
List<Annotation> annotations = new List<Annotation>(rows.Length);
foreach (PhysiologyData.Cells_AnnotationsRow row in rows)
annotations.Add(new Annotation(row.Entered, row.Text, row.UsersRow.Name));
return annotations;
}
}
public override ushort LengthAppearanceRating
{
get
{
if (BackingRow.IsLengthAppearanceRatingNull())
return 0;
return BackingRow.LengthAppearanceRating;
}
set
{
BackingRow.LengthAppearanceRating = value;
OnLengthAppearanceRatingChanged(EventArgs.Empty);
}
}
public override ushort RoughAppearanceRating
{
get
{
if (BackingRow.IsRoughAppearanceRatingNull())
return 0;
return BackingRow.RoughAppearanceRating;
}
set
{
BackingRow.RoughAppearanceRating = value;
OnRoughAppearanceRatingChanged(EventArgs.Empty);
}
}
public override ushort ShapeAppearanceRating
{
get
{
if (BackingRow.IsShapeAppearanceRatingNull())
return 0;
return BackingRow.ShapeAppearanceRating;
}
set
{
BackingRow.ShapeAppearanceRating = value;
OnShapeAppearanceRatingChanged(EventArgs.Empty);
}
}
}
}
| |
// Copyright (c) 2015, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.IO;
using System.Xml;
using System.Security.Principal;
using System.Resources;
using System.Configuration;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.Compilation;
using System.Web.Configuration;
using System.Web.UI;
using System.Web.Security;
using System.Web.UI.WebControls;
using System.Net;
using System.Net.Mail;
using System.Security.Cryptography;
using Microsoft.Web.Services3;
using WebsitePanel.EnterpriseServer;
using WebsitePanel.WebPortal;
namespace WebsitePanel.Portal
{
public class PortalUtils
{
public const string SharedResourcesFile = "SharedResources.ascx.resx";
public const string CONFIG_FOLDER = "~/App_Data/";
public const string SUPPORTED_THEMES_FILE = "SupportedThemes.config";
public const string SUPPORTED_LOCALES_FILE = "SupportedLocales.config";
public const string EXCHANGE_SERVER_HIERARCHY_FILE = "ESModule_ControlsHierarchy.config";
public const string USER_ID_PARAM = "UserID";
public const string SPACE_ID_PARAM = "SpaceID";
public const string SEARCH_QUERY_PARAM = "Query";
public static string CultureCookieName
{
get { return PortalConfiguration.SiteSettings["CultureCookieName"]; }
}
public static string ThemeCookieName
{
get { return PortalConfiguration.SiteSettings["ThemeCookieName"]; }
}
public static System.Globalization.CultureInfo CurrentCulture
{
get { return GetCurrentCulture(); }
}
public static System.Globalization.CultureInfo CurrentUICulture
{
get { return GetCurrentCulture(); }
}
public static string CurrentTheme
{
get { return GetCurrentTheme(); }
}
internal static string GetCurrentTheme()
{
string theme = (string) HttpContext.Current.Items[ThemeCookieName];
if (theme == null)
{
HttpCookie cookie = HttpContext.Current.Request.Cookies[ThemeCookieName];
if (cookie != null)
{
theme = cookie.Value;
if (!String.IsNullOrEmpty(theme))
{
HttpContext.Current.Items[ThemeCookieName] = theme;
return theme;
}
}
else
{
string appData = HttpContext.Current.Server.MapPath(CONFIG_FOLDER);
string path = Path.Combine(appData, SUPPORTED_THEMES_FILE);
XmlTextReader reader = new XmlTextReader(path);
reader.XmlResolver = null;
reader.WhitespaceHandling = WhitespaceHandling.None;
reader.MoveToContent();
if (reader.Name != null)
{
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
if (reader.HasAttributes)
{
reader.MoveToFirstAttribute();
theme = reader.Value;
return theme;
}
}
}
}
}
}
return String.IsNullOrEmpty(theme) ? "Default" : theme;
}
public static void SetCurrentTheme(string theme)
{
// theme
if (!String.IsNullOrEmpty(theme))
{
HttpCookie cookieTheme = new HttpCookie(ThemeCookieName, theme);
cookieTheme.Expires = DateTime.Now.AddMonths(2);
HttpContext.Current.Response.Cookies.Add(cookieTheme);
}
}
internal static System.Globalization.CultureInfo GetCurrentCulture()
{
System.Globalization.CultureInfo ci = (System.Globalization.CultureInfo)
HttpContext.Current.Items[CultureCookieName];
if (ci == null)
{
HttpCookie localeCrumb = HttpContext.Current.Request.Cookies[CultureCookieName];
if (localeCrumb != null)
{
ci = System.Globalization.CultureInfo.CreateSpecificCulture(localeCrumb.Value);
if (ci != null)
{
HttpContext.Current.Items[CultureCookieName] = ci;
return ci;
}
}
}
else
return ci;
return System.Threading.Thread.CurrentThread.CurrentCulture;
}
public static string AdminEmail
{
get { return PortalConfiguration.SiteSettings["AdminEmail"]; }
}
public static string FromEmail
{
get { return PortalConfiguration.SiteSettings["FromEmail"]; }
}
public static void SendMail(string from, string to, string bcc, string subject, string body)
{
// Command line argument must the the SMTP host.
SmtpClient client = new SmtpClient();
// set SMTP client settings
client.Host = PortalConfiguration.SiteSettings["SmtpHost"];
client.Port = Int32.Parse(PortalConfiguration.SiteSettings["SmtpPort"]);
string smtpUsername = PortalConfiguration.SiteSettings["SmtpUsername"];
string smtpPassword = PortalConfiguration.SiteSettings["SmtpPassword"];
if (String.IsNullOrEmpty(smtpUsername))
{
client.Credentials = new NetworkCredential(smtpUsername, smtpPassword);
}
// create message
MailMessage message = new MailMessage(from, to);
message.Body = body;
message.BodyEncoding = System.Text.Encoding.UTF8;
message.IsBodyHtml = false;
message.Subject = subject;
message.SubjectEncoding = System.Text.Encoding.UTF8;
if (!String.IsNullOrEmpty(bcc))
message.Bcc.Add(bcc);
// send message
try
{
client.Send(message);
}
finally
{
// Clean up.
message.Dispose();
}
}
public static void UserSignOut()
{
FormsAuthentication.SignOut();
if (HttpContext.Current.Session != null)
{
HttpContext.Current.Session.Clear();
HttpContext.Current.Session.Abandon();
}
// Clear authentication cookie
HttpCookie rFormsCookie = new HttpCookie(FormsAuthentication.FormsCookieName, "");
rFormsCookie.Expires = DateTime.Now.AddYears(-1);
HttpContext.Current.Response.Cookies.Add(rFormsCookie);
// Clear session cookie
HttpCookie rSessionCookie = new HttpCookie("ASP.NET_SessionId", "");
rSessionCookie.Expires = DateTime.Now.AddYears(-1);
HttpContext.Current.Response.Cookies.Add(rSessionCookie);
HttpContext.Current.Response.Redirect(LoginRedirectUrl);
}
public static MenuItem GetSpaceMenuItem(string menuItemKey)
{
MenuItem item = new MenuItem();
item.Value = menuItemKey;
menuItemKey = String.Concat("Space", menuItemKey);
PortalPage page = PortalConfiguration.Site.Pages[menuItemKey];
if (page != null)
item.NavigateUrl = DefaultPage.GetPageUrl(menuItemKey);
return item;
}
private static FormsAuthenticationTicket AuthTicket
{
get
{
FormsAuthenticationTicket authTicket = (FormsAuthenticationTicket)HttpContext.Current.Items[FormsAuthentication.FormsCookieName];
if (authTicket == null)
{
// original code
HttpCookie authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
// workaround for cases when AuthTicket is required before round-trip
if (authCookie == null || String.IsNullOrEmpty(authCookie.Value))
authCookie = HttpContext.Current.Response.Cookies[FormsAuthentication.FormsCookieName];
//
if (authCookie != null)
{
authTicket = FormsAuthentication.Decrypt(authCookie.Value);
HttpContext.Current.Items[FormsAuthentication.FormsCookieName] = authTicket;
}
}
return authTicket;
}
}
private static void SetAuthTicket(FormsAuthenticationTicket ticket, bool persistent)
{
// issue authentication cookie
HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName);
authCookie.Domain = FormsAuthentication.CookieDomain;
authCookie.Secure = FormsAuthentication.RequireSSL;
authCookie.Path = FormsAuthentication.FormsCookiePath;
authCookie.Value = FormsAuthentication.Encrypt(ticket);
authCookie.HttpOnly = true;
if (persistent)
authCookie.Expires = ticket.Expiration;
HttpContext.Current.Response.Cookies.Add(authCookie);
}
public static string ApplicationPath
{
get
{
if (HttpContext.Current.Request.ApplicationPath == "/")
return "";
else
return HttpContext.Current.Request.ApplicationPath;
}
}
public static string GetSharedLocalizedString(string moduleName, string resourceKey)
{
string className = SharedResourcesFile.Replace(".resx", "");
if (!String.IsNullOrEmpty(moduleName))
className = String.Concat(moduleName, "_", className);
return (string)HttpContext.GetGlobalResourceObject(className, resourceKey);
}
public static string GetLocalizedString(string virtualPath, string resourceKey)
{
return (string)HttpContext.GetLocalResourceObject(virtualPath, resourceKey);
}
public static string GetCurrentPageId()
{
return HttpContext.Current.Request["pid"];
}
public static bool PageExists(string pageId)
{
return PortalConfiguration.Site.Pages[pageId] != null;
}
public static string GetLocalizedPageName(string pageId)
{
return DefaultPage.GetLocalizedPageName(pageId);
}
public static string SHA1(string plainText)
{
// Convert plain text into a byte array.
byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
HashAlgorithm hash = new SHA1Managed(); ;
// Compute hash value of our plain text with appended salt.
byte[] hashBytes = hash.ComputeHash(plainTextBytes);
// Return the result.
return Convert.ToBase64String(hashBytes);
}
public static int AuthenticateUser(string username, string password, string ipAddress,
bool rememberLogin, string preferredLocale, string theme)
{
esAuthentication authService = new esAuthentication();
ConfigureEnterpriseServerProxy(authService, false);
string passwordSH = SHA1(password);
try
{
int authResult = authService.AuthenticateUser(username, passwordSH, ipAddress);
if (authResult < 0)
{
return authResult;
}
else
{
UserInfo user = authService.GetUserByUsernamePassword(username, passwordSH, ipAddress);
if (user != null)
{
if (IsRoleAllowedToLogin(user.Role))
{
// issue authentication ticket
FormsAuthenticationTicket ticket = CreateAuthTicket(user.Username, password, user.Role, rememberLogin);
SetAuthTicket(ticket, rememberLogin);
CompleteUserLogin(username, rememberLogin, preferredLocale, theme);
}
else return BusinessErrorCodes.ERROR_USER_ACCOUNT_ROLE_NOT_ALLOWED;
}
return authResult;
}
}
catch (Exception ex)
{
throw ex;
}
}
private static bool IsRoleAllowedToLogin(UserRole role)
{
string tmp = GetExcludedRolesToLogin();
if (tmp == null) tmp = string.Empty;
string roleKey = ((UserRole)role).ToString();
return !tmp.Contains(roleKey);
}
public static string GetExcludedRolesToLogin()
{
return PortalConfiguration.SiteSettings["ExcludedRolesToLogin"];
}
public static bool GetHideThemeAndLocale()
{
bool bResult = false;
try
{
bResult = Convert.ToBoolean(PortalConfiguration.SiteSettings["HideThemeAndLocale"]);
}
catch (Exception)
{
}
return bResult;
}
public static bool GetHideDemoCheckbox()
{
bool bResult = false;
try
{
bResult = Convert.ToBoolean(PortalConfiguration.SiteSettings["HideDemoCheckbox"]);
}
catch (Exception)
{
}
return bResult;
}
private static int GetAuthenticationFormsTimeout()
{
//default
int retValue = 30;
try
{
AuthenticationSection authenticationSection = WebConfigurationManager.GetSection("system.web/authentication") as AuthenticationSection;
if (authenticationSection != null)
{
FormsAuthenticationConfiguration fac = authenticationSection.Forms;
retValue = (int) Math.Truncate(fac.Timeout.TotalMinutes);
}
}
catch
{
return retValue;
}
return retValue;
}
private static FormsAuthenticationTicket CreateAuthTicket(string username, string password,
UserRole role, bool persistent)
{
return new FormsAuthenticationTicket(
1,
username,
DateTime.Now,
persistent ? DateTime.Now.AddMonths(1) : DateTime.Now.AddMinutes(GetAuthenticationFormsTimeout()),
persistent,
String.Concat(password, Environment.NewLine, Enum.GetName(typeof(UserRole), role))
);
}
public static int ChangeUserPassword(int userId, string newPassword)
{
// load user account
esUsers usersService = new esUsers();
ConfigureEnterpriseServerProxy(usersService, true);
try
{
UserInfo user = usersService.GetUserById(userId);
// change WebsitePanel account password
int result = usersService.ChangeUserPassword(userId, newPassword);
if (result < 0)
return result;
// change auth cookie
if (String.Compare(user.Username, AuthTicket.Name, true) == 0)
{
FormsAuthenticationTicket ticket = CreateAuthTicket(user.Username, newPassword, user.Role, AuthTicket.IsPersistent);
SetAuthTicket(ticket, AuthTicket.IsPersistent);
}
return result;
}
catch (Exception ex)
{
throw ex;
}
}
public static int UpdateUserAccount(UserInfo user)
{
return UpdateUserAccount(null, user);
}
public static int UpdateUserAccount(string taskId, UserInfo user)
{
esUsers usersService = new esUsers();
ConfigureEnterpriseServerProxy(usersService, true);
try
{
// update user in WebsitePanel
return usersService.UpdateUserTask(taskId, user);
}
catch (Exception ex)
{
throw ex;
}
}
public static int AddUserAccount(List<string> log, UserInfo user, bool sendLetter, string password)
{
esUsers usersService = new esUsers();
ConfigureEnterpriseServerProxy(usersService, true);
try
{
// add user to WebsitePanel server
return usersService.AddUser(user, sendLetter, password);
}
catch (Exception ex)
{
throw ex;
}
}
public static int DeleteUserAccount(int userId)
{
esUsers usersService = new esUsers();
ConfigureEnterpriseServerProxy(usersService, true);
try
{
// add user to WebsitePanel server
return usersService.DeleteUser(userId);
}
catch (Exception ex)
{
throw ex;
}
}
public static int ChangeUserStatus(int userId, UserStatus status)
{
esUsers usersService = new esUsers();
ConfigureEnterpriseServerProxy(usersService, true);
try
{
// add user to WebsitePanel server
return usersService.ChangeUserStatus(userId, status);
}
catch (Exception ex)
{
throw ex;
}
}
public static UserInfo GetCurrentUser()
{
UserInfo user = null;
if (AuthTicket != null)
{
esUsers usersService = new esUsers();
ConfigureEnterpriseServerProxy(usersService);
user = usersService.GetUserByUsername(AuthTicket.Name);
}
return user;
}
private static void CompleteUserLogin(string username, bool rememberLogin,
string preferredLocale, string theme)
{
// store last successful username in the cookie
HttpCookie cookie = new HttpCookie("WebsitePanelLogin", username);
cookie.Expires = DateTime.Now.AddDays(7);
cookie.Secure = FormsAuthentication.RequireSSL;
cookie.HttpOnly = true;
HttpContext.Current.Response.Cookies.Add(cookie);
// set language
SetCurrentLanguage(preferredLocale);
// set theme
SetCurrentTheme(theme);
//// remember me
//if (rememberLogin)
// HttpContext.Current.Response.Cookies[FormsAuthentication.FormsCookieName].Expires = DateTime.Now.AddMonths(1);
}
public static void SetCurrentLanguage(string preferredLocale)
{
if (!String.IsNullOrEmpty(preferredLocale))
{
HttpCookie localeCrumb = new HttpCookie(CultureCookieName, preferredLocale);
localeCrumb.Expires = DateTime.Now.AddMonths(2);
HttpContext.Current.Response.Cookies.Add(localeCrumb);
}
}
public static void ConfigureEnterpriseServerProxy(WebServicesClientProtocol proxy)
{
ConfigureEnterpriseServerProxy(proxy, true);
}
public static void ConfigureEnterpriseServerProxy(WebServicesClientProtocol proxy, bool applyPolicy)
{
// load ES properties
string serverUrl = PortalConfiguration.SiteSettings["EnterpriseServer"];
EnterpriseServerProxyConfigurator cnfg = new EnterpriseServerProxyConfigurator();
cnfg.EnterpriseServerUrl = serverUrl;
// create assertion
if (applyPolicy)
{
if (AuthTicket != null)
{
cnfg.Username = AuthTicket.Name;
cnfg.Password = AuthTicket.UserData.Substring(0, AuthTicket.UserData.IndexOf(Environment.NewLine));
}
}
cnfg.Configure(proxy);
}
public static XmlNode GetModuleContentNode(WebPortalControlBase module)
{
XmlNodeList nodes = module.Module.SelectNodes("Content");
return nodes.Count > 0 ? nodes[0] : null;
}
public static XmlNodeList GetModuleMenuItems(WebPortalControlBase module)
{
return module.Module.SelectNodes("MenuItem");
}
public static string FormatIconImageUrl(string url)
{
return url;
}
public static string FormatIconLinkUrl(object url)
{
return DefaultPage.GetPageUrl(url.ToString());
}
public static string GetThemedImage(string imageUrl)
{
Page page = (Page)HttpContext.Current.Handler;
return page.ResolveUrl("~/App_Themes/" + page.Theme + "/Images/" + imageUrl);
}
public static string GetThemedIcon(string iconUrl)
{
Page page = (Page)HttpContext.Current.Handler;
return page.ResolveUrl("~/App_Themes/" + page.Theme + "/" + iconUrl);
}
public static void LoadStatesDropDownList(DropDownList list, string countryCode)
{
string xmlFilePath = HttpContext.Current.Server.MapPath(CONFIG_FOLDER + "CountryStates.config");
list.Items.Clear();
if (File.Exists(xmlFilePath))
{
try
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(xmlFilePath);
List<ListItem> items = new List<ListItem>();
XmlNodeList xmlNodes = xmlDoc.SelectNodes("//State[@countryCode='" + countryCode + "']");
foreach (XmlElement xmlNode in xmlNodes)
{
string nodeName = xmlNode.GetAttribute("name");
string nodeKey = xmlNode.GetAttribute("key");
items.Add(new ListItem(nodeName, nodeKey));
}
list.Items.AddRange(items.ToArray());
}
catch
{
}
}
}
public static void LoadCountriesDropDownList(DropDownList list, string countryToSelect)
{
string countriesPath = HttpContext.Current.Server.MapPath(CONFIG_FOLDER + "Countries.config");
if (File.Exists(countriesPath))
{
try
{
XmlDocument xmlCountriesDoc = new XmlDocument();
xmlCountriesDoc.Load(countriesPath);
List<ListItem> items = new List<ListItem>();
XmlNodeList xmlCountries = xmlCountriesDoc.SelectNodes("//Country");
foreach (XmlElement xmlCountry in xmlCountries)
{
string countryName = xmlCountry.GetAttribute("name");
string countryKey = xmlCountry.GetAttribute("key");
if (String.Compare(countryKey, countryToSelect) == 0)
{
ListItem li = new ListItem(countryName, countryKey);
li.Selected = true;
items.Add(li);
}
else
items.Add(new ListItem(countryName, countryKey));
}
list.Items.AddRange(items.ToArray());
}
catch
{
}
}
}
public static void LoadCultureDropDownList(DropDownList list)
{
string localesPath = HttpContext.Current.Server.MapPath(CONFIG_FOLDER + "SupportedLocales.config");
if (File.Exists(localesPath))
{
string localeToSelect = CurrentCulture.Name;
try
{
XmlDocument xmlLocalesDoc = new XmlDocument();
xmlLocalesDoc.Load(localesPath);
XmlNodeList xmlLocales = xmlLocalesDoc.SelectNodes("//Locale");
for (int i = 0; i < xmlLocales.Count; i++)
{
XmlElement xmlLocale = (XmlElement) xmlLocales[i];
string localeName = xmlLocale.GetAttribute("name");
string localeKey = xmlLocale.GetAttribute("key");
list.Items.Add(new ListItem(localeName, localeKey));
}
HttpCookie localeCrumb = HttpContext.Current.Request.Cookies[CultureCookieName];
if (localeCrumb != null)
{
ListItem item = list.Items.FindByValue(localeToSelect);
if (item != null)
item.Selected = true;
}
else
{
if (list.Items.Count > 0 && list.Items[0] != null)
{
SetCurrentLanguage(list.Items[0].Value);
HttpContext.Current.Response.Redirect(HttpContext.Current.Request.Url.ToString());
}
}
}
catch
{
}
}
}
public static void LoadThemesDropDownList(DropDownList list)
{
string localesPath = HttpContext.Current.Server.MapPath(CONFIG_FOLDER + "SupportedThemes.config");
if (File.Exists(localesPath))
{
string themeToSelect = CurrentTheme;
try
{
XmlDocument doc = new XmlDocument();
doc.Load(localesPath);
XmlNodeList xmlThemes = doc.SelectNodes("//Theme");
for (int i = 0; i < xmlThemes.Count; i++)
{
XmlElement xmlTheme = (XmlElement)xmlThemes[i];
string themeName = xmlTheme.GetAttribute("name");
string themeTitle = xmlTheme.GetAttribute("title");
list.Items.Add(new ListItem(themeTitle, themeName));
if (String.Compare(themeName, themeToSelect) == 0)
list.Items[i].Selected = true;
}
}
catch
{
}
}
}
#region Navigation Routines
public static string LoginRedirectUrl
{
get { return DefaultPage.GetPageUrl(PortalConfiguration.SiteSettings["DefaultPage"]); }
}
public static string GetUserHomePageUrl(int userId)
{
string userHomePageId = PortalConfiguration.SiteSettings["UserHomePage"];
return userId > 0 ? NavigatePageURL(userHomePageId, USER_ID_PARAM, userId.ToString())
: NavigatePageURL(userHomePageId);
}
public static string GetUserCustomersPageId()
{
return PortalConfiguration.SiteSettings["UserCustomersPage"];
}
public static string GetUsersSearchPageId()
{
return PortalConfiguration.SiteSettings["UsersSearchPage"];
}
public static string GetSpacesSearchPageId()
{
return PortalConfiguration.SiteSettings["SpacesSearchPage"];
}
//TODO START
public static string GetObjectSearchPageId()
{
return "SearchObject";
}
//TODO END
public static string GetNestedSpacesPageId()
{
return PortalConfiguration.SiteSettings["NestedSpacesPage"];
}
public static string GetSpaceHomePageUrl(int spaceId)
{
string spaceHomePageId = PortalConfiguration.SiteSettings["SpaceHomePage"];
return spaceId > -1 ? NavigatePageURL(spaceHomePageId, SPACE_ID_PARAM, spaceId.ToString())
: NavigatePageURL(spaceHomePageId);
}
public static string GetLoggedUserAccountPageUrl()
{
return NavigatePageURL(PortalConfiguration.SiteSettings["LoggedUserAccountPage"]);
}
public static string NavigateURL()
{
return NavigateURL(null, null);
}
public static string NavigatePageURL(string pageId)
{
return NavigatePageURL(pageId, null, null, new string[] { });
}
public static string NavigateURL(string keyName, string keyValue, params string[] additionalParams)
{
return NavigatePageURL(HttpContext.Current.Request[DefaultPage.PAGE_ID_PARAM], keyName, keyValue, additionalParams);
}
public static string NavigatePageURL(string pageId, string keyName, string keyValue, params string[] additionalParams)
{
string navigateUrl = DefaultPage.DEFAULT_PAGE;
List<string> urlBuilder = new List<string>();
// add page id parameter
if (!String.IsNullOrEmpty(pageId))
urlBuilder.Add(String.Concat(DefaultPage.PAGE_ID_PARAM, "=", pageId));
// add specified key
if (!String.IsNullOrEmpty(keyName) && !String.IsNullOrEmpty(keyValue))
urlBuilder.Add(String.Concat(keyName, "=", keyValue));
// load additional params
if (additionalParams != null)
{
string controlId = null;
string moduleDefinitionId = null;
//
foreach (string paramStr in additionalParams)
{
if (paramStr.StartsWith("ctl=", StringComparison.InvariantCultureIgnoreCase))
{
// ensure page exists and avoid unnecessary exceptions throw
if (PortalConfiguration.Site.Pages.ContainsKey(pageId))
{
string[] pair = paramStr.Split('=');
controlId = pair[1];
}
}
else if (paramStr.StartsWith("moduleDefId=", StringComparison.InvariantCultureIgnoreCase))
{
// ensure page exists and avoid unnecessary exceptions throw
if (PortalConfiguration.Site.Pages.ContainsKey(pageId))
{
string[] pair = paramStr.Split('=');
moduleDefinitionId = pair[1];
}
continue;
}
urlBuilder.Add(paramStr);
}
if (!String.IsNullOrEmpty(moduleDefinitionId) && !String.IsNullOrEmpty(controlId))
{
// 1. Read module controls first information first
foreach (ModuleDefinition md in PortalConfiguration.ModuleDefinitions.Values)
{
if (String.Equals(md.Id, moduleDefinitionId, StringComparison.InvariantCultureIgnoreCase))
{
// 2. Lookup for module control
foreach (ModuleControl mc in md.Controls.Values)
{
// 3. Compare against ctl parameter value
if (mc.Key.Equals(controlId, StringComparison.InvariantCultureIgnoreCase))
{
// 4. Lookup for module id
foreach (int pmKey in PortalConfiguration.Site.Modules.Keys)
{
PageModule pm = PortalConfiguration.Site.Modules[pmKey];
if (String.Equals(pm.ModuleDefinitionID, md.Id,
StringComparison.InvariantCultureIgnoreCase))
{
// 5. Append module id parameter
urlBuilder.Add("mid=" + pmKey);
goto End;
}
}
}
}
}
}
}
}
End:
if (urlBuilder.Count > 0)
navigateUrl += String.Concat("?", String.Join("&", urlBuilder.ToArray()));
return navigateUrl;
}
public static string EditUrl(string keyName, string keyValue, string controlKey, params string[] additionalParams)
{
List<string> url = new List<string>();
string pageId = HttpContext.Current.Request[DefaultPage.PAGE_ID_PARAM];
if (!String.IsNullOrEmpty(pageId))
url.Add(String.Concat(DefaultPage.PAGE_ID_PARAM, "=", pageId));
url.Add(String.Concat(DefaultPage.MODULE_ID_PARAM, "=", HttpContext.Current.Request.QueryString["mid"]));
url.Add(String.Concat(DefaultPage.CONTROL_ID_PARAM, "=", controlKey));
if (!String.IsNullOrEmpty(keyName) && !String.IsNullOrEmpty(keyValue))
{
url.Add(String.Concat(keyName, "=", keyValue));
}
if (additionalParams != null)
{
foreach (string additionalParam in additionalParams)
url.Add(additionalParam);
}
return "~/Default.aspx?" + String.Join("&", url.ToArray());
}
#endregion
public static string GetGeneralESControlKey(string controlKey)
{
string generalControlKey = string.Empty;
string appData = HttpContext.Current.Server.MapPath(CONFIG_FOLDER);
string xmlFilePath = Path.Combine(appData, EXCHANGE_SERVER_HIERARCHY_FILE);
if (File.Exists(xmlFilePath))
{
try
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(xmlFilePath);
XmlElement xmlNode = (XmlElement)xmlDoc.SelectSingleNode(string.Format("/Controls/Control[@key='{0}']", controlKey));
if (xmlNode.HasAttribute("general_key"))
{
generalControlKey = xmlNode.GetAttribute("general_key");
}
else generalControlKey = xmlNode.GetAttribute("key");
}
catch
{
}
}
return generalControlKey;
}
}
}
/*
//
*/
| |
using System;
using System.Diagnostics;
using System.Collections.Generic;
#if OPENGL
#if MONOMAC
using MonoMac.OpenGL;
#elif WINDOWS || LINUX
using OpenTK.Graphics.OpenGL;
#elif GLES
using OpenTK.Graphics.ES20;
using EnableCap = OpenTK.Graphics.ES20.All;
using FrontFaceDirection = OpenTK.Graphics.ES20.All;
using CullFaceMode = OpenTK.Graphics.ES20.All;
#endif
#elif PSM
using Sce.PlayStation.Core.Graphics;
#endif
namespace Microsoft.Xna.Framework.Graphics
{
public class RasterizerState : GraphicsResource
{
#if DIRECTX
private SharpDX.Direct3D11.RasterizerState _state;
#endif
// TODO: We should be asserting if the state has
// been changed after it has been bound to the device!
public CullMode CullMode { get; set; }
public float DepthBias { get; set; }
public FillMode FillMode { get; set; }
public bool MultiSampleAntiAlias { get; set; }
public bool ScissorTestEnable { get; set; }
public float SlopeScaleDepthBias { get; set; }
private static readonly Utilities.ObjectFactoryWithReset<RasterizerState> _cullClockwise;
private static readonly Utilities.ObjectFactoryWithReset<RasterizerState> _cullCounterClockwise;
private static readonly Utilities.ObjectFactoryWithReset<RasterizerState> _cullNone;
public static RasterizerState CullClockwise { get { return _cullClockwise.Value; } }
public static RasterizerState CullCounterClockwise { get { return _cullCounterClockwise.Value; } }
public static RasterizerState CullNone { get { return _cullNone.Value; } }
public RasterizerState()
{
CullMode = CullMode.CullCounterClockwiseFace;
FillMode = FillMode.Solid;
DepthBias = 0;
MultiSampleAntiAlias = true;
ScissorTestEnable = false;
SlopeScaleDepthBias = 0;
}
static RasterizerState ()
{
_cullClockwise = new Utilities.ObjectFactoryWithReset<RasterizerState>(() => new RasterizerState
{
CullMode = CullMode.CullClockwiseFace
});
_cullCounterClockwise = new Utilities.ObjectFactoryWithReset<RasterizerState>(() => new RasterizerState
{
CullMode = CullMode.CullCounterClockwiseFace
});
_cullNone = new Utilities.ObjectFactoryWithReset<RasterizerState>(() => new RasterizerState
{
CullMode = CullMode.None
});
}
#if OPENGL
internal void ApplyState(GraphicsDevice device)
{
// When rendering offscreen the faces change order.
var offscreen = device.GetRenderTargets().Length > 0;
if (CullMode == CullMode.None)
{
GL.Disable(EnableCap.CullFace);
GraphicsExtensions.CheckGLError();
}
else
{
GL.Enable(EnableCap.CullFace);
GraphicsExtensions.CheckGLError();
GL.CullFace(CullFaceMode.Back);
GraphicsExtensions.CheckGLError();
if (CullMode == CullMode.CullClockwiseFace)
{
if (offscreen)
GL.FrontFace(FrontFaceDirection.Cw);
else
GL.FrontFace(FrontFaceDirection.Ccw);
GraphicsExtensions.CheckGLError();
}
else
{
if (offscreen)
GL.FrontFace(FrontFaceDirection.Ccw);
else
GL.FrontFace(FrontFaceDirection.Cw);
GraphicsExtensions.CheckGLError();
}
}
#if MONOMAC || WINDOWS || LINUX
if (FillMode == FillMode.Solid)
GL.PolygonMode(MaterialFace.FrontAndBack, PolygonMode.Fill);
else
GL.PolygonMode(MaterialFace.FrontAndBack, PolygonMode.Line);
#else
if (FillMode != FillMode.Solid)
throw new NotImplementedException();
#endif
if (ScissorTestEnable)
GL.Enable(EnableCap.ScissorTest);
else
GL.Disable(EnableCap.ScissorTest);
GraphicsExtensions.CheckGLError();
if (this.DepthBias != 0 || this.SlopeScaleDepthBias != 0)
{
GL.Enable(EnableCap.PolygonOffsetFill);
GL.PolygonOffset(this.SlopeScaleDepthBias, this.DepthBias);
}
else
GL.Disable(EnableCap.PolygonOffsetFill);
GraphicsExtensions.CheckGLError();
// TODO: Implement MultiSampleAntiAlias
}
#elif DIRECTX
protected internal override void GraphicsDeviceResetting()
{
SharpDX.Utilities.Dispose(ref _state);
base.GraphicsDeviceResetting();
}
internal void ApplyState(GraphicsDevice device)
{
if (_state == null)
{
// We're now bound to a device... no one should
// be changing the state of this object now!
GraphicsDevice = device;
// Build the description.
var desc = new SharpDX.Direct3D11.RasterizerStateDescription();
switch ( CullMode )
{
case Graphics.CullMode.CullClockwiseFace:
desc.CullMode = SharpDX.Direct3D11.CullMode.Front;
break;
case Graphics.CullMode.CullCounterClockwiseFace:
desc.CullMode = SharpDX.Direct3D11.CullMode.Back;
break;
case Graphics.CullMode.None:
desc.CullMode = SharpDX.Direct3D11.CullMode.None;
break;
}
desc.IsScissorEnabled = ScissorTestEnable;
desc.IsMultisampleEnabled = MultiSampleAntiAlias;
desc.DepthBias = (int)DepthBias;
desc.SlopeScaledDepthBias = SlopeScaleDepthBias;
if (FillMode == Graphics.FillMode.WireFrame)
desc.FillMode = SharpDX.Direct3D11.FillMode.Wireframe;
else
desc.FillMode = SharpDX.Direct3D11.FillMode.Solid;
// These are new DX11 features we should consider exposing
// as part of the extended MonoGame API.
desc.IsFrontCounterClockwise = false;
desc.IsAntialiasedLineEnabled = false;
// To support feature level 9.1 these must
// be set to these exact values.
desc.DepthBiasClamp = 0.0f;
desc.IsDepthClipEnabled = true;
// Create the state.
_state = new SharpDX.Direct3D11.RasterizerState(GraphicsDevice._d3dDevice, desc);
}
Debug.Assert(GraphicsDevice == device, "The state was created for a different device!");
// NOTE: We make the assumption here that the caller has
// locked the d3dContext for us to use.
// Apply the state!
device._d3dContext.Rasterizer.State = _state;
}
internal static void ResetStates()
{
_cullClockwise.Reset();
_cullCounterClockwise.Reset();
_cullNone.Reset();
}
#endif // DIRECTX
#if PSM
static readonly Dictionary<CullMode, CullFaceMode> MapCullMode = new Dictionary<CullMode, CullFaceMode> {
{CullMode.None, CullFaceMode.None},
{CullMode.CullClockwiseFace, CullFaceMode.Front}, // Cull cw
{CullMode.CullCounterClockwiseFace, CullFaceMode.Back}, // Cull ccw
};
internal void ApplyState(GraphicsDevice device)
{
var g = device.Context;
g.SetCullFace(MapCullMode[CullMode], CullFaceDirection.Cw); // Front == cw
g.Enable(EnableMode.CullFace, this.CullMode != CullMode.None);
// FIXME: Everything else
}
#endif
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace System.Linq.Expressions.Tests
{
public static class NonLiftedComparisonLessThanNullableTests
{
#region Test methods
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNonLiftedComparisonLessThanNullableByteTest(bool useInterpreter)
{
byte?[] values = new byte?[] { null, 0, 1, byte.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyComparisonLessThanNullableByte(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNonLiftedComparisonLessThanNullableCharTest(bool useInterpreter)
{
char?[] values = new char?[] { null, '\0', '\b', 'A', '\uffff' };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyComparisonLessThanNullableChar(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNonLiftedComparisonLessThanNullableDecimalTest(bool useInterpreter)
{
decimal?[] values = new decimal?[] { null, decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyComparisonLessThanNullableDecimal(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNonLiftedComparisonLessThanNullableDoubleTest(bool useInterpreter)
{
double?[] values = new double?[] { null, 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyComparisonLessThanNullableDouble(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNonLiftedComparisonLessThanNullableFloatTest(bool useInterpreter)
{
float?[] values = new float?[] { null, 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyComparisonLessThanNullableFloat(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNonLiftedComparisonLessThanNullableIntTest(bool useInterpreter)
{
int?[] values = new int?[] { null, 0, 1, -1, int.MinValue, int.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyComparisonLessThanNullableInt(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNonLiftedComparisonLessThanNullableLongTest(bool useInterpreter)
{
long?[] values = new long?[] { null, 0, 1, -1, long.MinValue, long.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyComparisonLessThanNullableLong(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNonLiftedComparisonLessThanNullableSByteTest(bool useInterpreter)
{
sbyte?[] values = new sbyte?[] { null, 0, 1, -1, sbyte.MinValue, sbyte.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyComparisonLessThanNullableSByte(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNonLiftedComparisonLessThanNullableShortTest(bool useInterpreter)
{
short?[] values = new short?[] { null, 0, 1, -1, short.MinValue, short.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyComparisonLessThanNullableShort(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNonLiftedComparisonLessThanNullableUIntTest(bool useInterpreter)
{
uint?[] values = new uint?[] { null, 0, 1, uint.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyComparisonLessThanNullableUInt(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNonLiftedComparisonLessThanNullableULongTest(bool useInterpreter)
{
ulong?[] values = new ulong?[] { null, 0, 1, ulong.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyComparisonLessThanNullableULong(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNonLiftedComparisonLessThanNullableUShortTest(bool useInterpreter)
{
ushort?[] values = new ushort?[] { null, 0, 1, ushort.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyComparisonLessThanNullableUShort(values[i], values[j], useInterpreter);
}
}
}
#endregion
#region Test verifiers
private static void VerifyComparisonLessThanNullableByte(byte? a, byte? b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.LessThan(
Expression.Constant(a, typeof(byte?)),
Expression.Constant(b, typeof(byte?)),
false,
null));
Func<bool> f = e.Compile(useInterpreter);
bool expected = a < b;
bool result = f();
Assert.Equal(expected, result);
}
private static void VerifyComparisonLessThanNullableChar(char? a, char? b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.LessThan(
Expression.Constant(a, typeof(char?)),
Expression.Constant(b, typeof(char?)),
false,
null));
Func<bool> f = e.Compile(useInterpreter);
bool expected = a < b;
bool result = f();
Assert.Equal(expected, result);
}
private static void VerifyComparisonLessThanNullableDecimal(decimal? a, decimal? b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.LessThan(
Expression.Constant(a, typeof(decimal?)),
Expression.Constant(b, typeof(decimal?)),
false,
null));
Func<bool> f = e.Compile(useInterpreter);
bool expected = a < b;
bool result = f();
Assert.Equal(expected, result);
}
private static void VerifyComparisonLessThanNullableDouble(double? a, double? b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.LessThan(
Expression.Constant(a, typeof(double?)),
Expression.Constant(b, typeof(double?)),
false,
null));
Func<bool> f = e.Compile(useInterpreter);
bool expected = a < b;
bool result = f();
Assert.Equal(expected, result);
}
private static void VerifyComparisonLessThanNullableFloat(float? a, float? b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.LessThan(
Expression.Constant(a, typeof(float?)),
Expression.Constant(b, typeof(float?)),
false,
null));
Func<bool> f = e.Compile(useInterpreter);
bool expected = a < b;
bool result = f();
Assert.Equal(expected, result);
}
private static void VerifyComparisonLessThanNullableInt(int? a, int? b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.LessThan(
Expression.Constant(a, typeof(int?)),
Expression.Constant(b, typeof(int?)),
false,
null));
Func<bool> f = e.Compile(useInterpreter);
bool expected = a < b;
bool result = f();
Assert.Equal(expected, result);
}
private static void VerifyComparisonLessThanNullableLong(long? a, long? b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.LessThan(
Expression.Constant(a, typeof(long?)),
Expression.Constant(b, typeof(long?)),
false,
null));
Func<bool> f = e.Compile(useInterpreter);
bool expected = a < b;
bool result = f();
Assert.Equal(expected, result);
}
private static void VerifyComparisonLessThanNullableSByte(sbyte? a, sbyte? b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.LessThan(
Expression.Constant(a, typeof(sbyte?)),
Expression.Constant(b, typeof(sbyte?)),
false,
null));
Func<bool> f = e.Compile(useInterpreter);
bool expected = a < b;
bool result = f();
Assert.Equal(expected, result);
}
private static void VerifyComparisonLessThanNullableShort(short? a, short? b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.LessThan(
Expression.Constant(a, typeof(short?)),
Expression.Constant(b, typeof(short?)),
false,
null));
Func<bool> f = e.Compile(useInterpreter);
bool expected = a < b;
bool result = f();
Assert.Equal(expected, result);
}
private static void VerifyComparisonLessThanNullableUInt(uint? a, uint? b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.LessThan(
Expression.Constant(a, typeof(uint?)),
Expression.Constant(b, typeof(uint?)),
false,
null));
Func<bool> f = e.Compile(useInterpreter);
bool expected = a < b;
bool result = f();
Assert.Equal(expected, result);
}
private static void VerifyComparisonLessThanNullableULong(ulong? a, ulong? b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.LessThan(
Expression.Constant(a, typeof(ulong?)),
Expression.Constant(b, typeof(ulong?)),
false,
null));
Func<bool> f = e.Compile(useInterpreter);
bool expected = a < b;
bool result = f();
Assert.Equal(expected, result);
}
private static void VerifyComparisonLessThanNullableUShort(ushort? a, ushort? b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.LessThan(
Expression.Constant(a, typeof(ushort?)),
Expression.Constant(b, typeof(ushort?)),
false,
null));
Func<bool> f = e.Compile(useInterpreter);
bool expected = a < b;
bool result = f();
Assert.Equal(expected, result);
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Runtime.InteropServices;
using System.Xml.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Completion;
using Microsoft.CodeAnalysis.CSharp.Formatting;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Editor.Shared.Options;
using Microsoft.CodeAnalysis.ExtractMethod;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Options;
using Microsoft.CodeAnalysis.Simplification;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.Options
{
[ComVisible(true)]
public class AutomationObject
{
private readonly Workspace _workspace;
internal AutomationObject(Workspace workspace)
{
_workspace = workspace;
}
/// <summary>
/// Unused. But kept around for back compat. Note this option is not about
/// turning warning into errors. It's about an aspect of 'remove unused using'
/// functionality we don't support anymore. Namely whether or not 'remove unused
/// using' should warn if you have any build errors as that might mean we
/// remove some usings inappropriately.
/// </summary>
public int WarnOnBuildErrors
{
get { return 0; }
set { }
}
public int AutoComment
{
get { return GetBooleanOption(FeatureOnOffOptions.AutoXmlDocCommentGeneration); }
set { SetBooleanOption(FeatureOnOffOptions.AutoXmlDocCommentGeneration, value); }
}
public int AutoInsertAsteriskForNewLinesOfBlockComments
{
get { return GetBooleanOption(FeatureOnOffOptions.AutoInsertBlockCommentStartString); }
set { SetBooleanOption(FeatureOnOffOptions.AutoInsertBlockCommentStartString, value); }
}
public int BringUpOnIdentifier
{
get { return GetBooleanOption(CompletionOptions.TriggerOnTypingLetters); }
set { SetBooleanOption(CompletionOptions.TriggerOnTypingLetters, value); }
}
public int HighlightMatchingPortionsOfCompletionListItems
{
get { return GetBooleanOption(CompletionOptions.HighlightMatchingPortionsOfCompletionListItems); }
set { SetBooleanOption(CompletionOptions.HighlightMatchingPortionsOfCompletionListItems, value); }
}
public int ShowCompletionItemFilters
{
get { return GetBooleanOption(CompletionOptions.ShowCompletionItemFilters); }
set { SetBooleanOption(CompletionOptions.ShowCompletionItemFilters, value); }
}
[Obsolete("This SettingStore option has now been deprecated in favor of CSharpClosedFileDiagnostics")]
public int ClosedFileDiagnostics
{
get { return GetBooleanOption(ServiceFeatureOnOffOptions.ClosedFileDiagnostic); }
set
{
// Even though this option has been deprecated, we want to respect the setting if the user has explicitly turned off closed file diagnostics (which is the non-default value for 'ClosedFileDiagnostics').
// So, we invoke the setter only for value = 0.
if (value == 0)
{
SetBooleanOption(ServiceFeatureOnOffOptions.ClosedFileDiagnostic, value);
}
}
}
public int CSharpClosedFileDiagnostics
{
get { return GetBooleanOption(ServiceFeatureOnOffOptions.ClosedFileDiagnostic); }
set { SetBooleanOption(ServiceFeatureOnOffOptions.ClosedFileDiagnostic, value); }
}
public int DisplayLineSeparators
{
get { return GetBooleanOption(FeatureOnOffOptions.LineSeparator); }
set { SetBooleanOption(FeatureOnOffOptions.LineSeparator, value); }
}
public int EnableHighlightRelatedKeywords
{
get { return GetBooleanOption(FeatureOnOffOptions.KeywordHighlighting); }
set { SetBooleanOption(FeatureOnOffOptions.KeywordHighlighting, value); }
}
public int EnterOutliningModeOnOpen
{
get { return GetBooleanOption(FeatureOnOffOptions.Outlining); }
set { SetBooleanOption(FeatureOnOffOptions.Outlining, value); }
}
public int ExtractMethod_AllowMovingDeclaration
{
get { return GetBooleanOption(ExtractMethodOptions.AllowMovingDeclaration); }
set { SetBooleanOption(ExtractMethodOptions.AllowMovingDeclaration, value); }
}
public int ExtractMethod_DoNotPutOutOrRefOnStruct
{
get { return GetBooleanOption(ExtractMethodOptions.DontPutOutOrRefOnStruct); }
set { SetBooleanOption(ExtractMethodOptions.DontPutOutOrRefOnStruct, value); }
}
public int Formatting_TriggerOnBlockCompletion
{
get { return GetBooleanOption(FeatureOnOffOptions.AutoFormattingOnCloseBrace); }
set { SetBooleanOption(FeatureOnOffOptions.AutoFormattingOnCloseBrace, value); }
}
public int Formatting_TriggerOnPaste
{
get { return GetBooleanOption(FeatureOnOffOptions.FormatOnPaste); }
set { SetBooleanOption(FeatureOnOffOptions.FormatOnPaste, value); }
}
public int Formatting_TriggerOnStatementCompletion
{
get { return GetBooleanOption(FeatureOnOffOptions.AutoFormattingOnSemicolon); }
set { SetBooleanOption(FeatureOnOffOptions.AutoFormattingOnSemicolon, value); }
}
public int HighlightReferences
{
get { return GetBooleanOption(FeatureOnOffOptions.ReferenceHighlighting); }
set { SetBooleanOption(FeatureOnOffOptions.ReferenceHighlighting, value); }
}
public int Indent_BlockContents
{
get { return GetBooleanOption(CSharpFormattingOptions.IndentBlock); }
set { SetBooleanOption(CSharpFormattingOptions.IndentBlock, value); }
}
public int Indent_Braces
{
get { return GetBooleanOption(CSharpFormattingOptions.IndentBraces); }
set { SetBooleanOption(CSharpFormattingOptions.IndentBraces, value); }
}
public int Indent_CaseContents
{
get { return GetBooleanOption(CSharpFormattingOptions.IndentSwitchCaseSection); }
set { SetBooleanOption(CSharpFormattingOptions.IndentSwitchCaseSection, value); }
}
public int Indent_CaseLabels
{
get { return GetBooleanOption(CSharpFormattingOptions.IndentSwitchSection); }
set { SetBooleanOption(CSharpFormattingOptions.IndentSwitchSection, value); }
}
public int Indent_FlushLabelsLeft
{
get
{
var option = _workspace.Options.GetOption(CSharpFormattingOptions.LabelPositioning);
return option == LabelPositionOptions.LeftMost ? 1 : 0;
}
set
{
_workspace.Options = _workspace.Options.WithChangedOption(CSharpFormattingOptions.LabelPositioning, value == 1 ? LabelPositionOptions.LeftMost : LabelPositionOptions.NoIndent);
}
}
public int Indent_UnindentLabels
{
get
{
return (int)_workspace.Options.GetOption(CSharpFormattingOptions.LabelPositioning);
}
set
{
_workspace.Options = _workspace.Options.WithChangedOption(CSharpFormattingOptions.LabelPositioning, value);
}
}
public int InsertNewlineOnEnterWithWholeWord
{
get { return (int)GetOption(CompletionOptions.EnterKeyBehavior); }
set { SetOption(CompletionOptions.EnterKeyBehavior, (EnterKeyRule)value); }
}
public int EnterKeyBehavior
{
get { return (int)GetOption(CompletionOptions.EnterKeyBehavior); }
set { SetOption(CompletionOptions.EnterKeyBehavior, (EnterKeyRule)value); }
}
public int SnippetsBehavior
{
get { return (int)GetOption(CompletionOptions.SnippetsBehavior); }
set { SetOption(CompletionOptions.SnippetsBehavior, (SnippetsRule)value); }
}
public int NewLines_AnonymousTypeInitializer_EachMember
{
get { return GetBooleanOption(CSharpFormattingOptions.NewLineForMembersInAnonymousTypes); }
set { SetBooleanOption(CSharpFormattingOptions.NewLineForMembersInAnonymousTypes, value); }
}
public int NewLines_Braces_AnonymousMethod
{
get { return GetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInAnonymousMethods); }
set { SetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInAnonymousMethods, value); }
}
public int NewLines_Braces_AnonymousTypeInitializer
{
get { return GetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInAnonymousTypes); }
set { SetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInAnonymousTypes, value); }
}
public int NewLines_Braces_ControlFlow
{
get { return GetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInControlBlocks); }
set { SetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInControlBlocks, value); }
}
public int NewLines_Braces_LambdaExpressionBody
{
get { return GetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInLambdaExpressionBody); }
set { SetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInLambdaExpressionBody, value); }
}
public int NewLines_Braces_Method
{
get { return GetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInMethods); }
set { SetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInMethods, value); }
}
public int NewLines_Braces_Property
{
get { return GetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInProperties); }
set { SetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInProperties, value); }
}
public int NewLines_Braces_Accessor
{
get { return GetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInAccessors); }
set { SetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInAccessors, value); }
}
public int NewLines_Braces_ObjectInitializer
{
get { return GetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInObjectCollectionArrayInitializers); }
set { SetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInObjectCollectionArrayInitializers, value); }
}
public int NewLines_Braces_Type
{
get { return GetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInTypes); }
set { SetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInTypes, value); }
}
public int NewLines_Keywords_Catch
{
get { return GetBooleanOption(CSharpFormattingOptions.NewLineForCatch); }
set { SetBooleanOption(CSharpFormattingOptions.NewLineForCatch, value); }
}
public int NewLines_Keywords_Else
{
get { return GetBooleanOption(CSharpFormattingOptions.NewLineForElse); }
set { SetBooleanOption(CSharpFormattingOptions.NewLineForElse, value); }
}
public int NewLines_Keywords_Finally
{
get { return GetBooleanOption(CSharpFormattingOptions.NewLineForFinally); }
set { SetBooleanOption(CSharpFormattingOptions.NewLineForFinally, value); }
}
public int NewLines_ObjectInitializer_EachMember
{
get { return GetBooleanOption(CSharpFormattingOptions.NewLineForMembersInObjectInit); }
set { SetBooleanOption(CSharpFormattingOptions.NewLineForMembersInObjectInit, value); }
}
public int NewLines_QueryExpression_EachClause
{
get { return GetBooleanOption(CSharpFormattingOptions.NewLineForClausesInQuery); }
set { SetBooleanOption(CSharpFormattingOptions.NewLineForClausesInQuery, value); }
}
public int Refactoring_Verification_Enabled
{
get { return GetBooleanOption(FeatureOnOffOptions.RefactoringVerification); }
set { SetBooleanOption(FeatureOnOffOptions.RefactoringVerification, value); }
}
public int RenameSmartTagEnabled
{
get { return GetBooleanOption(FeatureOnOffOptions.RenameTracking); }
set { SetBooleanOption(FeatureOnOffOptions.RenameTracking, value); }
}
public int RenameTrackingPreview
{
get { return GetBooleanOption(FeatureOnOffOptions.RenameTrackingPreview); }
set { SetBooleanOption(FeatureOnOffOptions.RenameTrackingPreview, value); }
}
public int ShowKeywords
{
get { return 0; }
set { }
}
[Obsolete("Use SnippetsBehavior instead")]
public int ShowSnippets
{
get
{
return GetOption(CompletionOptions.SnippetsBehavior) == SnippetsRule.AlwaysInclude
? 1 : 0;
}
set
{
if (value == 0)
{
SetOption(CompletionOptions.SnippetsBehavior, SnippetsRule.NeverInclude);
}
else
{
SetOption(CompletionOptions.SnippetsBehavior, SnippetsRule.AlwaysInclude);
}
}
}
public int SortUsings_PlaceSystemFirst
{
get { return GetBooleanOption(GenerationOptions.PlaceSystemNamespaceFirst); }
set { SetBooleanOption(GenerationOptions.PlaceSystemNamespaceFirst, value); }
}
public int AddImport_SuggestForTypesInReferenceAssemblies
{
get { return GetBooleanOption(AddImportOptions.SuggestForTypesInReferenceAssemblies); }
set { SetBooleanOption(AddImportOptions.SuggestForTypesInReferenceAssemblies, value); }
}
public int AddImport_SuggestForTypesInNuGetPackages
{
get { return GetBooleanOption(AddImportOptions.SuggestForTypesInNuGetPackages); }
set { SetBooleanOption(AddImportOptions.SuggestForTypesInNuGetPackages, value); }
}
public int Space_AfterBasesColon
{
get { return GetBooleanOption(CSharpFormattingOptions.SpaceAfterColonInBaseTypeDeclaration); }
set { SetBooleanOption(CSharpFormattingOptions.SpaceAfterColonInBaseTypeDeclaration, value); }
}
public int Space_AfterCast
{
get { return GetBooleanOption(CSharpFormattingOptions.SpaceAfterCast); }
set { SetBooleanOption(CSharpFormattingOptions.SpaceAfterCast, value); }
}
public int Space_AfterComma
{
get { return GetBooleanOption(CSharpFormattingOptions.SpaceAfterComma); }
set { SetBooleanOption(CSharpFormattingOptions.SpaceAfterComma, value); }
}
public int Space_AfterDot
{
get { return GetBooleanOption(CSharpFormattingOptions.SpaceAfterDot); }
set { SetBooleanOption(CSharpFormattingOptions.SpaceAfterDot, value); }
}
public int Space_AfterMethodCallName
{
get { return GetBooleanOption(CSharpFormattingOptions.SpaceAfterMethodCallName); }
set { SetBooleanOption(CSharpFormattingOptions.SpaceAfterMethodCallName, value); }
}
public int Space_AfterMethodDeclarationName
{
get { return GetBooleanOption(CSharpFormattingOptions.SpacingAfterMethodDeclarationName); }
set { SetBooleanOption(CSharpFormattingOptions.SpacingAfterMethodDeclarationName, value); }
}
public int Space_AfterSemicolonsInForStatement
{
get { return GetBooleanOption(CSharpFormattingOptions.SpaceAfterSemicolonsInForStatement); }
set { SetBooleanOption(CSharpFormattingOptions.SpaceAfterSemicolonsInForStatement, value); }
}
public int Space_AroundBinaryOperator
{
get
{
var option = _workspace.Options.GetOption(CSharpFormattingOptions.SpacingAroundBinaryOperator);
return option == BinaryOperatorSpacingOptions.Single ? 1 : 0;
}
set
{
var option = value == 1 ? BinaryOperatorSpacingOptions.Single : BinaryOperatorSpacingOptions.Ignore;
_workspace.Options = _workspace.Options.WithChangedOption(CSharpFormattingOptions.SpacingAroundBinaryOperator, option);
}
}
public int Space_BeforeBasesColon
{
get { return GetBooleanOption(CSharpFormattingOptions.SpaceBeforeColonInBaseTypeDeclaration); }
set { SetBooleanOption(CSharpFormattingOptions.SpaceBeforeColonInBaseTypeDeclaration, value); }
}
public int Space_BeforeComma
{
get { return GetBooleanOption(CSharpFormattingOptions.SpaceBeforeComma); }
set { SetBooleanOption(CSharpFormattingOptions.SpaceBeforeComma, value); }
}
public int Space_BeforeDot
{
get { return GetBooleanOption(CSharpFormattingOptions.SpaceBeforeDot); }
set { SetBooleanOption(CSharpFormattingOptions.SpaceBeforeDot, value); }
}
public int Space_BeforeOpenSquare
{
get { return GetBooleanOption(CSharpFormattingOptions.SpaceBeforeOpenSquareBracket); }
set { SetBooleanOption(CSharpFormattingOptions.SpaceBeforeOpenSquareBracket, value); }
}
public int Space_BeforeSemicolonsInForStatement
{
get { return GetBooleanOption(CSharpFormattingOptions.SpaceBeforeSemicolonsInForStatement); }
set { SetBooleanOption(CSharpFormattingOptions.SpaceBeforeSemicolonsInForStatement, value); }
}
public int Space_BetweenEmptyMethodCallParentheses
{
get { return GetBooleanOption(CSharpFormattingOptions.SpaceBetweenEmptyMethodCallParentheses); }
set { SetBooleanOption(CSharpFormattingOptions.SpaceBetweenEmptyMethodCallParentheses, value); }
}
public int Space_BetweenEmptyMethodDeclarationParentheses
{
get { return GetBooleanOption(CSharpFormattingOptions.SpaceBetweenEmptyMethodDeclarationParentheses); }
set { SetBooleanOption(CSharpFormattingOptions.SpaceBetweenEmptyMethodDeclarationParentheses, value); }
}
public int Space_BetweenEmptySquares
{
get { return GetBooleanOption(CSharpFormattingOptions.SpaceBetweenEmptySquareBrackets); }
set { SetBooleanOption(CSharpFormattingOptions.SpaceBetweenEmptySquareBrackets, value); }
}
public int Space_InControlFlowConstruct
{
get { return GetBooleanOption(CSharpFormattingOptions.SpaceAfterControlFlowStatementKeyword); }
set { SetBooleanOption(CSharpFormattingOptions.SpaceAfterControlFlowStatementKeyword, value); }
}
public int Space_WithinCastParentheses
{
get { return GetBooleanOption(CSharpFormattingOptions.SpaceWithinCastParentheses); }
set { SetBooleanOption(CSharpFormattingOptions.SpaceWithinCastParentheses, value); }
}
public int Space_WithinExpressionParentheses
{
get { return GetBooleanOption(CSharpFormattingOptions.SpaceWithinExpressionParentheses); }
set { SetBooleanOption(CSharpFormattingOptions.SpaceWithinExpressionParentheses, value); }
}
public int Space_WithinMethodCallParentheses
{
get { return GetBooleanOption(CSharpFormattingOptions.SpaceWithinMethodCallParentheses); }
set { SetBooleanOption(CSharpFormattingOptions.SpaceWithinMethodCallParentheses, value); }
}
public int Space_WithinMethodDeclarationParentheses
{
get { return GetBooleanOption(CSharpFormattingOptions.SpaceWithinMethodDeclarationParenthesis); }
set { SetBooleanOption(CSharpFormattingOptions.SpaceWithinMethodDeclarationParenthesis, value); }
}
public int Space_WithinOtherParentheses
{
get { return GetBooleanOption(CSharpFormattingOptions.SpaceWithinOtherParentheses); }
set { SetBooleanOption(CSharpFormattingOptions.SpaceWithinOtherParentheses, value); }
}
public int Space_WithinSquares
{
get { return GetBooleanOption(CSharpFormattingOptions.SpaceWithinSquareBrackets); }
set { SetBooleanOption(CSharpFormattingOptions.SpaceWithinSquareBrackets, value); }
}
public string Style_PreferIntrinsicPredefinedTypeKeywordInDeclaration
{
get { return GetXmlOption(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration); }
set { SetXmlOption(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration, value); }
}
public string Style_PreferIntrinsicPredefinedTypeKeywordInMemberAccess
{
get { return GetXmlOption(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess); }
set { SetXmlOption(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, value); }
}
public string Style_NamingPreferences
{
get
{
return _workspace.Options.GetOption(SimplificationOptions.NamingPreferences, LanguageNames.CSharp);
}
set
{
_workspace.Options = _workspace.Options.WithChangedOption(SimplificationOptions.NamingPreferences, LanguageNames.CSharp, value);
}
}
public string Style_QualifyFieldAccess
{
get { return GetXmlOption(CodeStyleOptions.QualifyFieldAccess); }
set { SetXmlOption(CodeStyleOptions.QualifyFieldAccess, value); }
}
public string Style_QualifyPropertyAccess
{
get { return GetXmlOption(CodeStyleOptions.QualifyPropertyAccess); }
set { SetXmlOption(CodeStyleOptions.QualifyPropertyAccess, value); }
}
public string Style_QualifyMethodAccess
{
get { return GetXmlOption(CodeStyleOptions.QualifyMethodAccess); }
set { SetXmlOption(CodeStyleOptions.QualifyMethodAccess, value); }
}
public string Style_QualifyEventAccess
{
get { return GetXmlOption(CodeStyleOptions.QualifyEventAccess); }
set { SetXmlOption(CodeStyleOptions.QualifyEventAccess, value); }
}
public int Style_UseVarWhenDeclaringLocals
{
get { return GetBooleanOption(CSharpCodeStyleOptions.UseVarWhenDeclaringLocals); }
set { SetBooleanOption(CSharpCodeStyleOptions.UseVarWhenDeclaringLocals, value); }
}
public string Style_UseImplicitTypeWherePossible
{
get { return GetXmlOption(CSharpCodeStyleOptions.UseImplicitTypeWherePossible); }
set { SetXmlOption(CSharpCodeStyleOptions.UseImplicitTypeWherePossible, value); }
}
public string Style_UseImplicitTypeWhereApparent
{
get { return GetXmlOption(CSharpCodeStyleOptions.UseImplicitTypeWhereApparent); }
set { SetXmlOption(CSharpCodeStyleOptions.UseImplicitTypeWhereApparent, value); }
}
public string Style_UseImplicitTypeForIntrinsicTypes
{
get { return GetXmlOption(CSharpCodeStyleOptions.UseImplicitTypeForIntrinsicTypes); }
set { SetXmlOption(CSharpCodeStyleOptions.UseImplicitTypeForIntrinsicTypes, value); }
}
public int Wrapping_IgnoreSpacesAroundBinaryOperators
{
get
{
return (int)_workspace.Options.GetOption(CSharpFormattingOptions.SpacingAroundBinaryOperator);
}
set
{
_workspace.Options = _workspace.Options.WithChangedOption(CSharpFormattingOptions.SpacingAroundBinaryOperator, value);
}
}
public int Wrapping_IgnoreSpacesAroundVariableDeclaration
{
get { return GetBooleanOption(CSharpFormattingOptions.SpacesIgnoreAroundVariableDeclaration); }
set { SetBooleanOption(CSharpFormattingOptions.SpacesIgnoreAroundVariableDeclaration, value); }
}
public int Wrapping_KeepStatementsOnSingleLine
{
get { return GetBooleanOption(CSharpFormattingOptions.WrappingKeepStatementsOnSingleLine); }
set { SetBooleanOption(CSharpFormattingOptions.WrappingKeepStatementsOnSingleLine, value); }
}
public int Wrapping_PreserveSingleLine
{
get { return GetBooleanOption(CSharpFormattingOptions.WrappingPreserveSingleLine); }
set { SetBooleanOption(CSharpFormattingOptions.WrappingPreserveSingleLine, value); }
}
private int GetBooleanOption(Option<bool> key)
{
return _workspace.Options.GetOption(key) ? 1 : 0;
}
private int GetBooleanOption(PerLanguageOption<bool> key)
{
return _workspace.Options.GetOption(key, LanguageNames.CSharp) ? 1 : 0;
}
private T GetOption<T>(PerLanguageOption<T> key)
{
return _workspace.Options.GetOption(key, LanguageNames.CSharp);
}
private void SetBooleanOption(Option<bool> key, int value)
{
_workspace.Options = _workspace.Options.WithChangedOption(key, value != 0);
}
private void SetBooleanOption(PerLanguageOption<bool> key, int value)
{
_workspace.Options = _workspace.Options.WithChangedOption(key, LanguageNames.CSharp, value != 0);
}
private void SetOption<T>(PerLanguageOption<T> key, T value)
{
_workspace.Options = _workspace.Options.WithChangedOption(key, LanguageNames.CSharp, value);
}
private int GetBooleanOption(PerLanguageOption<bool?> key)
{
var option = _workspace.Options.GetOption(key, LanguageNames.CSharp);
if (!option.HasValue)
{
return -1;
}
return option.Value ? 1 : 0;
}
private string GetXmlOption(Option<CodeStyleOption<bool>> option)
{
return _workspace.Options.GetOption(option).ToXElement().ToString();
}
private void SetBooleanOption(PerLanguageOption<bool?> key, int value)
{
bool? boolValue = (value < 0) ? (bool?)null : (value > 0);
_workspace.Options = _workspace.Options.WithChangedOption(key, LanguageNames.CSharp, boolValue);
}
private string GetXmlOption(PerLanguageOption<CodeStyleOption<bool>> option)
{
return _workspace.Options.GetOption(option, LanguageNames.CSharp).ToXElement().ToString();
}
private void SetXmlOption(Option<CodeStyleOption<bool>> option, string value)
{
var convertedValue = CodeStyleOption<bool>.FromXElement(XElement.Parse(value));
_workspace.Options = _workspace.Options.WithChangedOption(option, convertedValue);
}
private void SetXmlOption(PerLanguageOption<CodeStyleOption<bool>> option, string value)
{
var convertedValue = CodeStyleOption<bool>.FromXElement(XElement.Parse(value));
_workspace.Options = _workspace.Options.WithChangedOption(option, LanguageNames.CSharp, convertedValue);
}
}
}
| |
using System;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Security.Permissions;
namespace Alphaleonis.Win32.Vss
{
/// <summary>
/// Static class providing access to information about the operating system under which the
/// assembly is executing.
/// </summary>
public static class OperatingSystemInfo
{
#region Public Properties
/// <summary>
/// Gets the named version of the operating system.
/// </summary>
/// <value>The named version of the operating system.</value>
public static OSVersionName OSVersionName
{
get
{
if (s_servicePackVersion == null)
UpdateData();
return s_osVersionName;
}
}
/// <summary>
/// Gets a value indicating whether the operating system is a server os.
/// </summary>
/// <value>
/// <c>true</c> if the current operating system is a server os; otherwise, <c>false</c>.
/// </value>
public static bool IsServer
{
get
{
if (s_servicePackVersion == null)
UpdateData();
return s_isServer;
}
}
/// <summary>
/// Gets the numeric version of the operating system. This is the same as returned by
/// <see cref="System.Environment.OSVersion"/>.
/// </summary>
/// <value>The numeric version of the operating system.</value>
public static Version OSVersion
{
get { return s_osVersion; }
}
/// <summary>
/// Gets the version of the service pack currently installed on the operating system.
/// </summary>
/// <value>The version of the service pack currently installed on the operating system.</value>
/// <remarks>Only the <see cref="Version.Major"/> and <see cref="Version.Minor"/> fields are
/// used.</remarks>
public static Version ServicePackVersion
{
get
{
if (s_servicePackVersion == null)
UpdateData();
return s_servicePackVersion;
}
}
/// <summary>
/// Gets the processor architecture for which the operating system is targeted.
/// </summary>
/// <value>The processor architecture for which the operating system is targeted.</value>
/// <remarks>If running under WOW64 this will return a 32-bit processor. Use <see cref="IsWow64Process"/> to
/// determine if this is the case.
/// </remarks>
public static ProcessorArchitecture ProcessorArchitecture
{
get
{
if (s_servicePackVersion == null)
UpdateData();
return s_processorArchitecture;
}
}
#endregion
#region Public Methods
/// <summary>
/// Determines whether the current process is running under WOW64.
/// </summary>
/// <returns>
/// <c>true</c> if the current process is running under WOW64; otherwise, <c>false</c>.
/// </returns>
public static bool IsWow64Process()
{
IntPtr processHandle = System.Diagnostics.Process.GetCurrentProcess().Handle;
bool value = false;
if (!NativeMethods.IsWow64Process(processHandle, out value))
{
Marshal.ThrowExceptionForHR(Marshal.GetLastWin32Error());
}
return value;
}
/// <summary>
/// Determines whether the operating system is of the specified version or later.
/// </summary>
/// <param name="version">The lowest version for which to return <c>true</c>.</param>
/// <returns>
/// <c>true</c> if the operating system is of the specified <paramref name="version"/> or later; otherwise, <c>false</c>.
/// </returns>
public static bool IsAtLeast(OSVersionName version)
{
return OSVersionName >= version;
}
/// <summary>
/// Determines whether operating system is of the specified version or later, allowing specification of
/// a minimum service pack that must be installed on the lowest version.
/// </summary>
/// <param name="version">The minimum required version.</param>
/// <param name="servicePackVersion">The major version of the service pack that must be installed on the
/// minimum required version to return <c>true</c>. This can be 0 to indicate that no service pack is required.</param>
/// <returns>
/// <c>true</c> if the operating system matches the specified <paramref name="version"/> with the specified service pack, or if the operating system is of a later version; otherwise, <c>false</c>.
/// </returns>
public static bool IsAtLeast(OSVersionName version, int servicePackVersion)
{
return OSVersionName == version && ServicePackVersion.Major >= servicePackVersion || OSVersionName > version;
}
/// <summary>
/// Determines whether operating system is of the specified server version or later or if it is of the specified client
/// version or later and throws <see cref="UnsupportedOperatingSystemException"/> otherwise.
/// </summary>
/// <param name="serverVersion">The minimum server version.</param>
/// <param name="serverServicePackVersion">The minimum server service pack version (applies only if the version exactly matches the specified server version).</param>
/// <param name="clientVersion">The minimum client version.</param>
/// <param name="clientServicePackVersion">The minimum client service pack version (applies only if the version exactly matches the specified client version).</param>
public static void RequireServerOrClientAtLeast(OSVersionName serverVersion, int serverServicePackVersion, OSVersionName clientVersion, int clientServicePackVersion)
{
if (IsServer && !IsAtLeast(serverVersion, serverServicePackVersion) || !IsServer && !IsAtLeast(clientVersion, clientServicePackVersion))
throw new UnsupportedOperatingSystemException();
}
/// <summary>
/// Determines whether the operating system is a server operating system of atleast the specified <paramref name="serverVersion"/> and
/// <paramref name="serverServicePackVersion"/> and throws an <see cref="UnsupportedOperatingSystemException"/> otherwise.
/// </summary>
/// <param name="serverVersion">The server version.</param>
/// <param name="serverServicePackVersion">The server service pack version.</param>
public static void RequireServer(OSVersionName serverVersion, int serverServicePackVersion)
{
if (!IsServer || !IsAtLeast(serverVersion, serverServicePackVersion))
throw new UnsupportedOperatingSystemException();
}
/// <summary>
/// Determines whether the assembly is executing on the specified operating system version or later.
/// If not, an exception is thrown.
/// </summary>
/// <param name="osVersion">The minimum operating system version required.</param>
/// <exception cref="UnsupportedOperatingSystemException">The current operating system is of a version earlier than the specified <paramref name="osVersion"/></exception>
public static void RequireAtLeast(OSVersionName osVersion)
{
if (!IsAtLeast(osVersion))
throw new UnsupportedOperatingSystemException();
}
/// <summary>
/// Determines whether the assembly is executing on the specified operating system version with
/// the specified service pack installed or any later version of windows. If not, an exception is thrown.
/// </summary>
/// <param name="osVersion">The minimum operating system version required.</param>
/// <param name="servicePackVersion">The minimum service pack version required.</param>
/// <exception cref="UnsupportedOperatingSystemException">The current operating system is of a version earlier
/// than the specified <paramref name="osVersion"/> or the versions match but the operating system does not
/// have at least the specified service pack version <paramref name="servicePackVersion"/> installed.</exception>
public static void RequireAtLeast(OSVersionName osVersion, int servicePackVersion)
{
if (!IsAtLeast(osVersion, servicePackVersion))
throw new UnsupportedOperatingSystemException();
}
#endregion
#region Private members
private static void UpdateData()
{
NativeMethods.OSVERSIONINFOEX info = new NativeMethods.OSVERSIONINFOEX();
info.dwOSVersionInfoSize = Marshal.SizeOf(info);
NativeMethods.SYSTEM_INFO sysInfo = new NativeMethods.SYSTEM_INFO();
NativeMethods.GetSystemInfo(out sysInfo);
if (!NativeMethods.GetVersionExW(ref info))
{
Marshal.ThrowExceptionForHR(Marshal.GetLastWin32Error());
}
Debug.Assert(info.dwMajorVersion == Environment.OSVersion.Version.Major);
Debug.Assert(info.dwMinorVersion == Environment.OSVersion.Version.Minor);
Debug.Assert(info.dwBuildNumber == Environment.OSVersion.Version.Build);
s_processorArchitecture = (ProcessorArchitecture)sysInfo.processorArchitecture;
s_servicePackVersion = new Version(info.wServicePackMajor, info.wServicePackMinor);
s_isServer = info.wProductType == NativeMethods.VER_NT_DOMAIN_CONTROLLER || info.wProductType == NativeMethods.VER_NT_SERVER;
if (info.dwMajorVersion > 6)
{
s_osVersionName = OSVersionName.Later;
}
else if (info.dwMajorVersion == 6)
{
if (info.dwMinorVersion == 0) // Windows Vista or Windows Server 2008
{
if (info.wProductType == NativeMethods.VER_NT_WORKSTATION) // Vista
{
s_osVersionName = OSVersionName.WindowsVista;
}
else
{
s_osVersionName = OSVersionName.WindowsServer2008;
}
}
else if (info.dwMinorVersion == 1) // Windows 7 or Windows Server 2008 R2
{
if (info.wProductType == NativeMethods.VER_NT_WORKSTATION)
{
s_osVersionName = Vss.OSVersionName.Windows7;
}
else
{
s_osVersionName = Vss.OSVersionName.WindowsServer2008R2;
}
}
else
{
s_osVersionName = Vss.OSVersionName.Later;
}
}
else if (info.dwMajorVersion == 5)
{
if (info.dwMinorVersion == 0)
{
s_osVersionName = OSVersionName.Windows2000;
}
if (info.dwMinorVersion == 1)
{
s_osVersionName = OSVersionName.WindowsXP;
}
else if (info.dwMinorVersion == 2)
{
if (info.wProductType == NativeMethods.VER_NT_WORKSTATION && s_processorArchitecture == ProcessorArchitecture.X64)
{
s_osVersionName = OSVersionName.WindowsXP;
}
else if (info.wProductType != NativeMethods.VER_NT_WORKSTATION)
{
s_osVersionName = OSVersionName.WindowsServer2003;
}
else
{
s_osVersionName = OSVersionName.Later;
}
}
else
{
s_osVersionName = OSVersionName.Later;
}
}
}
private static OSVersionName s_osVersionName = OSVersionName.Later;
private static Version s_osVersion = Environment.OSVersion.Version;
private static Version s_servicePackVersion;
private static ProcessorArchitecture s_processorArchitecture;
private static bool s_isServer;
#endregion
#region P/Invoke members
private static class NativeMethods
{
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct OSVERSIONINFOEX
{
public int dwOSVersionInfoSize;
public int dwMajorVersion;
public int dwMinorVersion;
public int dwBuildNumber;
public int dwPlatformId;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
public string szCSDVersion;
public UInt16 wServicePackMajor;
public UInt16 wServicePackMinor;
public UInt16 wSuiteMask;
public byte wProductType;
public byte wReserved;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2205:UseManagedEquivalentsOfWin32Api")]
[DllImport("kernel32", CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetVersionExW(ref OSVERSIONINFOEX osvi);
[StructLayout(LayoutKind.Sequential)]
public struct SYSTEM_INFO
{
public ushort processorArchitecture;
ushort reserved;
public uint pageSize;
public IntPtr minimumApplicationAddress;
public IntPtr maximumApplicationAddress;
public IntPtr activeProcessorMask;
public uint numberOfProcessors;
public uint processorType;
public uint allocationGranularity;
public ushort processorLevel;
public ushort processorRevision;
}
[DllImport("kernel32.dll")]
public static extern void GetSystemInfo(out SYSTEM_INFO lpSystemInfo);
public const short VER_NT_WORKSTATION = 1;
public const short VER_NT_DOMAIN_CONTROLLER = 2;
public const short VER_NT_SERVER = 3;
[DllImport("kernel32.dll", SetLastError = true, CallingConvention = CallingConvention.Winapi)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool IsWow64Process(
[In] IntPtr hProcess,
[Out, MarshalAs(UnmanagedType.Bool)] out bool lpSystemInfo
);
}
#endregion
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
namespace DalSic
{
/// <summary>
/// Strongly-typed collection for the MamMaterial class.
/// </summary>
[Serializable]
public partial class MamMaterialCollection : ActiveList<MamMaterial, MamMaterialCollection>
{
public MamMaterialCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>MamMaterialCollection</returns>
public MamMaterialCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
MamMaterial o = this[i];
foreach (SubSonic.Where w in this.wheres)
{
bool remove = false;
System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName);
if (pi.CanRead)
{
object val = pi.GetValue(o, null);
switch (w.Comparison)
{
case SubSonic.Comparison.Equals:
if (!val.Equals(w.ParameterValue))
{
remove = true;
}
break;
}
}
if (remove)
{
this.Remove(o);
break;
}
}
}
return this;
}
}
/// <summary>
/// This is an ActiveRecord class which wraps the MAM_Material table.
/// </summary>
[Serializable]
public partial class MamMaterial : ActiveRecord<MamMaterial>, IActiveRecord
{
#region .ctors and Default Settings
public MamMaterial()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public MamMaterial(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public MamMaterial(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public MamMaterial(string columnName, object columnValue)
{
SetSQLProps();
InitSetDefaults();
LoadByParam(columnName,columnValue);
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
SetSQLProps();
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("MAM_Material", TableType.Table, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarIdMaterial = new TableSchema.TableColumn(schema);
colvarIdMaterial.ColumnName = "idMaterial";
colvarIdMaterial.DataType = DbType.Int32;
colvarIdMaterial.MaxLength = 0;
colvarIdMaterial.AutoIncrement = true;
colvarIdMaterial.IsNullable = false;
colvarIdMaterial.IsPrimaryKey = true;
colvarIdMaterial.IsForeignKey = false;
colvarIdMaterial.IsReadOnly = false;
colvarIdMaterial.DefaultSetting = @"";
colvarIdMaterial.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdMaterial);
TableSchema.TableColumn colvarDescripcion = new TableSchema.TableColumn(schema);
colvarDescripcion.ColumnName = "descripcion";
colvarDescripcion.DataType = DbType.AnsiString;
colvarDescripcion.MaxLength = 20;
colvarDescripcion.AutoIncrement = false;
colvarDescripcion.IsNullable = false;
colvarDescripcion.IsPrimaryKey = false;
colvarDescripcion.IsForeignKey = false;
colvarDescripcion.IsReadOnly = false;
colvarDescripcion.DefaultSetting = @"('')";
colvarDescripcion.ForeignKeyTableName = "";
schema.Columns.Add(colvarDescripcion);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("MAM_Material",schema);
}
}
#endregion
#region Props
[XmlAttribute("IdMaterial")]
[Bindable(true)]
public int IdMaterial
{
get { return GetColumnValue<int>(Columns.IdMaterial); }
set { SetColumnValue(Columns.IdMaterial, value); }
}
[XmlAttribute("Descripcion")]
[Bindable(true)]
public string Descripcion
{
get { return GetColumnValue<string>(Columns.Descripcion); }
set { SetColumnValue(Columns.Descripcion, value); }
}
#endregion
#region PrimaryKey Methods
protected override void SetPrimaryKey(object oValue)
{
base.SetPrimaryKey(oValue);
SetPKValues();
}
private DalSic.MamCirugiumCollection colMamCirugia;
public DalSic.MamCirugiumCollection MamCirugia
{
get
{
if(colMamCirugia == null)
{
colMamCirugia = new DalSic.MamCirugiumCollection().Where(MamCirugium.Columns.IdMaterialDer, IdMaterial).Load();
colMamCirugia.ListChanged += new ListChangedEventHandler(colMamCirugia_ListChanged);
}
return colMamCirugia;
}
set
{
colMamCirugia = value;
colMamCirugia.ListChanged += new ListChangedEventHandler(colMamCirugia_ListChanged);
}
}
void colMamCirugia_ListChanged(object sender, ListChangedEventArgs e)
{
if (e.ListChangedType == ListChangedType.ItemAdded)
{
// Set foreign key value
colMamCirugia[e.NewIndex].IdMaterialDer = IdMaterial;
}
}
private DalSic.MamCirugiumCollection colMamCirugiaFromMamMaterial;
public DalSic.MamCirugiumCollection MamCirugiaFromMamMaterial
{
get
{
if(colMamCirugiaFromMamMaterial == null)
{
colMamCirugiaFromMamMaterial = new DalSic.MamCirugiumCollection().Where(MamCirugium.Columns.IdMaterialIzq, IdMaterial).Load();
colMamCirugiaFromMamMaterial.ListChanged += new ListChangedEventHandler(colMamCirugiaFromMamMaterial_ListChanged);
}
return colMamCirugiaFromMamMaterial;
}
set
{
colMamCirugiaFromMamMaterial = value;
colMamCirugiaFromMamMaterial.ListChanged += new ListChangedEventHandler(colMamCirugiaFromMamMaterial_ListChanged);
}
}
void colMamCirugiaFromMamMaterial_ListChanged(object sender, ListChangedEventArgs e)
{
if (e.ListChangedType == ListChangedType.ItemAdded)
{
// Set foreign key value
colMamCirugiaFromMamMaterial[e.NewIndex].IdMaterialIzq = IdMaterial;
}
}
#endregion
//no foreign key tables defined (0)
//no ManyToMany tables defined (0)
#region ObjectDataSource support
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
public static void Insert(string varDescripcion)
{
MamMaterial item = new MamMaterial();
item.Descripcion = varDescripcion;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
public static void Update(int varIdMaterial,string varDescripcion)
{
MamMaterial item = new MamMaterial();
item.IdMaterial = varIdMaterial;
item.Descripcion = varDescripcion;
item.IsNew = false;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
#endregion
#region Typed Columns
public static TableSchema.TableColumn IdMaterialColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn DescripcionColumn
{
get { return Schema.Columns[1]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string IdMaterial = @"idMaterial";
public static string Descripcion = @"descripcion";
}
#endregion
#region Update PK Collections
public void SetPKValues()
{
if (colMamCirugia != null)
{
foreach (DalSic.MamCirugium item in colMamCirugia)
{
if (item.IdMaterialDer != IdMaterial)
{
item.IdMaterialDer = IdMaterial;
}
}
}
if (colMamCirugiaFromMamMaterial != null)
{
foreach (DalSic.MamCirugium item in colMamCirugiaFromMamMaterial)
{
if (item.IdMaterialIzq != IdMaterial)
{
item.IdMaterialIzq = IdMaterial;
}
}
}
}
#endregion
#region Deep Save
public void DeepSave()
{
Save();
if (colMamCirugia != null)
{
colMamCirugia.SaveAll();
}
if (colMamCirugiaFromMamMaterial != null)
{
colMamCirugiaFromMamMaterial.SaveAll();
}
}
#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.Data.Common;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
namespace System.Data.SqlClient
{
sealed internal class SqlSequentialStream : System.IO.Stream
{
private SqlDataReader _reader; // The SqlDataReader that we are reading data from
private int _columnIndex; // The index of out column in the table
private Task _currentTask; // Holds the current task being processed
private int _readTimeout; // Read timeout for this stream in ms (for Stream.ReadTimeout)
private CancellationTokenSource _disposalTokenSource; // Used to indicate that a cancellation is requested due to disposal
internal SqlSequentialStream(SqlDataReader reader, int columnIndex)
{
Debug.Assert(reader != null, "Null reader when creating sequential stream");
Debug.Assert(columnIndex >= 0, "Invalid column index when creating sequential stream");
_reader = reader;
_columnIndex = columnIndex;
_currentTask = null;
_disposalTokenSource = new CancellationTokenSource();
// Safely convert the CommandTimeout from seconds to milliseconds
if ((reader.Command != null) && (reader.Command.CommandTimeout != 0))
{
_readTimeout = (int)Math.Min((long)reader.Command.CommandTimeout * 1000L, (long)Int32.MaxValue);
}
else
{
_readTimeout = Timeout.Infinite;
}
}
public override bool CanRead
{
get { return ((_reader != null) && (!_reader.IsClosed)); }
}
public override bool CanSeek
{
get { return false; }
}
public override bool CanTimeout
{
get { return true; }
}
public override bool CanWrite
{
get { return false; }
}
public override void Flush()
{ }
public override long Length
{
get { throw ADP.NotSupported(); }
}
public override long Position
{
get { throw ADP.NotSupported(); }
set { throw ADP.NotSupported(); }
}
public override int ReadTimeout
{
get { return _readTimeout; }
set
{
if ((value > 0) || (value == Timeout.Infinite))
{
_readTimeout = value;
}
else
{
throw ADP.ArgumentOutOfRange(nameof(value));
}
}
}
internal int ColumnIndex
{
get { return _columnIndex; }
}
public override int Read(byte[] buffer, int offset, int count)
{
ValidateReadParameters(buffer, offset, count);
if (!CanRead)
{
throw ADP.ObjectDisposed(this);
}
if (_currentTask != null)
{
throw ADP.AsyncOperationPending();
}
try
{
return _reader.GetBytesInternalSequential(_columnIndex, buffer, offset, count, _readTimeout);
}
catch (SqlException ex)
{
// Stream.Read() can't throw a SqlException - so wrap it in an IOException
throw ADP.ErrorReadingFromStream(ex);
}
}
public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
ValidateReadParameters(buffer, offset, count);
TaskCompletionSource<int> completion = new TaskCompletionSource<int>();
if (!CanRead)
{
completion.SetException(ADP.ExceptionWithStackTrace(ADP.ObjectDisposed(this)));
}
else
{
try
{
Task original = Interlocked.CompareExchange<Task>(ref _currentTask, completion.Task, null);
if (original != null)
{
completion.SetException(ADP.ExceptionWithStackTrace(ADP.AsyncOperationPending()));
}
else
{
// Set up a combined cancellation token for both the user's and our disposal tokens
CancellationTokenSource combinedTokenSource;
if (!cancellationToken.CanBeCanceled)
{
// Users token is not cancellable - just use ours
combinedTokenSource = _disposalTokenSource;
}
else
{
// Setup registrations from user and disposal token to cancel the combined token
combinedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _disposalTokenSource.Token);
}
int bytesRead = 0;
Task<int> getBytesTask = null;
var reader = _reader;
if ((reader != null) && (!cancellationToken.IsCancellationRequested) && (!_disposalTokenSource.Token.IsCancellationRequested))
{
getBytesTask = reader.GetBytesAsync(_columnIndex, buffer, offset, count, _readTimeout, combinedTokenSource.Token, out bytesRead);
}
if (getBytesTask == null)
{
_currentTask = null;
if (cancellationToken.IsCancellationRequested)
{
completion.SetCanceled();
}
else if (!CanRead)
{
completion.SetException(ADP.ExceptionWithStackTrace(ADP.ObjectDisposed(this)));
}
else
{
completion.SetResult(bytesRead);
}
if (combinedTokenSource != _disposalTokenSource)
{
combinedTokenSource.Dispose();
}
}
else
{
getBytesTask.ContinueWith((t) =>
{
_currentTask = null;
// If we completed, but _reader is null (i.e. the stream is closed), then report cancellation
if ((t.Status == TaskStatus.RanToCompletion) && (CanRead))
{
completion.SetResult((int)t.Result);
}
else if (t.Status == TaskStatus.Faulted)
{
if (t.Exception.InnerException is SqlException)
{
// Stream.ReadAsync() can't throw a SqlException - so wrap it in an IOException
completion.SetException(ADP.ExceptionWithStackTrace(ADP.ErrorReadingFromStream(t.Exception.InnerException)));
}
else
{
completion.SetException(t.Exception.InnerException);
}
}
else if (!CanRead)
{
completion.SetException(ADP.ExceptionWithStackTrace(ADP.ObjectDisposed(this)));
}
else
{
completion.SetCanceled();
}
if (combinedTokenSource != _disposalTokenSource)
{
combinedTokenSource.Dispose();
}
}, TaskScheduler.Default);
}
}
}
catch (Exception ex)
{
// In case of any errors, ensure that the completion is completed and the task is set back to null if we switched it
completion.TrySetException(ex);
Interlocked.CompareExchange(ref _currentTask, null, completion.Task);
throw;
}
}
return completion.Task;
}
public override IAsyncResult BeginRead(byte[] array, int offset, int count, AsyncCallback asyncCallback, object asyncState) =>
TaskToApm.Begin(ReadAsync(array, offset, count, CancellationToken.None), asyncCallback, asyncState);
public override int EndRead(IAsyncResult asyncResult) =>
TaskToApm.End<int>(asyncResult);
public override long Seek(long offset, IO.SeekOrigin origin)
{
throw ADP.NotSupported();
}
public override void SetLength(long value)
{
throw ADP.NotSupported();
}
public override void Write(byte[] buffer, int offset, int count)
{
throw ADP.NotSupported();
}
/// <summary>
/// Forces the stream to act as if it was closed (i.e. CanRead=false and Read() throws)
/// This does not actually close the stream, read off the rest of the data or dispose this
/// </summary>
internal void SetClosed()
{
_disposalTokenSource.Cancel();
_reader = null;
// Wait for pending task
var currentTask = _currentTask;
if (currentTask != null)
{
((IAsyncResult)currentTask).AsyncWaitHandle.WaitOne();
}
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
// Set the stream as closed
SetClosed();
}
base.Dispose(disposing);
}
/// <summary>
/// Checks the parameters passed into a Read() method are valid
/// </summary>
/// <param name="buffer"></param>
/// <param name="index"></param>
/// <param name="count"></param>
internal static void ValidateReadParameters(byte[] buffer, int offset, int count)
{
if (buffer == null)
{
throw ADP.ArgumentNull(nameof(buffer));
}
if (offset < 0)
{
throw ADP.ArgumentOutOfRange(nameof(offset));
}
if (count < 0)
{
throw ADP.ArgumentOutOfRange(nameof(count));
}
try
{
if (checked(offset + count) > buffer.Length)
{
throw ExceptionBuilder.InvalidOffsetLength();
}
}
catch (OverflowException)
{
// If we've overflowed when adding offset and count, then they never would have fit into buffer anyway
throw ExceptionBuilder.InvalidOffsetLength();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace MusicCatalogue.Services.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try get sample provided for a specific mediaType, controllerName, actionName and parameterNames.
// If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames
// If still not found, try get the sample provided for a specific type and mediaType
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create one using <see cref="ObjectGenerator"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// Try create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
sampleObject = objectGenerator.GenerateObject(type);
}
return sampleObject;
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ActionDescriptor.ReturnType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
e.Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Net.Test.Common;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace System.Net.Sockets.Tests
{
public class SocketOptionNameTest
{
private static bool SocketsReuseUnicastPortSupport
{
get
{
return Capability.SocketsReuseUnicastPortSupport();
}
}
private static bool NoSocketsReuseUnicastPortSupport
{
get
{
return !Capability.SocketsReuseUnicastPortSupport();
}
}
[ActiveIssue(11088, PlatformID.Windows)]
[ConditionalFact(nameof(NoSocketsReuseUnicastPortSupport))]
public void ReuseUnicastPort_CreateSocketGetOption_NoSocketsReuseUnicastPortSupport_Throws()
{
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Assert.Throws<SocketException>(() =>
socket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseUnicastPort));
}
[ConditionalFact(nameof(SocketsReuseUnicastPortSupport))]
public void ReuseUnicastPort_CreateSocketGetOption_SocketsReuseUnicastPortSupport_OptionIsZero()
{
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
var optionValue = (int)socket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseUnicastPort);
Assert.Equal(0, optionValue);
}
[ActiveIssue(11088, PlatformID.Windows)]
[ConditionalFact(nameof(NoSocketsReuseUnicastPortSupport))]
public void ReuseUnicastPort_CreateSocketSetOption_NoSocketsReuseUnicastPortSupport_Throws()
{
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Assert.Throws<SocketException>(() =>
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseUnicastPort, 1));
}
[ConditionalFact(nameof(SocketsReuseUnicastPortSupport))]
public void ReuseUnicastPort_CreateSocketSetOptionToZeroAndGetOption_SocketsReuseUnicastPortSupport_OptionIsZero()
{
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseUnicastPort, 0);
int optionValue = (int)socket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseUnicastPort);
Assert.Equal(0, optionValue);
}
// TODO: Issue #4887
// The socket option 'ReuseUnicastPost' only works on Windows 10 systems. In addition, setting the option
// is a no-op unless specialized network settings using PowerShell configuration are first applied to the
// machine. This is currently difficult to test in the CI environment. So, this ests will be disabled for now
[ActiveIssue(4887)]
public void ReuseUnicastPort_CreateSocketSetOptionToOneAndGetOption_SocketsReuseUnicastPortSupport_OptionIsOne()
{
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseUnicastPort, 1);
int optionValue = (int)socket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseUnicastPort);
Assert.Equal(1, optionValue);
}
[Fact]
public void MulticastOption_CreateSocketSetGetOption_GroupAndInterfaceIndex_SetSucceeds_GetThrows()
{
int interfaceIndex = 0;
IPAddress groupIp = IPAddress.Parse("239.1.2.3");
using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
{
socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(groupIp, interfaceIndex));
Assert.Throws<SocketException>(() => socket.GetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership));
}
}
[Fact]
public async Task MulticastInterface_Set_AnyInterface_Succeeds()
{
// On all platforms, index 0 means "any interface"
await MulticastInterface_Set_Helper(0);
}
[Fact]
[PlatformSpecific(PlatformID.Windows)] // see comment below
public async Task MulticastInterface_Set_Loopback_Succeeds()
{
// On Windows, we can apparently assume interface 1 is "loopback." On other platforms, this is not a
// valid assumption. We could maybe use NetworkInterface.LoopbackInterfaceIndex to get the index, but
// this would introduce a dependency on System.Net.NetworkInformation, which depends on System.Net.Sockets,
// which is what we're testing here.... So for now, we'll just assume "loopback == 1" and run this on
// Windows only.
await MulticastInterface_Set_Helper(1);
}
private async Task MulticastInterface_Set_Helper(int interfaceIndex)
{
IPAddress multicastAddress = IPAddress.Parse("239.1.2.3");
string message = "hello";
int port;
using (Socket receiveSocket = CreateBoundUdpSocket(out port),
sendSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
{
receiveSocket.ReceiveTimeout = 1000;
receiveSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(multicastAddress, interfaceIndex));
sendSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastInterface, IPAddress.HostToNetworkOrder(interfaceIndex));
var receiveBuffer = new byte[1024];
var receiveTask = receiveSocket.ReceiveAsync(new ArraySegment<byte>(receiveBuffer), SocketFlags.None);
for (int i = 0; i < TestSettings.UDPRedundancy; i++)
{
sendSocket.SendTo(Encoding.UTF8.GetBytes(message), new IPEndPoint(multicastAddress, port));
}
int bytesReceived = await receiveTask;
string receivedMessage = Encoding.UTF8.GetString(receiveBuffer, 0, bytesReceived);
Assert.Equal(receivedMessage, message);
}
}
[Fact]
public void MulticastInterface_Set_InvalidIndex_Throws()
{
int interfaceIndex = 31415;
using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
{
Assert.Throws<SocketException>(() =>
s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastInterface, IPAddress.HostToNetworkOrder(interfaceIndex)));
}
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void FailedConnect_GetSocketOption_SocketOptionNameError(bool simpleGet)
{
using (var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) { Blocking = false })
{
// Fail a Connect
using (var server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
server.Bind(new IPEndPoint(IPAddress.Loopback, 0)); // bind but don't listen
Assert.ThrowsAny<Exception>(() => client.Connect(server.LocalEndPoint));
}
// Verify via Select that there's an error
const int FailedTimeout = 10 * 1000 * 1000; // 10 seconds
var errorList = new List<Socket> { client };
Socket.Select(null, null, errorList, FailedTimeout);
Assert.Equal(1, errorList.Count);
// Get the last error and validate it's what's expected
int errorCode;
if (simpleGet)
{
errorCode = (int)client.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Error);
}
else
{
byte[] optionValue = new byte[sizeof(int)];
client.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Error, optionValue);
errorCode = BitConverter.ToInt32(optionValue, 0);
}
Assert.Equal((int)SocketError.ConnectionRefused, errorCode);
// Then get it again
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
// The Windows implementation doesn't clear the error code after retrieved.
// https://github.com/dotnet/corefx/issues/8464
Assert.Equal(errorCode, (int)client.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Error));
}
else
{
// The Unix implementation matches the getsockopt and MSDN docs and clears the error code as part of retrieval.
Assert.Equal((int)SocketError.Success, (int)client.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Error));
}
}
}
// Create an Udp Socket and binds it to an available port
private static Socket CreateBoundUdpSocket(out int localPort)
{
Socket receiveSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
// sending a message will bind the socket to an available port
string sendMessage = "dummy message";
int port = 54320;
IPAddress multicastAddress = IPAddress.Parse("239.1.1.1");
receiveSocket.SendTo(Encoding.UTF8.GetBytes(sendMessage), new IPEndPoint(multicastAddress, port));
localPort = (receiveSocket.LocalEndPoint as IPEndPoint).Port;
return receiveSocket;
}
}
}
| |
/* ====================================================================
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 NPOI.Util;
using System.Text;
using System;
namespace NPOI.HWPF.Model.Types
{
/**
* List Format Override (LFO).
* <p>
* Class and fields descriptions are quoted from Microsoft Office Word 97-2007
* Binary File Format
*
* NOTE: This source is automatically generated please do not modify this file.
* Either subclass or remove the record in src/types/defInitions.
*
* @author Sergey Vladimirov; according to Microsoft Office Word 97-2007 Binary
* File Format Specification [*.doc]
*/
public abstract class LFOAbstractType : BaseObject
{
protected int field_1_lsid;
protected int field_2_reserved1;
protected int field_3_reserved2;
protected byte field_4_clfolvl;
protected byte field_5_ibstFltAutoNum;
protected byte field_6_grfhic;
private static BitField fHtmlChecked = new BitField(0x01);
private static BitField fHtmlUnsupported = new BitField(0x02);
private static BitField fHtmlListTextNotSharpDot = new BitField(0x04);
private static BitField fHtmlNotPeriod = new BitField(0x08);
private static BitField fHtmlFirstLineMismatch = new BitField(0x10);
private static BitField fHtmlTabLeftIndentMismatch = new BitField(
0x20);
private static BitField fHtmlHangingIndentBeneathNumber = new BitField(
0x40);
private static BitField fHtmlBuiltInBullet = new BitField(0x80);
protected byte field_7_reserved3;
protected LFOAbstractType()
{
}
protected void FillFields(byte[] data, int offset)
{
field_1_lsid = LittleEndian.GetInt(data, 0x0 + offset);
field_2_reserved1 = LittleEndian.GetInt(data, 0x4 + offset);
field_3_reserved2 = LittleEndian.GetInt(data, 0x8 + offset);
field_4_clfolvl = data[0xc + offset];
field_5_ibstFltAutoNum = data[0xd + offset];
field_6_grfhic = data[0xe + offset];
field_7_reserved3 = data[0xf + offset];
}
public void Serialize(byte[] data, int offset)
{
LittleEndian.PutInt(data, 0x0 + offset, field_1_lsid);
LittleEndian.PutInt(data, 0x4 + offset, field_2_reserved1);
LittleEndian.PutInt(data, 0x8 + offset, field_3_reserved2);
data[0xc + offset] = field_4_clfolvl;
data[0xd + offset] = field_5_ibstFltAutoNum;
data[0xe + offset] = field_6_grfhic;
data[0xf + offset] = field_7_reserved3;
}
/**
* Size of record
*/
public static int GetSize()
{
return 0 + 4 + 4 + 4 + 1 + 1 + 1 + 1;
}
public override String ToString()
{
StringBuilder builder = new StringBuilder();
builder.Append("[LFO]\n");
builder.Append(" .lsid = ");
builder.Append(" (").Append(GetLsid()).Append(" )\n");
builder.Append(" .reserved1 = ");
builder.Append(" (").Append(GetReserved1()).Append(" )\n");
builder.Append(" .reserved2 = ");
builder.Append(" (").Append(GetReserved2()).Append(" )\n");
builder.Append(" .clfolvl = ");
builder.Append(" (").Append(GetClfolvl()).Append(" )\n");
builder.Append(" .ibstFltAutoNum = ");
builder.Append(" (").Append(GetIbstFltAutoNum()).Append(" )\n");
builder.Append(" .grfhic = ");
builder.Append(" (").Append(GetGrfhic()).Append(" )\n");
builder.Append(" .fHtmlChecked = ")
.Append(IsFHtmlChecked()).Append('\n');
builder.Append(" .fHtmlUnsupported = ")
.Append(IsFHtmlUnsupported()).Append('\n');
builder.Append(" .fHtmlListTextNotSharpDot = ")
.Append(IsFHtmlListTextNotSharpDot()).Append('\n');
builder.Append(" .fHtmlNotPeriod = ")
.Append(IsFHtmlNotPeriod()).Append('\n');
builder.Append(" .fHtmlFirstLineMismatch = ")
.Append(IsFHtmlFirstLineMismatch()).Append('\n');
builder.Append(" .fHtmlTabLeftIndentMismatch = ")
.Append(IsFHtmlTabLeftIndentMismatch()).Append('\n');
builder.Append(" .fHtmlHangingIndentBeneathNumber = ")
.Append(IsFHtmlHangingIndentBeneathNumber()).Append('\n');
builder.Append(" .fHtmlBuiltInBullet = ")
.Append(IsFHtmlBuiltInBullet()).Append('\n');
builder.Append(" .reserved3 = ");
builder.Append(" (").Append(GetReserved3()).Append(" )\n");
builder.Append("[/LFO]\n");
return builder.ToString();
}
/**
* List ID of corresponding LSTF (see LSTF).
*/
public int GetLsid()
{
return field_1_lsid;
}
/**
* List ID of corresponding LSTF (see LSTF).
*/
public void SetLsid(int field_1_lsid)
{
this.field_1_lsid = field_1_lsid;
}
/**
* Reserved.
*/
public int GetReserved1()
{
return field_2_reserved1;
}
/**
* Reserved.
*/
public void SetReserved1(int field_2_reserved1)
{
this.field_2_reserved1 = field_2_reserved1;
}
/**
* Reserved.
*/
public int GetReserved2()
{
return field_3_reserved2;
}
/**
* Reserved.
*/
public void SetReserved2(int field_3_reserved2)
{
this.field_3_reserved2 = field_3_reserved2;
}
/**
* Count of levels whose format is overridden (see LFOLVL).
*/
public byte GetClfolvl()
{
return field_4_clfolvl;
}
/**
* Count of levels whose format is overridden (see LFOLVL).
*/
public void SetClfolvl(byte field_4_clfolvl)
{
this.field_4_clfolvl = field_4_clfolvl;
}
/**
* Used for AUTONUM field emulation.
*/
public byte GetIbstFltAutoNum()
{
return field_5_ibstFltAutoNum;
}
/**
* Used for AUTONUM field emulation.
*/
public void SetIbstFltAutoNum(byte field_5_ibstFltAutoNum)
{
this.field_5_ibstFltAutoNum = field_5_ibstFltAutoNum;
}
/**
* HTML compatibility flags.
*/
public byte GetGrfhic()
{
return field_6_grfhic;
}
/**
* HTML compatibility flags.
*/
public void SetGrfhic(byte field_6_grfhic)
{
this.field_6_grfhic = field_6_grfhic;
}
/**
* Reserved.
*/
public byte GetReserved3()
{
return field_7_reserved3;
}
/**
* Reserved.
*/
public void SetReserved3(byte field_7_reserved3)
{
this.field_7_reserved3 = field_7_reserved3;
}
/**
* Sets the fHtmlChecked field value. Checked
*/
public void SetFHtmlChecked(bool value)
{
field_6_grfhic = (byte)fHtmlChecked.SetBoolean(field_6_grfhic, value);
}
/**
* Checked
*
* @return the fHtmlChecked field value.
*/
public bool IsFHtmlChecked()
{
return fHtmlChecked.IsSet(field_6_grfhic);
}
/**
* Sets the fHtmlUnsupported field value. The numbering sequence or format
* is unsupported (includes tab & size)
*/
public void SetFHtmlUnsupported(bool value)
{
field_6_grfhic = (byte)fHtmlUnsupported.SetBoolean(field_6_grfhic,
value);
}
/**
* The numbering sequence or format is unsupported (includes tab & size)
*
* @return the fHtmlUnsupported field value.
*/
public bool IsFHtmlUnsupported()
{
return fHtmlUnsupported.IsSet(field_6_grfhic);
}
/**
* Sets the fHtmlListTextNotSharpDot field value. The list text is not "#."
*/
public void SetFHtmlListTextNotSharpDot(bool value)
{
field_6_grfhic = (byte)fHtmlListTextNotSharpDot.SetBoolean(
field_6_grfhic, value);
}
/**
* The list text is not "#."
*
* @return the fHtmlListTextNotSharpDot field value.
*/
public bool IsFHtmlListTextNotSharpDot()
{
return fHtmlListTextNotSharpDot.IsSet(field_6_grfhic);
}
/**
* Sets the fHtmlNotPeriod field value. Something other than a period is
* used
*/
public void SetFHtmlNotPeriod(bool value)
{
field_6_grfhic = (byte)fHtmlNotPeriod.SetBoolean(field_6_grfhic,
value);
}
/**
* Something other than a period is used
*
* @return the fHtmlNotPeriod field value.
*/
public bool IsFHtmlNotPeriod()
{
return fHtmlNotPeriod.IsSet(field_6_grfhic);
}
/**
* Sets the fHtmlFirstLineMismatch field value. First line indent mismatch
*/
public void SetFHtmlFirstLineMismatch(bool value)
{
field_6_grfhic = (byte)fHtmlFirstLineMismatch.SetBoolean(
field_6_grfhic, value);
}
/**
* First line indent mismatch
*
* @return the fHtmlFirstLineMismatch field value.
*/
public bool IsFHtmlFirstLineMismatch()
{
return fHtmlFirstLineMismatch.IsSet(field_6_grfhic);
}
/**
* Sets the fHtmlTabLeftIndentMismatch field value. The list tab and the
* dxaLeft don't match (need table?)
*/
public void SetFHtmlTabLeftIndentMismatch(bool value)
{
field_6_grfhic = (byte)fHtmlTabLeftIndentMismatch.SetBoolean(
field_6_grfhic, value);
}
/**
* The list tab and the dxaLeft don't match (need table?)
*
* @return the fHtmlTabLeftIndentMismatch field value.
*/
public bool IsFHtmlTabLeftIndentMismatch()
{
return fHtmlTabLeftIndentMismatch.IsSet(field_6_grfhic);
}
/**
* Sets the fHtmlHangingIndentBeneathNumber field value. The hanging indent
* falls beneath the number (need plain text)
*/
public void SetFHtmlHangingIndentBeneathNumber(bool value)
{
field_6_grfhic = (byte)fHtmlHangingIndentBeneathNumber.SetBoolean(
field_6_grfhic, value);
}
/**
* The hanging indent falls beneath the number (need plain text)
*
* @return the fHtmlHangingIndentBeneathNumber field value.
*/
public bool IsFHtmlHangingIndentBeneathNumber()
{
return fHtmlHangingIndentBeneathNumber.IsSet(field_6_grfhic);
}
/**
* Sets the fHtmlBuiltInBullet field value. A built-in HTML bullet
*/
public void SetFHtmlBuiltInBullet(bool value)
{
field_6_grfhic = (byte)fHtmlBuiltInBullet.SetBoolean(field_6_grfhic,
value);
}
/**
* A built-in HTML bullet
*
* @return the fHtmlBuiltInBullet field value.
*/
public bool IsFHtmlBuiltInBullet()
{
return fHtmlBuiltInBullet.IsSet(field_6_grfhic);
}
}
}
| |
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System;
/*
* BuildProcess
* Owlchemy Labs, LLC - 2011
*
* Menu-item driven build pipeline
* Comments and instructions are placed in-line
*/
public class BuildProcess : ScriptableObject
{
public static BuildOptions ManualBuildOptions = BuildOptions.AutoRunPlayer;
public static string DefaultBuildDirectory = "Builds";
//=====
//CHANGE ME
//Here we're specifying which scenes should go in which builds - add paths to all of your scenes in the arrays below.
//Sometimes you want to include different scenes with different platforms, such as removing the level editor on Webplayer for example
//=====
static string[] standaloneScenes = new string[] { @"Assets/MultiPlatformToolSuite/testScene.unity" };
static string[] iPhoneScenes = standaloneScenes;
static string[] iPadScenes = standaloneScenes;
static string[] iOSScenes = standaloneScenes;
static string[] webPlayerScenes = standaloneScenes;
static string[] androidScenes = standaloneScenes;
static string[] flashPlayerScenes = standaloneScenes;
static string[] naClScenes = standaloneScenes;
#if !UNITY_4_0 && !UNITY_4_1
static string[] winPhoneScenes = standaloneScenes;
static string[] windows8Scenes = standaloneScenes;
static string[] bb10Scenes = standaloneScenes;
#endif
static string[] levels; //This will be populated with the proper scenes for the chosen platform!
static char delim = System.IO.Path.DirectorySeparatorChar;
static string err = string.Empty;
//=====
//CHANGE ME - Make sure to set your bundle identifier and game name(s)!
//=====
static string bundleIdentifier = "com.CompanyName.GameName";
static string genericBuildName = "GameName";
static string genericProductName = "GameName";
static string macBuildName = genericBuildName + ".app";
static string macProductName = genericProductName;
static string winBuildName = genericBuildName + ".exe";
static string winProductName = genericProductName;
static string linBuildName_x86 = genericBuildName + ".x86";
static string linProductName_x86 = genericProductName;
static string linBuildName_x64 = genericBuildName + ".x86_64";
static string linProductName_x64 = genericProductName;
static string webBuildName = genericBuildName;
static string webProductName = genericProductName;
static string iPhoneBuildName = genericBuildName;
static string iPhoneProductName = genericProductName;
static string iPadBuildName = genericBuildName;
static string iPadProductName = genericProductName;
static string iOSBuildName = genericBuildName;
static string iOSProductName = genericProductName;
static string androidBuildName = genericBuildName;
static string androidProductName = genericProductName;
#if !UNITY_5
static string flashPlayerBuildName = genericBuildName + ".swf";
static string flashPlayerProductName = genericProductName;
static string naClBuildName = genericBuildName;
static string naClProductName = genericProductName;
#endif
#if !UNITY_4_0 && !UNITY_4_1
static string winPhoneBuildName = genericBuildName;
static string winPhoneProductName = genericProductName;
static string windows8BuildName = genericBuildName;
static string windows8ProductName = genericProductName;
static string bb10BuildName = genericBuildName;
static string bb10ProductName = genericProductName;
#endif
public static void SetBundleName(string bundleId)
{
bundleIdentifier = bundleId;
}
public static void SetBuildName(string buildName)
{
genericBuildName = buildName;
macBuildName = genericBuildName + ".app";
winBuildName = genericBuildName + ".exe";
linBuildName_x86 = genericBuildName + ".x86";
linBuildName_x64 = genericBuildName + ".x86_64";
webBuildName = genericBuildName;
iPhoneBuildName = genericBuildName;
iPadBuildName = genericBuildName;
iOSBuildName = genericBuildName;
androidBuildName = genericBuildName;
#if !UNITY_5
flashPlayerBuildName = genericBuildName + ".swf";
naClBuildName = genericBuildName;
#endif
#if !UNITY_4_0 && !UNITY_4_1
winPhoneBuildName = genericBuildName;
windows8BuildName = genericBuildName;
bb10BuildName = genericBuildName;
#endif
}
public static void SetProductName(string productName)
{
genericProductName = productName;
macProductName = genericProductName;
winProductName = genericProductName;
linProductName_x86 = genericProductName;
linProductName_x64 = genericProductName;
webProductName = genericProductName;
iPhoneProductName = genericProductName;
iPadProductName = genericProductName;
iOSProductName = genericProductName;
androidProductName = genericProductName;
#if !UNITY_5
flashPlayerProductName = genericProductName;
naClProductName = genericProductName;
#endif
#if !UNITY_4_0 && !UNITY_4_1
winPhoneProductName = genericProductName;
windows8ProductName = genericProductName;
bb10BuildName = genericBuildName;
#endif
}
//=====
//Below are the menu items under the Build menu. Feel free to add to this list to achieve custom build processes
//Examples include a debug build, a press build, a profiler build, a demo build, etc.
//=====
[MenuItem("Window/MultiPlatform ToolKit/Build/Build iPhone", false, 1)]
public static void BuildNonDebugiPhone ()
{
//Make platform-specific changes specifically for iPhone
PlatformSpecificChanges (Platform.iPhone);
//Finish the rest of the build process for iPhone
BuildiPhone (false, iPhoneBuildName, iPhoneProductName);
}
[MenuItem("Window/MultiPlatform ToolKit/Build/Build iPad", false, 1)]
public static void BuildNonDebugiPad ()
{
PlatformSpecificChanges (Platform.iPad);
BuildiPad (false, iPadBuildName, iPadProductName);
}
[MenuItem("Window/MultiPlatform ToolKit/Build/Build Universal iOS", false, 1)]
public static void BuildNonDebugUniversaliOS ()
{
PlatformSpecificChanges (Platform.iOS);
BuildiOS (false, iOSBuildName, iOSProductName);
}
[MenuItem("Window/MultiPlatform ToolKit/Build/Build Mac Intel", false, 1)]
public static void BuildMacIntelOnly ()
{
PlatformSpecificChanges (Platform.Standalone);
BuildMac (false, macBuildName, macProductName);
}
[MenuItem("Window/MultiPlatform ToolKit/Build/Build Windows", false, 1)]
public static void BuildWindowsOnly ()
{
PlatformSpecificChanges (Platform.Standalone);
BuildWin (false, winBuildName, winProductName);
}
[MenuItem("Window/MultiPlatform ToolKit/Build/Build Linux_x86", false, 1)]
public static void BuildLinuxOnly_x86 ()
{
PlatformSpecificChanges (Platform.Standalone);
BuildLin (false, linBuildName_x86, linProductName_x86, 86);
}
[MenuItem("Window/MultiPlatform ToolKit/Build/Build Linux_x64", false, 1)]
public static void BuildLinuxOnly_x64 ()
{
PlatformSpecificChanges (Platform.Standalone);
BuildLin (false, linBuildName_x64, linProductName_x64, 64);
}
[MenuItem("Window/MultiPlatform ToolKit/Build/Build Web", false, 1)]
public static void BuildWeb ()
{
PlatformSpecificChanges (Platform.WebPlayer);
BuildWeb (false, webBuildName, webProductName);
}
[MenuItem("Window/MultiPlatform ToolKit/Build/Build Android", false, 1)]
public static void BuildNonDebugAndroid ()
{
PlatformSpecificChanges (Platform.Android);
BuildAndroid (false, androidBuildName, androidProductName);
}
#if !UNITY_5
[MenuItem("Window/MultiPlatform ToolKit/Build/Build FlashPlayer", false, 1)]
public static void BuildNonDebugFlashPlayer ()
{
PlatformSpecificChanges (Platform.FlashPlayer);
BuildFlashPlayer (false, flashPlayerBuildName, flashPlayerProductName);
}
[MenuItem("Window/MultiPlatform ToolKit/Build/Build NaCl", false, 1)]
public static void BuildNonDebugNaCl ()
{
PlatformSpecificChanges (Platform.NaCl);
BuildNaCl (false, naClBuildName, naClProductName);
}
#endif
#if !UNITY_4_0 && !UNITY_4_1
[MenuItem("Window/MultiPlatform ToolKit/Build/Build WP8", false, 1)]
public static void BuildNonDebugWinPhone ()
{
PlatformSpecificChanges (Platform.WP8);
BuildWinPhone (false, winPhoneBuildName, winPhoneProductName);
}
[MenuItem("Window/MultiPlatform ToolKit/Build/Build Windows8", false, 1)]
public static void BuildNonDebugWindows8 ()
{
PlatformSpecificChanges (Platform.Windows8);
BuildWindows8 (false, windows8BuildName, windows8ProductName);
}
[MenuItem("Window/MultiPlatform ToolKit/Build/Build BB10", false, 1)]
public static void BuildNonDebugBB10 ()
{
PlatformSpecificChanges (Platform.BB10);
BuildBB10 (false, bb10BuildName, bb10ProductName);
}
#endif
//=====
//DEBUG build options
//=====
[MenuItem("Window/MultiPlatform ToolKit/Build/Debug/Build iPhone", false, 1)]
public static void BuildDebugiPhone ()
{
PlatformSpecificChanges (Platform.iPhone);
BuildiPhone (true, iPhoneBuildName, iPhoneProductName);
}
[MenuItem("Window/MultiPlatform ToolKit/Build/Debug/Build iPad", false, 1)]
public static void BuildDebugiPad ()
{
PlatformSpecificChanges (Platform.iPad);
BuildiPad (true, iPadBuildName, iPadProductName);
}
[MenuItem("Window/MultiPlatform ToolKit/Build/Debug/Build Universal iOS", false, 1)]
public static void BuildDebugiOS ()
{
PlatformSpecificChanges (Platform.iOS);
BuildiOS (true, iOSBuildName, iOSProductName);
}
[MenuItem("Window/MultiPlatform ToolKit/Build/Debug/Build Android", false, 1)]
public static void BuildDebugAndroid ()
{
PlatformSpecificChanges (Platform.Android);
BuildAndroid (true,androidBuildName, androidProductName);
}
#if !UNITY_5
[MenuItem("Window/MultiPlatform ToolKit/Build/Debug/Build FlashPlayer", false, 1)]
public static void BuildDebugFlashPlayer ()
{
PlatformSpecificChanges (Platform.FlashPlayer);
BuildFlashPlayer (true,flashPlayerBuildName, flashPlayerProductName);
}
[MenuItem("Window/MultiPlatform ToolKit/Build/Debug/Build NaCl", false, 1)]
public static void BuildDebugNaCl ()
{
PlatformSpecificChanges (Platform.NaCl);
BuildNaCl (true,naClBuildName, naClProductName);
}
#endif
#if !UNITY_4_0 && !UNITY_4_1
[MenuItem("Window/MultiPlatform ToolKit/Build/Debug/Build WP8", false, 1)]
public static void BuildDebugWinPhone ()
{
PlatformSpecificChanges (Platform.WP8);
BuildWinPhone (true, winPhoneBuildName, winPhoneProductName);
}
[MenuItem("Window/MultiPlatform ToolKit/Build/Debug/Build Windows8", false, 1)]
public static void BuildDebugWindows8 ()
{
PlatformSpecificChanges (Platform.Windows8);
BuildWindows8 (true, windows8BuildName, windows8ProductName);
}
[MenuItem("Window/MultiPlatform ToolKit/Build/Debug/Build BB10", false, 1)]
public static void BuildDebugBB10 ()
{
PlatformSpecificChanges (Platform.BB10);
BuildBB10 (true, bb10BuildName, bb10ProductName);
}
#endif
//=====
//Run through all of the scenes (working on duplicates) and make changes specified in PlatformSpecifics BEFORE building
//=====
public static void PlatformSpecificChanges (Platform platform) {
//Set platform override to the specified platform during the platform-specific changes, but revert back
//to the platform that was originally set at the end
string previousPlatformOverride = EditorPrefs.GetString (Platforms.editorPlatformOverrideKey, "Standalone");
EditorPrefs.SetString (Platforms.editorPlatformOverrideKey, platform.ToString ());
//Make sure to use the proper array of scenes, specified at the top of the file
if (platform == Platform.WebPlayer)
levels = webPlayerScenes;
else if (platform == Platform.iPhone)
levels = iPhoneScenes;
else if (platform == Platform.iPad)
levels = iPadScenes;
else if (platform == Platform.iOS)
levels = iOSScenes;
else if (platform == Platform.Android)
levels = androidScenes;
else if (platform == Platform.FlashPlayer)
levels = flashPlayerScenes;
else if (platform == Platform.NaCl)
levels = naClScenes;
#if !UNITY_4_0 && !UNITY_4_1
else if (platform == Platform.WP8)
levels = winPhoneScenes;
else if (platform == Platform.Windows8)
levels = windows8Scenes;
else if (platform == Platform.BB10)
levels = bb10Scenes;
#endif
else
levels = standaloneScenes;
//=====
//First, save the current scene!
//WARNING Running a build will save your current scene
//This is 'destructive' if you're not using version control or didnt want to save.
//=====
EditorApplication.SaveScene (EditorApplication.currentScene);
//Duplicate the scenes to work on them, then we can restore the originals later on
foreach (string scenePath in levels) {
string newPath = scenePath.Insert (scenePath.IndexOf (".unity"), "_temp");
//Rename the original scenes with a _temp suffix
AssetDatabase.MoveAsset (scenePath, newPath);
//Rename original scene file
AssetDatabase.CopyAsset (newPath, scenePath);
//Create duplicate file that uses the original scene file name
}
//Loop through each scene
foreach (string scenePath in levels) {
//Open the scene
EditorApplication.OpenScene (scenePath);
Debug.Log ("Processing scene: " + scenePath);
//Save, then do it again!
EditorApplication.SaveScene (scenePath);
AssetDatabase.Refresh ();
}
//Set the Editor to return to the first scene in the build settings, now that we're done combing through the scenes
EditorApplication.OpenScene (levels[0]);
//Revert platform override to what was previously set
EditorPrefs.SetString (Platforms.editorPlatformOverrideKey, previousPlatformOverride);
}
//=====
//Build processes for each platform, run after the PlatformSpecificChanges are done
//=====
public static void BuildiPhone (bool debug, string buildName, string productName)
{
string buildPath = GetBuildDirectory ().FullName + delim + buildName;
#if UNITY_5
BuildTarget target = BuildTarget.iOS;
#else
BuildTarget target = BuildTarget.iPhone;
#endif
PlayerSettings.productName = productName;
PlayerSettings.iOS.targetDevice = iOSTargetDevice.iPhoneOnly;
PlayerSettings.iOS.targetResolution = iOSTargetResolution.Native;
PlayerSettings.bundleIdentifier = bundleIdentifier;
PlayerSettings.iOS.applicationDisplayName = productName;
PlayerSettings.defaultInterfaceOrientation = UIOrientation.LandscapeLeft;
PreProcessiOSBuild ();
if (!debug)
err = BuildPipeline.BuildPlayer (levels, buildPath, target, ManualBuildOptions);
else
err = BuildPipeline.BuildPlayer (levels, buildPath, target, BuildOptions.Development | BuildOptions.ConnectWithProfiler);
if (err != string.Empty) {
Debug.Log (err);
} else {
PostProcessiOSBuild (buildPath);
}
RevertScenes ();
}
public static void BuildiPad (bool debug, string buildName, string productName)
{
//Get the build directory - by default it's the project's root directory
string buildPath = GetBuildDirectory ().FullName + delim + buildName;
//Currently we've configured this example project to create separate iPad builds from iPhone builds
//instead of a universal build
#if UNITY_5
BuildTarget target = BuildTarget.iOS;
#else
BuildTarget target = BuildTarget.iPhone;
#endif
//iPhone here really means 'iOS'
PlayerSettings.productName = productName;
//product name should have been set above!
PlayerSettings.iOS.targetDevice = iOSTargetDevice.iPadOnly;
//lets make an iPad only build
PlayerSettings.iOS.targetResolution = iOSTargetResolution.Native;
//native iPad resolution
PlayerSettings.bundleIdentifier = bundleIdentifier;
//bundle identifier should have been set above!
PlayerSettings.iOS.applicationDisplayName = productName;
//you can change the display name here (in the springboard on-device)
PlayerSettings.defaultInterfaceOrientation = UIOrientation.LandscapeLeft;
//lets default to Landscape Left
PlayerSettings.allowedAutorotateToLandscapeLeft = false;
//lets also block all other orientations!
PlayerSettings.allowedAutorotateToLandscapeRight = false;
PlayerSettings.allowedAutorotateToPortrait = false;
PlayerSettings.allowedAutorotateToPortraitUpsideDown = false;
//There's a whole bunch of other optional PlayerSettings that can be automatically set here! Check out the API.
//Pre-process the build
PreProcessiOSBuild ();
//Actually execute the build!
if (!debug)
err = BuildPipeline.BuildPlayer (levels, buildPath, target, ManualBuildOptions);
else
err = BuildPipeline.BuildPlayer (levels, buildPath, target, BuildOptions.Development | BuildOptions.ConnectWithProfiler);
//Post-process the build
if (err != string.Empty) {
Debug.Log (err);
} else {
PostProcessiOSBuild (buildPath);
}
//Finally, revert back to the scene files that were present at the beginning of the build process
RevertScenes ();
}
public static void BuildiOS (bool debug, string buildName, string productName)
{
//Get the build directory - by default it's the project's root directory
string buildPath = GetBuildDirectory ().FullName + delim + buildName;
//Currently we've configured this example project to create separate iPad builds from iPhone builds
//instead of a universal build
#if UNITY_5
BuildTarget target = BuildTarget.iOS;
#else
BuildTarget target = BuildTarget.iPhone;
#endif
//iPhone here really means 'iOS'
PlayerSettings.productName = productName;
//product name should have been set above!
PlayerSettings.iOS.targetDevice = iOSTargetDevice.iPhoneAndiPad;
//lets make an iOS only build
PlayerSettings.iOS.targetResolution = iOSTargetResolution.Native;
//native iOS resolution
PlayerSettings.bundleIdentifier = bundleIdentifier;
//bundle identifier should have been set above!
PlayerSettings.iOS.applicationDisplayName = productName;
//you can change the display name here (in the springboard on-device)
PlayerSettings.defaultInterfaceOrientation = UIOrientation.LandscapeLeft;
//lets default to Landscape Left
PlayerSettings.allowedAutorotateToLandscapeLeft = false;
//lets also block all other orientations!
PlayerSettings.allowedAutorotateToLandscapeRight = false;
PlayerSettings.allowedAutorotateToPortrait = false;
PlayerSettings.allowedAutorotateToPortraitUpsideDown = false;
//There's a whole bunch of other optional PlayerSettings that can be automatically set here! Check out the API.
//Pre-process the build
PreProcessiOSBuild ();
//Actually execute the build!
if (!debug)
err = BuildPipeline.BuildPlayer (levels, buildPath, target, ManualBuildOptions);
else
err = BuildPipeline.BuildPlayer (levels, buildPath, target, BuildOptions.Development | BuildOptions.ConnectWithProfiler);
//Post-process the build
if (err != string.Empty) {
Debug.Log (err);
} else {
PostProcessiOSBuild (buildPath);
}
//Finally, revert back to the scene files that were present at the beginning of the build process
RevertScenes ();
}
public static void BuildAndroid (bool debug, string buildName, string productName)
{
string buildPath = GetBuildDirectory ().FullName + delim + buildName;
BuildTarget target = BuildTarget.Android;
PlayerSettings.productName = productName;
PlayerSettings.Android.targetDevice = AndroidTargetDevice.ARMv7;
//remember to set your Android bundle version code higher each time.
//see the Bundle Version Code docs here: http://unity3d.com/support/documentation/Components/class-PlayerSettings.html
PlayerSettings.Android.bundleVersionCode = 1;
PlayerSettings.bundleVersion = "1.0";
PlayerSettings.bundleIdentifier = bundleIdentifier;
PlayerSettings.defaultInterfaceOrientation = UIOrientation.LandscapeLeft;
//You may choose to pre-process your Android build here.
if (!debug)
err = BuildPipeline.BuildPlayer (levels, buildPath, target, ManualBuildOptions);
else
err = BuildPipeline.BuildPlayer (levels, buildPath, target, BuildOptions.Development | BuildOptions.ConnectWithProfiler);
if (err != string.Empty) {
Debug.Log (err);
} else {
//You may choose to post-process your Android build here.
}
RevertScenes ();
}
#if !UNITY_5
public static void BuildFlashPlayer (bool debug, string buildName, string productName)
{
string buildPath = GetBuildDirectory ().FullName + delim + buildName;
BuildTarget target = BuildTarget.FlashPlayer;
PlayerSettings.productName = productName;
//More flash-specific player settings coming soon in the final v3.5!
//You may choose to pre-process your Flash build here.
if (!debug)
err = BuildPipeline.BuildPlayer (levels, buildPath, target, ManualBuildOptions);
else
err = BuildPipeline.BuildPlayer (levels, buildPath, target, BuildOptions.Development | BuildOptions.ConnectWithProfiler | ManualBuildOptions);
if (err != string.Empty) {
Debug.Log (err);
} else {
//You may choose to post-process your Flash build here.
}
RevertScenes ();
}
public static void BuildNaCl (bool debug, string buildName, string productName)
{
string buildPath = GetBuildDirectory ().FullName + delim + buildName;
BuildTarget target = BuildTarget.NaCl;
PlayerSettings.productName = productName;
//offline testing support
//=====
//CHANGE ME when you want to disable offline deployment
//=====
EditorUserBuildSettings.webPlayerOfflineDeployment = true;
//You may choose to pre-process your NaCl build here.
//You may choose to pre-process your NaCl build here.
if (!debug)
err = BuildPipeline.BuildPlayer (levels, buildPath, target, ManualBuildOptions);
else
err = BuildPipeline.BuildPlayer (levels, buildPath, target, BuildOptions.Development | BuildOptions.ConnectWithProfiler | ManualBuildOptions);
if (err != string.Empty) {
Debug.Log (err);
} else {
//You may choose to post-process your NaCl build here.
}
RevertScenes ();
}
#endif
#if !UNITY_4_0 && !UNITY_4_1
public static void BuildWinPhone (bool debug, string buildName, string productName)
{
string buildPath = GetBuildDirectory ().FullName + delim + buildName;
BuildTarget target = BuildTarget.WP8Player;
//then set this to true!
bool doWinBuild = false;
PlayerSettings.productName = productName;
//You may choose to pre-process your WP8 build here.
if(doWinBuild)
{
if (!debug)
err = BuildPipeline.BuildPlayer (levels, buildPath, target, ManualBuildOptions);
else
err = BuildPipeline.BuildPlayer (levels, buildPath, target, BuildOptions.Development | BuildOptions.ConnectWithProfiler | ManualBuildOptions);
if (err != string.Empty) {
Debug.Log (err);
} else {
//You may choose to post-process your WP8 build here.
}
}
else
{
Debug.LogWarning("DoWinBuild is set to false - set me to true to enable building!");
}
RevertScenes ();
}
public static void BuildWindows8 (bool debug, string buildName, string productName)
{
string buildPath = GetBuildDirectory ().FullName + delim + buildName;
//
//uncomment these lines for various win8 buildtypes
//
//BuildTarget target = BuildTarget.MetroPlayerX86;
//BuildTarget target = BuildTarget.MetroPlayer;
//BuildTarget target = BuildTarget.MetroPlayerX64;
//BuildTarget target = BuildTarget.WP8Player
#if UNITY_5
BuildTarget target = BuildTarget.WSAPlayer;
#else
BuildTarget target = BuildTarget.MetroPlayer;
#endif
//then set this to true!
bool doWinBuild = false;
PlayerSettings.productName = productName;
//You may choose to pre-process your Windows8 build here.
if(doWinBuild)
{
if (!debug)
err = BuildPipeline.BuildPlayer (levels, buildPath, target, ManualBuildOptions);
else
err = BuildPipeline.BuildPlayer (levels, buildPath, target, BuildOptions.Development | BuildOptions.ConnectWithProfiler | ManualBuildOptions);
if (err != string.Empty) {
Debug.Log (err);
} else {
//You may choose to post-process your Windows8 build here.
}
}
else
{
Debug.LogWarning("DoWinBuild is set to false - set me to true to enable building!");
}
RevertScenes ();
}
public static void BuildBB10 (bool debug, string buildName, string productName)
{
string buildPath = GetBuildDirectory ().FullName + delim + buildName;
//
//uncomment these lines for various bb10 buildtypes
//
#if UNITY_4_0 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3
BuildTarget target = BuildTarget.BB10;
#else
BuildTarget target = BuildTarget.BlackBerry;
#endif
//then set this to true!
bool doBB10Build = true;
PlayerSettings.productName = productName;
//You may choose to pre-process your Windows8 build here.
if(doBB10Build)
{
if (!debug)
err = BuildPipeline.BuildPlayer (levels, buildPath, target, ManualBuildOptions);
else
err = BuildPipeline.BuildPlayer (levels, buildPath, target, BuildOptions.Development | BuildOptions.ConnectWithProfiler | ManualBuildOptions);
if (err != string.Empty) {
Debug.Log (err);
} else {
//You may choose to post-process your BB10 build here.
}
}
else
{
Debug.LogWarning("DoBB10Build is set to false - set me to true to enable building!");
}
RevertScenes ();
}
#endif
public static void BuildWeb (bool debug, string buildName, string productName)
{
string buildPath = GetBuildDirectory ().FullName + delim + buildName;
BuildTarget target = BuildTarget.WebPlayer;
PlayerSettings.productName = productName;
err = BuildPipeline.BuildPlayer (levels, buildPath, target, BuildOptions.ShowBuiltPlayer);
if (err != string.Empty)
Debug.Log (err);
RevertScenes ();
}
public static void BuildMac (bool debug, string buildName, string productName)
{
string buildPath = GetBuildDirectory ().FullName + delim + buildName;
BuildTarget target = BuildTarget.StandaloneOSXIntel;
PlayerSettings.productName = productName;
PlayerSettings.defaultIsFullScreen = true;
//There's a whole bunch of other optional PlayerSettings that can be automatically set here! Check out the API.
err = BuildPipeline.BuildPlayer (levels, buildPath, target, BuildOptions.ShowBuiltPlayer);
if (err != string.Empty)
Debug.Log (err);
RevertScenes ();
}
public static void BuildWin (bool debug, string buildName, string productName)
{
string buildPath = GetBuildDirectory ().FullName + delim + buildName;
Debug.Log (buildPath);
BuildTarget target = BuildTarget.StandaloneWindows;
PlayerSettings.productName = productName;
PlayerSettings.defaultIsFullScreen = true;
err = BuildPipeline.BuildPlayer (levels, buildPath, target, BuildOptions.ShowBuiltPlayer);
if (err != string.Empty)
Debug.Log (err);
RevertScenes ();
}
public static void BuildLin (bool debug, string buildName, string productName, int bitValue)
{
string buildPath = GetBuildDirectory ().FullName + delim + buildName;
BuildTarget target = bitValue == 86 ? BuildTarget.StandaloneLinux : BuildTarget.StandaloneLinux64;
PlayerSettings.productName = productName;
PlayerSettings.defaultIsFullScreen = true;
//There's a whole bunch of other optional PlayerSettings that can be automatically set here! Check out the API.
err = BuildPipeline.BuildPlayer (levels, buildPath, target, BuildOptions.ShowBuiltPlayer);
if (err != string.Empty)
Debug.Log (err);
RevertScenes ();
}
public static void PreProcessiOSBuild ()
{
//Do any pre-processing or moving around of files before the build happens, in here!
//For example, we renamed a .dll file that was only for PC builds so that it wouldn't get included in the XCode project
//This might be useful for some, so that code is included below (commented out for example purposes)
//Rename PC_ONLY.dll file so it doesn't get built into XCode project
//AssetDatabase.MoveAsset("Assets/Scripts/PC/PC_ONLY.dll", "Assets/Scripts/PC/PC_ONLY.txt");
}
public static void PostProcessiOSBuild (string buildDirectoryPath)
{
//=====
//Example for how to postprocess the iOS Info.plist
//=====
ModifyInfoPlist ();
//=====
//Copy over all classes - useful for copying Objective C files into your XCode project
//=====
// DirectoryInfo classesDirectory = new DirectoryInfo(Application.dataPath + "/Editor/Build Resources/Classes");
// FileInfo[] classFiles = classesDirectory.GetFiles();
// foreach(FileInfo classFile in classFiles) {
// classFile.CopyTo(buildDirectoryPath + "/Classes/" + classFile.Name, true);
// }
//=====
//Next we're going to edit an AppleScript which will modify our XCode project for us
//=====
// //Write project path to postprocess apple script
// Debug.Log("Writing project path to postprocess AppleScript.");
// string appleScriptPath = Application.dataPath + "/Editor/Build Resources/PostProcessAppleScript.txt";
// Debug.Log("AppleScript path: " + appleScriptPath);
// string appleScript = File.ReadAllText(appleScriptPath);
// List<string> lines = new List<string>(appleScript.Split('\n'));
// //Remove the very last line since it'll be an empty one after the Split
// lines.RemoveAt(lines.Count - 1);
//
// //Replace 3rd line to include project path
// lines[2] = " open \"" + buildDirectoryPath + "/Unity-iPhone.xcodeproj" + "\"";
// File.WriteAllLines(appleScriptPath, lines.ToArray());
//
// //Add custom classes to XCode build
// System.Diagnostics.Process process = new System.Diagnostics.Process();
// process.StartInfo.FileName = "/usr/bin/osascript";
// process.StartInfo.UseShellExecute = false;
// process.StartInfo.RedirectStandardError = true;
// process.StartInfo.RedirectStandardOutput = true;
// process.StartInfo.Arguments = "\"" + appleScriptPath + "\"";
// process.Start();
// Debug.Log("Postprocess StdError: " + process.StandardError.ReadToEnd());
// Debug.Log("Postprocess StdOutput: " + process.StandardOutput.ReadToEnd());
// process.WaitForExit();
// process.Dispose();
//Undo the renaming we did in PreProcessiOSBuild()
// AssetDatabase.MoveAsset("Assets/Scripts/PC/PC_ONLY.txt", "Assets/Scripts/PC/PC_ONLY.dll");
}
public static void ModifyInfoPlist ()
{
//=====
//Modify the Info Plist
//In this example, we're going to remove the Orientation entry for LandscapeLeft
//since there was a bug in Unity 3.3 that wouldn't allow you to set a single orientation like this from within Unity
//Including for example purposes
//=====
// DirectoryInfo buildDirectory = new DirectoryInfo(buildDirectoryPath); //Get build directory
// FileInfo[] plistFiles = buildDirectory.GetFiles("Info.plist"); //Get Info.plist files in build directory
// if(plistFiles == null || plistFiles.Length == 0) { //If none were found
// Debug.Log("No Plist files were found in build directory."); //Log error
// return;
// }
// FileInfo plist = plistFiles[0]; //Get the first Info.plist file
// StreamReader readStream = plist.OpenText(); //Open Info.plist for reading
// FileInfo newPlist = new FileInfo(buildDirectoryPath + Path.DirectorySeparatorChar + "Info_tmp.plist"); //Create a new Info_tmp.plist file
// StreamWriter writeStream = newPlist.CreateText(); //Open Info_tmp.plist for writing
//
// string line = string.Empty;
//
// //Copy Info.plist to Info_tmp.plist line by line
// //but skip the line that contains UIInterfaceOrientationLandscapeLeft
// while((line = readStream.ReadLine()) != null) {
// if(line.Contains("UIInterfaceOrientationLandscapeLeft")) //If line contains LandscapeLeft orientation
// continue; //Skip this line
// writeStream.WriteLine(line); //Write line
// }
//
// writeStream.Close(); //Close write stream
// readStream.Close(); //Close read stream
//
// string filename = plist.FullName; //Get the filename of Info.plist
// plist.Delete(); //Delete Info.plist
// newPlist.MoveTo(filename); //Rename Info_tmp.plist to Info.plist
}
//=====
//Get the build directory
//By default, the build directory is in the project's base directory
//If you have a "Builds" folder, it'll place builds in there (recommended to reduce clutter)
//=====
static DirectoryInfo GetBuildDirectory ()
{
DirectoryInfo assetsDirectory = new DirectoryInfo (Application.dataPath);
DirectoryInfo projectDirectory = assetsDirectory.Parent;
DirectoryInfo[] buildDirectories = projectDirectory.GetDirectories (DefaultBuildDirectory);
return (buildDirectories == null || buildDirectories.Length == 0) ? projectDirectory : buildDirectories[0];
}
//Revert the scenes back to normal, removing the _temp appended to the end
public static void RevertScenes ()
{
foreach (string scenePath in levels) {
string newPath = scenePath.Insert (scenePath.IndexOf (".unity"), "_temp");
AssetDatabase.DeleteAsset (scenePath);
AssetDatabase.MoveAsset (newPath, scenePath);
}
EditorApplication.OpenScene (levels[0]);
Debug.Log ("Build complete!");
}
}
| |
// 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.
/*=============================================================================
**
**
**
**
**
** Purpose: Holds state about A/G/R permissionsets in a callstack or appdomain
** (Replacement for PermissionListSet)
**
=============================================================================*/
namespace System.Security
{
using System.Globalization;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
using System.Threading;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
[Serializable]
sealed internal class PermissionListSet
{
// Only internal (public) methods are creation methods and demand evaluation methods.
// Scroll down to the end to see them.
private PermissionSetTriple m_firstPermSetTriple;
private ArrayList m_permSetTriples;
#if FEATURE_COMPRESSEDSTACK
private ArrayList m_zoneList;
private ArrayList m_originList;
#endif // FEATURE_COMPRESSEDSTACK
internal PermissionListSet() {}
private void EnsureTriplesListCreated()
{
if (m_permSetTriples == null)
{
m_permSetTriples = new ArrayList();
if (m_firstPermSetTriple != null)
{
m_permSetTriples.Add(m_firstPermSetTriple);
m_firstPermSetTriple = null;
}
}
}
#if FEATURE_PLS
[System.Security.SecurityCritical] // auto-generated
internal void UpdateDomainPLS (PermissionListSet adPLS) {
if (adPLS != null && adPLS.m_firstPermSetTriple != null)
UpdateDomainPLS(adPLS.m_firstPermSetTriple.GrantSet, adPLS.m_firstPermSetTriple.RefusedSet);
}
[System.Security.SecurityCritical] // auto-generated
internal void UpdateDomainPLS (PermissionSet grantSet, PermissionSet deniedSet) {
Contract.Assert(m_permSetTriples == null, "m_permSetTriples != null");
if (m_firstPermSetTriple == null)
m_firstPermSetTriple = new PermissionSetTriple();
// update the grant and denied sets
m_firstPermSetTriple.UpdateGrant(grantSet);
m_firstPermSetTriple.UpdateRefused(deniedSet);
}
#endif // FEATURE_PLS
private void Terminate(PermissionSetTriple currentTriple)
{
UpdateTripleListAndCreateNewTriple(currentTriple, null);
}
[System.Security.SecurityCritical] // auto-generated
private void Terminate(PermissionSetTriple currentTriple, PermissionListSet pls)
{
#if FEATURE_COMPRESSEDSTACK
this.UpdateZoneAndOrigin(pls);
#endif // FEATURE_COMPRESSEDSTACK
this.UpdatePermissions(currentTriple, pls);
this.UpdateTripleListAndCreateNewTriple(currentTriple, null);
}
[System.Security.SecurityCritical] // auto-generated
private bool Update(PermissionSetTriple currentTriple, PermissionListSet pls)
{
#if FEATURE_COMPRESSEDSTACK
this.UpdateZoneAndOrigin(pls);
#endif // FEATURE_COMPRESSEDSTACK
return this.UpdatePermissions(currentTriple, pls);
}
[System.Security.SecurityCritical] // auto-generated
private bool Update(PermissionSetTriple currentTriple, FrameSecurityDescriptor fsd)
{
#if FEATURE_COMPRESSEDSTACK
FrameSecurityDescriptorWithResolver fsdWithResolver = fsd as FrameSecurityDescriptorWithResolver;
if (fsdWithResolver != null)
{
return Update2(currentTriple, fsdWithResolver);
}
#endif // FEATURE_COMPRESSEDSTACK
// check imperative
bool fHalt = Update2(currentTriple, fsd, false);
if (!fHalt)
{
// then declarative
fHalt = Update2(currentTriple, fsd, true);
}
return fHalt;
}
#if FEATURE_COMPRESSEDSTACK
[System.Security.SecurityCritical]
private bool Update2(PermissionSetTriple currentTriple, FrameSecurityDescriptorWithResolver fsdWithResolver)
{
System.Reflection.Emit.DynamicResolver resolver = fsdWithResolver.Resolver;
CompressedStack dynamicCompressedStack = resolver.GetSecurityContext();
dynamicCompressedStack.CompleteConstruction(null);
return this.Update(currentTriple, dynamicCompressedStack.PLS);
}
#endif // FEATURE_COMPRESSEDSTACK
[System.Security.SecurityCritical] // auto-generated
private bool Update2(PermissionSetTriple currentTriple, FrameSecurityDescriptor fsd, bool fDeclarative)
{
// Deny
PermissionSet deniedPset = fsd.GetDenials(fDeclarative);
if (deniedPset != null)
{
currentTriple.UpdateRefused(deniedPset);
}
// permit only
PermissionSet permitOnlyPset = fsd.GetPermitOnly(fDeclarative);
if (permitOnlyPset != null)
{
currentTriple.UpdateGrant(permitOnlyPset);
}
// Assert all possible
if (fsd.GetAssertAllPossible())
{
// If we have no grant set, it means that the only assembly we've seen on the stack so
// far is mscorlib. Since mscorlib will always be fully trusted, the grant set of the
// compressed stack is also FullTrust.
if (currentTriple.GrantSet == null)
currentTriple.GrantSet = PermissionSet.s_fullTrust;
UpdateTripleListAndCreateNewTriple(currentTriple, m_permSetTriples);
currentTriple.GrantSet = PermissionSet.s_fullTrust;
currentTriple.UpdateAssert(fsd.GetAssertions(fDeclarative));
return true;
}
// Assert
PermissionSet assertPset = fsd.GetAssertions(fDeclarative);
if (assertPset != null)
{
if (assertPset.IsUnrestricted())
{
// If we have no grant set, it means that the only assembly we've seen on the stack so
// far is mscorlib. Since mscorlib will always be fully trusted, the grant set of the
// compressed stack is also FullTrust.
if (currentTriple.GrantSet == null)
currentTriple.GrantSet = PermissionSet.s_fullTrust;
UpdateTripleListAndCreateNewTriple(currentTriple, m_permSetTriples);
currentTriple.GrantSet = PermissionSet.s_fullTrust;
currentTriple.UpdateAssert(assertPset);
return true;
}
PermissionSetTriple retTriple = currentTriple.UpdateAssert(assertPset);
if (retTriple != null)
{
EnsureTriplesListCreated();
m_permSetTriples.Add(retTriple);
}
}
return false;
}
[System.Security.SecurityCritical] // auto-generated
private void Update(PermissionSetTriple currentTriple, PermissionSet in_g, PermissionSet in_r)
{
#if FEATURE_COMPRESSEDSTACK
ZoneIdentityPermission z;
UrlIdentityPermission u;
currentTriple.UpdateGrant(in_g, out z, out u);
currentTriple.UpdateRefused(in_r);
AppendZoneOrigin(z, u);
#else // !FEATURE_COMPRESEDSTACK
currentTriple.UpdateGrant(in_g);
currentTriple.UpdateRefused(in_r);
#endif // FEATURE_COMPRESSEDSTACK
}
// Called from the VM for HG CS construction
[System.Security.SecurityCritical] // auto-generated
private void Update(PermissionSet in_g)
{
if (m_firstPermSetTriple == null)
m_firstPermSetTriple = new PermissionSetTriple();
Update(m_firstPermSetTriple, in_g, null);
}
#if FEATURE_COMPRESSEDSTACK
private void UpdateZoneAndOrigin(PermissionListSet pls)
{
if (pls != null)
{
if (this.m_zoneList == null && pls.m_zoneList != null && pls.m_zoneList.Count > 0)
this.m_zoneList = new ArrayList();
UpdateArrayList(this.m_zoneList, pls.m_zoneList);
if (this.m_originList == null && pls.m_originList != null && pls.m_originList.Count > 0)
this.m_originList = new ArrayList();
UpdateArrayList(this.m_originList, pls.m_originList);
}
}
#endif // FEATURE_COMPRESSEDSTACK
[System.Security.SecurityCritical] // auto-generated
private bool UpdatePermissions(PermissionSetTriple currentTriple, PermissionListSet pls)
{
if (pls != null)
{
if (pls.m_permSetTriples != null)
{
// DCS has an AGR List. So we need to add the AGR List
UpdateTripleListAndCreateNewTriple(currentTriple,pls.m_permSetTriples);
}
else
{
// Common case: One AGR set
PermissionSetTriple tmp_psTriple = pls.m_firstPermSetTriple;
PermissionSetTriple retTriple;
// First try and update currentTriple. Return value indicates if we can stop construction
if (currentTriple.Update(tmp_psTriple, out retTriple))
return true;
// If we got a non-null retTriple, what it means is that compression failed,
// and we now have 2 triples to deal with: retTriple and currentTriple.
// retTriple has to be appended first. then currentTriple.
if (retTriple != null)
{
EnsureTriplesListCreated();
// we just created a new triple...add the previous one (returned) to the list
m_permSetTriples.Add(retTriple);
}
}
}
else
{
// pls can be null only outside the loop in CreateCompressedState
UpdateTripleListAndCreateNewTriple(currentTriple, null);
}
return false;
}
private void UpdateTripleListAndCreateNewTriple(PermissionSetTriple currentTriple, ArrayList tripleList)
{
if (!currentTriple.IsEmpty())
{
if (m_firstPermSetTriple == null && m_permSetTriples == null)
{
m_firstPermSetTriple = new PermissionSetTriple(currentTriple);
}
else
{
EnsureTriplesListCreated();
m_permSetTriples.Add(new PermissionSetTriple(currentTriple));
}
currentTriple.Reset();
}
if (tripleList != null)
{
EnsureTriplesListCreated();
m_permSetTriples.AddRange(tripleList);
}
}
private static void UpdateArrayList(ArrayList current, ArrayList newList)
{
if (newList == null)
return;
for(int i=0;i < newList.Count; i++)
{
if (!current.Contains(newList[i]))
current.Add(newList[i]);
}
}
#if FEATURE_COMPRESSEDSTACK
private void AppendZoneOrigin(ZoneIdentityPermission z, UrlIdentityPermission u)
{
if (z != null)
{
if (m_zoneList == null)
m_zoneList = new ArrayList();
z.AppendZones(m_zoneList);
}
if (u != null)
{
if (m_originList == null)
m_originList = new ArrayList();
u.AppendOrigin(m_originList);
}
}
[System.Security.SecurityCritical] // auto-generated
[System.Runtime.InteropServices.ComVisible(true)]
// public(internal) interface begins...
// Creation functions
static internal PermissionListSet CreateCompressedState(CompressedStack cs, CompressedStack innerCS)
{
// function that completes the construction of the compressed stack if not done so already (bottom half for demand evaluation)
bool bHaltConstruction = false;
if (cs.CompressedStackHandle == null)
return null; // FT case or Security off
PermissionListSet pls = new PermissionListSet();
PermissionSetTriple currentTriple = new PermissionSetTriple();
int numDomains = CompressedStack.GetDCSCount(cs.CompressedStackHandle);
for (int i=numDomains-1; (i >= 0 && !bHaltConstruction) ; i--)
{
DomainCompressedStack dcs = CompressedStack.GetDomainCompressedStack(cs.CompressedStackHandle, i);
if (dcs == null)
continue; // we hit a FT Domain
if (dcs.PLS == null)
{
// We failed on some DCS
throw new SecurityException(String.Format(CultureInfo.InvariantCulture, Environment.GetResourceString("Security_Generic")));
}
pls.UpdateZoneAndOrigin(dcs.PLS);
pls.Update(currentTriple, dcs.PLS);
bHaltConstruction = dcs.ConstructionHalted;
}
if (!bHaltConstruction)
{
PermissionListSet tmp_pls = null;
// Construction did not halt.
if (innerCS != null)
{
innerCS.CompleteConstruction(null);
tmp_pls = innerCS.PLS;
}
pls.Terminate(currentTriple, tmp_pls);
}
else
{
pls.Terminate(currentTriple);
}
return pls;
}
[System.Security.SecurityCritical] // auto-generated
static internal PermissionListSet CreateCompressedState(IntPtr unmanagedDCS, out bool bHaltConstruction)
{
PermissionListSet pls = new PermissionListSet();
PermissionSetTriple currentTriple = new PermissionSetTriple();
PermissionSet tmp_g, tmp_r;
// Construct the descriptor list
int descCount = DomainCompressedStack.GetDescCount(unmanagedDCS);
bHaltConstruction = false;
for(int i=0; (i < descCount && !bHaltConstruction); i++)
{
FrameSecurityDescriptor fsd;
Assembly assembly;
if (DomainCompressedStack.GetDescriptorInfo(unmanagedDCS, i, out tmp_g, out tmp_r, out assembly, out fsd))
{
// Got an FSD
bHaltConstruction = pls.Update(currentTriple, fsd);
}
else
{
pls.Update(currentTriple, tmp_g, tmp_r);
}
}
if (!bHaltConstruction)
{
// domain
if (!DomainCompressedStack.IgnoreDomain(unmanagedDCS))
{
DomainCompressedStack.GetDomainPermissionSets(unmanagedDCS, out tmp_g, out tmp_r);
pls.Update(currentTriple, tmp_g, tmp_r);
}
}
pls.Terminate(currentTriple);
// return the created object
return pls;
}
[System.Security.SecurityCritical] // auto-generated
static internal PermissionListSet CreateCompressedState_HG()
{
PermissionListSet pls = new PermissionListSet();
CompressedStack.GetHomogeneousPLS(pls);
return pls;
}
#endif // #if FEATURE_COMPRESSEDSTACK
// Private Demand evaluation functions - only called from the VM
[System.Security.SecurityCritical] // auto-generated
internal bool CheckDemandNoThrow(CodeAccessPermission demand)
{
// AppDomain permissions - no asserts. So there should only be one triple to work with
Contract.Assert(m_permSetTriples == null && m_firstPermSetTriple != null, "More than one PermissionSetTriple encountered in AD PermissionListSet");
PermissionToken permToken = null;
if (demand != null)
permToken = PermissionToken.GetToken(demand);
return m_firstPermSetTriple.CheckDemandNoThrow(demand, permToken);
}
[System.Security.SecurityCritical] // auto-generated
internal bool CheckSetDemandNoThrow(PermissionSet pSet)
{
// AppDomain permissions - no asserts. So there should only be one triple to work with
Contract.Assert(m_permSetTriples == null && m_firstPermSetTriple != null, "More than one PermissionSetTriple encountered in AD PermissionListSet");
return m_firstPermSetTriple.CheckSetDemandNoThrow(pSet);
}
// Demand evauation functions
[System.Security.SecurityCritical] // auto-generated
internal bool CheckDemand(CodeAccessPermission demand, PermissionToken permToken, RuntimeMethodHandleInternal rmh)
{
bool bRet = SecurityRuntime.StackContinue;
if (m_permSetTriples != null)
{
for (int i=0; (i < m_permSetTriples.Count && bRet != SecurityRuntime.StackHalt) ; i++)
{
PermissionSetTriple psTriple = (PermissionSetTriple)m_permSetTriples[i];
bRet = psTriple.CheckDemand(demand, permToken, rmh);
}
}
else if (m_firstPermSetTriple != null)
{
bRet = m_firstPermSetTriple.CheckDemand(demand, permToken, rmh);
}
return bRet;
}
[System.Security.SecurityCritical] // auto-generated
internal bool CheckSetDemand(PermissionSet pset , RuntimeMethodHandleInternal rmh)
{
PermissionSet unused;
CheckSetDemandWithModification(pset, out unused, rmh);
return SecurityRuntime.StackHalt; // CS demand check always terminates the stackwalk
}
[System.Security.SecurityCritical]
internal bool CheckSetDemandWithModification(PermissionSet pset, out PermissionSet alteredDemandSet, RuntimeMethodHandleInternal rmh)
{
bool bRet = SecurityRuntime.StackContinue;
PermissionSet demandSet = pset;
alteredDemandSet = null;
if (m_permSetTriples != null)
{
for (int i=0; (i < m_permSetTriples.Count && bRet != SecurityRuntime.StackHalt) ; i++)
{
PermissionSetTriple psTriple = (PermissionSetTriple)m_permSetTriples[i];
bRet = psTriple.CheckSetDemand(demandSet, out alteredDemandSet, rmh);
if (alteredDemandSet != null)
demandSet = alteredDemandSet;
}
}
else if (m_firstPermSetTriple != null)
{
bRet = m_firstPermSetTriple.CheckSetDemand(demandSet, out alteredDemandSet, rmh);
}
return bRet;
}
/// <summary>
/// Check to see if the PLS satisfies a demand for the special permissions encoded in flags
/// </summary>
/// <param name="flags">set of flags to check (See PermissionType)</param>
[System.Security.SecurityCritical] // auto-generated
private bool CheckFlags(int flags)
{
Contract.Assert(flags != 0, "Invalid permission flag demand");
bool check = true;
if (m_permSetTriples != null)
{
for (int i = 0; i < m_permSetTriples.Count && check && flags != 0; i++)
{
check &= ((PermissionSetTriple)m_permSetTriples[i]).CheckFlags(ref flags);
}
}
else if (m_firstPermSetTriple != null)
{
check = m_firstPermSetTriple.CheckFlags(ref flags);
}
return check;
}
/// <summary>
/// Demand which succeeds if either a set of special permissions or a permission set is granted
/// to the call stack
/// </summary>
/// <param name="flags">set of flags to check (See PermissionType)</param>
/// <param name="grantSet">alternate permission set to check</param>
[System.Security.SecurityCritical] // auto-generated
internal void DemandFlagsOrGrantSet(int flags, PermissionSet grantSet)
{
if (CheckFlags(flags))
return;
CheckSetDemand(grantSet, RuntimeMethodHandleInternal.EmptyHandle);
}
#if FEATURE_COMPRESSEDSTACK
internal void GetZoneAndOrigin(ArrayList zoneList, ArrayList originList, PermissionToken zoneToken, PermissionToken originToken)
{
if (m_zoneList != null)
zoneList.AddRange(m_zoneList);
if (m_originList != null)
originList.AddRange(m_originList);
}
#endif
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Collections.Generic;
namespace System.Management.Automation
{
/// <summary>
/// Enumerates the items matching a particular name in the scopes specified using
/// the appropriate scoping lookup rules.
/// </summary>
/// <typeparam name="T">
/// The type of items that the derived class returns.
/// </typeparam>
internal abstract class ScopedItemSearcher<T> : IEnumerator<T>, IEnumerable<T>
{
#region ctor
/// <summary>
/// Constructs a scoped item searcher.
/// </summary>
/// <param name="sessionState">
/// The state of the engine instance to enumerate through the scopes.
/// </param>
/// <param name="lookupPath">
/// The parsed name of the item to lookup.
/// </param>
/// <exception cref="ArgumentNullException">
/// If <paramref name="sessionState"/> or <paramref name="lookupPath"/>
/// is null.
/// </exception>
internal ScopedItemSearcher(
SessionStateInternal sessionState,
VariablePath lookupPath)
{
if (sessionState == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(sessionState));
}
if (lookupPath == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(lookupPath));
}
this.sessionState = sessionState;
_lookupPath = lookupPath;
InitializeScopeEnumerator();
}
#endregion ctor
#region IEnumerable/IEnumerator members
/// <summary>
/// Gets the current object as an IEnumerator.
/// </summary>
/// <returns>
/// The current object as an IEnumerator.
/// </returns>
System.Collections.Generic.IEnumerator<T> System.Collections.Generic.IEnumerable<T>.GetEnumerator()
{
return this;
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return this;
}
/// <summary>
/// Moves the enumerator to the next matching scoped item.
/// </summary>
/// <returns>
/// True if another matching scoped item was found, or false otherwise.
/// </returns>
public bool MoveNext()
{
bool result = true;
if (!_isInitialized)
{
InitializeScopeEnumerator();
}
// Enumerate the scopes until a matching scoped item is found
while (_scopeEnumerable.MoveNext())
{
T newCurrentItem;
if (TryGetNewScopeItem(((IEnumerator<SessionStateScope>)_scopeEnumerable).Current, out newCurrentItem))
{
_currentScope = ((IEnumerator<SessionStateScope>)_scopeEnumerable).Current;
_current = newCurrentItem;
result = true;
break;
}
result = false;
if (_isSingleScopeLookup)
{
break;
}
}
return result;
}
/// <summary>
/// Gets the current scoped item.
/// </summary>
T IEnumerator<T>.Current
{
get
{
return _current;
}
}
public object Current
{
get
{
return _current;
}
}
public void Reset()
{
InitializeScopeEnumerator();
}
public void Dispose()
{
_current = default(T);
_scopeEnumerable.Dispose();
_scopeEnumerable = null;
_isInitialized = false;
GC.SuppressFinalize(this);
}
/// <summary>
/// Derived classes override this method to return their
/// particular type of scoped item.
/// </summary>
/// <param name="scope">
/// The scope to look the item up in.
/// </param>
/// <param name="name">
/// The name of the item to retrieve.
/// </param>
/// <param name="newCurrentItem">
/// The scope item that the derived class should return.
/// </param>
/// <returns>
/// True if the scope item was found or false otherwise.
/// </returns>
protected abstract bool GetScopeItem(
SessionStateScope scope,
VariablePath name,
out T newCurrentItem);
#endregion IEnumerable/IEnumerator members
/// <summary>
/// Gets the lookup scope that the Current item was found in.
/// </summary>
internal SessionStateScope CurrentLookupScope
{
get { return _currentScope; }
}
private SessionStateScope _currentScope;
/// <summary>
/// Gets the scope in which the search begins.
/// </summary>
internal SessionStateScope InitialScope
{
get { return _initialScope; }
}
private SessionStateScope _initialScope;
#region private members
private bool TryGetNewScopeItem(
SessionStateScope lookupScope,
out T newCurrentItem)
{
bool result = GetScopeItem(
lookupScope,
_lookupPath,
out newCurrentItem);
return result;
}
private void InitializeScopeEnumerator()
{
// Define the lookup scope and if we have to do single
// level or dynamic lookup based on the lookup variable
_initialScope = sessionState.CurrentScope;
if (_lookupPath.IsGlobal)
{
_initialScope = sessionState.GlobalScope;
_isSingleScopeLookup = true;
}
else if (_lookupPath.IsLocal ||
_lookupPath.IsPrivate)
{
_initialScope = sessionState.CurrentScope;
_isSingleScopeLookup = true;
}
else if (_lookupPath.IsScript)
{
_initialScope = sessionState.ScriptScope;
_isSingleScopeLookup = true;
}
_scopeEnumerable =
new SessionStateScopeEnumerator(_initialScope);
_isInitialized = true;
}
private T _current;
protected SessionStateInternal sessionState;
private readonly VariablePath _lookupPath;
private SessionStateScopeEnumerator _scopeEnumerable;
private bool _isSingleScopeLookup;
private bool _isInitialized;
#endregion private members
}
/// <summary>
/// The scope searcher for variables.
/// </summary>
internal class VariableScopeItemSearcher : ScopedItemSearcher<PSVariable>
{
public VariableScopeItemSearcher(
SessionStateInternal sessionState,
VariablePath lookupPath,
CommandOrigin origin) : base(sessionState, lookupPath)
{
_origin = origin;
}
private readonly CommandOrigin _origin;
/// <summary>
/// Derived classes override this method to return their
/// particular type of scoped item.
/// </summary>
/// <param name="scope">
/// The scope to look the item up in.
/// </param>
/// <param name="name">
/// The name of the item to retrieve.
/// </param>
/// <param name="variable">
/// The scope item that the derived class should return.
/// </param>
/// <returns>
/// True if the scope item was found or false otherwise.
/// </returns>
protected override bool GetScopeItem(
SessionStateScope scope,
VariablePath name,
out PSVariable variable)
{
Diagnostics.Assert(name is not FunctionLookupPath,
"name was scanned incorrect if we get here and it is a FunctionLookupPath");
bool result = true;
variable = scope.GetVariable(name.QualifiedName, _origin);
// If the variable is private and the lookup scope
// isn't the current scope, claim that the variable
// doesn't exist so that the lookup continues.
if (variable == null ||
(variable.IsPrivate &&
scope != sessionState.CurrentScope))
{
result = false;
}
return result;
}
}
/// <summary>
/// The scope searcher for aliases.
/// </summary>
internal class AliasScopeItemSearcher : ScopedItemSearcher<AliasInfo>
{
public AliasScopeItemSearcher(
SessionStateInternal sessionState,
VariablePath lookupPath) : base(sessionState, lookupPath)
{
}
/// <summary>
/// Derived classes override this method to return their
/// particular type of scoped item.
/// </summary>
/// <param name="scope">
/// The scope to look the item up in.
/// </param>
/// <param name="name">
/// The name of the item to retrieve.
/// </param>
/// <param name="alias">
/// The scope item that the derived class should return.
/// </param>
/// <returns>
/// True if the scope item was found or false otherwise.
/// </returns>
protected override bool GetScopeItem(
SessionStateScope scope,
VariablePath name,
out AliasInfo alias)
{
Diagnostics.Assert(name is not FunctionLookupPath,
"name was scanned incorrect if we get here and it is a FunctionLookupPath");
bool result = true;
alias = scope.GetAlias(name.QualifiedName);
// If the alias is private and the lookup scope
// isn't the current scope, claim that the alias
// doesn't exist so that the lookup continues.
if (alias == null ||
((alias.Options & ScopedItemOptions.Private) != 0 &&
scope != sessionState.CurrentScope))
{
result = false;
}
return result;
}
}
/// <summary>
/// The scope searcher for functions.
/// </summary>
internal class FunctionScopeItemSearcher : ScopedItemSearcher<FunctionInfo>
{
public FunctionScopeItemSearcher(
SessionStateInternal sessionState,
VariablePath lookupPath,
CommandOrigin origin) : base(sessionState, lookupPath)
{
_origin = origin;
}
private readonly CommandOrigin _origin;
/// <summary>
/// Derived classes override this method to return their
/// particular type of scoped item.
/// </summary>
/// <param name="scope">
/// The scope to look the item up in.
/// </param>
/// <param name="path">
/// The name of the item to retrieve.
/// </param>
/// <param name="script">
/// The scope item that the derived class should return.
/// </param>
/// <returns>
/// True if the scope item was found or false otherwise.
/// </returns>
protected override bool GetScopeItem(
SessionStateScope scope,
VariablePath path,
out FunctionInfo script)
{
Diagnostics.Assert(path is FunctionLookupPath,
"name was scanned incorrect if we get here and it is not a FunctionLookupPath");
bool result = true;
_name = path.IsFunction ? path.UnqualifiedPath : path.QualifiedName;
script = scope.GetFunction(_name);
if (script != null)
{
bool isPrivate;
FilterInfo filterInfo = script as FilterInfo;
if (filterInfo != null)
{
isPrivate = (filterInfo.Options & ScopedItemOptions.Private) != 0;
}
else
{
isPrivate = (script.Options & ScopedItemOptions.Private) != 0;
}
// If the function is private and the lookup scope
// isn't the current scope, claim that the function
// doesn't exist so that the lookup continues.
if (isPrivate &&
scope != sessionState.CurrentScope)
{
result = false;
}
else
{
// Now check the visibility of the variable...
SessionState.ThrowIfNotVisible(_origin, script);
}
}
else
{
result = false;
}
return result;
}
internal string Name
{
get { return _name; }
}
private string _name = string.Empty;
}
/// <summary>
/// The scope searcher for drives.
/// </summary>
internal class DriveScopeItemSearcher : ScopedItemSearcher<PSDriveInfo>
{
public DriveScopeItemSearcher(
SessionStateInternal sessionState,
VariablePath lookupPath) : base(sessionState, lookupPath)
{
}
/// <summary>
/// Derived classes override this method to return their
/// particular type of scoped item.
/// </summary>
/// <param name="scope">
/// The scope to look the item up in.
/// </param>
/// <param name="name">
/// The name of the item to retrieve.
/// </param>
/// <param name="drive">
/// The scope item that the derived class should return.
/// </param>
/// <returns>
/// True if the scope item was found or false otherwise.
/// </returns>
protected override bool GetScopeItem(
SessionStateScope scope,
VariablePath name,
out PSDriveInfo drive)
{
Diagnostics.Assert(name is not FunctionLookupPath,
"name was scanned incorrect if we get here and it is a FunctionLookupPath");
bool result = true;
drive = scope.GetDrive(name.DriveName);
if (drive == null)
{
result = false;
}
return result;
}
}
}
| |
// 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.Threading.Tasks;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations
{
public class ClassKeywordRecommenderTests : KeywordRecommenderTests
{
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAtRoot_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterClass_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"class C { }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGlobalStatement_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"System.Console.WriteLine();
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGlobalVariableDeclaration_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"int i = 0;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInUsingAlias()
{
await VerifyAbsenceAsync(
@"using Foo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInEmptyStatement()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInCompilationUnit()
{
await VerifyKeywordAsync(
@"$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterExtern()
{
await VerifyKeywordAsync(
@"extern alias Foo;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterUsing()
{
await VerifyKeywordAsync(
@"using Foo;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNamespace()
{
await VerifyKeywordAsync(
@"namespace N {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterTypeDeclaration()
{
await VerifyKeywordAsync(
@"class C {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterDelegateDeclaration()
{
await VerifyKeywordAsync(
@"delegate void Foo();
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterMethod()
{
await VerifyKeywordAsync(
@"class C {
void Foo() {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterField()
{
await VerifyKeywordAsync(
@"class C {
int i;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterProperty()
{
await VerifyKeywordAsync(
@"class C {
int i { get; }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotBeforeUsing()
{
await VerifyAbsenceAsync(SourceCodeKind.Regular,
@"$$
using Foo;");
}
[WpfFact(Skip = "528041"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotBeforeUsing_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"$$
using Foo;");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterAssemblyAttribute()
{
await VerifyKeywordAsync(
@"[assembly: foo]
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRootAttribute()
{
await VerifyKeywordAsync(
@"[foo]
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedAttribute()
{
await VerifyKeywordAsync(
@"class C {
[foo]
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInsideStruct()
{
await VerifyKeywordAsync(
@"struct S {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInsideInterface()
{
await VerifyAbsenceAsync(@"interface I {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInsideClass()
{
await VerifyKeywordAsync(
@"class C {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterPartial()
{
await VerifyKeywordAsync(
@"partial $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterAbstract()
{
await VerifyKeywordAsync(
@"abstract $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterInternal()
{
await VerifyKeywordAsync(
@"internal $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterStaticPublic()
{
await VerifyKeywordAsync(
@"static public $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterPublicStatic()
{
await VerifyKeywordAsync(
@"public static $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterInvalidPublic()
{
await VerifyAbsenceAsync(@"virtual public $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterPublic()
{
await VerifyKeywordAsync(
@"public $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterPrivate()
{
await VerifyKeywordAsync(
@"private $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterProtected()
{
await VerifyKeywordAsync(
@"protected $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterSealed()
{
await VerifyKeywordAsync(
@"sealed $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterStatic()
{
await VerifyKeywordAsync(
@"static $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterStaticInUsingDirective()
{
await VerifyAbsenceAsync(
@"using static $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterClass()
{
await VerifyAbsenceAsync(@"class $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotBetweenUsings()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"using Foo;
$$
using Bar;"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterClassTypeParameterConstraint()
{
await VerifyKeywordAsync(
@"class C<T> where T : $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterClassTypeParameterConstraint2()
{
await VerifyKeywordAsync(
@"class C<T>
where T : $$
where U : U");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterMethodTypeParameterConstraint()
{
await VerifyKeywordAsync(
@"class C {
void Foo<T>()
where T : $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterMethodTypeParameterConstraint2()
{
await VerifyKeywordAsync(
@"class C {
void Foo<T>()
where T : $$
where U : T");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNew()
{
await VerifyKeywordAsync(
@"class C {
new $$");
}
}
}
| |
using NUnit.Framework;
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls.Primitives;
using System.Windows.Threading;
using System.Diagnostics;
using System.Text;
using System.Linq;
using System.Reflection;
using System.Collections.Generic;
namespace DevExpress {
public class WpfTestWindow {
public static readonly DependencyProperty MethodsToSkipProperty = DependencyProperty.RegisterAttached("MethodsToSkip", typeof(IEnumerable<string>), typeof(WpfTestWindow), new PropertyMetadata(Enumerable.Empty<string>()));
public static IEnumerable<string> GetMethodsToSkip(DependencyObject obj) {
return (IEnumerable<string>)obj.GetValue(MethodsToSkipProperty);
}
public static void SetMethodsToSkip(DependencyObject obj, IEnumerable<string> value) {
obj.SetValue(MethodsToSkipProperty, value);
}
TestWindow window;
Window realWindow;
static WpfTestWindow() {
DispatcherHelper.ForceIncreasePriorityContextIdleMessages();
}
public WpfTestWindow() {
MethodsToSkip = Enumerable.Empty<string>();
}
public virtual int TimeoutInSeconds { get { return 5; } }
protected virtual TestWindow CreateTestWindow() { return TestWindow.GetContainer(); }
protected virtual Window CreateRealWindow() { return new Window(); }
protected virtual void SetUpCore() {
}
protected virtual void TearDownCore() {
if(realWindow != null) {
realWindow.SourceInitialized -= OnRealWindowSourceInitialized;
realWindow.Close();
realWindow.Content = null;
}
if (window != null) {
window.Close();
window.Content = null;
window.MaxWidth = double.PositiveInfinity;
window.MinWidth = 0.0;
window.MaxHeight = double.PositiveInfinity;
window.MinHeight = 0.0;
window.Width = double.NaN;
window.Height = double.NaN;
}
window = null;
realWindow = null;
DispatcherHelper.DoEvents();
}
IEnumerable<string> MethodsToSkip;
static Type voidType = typeof(void);
protected virtual void FixtureSetUpCore() {
List<string> methodsToSkip = new List<string>();
MethodsToSkip = methodsToSkip;
}
protected virtual void FixtureTearDownCore() {
}
[SetUp]
public void SetUp() {
SetUpCore();
}
[TearDown]
public void TearDown() {
TearDownCore();
}
[OneTimeSetUp]
public void FixtureSetUp() {
FixtureSetUpCore();
}
[OneTimeTearDown]
public void FixtureTearDown() {
FixtureTearDownCore();
}
public TestWindow Window {
get {
if(window == null) {
window = CreateTestWindow();
SetMethodsToSkip(window, MethodsToSkip);
SetThemeForWindow(window);
}
return window;
}
}
public Window RealWindow {
get {
if(realWindow == null) {
realWindow = CreateRealWindow();
realWindow.SourceInitialized += OnRealWindowSourceInitialized;
SetThemeForWindow(realWindow);
}
return realWindow;
}
}
void OnRealWindowSourceInitialized(object sender, EventArgs e) {
CheckToSkip(MethodsToSkip);
}
protected virtual void SetThemeForWindow(System.Windows.Controls.ContentControl window) {
}
public virtual void EnqueueCallback(Action testCallbackDelegate) {
testCallbackDelegate();
}
protected sealed class TimeoutGuard : IDisposable {
DispatcherTimer timer = new DispatcherTimer();
public TimeoutGuard(int timeoutInSeconds, string message) {
timer.Interval = new TimeSpan(0, 0, timeoutInSeconds);
timer.Tick += (s, e) => {
timer.Stop();
throw new Exception(message);
};
timer.Start();
}
public void Dispose() {
if(timer.IsEnabled)
timer.Stop();
}
}
public virtual void EnqueueDialog(Action testCallbackDelegate, string message = null) {
using(new TimeoutGuard(TimeoutInSeconds, GetActionTimeOutMessage(message, testCallbackDelegate))) {
testCallbackDelegate();
}
}
public virtual void EnqueueDialog<T>(Func<T> testCallbackDelegate, Action<T> result, string message = null) {
T resultValue = default(T);
using(new TimeoutGuard(TimeoutInSeconds, GetActionTimeOutMessage(message, testCallbackDelegate))) {
resultValue = testCallbackDelegate();
}
result(resultValue);
}
public void EnqueueTestWindowMainCallback(Action testCallbackDelegate) {
EnqueueShowWindow();
EnqueueLastCallback(testCallbackDelegate);
}
public void EnqueueRealWindowMainCallback(Action testCallbackDelegate) {
EnqueueShowRealWindow();
EnqueueLastCallback(testCallbackDelegate);
}
public virtual void EnqueueLastCallback(Action testCallbackDelegate) {
EnqueueCallback(testCallbackDelegate);
EnqueueTestComplete();
}
public void EnqueueDelay(int delayInMillisceconds) {
EnqueueDelay(TimeSpan.FromMilliseconds(delayInMillisceconds));
}
public void EnqueueDelay(TimeSpan delay) {
DateTime start = DateTime.Now;
while(delay > DateTime.Now - start) {
DispatcherHelper.DoEvents();
}
}
public virtual void EnqueueConditional(Func<bool> conditionalDelegate, string message) {
Assert.AreEqual(true, conditionalDelegate(), GetTimeOutMessage(message, conditionalDelegate));
}
public virtual void EnqueueWait(Func<bool> conditionalDelegate) {
EnqueWaitForObject(() => conditionalDelegate() ? conditionalDelegate : null, o => { });
}
public virtual void EnqueueWaitRealWindow(Func<bool> conditionalDelegate) {
EnqueWaitForObjectRealWindow(() => conditionalDelegate() ? conditionalDelegate : null, o => { });
}
public virtual void EnqueWaitForAsync(Thread t) {
EnqueWaitForAsync(t, DispatcherPriority.Background);
}
public virtual void EnqueWaitForAsync(Thread t, DispatcherPriority priority) {
if(t == null) return;
EnqueWaitForObject(() => t.Join(1) ? t : null, o => { }, priority);
}
public virtual void EnqueWaitForAsync(ManualResetEvent e) {
EnqueWaitForAsync(e, DispatcherPriority.Background);
}
public virtual void EnqueWaitForAsync(ManualResetEvent e, DispatcherPriority priority) {
if(e == null) return;
EnqueWaitForObject(() => e.WaitOne(1) ? e : null, o => { }, priority);
}
public virtual void EnqueWaitForAsync(Task task) {
EnqueWaitForAsync(task, DispatcherPriority.Background);
}
public virtual void EnqueWaitForAsync(Task task, DispatcherPriority priority) {
if(task == null) return;
EnqueWaitForObject(() => task.Wait(1) ? task : null, o => { }, priority);
}
public virtual void EnqueWaitForObject(Func<object> getObject, Action<object> setObject) {
EnqueWaitForObject(getObject, setObject, DispatcherPriority.Background);
}
public virtual void EnqueWaitForObjectRealWindow(Func<object> getObject, Action<object> setObject) {
EnqueWaitForObjectRealWindow(getObject, setObject, DispatcherPriority.Background);
}
public virtual void EnqueWaitForObjectRealWindow(Func<object> getObject, Action<object> setObject, DispatcherPriority priority) {
EnqueueCallback(() => {
DateTime start = DateTime.Now;
while(TimeSpan.FromSeconds(TimeoutInSeconds) > DateTime.Now - start) {
object obj = getObject();
if(obj != null) {
setObject(obj);
return;
}
DispatcherHelper.UpdateLayoutAndDoEvents(RealWindow, priority);
}
throw new Exception(GetTimeOutMessage(null, () => false));
});
}
public virtual void EnqueWaitForObject(Func<object> getObject, Action<object> setObject, DispatcherPriority priority) {
EnqueueCallback(() => {
DateTime start = DateTime.Now;
while(TimeSpan.FromSeconds(TimeoutInSeconds) > DateTime.Now - start) {
object obj = getObject();
if(obj != null) {
setObject(obj);
return;
}
DispatcherHelper.UpdateLayoutAndDoEvents(Window, priority);
}
throw new Exception(GetTimeOutMessage(null, () => false));
});
}
public virtual void EnqueDelayOrWaitForObject(Func<object> getObject, Action<object> setObject, int delayInMillisceconds) {
EnqueueCallback(() => {
DateTime start = DateTime.Now;
while(TimeSpan.FromMilliseconds(delayInMillisceconds) > DateTime.Now - start) {
object obj = getObject();
if(obj != null) {
setObject(obj);
return;
}
DispatcherHelper.UpdateLayoutAndDoEvents(Window);
}
});
}
string GetActionTimeOutMessage(string message, Delegate testDelegate) {
return string.IsNullOrEmpty(message) ? string.Format("Action aborted with timeout {0} seconds: {1}", TimeoutInSeconds, testDelegate.Method) : message;
}
protected string GetTimeOutMessage(string message, Func<bool> conditionalDelegate) {
return string.IsNullOrEmpty(message) ? string.Format("The condition failed with timeout {0} seconds: {1}", TimeoutInSeconds, conditionalDelegate.Method) : message;
}
public virtual void EnqueueConditional(Func<bool> conditionalDelegate) {
EnqueueConditional(conditionalDelegate, null);
}
public virtual void EnqueueTestComplete() {
}
public virtual void EnqueueShowRealWindow() {
EnqueueLoadedEventAction(RealWindow, () => RealWindow.Show());
}
public virtual void EnqueueShowWindow() {
EnqueueShowWindow(Window);
}
public virtual void EnqueueShowWindow(TestWindow window) {
EnqueueLoadedEventAction(window, () => window.Show());
}
public virtual void EnqueueWindowUpdateLayout() {
EnqueueCallback(delegate {
DispatcherHelper.UpdateLayoutAndDoEvents(Window);
});
}
public virtual void EnqueueWindowUpdateLayout(DispatcherPriority priority) {
EnqueueCallback(delegate {
DispatcherHelper.UpdateLayoutAndDoEvents(Window, priority);
});
}
public void EnqueueLoadedEventAction(FrameworkElement element, Action action) {
EnqueueLoadedEventAction(() => element, action);
}
public void EnqueueLoadedEventAction(Func<FrameworkElement> getElement, Action action) {
EnqueueWaitEventEventAction(getElement, action, (getElementDelegate, handler) => getElementDelegate().Loaded += handler);
}
public void EnqueueClickButton(Func<ButtonBase> getButtonDelegate) {
EnqueueWaitEventEventAction(() => getButtonDelegate(), () => UITestHelper.ClickButton(getButtonDelegate()), (getElementDelegate_, handler) => ((ButtonBase)getElementDelegate_()).Click += handler);
}
public void EnqueueClickButton(ButtonBase button) {
EnqueueClickButton(() => button);
}
protected delegate void SubscribeDelegate(Func<FrameworkElement> getElementDelegate, RoutedEventHandler handler);
protected void EnqueueWaitEventEventAction(Func<FrameworkElement> getElementDelegate, Action action, SubscribeDelegate subscribeDelegate) {
action();
}
protected void EnqueueWaitRenderAction() { }
public static void CheckToSkip(IEnumerable<string> methodsToSkip) {
if (methodsToSkip.Count() == 0)
return;
}
}
}
| |
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
namespace osu.Framework.Input.Bindings
{
/// <summary>
/// A collection of keys, mouse and other controllers' buttons.
/// </summary>
public enum InputKey
{
/// <summary>
/// No key pressed.
/// </summary>
None = 0,
/// <summary>
/// The shift key.
/// </summary>
Shift = 1,
/// <summary>
/// The control key.
/// </summary>
Control = 3,
/// <summary>
/// The alt key.
/// </summary>
Alt = 5,
/// <summary>
/// The win key.
/// </summary>
Super = 7,
/// <summary>
/// The menu key.
/// </summary>
Menu = 9,
/// <summary>
/// The F1 key.
/// </summary>
F1 = 10,
/// <summary>
/// The F2 key.
/// </summary>
F2 = 11,
/// <summary>
/// The F3 key.
/// </summary>
F3 = 12,
/// <summary>
/// The F4 key.
/// </summary>
F4 = 13,
/// <summary>
/// The F5 key.
/// </summary>
F5 = 14,
/// <summary>
/// The F6 key.
/// </summary>
F6 = 15,
/// <summary>
/// The F7 key.
/// </summary>
F7 = 16,
/// <summary>
/// The F8 key.
/// </summary>
F8 = 17,
/// <summary>
/// The F9 key.
/// </summary>
F9 = 18,
/// <summary>
/// The F10 key.
/// </summary>
F10 = 19,
/// <summary>
/// The F11 key.
/// </summary>
F11 = 20,
/// <summary>
/// The F12 key.
/// </summary>
F12 = 21,
/// <summary>
/// The F13 key.
/// </summary>
F13 = 22,
/// <summary>
/// The F14 key.
/// </summary>
F14 = 23,
/// <summary>
/// The F15 key.
/// </summary>
F15 = 24,
/// <summary>
/// The F16 key.
/// </summary>
F16 = 25,
/// <summary>
/// The F17 key.
/// </summary>
F17 = 26,
/// <summary>
/// The F18 key.
/// </summary>
F18 = 27,
/// <summary>
/// The F19 key.
/// </summary>
F19 = 28,
/// <summary>
/// The F20 key.
/// </summary>
F20 = 29,
/// <summary>
/// The F21 key.
/// </summary>
F21 = 30,
/// <summary>
/// The F22 key.
/// </summary>
F22 = 31,
/// <summary>
/// The F23 key.
/// </summary>
F23 = 32,
/// <summary>
/// The F24 key.
/// </summary>
F24 = 33,
/// <summary>
/// The F25 key.
/// </summary>
F25 = 34,
/// <summary>
/// The F26 key.
/// </summary>
F26 = 35,
/// <summary>
/// The F27 key.
/// </summary>
F27 = 36,
/// <summary>
/// The F28 key.
/// </summary>
F28 = 37,
/// <summary>
/// The F29 key.
/// </summary>
F29 = 38,
/// <summary>
/// The F30 key.
/// </summary>
F30 = 39,
/// <summary>
/// The F31 key.
/// </summary>
F31 = 40,
/// <summary>
/// The F32 key.
/// </summary>
F32 = 41,
/// <summary>
/// The F33 key.
/// </summary>
F33 = 42,
/// <summary>
/// The F34 key.
/// </summary>
F34 = 43,
/// <summary>
/// The F35 key.
/// </summary>
F35 = 44,
/// <summary>
/// The up arrow key.
/// </summary>
Up = 45,
/// <summary>
/// The down arrow key.
/// </summary>
Down = 46,
/// <summary>
/// The left arrow key.
/// </summary>
Left = 47,
/// <summary>
/// The right arrow key.
/// </summary>
Right = 48,
/// <summary>
/// The enter key.
/// </summary>
Enter = 49,
/// <summary>
/// The escape key.
/// </summary>
Escape = 50,
/// <summary>
/// The space key.
/// </summary>
Space = 51,
/// <summary>
/// The tab key.
/// </summary>
Tab = 52,
/// <summary>
/// The backspace key.
/// </summary>
BackSpace = 53,
/// <summary>
/// The backspace key (equivalent to BackSpace).
/// </summary>
Back = 53,
/// <summary>
/// The insert key.
/// </summary>
Insert = 54,
/// <summary>
/// The delete key.
/// </summary>
Delete = 55,
/// <summary>
/// The page up key.
/// </summary>
PageUp = 56,
/// <summary>
/// The page down key.
/// </summary>
PageDown = 57,
/// <summary>
/// The home key.
/// </summary>
Home = 58,
/// <summary>
/// The end key.
/// </summary>
End = 59,
/// <summary>
/// The caps lock key.
/// </summary>
CapsLock = 60,
/// <summary>
/// The scroll lock key.
/// </summary>
ScrollLock = 61,
/// <summary>
/// The print screen key.
/// </summary>
PrintScreen = 62,
/// <summary>
/// The pause key.
/// </summary>
Pause = 63,
/// <summary>
/// The num lock key.
/// </summary>
NumLock = 64,
/// <summary>
/// The clear key (Keypad5 with NumLock disabled, on typical keyboards).
/// </summary>
Clear = 65,
/// <summary>
/// The sleep key.
/// </summary>
Sleep = 66,
/// <summary>
/// The keypad 0 key.
/// </summary>
Keypad0 = 67,
/// <summary>
/// The keypad 1 key.
/// </summary>
Keypad1 = 68,
/// <summary>
/// The keypad 2 key.
/// </summary>
Keypad2 = 69,
/// <summary>
/// The keypad 3 key.
/// </summary>
Keypad3 = 70,
/// <summary>
/// The keypad 4 key.
/// </summary>
Keypad4 = 71,
/// <summary>
/// The keypad 5 key.
/// </summary>
Keypad5 = 72,
/// <summary>
/// The keypad 6 key.
/// </summary>
Keypad6 = 73,
/// <summary>
/// The keypad 7 key.
/// </summary>
Keypad7 = 74,
/// <summary>
/// The keypad 8 key.
/// </summary>
Keypad8 = 75,
/// <summary>
/// The keypad 9 key.
/// </summary>
Keypad9 = 76,
/// <summary>
/// The keypad divide key.
/// </summary>
KeypadDivide = 77,
/// <summary>
/// The keypad multiply key.
/// </summary>
KeypadMultiply = 78,
/// <summary>
/// The keypad subtract key.
/// </summary>
KeypadSubtract = 79,
/// <summary>
/// The keypad minus key (equivalent to KeypadSubtract).
/// </summary>
KeypadMinus = 79,
/// <summary>
/// The keypad add key.
/// </summary>
KeypadAdd = 80,
/// <summary>
/// The keypad plus key (equivalent to KeypadAdd).
/// </summary>
KeypadPlus = 80,
/// <summary>
/// The keypad decimal key.
/// </summary>
KeypadDecimal = 81,
/// <summary>
/// The keypad period key (equivalent to KeypadDecimal).
/// </summary>
KeypadPeriod = 81,
/// <summary>
/// The keypad enter key.
/// </summary>
KeypadEnter = 82,
/// <summary>
/// The A key.
/// </summary>
A = 83,
/// <summary>
/// The B key.
/// </summary>
B = 84,
/// <summary>
/// The C key.
/// </summary>
C = 85,
/// <summary>
/// The D key.
/// </summary>
D = 86,
/// <summary>
/// The E key.
/// </summary>
E = 87,
/// <summary>
/// The F key.
/// </summary>
F = 88,
/// <summary>
/// The G key.
/// </summary>
G = 89,
/// <summary>
/// The H key.
/// </summary>
H = 90,
/// <summary>
/// The I key.
/// </summary>
I = 91,
/// <summary>
/// The J key.
/// </summary>
J = 92,
/// <summary>
/// The K key.
/// </summary>
K = 93,
/// <summary>
/// The L key.
/// </summary>
L = 94,
/// <summary>
/// The M key.
/// </summary>
M = 95,
/// <summary>
/// The N key.
/// </summary>
N = 96,
/// <summary>
/// The O key.
/// </summary>
O = 97,
/// <summary>
/// The P key.
/// </summary>
P = 98,
/// <summary>
/// The Q key.
/// </summary>
Q = 99,
/// <summary>
/// The R key.
/// </summary>
R = 100,
/// <summary>
/// The S key.
/// </summary>
S = 101,
/// <summary>
/// The T key.
/// </summary>
T = 102,
/// <summary>
/// The U key.
/// </summary>
U = 103,
/// <summary>
/// The V key.
/// </summary>
V = 104,
/// <summary>
/// The W key.
/// </summary>
W = 105,
/// <summary>
/// The X key.
/// </summary>
X = 106,
/// <summary>
/// The Y key.
/// </summary>
Y = 107,
/// <summary>
/// The Z key.
/// </summary>
Z = 108,
/// <summary>
/// The number 0 key.
/// </summary>
Number0 = 109,
/// <summary>
/// The number 1 key.
/// </summary>
Number1 = 110,
/// <summary>
/// The number 2 key.
/// </summary>
Number2 = 111,
/// <summary>
/// The number 3 key.
/// </summary>
Number3 = 112,
/// <summary>
/// The number 4 key.
/// </summary>
Number4 = 113,
/// <summary>
/// The number 5 key.
/// </summary>
Number5 = 114,
/// <summary>
/// The number 6 key.
/// </summary>
Number6 = 115,
/// <summary>
/// The number 7 key.
/// </summary>
Number7 = 116,
/// <summary>
/// The number 8 key.
/// </summary>
Number8 = 117,
/// <summary>
/// The number 9 key.
/// </summary>
Number9 = 118,
/// <summary>
/// The tilde key.
/// </summary>
Tilde = 119,
/// <summary>
/// The grave key (equivaent to Tilde).
/// </summary>
Grave = 119,
/// <summary>
/// The minus key.
/// </summary>
Minus = 120,
/// <summary>
/// The plus key.
/// </summary>
Plus = 121,
/// <summary>
/// The left bracket key.
/// </summary>
BracketLeft = 122,
/// <summary>
/// The left bracket key (equivalent to BracketLeft).
/// </summary>
LBracket = 122,
/// <summary>
/// The right bracket key.
/// </summary>
BracketRight = 123,
/// <summary>
/// The right bracket key (equivalent to BracketRight).
/// </summary>
RBracket = 123,
/// <summary>
/// The semicolon key.
/// </summary>
Semicolon = 124,
/// <summary>
/// The quote key.
/// </summary>
Quote = 125,
/// <summary>
/// The comma key.
/// </summary>
Comma = 126,
/// <summary>
/// The period key.
/// </summary>
Period = 127,
/// <summary>
/// The slash key.
/// </summary>
Slash = 128,
/// <summary>
/// The backslash key.
/// </summary>
BackSlash = 129,
/// <summary>
/// The secondary backslash key.
/// </summary>
NonUSBackSlash = 130,
/// <summary>
/// Indicates the last available keyboard key.
/// </summary>
LastKey = 131,
FirstMouseButton = 132,
/// <summary>
/// The left mouse button.
/// </summary>
MouseLeft = 132,
/// <summary>
/// The middle mouse button.
/// </summary>
MouseMiddle = 133,
/// <summary>
/// The right mouse button.
/// </summary>
MouseRight = 134,
/// <summary>
/// The first extra mouse button.
/// </summary>
MouseButton1 = 135,
/// <summary>
/// The second extra mouse button.
/// </summary>
MouseButton2 = 136,
/// <summary>
/// The third extra mouse button.
/// </summary>
MouseButton3 = 137,
/// <summary>
/// The fourth extra mouse button.
/// </summary>
MouseButton4 = 138,
/// <summary>
/// The fifth extra mouse button.
/// </summary>
MouseButton5 = 139,
/// <summary>
/// The sixth extra mouse button.
/// </summary>
MouseButton6 = 140,
/// <summary>
/// The seventh extra mouse button.
/// </summary>
MouseButton7 = 141,
/// <summary>
/// The eigth extra mouse button.
/// </summary>
MouseButton8 = 142,
/// <summary>
/// The ninth extra mouse button.
/// </summary>
MouseButton9 = 143,
/// <summary>
/// Indicates the last available mouse button.
/// </summary>
MouseLastButton = 144,
/// <summary>
/// Mouse wheel rolled up.
/// </summary>
MouseWheelUp = 145,
/// <summary>
/// Mouse wheel rolled down.
/// </summary>
MouseWheelDown = 146
}
}
| |
// 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 Debug = System.Diagnostics.Debug;
namespace Internal.TypeSystem
{
public static partial class CastingHelper
{
/// <summary>
/// Returns true if '<paramref name="thisType"/>' can be cast to '<paramref name="otherType"/>'.
/// Assumes '<paramref name="thisType"/>' is in it's boxed form if it's a value type (i.e.
/// [System.Int32].CanCastTo([System.Object]) will return true).
/// </summary>
public static bool CanCastTo(this TypeDesc thisType, TypeDesc otherType)
{
return thisType.CanCastToInternal(otherType, null);
}
private static bool CanCastToInternal(this TypeDesc thisType, TypeDesc otherType, StackOverflowProtect protect)
{
if (thisType == otherType)
{
return true;
}
switch (thisType.Category)
{
case TypeFlags.GenericParameter:
return ((GenericParameterDesc)thisType).CanCastGenericParameterTo(otherType, protect);
case TypeFlags.Array:
case TypeFlags.SzArray:
return ((ArrayType)thisType).CanCastArrayTo(otherType, protect);
default:
Debug.Assert(thisType.IsDefType);
return thisType.CanCastToClassOrInterface(otherType, protect);
}
}
private static bool CanCastGenericParameterTo(this GenericParameterDesc thisType, TypeDesc otherType, StackOverflowProtect protect)
{
// A boxed variable type can be cast to any of its constraints, or object, if none are specified
if (otherType.IsObject)
{
return true;
}
if (thisType.HasNotNullableValueTypeConstraint &&
otherType.IsWellKnownType(WellKnownType.ValueType))
{
return true;
}
foreach (var typeConstraint in thisType.TypeConstraints)
{
if (typeConstraint.CanCastToInternal(otherType, protect))
{
return true;
}
}
return false;
}
private static bool CanCastArrayTo(this ArrayType thisType, TypeDesc otherType, StackOverflowProtect protect)
{
// Casting the array to one of the base types or interfaces?
if (otherType.IsDefType)
{
return thisType.CanCastToClassOrInterface(otherType, protect);
}
// Casting array to something else (between SzArray and Array, for example)?
if (thisType.Category != otherType.Category)
{
return false;
}
ArrayType otherArrayType = (ArrayType)otherType;
// Check ranks if we're casting multidim arrays
if (!thisType.IsSzArray && thisType.Rank != otherArrayType.Rank)
{
return false;
}
return thisType.CanCastParamTo(otherArrayType.ParameterType, protect);
}
private static bool CanCastParamTo(this ParameterizedType thisType, TypeDesc paramType, StackOverflowProtect protect)
{
// While boxed value classes inherit from object their
// unboxed versions do not. Parameterized types have the
// unboxed version, thus, if the from type parameter is value
// class then only an exact match/equivalence works.
if (thisType.ParameterType == paramType)
{
return true;
}
TypeDesc curTypesParm = thisType.ParameterType;
// Object parameters don't need an exact match but only inheritance, check for that
TypeDesc fromParamUnderlyingType = curTypesParm.UnderlyingType;
if (fromParamUnderlyingType.IsGCPointer)
{
return curTypesParm.CanCastToInternal(paramType, protect);
}
else if (curTypesParm.IsGenericParameter)
{
var genericVariableFromParam = (GenericParameterDesc)curTypesParm;
if (genericVariableFromParam.HasReferenceTypeConstraint)
{
return genericVariableFromParam.CanCastToInternal(paramType, protect);
}
}
else if (fromParamUnderlyingType.IsPrimitive)
{
TypeDesc toParamUnderlyingType = paramType.UnderlyingType;
if (toParamUnderlyingType.IsPrimitive)
{
if (toParamUnderlyingType == fromParamUnderlyingType)
{
return true;
}
if (ArePrimitveTypesEquivalentSize(fromParamUnderlyingType, toParamUnderlyingType))
{
return true;
}
}
}
// Anything else is not a match
return false;
}
// Returns true of the two types are equivalent primitive types. Used by array casts.
private static bool ArePrimitveTypesEquivalentSize(TypeDesc type1, TypeDesc type2)
{
Debug.Assert(type1.IsPrimitive && type2.IsPrimitive);
// Primitive types such as E_T_I4 and E_T_U4 are interchangeable
// Enums with interchangeable underlying types are interchangable
// BOOL is NOT interchangeable with I1/U1, neither CHAR -- with I2/U2
// Float and double are not interchangable here.
int sourcePrimitiveTypeEquivalenceSize = type1.GetIntegralTypeMatchSize();
// Quick check to see if the first type can be matched.
if (sourcePrimitiveTypeEquivalenceSize == 0)
{
return false;
}
int targetPrimitiveTypeEquivalenceSize = type2.GetIntegralTypeMatchSize();
return sourcePrimitiveTypeEquivalenceSize == targetPrimitiveTypeEquivalenceSize;
}
private static int GetIntegralTypeMatchSize(this TypeDesc type)
{
Debug.Assert(type.IsPrimitive);
switch (type.Category)
{
case TypeFlags.SByte:
case TypeFlags.Byte:
return 1;
case TypeFlags.UInt16:
case TypeFlags.Int16:
return 2;
case TypeFlags.Int32:
case TypeFlags.UInt32:
return 4;
case TypeFlags.Int64:
case TypeFlags.UInt64:
return 8;
case TypeFlags.IntPtr:
case TypeFlags.UIntPtr:
return type.Context.Target.PointerSize;
default:
return 0;
}
}
private static bool CanCastToClassOrInterface(this TypeDesc thisType, TypeDesc otherType, StackOverflowProtect protect)
{
if (otherType.IsInterface)
{
return thisType.CanCastToInterface(otherType, protect);
}
else
{
return thisType.CanCastToClass(otherType, protect);
}
}
private static bool CanCastToInterface(this TypeDesc thisType, TypeDesc otherType, StackOverflowProtect protect)
{
if (!otherType.HasVariance)
{
return thisType.CanCastToNonVariantInterface(otherType,protect);
}
else
{
if (thisType.CanCastByVarianceToInterfaceOrDelegate(otherType, protect))
{
return true;
}
foreach (var interfaceType in thisType.RuntimeInterfaces)
{
if (interfaceType.CanCastByVarianceToInterfaceOrDelegate(otherType, protect))
{
return true;
}
}
}
return false;
}
private static bool CanCastToNonVariantInterface(this TypeDesc thisType, TypeDesc otherType, StackOverflowProtect protect)
{
if (otherType == thisType)
{
return true;
}
foreach (var interfaceType in thisType.RuntimeInterfaces)
{
if (interfaceType == otherType)
{
return true;
}
}
return false;
}
private static bool CanCastByVarianceToInterfaceOrDelegate(this TypeDesc thisType, TypeDesc otherType, StackOverflowProtect protectInput)
{
if (!thisType.HasSameTypeDefinition(otherType))
{
return false;
}
var stackOverflowProtectKey = new CastingPair(thisType, otherType);
if (protectInput != null)
{
if (protectInput.Contains(stackOverflowProtectKey))
return false;
}
StackOverflowProtect protect = new StackOverflowProtect(stackOverflowProtectKey, protectInput);
Instantiation instantiationThis = thisType.Instantiation;
Instantiation instantiationTarget = otherType.Instantiation;
Instantiation instantiationOpen = thisType.GetTypeDefinition().Instantiation;
Debug.Assert(instantiationThis.Length == instantiationTarget.Length &&
instantiationThis.Length == instantiationOpen.Length);
for (int i = 0; i < instantiationThis.Length; i++)
{
TypeDesc arg = instantiationThis[i];
TypeDesc targetArg = instantiationTarget[i];
if (arg != targetArg)
{
GenericParameterDesc openArgType = (GenericParameterDesc)instantiationOpen[i];
switch (openArgType.Variance)
{
case GenericVariance.Covariant:
if (!arg.IsBoxedAndCanCastTo(targetArg, protect))
return false;
break;
case GenericVariance.Contravariant:
if (!targetArg.IsBoxedAndCanCastTo(arg, protect))
return false;
break;
default:
// non-variant
Debug.Assert(openArgType.Variance == GenericVariance.None);
return false;
}
}
}
return true;
}
private static bool CanCastToClass(this TypeDesc thisType, TypeDesc otherType, StackOverflowProtect protect)
{
TypeDesc curType = thisType;
// If the target type has variant type parameters, we take a slower path
if (curType.HasVariance)
{
// First chase inheritance hierarchy until we hit a class that only differs in its instantiation
do
{
if (curType == otherType)
{
return true;
}
if (curType.CanCastByVarianceToInterfaceOrDelegate(otherType, protect))
{
return true;
}
curType = curType.BaseType;
}
while (curType != null);
}
else
{
// If there are no variant type parameters, just chase the hierarchy
// Allow curType to be nullable, which means this method
// will additionally return true if curType is Nullable<T> && (
// currType == otherType
// OR otherType is System.ValueType or System.Object)
// Always strip Nullable from the otherType, if present
if (otherType.IsNullable && !curType.IsNullable)
{
return thisType.CanCastTo(otherType.Instantiation[0]);
}
do
{
if (curType == otherType)
return true;
curType = curType.BaseType;
} while (curType != null);
}
return false;
}
private static bool IsBoxedAndCanCastTo(this TypeDesc thisType, TypeDesc otherType, StackOverflowProtect protect)
{
TypeDesc fromUnderlyingType = thisType.UnderlyingType;
if (fromUnderlyingType.IsGCPointer)
{
return thisType.CanCastToInternal(otherType, protect);
}
else if (thisType.IsGenericParameter)
{
var genericVariableFromParam = (GenericParameterDesc)thisType;
if (genericVariableFromParam.HasReferenceTypeConstraint)
{
return genericVariableFromParam.CanCastToInternal(otherType, protect);
}
}
return false;
}
private class StackOverflowProtect
{
private CastingPair _value;
private StackOverflowProtect _previous;
public StackOverflowProtect(CastingPair value, StackOverflowProtect previous)
{
_value = value;
_previous = previous;
}
public bool Contains(CastingPair value)
{
for (var current = this; current != null; current = current._previous)
if (current._value.Equals(value))
return true;
return false;
}
}
private struct CastingPair
{
public readonly TypeDesc FromType;
public readonly TypeDesc ToType;
public CastingPair(TypeDesc fromType, TypeDesc toType)
{
FromType = fromType;
ToType = toType;
}
public bool Equals(CastingPair other) => FromType == other.FromType && ToType == other.ToType;
}
}
}
| |
using System;
using System.Linq;
using System.Collections.Generic;
using System.Reflection;
using System.IO;
using System.Reflection.Metadata.Ecma335;
using System.Reflection.Metadata;
namespace Semmle.Extraction.CIL.Entities
{
/// <summary>
/// A type defined in the current assembly.
/// </summary>
internal sealed class TypeDefinitionType : Type
{
private readonly TypeDefinitionHandle handle;
private readonly TypeDefinition td;
private readonly Lazy<IEnumerable<TypeTypeParameter>> typeParams;
private readonly Type? declType;
private readonly NamedTypeIdWriter idWriter;
public TypeDefinitionType(Context cx, TypeDefinitionHandle handle) : base(cx)
{
idWriter = new NamedTypeIdWriter(this);
td = cx.MdReader.GetTypeDefinition(handle);
this.handle = handle;
declType =
td.GetDeclaringType().IsNil ? null :
(Type)cx.Create(td.GetDeclaringType());
// Lazy because should happen during population.
typeParams = new Lazy<IEnumerable<TypeTypeParameter>>(MakeTypeParameters);
}
public override bool Equals(object? obj)
{
return obj is TypeDefinitionType t && handle.Equals(t.handle);
}
public override int GetHashCode() => handle.GetHashCode();
public override void WriteId(EscapingTextWriter trapFile, bool inContext)
{
idWriter.WriteId(trapFile, inContext);
}
public override string Name => GenericsHelper.GetNonGenericName(td.Name, Context.MdReader);
public override Namespace ContainingNamespace => Context.Create(td.NamespaceDefinition);
public override Type? ContainingType => declType;
public override CilTypeKind Kind => CilTypeKind.ValueOrRefType;
public override Type Construct(IEnumerable<Type> typeArguments)
{
if (TotalTypeParametersCount != typeArguments.Count())
throw new InternalError("Mismatched type arguments");
return Context.Populate(new ConstructedType(Context, this, typeArguments));
}
public override void WriteAssemblyPrefix(TextWriter trapFile)
{
var ct = ContainingType;
if (ct is null)
Context.WriteAssemblyPrefix(trapFile);
else if (IsPrimitiveType)
trapFile.Write(Type.PrimitiveTypePrefix);
else
ct.WriteAssemblyPrefix(trapFile);
}
private IEnumerable<TypeTypeParameter> MakeTypeParameters()
{
if (ThisTypeParameterCount == 0)
return Enumerable.Empty<TypeTypeParameter>();
var newTypeParams = new TypeTypeParameter[ThisTypeParameterCount];
var genericParams = td.GetGenericParameters();
var toSkip = genericParams.Count - newTypeParams.Length;
// Two-phase population because type parameters can be mutually dependent
for (var i = 0; i < newTypeParams.Length; ++i)
newTypeParams[i] = Context.Populate(new TypeTypeParameter(this, i));
for (var i = 0; i < newTypeParams.Length; ++i)
newTypeParams[i].PopulateHandle(genericParams[i + toSkip]);
return newTypeParams;
}
public override int ThisTypeParameterCount
{
get
{
var containingType = td.GetDeclaringType();
var parentTypeParameters = containingType.IsNil
? 0
: Context.MdReader.GetTypeDefinition(containingType).GetGenericParameters().Count;
return td.GetGenericParameters().Count - parentTypeParameters;
}
}
public override IEnumerable<Type> TypeParameters => GenericsHelper.GetAllTypeParameters(declType, typeParams!.Value);
public override IEnumerable<Type> ThisGenericArguments => typeParams.Value;
public override IEnumerable<IExtractionProduct> Contents
{
get
{
yield return Tuples.metadata_handle(this, Context.Assembly, MetadataTokens.GetToken(handle));
foreach (var c in base.Contents) yield return c;
MakeTypeParameters();
foreach (var f in td.GetFields())
{
// Populate field if needed
yield return Context.CreateGeneric(this, f);
}
foreach (var prop in td.GetProperties())
{
yield return new Property(this, this, prop);
}
foreach (var @event in td.GetEvents())
{
yield return new Event(Context, this, @event);
}
foreach (var a in Attribute.Populate(Context, this, td.GetCustomAttributes()))
yield return a;
foreach (var impl in td.GetMethodImplementations().Select(i => Context.MdReader.GetMethodImplementation(i)))
{
var m = (Method)Context.CreateGeneric(this, impl.MethodBody);
var decl = (Method)Context.CreateGeneric(this, impl.MethodDeclaration);
yield return m;
yield return decl;
yield return Tuples.cil_implements(m, decl);
}
if (td.Attributes.HasFlag(TypeAttributes.Abstract))
yield return Tuples.cil_abstract(this);
if (td.Attributes.HasFlag(TypeAttributes.Interface))
yield return Tuples.cil_interface(this);
else
yield return Tuples.cil_class(this);
if (td.Attributes.HasFlag(TypeAttributes.Public))
yield return Tuples.cil_public(this);
if (td.Attributes.HasFlag(TypeAttributes.Sealed))
yield return Tuples.cil_sealed(this);
if (td.Attributes.HasFlag(TypeAttributes.HasSecurity))
yield return Tuples.cil_security(this);
// Base types
if (!td.BaseType.IsNil)
{
var @base = (Type)Context.CreateGeneric(this, td.BaseType);
yield return @base;
yield return Tuples.cil_base_class(this, @base);
if (IsSystemEnum(td.BaseType) &&
GetUnderlyingEnumType() is var underlying &&
underlying.HasValue)
{
var underlyingType = Context.Create(underlying.Value);
yield return underlyingType;
yield return Tuples.cil_enum_underlying_type(this, underlyingType);
}
}
foreach (var @interface in td.GetInterfaceImplementations().Select(i => Context.MdReader.GetInterfaceImplementation(i)))
{
var t = (Type)Context.CreateGeneric(this, @interface.Interface);
yield return t;
yield return Tuples.cil_base_interface(this, t);
}
// Only type definitions have locations.
yield return Tuples.cil_type_location(this, Context.Assembly);
}
}
private bool IsSystemEnum(EntityHandle baseType)
{
return baseType.Kind switch
{
HandleKind.TypeReference => IsSystemEnum((TypeReferenceHandle)baseType),
HandleKind.TypeDefinition => IsSystemEnum((TypeDefinitionHandle)baseType),
_ => false,
};
}
private bool IsSystemEnum(TypeReferenceHandle baseType)
{
var baseTypeReference = Context.MdReader.GetTypeReference(baseType);
return IsSystemEnum(baseTypeReference.Name, baseTypeReference.Namespace);
}
private bool IsSystemEnum(TypeDefinitionHandle baseType)
{
var baseTypeDefinition = Context.MdReader.GetTypeDefinition(baseType);
return IsSystemEnum(baseTypeDefinition.Name, baseTypeDefinition.Namespace);
}
private bool IsSystemEnum(StringHandle typeName, StringHandle namespaceName)
{
return Context.MdReader.StringComparer.Equals(typeName, "Enum") &&
!namespaceName.IsNil &&
Context.MdReader.StringComparer.Equals(namespaceName, "System");
}
internal PrimitiveTypeCode? GetUnderlyingEnumType()
{
foreach (var handle in td.GetFields())
{
var field = Context.MdReader.GetFieldDefinition(handle);
if (field.Attributes.HasFlag(FieldAttributes.Static))
{
continue;
}
var blob = Context.MdReader.GetBlobReader(field.Signature);
if (blob.ReadSignatureHeader().Kind != SignatureKind.Field)
{
break;
}
return (PrimitiveTypeCode)blob.ReadByte();
}
return null;
}
internal override Method LookupMethod(StringHandle name, BlobHandle signature)
{
foreach (var h in td.GetMethods())
{
var md = Context.MdReader.GetMethodDefinition(h);
if (md.Name == name && md.Signature == signature)
{
return (Method)Context.Create(h);
}
}
throw new InternalError("Couldn't locate method in type");
}
}
}
| |
// 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.Threading;
using System.ComponentModel;
using System.Diagnostics;
namespace MS.Win32
{
using Accessibility;
using SRCS = System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System;
using System.Collections;
using System.IO;
using System.Text;
using System.Security;
using Microsoft.Win32.SafeHandles;
using MS.Internal;
using MS.Internal.Interop;
using MS.Utility;
#if WINDOWS_BASE
using MS.Internal.WindowsBase;
#elif PRESENTATION_CORE
using MS.Internal.PresentationCore;
#elif PRESENTATIONFRAMEWORK
using MS.Internal.PresentationFramework;
#elif DRT
using MS.Internal.Drt;
#else
#error Attempt to use FriendAccessAllowedAttribute from an unknown assembly.
using MS.Internal.YourAssemblyName;
#endif
using IComDataObject = System.Runtime.InteropServices.ComTypes.IDataObject;
[FriendAccessAllowed]
internal partial class UnsafeNativeMethods
{
[DllImport(ExternDll.Kernel32, CharSet=CharSet.Unicode, SetLastError=true, EntryPoint="GetTempFileName")]
internal static extern uint _GetTempFileName(string tmpPath, string prefix, uint uniqueIdOrZero, StringBuilder tmpFileName);
internal static uint GetTempFileName(string tmpPath, string prefix, uint uniqueIdOrZero, StringBuilder tmpFileName)
{
uint result = _GetTempFileName(tmpPath, prefix, uniqueIdOrZero, tmpFileName);
if (result == 0)
{
throw new Win32Exception();
}
return result;
}
[DllImport(ExternDll.Shell32, CharSet = System.Runtime.InteropServices.CharSet.Auto, BestFitMapping = false, ThrowOnUnmappableChar = true)]
internal static extern int ExtractIconEx(
string szExeFileName,
int nIconIndex,
out NativeMethods.IconHandle phiconLarge,
out NativeMethods.IconHandle phiconSmall,
int nIcons);
[DllImport(ExternDll.User32, CharSet = System.Runtime.InteropServices.CharSet.Auto, SetLastError=true)]
internal static extern NativeMethods.IconHandle CreateIcon(IntPtr hInstance, int nWidth, int nHeight, byte cPlanes, byte cBitsPixel, byte[] lpbANDbits, byte[] lpbXORbits);
[DllImport(ExternDll.User32, SetLastError = true)]
public static extern bool CreateCaret(HandleRef hwnd, NativeMethods.BitmapHandle hbitmap, int width, int height);
[DllImport(ExternDll.User32, SetLastError = true)]
public static extern bool ShowCaret(HandleRef hwnd);
[DllImport(ExternDll.User32, SetLastError = true)]
public static extern bool HideCaret(HandleRef hwnd);
[DllImport(ExternDll.User32, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
public static extern bool ShowWindowAsync(HandleRef hWnd, int nCmdShow);
[DllImport(ExternDll.User32, EntryPoint="LoadImage", CharSet = System.Runtime.InteropServices.CharSet.Auto, SetLastError = true, BestFitMapping = false, ThrowOnUnmappableChar = true)]
internal static extern NativeMethods.IconHandle LoadImageIcon(IntPtr hinst, string stName, int nType, int cxDesired, int cyDesired, int nFlags);
[DllImport(ExternDll.User32, EntryPoint="LoadImage", CharSet = System.Runtime.InteropServices.CharSet.Auto, SetLastError = true, BestFitMapping = false, ThrowOnUnmappableChar = true)]
internal static extern NativeMethods.CursorHandle LoadImageCursor(IntPtr hinst, string stName, int nType, int cxDesired, int cyDesired, int nFlags);
// uncomment this if you plan to use LoadImage to load anything other than Icons/Cursors.
/*
[DllImport(ExternDll.User32, CharSet = System.Runtime.InteropServices.CharSet.Auto, SetLastError = true, BestFitMapping = false, ThrowOnUnmappableChar = true)]
internal static extern SafeHandle LoadImage(
IntPtr hinst, string stName, int nType, int cxDesired, int cyDesired, int nFlags);
*/
/*
[DllImport(ExternDll.User32, CharSet = System.Runtime.InteropServices.CharSet.Auto, SetLastError = true, BestFitMapping = false, ThrowOnUnmappableChar = true)]
internal static extern NativeMethods.IconHandle LoadImage(
IntPtr hinst, string stName, int nType, int cxDesired, int cyDesired, int nFlags);
*/
[DllImport( ExternDll.Urlmon, ExactSpelling=true)]
internal static extern int CoInternetIsFeatureEnabled( int featureEntry , int dwFlags );
[DllImport( ExternDll.Urlmon, ExactSpelling=true)]
internal static extern int CoInternetSetFeatureEnabled( int featureEntry , int dwFlags, bool fEnable );
[DllImport( ExternDll.Urlmon, ExactSpelling=true)]
internal static extern int CoInternetIsFeatureZoneElevationEnabled(
[MarshalAs(UnmanagedType.LPWStr)] string szFromURL,
[MarshalAs(UnmanagedType.LPWStr)] string szToURL,
UnsafeNativeMethods.IInternetSecurityManager secMgr,
int dwFlags
);
[DllImport(ExternDll.PresentationHostDll, EntryPoint = "ProcessUnhandledException")]
internal static extern void ProcessUnhandledException_DLL([MarshalAs(UnmanagedType.BStr)] string errMsg);
[DllImport(ExternDll.Kernel32, CharSet=CharSet.Unicode)]
internal static extern bool GetVersionEx([In, Out] NativeMethods.OSVERSIONINFOEX ver);
[DllImport( ExternDll.Urlmon, ExactSpelling=true)]
internal static extern int CoInternetCreateSecurityManager(
[MarshalAs(UnmanagedType.Interface)] object pIServiceProvider,
[MarshalAs(UnmanagedType.Interface)] out object ppISecurityManager ,
int dwReserved ) ;
[ComImport, ComVisible(false), Guid("79eac9ee-baf9-11ce-8c82-00aa004ba90b"), System.Runtime.InteropServices.InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface IInternetSecurityManager
{
void SetSecuritySite( NativeMethods.IInternetSecurityMgrSite pSite);
unsafe void GetSecuritySite( /* [out] */ void **ppSite);
void MapUrlToZone(
[In, MarshalAs(UnmanagedType.BStr)]
string pwszUrl,
[Out] out int pdwZone,
[In] int dwFlags);
unsafe void GetSecurityId( /* [in] */ string pwszUrl,
/* [size_is][out] */ byte *pbSecurityId,
/* [out][in] */ int *pcbSecurityId,
/* [in] */ int dwReserved);
unsafe void ProcessUrlAction(
/* [in] */ string pwszUrl,
/* [in] */ int dwAction,
/* [size_is][out] */ byte *pPolicy,
/* [in] */ int cbPolicy,
/* [in] */ byte *pContext,
/* [in] */ int cbContext,
/* [in] */ int dwFlags,
/* [in] */ int dwReserved);
unsafe void QueryCustomPolicy(
/* [in] */ string pwszUrl,
/* [in] */ /*REFGUID*/ void *guidKey,
/* [size_is][size_is][out] */ byte **ppPolicy,
/* [out] */ int *pcbPolicy,
/* [in] */ byte *pContext,
/* [in] */ int cbContext,
/* [in] */ int dwReserved);
unsafe void SetZoneMapping( /* [in] */ int dwZone, /* [in] */ string lpszPattern, /* [in] */ int dwFlags);
unsafe void GetZoneMappings( /* [in] */ int dwZone, /* [out] */ /*IEnumString*/ void **ppenumString, /* [in] */ int dwFlags);
}
/// <summary>
///
/// </summary>
/// <param name="hMem"></param>
/// <returns></returns>
#pragma warning disable SYSLIB0004 // The Constrained Execution Region (CER) feature is not supported.
[DllImport(ExternDll.Kernel32, SetLastError = true), ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
#pragma warning restore SYSLIB0004 // The Constrained Execution Region (CER) feature is not supported.
internal static extern IntPtr LocalFree(IntPtr hMem);
#if BASE_NATIVEMETHODS
[DllImport(ExternDll.Kernel32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false, ThrowOnUnmappableChar = true)]
internal unsafe static extern SafeFileHandle CreateFile(
string lpFileName,
uint dwDesiredAccess,
uint dwShareMode,
[In] NativeMethods.SECURITY_ATTRIBUTES lpSecurityAttributes,
int dwCreationDisposition,
int dwFlagsAndAttributes,
IntPtr hTemplateFile);
#endif
#if BASE_NATIVEMETHODS
[DllImport(ExternDll.User32, CharSet = CharSet.Auto)]
internal static extern IntPtr GetMessageExtraInfo();
#endif
#if BASE_NATIVEMETHODS
[DllImport(ExternDll.Kernel32, EntryPoint="WaitForMultipleObjectsEx", SetLastError = true, CharSet = CharSet.Auto)]
private static extern int IntWaitForMultipleObjectsEx(int nCount, IntPtr[] pHandles, bool bWaitAll, int dwMilliseconds, bool bAlertable);
public const int WAIT_FAILED = unchecked((int)0xFFFFFFFF);
internal static int WaitForMultipleObjectsEx(int nCount, IntPtr[] pHandles, bool bWaitAll, int dwMilliseconds, bool bAlertable)
{
int result = IntWaitForMultipleObjectsEx(nCount, pHandles, bWaitAll, dwMilliseconds, bAlertable);
if(result == UnsafeNativeMethods.WAIT_FAILED)
{
throw new Win32Exception();
}
return result;
}
[DllImport(ExternDll.User32, EntryPoint="MsgWaitForMultipleObjectsEx", SetLastError=true, ExactSpelling = true, CharSet = CharSet.Auto)]
private static extern int IntMsgWaitForMultipleObjectsEx(int nCount, IntPtr[] pHandles, int dwMilliseconds, int dwWakeMask, int dwFlags);
internal static int MsgWaitForMultipleObjectsEx(int nCount, IntPtr[] pHandles, int dwMilliseconds, int dwWakeMask, int dwFlags)
{
int result = IntMsgWaitForMultipleObjectsEx(nCount, pHandles, dwMilliseconds, dwWakeMask, dwFlags);
if(result == -1)
{
throw new Win32Exception();
}
return result;
}
#endif
[DllImport(ExternDll.User32, EntryPoint="RegisterClassEx", CharSet=CharSet.Unicode, SetLastError=true, BestFitMapping=false)]
internal static extern UInt16 IntRegisterClassEx(NativeMethods.WNDCLASSEX_D wc_d);
internal static UInt16 RegisterClassEx(NativeMethods.WNDCLASSEX_D wc_d)
{
UInt16 result = IntRegisterClassEx(wc_d);
if(result == 0)
{
throw new Win32Exception();
}
return result;
}
[DllImport(ExternDll.User32, EntryPoint="UnregisterClass",CharSet = CharSet.Auto, SetLastError = true, BestFitMapping=false)]
internal static extern int IntUnregisterClass(IntPtr atomString /*lpClassName*/ , IntPtr hInstance);
internal static void UnregisterClass(IntPtr atomString /*lpClassName*/ , IntPtr hInstance)
{
int result = IntUnregisterClass(atomString, hInstance);
if (result == 0)
{
throw new Win32Exception();
}
}
#if !DRT
[DllImport("user32.dll", EntryPoint="ChangeWindowMessageFilter", SetLastError=true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool IntChangeWindowMessageFilter(WindowMessage message, MSGFLT dwFlag);
[DllImport("user32.dll", EntryPoint = "ChangeWindowMessageFilterEx", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool IntChangeWindowMessageFilterEx(IntPtr hwnd, WindowMessage message, MSGFLT action, [In, Out, Optional] ref CHANGEFILTERSTRUCT pChangeFilterStruct);
// Note that processes at or below SECURITY_MANDATORY_LOW_RID are not allowed to change the message filter.
// If those processes call this function, it will fail and generate the extended error code, ERROR_ACCESS_DENIED.
internal static MS.Internal.Interop.HRESULT ChangeWindowMessageFilterEx(IntPtr hwnd, WindowMessage message, MSGFLT action, out MSGFLTINFO extStatus)
{
extStatus = MSGFLTINFO.NONE;
// This API were added for Vista. The Ex version was added for Windows 7.
// If we're not on either, then this message filter isolation doesn't exist.
if (!Utilities.IsOSVistaOrNewer)
{
return MS.Internal.Interop.HRESULT.S_FALSE;
}
// If we're on Vista rather than Win7 then we can't use the Ex version of this function.
// The Ex version is preferred if possible because this results in process-wide modifications of the filter
// and is deprecated as of Win7.
if (!Utilities.IsOSWindows7OrNewer)
{
// Note that the Win7 MSGFLT_ALLOW/DISALLOW enum values map to the Vista MSGFLT_ADD/REMOVE
if (!IntChangeWindowMessageFilter(message, action))
{
return (MS.Internal.Interop.HRESULT)Win32Error.GetLastError();
}
return MS.Internal.Interop.HRESULT.S_OK;
}
var filterstruct = new CHANGEFILTERSTRUCT { cbSize = (uint)Marshal.SizeOf(typeof(CHANGEFILTERSTRUCT)) };
if (!IntChangeWindowMessageFilterEx(hwnd, message, action, ref filterstruct))
{
return (MS.Internal.Interop.HRESULT)Win32Error.GetLastError();
}
extStatus = filterstruct.ExtStatus;
return MS.Internal.Interop.HRESULT.S_OK;
}
[DllImport(ExternDll.Urlmon, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Ansi, BestFitMapping = false, ThrowOnUnmappableChar = true)]
private static extern MS.Internal.Interop.HRESULT ObtainUserAgentString(int dwOption, StringBuilder userAgent, ref int length);
internal static string ObtainUserAgentString()
{
int length = MS.Win32.NativeMethods.MAX_PATH;
StringBuilder userAgentBuffer = new StringBuilder(length);
MS.Internal.Interop.HRESULT hr = ObtainUserAgentString(0 /*reserved. must be 0*/, userAgentBuffer, ref length);
// Installing .NET 4.0 adds two parts to the user agent string, i.e.
// .NET4.0C and .NET4.0E, potentially causing the user agent string to overflow its
// documented maximum length of MAX_PATH. Turns out ObtainUserAgentString can return
// a longer string if asked to do so. Therefore we grow the string dynamically when
// needed, accommodating for this failure condition.
if (hr == MS.Internal.Interop.HRESULT.E_OUTOFMEMORY)
{
userAgentBuffer = new StringBuilder(length);
hr = ObtainUserAgentString(0 /*reserved. must be 0*/, userAgentBuffer, ref length);
}
hr.ThrowIfFailed();
return userAgentBuffer.ToString();
}
// note that this method exists in UnsafeNativeMethodsCLR.cs but with a different signature
// using a HandleRef for the hWnd instead of an IntPtr, and not using an IntPtr for lParam
[DllImport(ExternDll.User32, CharSet = CharSet.Auto)]
internal static extern IntPtr SendMessage(IntPtr hWnd, WindowMessage msg, IntPtr wParam, IntPtr lParam);
// note that this method exists in UnsafeNativeMethodsCLR.cs but with a different signature
// using a HandleRef for the hWnd instead of an IntPtr, and not using an IntPtr for lParam
[DllImport(ExternDll.User32,EntryPoint="SendMessage", CharSet = CharSet.Auto)]
internal static extern IntPtr UnsafeSendMessage(IntPtr hWnd, WindowMessage msg, IntPtr wParam, IntPtr lParam);
[DllImport(ExternDll.User32,EntryPoint="RegisterPowerSettingNotification")]
unsafe internal static extern IntPtr RegisterPowerSettingNotification(IntPtr hRecipient, Guid *pGuid, int Flags);
[DllImport(ExternDll.User32,EntryPoint="UnregisterPowerSettingNotification")]
unsafe internal static extern IntPtr UnregisterPowerSettingNotification(IntPtr hPowerNotify);
/*
//
// SendMessage taking a SafeHandle for wParam. Needed by some Win32 messages. e.g. WM_PRINT
//
[DllImport(ExternDll.User32, CharSet = CharSet.Auto)]
internal static extern IntPtr SendMessage(HandleRef hWnd, WindowMessage msg, SafeHandle wParam, IntPtr lParam);
*/
// private DllImport - that takes an IconHandle.
[DllImport(ExternDll.User32, CharSet = CharSet.Auto, SetLastError = true)]
internal static extern IntPtr SendMessage( HandleRef hWnd, WindowMessage msg, IntPtr wParam, NativeMethods.IconHandle iconHandle );
#endif
[DllImport(ExternDll.Kernel32, ExactSpelling = true, CharSet = CharSet.Auto)]
internal static extern void SetLastError(int dwErrorCode);
#if BASE_NATIVEMETHODS || CORE_NATIVEMETHODS || FRAMEWORK_NATIVEMETHODS
/// <summary>
/// Win32 GetLayeredWindowAttributes.
/// </summary>
/// <param name="hwnd"></param>
/// <param name="pcrKey"></param>
/// <param name="pbAlpha"></param>
/// <param name="pdwFlags"></param>
/// <returns></returns>
[DllImport("user32.dll")]
public static extern bool GetLayeredWindowAttributes(
HandleRef hwnd, IntPtr pcrKey, IntPtr pbAlpha, IntPtr pdwFlags);
internal sealed class SafeFileMappingHandle : SafeHandleZeroOrMinusOneIsInvalid
{
internal SafeFileMappingHandle(IntPtr handle) : base(false)
{
SetHandle(handle);
}
internal SafeFileMappingHandle() : base(true)
{
}
public override bool IsInvalid
{
get
{
return handle == IntPtr.Zero;
}
}
protected override bool ReleaseHandle()
{
return CloseHandleNoThrow(new HandleRef(null, handle));
}
}
internal sealed class SafeViewOfFileHandle : SafeHandleZeroOrMinusOneIsInvalid
{
internal SafeViewOfFileHandle() : base(true) { }
internal unsafe void* Memory
{
get
{
Debug.Assert(handle != IntPtr.Zero);
return (void*)handle;
}
}
override protected bool ReleaseHandle()
{
return UnsafeNativeMethods.UnmapViewOfFileNoThrow(new HandleRef(null, handle));
}
}
[DllImport(ExternDll.Kernel32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false, ThrowOnUnmappableChar = true)]
internal unsafe static extern SafeFileMappingHandle CreateFileMapping(SafeFileHandle hFile, NativeMethods.SECURITY_ATTRIBUTES lpFileMappingAttributes, int flProtect, uint dwMaximumSizeHigh, uint dwMaximumSizeLow, string lpName);
[DllImport(ExternDll.Kernel32, SetLastError = true)]
internal static extern SafeViewOfFileHandle MapViewOfFileEx(SafeFileMappingHandle hFileMappingObject, int dwDesiredAccess, int dwFileOffsetHigh, int dwFileOffsetLow, IntPtr dwNumberOfBytesToMap, IntPtr lpBaseAddress);
#endif // BASE_NATIVEMETHODS
internal static IntPtr SetWindowLong(HandleRef hWnd, int nIndex, IntPtr dwNewLong)
{
IntPtr result = IntPtr.Zero;
if (IntPtr.Size == 4)
{
// use SetWindowLong
Int32 tempResult = NativeMethodsSetLastError.SetWindowLong(hWnd, nIndex, NativeMethods.IntPtrToInt32(dwNewLong));
result = new IntPtr(tempResult);
}
else
{
// use SetWindowLongPtr
result = NativeMethodsSetLastError.SetWindowLongPtr(hWnd, nIndex, dwNewLong);
}
return result;
}
internal static IntPtr CriticalSetWindowLong(HandleRef hWnd, int nIndex, IntPtr dwNewLong)
{
IntPtr result = IntPtr.Zero;
if (IntPtr.Size == 4)
{
// use SetWindowLong
Int32 tempResult = NativeMethodsSetLastError.SetWindowLong(hWnd, nIndex, NativeMethods.IntPtrToInt32(dwNewLong));
result = new IntPtr(tempResult);
}
else
{
// use SetWindowLongPtr
result = NativeMethodsSetLastError.SetWindowLongPtr(hWnd, nIndex, dwNewLong);
}
return result;
}
internal static IntPtr CriticalSetWindowLong(HandleRef hWnd, int nIndex, NativeMethods.WndProc dwNewLong)
{
int errorCode;
IntPtr retVal;
if (IntPtr.Size == 4)
{
Int32 tempRetVal = NativeMethodsSetLastError.SetWindowLongWndProc(hWnd, nIndex, dwNewLong);
errorCode = Marshal.GetLastWin32Error();
retVal = new IntPtr(tempRetVal);
}
else
{
retVal = NativeMethodsSetLastError.SetWindowLongPtrWndProc(hWnd, nIndex, dwNewLong);
errorCode = Marshal.GetLastWin32Error();
}
if (retVal == IntPtr.Zero)
{
if (errorCode != 0)
{
throw new System.ComponentModel.Win32Exception(errorCode);
}
}
return retVal;
}
internal static IntPtr GetWindowLongPtr(HandleRef hWnd, int nIndex )
{
IntPtr result = IntPtr.Zero;
int error = 0;
if (IntPtr.Size == 4)
{
// use getWindowLong
Int32 tempResult = NativeMethodsSetLastError.GetWindowLong(hWnd, nIndex);
error = Marshal.GetLastWin32Error();
result = new IntPtr(tempResult);
}
else
{
// use GetWindowLongPtr
result = NativeMethodsSetLastError.GetWindowLongPtr(hWnd, nIndex);
error = Marshal.GetLastWin32Error();
}
if ((result == IntPtr.Zero) && (error != 0))
{
// To be consistent with out other PInvoke wrappers
// we should "throw" here. But we don't want to
// introduce new "throws" w/o time to follow up on any
// new problems that causes.
Debug.WriteLine("GetWindowLongPtr failed. Error = " + error);
// throw new System.ComponentModel.Win32Exception(error);
}
return result;
}
internal static Int32 GetWindowLong(HandleRef hWnd, int nIndex )
{
int iResult = 0;
IntPtr result = IntPtr.Zero;
int error = 0;
if (IntPtr.Size == 4)
{
// use GetWindowLong
iResult = NativeMethodsSetLastError.GetWindowLong(hWnd, nIndex);
error = Marshal.GetLastWin32Error();
result = new IntPtr(iResult);
}
else
{
// use GetWindowLongPtr
result = NativeMethodsSetLastError.GetWindowLongPtr(hWnd, nIndex);
error = Marshal.GetLastWin32Error();
iResult = NativeMethods.IntPtrToInt32(result);
}
if ((result == IntPtr.Zero) && (error != 0))
{
// To be consistent with out other PInvoke wrappers
// we should "throw" here. But we don't want to
// introduce new "throws" w/o time to follow up on any
// new problems that causes.
Debug.WriteLine("GetWindowLong failed. Error = " + error);
// throw new System.ComponentModel.Win32Exception(error);
}
return iResult;
}
internal static NativeMethods.WndProc GetWindowLongWndProc(HandleRef hWnd)
{
NativeMethods.WndProc returnValue = null;
int error = 0;
if (IntPtr.Size == 4)
{
// use getWindowLong
returnValue = NativeMethodsSetLastError.GetWindowLongWndProc(hWnd, NativeMethods.GWL_WNDPROC);
error = Marshal.GetLastWin32Error();
}
else
{
// use GetWindowLongPtr
returnValue = NativeMethodsSetLastError.GetWindowLongPtrWndProc(hWnd, NativeMethods.GWL_WNDPROC);
error = Marshal.GetLastWin32Error();
}
if (null == returnValue)
{
throw new Win32Exception(error);
}
return returnValue;
}
[DllImport("winmm.dll", CharSet = CharSet.Unicode)]
internal static extern bool PlaySound([In]string soundName, IntPtr hmod, SafeNativeMethods.PlaySoundFlags soundFlags);
internal const uint
INTERNET_COOKIE_THIRD_PARTY = 0x10,
INTERNET_COOKIE_EVALUATE_P3P = 0x40,
INTERNET_COOKIE_IS_RESTRICTED = 0x200,
COOKIE_STATE_REJECT = 5;
//!!! CAUTION
// PresentationHost intercepts calls to InternetGetCookieEx & InternetSetCookieEx and delegates them
// to the browser. It doesn't do this for InternetGetCookie & InternetSetCookie.
// See also Application.Get/SetCookie().
//!!!
[DllImport(ExternDll.Wininet, SetLastError=true, ExactSpelling=true, EntryPoint="InternetGetCookieExW", CharSet=CharSet.Unicode)]
internal static extern bool InternetGetCookieEx([In]string Url, [In]string cookieName,
[Out] StringBuilder cookieData, [In, Out] ref UInt32 pchCookieData, uint flags, IntPtr reserved);
[DllImport(ExternDll.Wininet, SetLastError = true, ExactSpelling = true, EntryPoint = "InternetSetCookieExW", CharSet = CharSet.Unicode)]
internal static extern uint InternetSetCookieEx([In]string Url, [In]string CookieName, [In]string cookieData, uint flags, [In] string p3pHeader);
#if DRT_NATIVEMETHODS
[DllImport(ExternDll.User32, ExactSpelling = true, EntryPoint = "mouse_event", CharSet = CharSet.Auto)]
internal static extern void Mouse_event(int flags, int dx, int dy, int dwData, IntPtr extrainfo);
#endif
/////////////////////////////
// needed by Framework
[DllImport(ExternDll.Kernel32, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GetLocaleInfoW(int locale, int type, string data, int dataSize);
[DllImport(ExternDll.Kernel32, ExactSpelling = true, SetLastError = true)]
internal static extern int FindNLSString(int locale, uint flags, [MarshalAs(UnmanagedType.LPWStr)]string sourceString, int sourceCount, [MarshalAs(UnmanagedType.LPWStr)]string findString, int findCount, out int found);
//[DllImport(ExternDll.Psapi, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)]
//public static extern int GetModuleFileNameEx(IntPtr hProcess, IntPtr hModule, StringBuilder buffer, int length);
//
// OpenProcess
//
public const int PROCESS_VM_READ = 0x0010;
public const int PROCESS_QUERY_INFORMATION = 0x0400;
//[DllImport(ExternDll.Kernel32, SetLastError = true, CharSet = CharSet.Auto)]
//public static extern IntPtr OpenProcess(int dwDesiredAccess, bool fInherit, int dwProcessId);
[DllImport(ExternDll.User32, EntryPoint = "SetWindowText", CharSet = CharSet.Auto, SetLastError = true, BestFitMapping = false)]
private static extern bool IntSetWindowText(HandleRef hWnd, string text);
internal static void SetWindowText(HandleRef hWnd, string text)
{
if (IntSetWindowText(hWnd, text) == false)
{
throw new Win32Exception();
}
}
[DllImport(ExternDll.User32, EntryPoint = "GetIconInfo", CharSet = CharSet.Auto, SetLastError = true)]
#pragma warning disable SYSLIB0004 // The Constrained Execution Region (CER) feature is not supported.
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
#pragma warning restore SYSLIB0004 // The Constrained Execution Region (CER) feature is not supported.
private static extern bool GetIconInfoImpl(HandleRef hIcon, [Out] ICONINFO_IMPL piconinfo);
[StructLayout(LayoutKind.Sequential)]
internal class ICONINFO_IMPL
{
public bool fIcon = false;
public int xHotspot = 0;
public int yHotspot = 0;
public IntPtr hbmMask = IntPtr.Zero;
public IntPtr hbmColor = IntPtr.Zero;
}
// FOR REVIEW
// note that a different-signature version of this method is defined in SafeNativeMethodsCLR.cs, but
// this appears to be an intentional override of the functionality. Seems odd if the real method
// is really safe to reimplement it in an unsafe manner. Need to review this.
internal static void GetIconInfo(HandleRef hIcon, out NativeMethods.ICONINFO piconinfo)
{
bool success = false;
int error = 0;
piconinfo = new NativeMethods.ICONINFO();
ICONINFO_IMPL iconInfoImpl = new ICONINFO_IMPL();
#pragma warning disable SYSLIB0004 // The Constrained Execution Region (CER) feature is not supported.
SRCS.RuntimeHelpers.PrepareConstrainedRegions(); // Mark the following as special
#pragma warning restore SYSLIB0004 // The Constrained Execution Region (CER) feature is not supported.
try
{
// Intentionally empty
}
finally
{
// This block won't be interrupted by certain runtime induced failures or thread abort
success = GetIconInfoImpl(hIcon, iconInfoImpl);
error = Marshal.GetLastWin32Error();
if (success)
{
piconinfo.hbmMask = NativeMethods.BitmapHandle.CreateFromHandle(iconInfoImpl.hbmMask);
piconinfo.hbmColor = NativeMethods.BitmapHandle.CreateFromHandle(iconInfoImpl.hbmColor);
piconinfo.fIcon = iconInfoImpl.fIcon;
piconinfo.xHotspot = iconInfoImpl.xHotspot;
piconinfo.yHotspot = iconInfoImpl.yHotspot;
}
}
if(!success)
{
Debug.WriteLine("GetIconInfo failed. Error = " + error);
throw new Win32Exception();
}
}
#if never
[DllImport(ExternDll.User32,
#if WIN64
EntryPoint="GetClassLongPtr",
#endif
CharSet = CharSet.Auto, SetLastError = true)
]
internal static extern UInt32 GetClassLong(IntPtr hwnd, int nIndex);
#endif
[DllImport(ExternDll.User32, EntryPoint = "GetWindowPlacement", ExactSpelling = true, CharSet = CharSet.Auto, SetLastError = true)]
private static extern bool IntGetWindowPlacement(HandleRef hWnd, ref NativeMethods.WINDOWPLACEMENT placement);
// note: this method exists in UnsafeNativeMethodsCLR.cs, but that method does not have the if/throw implemntation
internal static void GetWindowPlacement(HandleRef hWnd, ref NativeMethods.WINDOWPLACEMENT placement)
{
if (IntGetWindowPlacement(hWnd, ref placement) == false)
{
throw new Win32Exception();
}
}
[DllImport(ExternDll.User32, EntryPoint = "SetWindowPlacement", ExactSpelling = true, CharSet = CharSet.Auto, SetLastError = true)]
private static extern bool IntSetWindowPlacement(HandleRef hWnd, [In] ref NativeMethods.WINDOWPLACEMENT placement);
// note: this method appears in UnsafeNativeMethodsCLR.cs but does not have the if/throw block
internal static void SetWindowPlacement(HandleRef hWnd, [In] ref NativeMethods.WINDOWPLACEMENT placement)
{
if (IntSetWindowPlacement(hWnd, ref placement) == false)
{
throw new Win32Exception();
}
}
//[DllImport("secur32.dll", CharSet = CharSet.Unicode, SetLastError = true, ExactSpelling = true)]
//internal static extern bool GetUserNameExW(
// [In] EXTENDED_NAME_FORMAT nameFormat,
// [MarshalAs(UnmanagedType.LPWStr)] StringBuilder lpNameBuffer,
// [In, Out] ref ulong nSize);
[DllImport(ExternDll.User32, CharSet = CharSet.Auto, BestFitMapping = false)]
internal static extern bool SystemParametersInfo(int nAction, int nParam, [In, Out] NativeMethods.ANIMATIONINFO anim, int nUpdate);
[DllImport(ExternDll.User32, CharSet = CharSet.Auto, BestFitMapping = false, ThrowOnUnmappableChar = true)]
internal static extern bool SystemParametersInfo(int nAction, int nParam, [In, Out] NativeMethods.ICONMETRICS metrics, int nUpdate);
//---------------------------------------------------------------------------
// SetWindowThemeAttribute()
// - set attributes to control how themes are applied to
// windows.
//
// hwnd - the handle of the window (cannot be NULL)
//
// eAttribute - one of the following:
//
// WTA_NONCLIENT:
// pvAttribute must be a WINDOWTHEMEATTRIBUTE pointer with a valid WTNCA flag
// the default is all flags set to 0
//
// pvAttribute - pointer to data relevant to property being set size
// is cbAttribute see each property for details.
//
// cbAttribute - size in bytes of the data pointed to by pvAttribute
//
//---------------------------------------------------------------------------
#if WCP_SYSTEM_THEMES_ENABLED
[DllImport(ExternDll.Uxtheme, CharSet = CharSet.Unicode)]
public static extern uint SetWindowThemeAttribute(HandleRef hwnd, NativeMethods.WINDOWTHEMEATTRIBUTETYPE eAttribute, [In, MarshalAs(UnmanagedType.LPStruct)] NativeMethods.WTA_OPTIONS pvAttribute, int cbAttribute);
public static uint SetWindowThemeAttribute(HandleRef hwnd, NativeMethods.WINDOWTHEMEATTRIBUTETYPE eAttribute, NativeMethods.WTA_OPTIONS pvAttribute)
{
return SetWindowThemeAttribute(hwnd, eAttribute, pvAttribute, Marshal.SizeOf(typeof(NativeMethods.WTA_OPTIONS)));
}
#endif
//---------------------------------------------------------------------------
// BeginPanningFeedback - Visual feedback init function related to pan gesture
//
// HWND hwnd - The handle to the Target window that will receive feedback
//
//---------------------------------------------------------------------------
[DllImport(ExternDll.Uxtheme, CharSet = CharSet.Unicode)]
public static extern bool BeginPanningFeedback(HandleRef hwnd);
//---------------------------------------------------------------------------
// UpdatePanningFeedback : Visual feedback function related to pan gesture
// Can Be called only after a BeginPanningFeedback call
//
// HWND hwnd - The handle to the Target window that will receive feedback
// For the method to succeed this must be the same hwnd as provided in
// BeginPanningFeedback
//
// LONG lTotalOverpanOffsetX - The Total displacement that the window has moved in the horizontal direction
// since the end of scrollable region was reached. The API would move the window by the distance specified
// A maximum displacement of 30 pixels is allowed
//
// LONG lTotalOverpanOffsetY - The Total displacement that the window has moved in the horizontal direction
// since the end of scrollable
// region was reached. The API would move the window by the distance specified
// A maximum displacement of 30 pixels is allowed
//
// BOOL fInInertia - Flag dictating whether the Application is handling a WM_GESTURE message with the
// GF_INERTIA FLAG set
//
// Incremental calls to UpdatePanningFeedback should make sure they always pass
// the sum of the increments and not just the increment themselves
// Eg : If the initial displacement is 10 pixels and the next displacement 10 pixels
// the second call would be with the parameter as 20 pixels as opposed to 10
// Eg : UpdatePanningFeedback(hwnd, 10, 10, TRUE)
//
[DllImport(ExternDll.Uxtheme, CharSet = CharSet.Unicode)]
public static extern bool UpdatePanningFeedback(
HandleRef hwnd,
int lTotalOverpanOffsetX,
int lTotalOverpanOffsetY,
bool fInInertia);
//---------------------------------------------------------------------------
//
// EndPanningFeedback :Visual feedback reset function related to pan gesture
// Terminates any existing animation that was in process or set up by BeginPanningFeedback and UpdatePanningFeedback
// The EndPanningFeedBack needs to be called Prior to calling any BeginPanningFeedBack if we have already
// called a BeginPanningFeedBack followed by one/ more UpdatePanningFeedback calls
//
// HWND hwnd - The handle to the Target window that will receive feedback
//
// BOOL fAnimateBack - Flag to indicate whether you wish the displaced window to move back
// to the original position via animation or a direct jump.
// Either way, the method will try to restore the moved window.
// The latter case exists for compatibility with legacy apps.
//
[DllImport(ExternDll.Uxtheme, CharSet = CharSet.Unicode)]
public static extern bool EndPanningFeedback(
HandleRef hwnd,
bool fAnimateBack);
/// <summary>
///
/// </summary>
[DllImport(ExternDll.Kernel32, CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool SetEvent(IntPtr hEvent);
[DllImport(ExternDll.Kernel32, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Auto)]
public static extern int SetEvent([In] SafeWaitHandle hHandle);
[DllImport(ExternDll.Kernel32, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Auto)]
public static extern int WaitForSingleObject([In] SafeWaitHandle hHandle, [In] int dwMilliseconds);
//[DllImport(ExternDll.Kernel32, SetLastError = true)]
//internal static extern int GetFileSize(SafeFileHandle hFile, ref int lpFileSizeHigh);
//////////////////////////////////////
// Needed by BASE
#if BASE_NATIVEMETHODS
[DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Auto, SetLastError = true)]
internal static extern int GetMouseMovePointsEx(
uint cbSize,
[In] ref NativeMethods.MOUSEMOVEPOINT pointsIn,
[Out] NativeMethods.MOUSEMOVEPOINT[] pointsBufferOut,
int nBufPoints,
uint resolution
);
[StructLayout(LayoutKind.Explicit)]
internal unsafe struct ULARGE_INTEGER
{
[FieldOffset(0)]
internal uint LowPart;
[FieldOffset(4)]
internal uint HighPart;
[FieldOffset(0)]
internal ulong QuadPart;
}
[StructLayout(LayoutKind.Explicit)]
internal unsafe struct LARGE_INTEGER
{
[FieldOffset(0)]
internal int LowPart;
[FieldOffset(4)]
internal int HighPart;
[FieldOffset(0)]
internal long QuadPart;
}
[DllImport(ExternDll.Kernel32, SetLastError = true)]
internal static extern bool GetFileSizeEx(
SafeFileHandle hFile,
ref LARGE_INTEGER lpFileSize
);
/// <summary>Win32 constants</summary>
internal static readonly IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1);
/// <summary>Win32 constants</summary>
internal const int PAGE_NOACCESS = 0x01;
/// <summary>Win32 constants</summary>
internal const int PAGE_READONLY = 0x02;
/// <summary>Win32 constants</summary>
internal const int PAGE_READWRITE = 0x04;
/// <summary>Win32 constants</summary>
internal const int PAGE_WRITECOPY = 0x08;
/// <summary>Win32 constants</summary>
internal const int PAGE_EXECUTE = 0x10;
/// <summary>Win32 constants</summary>
internal const int PAGE_EXECUTE_READ = 0x20;
/// <summary>Win32 constants</summary>
internal const int PAGE_EXECUTE_READWRITE = 0x40;
/// <summary>Win32 constants</summary>
internal const int PAGE_EXECUTE_WRITECOPY = 0x80;
/// <summary>Win32 constants</summary>
internal const int PAGE_GUARD = 0x100;
/// <summary>Win32 constants</summary>
internal const int PAGE_NOCACHE = 0x200;
/// <summary>Win32 constants</summary>
internal const int PAGE_WRITECOMBINE = 0x400;
/// <summary>Win32 constants</summary>
internal const int MEM_COMMIT = 0x1000;
/// <summary>Win32 constants</summary>
internal const int MEM_RESERVE = 0x2000;
/// <summary>Win32 constants</summary>
internal const int MEM_DECOMMIT = 0x4000;
/// <summary>Win32 constants</summary>
internal const int MEM_RELEASE = 0x8000;
/// <summary>Win32 constants</summary>
internal const int MEM_FREE = 0x10000;
/// <summary>Win32 constants</summary>
internal const int MEM_PRIVATE = 0x20000;
/// <summary>Win32 constants</summary>
internal const int MEM_MAPPED = 0x40000;
/// <summary>Win32 constants</summary>
internal const int MEM_RESET = 0x80000;
/// <summary>Win32 constants</summary>
internal const int MEM_TOP_DOWN = 0x100000;
/// <summary>Win32 constants</summary>
internal const int MEM_WRITE_WATCH = 0x200000;
/// <summary>Win32 constants</summary>
internal const int MEM_PHYSICAL = 0x400000;
/// <summary>Win32 constants</summary>
internal const int MEM_4MB_PAGES = unchecked((int)0x80000000);
/// <summary>Win32 constants</summary>
internal const int SEC_FILE = 0x800000;
/// <summary>Win32 constants</summary>
internal const int SEC_IMAGE = 0x1000000;
/// <summary>Win32 constants</summary>
internal const int SEC_RESERVE = 0x4000000;
/// <summary>Win32 constants</summary>
internal const int SEC_COMMIT = 0x8000000;
/// <summary>Win32 constants</summary>
internal const int SEC_NOCACHE = 0x10000000;
/// <summary>Win32 constants</summary>
internal const int MEM_IMAGE = SEC_IMAGE;
/// <summary>Win32 constants</summary>
internal const int WRITE_WATCH_FLAG_RESET = 0x01;
/// <summary>Win32 constants</summary>
internal const int SECTION_ALL_ACCESS =
STANDARD_RIGHTS_REQUIRED |
SECTION_QUERY |
SECTION_MAP_WRITE |
SECTION_MAP_READ |
SECTION_MAP_EXECUTE |
SECTION_EXTEND_SIZE;
/// <summary>Win32 constants</summary>
internal const int STANDARD_RIGHTS_REQUIRED = 0x000F0000;
/// <summary>Win32 constants</summary>
internal const int SECTION_QUERY = 0x0001;
/// <summary>Win32 constants</summary>
internal const int SECTION_MAP_WRITE = 0x0002;
/// <summary>Win32 constants</summary>
internal const int SECTION_MAP_READ = 0x0004;
/// <summary>Win32 constants</summary>
internal const int SECTION_MAP_EXECUTE = 0x0008;
/// <summary>Win32 constants</summary>
internal const int SECTION_EXTEND_SIZE = 0x0010;
/// <summary>Win32 constants</summary>
internal const int FILE_MAP_COPY = SECTION_QUERY;
/// <summary>Win32 constants</summary>
internal const int FILE_MAP_WRITE = SECTION_MAP_WRITE;
/// <summary>Win32 constants</summary>
internal const int FILE_MAP_READ = SECTION_MAP_READ;
/// <summary>Win32 constants</summary>
internal const int FILE_MAP_ALL_ACCESS = SECTION_ALL_ACCESS;
/// <summary>
///
/// </summary>
/// <param name="stringSecurityDescriptor"></param>
/// <param name="stringSDRevision"></param>
/// <param name="securityDescriptor"></param>
/// <param name="securityDescriptorSize"></param>
/// <returns></returns>
[DllImport(ExternDll.Advapi32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false, ThrowOnUnmappableChar = true)]
internal static extern bool ConvertStringSecurityDescriptorToSecurityDescriptor(
string stringSecurityDescriptor, // security descriptor string
int stringSDRevision, // revision level
ref IntPtr securityDescriptor, // SD
IntPtr securityDescriptorSize // SD size
);
/// <summary>Win32 constants</summary>
internal const int SDDL_REVISION_1 = 1;
/// <summary>Win32 constants</summary>
internal const int SDDL_REVISION = SDDL_REVISION_1;
[DllImport(ExternDll.Kernel32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false, ThrowOnUnmappableChar = true)]
internal static extern SafeFileMappingHandle OpenFileMapping(
int dwDesiredAccess,
bool bInheritHandle,
string lpName
);
[DllImport(ExternDll.Kernel32, SetLastError = true)]
internal static extern IntPtr VirtualAlloc(
IntPtr lpAddress,
UIntPtr dwSize,
int flAllocationType,
int flProtect
);
//
// RIT WM_MOUSEQUERY structure for DWM WM_MOUSEQUERY (see HwndMouseInputSource.cs)
//
[StructLayout(LayoutKind.Sequential, Pack = 1)] // For DWM WM_MOUSEQUERY
internal unsafe struct MOUSEQUERY
{
internal UInt32 uMsg;
internal IntPtr wParam;
internal IntPtr lParam;
internal Int32 ptX;
internal Int32 ptY;
internal IntPtr hwnd;
}
[DllImport(ExternDll.Ole32, ExactSpelling = true, CharSet = CharSet.Auto)]
public static extern int OleIsCurrentClipboard(IComDataObject pDataObj);
[DllImport(ExternDll.Kernel32, ExactSpelling = true, CharSet = CharSet.Auto)]
internal static extern int GetOEMCP();
#if never
[DllImport("user32.dll", CharSet = CharSet.Auto, BestFitMapping = false, ThrowOnUnmappableChar = true)]
internal static extern int ToUnicode(int nVirtKey, int nScanCode, byte[] keystate, StringBuilder text, int cch, int flags);
#endif
// WinEvent fired when new Avalon UI is created
public const int EventObjectUIFragmentCreate = 0x6FFFFFFF;
//////////////////////////////////
// Needed by FontCache
[DllImport("ntdll.dll")]
internal static extern int RtlNtStatusToDosError(int Status);
internal static bool NtSuccess(int err)
{
return err >= STATUS_SUCCESS;
}
internal static void NtCheck(int err)
{
if (!NtSuccess(err))
{
int win32error = RtlNtStatusToDosError(err);
throw new System.ComponentModel.Win32Exception(win32error);
}
}
internal const int STATUS_SUCCESS = 0;
internal const int STATUS_TIMEOUT = 0x00000102;
internal const int STATUS_BUFFER_TOO_SMALL = unchecked((int)0xC0000023);
#endif // BASE_NATIVEMETHODS
//
// COM Helper Methods
//
internal static int SafeReleaseComObject(object o)
{
int refCount = 0;
// Validate
if (o != null)
{
if (Marshal.IsComObject(o))
{
refCount = Marshal.ReleaseComObject(o);
}
}
return refCount;
}
#if WINDOWS_BASE
[DllImport(DllImport.Wininet, EntryPoint = "GetUrlCacheConfigInfoW", SetLastError=true)]
internal static extern bool GetUrlCacheConfigInfo(
ref NativeMethods.InternetCacheConfigInfo pInternetCacheConfigInfo,
ref UInt32 cbCacheConfigInfo,
UInt32 /* DWORD */ fieldControl
);
#endif
[DllImport("WtsApi32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool WTSRegisterSessionNotification(IntPtr hwnd, uint dwFlags);
[DllImport("WtsApi32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool WTSUnRegisterSessionNotification(IntPtr hwnd);
[DllImport(ExternDll.Kernel32, SetLastError = true)]
public static extern IntPtr GetCurrentProcess();
public const int DUPLICATE_CLOSE_SOURCE = 1;
public const int DUPLICATE_SAME_ACCESS = 2;
[DllImport(ExternDll.Kernel32, SetLastError = true)]
public static extern bool DuplicateHandle(
IntPtr hSourceProcess,
SafeWaitHandle hSourceHandle,
IntPtr hTargetProcessHandle,
out IntPtr hTargetHandle,
uint dwDesiredAccess,
bool fInheritHandle,
uint dwOptions
);
//
// <Windows Color System (WCS) types>
//
[StructLayout(LayoutKind.Sequential)]
public unsafe struct PROFILEHEADER
{
public uint phSize; // profile size in bytes
public uint phCMMType; // CMM for this profile
public uint phVersion; // profile format version number
public uint phClass; // type of profile
public NativeMethods.ColorSpace phDataColorSpace; // color space of data
public uint phConnectionSpace; // PCS
public uint phDateTime_0; // date profile was created
public uint phDateTime_1; // date profile was created
public uint phDateTime_2; // date profile was created
public uint phSignature; // magic number ("Reserved for internal use.")
public uint phPlatform; // primary platform
public uint phProfileFlags; // various bit settings
public uint phManufacturer; // device manufacturer
public uint phModel; // device model number
public uint phAttributes_0; // device attributes
public uint phAttributes_1; // device attributes
public uint phRenderingIntent; // rendering intent
public uint phIlluminant_0; // profile illuminant
public uint phIlluminant_1; // profile illuminant
public uint phIlluminant_2; // profile illuminant
public uint phCreator; // profile creator
public fixed byte phReserved[44];
};
[StructLayout(LayoutKind.Sequential)]
public unsafe struct PROFILE
{
public NativeMethods.ProfileType dwType; // profile type
public void* pProfileData; // either the filename of the profile or buffer containing profile depending upon dwtype
public uint cbDataSize; // size in bytes of pProfileData
};
/// <summary>The IsIconic function determines whether the specified window is minimized (iconic).</summary>
[DllImport(ExternDll.User32)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool IsIconic(IntPtr hWnd);
public enum HookType : int
{
WH_JOURNALRECORD = 0,
WH_JOURNALPLAYBACK = 1,
WH_KEYBOARD = 2,
WH_GETMESSAGE = 3,
WH_CALLWNDPROC = 4,
WH_CBT = 5,
WH_SYSMSGFILTER = 6,
WH_MOUSE = 7,
WH_HARDWARE = 8,
WH_DEBUG = 9,
WH_SHELL = 10,
WH_FOREGROUNDIDLE = 11,
WH_CALLWNDPROCRET = 12,
WH_KEYBOARD_LL = 13,
WH_MOUSE_LL = 14,
}
[StructLayout(LayoutKind.Sequential)]
public struct MOUSEHOOKSTRUCT
{
public NativeMethods.POINT pt;
public IntPtr hwnd;
public uint wHitTestCode;
public IntPtr dwExtraInfo;
}
public delegate IntPtr HookProc(int code, IntPtr wParam, IntPtr lParam);
public static HandleRef SetWindowsHookEx(HookType idHook, HookProc lpfn, IntPtr hMod, int dwThreadId)
{
IntPtr result = IntSetWindowsHookEx(idHook, lpfn, hMod, dwThreadId);
if (result == IntPtr.Zero)
{
throw new Win32Exception();
}
return new HandleRef(lpfn, result);
}
[DllImport(ExternDll.User32, EntryPoint = "SetWindowsHookExW", SetLastError = true)]
private static extern IntPtr IntSetWindowsHookEx(HookType idHook, HookProc lpfn, IntPtr hMod, int dwThreadId);
[DllImport(ExternDll.User32, SetLastError = true)]
public static extern bool UnhookWindowsHookEx(HandleRef hhk);
[DllImport(ExternDll.User32, SetLastError = true)]
public static extern IntPtr CallNextHookEx(HandleRef hhk, int nCode, IntPtr wParam, IntPtr lParam);
}
}
| |
// 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.Threading;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Security.Permissions;
namespace System.Timers
{
/// <summary>
/// <para>Handles recurring events in an application.</para>
/// </summary>
[DefaultProperty("Interval"), DefaultEvent("Elapsed")]
public partial class Timer : Component, ISupportInitialize
{
private double _interval;
private bool _enabled;
private bool _initializing;
private bool _delayedEnable;
private ElapsedEventHandler _onIntervalElapsed;
private bool _autoReset;
private ISynchronizeInvoke _synchronizingObject;
private bool _disposed;
private Threading.Timer _timer;
private TimerCallback _callback;
private object _cookie;
/// <summary>
/// <para>Initializes a new instance of the <see cref='System.Timers.Timer'/> class, with the properties
/// set to initial values.</para>
/// </summary>
public Timer()
: base()
{
_interval = 100;
_enabled = false;
_autoReset = true;
_initializing = false;
_delayedEnable = false;
_callback = new TimerCallback(MyTimerCallback);
}
/// <summary>
/// <para>
/// Initializes a new instance of the <see cref='System.Timers.Timer'/> class, setting the <see cref='System.Timers.Timer.Interval'/> property to the specified period.
/// </para>
/// </summary>
public Timer(double interval)
: this()
{
if (interval <= 0)
throw new ArgumentException(SR.Format(SR.InvalidParameter, nameof(interval), interval));
double roundedInterval = Math.Ceiling(interval);
if (roundedInterval > int.MaxValue || roundedInterval <= 0)
{
throw new ArgumentException(SR.Format(SR.InvalidParameter, nameof(interval), interval));
}
_interval = (int)roundedInterval;
}
/// <summary>
/// <para>Gets or sets a value indicating whether the Timer raises the Tick event each time the specified
/// Interval has elapsed,
/// when Enabled is set to true.</para>
/// </summary>
[TimersDescription(nameof(SR.TimerAutoReset), null), DefaultValue(true)]
public bool AutoReset
{
get
{
return _autoReset;
}
set
{
if (DesignMode)
_autoReset = value;
else if (_autoReset != value)
{
_autoReset = value;
if (_timer != null)
{
UpdateTimer();
}
}
}
}
/// <summary>
/// <para>Gets or sets a value indicating whether the <see cref='System.Timers.Timer'/>
/// is able
/// to raise events at a defined interval.</para>
/// </summary>
// The default value by design is false, don't change it.
[TimersDescription(nameof(SR.TimerEnabled), null), DefaultValue(false)]
public bool Enabled
{
get
{
return _enabled;
}
set
{
if (DesignMode)
{
_delayedEnable = value;
_enabled = value;
}
else if (_initializing)
_delayedEnable = value;
else if (_enabled != value)
{
if (!value)
{
if (_timer != null)
{
_cookie = null;
_timer.Dispose();
_timer = null;
}
_enabled = value;
}
else
{
_enabled = value;
if (_timer == null)
{
if (_disposed)
{
throw new ObjectDisposedException(GetType().Name);
}
int i = (int)Math.Ceiling(_interval);
_cookie = new object();
_timer = new Threading.Timer(_callback, _cookie, Timeout.Infinite, Timeout.Infinite);
_timer.Change(i, _autoReset ? i : Timeout.Infinite);
}
else
{
UpdateTimer();
}
}
}
}
}
private void UpdateTimer()
{
int i = (int)Math.Ceiling(_interval);
_timer.Change(i, _autoReset ? i : Timeout.Infinite);
}
/// <summary>
/// <para>Gets or
/// sets the interval on which
/// to raise events.</para>
/// </summary>
[TimersDescription(nameof(SR.TimerInterval), null), DefaultValue(100d)]
public double Interval
{
get
{
return _interval;
}
set
{
if (value <= 0)
throw new ArgumentException(SR.Format(SR.TimerInvalidInterval, value, 0));
_interval = value;
if (_timer != null)
{
UpdateTimer();
}
}
}
/// <summary>
/// <para>Occurs when the <see cref='System.Timers.Timer.Interval'/> has
/// elapsed.</para>
/// </summary>
[TimersDescription(nameof(SR.TimerIntervalElapsed), null)]
public event ElapsedEventHandler Elapsed
{
add
{
_onIntervalElapsed += value;
}
remove
{
_onIntervalElapsed -= value;
}
}
/// <summary>
/// <para>
/// Sets the enable property in design mode to true by default.
/// </para>
/// </summary>
/// <internalonly/>
public override ISite Site
{
get
{
return base.Site;
}
set
{
base.Site = value;
if (DesignMode)
_enabled = true;
}
}
/// <summary>
/// <para>Gets or sets the object used to marshal event-handler calls that are issued when
/// an interval has elapsed.</para>
/// </summary>
[DefaultValue(null), TimersDescription(nameof(SR.TimerSynchronizingObject), null)]
public ISynchronizeInvoke SynchronizingObject
{
get
{
if (_synchronizingObject == null && DesignMode)
{
IDesignerHost host = (IDesignerHost)GetService(typeof(IDesignerHost));
object baseComponent = host?.RootComponent;
if (baseComponent != null && baseComponent is ISynchronizeInvoke)
_synchronizingObject = (ISynchronizeInvoke)baseComponent;
}
return _synchronizingObject;
}
set
{
_synchronizingObject = value;
}
}
/// <summary>
/// <para>
/// Notifies
/// the object that initialization is beginning and tells it to stand by.
/// </para>
/// </summary>
public void BeginInit()
{
Close();
_initializing = true;
}
/// <summary>
/// <para>Disposes of the resources (other than memory) used by
/// the <see cref='System.Timers.Timer'/>.</para>
/// </summary>
public void Close()
{
_initializing = false;
_delayedEnable = false;
_enabled = false;
if (_timer != null)
{
_timer.Dispose();
_timer = null;
}
}
protected override void Dispose(bool disposing)
{
Close();
_disposed = true;
base.Dispose(disposing);
}
/// <summary>
/// <para>
/// Notifies the object that initialization is complete.
/// </para>
/// </summary>
public void EndInit()
{
_initializing = false;
Enabled = _delayedEnable;
}
/// <summary>
/// <para>Starts the timing by setting <see cref='System.Timers.Timer.Enabled'/> to <see langword='true'/>.</para>
/// </summary>
public void Start()
{
Enabled = true;
}
/// <summary>
/// <para>
/// Stops the timing by setting <see cref='System.Timers.Timer.Enabled'/> to <see langword='false'/>.
/// </para>
/// </summary>
public void Stop()
{
Enabled = false;
}
private void MyTimerCallback(object state)
{
// System.Threading.Timer will not cancel the work item queued before the timer is stopped.
// We don't want to handle the callback after a timer is stopped.
if (state != _cookie)
{
return;
}
if (!_autoReset)
{
_enabled = false;
}
ElapsedEventArgs elapsedEventArgs = new ElapsedEventArgs(DateTime.UtcNow.ToFileTime());
try
{
// To avoid race between remove handler and raising the event
ElapsedEventHandler intervalElapsed = _onIntervalElapsed;
if (intervalElapsed != null)
{
if (SynchronizingObject != null && SynchronizingObject.InvokeRequired)
SynchronizingObject.BeginInvoke(intervalElapsed, new object[] { this, elapsedEventArgs });
else
intervalElapsed(this, elapsedEventArgs);
}
}
catch
{
}
}
}
}
| |
// [Twin] Copyright eBay Inc., Twin authors, and other contributors.
// This file is provided to you under the terms of the Apache License, Version 2.0.
// See LICENSE.txt and NOTICE.txt for license and copyright information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Windows.Automation;
using Twin.SharpClaws.API;
using Twin.Logging;
using Twin.Model;
using Twin.View;
// ResponseStatus
namespace Twin.Generic
{
class ParsedRequest {
public readonly JasonServlet Servlet;
public readonly IRequest Request;
public readonly Dictionary<string, string> Parameters;
public ParsedRequest(IRequest request, Dictionary<string, string> parameters) {
this.Request = request;
this.Servlet = (JasonServlet)request.Servlet;
this.Parameters = parameters;
}
}
delegate void Handler(ParsedRequest request);
class Responder {
private Handler handler;
public Responder(Handler handler) {
this.handler = handler;
}
public virtual void Respond(ParsedRequest request) {
handler(request);
}
public static implicit operator Responder(Handler handler) {
return new Responder(handler);
}
public static implicit operator Responder(JSONHandler handler) {
return new JSONResponder(handler);
}
public static implicit operator Responder(SessionHandler handler) {
return new SessionResponder(handler);
}
public static implicit operator Responder(ElementHandler handler) {
return new ElementResponder(handler, false); // element must exist
}
}
class ResourceResponder : Responder {
string name;
string contentType;
public ResourceResponder(string name, string contentType) : base(null) {
this.name = name;
this.contentType = contentType;
}
public override void Respond(ParsedRequest request) {
request.Request.Response.WriteResource(name, contentType);
}
}
class JSONRequest : ParsedRequest {
public JSONRequest(ParsedRequest parent) : base(parent.Request, parent.Parameters) {
if (parent.Request.ContentType == "application/json") {
byte[] dataBytes = parent.Request.ReadBytes();
string data = dataBytes == null ? null : Encoding.UTF8.GetString(dataBytes);
object body = JSON.ToObject(data);
if (!(body is Dictionary<string, object>))
throw new HttpException(400, "Body was application/json, but decoded as a " +
(body==null ? "null" : body.GetType().Name)
+ " rather than Dictionary");
Body = (Dictionary<string, object>)body;
}
}
public JSONRequest(JSONRequest parent) : base(parent.Request, parent.Parameters) {
Body = parent.Body;
}
public Dictionary<string, object> Body;
}
class JSONResponse {
public int StatusCode = 200;
public Dictionary<string,object> Body;
public string Location;
public string[] Options;
}
delegate JSONResponse JSONHandler(JSONRequest request);
class JSONResponder : Responder {
JSONHandler handler;
public JSONResponder(JSONHandler handler) : base(null) {
this.handler = handler;
}
public virtual JSONResponse Respond(JSONRequest request) {
return handler(request);
}
public override void Respond(ParsedRequest request) {
JSONRequest jreq = new JSONRequest(request);
JSONResponse jres = null;
try {
jres = Respond(jreq);
} catch (Exception e) {
if (e is HttpException)
throw e;
jres = GetExceptionResponse(e);
}
WriteJSONResponse(jres, request.Request.Response);
}
JSONResponse GetExceptionResponse(Exception e) {
Logger.Current.Trace("Building response for thrown exception");
Logger.Current.Trace(e);
JSONResponse response = new JSONResponse();
response.StatusCode = 500;
// TODO: should this be here? breaks layering
ResponseStatus responseCode = ResponseStatus.UnknownError; // unknown
if (e is TwinException)
responseCode = ((TwinException)e).ResponseStatus;
if (e is ElementNotAvailableException)
responseCode = ResponseStatus.NoSuchElement;
Dictionary<string, object> wrapper = new Dictionary<string, object>();
wrapper["status"] = (int)responseCode;
wrapper["value"] = EncodeException(e);
response.Body = wrapper;
return response;
}
public static Object EncodeException(Exception e) {
Dictionary<string, object> body = new Dictionary<string, object>();
body["message"] = e.Message;
body["class"] = e.GetType().FullName;
List<object> traceJson = new List<Object>();
StackTrace trace = new StackTrace(e, true);
foreach (StackFrame frame in trace.GetFrames()) {
Dictionary<string, object> frameJson = new Dictionary<string, object>();
frameJson["className"] = frame.GetMethod().DeclaringType.FullName;
frameJson["methodName"] = frame.GetMethod().Name;
if (frame.GetFileName() != null)
frameJson["fileName"] = frame.GetFileName();
if (frame.GetFileLineNumber() != 0)
frameJson["lineNumber"] = frame.GetFileLineNumber();
traceJson.Add(frameJson);
}
if (e.InnerException != null && e.InnerException != e) {
body["cause"] = EncodeException(e.InnerException);
}
body["stackTrace"] = traceJson;
return body;
}
void WriteJSONResponse(JSONResponse response, IResponse http) {
http.StatusCode = response.StatusCode;
if (response.Location != null)
http.Headers["Location"] = http.URL(response.Location);
if (response.Options != null)
http.Headers["Allow"] = string.Join(",", response.Options);
if(response.Body != null)
using(TextWriter writer = http.OpenWriter("application/json")) {
// Ideally we'd stream the object for perf reasons.
// however during dev, if the serialiser hits an unrecognised object we want the stacktrace to be sent to the client
// this can't happen if data has already been written. So for now, convert to a string in memory, then write when done.
// JSON.Write(response.Body, writer);
writer.Write(JSON.ToString(response.Body, 4));
}
}
}
class SessionRequest : JSONRequest {
public readonly Session Session;
public SessionRequest(JSONRequest basic) : base(basic) {
try {
this.Session = Sessions.GetSession(basic);
} catch (ArgumentException ex) {
throw new TwinException(ResponseStatus.NoSuchSession, ex.Message, ex);
}
}
}
delegate object SessionHandler(SessionRequest request);
class SessionResponder : JSONResponder {
SessionHandler handler;
public SessionResponder(SessionHandler handler) : base(null) {
this.handler = handler;
}
public virtual object Respond(SessionRequest request) {
return handler(request);
}
public override JSONResponse Respond(JSONRequest request) {
SessionRequest sessionRequest = new SessionRequest(request);
object value = Respond(sessionRequest);
if (value is JSONResponse)
return (JSONResponse)value;
JSONResponse response = new JSONResponse();
response.Body = new Dictionary<string, object>();
response.Body["sessionId"] = sessionRequest.Session.ToString();
response.Body["status"] = (int)ResponseStatus.Success;
response.Body["value"] = value;
return response;
}
}
class ElementRequest : SessionRequest {
public ElementRequest(SessionRequest basic, Element target) : base(basic) {
Target = target;
}
public readonly Element Target;
}
delegate object ElementHandler(ElementRequest request);
class ElementResponder : SessionResponder {
ElementHandler handler;
bool optional;
public ElementResponder(ElementHandler handler, bool optional) : base(null) {
this.handler = handler;
this.optional = optional;
}
public virtual object Respond(ElementRequest request) {
return handler(request);
}
public override object Respond(SessionRequest request) {
Element element = GetTargetElement(request);
if(!optional && !element.Exists)
throw new ElementNotAvailableException("Element no longer exists");
return Respond(new ElementRequest(request, element));
}
protected virtual Element GetTargetElement(SessionRequest basic) {
string targetId = (string)basic.Parameters["target"];
return (Element)basic.Session[new Guid(targetId)];
}
}
class DesktopResponder : ElementResponder {
public DesktopResponder(ElementHandler handler) : base(handler, true) {} // optional for efficiency, desktop will always exist
public static explicit operator DesktopResponder(ElementHandler handler) {
return new DesktopResponder(handler);
}
protected override Element GetTargetElement(SessionRequest basic) {
return Desktop.GetInstance(basic.Session.Process.Id);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.12.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsBodyDateTimeRfc1123
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Models;
/// <summary>
/// Datetimerfc1123 operations.
/// </summary>
public partial class Datetimerfc1123 : IServiceOperations<AutoRestRFC1123DateTimeTestService>, IDatetimerfc1123
{
/// <summary>
/// Initializes a new instance of the Datetimerfc1123 class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
public Datetimerfc1123(AutoRestRFC1123DateTimeTestService client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the AutoRestRFC1123DateTimeTestService
/// </summary>
public AutoRestRFC1123DateTimeTestService Client { get; private set; }
/// <summary>
/// Get null datetime value
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse<DateTime?>> GetNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "GetNull", tracingParameters);
}
// Construct URL
var baseUrl = this.Client.BaseUri.AbsoluteUri;
var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "datetimerfc1123/null").ToString();
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("GET");
httpRequest.RequestUri = new Uri(url);
// Set Headers
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
if (httpRequest.Headers.Contains(header.Key))
{
httpRequest.Headers.Remove(header.Key);
}
httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
}
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse<DateTime?>();
result.Request = httpRequest;
result.Response = httpResponse;
// Deserialize Response
if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))
{
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result.Body = JsonConvert.DeserializeObject<DateTime?>(responseContent, this.Client.DeserializationSettings);
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Get invalid datetime value
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse<DateTime?>> GetInvalidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "GetInvalid", tracingParameters);
}
// Construct URL
var baseUrl = this.Client.BaseUri.AbsoluteUri;
var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "datetimerfc1123/invalid").ToString();
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("GET");
httpRequest.RequestUri = new Uri(url);
// Set Headers
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
if (httpRequest.Headers.Contains(header.Key))
{
httpRequest.Headers.Remove(header.Key);
}
httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
}
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse<DateTime?>();
result.Request = httpRequest;
result.Response = httpResponse;
// Deserialize Response
if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))
{
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result.Body = JsonConvert.DeserializeObject<DateTime?>(responseContent, this.Client.DeserializationSettings);
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Get overflow datetime value
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse<DateTime?>> GetOverflowWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "GetOverflow", tracingParameters);
}
// Construct URL
var baseUrl = this.Client.BaseUri.AbsoluteUri;
var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "datetimerfc1123/overflow").ToString();
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("GET");
httpRequest.RequestUri = new Uri(url);
// Set Headers
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
if (httpRequest.Headers.Contains(header.Key))
{
httpRequest.Headers.Remove(header.Key);
}
httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
}
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse<DateTime?>();
result.Request = httpRequest;
result.Response = httpResponse;
// Deserialize Response
if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))
{
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result.Body = JsonConvert.DeserializeObject<DateTime?>(responseContent, this.Client.DeserializationSettings);
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Get underflow datetime value
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse<DateTime?>> GetUnderflowWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "GetUnderflow", tracingParameters);
}
// Construct URL
var baseUrl = this.Client.BaseUri.AbsoluteUri;
var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "datetimerfc1123/underflow").ToString();
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("GET");
httpRequest.RequestUri = new Uri(url);
// Set Headers
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
if (httpRequest.Headers.Contains(header.Key))
{
httpRequest.Headers.Remove(header.Key);
}
httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
}
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse<DateTime?>();
result.Request = httpRequest;
result.Response = httpResponse;
// Deserialize Response
if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))
{
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result.Body = JsonConvert.DeserializeObject<DateTime?>(responseContent, this.Client.DeserializationSettings);
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Put max datetime value Fri, 31 Dec 9999 23:59:59 GMT
/// </summary>
/// <param name='datetimeBody'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse> PutUtcMaxDateTimeWithHttpMessagesAsync(DateTime? datetimeBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (datetimeBody == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "datetimeBody");
}
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("datetimeBody", datetimeBody);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "PutUtcMaxDateTime", tracingParameters);
}
// Construct URL
var baseUrl = this.Client.BaseUri.AbsoluteUri;
var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "datetimerfc1123/max").ToString();
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("PUT");
httpRequest.RequestUri = new Uri(url);
// Set Headers
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
if (httpRequest.Headers.Contains(header.Key))
{
httpRequest.Headers.Remove(header.Key);
}
httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
}
// Serialize Request
string requestContent = JsonConvert.SerializeObject(datetimeBody, new DateTimeRfc1123JsonConverter());
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse();
result.Request = httpRequest;
result.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Get max datetime value fri, 31 dec 9999 23:59:59 gmt
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse<DateTime?>> GetUtcLowercaseMaxDateTimeWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "GetUtcLowercaseMaxDateTime", tracingParameters);
}
// Construct URL
var baseUrl = this.Client.BaseUri.AbsoluteUri;
var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "datetimerfc1123/max/lowercase").ToString();
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("GET");
httpRequest.RequestUri = new Uri(url);
// Set Headers
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
if (httpRequest.Headers.Contains(header.Key))
{
httpRequest.Headers.Remove(header.Key);
}
httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
}
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse<DateTime?>();
result.Request = httpRequest;
result.Response = httpResponse;
// Deserialize Response
if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))
{
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result.Body = JsonConvert.DeserializeObject<DateTime?>(responseContent, this.Client.DeserializationSettings);
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Get max datetime value FRI, 31 DEC 9999 23:59:59 GMT
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse<DateTime?>> GetUtcUppercaseMaxDateTimeWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "GetUtcUppercaseMaxDateTime", tracingParameters);
}
// Construct URL
var baseUrl = this.Client.BaseUri.AbsoluteUri;
var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "datetimerfc1123/max/uppercase").ToString();
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("GET");
httpRequest.RequestUri = new Uri(url);
// Set Headers
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
if (httpRequest.Headers.Contains(header.Key))
{
httpRequest.Headers.Remove(header.Key);
}
httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
}
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse<DateTime?>();
result.Request = httpRequest;
result.Response = httpResponse;
// Deserialize Response
if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))
{
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result.Body = JsonConvert.DeserializeObject<DateTime?>(responseContent, this.Client.DeserializationSettings);
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Put min datetime value Mon, 1 Jan 0001 00:00:00 GMT
/// </summary>
/// <param name='datetimeBody'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse> PutUtcMinDateTimeWithHttpMessagesAsync(DateTime? datetimeBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (datetimeBody == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "datetimeBody");
}
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("datetimeBody", datetimeBody);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "PutUtcMinDateTime", tracingParameters);
}
// Construct URL
var baseUrl = this.Client.BaseUri.AbsoluteUri;
var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "datetimerfc1123/min").ToString();
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("PUT");
httpRequest.RequestUri = new Uri(url);
// Set Headers
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
if (httpRequest.Headers.Contains(header.Key))
{
httpRequest.Headers.Remove(header.Key);
}
httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
}
// Serialize Request
string requestContent = JsonConvert.SerializeObject(datetimeBody, new DateTimeRfc1123JsonConverter());
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse();
result.Request = httpRequest;
result.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Get min datetime value Mon, 1 Jan 0001 00:00:00 GMT
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse<DateTime?>> GetUtcMinDateTimeWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "GetUtcMinDateTime", tracingParameters);
}
// Construct URL
var baseUrl = this.Client.BaseUri.AbsoluteUri;
var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "datetimerfc1123/min").ToString();
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("GET");
httpRequest.RequestUri = new Uri(url);
// Set Headers
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
if (httpRequest.Headers.Contains(header.Key))
{
httpRequest.Headers.Remove(header.Key);
}
httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
}
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse<DateTime?>();
result.Request = httpRequest;
result.Response = httpResponse;
// Deserialize Response
if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))
{
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result.Body = JsonConvert.DeserializeObject<DateTime?>(responseContent, this.Client.DeserializationSettings);
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
}
}
| |
/*
* 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.
*/
namespace Apache.Ignite.Core.Impl
{
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using Apache.Ignite.Core.Cache;
using Apache.Ignite.Core.Cluster;
using Apache.Ignite.Core.Common;
using Apache.Ignite.Core.Impl.Binary;
using Apache.Ignite.Core.Impl.Cluster;
using Apache.Ignite.Core.Impl.Common;
using BinaryReader = Apache.Ignite.Core.Impl.Binary.BinaryReader;
/// <summary>
/// Native utility methods.
/// </summary>
internal static class IgniteUtils
{
/** Thread-local random. */
[ThreadStatic]
private static Random _rnd;
/// <summary>
/// Gets thread local random.
/// </summary>
/// <value>Thread local random.</value>
public static Random ThreadLocalRandom
{
get { return _rnd ?? (_rnd = new Random()); }
}
/// <summary>
/// Returns shuffled list copy.
/// </summary>
/// <returns>Shuffled list copy.</returns>
public static IList<T> Shuffle<T>(IList<T> list)
{
int cnt = list.Count;
if (cnt > 1) {
List<T> res = new List<T>(list);
Random rnd = ThreadLocalRandom;
while (cnt > 1)
{
cnt--;
int idx = rnd.Next(cnt + 1);
T val = res[idx];
res[idx] = res[cnt];
res[cnt] = val;
}
return res;
}
return list;
}
/// <summary>
/// Create new instance of specified class.
/// </summary>
/// <param name="typeName">Class name</param>
/// <param name="props">Properties to set.</param>
/// <returns>New Instance.</returns>
public static T CreateInstance<T>(string typeName, IEnumerable<KeyValuePair<string, object>> props = null)
{
IgniteArgumentCheck.NotNullOrEmpty(typeName, "typeName");
var type = new TypeResolver().ResolveType(typeName);
if (type == null)
throw new IgniteException("Failed to create class instance [className=" + typeName + ']');
var res = (T) Activator.CreateInstance(type);
if (props != null)
SetProperties(res, props);
return res;
}
/// <summary>
/// Set properties on the object.
/// </summary>
/// <param name="target">Target object.</param>
/// <param name="props">Properties.</param>
private static void SetProperties(object target, IEnumerable<KeyValuePair<string, object>> props)
{
if (props == null)
return;
IgniteArgumentCheck.NotNull(target, "target");
Type typ = target.GetType();
foreach (KeyValuePair<string, object> prop in props)
{
PropertyInfo prop0 = typ.GetProperty(prop.Key,
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
if (prop0 == null)
throw new IgniteException("Property is not found [type=" + typ.Name +
", property=" + prop.Key + ']');
prop0.SetValue(target, prop.Value, null);
}
}
/// <summary>
/// Convert unmanaged char array to string.
/// </summary>
/// <param name="chars">Char array.</param>
/// <param name="charsLen">Char array length.</param>
/// <returns></returns>
public static unsafe string Utf8UnmanagedToString(sbyte* chars, int charsLen)
{
IntPtr ptr = new IntPtr(chars);
if (ptr == IntPtr.Zero)
return null;
byte[] arr = new byte[charsLen];
Marshal.Copy(ptr, arr, 0, arr.Length);
return Encoding.UTF8.GetString(arr);
}
/// <summary>
/// Convert string to unmanaged byte array.
/// </summary>
/// <param name="str">String.</param>
/// <returns>Unmanaged byte array.</returns>
public static unsafe sbyte* StringToUtf8Unmanaged(string str)
{
var ptr = IntPtr.Zero;
if (str != null)
{
byte[] strBytes = Encoding.UTF8.GetBytes(str);
ptr = Marshal.AllocHGlobal(strBytes.Length + 1);
Marshal.Copy(strBytes, 0, ptr, strBytes.Length);
*((byte*)ptr.ToPointer() + strBytes.Length) = 0; // NULL-terminator.
}
return (sbyte*)ptr.ToPointer();
}
/// <summary>
/// Reads node collection from stream.
/// </summary>
/// <param name="reader">Reader.</param>
/// <param name="pred">The predicate.</param>
/// <returns> Nodes list or null. </returns>
public static List<IClusterNode> ReadNodes(BinaryReader reader, Func<ClusterNodeImpl, bool> pred = null)
{
var cnt = reader.ReadInt();
if (cnt < 0)
return null;
var res = new List<IClusterNode>(cnt);
var ignite = reader.Marshaller.Ignite;
if (pred == null)
{
for (var i = 0; i < cnt; i++)
res.Add(ignite.GetNode(reader.ReadGuid()));
}
else
{
for (var i = 0; i < cnt; i++)
{
var node = ignite.GetNode(reader.ReadGuid());
if (pred(node))
res.Add(node);
}
}
return res;
}
/// <summary>
/// Encodes the peek modes into a single int value.
/// </summary>
public static int EncodePeekModes(CachePeekMode[] modes, out bool hasPlatformCache)
{
var res = 0;
hasPlatformCache = false;
if (modes == null)
{
return res;
}
foreach (var mode in modes)
{
res |= (int) mode;
}
// Clear Platform bit: Java does not understand it.
const int platformCache = (int) CachePeekMode.Platform;
const int all = (int) CachePeekMode.All;
hasPlatformCache = (res & platformCache) == platformCache || (res & all) == all;
return res & ~platformCache;
}
}
}
| |
// 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.
//
// ABOUT THIS FILE:
// -- This file contains native methods which are deemed NOT SAFE in the sense that any usage of them
// must be carefully reviewed. FXCop will flag callers of these for review.
// -- These methods DO have the SuppressUnmanagedCodeSecurity attribute which means stalk walks for unmanaged
// code will stop with the immediate caler.
// -- Put methods in here when a stack walk is innappropriate due to performance concerns
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
using System.Runtime.ConstrainedExecution;
using System;
using MS.Internal;
using MS.Internal.PresentationCore;
using System.Security;
using System.Collections;
using System.IO;
using System.Text;
using System.Windows.Media.Composition;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows;
using MS.Win32;
using IComDataObject = System.Runtime.InteropServices.ComTypes.IDataObject;
using DllImport = MS.Internal.PresentationCore.DllImport;
#pragma warning disable 1634, 1691 // suppressing PreSharp warnings
namespace MS.Win32.PresentationCore
{
internal static partial class UnsafeNativeMethods
{
internal static class MilCoreApi
{
[DllImport(DllImport.MilCore, EntryPoint = "MilCompositionEngine_EnterCompositionEngineLock")]
internal static extern void EnterCompositionEngineLock();
[DllImport(DllImport.MilCore, EntryPoint = "MilCompositionEngine_ExitCompositionEngineLock")]
internal static extern void ExitCompositionEngineLock();
[DllImport(DllImport.MilCore, EntryPoint = "MilCompositionEngine_EnterMediaSystemLock")]
internal static extern void EnterMediaSystemLock();
[DllImport(DllImport.MilCore, EntryPoint = "MilCompositionEngine_ExitMediaSystemLock")]
internal static extern void ExitMediaSystemLock();
[DllImport(DllImport.MilCore)]
internal static extern int MilVersionCheck(
uint uiCallerMilSdkVersion
);
[DllImport(DllImport.MilCore)]
internal static extern bool WgxConnection_ShouldForceSoftwareForGraphicsStreamClient();
[DllImport(DllImport.MilCore)]
internal static extern int WgxConnection_Create(
bool requestSynchronousTransport,
out IntPtr ppConnection);
[DllImport(DllImport.MilCore)]
internal static extern int WgxConnection_Disconnect(IntPtr pTranspManager);
//[DllImport(DllImport.MilCore)]
//internal extern static int /* HRESULT */ MILCreateStreamFromStreamDescriptor(ref System.Windows.Media.StreamDescriptor pSD, out IntPtr ppStream);
//[DllImport(DllImport.MilCore)]
//unsafe internal static extern void MilUtility_GetTileBrushMapping(
// D3DMATRIX* transform,
// D3DMATRIX* relativeTransform,
// Stretch stretch,
// AlignmentX alignmentX,
// AlignmentY alignmentY,
// BrushMappingMode viewPortUnits,
// BrushMappingMode viewBoxUnits,
// Rect* shapeFillBounds,
// Rect* contentBounds,
// ref Rect viewport,
// ref Rect viewbox,
// out D3DMATRIX contentToShape,
// out int brushIsEmpty
// );
//[DllImport(DllImport.MilCore)]
//internal unsafe static extern int MilUtility_PathGeometryBounds(
// MIL_PEN_DATA* pPenData,
// double* pDashArray,
// MilMatrix3x2D* pWorldMatrix,
// FillRule fillRule,
// byte* pPathData,
// UInt32 nSize,
// MilMatrix3x2D* pGeometryMatrix,
// double rTolerance,
// bool fRelative,
// bool fSkipHollows,
// MilRectD* pBounds);
//[DllImport(DllImport.MilCore)]
//internal unsafe static extern int MilUtility_PathGeometryCombine(
// MilMatrix3x2D* pMatrix,
// MilMatrix3x2D* pMatrix1,
// FillRule fillRule1,
// byte* pPathData1,
// UInt32 nSize1,
// MilMatrix3x2D* pMatrix2,
// FillRule fillRule2,
// byte* pPathData2,
// UInt32 nSize2,
// double rTolerance,
// bool fRelative,
// Delegate addFigureCallback,
// GeometryCombineMode combineMode,
// out FillRule resultFillRule);
//[DllImport(DllImport.MilCore)]
//internal unsafe static extern int MilUtility_PathGeometryWiden(
// MIL_PEN_DATA* pPenData,
// double* pDashArray,
// MilMatrix3x2D* pMatrix,
// FillRule fillRule,
// byte* pPathData,
// UInt32 nSize,
// double rTolerance,
// bool fRelative,
// Delegate addFigureCallback,
// out FillRule widenedFillRule);
//[DllImport(DllImport.MilCore)]
//internal unsafe static extern int MilUtility_PathGeometryOutline(
// MilMatrix3x2D* pMatrix,
// FillRule fillRule,
// byte* pPathData,
// UInt32 nSize,
// double rTolerance,
// bool fRelative,
// Delegate addFigureCallback,
// out FillRule outlinedFillRule);
//[DllImport(DllImport.MilCore)]
//internal unsafe static extern int MilUtility_PathGeometryFlatten(
// MilMatrix3x2D* pMatrix,
// FillRule fillRule,
// byte* pPathData,
// UInt32 nSize,
// double rTolerance,
// bool fRelative,
// Delegate addFigureCallback,
// out FillRule resultFillRule);
//[DllImport(DllImport.MilCore)]
//internal unsafe static extern int /* HRESULT */ MilGlyphCache_SetCreateGlyphBitmapsCallback(
// MulticastDelegate del
// );
//[DllImport(DllImport.MilCore)]
//internal unsafe static extern int MilGlyphCache_BeginCommandAtRenderTime(
// IntPtr pMilSlaveGlyphCacheTarget,
// byte* pbData,
// uint cbSize,
// uint cbExtra
// );
//[DllImport(DllImport.MilCore)]
//internal unsafe static extern int MilGlyphCache_AppendCommandDataAtRenderTime(
// IntPtr pMilSlaveGlyphCacheTarget,
// byte* pbData,
// uint cbSize
// );
//[DllImport(DllImport.MilCore)]
//internal unsafe static extern int MilGlyphCache_EndCommandAtRenderTime(
// IntPtr pMilSlaveGlyphCacheTarget
// );
//[DllImport(DllImport.MilCore)]
//internal unsafe static extern int MilGlyphRun_SetGeometryAtRenderTime(
// IntPtr pMilGlyphRunTarget,
// byte* pCmd,
// uint cbCmd
// );
//[DllImport(DllImport.MilCore)]
//internal unsafe static extern int MilGlyphRun_GetGlyphOutline(
// IntPtr pFontFace,
// ushort glyphIndex,
// bool sideways,
// double renderingEmSize,
// out byte* pPathGeometryData,
// out UInt32 pSize,
// out FillRule pFillRule
// );
//[DllImport(DllImport.MilCore)]
//internal unsafe static extern int MilGlyphRun_ReleasePathGeometryData(
// byte* pPathGeometryData
// );
//[DllImport(DllImport.MilCore, EntryPoint = "MilCreateReversePInvokeWrapper")]
//internal unsafe static extern /*HRESULT*/ int MilCreateReversePInvokeWrapper(
// IntPtr pFcn,
// out IntPtr reversePInvokeWrapper);
//[DllImport(DllImport.MilCore, EntryPoint = "MilReleasePInvokePtrBlocking")]
//internal unsafe static extern void MilReleasePInvokePtrBlocking(
// IntPtr reversePInvokeWrapper);
//[DllImport(DllImport.MilCore, EntryPoint = "RenderOptions_ForceSoftwareRenderingModeForProcess")]
//internal unsafe static extern void RenderOptions_ForceSoftwareRenderingModeForProcess(
// bool fForce);
//[DllImport(DllImport.MilCore, EntryPoint = "RenderOptions_IsSoftwareRenderingForcedForProcess")]
//internal unsafe static extern bool RenderOptions_IsSoftwareRenderingForcedForProcess();
//[DllImport(DllImport.MilCore, EntryPoint = "MilResource_CreateCWICWrapperBitmap")]
//internal unsafe static extern int /* HRESULT */ CreateCWICWrapperBitmap(
// BitmapSourceSafeMILHandle /* IWICBitmapSource */ pIWICBitmapSource,
// out BitmapSourceSafeMILHandle /* CWICWrapperBitmap as IWICBitmapSource */ pCWICWrapperBitmap);
}
// internal static class WICComponentInfo
// {
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICComponentInfo_GetCLSID_Proxy")]
// internal static extern int /* HRESULT */ GetCLSID(
// System.Windows.Media.SafeMILHandle /* IWICComponentInfo */ THIS_PTR,
// out Guid pclsid);
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICComponentInfo_GetAuthor_Proxy")]
// internal static extern int /* HRESULT */ GetAuthor(
// System.Windows.Media.SafeMILHandle /* IWICComponentInfo */ THIS_PTR,
// UInt32 cchAuthor,
// [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder wzAuthor,
// out UInt32 pcchActual);
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICComponentInfo_GetVersion_Proxy")]
// internal static extern int /* HRESULT */ GetVersion(
// System.Windows.Media.SafeMILHandle /* IWICComponentInfo */ THIS_PTR,
// UInt32 cchVersion,
// [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder wzVersion,
// out UInt32 pcchActual);
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICComponentInfo_GetSpecVersion_Proxy")]
// internal static extern int /* HRESULT */ GetSpecVersion(
// System.Windows.Media.SafeMILHandle /* IWICComponentInfo */ THIS_PTR,
// UInt32 cchSpecVersion,
// [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder wzSpecVersion,
// out UInt32 pcchActual);
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICComponentInfo_GetFriendlyName_Proxy")]
// internal static extern int /* HRESULT */ GetFriendlyName(
// System.Windows.Media.SafeMILHandle /* IWICComponentInfo */ THIS_PTR,
// UInt32 cchFriendlyName,
// [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder wzFriendlyName,
// out UInt32 pcchActual);
// }
// internal static class WICBitmapCodecInfo
// {
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICBitmapCodecInfo_GetContainerFormat_Proxy")]
// internal static extern int /* HRESULT */ GetContainerFormat(
// System.Windows.Media.SafeMILHandle /* IWICBitmapCodecInfo */ THIS_PTR,
// out Guid pguidContainerFormat);
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICBitmapCodecInfo_GetDeviceManufacturer_Proxy")]
// internal static extern int /* HRESULT */ GetDeviceManufacturer(
// System.Windows.Media.SafeMILHandle /* IWICBitmapCodecInfo */ THIS_PTR,
// UInt32 cchDeviceManufacturer,
// [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder wzDeviceManufacturer,
// out UInt32 pcchActual
// );
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICBitmapCodecInfo_GetDeviceModels_Proxy")]
// internal static extern int /* HRESULT */ GetDeviceModels(
// System.Windows.Media.SafeMILHandle /* IWICBitmapCodecInfo */ THIS_PTR,
// UInt32 cchDeviceModels,
// [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder wzDeviceModels,
// out UInt32 pcchActual
// );
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICBitmapCodecInfo_GetMimeTypes_Proxy")]
// internal static extern int /* HRESULT */ GetMimeTypes(
// System.Windows.Media.SafeMILHandle /* IWICBitmapCodecInfo */ THIS_PTR,
// UInt32 cchMimeTypes,
// [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder wzMimeTypes,
// out UInt32 pcchActual
// );
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICBitmapCodecInfo_GetFileExtensions_Proxy")]
// internal static extern int /* HRESULT */ GetFileExtensions(
// System.Windows.Media.SafeMILHandle /* IWICBitmapCodecInfo */ THIS_PTR,
// UInt32 cchFileExtensions,
// [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder wzFileExtensions,
// out UInt32 pcchActual
// );
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICBitmapCodecInfo_DoesSupportAnimation_Proxy")]
// internal static extern int /* HRESULT */ DoesSupportAnimation(
// System.Windows.Media.SafeMILHandle /* IWICBitmapCodecInfo */ THIS_PTR,
// out bool pfSupportAnimation
// );
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICBitmapCodecInfo_DoesSupportLossless_Proxy")]
// internal static extern int /* HRESULT */ DoesSupportLossless(
// System.Windows.Media.SafeMILHandle /* IWICBitmapCodecInfo */ THIS_PTR,
// out bool pfSupportLossless
// );
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICBitmapCodecInfo_DoesSupportMultiframe_Proxy")]
// internal static extern int /* HRESULT */ DoesSupportMultiframe(
// System.Windows.Media.SafeMILHandle /* IWICBitmapCodecInfo */ THIS_PTR,
// out bool pfSupportMultiframe
// );
// }
// internal static class WICMetadataQueryReader
// {
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICMetadataQueryReader_GetContainerFormat_Proxy")]
// internal static extern int /* HRESULT */ GetContainerFormat(
// System.Windows.Media.SafeMILHandle /* IWICMetadataQueryReader */ THIS_PTR,
// out Guid pguidContainerFormat);
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICMetadataQueryReader_GetLocation_Proxy")]
// internal static extern int /* HRESULT */ GetLocation(
// System.Windows.Media.SafeMILHandle /* IWICMetadataQueryReader */ THIS_PTR,
// UInt32 cchLocation,
// [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder wzNamespace,
// out UInt32 pcchActual
// );
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICMetadataQueryReader_GetMetadataByName_Proxy")]
// internal static extern int /* HRESULT */ GetMetadataByName(
// System.Windows.Media.SafeMILHandle /* IWICMetadataQueryReader */ THIS_PTR,
// [MarshalAs(UnmanagedType.LPWStr)] String wzName,
// ref System.Windows.Media.Imaging.PROPVARIANT propValue
// );
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICMetadataQueryReader_GetMetadataByName_Proxy")]
// internal static extern int /* HRESULT */ ContainsMetadataByName(
// System.Windows.Media.SafeMILHandle /* IWICMetadataQueryReader */ THIS_PTR,
// [MarshalAs(UnmanagedType.LPWStr)] String wzName,
// IntPtr propVar
// );
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICMetadataQueryReader_GetEnumerator_Proxy")]
// internal static extern int /* HRESULT */ GetEnumerator(
// System.Windows.Media.SafeMILHandle /* IWICMetadataQueryReader */ THIS_PTR,
// out System.Windows.Media.SafeMILHandle /* IEnumString */ enumString
// );
// }
// internal static class WICMetadataQueryWriter
// {
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICMetadataQueryWriter_SetMetadataByName_Proxy")]
// internal static extern int /* HRESULT */ SetMetadataByName(
// System.Windows.Media.SafeMILHandle /* IWICMetadataQueryWriter */ THIS_PTR,
// [MarshalAs(UnmanagedType.LPWStr)] String wzName,
// ref System.Windows.Media.Imaging.PROPVARIANT propValue
// );
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICMetadataQueryWriter_RemoveMetadataByName_Proxy")]
// internal static extern int /* HRESULT */ RemoveMetadataByName(
// System.Windows.Media.SafeMILHandle /* IWICMetadataQueryWriter */ THIS_PTR,
// [MarshalAs(UnmanagedType.LPWStr)] String wzName
// );
// }
// internal static class WICFastMetadataEncoder
// {
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICFastMetadataEncoder_Commit_Proxy")]
// internal static extern int /* HRESULT */ Commit(
// System.Windows.Media.SafeMILHandle /* IWICFastMetadataEncoder */ THIS_PTR
// );
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICFastMetadataEncoder_GetMetadataQueryWriter_Proxy")]
// internal static extern int /* HRESULT */ GetMetadataQueryWriter(
// System.Windows.Media.SafeMILHandle /* IWICFastMetadataEncoder */ THIS_PTR,
// out SafeMILHandle /* IWICMetadataQueryWriter */ ppIQueryWriter
// );
// }
// internal static class EnumString
// {
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IEnumString_Next_WIC_Proxy")]
// internal static extern int /* HRESULT */ Next(
// System.Windows.Media.SafeMILHandle /* IEnumString */ THIS_PTR,
// Int32 celt,
// ref IntPtr rgElt,
// ref Int32 pceltFetched
// );
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IEnumString_Reset_WIC_Proxy")]
// internal static extern int /* HRESULT */ Reset(
// System.Windows.Media.SafeMILHandle /* IEnumString */ THIS_PTR
// );
// }
// internal static class IPropertyBag2
// {
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IPropertyBag2_Write_Proxy")]
// internal static extern int /* HRESULT */ Write(
// System.Windows.Media.SafeMILHandle /* IPropertyBag2 */ THIS_PTR,
// UInt32 cProperties,
// ref System.Windows.Media.Imaging.PROPBAG2 propBag,
// ref System.Windows.Media.Imaging.PROPVARIANT propValue
// );
// }
// internal static class WICBitmapSource
// {
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICBitmapSource_GetSize_Proxy")]
// internal static extern int /* HRESULT */ GetSize(
// System.Windows.Media.SafeMILHandle /* IWICBitmapSource */ THIS_PTR,
// out UInt32 puiWidth,
// out UInt32 puiHeight);
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICBitmapSource_GetPixelFormat_Proxy")]
// internal static extern int /* HRESULT */ GetPixelFormat(
// System.Windows.Media.SafeMILHandle /* IWICBitmapSource */ THIS_PTR,
// out Guid pPixelFormatEnum);
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICBitmapSource_GetResolution_Proxy")]
// internal static extern int /* HRESULT */ GetResolution(
// System.Windows.Media.SafeMILHandle /* IWICBitmapSource */ THIS_PTR,
// out double pDpiX,
// out double pDpiY);
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICBitmapSource_CopyPalette_Proxy")]
// internal static extern int /* HRESULT */ CopyPalette(
// System.Windows.Media.SafeMILHandle /* IWICBitmapSource */ THIS_PTR,
// System.Windows.Media.SafeMILHandle /* IMILPalette */ pIPalette);
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICBitmapSource_CopyPixels_Proxy")]
// internal static extern int /* HRESULT */ CopyPixels(
// SafeMILHandle /* IWICBitmapSource */ THIS_PTR,
// ref Int32Rect prc,
// UInt32 cbStride,
// UInt32 cbBufferSize,
// IntPtr /* BYTE* */ pvPixels);
// }
// internal static class WICBitmapDecoder
// {
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICBitmapDecoder_GetDecoderInfo_Proxy")]
// internal static extern int /* HRESULT */ GetDecoderInfo(
// SafeMILHandle THIS_PTR,
// out SafeMILHandle /* IWICBitmapDecoderInfo */ ppIDecoderInfo);
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICBitmapDecoder_CopyPalette_Proxy")]
// internal static extern int /* HRESULT */ CopyPalette(
// SafeMILHandle /* IWICBitmapDecoder */ THIS_PTR,
// SafeMILHandle /* IMILPalette */ pIPalette);
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICBitmapDecoder_GetPreview_Proxy")]
// internal static extern int /* HRESULT */ GetPreview(
// SafeMILHandle THIS_PTR,
// out IntPtr /* IWICBitmapSource */ ppIBitmapSource
// );
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICBitmapDecoder_GetColorContexts_Proxy")]
// internal static extern int /* HRESULT */ GetColorContexts(
// SafeMILHandle THIS_PTR,
// uint count,
// IntPtr[] /* IWICColorContext */ ppIColorContext,
// out uint pActualCount
// );
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICBitmapDecoder_GetThumbnail_Proxy")]
// internal static extern int /* HRESULT */ GetThumbnail(
// SafeMILHandle /* IWICBitmapDecoder */ THIS_PTR,
// out IntPtr /* IWICBitmapSource */ ppIThumbnail
// );
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICBitmapDecoder_GetMetadataQueryReader_Proxy")]
// internal static extern int /* HRESULT */ GetMetadataQueryReader(
// SafeMILHandle /* IWICBitmapDecoder */ THIS_PTR,
// out IntPtr /* IWICMetadataQueryReader */ ppIQueryReader
// );
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICBitmapDecoder_GetFrameCount_Proxy")]
// internal static extern int /* HRESULT */ GetFrameCount(
// SafeMILHandle THIS_PTR,
// out uint pFrameCount
// );
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICBitmapDecoder_GetFrame_Proxy")]
// internal static extern int /* HRESULT */ GetFrame(
// SafeMILHandle /* IWICBitmapDecoder */ THIS_PTR,
// UInt32 index,
// out IntPtr /* IWICBitmapFrameDecode */ ppIFrameDecode
// );
// }
// internal static class WICBitmapFrameDecode
// {
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICBitmapFrameDecode_GetThumbnail_Proxy")]
// internal static extern int /* HRESULT */ GetThumbnail(
// SafeMILHandle /* IWICBitmapFrameDecode */ THIS_PTR,
// out IntPtr /* IWICBitmap */ ppIThumbnail
// );
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICBitmapFrameDecode_GetMetadataQueryReader_Proxy")]
// internal static extern int /* HRESULT */ GetMetadataQueryReader(
// SafeMILHandle /* IWICBitmapFrameDecode */ THIS_PTR,
// out IntPtr /* IWICMetadataQueryReader */ ppIQueryReader
// );
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICBitmapFrameDecode_GetColorContexts_Proxy")]
// internal static extern int /* HRESULT */ GetColorContexts(
// SafeMILHandle /* IWICBitmapFrameDecode */ THIS_PTR,
// uint count,
// IntPtr[] /* IWICColorContext */ ppIColorContext,
// out uint pActualCount
// );
// }
// internal static class MILUnknown
// {
// [DllImport(DllImport.MilCore, EntryPoint = "MILAddRef")]
// internal static extern UInt32 AddRef(SafeMILHandle pIUnkown);
// [DllImport(DllImport.MilCore, EntryPoint = "MILAddRef")]
// internal static extern UInt32 AddRef(SafeReversePInvokeWrapper pIUnknown);
// [DllImport(DllImport.MilCore, EntryPoint = "MILRelease"), ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
// internal static extern int Release(IntPtr pIUnkown);
// internal static void ReleaseInterface(ref IntPtr ptr)
// {
// if (ptr != IntPtr.Zero)
// {
//#pragma warning suppress 6031 // Return value ignored on purpose.
// UnsafeNativeMethods.MILUnknown.Release(ptr);
// ptr = IntPtr.Zero;
// }
// }
// [DllImport(DllImport.MilCore, EntryPoint = "MILQueryInterface")]
// internal static extern int /* HRESULT */ QueryInterface(
// IntPtr pIUnknown,
// ref Guid guid,
// out IntPtr ppvObject);
// [DllImport(DllImport.MilCore, EntryPoint = "MILQueryInterface")]
// internal static extern int /* HRESULT */ QueryInterface(
// SafeMILHandle pIUnknown,
// ref Guid guid,
// out IntPtr ppvObject);
// }
// internal static class WICStream
// {
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICStream_InitializeFromIStream_Proxy")]
// internal static extern int /*HRESULT*/ InitializeFromIStream(
// IntPtr pIWICStream,
// IntPtr pIStream);
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICStream_InitializeFromMemory_Proxy")]
// internal static extern int /*HRESULT*/ InitializeFromMemory(
// IntPtr pIWICStream,
// IntPtr pbBuffer,
// uint cbSize);
// }
// internal static class WindowsCodecApi
// {
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "WICCreateBitmapFromSection")]
// internal static extern int /*HRESULT*/ CreateBitmapFromSection(
// UInt32 width,
// UInt32 height,
// ref Guid pixelFormatGuid,
// IntPtr hSection,
// UInt32 stride,
// UInt32 offset,
// out BitmapSourceSafeMILHandle /* IWICBitmap */ ppIBitmap);
// }
// internal static class WICBitmapFrameEncode
// {
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICBitmapFrameEncode_Initialize_Proxy")]
// internal static extern int /* HRESULT */ Initialize(SafeMILHandle /* IWICBitmapFrameEncode* */ THIS_PTR,
// SafeMILHandle /* IPropertyBag2* */ pIEncoderOptions);
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICBitmapFrameEncode_Commit_Proxy")]
// internal static extern int /* HRESULT */ Commit(SafeMILHandle /* IWICBitmapFrameEncode* */ THIS_PTR);
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICBitmapFrameEncode_SetSize_Proxy")]
// internal static extern int /* HRESULT */ SetSize(SafeMILHandle /* IWICBitmapFrameEncode* */ THIS_PTR,
// int width,
// int height);
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICBitmapFrameEncode_SetResolution_Proxy")]
// internal static extern int /* HRESULT */ SetResolution(SafeMILHandle /* IWICBitmapFrameEncode* */ THIS_PTR,
// double dpiX,
// double dpiY);
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICBitmapFrameEncode_WriteSource_Proxy")]
// internal static extern int /* HRESULT */ WriteSource(SafeMILHandle /* IWICBitmapFrameEncode* */ THIS_PTR,
// SafeMILHandle /* IWICBitmapSource* */ pIBitmapSource,
// ref Int32Rect /* MILRect* */ r);
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICBitmapFrameEncode_SetThumbnail_Proxy")]
// internal static extern int /* HRESULT */ SetThumbnail(SafeMILHandle /* IWICBitmapFrameEncode* */ THIS_PTR,
// System.Windows.Media.SafeMILHandle /* IWICBitmapSource* */ pIThumbnail);
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICBitmapFrameEncode_GetMetadataQueryWriter_Proxy")]
// internal static extern int /* HRESULT */ GetMetadataQueryWriter(
// SafeMILHandle /* IWICBitmapFrameEncode */ THIS_PTR,
// out SafeMILHandle /* IWICMetadataQueryWriter */ ppIQueryWriter
// );
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICBitmapFrameEncode_SetColorContexts_Proxy")]
// internal static extern int /* HRESULT */ SetColorContexts(SafeMILHandle /* IWICBitmapEncoder* */ THIS_PTR,
// uint nIndex,
// IntPtr[] /* IWICColorContext */ ppIColorContext
// );
// }
// internal static class WICBitmapEncoder
// {
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICBitmapEncoder_Initialize_Proxy")]
// internal static extern int /* HRESULT */ Initialize(SafeMILHandle /* IWICBitmapEncoder* */ THIS_PTR,
// IntPtr /* IStream */ pStream,
// WICBitmapEncodeCacheOption option);
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICBitmapEncoder_GetEncoderInfo_Proxy")]
// internal static extern int /* HRESULT */ GetEncoderInfo(SafeMILHandle /* IWICBitmapEncoder* */ THIS_PTR,
// out SafeMILHandle /* IWICBitmapEncoderInfo ** */ ppIEncoderInfo
// );
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICBitmapEncoder_CreateNewFrame_Proxy")]
// internal static extern int /* HRESULT */ CreateNewFrame(SafeMILHandle /* IWICBitmapEncoder* */ THIS_PTR,
// out SafeMILHandle /* IWICBitmapFrameEncode ** */ ppIFramEncode,
// out SafeMILHandle /* IPropertyBag2 ** */ ppIEncoderOptions
// );
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICBitmapEncoder_SetThumbnail_Proxy")]
// internal static extern int /* HRESULT */ SetThumbnail(SafeMILHandle /* IWICBitmapEncoder* */ THIS_PTR,
// System.Windows.Media.SafeMILHandle /* IWICBitmapSource* */ pIThumbnail);
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICBitmapEncoder_SetPalette_Proxy")]
// internal static extern int /* HRESULT */ SetPalette(SafeMILHandle /* IWICBitmapEncoder* */ THIS_PTR,
// System.Windows.Media.SafeMILHandle /* IWICPalette* */ pIPalette);
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICBitmapEncoder_GetMetadataQueryWriter_Proxy")]
// internal static extern int /* HRESULT */ GetMetadataQueryWriter(
// SafeMILHandle /* IWICBitmapEncoder */ THIS_PTR,
// out SafeMILHandle /* IWICMetadataQueryWriter */ ppIQueryWriter
// );
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICBitmapEncoder_Commit_Proxy")]
// internal static extern int /* HRESULT */ Commit(SafeMILHandle /* IWICBitmapEncoder* */ THIS_PTR);
// }
// internal static class WICPalette
// {
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICPalette_InitializePredefined_Proxy")]
// internal static extern int /* HRESULT */ InitializePredefined(System.Windows.Media.SafeMILHandle /* IWICPalette */ THIS_PTR,
// WICPaletteType ePaletteType,
// bool fAddTransparentColor);
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICPalette_InitializeCustom_Proxy")]
// internal static extern int /* HRESULT */ InitializeCustom(System.Windows.Media.SafeMILHandle /* IWICPalette */ THIS_PTR,
// IntPtr /* MILColor* */ pColors,
// int colorCount);
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICPalette_InitializeFromBitmap_Proxy")]
// internal static extern int /* HRESULT */ InitializeFromBitmap(System.Windows.Media.SafeMILHandle /* IWICPalette */ THIS_PTR,
// System.Windows.Media.SafeMILHandle /* IWICBitmapSource* */ pISurface,
// int colorCount,
// bool fAddTransparentColor);
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICPalette_InitializeFromPalette_Proxy")]
// internal static extern int /* HRESULT */ InitializeFromPalette(IntPtr /* IWICPalette */ THIS_PTR,
// System.Windows.Media.SafeMILHandle /* IWICPalette */ pIWICPalette);
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICPalette_GetType_Proxy")]
// internal static extern int /* HRESULT */ GetType(System.Windows.Media.SafeMILHandle /* IWICPalette */ THIS_PTR,
// out WICPaletteType pePaletteType);
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICPalette_GetColorCount_Proxy")]
// internal static extern int /* HRESULT */ GetColorCount(System.Windows.Media.SafeMILHandle /* IWICPalette */ THIS_PTR,
// out int pColorCount);
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICPalette_GetColors_Proxy")]
// internal static extern int /* HRESULT */ GetColors(System.Windows.Media.SafeMILHandle /* IWICPalette */ THIS_PTR,
// int colorCount,
// IntPtr /* MILColor* */ pColors,
// out int pcActualCount);
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICPalette_HasAlpha_Proxy")]
// internal static extern int /* HRESULT */ HasAlpha(System.Windows.Media.SafeMILHandle /* IWICPalette */ THIS_PTR,
// out bool pfHasAlpha);
// }
// internal static class WICImagingFactory
// {
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICImagingFactory_CreateDecoderFromStream_Proxy")]
// internal static extern int /*HRESULT*/ CreateDecoderFromStream(
// IntPtr pICodecFactory,
// IntPtr /* IStream */ pIStream,
// ref Guid guidVendor,
// UInt32 metadataFlags,
// out IntPtr /* IWICBitmapDecoder */ ppIDecode);
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICImagingFactory_CreateDecoderFromFileHandle_Proxy")]
// internal static extern int /*HRESULT*/ CreateDecoderFromFileHandle(
// IntPtr pICodecFactory,
// Microsoft.Win32.SafeHandles.SafeFileHandle /*ULONG_PTR*/ hFileHandle,
// ref Guid guidVendor,
// UInt32 metadataFlags,
// out IntPtr /* IWICBitmapDecoder */ ppIDecode);
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICImagingFactory_CreateComponentInfo_Proxy")]
// internal static extern int /*HRESULT*/ CreateComponentInfo(
// IntPtr pICodecFactory,
// ref Guid clsidComponent,
// out IntPtr /* IWICComponentInfo */ ppIComponentInfo);
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICImagingFactory_CreatePalette_Proxy")]
// internal static extern int /*HRESULT*/ CreatePalette(
// IntPtr pICodecFactory,
// out SafeMILHandle /* IWICPalette */ ppIPalette);
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICImagingFactory_CreateFormatConverter_Proxy")]
// internal static extern int /* HRESULT */ CreateFormatConverter(
// IntPtr pICodecFactory,
// out BitmapSourceSafeMILHandle /* IWICFormatConverter */ ppFormatConverter);
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICImagingFactory_CreateBitmapScaler_Proxy")]
// internal static extern int /* HRESULT */ CreateBitmapScaler(
// IntPtr pICodecFactory,
// out BitmapSourceSafeMILHandle /* IWICBitmapScaler */ ppBitmapScaler);
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICImagingFactory_CreateBitmapClipper_Proxy")]
// internal static extern int /* HRESULT */ CreateBitmapClipper(
// IntPtr pICodecFactory,
// out BitmapSourceSafeMILHandle /* IWICBitmapClipper */ ppBitmapClipper);
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICImagingFactory_CreateBitmapFlipRotator_Proxy")]
// internal static extern int /* HRESULT */ CreateBitmapFlipRotator(
// IntPtr pICodecFactory,
// out BitmapSourceSafeMILHandle /* IWICBitmapFlipRotator */ ppBitmapFlipRotator);
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICImagingFactory_CreateStream_Proxy")]
// internal static extern int /* HRESULT */ CreateStream(
// IntPtr pICodecFactory,
// out IntPtr /* IWICBitmapStream */ ppIStream);
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICImagingFactory_CreateEncoder_Proxy")]
// internal static extern int /* HRESULT */ CreateEncoder(
// IntPtr pICodecFactory,
// ref Guid guidContainerFormat,
// ref Guid guidVendor,
// out SafeMILHandle /* IUnknown** */ ppICodec);
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICImagingFactory_CreateBitmapFromSource_Proxy")]
// internal static extern int /*HRESULT*/ CreateBitmapFromSource(
// IntPtr THIS_PTR,
// SafeMILHandle /* IWICBitmapSource */ pIBitmapSource,
// WICBitmapCreateCacheOptions options,
// out BitmapSourceSafeMILHandle /* IWICBitmap */ ppIBitmap);
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICImagingFactory_CreateBitmapFromMemory_Proxy")]
// internal static extern int /*HRESULT*/ CreateBitmapFromMemory(
// IntPtr THIS_PTR,
// UInt32 width,
// UInt32 height,
// ref Guid pixelFormatGuid,
// UInt32 stride,
// UInt32 cbBufferSize,
// IntPtr /* BYTE* */ pvPixels,
// out BitmapSourceSafeMILHandle /* IWICBitmap */ ppIBitmap);
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICImagingFactory_CreateBitmap_Proxy")]
// internal static extern int /*HRESULT*/ CreateBitmap(
// IntPtr THIS_PTR,
// UInt32 width,
// UInt32 height,
// ref Guid pixelFormatGuid,
// WICBitmapCreateCacheOptions options,
// out BitmapSourceSafeMILHandle /* IWICBitmap */ ppIBitmap);
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICImagingFactory_CreateBitmapFromHBITMAP_Proxy")]
// internal static extern int /*HRESULT*/ CreateBitmapFromHBITMAP(
// IntPtr THIS_PTR,
// IntPtr hBitmap,
// IntPtr hPalette,
// WICBitmapAlphaChannelOption options,
// out BitmapSourceSafeMILHandle /* IWICBitmap */ ppIBitmap);
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICImagingFactory_CreateBitmapFromHICON_Proxy")]
// internal static extern int /*HRESULT*/ CreateBitmapFromHICON(
// IntPtr THIS_PTR,
// IntPtr hIcon,
// out BitmapSourceSafeMILHandle /* IWICBitmap */ ppIBitmap);
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICImagingFactory_CreateFastMetadataEncoderFromDecoder_Proxy")]
// internal static extern int /*HRESULT*/ CreateFastMetadataEncoderFromDecoder(
// IntPtr THIS_PTR,
// SafeMILHandle /* IWICBitmapDecoder */ pIDecoder,
// out SafeMILHandle /* IWICFastMetadataEncoder */ ppIFME);
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICImagingFactory_CreateFastMetadataEncoderFromFrameDecode_Proxy")]
// internal static extern int /*HRESULT*/ CreateFastMetadataEncoderFromFrameDecode(
// IntPtr THIS_PTR,
// BitmapSourceSafeMILHandle /* IWICBitmapFrameDecode */ pIFrameDecode,
// out SafeMILHandle /* IWICFastMetadataEncoder */ ppIBitmap);
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICImagingFactory_CreateQueryWriter_Proxy")]
// internal static extern int /*HRESULT*/ CreateQueryWriter(
// IntPtr THIS_PTR,
// ref Guid metadataFormat,
// ref Guid guidVendor,
// out IntPtr /* IWICMetadataQueryWriter */ queryWriter
// );
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICImagingFactory_CreateQueryWriterFromReader_Proxy")]
// internal static extern int /*HRESULT*/ CreateQueryWriterFromReader(
// IntPtr THIS_PTR,
// SafeMILHandle /* IWICMetadataQueryReader */ queryReader,
// ref Guid guidVendor,
// out IntPtr /* IWICMetadataQueryWriter */ queryWriter
// );
// }
// internal static class WICComponentFactory
// {
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICComponentFactory_CreateMetadataWriterFromReader_Proxy")]
// internal static extern int /*HRESULT*/ CreateMetadataWriterFromReader(
// IntPtr pICodecFactory,
// SafeMILHandle pIMetadataReader,
// ref Guid guidVendor,
// out IntPtr metadataWriter
// );
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICComponentFactory_CreateQueryWriterFromBlockWriter_Proxy")]
// internal static extern int /*HRESULT*/ CreateQueryWriterFromBlockWriter(
// IntPtr pICodecFactory,
// IntPtr pIBlockWriter,
// ref IntPtr ppIQueryWriter
// );
// }
// internal static class WICMetadataBlockReader
// {
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICMetadataBlockReader_GetCount_Proxy")]
// internal static extern int /*HRESULT*/ GetCount(
// IntPtr pIBlockReader,
// out UInt32 count
// );
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICMetadataBlockReader_GetReaderByIndex_Proxy")]
// internal static extern int /*HRESULT*/ GetReaderByIndex(
// IntPtr pIBlockReader,
// UInt32 index,
// out SafeMILHandle /* IWICMetadataReader* */ pIMetadataReader
// );
// }
// internal static class WICPixelFormatInfo
// {
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICPixelFormatInfo_GetBitsPerPixel_Proxy")]
// internal static extern int /*HRESULT*/ GetBitsPerPixel(
// IntPtr /* IWICPixelFormatInfo */ pIPixelFormatInfo,
// out UInt32 uiBitsPerPixel
// );
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICPixelFormatInfo_GetChannelCount_Proxy")]
// internal static extern int /*HRESULT*/ GetChannelCount(
// IntPtr /* IWICPixelFormatInfo */ pIPixelFormatInfo,
// out UInt32 uiChannelCount
// );
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICPixelFormatInfo_GetChannelMask_Proxy")]
// internal unsafe static extern int /*HRESULT*/ GetChannelMask(
// IntPtr /* IWICPixelFormatInfo */ pIPixelFormatInfo,
// UInt32 uiChannelIndex,
// UInt32 cbMaskBuffer,
// byte* pbMaskBuffer,
// out UInt32 cbActual
// );
// }
// internal static class WICBitmapClipper
// {
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICBitmapClipper_Initialize_Proxy")]
// internal static extern int /* HRESULT */ Initialize(
// System.Windows.Media.SafeMILHandle /* IWICBitmapClipper */ THIS_PTR,
// System.Windows.Media.SafeMILHandle /* IWICBitmapSource */ source,
// ref Int32Rect prc);
// }
// internal static class WICBitmapFlipRotator
// {
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICBitmapFlipRotator_Initialize_Proxy")]
// internal static extern int /* HRESULT */ Initialize(
// System.Windows.Media.SafeMILHandle /* IWICBitmapFlipRotator */ THIS_PTR,
// System.Windows.Media.SafeMILHandle /* IWICBitmapSource */ source,
// WICBitmapTransformOptions options);
// }
// internal static class WICBitmapScaler
// {
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICBitmapScaler_Initialize_Proxy")]
// internal static extern int /* HRESULT */ Initialize(
// System.Windows.Media.SafeMILHandle /* IWICBitmapScaler */ THIS_PTR,
// System.Windows.Media.SafeMILHandle /* IWICBitmapSource */ source,
// uint width,
// uint height,
// WICInterpolationMode mode);
// }
// internal static class WICFormatConverter
// {
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICFormatConverter_Initialize_Proxy")]
// internal static extern int /* HRESULT */ Initialize(
// System.Windows.Media.SafeMILHandle /* IWICFormatConverter */ THIS_PTR,
// System.Windows.Media.SafeMILHandle /* IWICBitmapSource */ source,
// ref Guid dstFormat,
// DitherType dither,
// System.Windows.Media.SafeMILHandle /* IWICBitmapPalette */ bitmapPalette,
// double alphaThreshold,
// WICPaletteType paletteTranslate
// );
// }
// internal static class IWICColorContext
// {
// internal enum WICColorContextType : uint
// {
// WICColorContextUninitialized = 0,
// WICColorContextProfile = 1,
// WICColorContextExifColorSpace = 2
// };
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICColorContext_InitializeFromMemory_Proxy")]
// internal static extern int /* HRESULT */ InitializeFromMemory(
// SafeMILHandle THIS_PTR,
// byte[] pbBuffer,
// uint cbBufferSize
// );
// // We import the following functions from MilCore because WindowsCodecs does not have
// // them built-in
// [DllImport(DllImport.MilCore, EntryPoint = "IWICColorContext_GetProfileBytes_Proxy")]
// internal static extern int /* HRESULT */ GetProfileBytes(
// SafeMILHandle THIS_PTR,
// uint cbBuffer,
// /* inout */ byte[] pbBuffer,
// out uint pcbActual
// );
// [DllImport(DllImport.MilCore, EntryPoint = "IWICColorContext_GetType_Proxy")]
// internal static extern int /* HRESULT */ GetType(
// SafeMILHandle THIS_PTR,
// out WICColorContextType pType
// );
// [DllImport(DllImport.MilCore, EntryPoint = "IWICColorContext_GetExifColorSpace_Proxy")]
// internal static extern int /* HRESULT */ GetExifColorSpace(
// SafeMILHandle THIS_PTR,
// out uint pValue
// );
// }
// internal static class WICColorTransform
// {
// [DllImport(DllImport.WindowsCodecsExt, EntryPoint = "IWICColorTransform_Initialize_Proxy")]
// internal static extern int /* HRESULT */ Initialize(
// System.Windows.Media.SafeMILHandle /* IWICColorTransform */ THIS_PTR,
// System.Windows.Media.SafeMILHandle /* IWICBitmapSource */ source,
// System.Windows.Media.SafeMILHandle /* IWICColorContext */ pIContextSource,
// System.Windows.Media.SafeMILHandle /* IWICColorContext */ pIContextDest,
// ref Guid pixelFmtDest
// );
// }
// internal static class WICBitmap
// {
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICBitmap_Lock_Proxy")]
// internal static extern int /* HRESULT */ Lock(
// System.Windows.Media.SafeMILHandle /* IWICBitmap */ THIS_PTR,
// ref Int32Rect prcLock,
// LockFlags flags,
// out SafeMILHandle /* IWICBitmapLock* */ ppILock);
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICBitmap_SetResolution_Proxy")]
// internal static extern int /* HRESULT */ SetResolution(
// System.Windows.Media.SafeMILHandle /* IWICBitmap */ THIS_PTR,
// double dpiX,
// double dpiY);
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICBitmap_SetPalette_Proxy")]
// internal static extern int /* HRESULT */ SetPalette(
// System.Windows.Media.SafeMILHandle /* IWICBitmap */ THIS_PTR,
// System.Windows.Media.SafeMILHandle /* IMILPalette */ pIPalette);
// }
// internal static class WICBitmapLock
// {
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICBitmapLock_GetStride_Proxy")]
// internal static extern int /* HRESULT */ GetStride(
// SafeMILHandle /* IWICBitmapLock */ pILock,
// ref uint pcbStride
// );
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "IWICBitmapLock_GetDataPointer_STA_Proxy")]
// internal static extern int /* HRESULT */ GetDataPointer(
// SafeMILHandle /* IWICBitmapLock */ pILock,
// ref uint pcbBufferSize,
// ref IntPtr ppbData
// );
// }
// internal static class WICCodec
// {
// // When updating this value be sure to update milrender.h's version
// // Reserve the number by editing and resubmitting SDKVersion.txt
// internal const int WINCODEC_SDK_VERSION = 0x0236;
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "WICCreateImagingFactory_Proxy")]
// internal static extern int CreateImagingFactory(
// UInt32 SDKVersion,
// out IntPtr ppICodecFactory
// );
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "WICConvertBitmapSource")]
// internal static extern int /* HRESULT */ WICConvertBitmapSource(
// ref Guid dstPixelFormatGuid,
// SafeMILHandle /* IWICBitmapSource */ pISrc,
// out BitmapSourceSafeMILHandle /* IWICBitmapSource* */ ppIDst);
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "WICSetEncoderFormat_Proxy")]
// internal static extern int /* HRESULT */ WICSetEncoderFormat(
// SafeMILHandle /* IWICBitmapSource */ pSourceIn,
// SafeMILHandle /* IMILPalette */ pIPalette,
// SafeMILHandle /* IWICBitmapFrameEncode* */ pIFrameEncode,
// out SafeMILHandle /* IWICBitmapSource** */ ppSourceOut);
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "WICMapGuidToShortName")]//CASRemoval:
// internal static extern int /* HRESULT */ WICMapGuidToShortName(
// ref Guid guid,
// uint cchName,
// [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder wzName,
// ref uint pcchActual);
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "WICMapShortNameToGuid")]//CASRemoval:
// internal static extern int /* HRESULT */ WICMapShortNameToGuid(
// [MarshalAs(UnmanagedType.LPWStr)] String wzName,
// ref Guid guid);
// [DllImport(DllImport.WindowsCodecsExt, EntryPoint = "WICCreateColorTransform_Proxy")]
// internal static extern int /* HRESULT */ CreateColorTransform(
// out BitmapSourceSafeMILHandle /* IWICColorTransform */ ppWICColorTransform);
// [DllImport(DllImport.WindowsCodecs, EntryPoint = "WICCreateColorContext_Proxy")]
// internal static extern int /* HRESULT */ CreateColorContext(
// IntPtr pICodecFactory,
// out System.Windows.Media.SafeMILHandle /* IWICColorContext */ ppColorContext);
// [DllImport("ole32.dll")]
// internal static extern int /* HRESULT */ CoInitialize(
// IntPtr reserved);
// [DllImport("ole32.dll")]
// internal static extern void CoUninitialize();
// }
// internal static class Mscms
// {
// [DllImport(DllImport.Mscms, EntryPoint = "CreateMultiProfileTransform")]
// internal static extern ColorTransformHandle /* HTRANSFORM */ CreateMultiProfileTransform(IntPtr[] /* PHPROFILE */ pahProfiles, UInt32 nProfiles, UInt32[] padwIntent, UInt32 nIntents, UInt32 dwFlags, UInt32 indexPreferredCMM);
// [DllImport(DllImport.Mscms, EntryPoint = "DeleteColorTransform", SetLastError = true)]
// internal static extern bool DeleteColorTransform(IntPtr /* HTRANSFORM */ hColorTransform);
// [DllImport(DllImport.Mscms, EntryPoint = "TranslateColors")]
// internal static extern int /* HRESULT */ TranslateColors(ColorTransformHandle /* HTRANSFORM */ hColorTransform, IntPtr paInputColors, UInt32 nColors, UInt32 ctInput, IntPtr paOutputColors, UInt32 ctOutput);
// [DllImport(DllImport.Mscms, EntryPoint = "OpenColorProfile")]
// internal static extern SafeProfileHandle /* HANDLE */ OpenColorProfile(ref MS.Win32.UnsafeNativeMethods.PROFILE pProfile, UInt32 dwDesiredAccess, UInt32 dwShareMode, UInt32 dwCreationMode);
// [DllImport(DllImport.Mscms, EntryPoint = "CloseColorProfile", SetLastError = true)]
// internal static extern bool CloseColorProfile(IntPtr /* HANDLE */ phProfile);
// [DllImport(DllImport.Mscms, EntryPoint = "GetColorProfileHeader", SetLastError = true)]
// internal static extern bool GetColorProfileHeader(SafeProfileHandle /* HANDLE */ phProfile, out MS.Win32.UnsafeNativeMethods.PROFILEHEADER pHeader);
// [DllImport(DllImport.Mscms, CharSet = CharSet.Auto, BestFitMapping = false)]
// internal static extern int /* HRESULT */ GetColorDirectory(IntPtr pMachineName, StringBuilder pBuffer, out uint pdwSize);
// [DllImport(DllImport.Mscms, CharSet = CharSet.Auto, BestFitMapping = false)]
// internal static extern int /* HRESULT */ GetStandardColorSpaceProfile(IntPtr pMachineName, uint dwProfileID, StringBuilder pProfileName, out uint pdwSize);
// [DllImport(DllImport.Mscms, EntryPoint = "GetColorProfileFromHandle", SetLastError = true)]
// internal static extern bool GetColorProfileFromHandle(SafeProfileHandle /* HANDLE */ hProfile, byte[] pBuffer, ref uint pdwSize);
// }
// internal static class MILFactory2
// {
// [DllImport(DllImport.MilCore, EntryPoint = "MILCreateFactory")]
// internal static extern int CreateFactory(
// out IntPtr ppIFactory,
// UInt32 SDKVersion
// );
// [DllImport(DllImport.MilCore, EntryPoint = "MILFactoryCreateMediaPlayer")]
// internal static extern int /*HRESULT*/ CreateMediaPlayer(
// IntPtr THIS_PTR,
// SafeMILHandle /* CEventProxy */ pEventProxy,
// bool canOpenAllMedia,
// out SafeMediaHandle /* IMILMedia */ ppMedia);
// [DllImport(DllImport.MilCore, EntryPoint = "MILFactoryCreateBitmapRenderTarget")]
// internal static extern int /* HRESULT */ CreateBitmapRenderTarget(
// IntPtr THIS_PTR,
// UInt32 width,
// UInt32 height,
// PixelFormatEnum pixelFormatEnum,
// float dpiX,
// float dpiY,
// MILRTInitializationFlags dwFlags,
// out SafeMILHandle /* IMILRenderTargetBitmap */ ppIRenderTargetBitmap);
// [DllImport(DllImport.MilCore, EntryPoint = "MILFactoryCreateSWRenderTargetForBitmap")]
// internal static extern int /* HRESULT */ CreateBitmapRenderTargetForBitmap(
// IntPtr THIS_PTR,
// BitmapSourceSafeMILHandle /* IWICBitmap */ pIBitmap,
// out SafeMILHandle /* IMILRenderTargetBitmap */ ppIRenderTargetBitmap);
// }
// internal static class InteropDeviceBitmap
// {
// internal delegate void FrontBufferAvailableCallback(bool lost, uint version);
// [DllImport(DllImport.MilCore, EntryPoint = "InteropDeviceBitmap_Create")]
// internal static extern int Create(
// IntPtr d3dResource,
// double dpiX,
// double dpiY,
// uint version,
// FrontBufferAvailableCallback pfnCallback,
// bool isSoftwareFallbackEnabled,
// out SafeMILHandle ppInteropDeviceBitmap,
// out uint pixelWidth,
// out uint pixelHeight
// );
// [DllImport(DllImport.MilCore, EntryPoint = "InteropDeviceBitmap_Detach")]
// internal static extern void Detach(
// SafeMILHandle pInteropDeviceBitmap
// );
// [DllImport(DllImport.MilCore, EntryPoint = "InteropDeviceBitmap_AddDirtyRect")]
// internal static extern int AddDirtyRect(
// int x,
// int y,
// int w,
// int h,
// SafeMILHandle pInteropDeviceBitmap
// );
// [DllImport(DllImport.MilCore, EntryPoint = "InteropDeviceBitmap_GetAsSoftwareBitmap")]
// internal static extern int GetAsSoftwareBitmap(SafeMILHandle pInteropDeviceBitmap, out BitmapSourceSafeMILHandle pIWICBitmapSource);
// }
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Baseline;
using Baseline.ImTools;
using Marten.Events.Aggregation;
using Marten.Events.Daemon;
using Marten.Exceptions;
namespace Marten.Events.Projections
{
/// <summary>
/// Used to register projections with Marten
/// </summary>
public class ProjectionOptions : DaemonSettings
{
private readonly StoreOptions _options;
private readonly Dictionary<Type, object> _liveAggregateSources = new Dictionary<Type, object>();
private ImHashMap<Type, object> _liveAggregators = ImHashMap<Type, object>.Empty;
private Lazy<Dictionary<string, AsyncProjectionShard>> _asyncShards;
internal ProjectionOptions(StoreOptions options)
{
_options = options;
}
internal IList<ProjectionSource> All { get; } = new List<ProjectionSource>();
internal IList<AsyncProjectionShard> BuildAllShards(DocumentStore store)
{
return All.SelectMany(x => x.AsyncProjectionShards(store)).ToList();
}
internal bool HasAnyAsyncProjections()
{
return All.Any(x => x.Lifecycle == ProjectionLifecycle.Async);
}
internal IEnumerable<Type> AllAggregateTypes()
{
foreach (var kv in _liveAggregators.Enumerate())
{
yield return kv.Key;
}
foreach (var projection in All.OfType<IAggregateProjection>())
{
yield return projection.AggregateType;
}
}
internal IProjection[] BuildInlineProjections(DocumentStore store)
{
var inlineSources = All.Where(x => x.Lifecycle == ProjectionLifecycle.Inline).ToArray();
return inlineSources.Select(x =>
{
try
{
return x.Build(store);
}
catch (Exception e)
{
Console.WriteLine("Error trying to build an IProjection for projection " + x.ProjectionName);
Console.WriteLine(e.ToString());
throw;
}
}).ToArray();
}
/// <summary>
/// Register a projection to the Marten configuration
/// </summary>
/// <param name="projection">Value values are Inline/Async, The default is Inline</param>
/// <param name="lifecycle"></param>
/// <param name="projectionName">Overwrite the named identity of this projection. This is valuable if using the projection asynchonously</param>
/// <param name="asyncConfiguration">Optional configuration including teardown instructions for the usage of this projection within the async projection daempon</param>
public void Add(IProjection projection, ProjectionLifecycle lifecycle = ProjectionLifecycle.Inline,
string projectionName = null, Action<AsyncOptions> asyncConfiguration = null)
{
if (lifecycle == ProjectionLifecycle.Live)
{
throw new ArgumentOutOfRangeException(nameof(lifecycle),
$"{nameof(ProjectionLifecycle.Live)} cannot be used for IProjection");
}
var wrapper = new ProjectionWrapper(projection, lifecycle);
if (projectionName.IsNotEmpty())
{
wrapper.ProjectionName = projectionName;
}
asyncConfiguration?.Invoke(wrapper.Options);
All.Add(wrapper);
}
/// <summary>
/// Add a projection that will be executed inline
/// </summary>
/// <param name="projection"></param>
/// <param name="lifecycle">Optionally override the lifecycle of this projection. The default is Inline</param>
public void Add(EventProjection projection, ProjectionLifecycle? lifecycle = null)
{
if (lifecycle.HasValue)
{
projection.Lifecycle = lifecycle.Value;
}
projection.AssertValidity();
All.Add(projection);
}
/// <summary>
/// Use a "self-aggregating" aggregate of type.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="lifecycle">Override the aggregate lifecycle. The default is Inline</param>
/// <returns>The extended storage configuration for document T</returns>
public MartenRegistry.DocumentMappingExpression<T> SelfAggregate<T>(ProjectionLifecycle? lifecycle = null)
{
// Make sure there's a DocumentMapping for the aggregate
var expression = _options.Schema.For<T>();
var source = new AggregateProjection<T>()
{
Lifecycle = lifecycle ?? ProjectionLifecycle.Inline
};
source.AssertValidity();
All.Add(source);
return expression;
}
/// <summary>
/// Register an aggregate projection that should be evaluated inline
/// </summary>
/// <typeparam name="TProjection">Projection type</typeparam>
/// <param name="lifecycle">Optionally override the ProjectionLifecycle</param>
/// <returns>The extended storage configuration for document T</returns>
public void Add<TProjection>(ProjectionLifecycle? lifecycle = null) where TProjection: ProjectionSource, new()
{
var projection = new TProjection();
if (lifecycle.HasValue)
{
projection.Lifecycle = lifecycle.Value;
}
projection.AssertValidity();
All.Add(projection);
}
/// <summary>
/// Register an aggregate projection that should be evaluated inline
/// </summary>
/// <param name="projection"></param>
/// <typeparam name="T"></typeparam>
/// <param name="lifecycle">Optionally override the ProjectionLifecycle</param>
/// <returns>The extended storage configuration for document T</returns>
public void Add<T>(AggregateProjection<T> projection, ProjectionLifecycle? lifecycle = null)
{
if (lifecycle.HasValue)
{
projection.Lifecycle = lifecycle.Value;
}
projection.AssertValidity();
All.Add(projection);
}
internal bool Any()
{
return All.Any();
}
internal ILiveAggregator<T> AggregatorFor<T>() where T : class
{
if (_liveAggregators.TryFind(typeof(T), out var aggregator))
{
return (ILiveAggregator<T>) aggregator;
}
var source = tryFindProjectionSourceForAggregateType<T>();
source.AssertValidity();
aggregator = source.As<ILiveAggregatorSource<T>>().Build(_options);
_liveAggregators = _liveAggregators.AddOrUpdate(typeof(T), aggregator);
return (ILiveAggregator<T>) aggregator;
}
private AggregateProjection<T> tryFindProjectionSourceForAggregateType<T>() where T : class
{
var candidate = All.OfType<AggregateProjection<T>>().FirstOrDefault();
if (candidate != null)
{
return candidate;
}
if (!_liveAggregateSources.TryGetValue(typeof(T), out var source))
{
return new AggregateProjection<T>();
}
return source as AggregateProjection<T>;
}
internal void AssertValidity(DocumentStore store)
{
var duplicateNames = All
.GroupBy(x => x.ProjectionName)
.Where(x => x.Count() > 1)
.Select(group => $"Duplicate projection name '{group.Key}': {group.Select(x => x.ToString()).Join(", ")}")
.ToArray();
if (duplicateNames.Any())
{
throw new InvalidOperationException(duplicateNames.Join("; "));
}
var messages = All.Concat(_liveAggregateSources.Values)
.OfType<ProjectionSource>()
.Distinct()
.SelectMany(x => x.ValidateConfiguration(_options))
.ToArray();
_asyncShards = new Lazy<Dictionary<string, AsyncProjectionShard>>(() =>
{
return All
.Where(x => x.Lifecycle == ProjectionLifecycle.Async)
.SelectMany(x => x.AsyncProjectionShards(store))
.ToDictionary(x => x.Name.Identity);
});
if (messages.Any())
{
throw new InvalidProjectionException(messages);
}
}
internal IReadOnlyList<AsyncProjectionShard> AllShards()
{
return _asyncShards.Value.Values.ToList();
}
internal bool TryFindAsyncShard(string projectionOrShardName, out AsyncProjectionShard shard)
{
return _asyncShards.Value.TryGetValue(projectionOrShardName, out shard);
}
internal bool TryFindProjection(string projectionName, out ProjectionSource source)
{
source = All.FirstOrDefault(x => x.ProjectionName.EqualsIgnoreCase(projectionName));
return source != null;
}
internal string[] AllProjectionNames()
{
return All.Select(x => $"'{x.ProjectionName}'").ToArray();
}
internal IEnumerable<Type> AllPublishedTypes()
{
return All.OfType<IProjectionSource>().SelectMany(x => x.PublishedTypes()).Distinct();
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.