context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
#region PDFsharp - A .NET library for processing PDF
//
// Authors:
// Stefan Lange
//
// Copyright (c) 2005-2016 empira Software GmbH, Cologne Area (Germany)
//
// http://www.pdfsharp.com
// http://sourceforge.net/projects/pdfsharp
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using PdfSharp.Fonts;
#if CORE || GDI
using System.Drawing;
using System.Drawing.Drawing2D;
using GdiFontFamily = System.Drawing.FontFamily;
using GdiFont = System.Drawing.Font;
using GdiFontStyle = System.Drawing.FontStyle;
using GdiPrivateFontCollection = System.Drawing.Text.PrivateFontCollection;
#endif
#if WPF
using System.Windows.Markup;
using WpfFonts = System.Windows.Media.Fonts;
using WpfFontFamily = System.Windows.Media.FontFamily;
using WpfTypeface = System.Windows.Media.Typeface;
using WpfGlyphTypeface = System.Windows.Media.GlyphTypeface;
#endif
namespace PdfSharp.Drawing
{
#if true
///<summary>
/// Makes fonts that are not installed on the system available within the current application domain.<br/>
/// In Silverlight required for all fonts used in PDF documents.
/// </summary>
public sealed class XPrivateFontCollection
{
// This one is global and can only grow. It is not possible to remove fonts that have been added.
/// <summary>
/// Initializes a new instance of the <see cref="XPrivateFontCollection"/> class.
/// </summary>
XPrivateFontCollection()
{
// HACK: Use one global PrivateFontCollection in GDI+
}
#if GDI
//internal PrivateFontCollection PrivateFontCollection
//{
// get { return privateFontCollection; }
// set { privateFontCollection = value; }
//}
GdiPrivateFontCollection GetPrivateFontCollection()
{
// Create only if really needed.
if (_privateFontCollection == null)
_privateFontCollection = new GdiPrivateFontCollection();
return _privateFontCollection;
}
// PrivateFontCollection of GDI+
private GdiPrivateFontCollection _privateFontCollection;
#endif
/// <summary>
/// Gets the global font collection.
/// </summary>
internal static XPrivateFontCollection Singleton
{
get { return _singleton; }
}
internal static XPrivateFontCollection _singleton = new XPrivateFontCollection();
#if GDI
/// <summary>
/// Adds the font data to the font collections.
/// </summary>
[Obsolete("Use Add(Stream stream)")]
public void AddFont(byte[] data, string familyName)
{
if (String.IsNullOrEmpty(familyName))
throw new ArgumentNullException("familyName");
//if (glyphTypeface == null)
// throw new ArgumentNullException("glyphTypeface");
// Add to GDI+ PrivateFontCollection
int length = data.Length;
// Copy data without unsafe code
IntPtr ip = Marshal.AllocCoTaskMem(length);
Marshal.Copy(data, 0, ip, length);
GetPrivateFontCollection().AddMemoryFont(ip, length);
// Do not free the memory here, AddMemoryFont stores a pointer, not a copy!
//Marshal.FreeCoTaskMem(ip);
//privateFonts.Add(glyphTypeface);
}
#endif
/// <summary>
/// Adds the specified font data to the global PrivateFontCollection.
/// Family name and style are automatically retrieved from the font.
/// </summary>
[Obsolete("Use Add(Stream stream)")]
public static void AddFont(string filename)
{
throw new NotImplementedException();
//XGlyphTypeface glyphTypeface = new XGlyphTypeface(filename);
//Global.AddGlyphTypeface(glyphTypeface);
}
#if GDI
/// <summary>
/// Adds the specified font data to the global PrivateFontCollection.
/// Family name and style are automatically retrieved from the font.
/// </summary>
[Obsolete("Use Add(stream).")]
public static void AddFont(Stream stream)
{
Add(stream);
}
/// <summary>
/// Adds the specified font data to the global PrivateFontCollection.
/// Family name and style are automatically retrieved from the font.
/// </summary>
public static void Add(Stream stream)
{
int length = (int)stream.Length;
byte[] bytes = new byte[length];
stream.Read(bytes, 0, length);
Add(bytes);
}
/// <summary>
/// Adds the specified font data to the global PrivateFontCollection.
/// Family name and style are automatically retrieved from the font.
/// </summary>
public static void Add(byte[] font)
{
IntPtr unmanagedPointer = Marshal.AllocCoTaskMem(font.Length);
Marshal.Copy(font, 0, unmanagedPointer, font.Length);
Singleton.GetPrivateFontCollection().AddMemoryFont(unmanagedPointer, font.Length);
// Do not free the memory here, AddMemoryFont stores a pointer, not a copy!
//Marshal.FreeCoTaskMem(ip);
XFontSource fontSource = XFontSource.GetOrCreateFrom(font);
string familyName = fontSource.FontName;
if (familyName.EndsWith(" Regular", StringComparison.OrdinalIgnoreCase))
familyName = familyName.Substring(0, familyName.Length - 8);
bool bold = fontSource.Fontface.os2.IsBold;
bool italic = fontSource.Fontface.os2.IsItalic;
IncompetentlyMakeAHackToFixAProblemYouWoldNeverHaveIfYouUseAFontResolver(fontSource, ref familyName, ref bold, ref italic);
string key = MakeKey(familyName, bold, italic);
Singleton._fontSources.Add(key, fontSource);
string typefaceKey = XGlyphTypeface.ComputeKey(familyName, bold, italic);
FontFactory.CacheExistingFontSourceWithNewTypefaceKey(typefaceKey, fontSource);
}
static void IncompetentlyMakeAHackToFixAProblemYouWoldNeverHaveIfYouUseAFontResolver(XFontSource fontSource,
ref string familyName, ref bool bold, ref bool italic)
{
const string regularSuffix = " Regular";
const string boldSuffix = " Bold";
const string italicSuffix = " Italic";
const string boldItalicSuffix = " Bold Italic";
const string italicBoldSuffix = " Italic Bold";
if (familyName.EndsWith(regularSuffix, StringComparison.OrdinalIgnoreCase))
{
familyName = familyName.Substring(0, familyName.Length - regularSuffix.Length);
Debug.Assert(!bold && !italic);
bold = italic = false;
}
else if (familyName.EndsWith(boldItalicSuffix, StringComparison.OrdinalIgnoreCase) || familyName.EndsWith(italicBoldSuffix, StringComparison.OrdinalIgnoreCase))
{
familyName = familyName.Substring(0, familyName.Length - boldItalicSuffix.Length);
Debug.Assert(bold && italic);
bold = italic = true;
}
else if (familyName.EndsWith(boldSuffix, StringComparison.OrdinalIgnoreCase))
{
familyName = familyName.Substring(0, familyName.Length - boldSuffix.Length);
Debug.Assert(bold && !italic);
bold = true;
italic = false;
}
else if (familyName.EndsWith(italicSuffix, StringComparison.OrdinalIgnoreCase))
{
familyName = familyName.Substring(0, familyName.Length - italicSuffix.Length);
Debug.Assert(!bold && italic);
bold = false;
italic = true;
}
else
{
Debug.Assert(!bold && !italic);
bold = false;
italic = false;
}
}
#endif
/// <summary>
/// Adds the specified font data to the global PrivateFontCollection.
/// Family name and style are automatically retrieved from the font.
/// </summary>
[Obsolete("Use Add(Stream stream)")]
public static void AddFont(Stream stream, string facename)
{
throw new NotImplementedException();
//XGlyphTypeface glyphTypeface = new XGlyphTypeface(stream, facename);
//Global.AddGlyphTypeface(glyphTypeface);
}
// /// <summary>
// /// Adds XGlyphTypeface to internal collection.
// /// Family name and style are automatically retrieved from the font.
// /// </summary>
// void AddGlyphTypeface(XGlyphTypeface glyphTypeface)
// {
// string name = MakeName(glyphTypeface);
// if (_typefaces.ContainsKey(name))
// throw new InvalidOperationException(PSSR.FontAlreadyAdded(glyphTypeface.DisplayName));
// _typefaces.Add(name, glyphTypeface);
// //Debug.WriteLine("Font added: " + name);
//#if GDI
// // Add to GDI+ PrivateFontCollection singleton.
// byte[] data = glyphTypeface.Fontface.FontSource.Bytes;
// int length = data.Length;
// IntPtr ip = Marshal.AllocCoTaskMem(length);
// Marshal.Copy(data, 0, ip, length);
// _privateFontCollection.AddMemoryFont(ip, length);
// // Do not free the memory here, AddMemoryFont stores a pointer, not a copy!
// // Marshal.FreeCoTaskMem(ip);
//#endif
//#if WPF
//#endif
// }
#if WPF
/// <summary>
/// Initializes a new instance of the FontFamily class from the specified font family name and an optional base uniform resource identifier (URI) value.
/// Sample: Add(new Uri("pack://application:,,,/"), "./myFonts/#FontFamilyName");)
/// </summary>
/// <param name="baseUri">Specifies the base URI that is used to resolve familyName.</param>
/// <param name="familyName">The family name or names that comprise the new FontFamily. Multiple family names should be separated by commas.</param>
public static void Add(Uri baseUri, string familyName)
{
Uri uri = new Uri("pack://application:,,,/");
// TODO: What means 'Multiple family names should be separated by commas.'?
// does not work
if (String.IsNullOrEmpty(familyName))
throw new ArgumentNullException("familyName");
if (familyName.Contains(","))
throw new NotImplementedException("Only one family name is supported.");
// Family name starts right of '#'.
int idxHash = familyName.IndexOf('#');
if (idxHash < 0)
throw new ArgumentException("Family name must contain a '#'. Example './#MyFontFamilyName'", "familyName");
string key = familyName.Substring(idxHash + 1);
if (String.IsNullOrEmpty(key))
throw new ArgumentException("familyName has invalid format.");
if (Singleton._fontFamilies.ContainsKey(key))
throw new ArgumentException("An entry with the specified family name already exists.");
#if !SILVERLIGHT
#if DEBUG_
foreach (WpfFontFamily fontFamily1 in WpfFonts.GetFontFamilies(baseUri, familyName))
{
ICollection<WpfTypeface> wpfTypefaces = fontFamily1.GetTypefaces();
wpfTypefaces.GetType();
}
#endif
// Create WPF font family.
WpfFontFamily fontFamily = new WpfFontFamily(baseUri, familyName);
//System.Windows.Media.FontFamily x;
// Required for new Uri("pack://application:,,,/")
// ReSharper disable once ObjectCreationAsStatement
// new System.Windows.Application();
#else
System.Windows.Media.FontFamily fontFamily = new System.Windows.Media.FontFamily(familyName);
#endif
// Check whether font data really exists
#if DEBUG && !SILVERLIGHT
ICollection<WpfTypeface> list = fontFamily.GetTypefaces();
foreach (WpfTypeface typeFace in list)
{
Debug.WriteLine(String.Format("{0}, {1}, {2}, {3}, {4}", familyName, typeFace.FaceNames[FontHelper.XmlLanguageEnUs], typeFace.Style, typeFace.Weight, typeFace.Stretch));
WpfGlyphTypeface glyphTypeface;
if (!typeFace.TryGetGlyphTypeface(out glyphTypeface))
{
Debug.WriteLine(" Glyph typeface does not exists.");
//throw new ArgumentException("Font with the specified family name does not exist.");
}
}
#endif
Singleton._fontFamilies.Add(key, fontFamily);
}
#endif
//internal static XGlyphTypeface TryGetXGlyphTypeface(string familyName, XFontStyle style)
//{
// string name = MakeName(familyName, style);
// XGlyphTypeface typeface;
// _global._typefaces.TryGetValue(name, out typeface);
// return typeface;
//}
#if GDI
internal static GdiFont TryCreateFont(string name, double size, GdiFontStyle style, out XFontSource fontSource)
{
fontSource = null;
try
{
GdiPrivateFontCollection pfc = Singleton._privateFontCollection;
if (pfc == null)
return null;
#if true
string key = MakeKey(name, (XFontStyle)style);
if (Singleton._fontSources.TryGetValue(key, out fontSource))
{
GdiFont font = new GdiFont(name, (float)size, style, GraphicsUnit.World);
#if DEBUG_
Debug.Assert(StringComparer.OrdinalIgnoreCase.Compare(name, font.Name) == 0);
Debug.Assert(font.Bold == ((style & GdiFontStyle.Bold) != 0));
Debug.Assert(font.Italic == ((style & GdiFontStyle.Italic) != 0));
#endif
return font;
}
return null;
#else
foreach (GdiFontFamily family in pfc.Families)
{
if (string.Compare(family.Name, name, StringComparison.OrdinalIgnoreCase) == 0)
{
GdiFont font = new GdiFont(family, (float)size, style, GraphicsUnit.World);
if (string.Compare(font.Name, name, StringComparison.OrdinalIgnoreCase) != 0)
{
// Style simulation is not implemented in GDI+.
// Use WPF build.
}
return font;
}
}
#endif
}
catch (Exception ex)
{
// Ignore exception and return null.
Debug.WriteLine(ex.ToString());
}
return null;
}
#endif
#if WPF && !SILVERLIGHT
internal static WpfTypeface TryCreateTypeface(string name, XFontStyle style, out WpfFontFamily fontFamily)
{
if (Singleton._fontFamilies.TryGetValue(name, out fontFamily))
{
WpfTypeface typeface = FontHelper.CreateTypeface(fontFamily, style);
return typeface;
}
return null;
}
#endif
static string MakeKey(string familyName, XFontStyle style)
{
return MakeKey(familyName, (style & XFontStyle.Bold) != 0, (style & XFontStyle.Italic) != 0);
}
static string MakeKey(string familyName, bool bold, bool italic)
{
return familyName + "#" + (bold ? "b" : "") + (italic ? "i" : "");
}
readonly Dictionary<string, XGlyphTypeface> _typefaces = new Dictionary<string, XGlyphTypeface>();
#if GDI
//List<XGlyphTypeface> privateFonts = new List<XGlyphTypeface>();
readonly Dictionary<string, XFontSource> _fontSources = new Dictionary<string, XFontSource>(StringComparer.OrdinalIgnoreCase);
#endif
#if WPF
readonly Dictionary<string, WpfFontFamily> _fontFamilies = new Dictionary<string, WpfFontFamily>(StringComparer.OrdinalIgnoreCase);
#endif
}
#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 BinaryNullableLessThanOrEqualTests
{
#region Test methods
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableByteLessThanOrEqualTest(bool useInterpreter)
{
byte?[] array = new byte?[] { null, 0, 1, byte.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableByteLessThanOrEqual(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableCharLessThanOrEqualTest(bool useInterpreter)
{
char?[] array = new char?[] { null, '\0', '\b', 'A', '\uffff' };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableCharLessThanOrEqual(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableDecimalLessThanOrEqualTest(bool useInterpreter)
{
decimal?[] array = new decimal?[] { null, decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableDecimalLessThanOrEqual(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableDoubleLessThanOrEqualTest(bool useInterpreter)
{
double?[] array = new double?[] { null, 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableDoubleLessThanOrEqual(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableFloatLessThanOrEqualTest(bool useInterpreter)
{
float?[] array = new float?[] { null, 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableFloatLessThanOrEqual(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableIntLessThanOrEqualTest(bool useInterpreter)
{
int?[] array = new int?[] { null, 0, 1, -1, int.MinValue, int.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableIntLessThanOrEqual(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableLongLessThanOrEqualTest(bool useInterpreter)
{
long?[] array = new long?[] { null, 0, 1, -1, long.MinValue, long.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableLongLessThanOrEqual(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableSByteLessThanOrEqualTest(bool useInterpreter)
{
sbyte?[] array = new sbyte?[] { null, 0, 1, -1, sbyte.MinValue, sbyte.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableSByteLessThanOrEqual(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableShortLessThanOrEqualTest(bool useInterpreter)
{
short?[] array = new short?[] { null, 0, 1, -1, short.MinValue, short.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableShortLessThanOrEqual(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableUIntLessThanOrEqualTest(bool useInterpreter)
{
uint?[] array = new uint?[] { null, 0, 1, uint.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableUIntLessThanOrEqual(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableULongLessThanOrEqualTest(bool useInterpreter)
{
ulong?[] array = new ulong?[] { null, 0, 1, ulong.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableULongLessThanOrEqual(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableUShortLessThanOrEqualTest(bool useInterpreter)
{
ushort?[] array = new ushort?[] { null, 0, 1, ushort.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableUShortLessThanOrEqual(array[i], array[j], useInterpreter);
}
}
}
#endregion
#region Test verifiers
private static void VerifyNullableByteLessThanOrEqual(byte? a, byte? b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.LessThanOrEqual(
Expression.Constant(a, typeof(byte?)),
Expression.Constant(b, typeof(byte?))),
Enumerable.Empty<ParameterExpression>());
Func<bool> f = e.Compile(useInterpreter);
Assert.Equal(a <= b, f());
}
private static void VerifyNullableCharLessThanOrEqual(char? a, char? b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.LessThanOrEqual(
Expression.Constant(a, typeof(char?)),
Expression.Constant(b, typeof(char?))),
Enumerable.Empty<ParameterExpression>());
Func<bool> f = e.Compile(useInterpreter);
Assert.Equal(a <= b, f());
}
private static void VerifyNullableDecimalLessThanOrEqual(decimal? a, decimal? b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.LessThanOrEqual(
Expression.Constant(a, typeof(decimal?)),
Expression.Constant(b, typeof(decimal?))),
Enumerable.Empty<ParameterExpression>());
Func<bool> f = e.Compile(useInterpreter);
Assert.Equal(a <= b, f());
}
private static void VerifyNullableDoubleLessThanOrEqual(double? a, double? b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.LessThanOrEqual(
Expression.Constant(a, typeof(double?)),
Expression.Constant(b, typeof(double?))),
Enumerable.Empty<ParameterExpression>());
Func<bool> f = e.Compile(useInterpreter);
Assert.Equal(a <= b, f());
}
private static void VerifyNullableFloatLessThanOrEqual(float? a, float? b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.LessThanOrEqual(
Expression.Constant(a, typeof(float?)),
Expression.Constant(b, typeof(float?))),
Enumerable.Empty<ParameterExpression>());
Func<bool> f = e.Compile(useInterpreter);
Assert.Equal(a <= b, f());
}
private static void VerifyNullableIntLessThanOrEqual(int? a, int? b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.LessThanOrEqual(
Expression.Constant(a, typeof(int?)),
Expression.Constant(b, typeof(int?))),
Enumerable.Empty<ParameterExpression>());
Func<bool> f = e.Compile(useInterpreter);
Assert.Equal(a <= b, f());
}
private static void VerifyNullableLongLessThanOrEqual(long? a, long? b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.LessThanOrEqual(
Expression.Constant(a, typeof(long?)),
Expression.Constant(b, typeof(long?))),
Enumerable.Empty<ParameterExpression>());
Func<bool> f = e.Compile(useInterpreter);
Assert.Equal(a <= b, f());
}
private static void VerifyNullableSByteLessThanOrEqual(sbyte? a, sbyte? b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.LessThanOrEqual(
Expression.Constant(a, typeof(sbyte?)),
Expression.Constant(b, typeof(sbyte?))),
Enumerable.Empty<ParameterExpression>());
Func<bool> f = e.Compile(useInterpreter);
Assert.Equal(a <= b, f());
}
private static void VerifyNullableShortLessThanOrEqual(short? a, short? b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.LessThanOrEqual(
Expression.Constant(a, typeof(short?)),
Expression.Constant(b, typeof(short?))),
Enumerable.Empty<ParameterExpression>());
Func<bool> f = e.Compile(useInterpreter);
Assert.Equal(a <= b, f());
}
private static void VerifyNullableUIntLessThanOrEqual(uint? a, uint? b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.LessThanOrEqual(
Expression.Constant(a, typeof(uint?)),
Expression.Constant(b, typeof(uint?))),
Enumerable.Empty<ParameterExpression>());
Func<bool> f = e.Compile(useInterpreter);
Assert.Equal(a <= b, f());
}
private static void VerifyNullableULongLessThanOrEqual(ulong? a, ulong? b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.LessThanOrEqual(
Expression.Constant(a, typeof(ulong?)),
Expression.Constant(b, typeof(ulong?))),
Enumerable.Empty<ParameterExpression>());
Func<bool> f = e.Compile(useInterpreter);
Assert.Equal(a <= b, f());
}
private static void VerifyNullableUShortLessThanOrEqual(ushort? a, ushort? b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.LessThanOrEqual(
Expression.Constant(a, typeof(ushort?)),
Expression.Constant(b, typeof(ushort?))),
Enumerable.Empty<ParameterExpression>());
Func<bool> f = e.Compile(useInterpreter);
Assert.Equal(a <= b, f());
}
#endregion
}
}
| |
using System;
using System.Windows.Forms;
using MouseKeyboardActivityMonitor.WinApi;
namespace MouseKeyboardActivityMonitor.Demo
{
public partial class TestFormHookListeners : Form
{
private readonly KeyboardHookListener m_KeyboardHookManager;
private readonly MouseHookListener m_MouseHookManager;
public TestFormHookListeners()
{
InitializeComponent();
m_KeyboardHookManager = new KeyboardHookListener(new GlobalHooker());
m_KeyboardHookManager.Enabled = true;
m_MouseHookManager = new MouseHookListener(new GlobalHooker());
m_MouseHookManager.Enabled = true;
}
//##################################################################
#region Check boxes to set or remove particular event handlers.
private void checkBoxOnMouseMove_CheckedChanged(object sender, EventArgs e)
{
if (checkBoxOnMouseMove.Checked)
{
m_MouseHookManager.MouseMove += HookManager_MouseMove;
}
else
{
m_MouseHookManager.MouseMove -= HookManager_MouseMove;
}
}
private void checkBoxOnMouseClick_CheckedChanged(object sender, EventArgs e)
{
if (checkBoxOnMouseClick.Checked)
{
m_MouseHookManager.MouseClickExt += HookManager_MouseClick;
}
else
{
checkBoxSuppressMouse.Checked = false;
m_MouseHookManager.MouseClickExt -= HookManager_MouseClick;
}
}
private void checkBoxOnMouseUp_CheckedChanged(object sender, EventArgs e)
{
if (checkBoxOnMouseUp.Checked)
{
m_MouseHookManager.MouseUp += HookManager_MouseUp;
}
else
{
m_MouseHookManager.MouseUp -= HookManager_MouseUp;
}
}
private void checkBoxOnMouseDown_CheckedChanged(object sender, EventArgs e)
{
if (checkBoxOnMouseDown.Checked)
{
m_MouseHookManager.MouseDown += HookManager_MouseDown;
}
else
{
m_MouseHookManager.MouseDown -= HookManager_MouseDown;
}
}
private void checkBoxMouseDoubleClick_CheckedChanged(object sender, EventArgs e)
{
if (checkBoxMouseDoubleClick.Checked)
{
m_MouseHookManager.MouseDoubleClick += HookManager_MouseDoubleClick;
}
else
{
m_MouseHookManager.MouseDoubleClick -= HookManager_MouseDoubleClick;
}
}
private void checkBoxMouseWheel_CheckedChanged(object sender, EventArgs e)
{
if (checkBoxMouseWheel.Checked)
{
m_MouseHookManager.MouseWheel += HookManager_MouseWheel;
}
else
{
m_MouseHookManager.MouseWheel -= HookManager_MouseWheel;
}
}
private void checkBoxSuppressMouse_CheckedChanged(object sender, EventArgs e)
{
if (checkBoxSuppressMouse.Checked)
{
m_MouseHookManager.MouseDownExt += HookManager_Supress;
}
else
{
m_MouseHookManager.MouseDownExt -= HookManager_Supress;
}
}
private void checkBoxKeyDown_CheckedChanged(object sender, EventArgs e)
{
if (checkBoxKeyDown.Checked)
{
m_KeyboardHookManager.KeyDown += HookManager_KeyDown;
}
else
{
m_KeyboardHookManager.KeyDown -= HookManager_KeyDown;
}
}
private void checkBoxKeyUp_CheckedChanged(object sender, EventArgs e)
{
if (checkBoxKeyUp.Checked)
{
m_KeyboardHookManager.KeyUp += HookManager_KeyUp;
}
else
{
m_KeyboardHookManager.KeyUp -= HookManager_KeyUp;
}
}
private void checkBoxKeyPress_CheckedChanged(object sender, EventArgs e)
{
if (checkBoxKeyPress.Checked)
{
m_KeyboardHookManager.KeyPress += HookManager_KeyPress;
}
else
{
m_KeyboardHookManager.KeyPress -= HookManager_KeyPress;
}
}
#endregion
//##################################################################
#region Event handlers of particular events. They will be activated when an appropriate check box is checked.
private void HookManager_KeyDown(object sender, KeyEventArgs e)
{
Log(string.Format("KeyDown \t\t {0}\n", e.KeyCode));
}
private void HookManager_KeyUp(object sender, KeyEventArgs e)
{
Log(string.Format("KeyUp \t\t {0}\n", e.KeyCode));
}
private void HookManager_KeyPress(object sender, KeyPressEventArgs e)
{
Log(string.Format("KeyPress \t\t {0}\n", e.KeyChar));
}
private void HookManager_MouseMove(object sender, MouseEventArgs e)
{
labelMousePosition.Text = string.Format("x={0:0000}; y={1:0000}", e.X, e.Y);
}
private void HookManager_MouseClick(object sender, MouseEventArgs e)
{
Log(string.Format("MouseClick \t\t {0}\n", e.Button));
}
private void HookManager_MouseUp(object sender, MouseEventArgs e)
{
Log(string.Format("MouseUp \t\t {0}\n", e.Button));
}
private void HookManager_MouseDown(object sender, MouseEventArgs e)
{
Log(string.Format("MouseDown \t\t {0}\n", e.Button));
}
private void HookManager_MouseDoubleClick(object sender, MouseEventArgs e)
{
Log(string.Format("MouseDoubleClick \t\t {0}\n", e.Button));
}
private void HookManager_MouseWheel(object sender, MouseEventArgs e)
{
labelWheel.Text = string.Format("Wheel={0:000}", e.Delta);
}
private void Log(string text)
{
textBoxLog.AppendText(text);
textBoxLog.ScrollToCaret();
}
#endregion
private void checkBoxEnabled_CheckedChanged(object sender, EventArgs e)
{
m_MouseHookManager.Enabled = checkBoxEnabled.Checked;
m_KeyboardHookManager.Enabled = checkBoxEnabled.Checked;
}
private void radioHooksType_CheckedChanged(object sender, EventArgs e)
{
Hooker hook;
if (radioApplication.Checked)
{
hook = new AppHooker();
}
else
{
hook = new GlobalHooker();
}
m_KeyboardHookManager.Replace(hook);
m_MouseHookManager.Replace(hook);
}
private void HookManager_Supress(object sender, MouseEventExtArgs e)
{
if (e.Button != MouseButtons.Right) { return;}
Log("Suppressed.\n");
e.Handled = true;
}
}
}
| |
/*
* Copyright (c) 2008, Anthony James McCreath
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1 Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2 Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3 Neither the name of the 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 Anthony James McCreath "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 Anthony James McCreath 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.Text;
using System.Xml;
using System.IO;
namespace ClockWork.ScriptBuilder.XmlScript
{
/// <summary>
/// Represents an xml element.
/// can contain any item.
/// XsAttribute items will be rendered as attributes
/// xml specific items implement IXmlRenderer which lets you render directly to an XmlDocument or XmlElement
/// other objects are wrapped into a XsText item that encodes their rendered content as a text node
/// </summary>
public class XsElement : ScriptSet, IXmlRenderer
{
#region Constructors
/// <summary>
/// creates an empty element
/// </summary>
/// <param name="name"></param>
public XsElement(string name) : base() { Name = name; }
/// <summary>
/// creates an empty element
/// </summary>
/// <param name="layout"></param>
/// <param name="name"></param>
public XsElement(ScriptLayout layout, string name) : base(layout) { Name = name; }
/// <summary>
/// creates an element containing items
/// </summary>
/// <param name="name"></param>
/// <param name="items"></param>
public XsElement(string name, IEnumerable<object> items) : base(items) { Name = name; }
/// <summary>
/// creates an element containing items
/// </summary>
/// <param name="name"></param>
/// <param name="items"></param>
public XsElement(string name, params object[] items) : base(items) { Name = name; }
/// <summary>
/// creates an element containing items
/// </summary>
/// <param name="layout"></param>
/// <param name="name"></param>
/// <param name="items"></param>
public XsElement(ScriptLayout layout, string name, IEnumerable<object> items) : base(layout, items) { Name = name; }
/// <summary>
/// creates an element containing items
/// </summary>
/// <param name="layout"></param>
/// <param name="name"></param>
/// <param name="items"></param>
public XsElement(ScriptLayout layout, string name, params object[] items) : base(layout, items) { Name = name; }
#endregion
#region Data
private string _Name;
/// <summary>
/// element name
/// can include namespace (I think!)
/// </summary>
public string Name
{
get { return _Name; }
set { _Name = value; }
}
#endregion
#region Layout
/// <summary>
/// Defines the default layout that this item with use
/// </summary>
public override ScriptLayout DefaultLayout
{
get { return ScriptLayout.Inline; }
}
#endregion
#region Rendering
/// <summary>
/// Render the xml element
/// detects XsAttributes form within its collection and renders appropriately
/// non IXmlRenderer objects are wrapped within XsText rendering i.e. encoded
/// </summary>
/// <param name="e"></param>
protected override void OnRender(RenderingEventArgs e)
{
IScriptWriter writer = e.Writer;
// this uses EncodeName which means the name can include the namespace
// Iif we implement namespace as a seperate entitiy we should use EncodeLocalName
List<XsAttribute> attributes = new List<XsAttribute>();
bool hasInnerNodes = false;
bool hasElements = false;
foreach (object o in this)
{
if (o is XsAttribute)
{
attributes.Add((XsAttribute)o);
}
else
hasInnerNodes = true;
if (o is XsElement)
hasElements = true;
}
if (hasElements)
this.TrySetLayout(ScriptLayout.Block);
// do the tag and attributes
if (this.Layout == ScriptLayout.Block && this.HasRenderContent)
writer.WriteNewLineAndIndent();
writer.Write("<" + XmlConvert.EncodeName(Name));
foreach (XsAttribute a in attributes)
{
writer.Write(" ");
writer.Write(a);
}
if (hasInnerNodes)
{
writer.Write(">");
if (this.Layout == ScriptLayout.InlineBlock)
writer.WriteNewLineAndIndent();
writer.BeginIndent();
base.OnRender(e); // does inner items
writer.EndIndent();
if (this.Layout == ScriptLayout.InlineBlock || this.Layout == ScriptLayout.Block)
writer.WriteNewLineAndIndent();
// do the end tag
writer.Write("</" + XmlConvert.EncodeName(Name) + ">");
}
else
{
writer.Write("/>");
}
}
/// <summary>
/// remove attributes from render list
/// </summary>
/// <param name="dest"></param>
/// <param name="o"></param>
protected override void AddToRenderList(List<object> dest, object o)
{
if (o is XsAttribute)
{
// skip
}
else if (o is IXmlRenderer)
{
base.AddToRenderList(dest,o);
}
else
base.AddToRenderList(dest, new XsText(o)); // wrap unknowns as text nodes
}
#endregion
#region IXmlRenderer
/// <summary>
/// add as the root XmlElement
/// </summary>
/// <param name="doc"></param>
public void Render(XmlDocument doc)
{
doc.AppendChild(CreateXmlElement(doc));
}
/// <summary>
/// add as an XmlElement to the children of parentElement
/// </summary>
/// <param name="parentElement"></param>
public void Render(XmlElement parentElement)
{
parentElement.AppendChild(CreateXmlElement(parentElement.OwnerDocument));
}
/// <summary>
/// Creates an XmlElement based on this
/// Adds all children
/// </summary>
/// <param name="doc"></param>
/// <returns></returns>
protected XmlElement CreateXmlElement(XmlDocument doc)
{
XmlElement element = doc.CreateElement(this.Name);
foreach (object o in this)
{
if (o is IXmlRenderer)
{
((IXmlRenderer)o).Render(element);
}
else
{
Xs.Text(o).Render(element);
}
}
return element;
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace IoTService.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using UnityEditor;
using UnityEngine;
using Vexe.Editor.Extensions;
using Vexe.Editor.GUIs;
using Vexe.Editor.Helpers;
using Vexe.Editor.Internal;
using Vexe.Editor.Types;
using Vexe.Editor.Visibility;
using Vexe.Editor.Windows;
using Vexe.Runtime.Extensions;
using Vexe.Runtime.Helpers;
using Vexe.Runtime.Types;
using UnityObject = UnityEngine.Object;
namespace Vexe.Editor.Drawers
{
public class RecursiveDrawer : ObjectDrawer<object>
{
private bool _isToStringImpl;
private Type _polymorphicType;
private string _nullString;
private Tab[] _tabs;
private Predicate<UnityObject[]> _isDropAccepted;
private Func<UnityObject[], UnityObject> _getDraggedObject;
private Func<Func<Type[]>, Action<Type>, string, Tab> _newTypeTab;
private Func<Func<UnityObject[]>, string, Tab> _newUnityTab;
private bool _disablePicker, _autoAlloc;
protected override void Initialize()
{
_nullString = string.Format("null ({0})", memberTypeName);
if (memberValue != null)
{
_polymorphicType = memberValue.GetType();
_isToStringImpl = _polymorphicType.IsMethodImplemented("ToString", Type.EmptyTypes);
}
else
_isToStringImpl = memberType.IsMethodImplemented("ToString", Type.EmptyTypes);
_getDraggedObject = objs =>
{
for (int i = 0; i < objs.Length; i++)
{
var drag = objs[i];
if (drag == null)
continue;
var go = drag as GameObject;
if (go != null)
{
if (!memberType.IsA<Component>())
continue;
var c = go.GetComponent(memberType);
if (c != null)
return c;
}
if (drag.GetType().IsA(memberType))
return drag;
}
return null;
};
_isDropAccepted = objs => _getDraggedObject(objs) != null;
_newTypeTab = (getValues, create, title) =>
new Tab<Type>(
@getValues: getValues,
@getCurrent: () => { var x = memberValue; return x == null ? null : x.GetType(); },
@setTarget: newType => { if (newType == null) memberValue = memberType.GetDefaultValueEmptyIfString(); else create(newType); },
@getValueName: type => type.GetNiceName(),
@title: title
);
_newUnityTab = (getValues, title) =>
new Tab<UnityObject>(
@getValues: getValues,
@getCurrent: member.As<UnityObject>,
@setTarget: member.Set,
@getValueName: obj => obj.name + " (" + obj.GetType().GetNiceName() + ")",
@title: title
);
int idx = 0;
if (memberType.IsInterface)
{
_tabs = new Tab[4];
_tabs[idx++] = _newUnityTab(() => UnityObject.FindObjectsOfType<UnityObject>()
.OfType(memberType)
.ToArray(), "Scene");
_tabs[idx++] = _newUnityTab(() => PrefabHelper.GetComponentPrefabs(memberType)
.ToArray(), "Prefab");
_tabs[idx++] = _newTypeTab(() => ReflectionHelper.GetAllUserTypesOf(memberType)
.Where(t => t.IsA<MonoBehaviour>() && !t.IsAbstract)
.ToArray(), TryCreateInstanceInGO, "New Behaviour");
}
else _tabs = new Tab[1];
var systemTypes = ReflectionHelper.GetAllUserTypesOf(memberType)
.Where(t => !t.IsA<UnityObject>() && !t.IsAbstract)
.ToArray();
if (memberType.IsGenericType && !systemTypes.Contains(memberType))
ArrayUtility.Add(ref systemTypes, memberType);
_tabs[idx] = _newTypeTab(() => systemTypes, TryCreateInstance, "System Type");
var display = attributes.GetAttribute<DisplayAttribute>();
if (display != null)
{
_autoAlloc = (display.ObjOpt & Obj.AutoAlloc) != 0;
_disablePicker = (display.ObjOpt & Obj.DisablePicker) != 0;
}
}
public override void OnGUI()
{
using (gui.Horizontal())
{
if (_autoAlloc && memberValue == null)
{
if (memberType.IsA<UnityObject>())
Debug.Log("Cannot automatically allocate memory for UnityObject member: " + member.NiceName);
else if (memberType.IsAbstract)
Debug.Log("Cannot automatically allocate memory for abstract member: " + member.NiceName);
else
memberValue = memberType.ActivatorInstance();
}
var isEmpty = string.IsNullOrEmpty(displayText);
var label = isEmpty ? string.Empty : displayText + " " + (foldout ? "^" : ">");
var value = member.Value;
var unityObj = value as UnityObject;
string field;
if (value == null)
field = _nullString;
else
field = (_isToStringImpl || unityObj != null) ? value.ToString() : value.GetType().GetNiceName();
if (isEmpty)
Foldout();
var e = Event.current;
gui.Prefix(label);
var labelRect = gui.LastRect;
gui.Cursor(labelRect, MouseCursor.Link);
if (!isEmpty && e.IsMouseContained(labelRect) && e.IsLMBDown())
foldout = !foldout;
gui.Space(2.3f);
if (unityObj != null)
{
var icon = AssetPreview.GetMiniThumbnail(unityObj);
gui.Label(new GUIContent(field, icon), GUIStyles.ObjectField);
}
else
gui.Label(field, GUIStyles.ObjectField);
var totalRect = gui.LastRect;
var fieldRect = totalRect;
fieldRect.width -= 15f;
if (unityObj != null)
{
gui.Cursor(fieldRect, MouseCursor.Zoom);
if (fieldRect.Contains(e.mousePosition))
{
if (e.IsLMBDown())
{
EditorHelper.PingObject(unityObj);
if (e.IsDoubleClick())
EditorHelper.SelectObject(unityObj);
e.Use();
}
else if (e.IsRMBDown())
{
var mb = unityObj as MonoBehaviour;
if (mb != null)
{
var monoscript = MonoScript.FromMonoBehaviour(mb);
var scriptPath = AssetDatabase.GetAssetPath(monoscript);
UnityEditorInternal.InternalEditorUtility.OpenFileAtLineExternal(scriptPath, 0);
}
}
}
}
var drop = gui.RegisterFieldForDrop<UnityObject>(fieldRect, _getDraggedObject, _isDropAccepted);
if (drop != null)
{
memberValue = drop;
GUI.changed = true;
}
var thumbRect = totalRect;
thumbRect.width -= fieldRect.width;
thumbRect.x += fieldRect.width;
gui.Cursor(thumbRect, MouseCursor.Link);
// Selection/thumb button
{
if (e.IsMouseContained(thumbRect) && e.IsMouseDown())
{
if (e.IsLMB())
{
if (_disablePicker)
memberValue = memberType.ActivatorInstance();
else
SelectionWindow.Show("Select a `" + memberTypeName + "` object", _tabs);
}
else if (e.IsRMB())
{
try
{
memberValue = memberType.ActivatorInstance();
}
catch(Exception ex)
{
Debug.Log("Error creating new instance of type `{0}`: {1}".FormatWith(memberType.GetNiceName(), ex.Message));
}
}
}
}
}
if (!foldout)
return;
if (member.IsNull())
{
gui.HelpBox("Member value is null");
return;
}
if (_polymorphicType == null || _polymorphicType == memberType)
{
object value = member.Value;
DrawRecursive(ref value, gui, id, unityTarget);
member.Value = value;
}
else
{
var drawer = MemberDrawersHandler.CachedGetObjectDrawer(_polymorphicType);
var drawerType = drawer.GetType();
if (drawerType == typeof(RecursiveDrawer) || drawerType == typeof(UnityObjectDrawer))
{
object value = member.Value;
DrawRecursive(ref value, gui, id, unityTarget);
member.Value = value;
}
else
{
drawer.Initialize(member, attributes, gui, prefs);
gui.Member(member, attributes, drawer, false);
}
}
}
/// <summary>
/// if memberNames was null or empty, draws members in 'obj' recursively. Members are fetched according to the default visibility logic
/// otherwise, draws only the specified members by memberNames
/// </summary>
public static bool DrawRecursive(object target, BaseGUI gui, int id, UnityObject unityTarget, params string[] memberNames)
{
return DrawRecursive(ref target, gui, id, unityTarget, memberNames);
}
public static bool DrawRecursive(ref object target, BaseGUI gui, int id, UnityObject unityTarget, params string[] memberNames)
{
List<MemberInfo> members;
var targetType = target.GetType();
if (memberNames.IsNullOrEmpty())
{
members = VisibilityLogic.CachedGetVisibleMembers(targetType);
}
else
{
members = new List<MemberInfo>();
for (int i = 0; i < memberNames.Length; i++)
{
var name = memberNames[i];
var member = ReflectionHelper.CachedGetMember(targetType, name);
if (member == null)
{
LogFormat("RecursiveDrawer: Couldn't find member {0} in {1}", name, targetType.Name);
continue;
}
if (VisibilityLogic.IsVisibleMember(member))
members.Add(member);
}
}
if (members.Count == 0)
{
gui.HelpBox("Object doesn't have any visible members");
return false;
}
bool changed = false;
using (gui.Indent())
{
for (int i = 0; i < members.Count; i++)
{
MemberInfo member = members[i];
if (!ConditionalVisibility.IsVisible(member, target))
continue;
EditorMember em;
changed |= gui.Member(member, target, unityTarget, id, false, out em);
if (em != null)
target = em.RawTarget;
}
}
return changed;
}
private void TryCreateInstanceInGO(Type newType)
{
TryCreateInstance(() => new GameObject("(new) " + newType.GetNiceName()).AddComponent(newType));
}
private void TryCreateInstance(Type newType)
{
TryCreateInstance(() => newType.Instance());
}
private void TryCreateInstance(Func<object> create)
{
try
{
var inst = create();
member.Set(inst);
if (memberValue != null)
_polymorphicType = memberValue.GetType();
}
catch (TargetInvocationException e)
{
Debug.LogError(string.Format("Couldn't create instance of type {0}. Make sure the type has an empty constructor. Message: {1}, Stacktrace: {2}", memberTypeName, e.Message, e.StackTrace));
}
}
}
}
| |
//----------------------------------------------------------------------------
// Anti-Grain Geometry - Version 2.4
// Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com)
//
// C# Port port by: Lars Brubaker
// larsbrubaker@gmail.com
// Copyright (C) 2007
//
// Permission to copy, use, modify, sell and distribute this software
// is granted provided this copyright notice appears in all copies.
// This software is provided "as is" without express or implied
// warranty, and with no claim as to its suitability for any purpose.
//
//----------------------------------------------------------------------------
// Contact: mcseem@antigrain.com
// mcseemagg@yahoo.com
// http://www.antigrain.com
//----------------------------------------------------------------------------
//
// Liang-Barsky clipping
//
//----------------------------------------------------------------------------
namespace MatterHackers.Agg
{
public static class ClipLiangBarsky
{
//------------------------------------------------------------------------
private enum clipping_flags_e
{
clipping_flags_x1_clipped = 4,
clipping_flags_x2_clipped = 1,
clipping_flags_y1_clipped = 8,
clipping_flags_y2_clipped = 2,
clipping_flags_x_clipped = clipping_flags_x1_clipped | clipping_flags_x2_clipped,
clipping_flags_y_clipped = clipping_flags_y1_clipped | clipping_flags_y2_clipped
};
//----------------------------------------------------------clipping_flags
// Determine the clipping code of the vertex according to the
// Cyrus-Beck line clipping algorithm
//
// | |
// 0110 | 0010 | 0011
// | |
// -------+--------+-------- clip_box.y2
// | |
// 0100 | 0000 | 0001
// | |
// -------+--------+-------- clip_box.y1
// | |
// 1100 | 1000 | 1001
// | |
// clip_box.x1 clip_box.x2
//
//
//template<class T>
public static int clipping_flags(int x, int y, RectangleInt clip_box)
{
return ((x > clip_box.Right) ? 1 : 0)
| ((y > clip_box.Top) ? 1 << 1 : 0)
| ((x < clip_box.Left) ? 1 << 2 : 0)
| ((y < clip_box.Bottom) ? 1 << 3 : 0);
}
public static int clipping_flags_x(int x, RectangleInt clip_box)
{
return ((x > clip_box.Right ? 1 : 0) | ((x < clip_box.Left ? 1 : 0) << 2));
}
public static int clipping_flags_y(int y, RectangleInt clip_box)
{
return (((y > clip_box.Top ? 1 : 0) << 1) | ((y < clip_box.Bottom ? 1 : 0) << 3));
}
public static int clip_liang_barsky(int x1, int y1, int x2, int y2,
RectangleInt clip_box,
int[] x, int[] y)
{
int XIndex = 0;
int YIndex = 0;
double nearzero = 1e-30;
double deltax = x2 - x1;
double deltay = y2 - y1;
double xin;
double xout;
double yin;
double yout;
double tinx;
double tiny;
double toutx;
double touty;
double tin1;
double tin2;
double tout1;
int np = 0;
if (deltax == 0.0)
{
// bump off of the vertical
deltax = (x1 > clip_box.Left) ? -nearzero : nearzero;
}
if (deltay == 0.0)
{
// bump off of the horizontal
deltay = (y1 > clip_box.Bottom) ? -nearzero : nearzero;
}
if (deltax > 0.0)
{
// points to right
xin = clip_box.Left;
xout = clip_box.Right;
}
else
{
xin = clip_box.Right;
xout = clip_box.Left;
}
if (deltay > 0.0)
{
// points up
yin = clip_box.Bottom;
yout = clip_box.Top;
}
else
{
yin = clip_box.Top;
yout = clip_box.Bottom;
}
tinx = (xin - x1) / deltax;
tiny = (yin - y1) / deltay;
if (tinx < tiny)
{
// hits x first
tin1 = tinx;
tin2 = tiny;
}
else
{
// hits y first
tin1 = tiny;
tin2 = tinx;
}
if (tin1 <= 1.0)
{
if (0.0 < tin1)
{
x[XIndex++] = (int)xin;
y[YIndex++] = (int)yin;
++np;
}
if (tin2 <= 1.0)
{
toutx = (xout - x1) / deltax;
touty = (yout - y1) / deltay;
tout1 = (toutx < touty) ? toutx : touty;
if (tin2 > 0.0 || tout1 > 0.0)
{
if (tin2 <= tout1)
{
if (tin2 > 0.0)
{
if (tinx > tiny)
{
x[XIndex++] = (int)xin;
y[YIndex++] = (int)(y1 + tinx * deltay);
}
else
{
x[XIndex++] = (int)(x1 + tiny * deltax);
y[YIndex++] = (int)yin;
}
++np;
}
if (tout1 < 1.0)
{
if (toutx < touty)
{
x[XIndex++] = (int)xout;
y[YIndex++] = (int)(y1 + toutx * deltay);
}
else
{
x[XIndex++] = (int)(x1 + touty * deltax);
y[YIndex++] = (int)yout;
}
}
else
{
x[XIndex++] = x2;
y[YIndex++] = y2;
}
++np;
}
else
{
if (tinx > tiny)
{
x[XIndex++] = (int)xin;
y[YIndex++] = (int)yout;
}
else
{
x[XIndex++] = (int)xout;
y[YIndex++] = (int)yin;
}
++np;
}
}
}
}
return np;
}
public static bool clip_move_point(int x1, int y1, int x2, int y2,
RectangleInt clip_box,
ref int x, ref int y, int flags)
{
int bound;
if ((flags & (int)clipping_flags_e.clipping_flags_x_clipped) != 0)
{
if (x1 == x2)
{
return false;
}
bound = ((flags & (int)clipping_flags_e.clipping_flags_x1_clipped) != 0) ? clip_box.Left : clip_box.Right;
y = (int)((double)(bound - x1) * (y2 - y1) / (x2 - x1) + y1);
x = bound;
}
flags = clipping_flags_y(y, clip_box);
if ((flags & (int)clipping_flags_e.clipping_flags_y_clipped) != 0)
{
if (y1 == y2)
{
return false;
}
bound = ((flags & (int)clipping_flags_e.clipping_flags_x1_clipped) != 0) ? clip_box.Bottom : clip_box.Top;
x = (int)((double)(bound - y1) * (x2 - x1) / (y2 - y1) + x1);
y = bound;
}
return true;
}
//-------------------------------------------------------clip_line_segment
// Returns: ret >= 4 - Fully clipped
// (ret & 1) != 0 - First point has been moved
// (ret & 2) != 0 - Second point has been moved
//
//template<class T>
public static int clip_line_segment(ref int x1, ref int y1, ref int x2, ref int y2,
RectangleInt clip_box)
{
int f1 = clipping_flags(x1, y1, clip_box);
int f2 = clipping_flags(x2, y2, clip_box);
int ret = 0;
if ((f2 | f1) == 0)
{
// Fully visible
return 0;
}
if ((f1 & (int)clipping_flags_e.clipping_flags_x_clipped) != 0 &&
(f1 & (int)clipping_flags_e.clipping_flags_x_clipped) == (f2 & (int)clipping_flags_e.clipping_flags_x_clipped))
{
// Fully clipped
return 4;
}
if ((f1 & (int)clipping_flags_e.clipping_flags_y_clipped) != 0 &&
(f1 & (int)clipping_flags_e.clipping_flags_y_clipped) == (f2 & (int)clipping_flags_e.clipping_flags_y_clipped))
{
// Fully clipped
return 4;
}
int tx1 = x1;
int ty1 = y1;
int tx2 = x2;
int ty2 = y2;
if (f1 != 0)
{
if (!clip_move_point(tx1, ty1, tx2, ty2, clip_box, ref x1, ref y1, f1))
{
return 4;
}
if (x1 == x2 && y1 == y2)
{
return 4;
}
ret |= 1;
}
if (f2 != 0)
{
if (!clip_move_point(tx1, ty1, tx2, ty2, clip_box, ref x2, ref y2, f2))
{
return 4;
}
if (x1 == x2 && y1 == y2)
{
return 4;
}
ret |= 2;
}
return ret;
}
}
}
//#endif
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.IO;
using System.Threading;
using System.Collections;
using System.Collections.Generic;
using System.Security;
using System.Security.Policy;
using System.Reflection;
using System.Globalization;
using System.Xml;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using log4net;
using Nini.Config;
using Amib.Threading;
using OpenSim.Framework;
using OpenSim.Region.CoreModules.Framework.EventQueue;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.ScriptEngine.Shared;
using OpenSim.Region.ScriptEngine.Shared.ScriptBase;
using OpenSim.Region.ScriptEngine.Shared.CodeTools;
using OpenSim.Region.ScriptEngine.Shared.Instance;
using OpenSim.Region.ScriptEngine.Interfaces;
using ScriptCompileQueue = OpenSim.Framework.LocklessQueue<object[]>;
namespace OpenSim.Region.ScriptEngine.XEngine
{
public class XEngine : INonSharedRegionModule, IScriptModule, IScriptEngine
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private SmartThreadPool m_ThreadPool;
private int m_MaxScriptQueue;
private Scene m_Scene;
private IConfig m_ScriptConfig = null;
private IConfigSource m_ConfigSource = null;
private ICompiler m_Compiler;
private int m_MinThreads;
private int m_MaxThreads ;
private int m_IdleTimeout;
private int m_StackSize;
private int m_SleepTime;
private int m_SaveTime;
private ThreadPriority m_Prio;
private bool m_Enabled = false;
private bool m_InitialStartup = true;
private int m_ScriptFailCount; // Number of script fails since compile queue was last empty
private string m_ScriptErrorMessage;
private Dictionary<string, string> m_uniqueScripts = new Dictionary<string, string>();
private bool m_AppDomainLoading;
private Dictionary<UUID,ArrayList> m_ScriptErrors =
new Dictionary<UUID,ArrayList>();
// disable warning: need to keep a reference to XEngine.EventManager
// alive to avoid it being garbage collected
#pragma warning disable 414
private EventManager m_EventManager;
#pragma warning restore 414
private IXmlRpcRouter m_XmlRpcRouter;
private int m_EventLimit;
private bool m_KillTimedOutScripts;
private static List<XEngine> m_ScriptEngines =
new List<XEngine>();
// Maps the local id to the script inventory items in it
private Dictionary<uint, List<UUID> > m_PrimObjects =
new Dictionary<uint, List<UUID> >();
// Maps the UUID above to the script instance
private Dictionary<UUID, IScriptInstance> m_Scripts =
new Dictionary<UUID, IScriptInstance>();
// Maps the asset ID to the assembly
private Dictionary<UUID, string> m_Assemblies =
new Dictionary<UUID, string>();
private Dictionary<string, int> m_AddingAssemblies =
new Dictionary<string, int>();
// This will list AppDomains by script asset
private Dictionary<UUID, AppDomain> m_AppDomains =
new Dictionary<UUID, AppDomain>();
// List the scripts running in each appdomain
private Dictionary<UUID, List<UUID> > m_DomainScripts =
new Dictionary<UUID, List<UUID> >();
private ScriptCompileQueue m_CompileQueue = new ScriptCompileQueue();
IWorkItemResult m_CurrentCompile = null;
private Dictionary<UUID, int> m_CompileDict = new Dictionary<UUID, int>();
public string ScriptEngineName
{
get { return "XEngine"; }
}
public Scene World
{
get { return m_Scene; }
}
public static List<XEngine> ScriptEngines
{
get { return m_ScriptEngines; }
}
public IScriptModule ScriptModule
{
get { return this; }
}
// private struct RezScriptParms
// {
// uint LocalID;
// UUID ItemID;
// string Script;
// }
public IConfig Config
{
get { return m_ScriptConfig; }
}
public IConfigSource ConfigSource
{
get { return m_ConfigSource; }
}
public event ScriptRemoved OnScriptRemoved;
public event ObjectRemoved OnObjectRemoved;
//
// IRegionModule functions
//
public void Initialise(IConfigSource configSource)
{
if (configSource.Configs["XEngine"] == null)
return;
m_ScriptConfig = configSource.Configs["XEngine"];
m_ConfigSource = configSource;
}
public void AddRegion(Scene scene)
{
if (m_ScriptConfig == null)
return;
m_ScriptFailCount = 0;
m_ScriptErrorMessage = String.Empty;
if (m_ScriptConfig == null)
{
// m_log.ErrorFormat("[XEngine] No script configuration found. Scripts disabled");
return;
}
m_Enabled = m_ScriptConfig.GetBoolean("Enabled", true);
if (!m_Enabled)
return;
AppDomain.CurrentDomain.AssemblyResolve +=
OnAssemblyResolve;
m_log.InfoFormat("[XEngine] Initializing scripts in region {0}",
scene.RegionInfo.RegionName);
m_Scene = scene;
m_MinThreads = m_ScriptConfig.GetInt("MinThreads", 2);
m_MaxThreads = m_ScriptConfig.GetInt("MaxThreads", 100);
m_IdleTimeout = m_ScriptConfig.GetInt("IdleTimeout", 60);
string priority = m_ScriptConfig.GetString("Priority", "BelowNormal");
m_MaxScriptQueue = m_ScriptConfig.GetInt("MaxScriptEventQueue",300);
m_StackSize = m_ScriptConfig.GetInt("ThreadStackSize", 262144);
m_SleepTime = m_ScriptConfig.GetInt("MaintenanceInterval", 10) * 1000;
m_AppDomainLoading = m_ScriptConfig.GetBoolean("AppDomainLoading", true);
m_EventLimit = m_ScriptConfig.GetInt("EventLimit", 30);
m_KillTimedOutScripts = m_ScriptConfig.GetBoolean("KillTimedOutScripts", false);
m_SaveTime = m_ScriptConfig.GetInt("SaveInterval", 120) * 1000;
m_Prio = ThreadPriority.BelowNormal;
switch (priority)
{
case "Lowest":
m_Prio = ThreadPriority.Lowest;
break;
case "BelowNormal":
m_Prio = ThreadPriority.BelowNormal;
break;
case "Normal":
m_Prio = ThreadPriority.Normal;
break;
case "AboveNormal":
m_Prio = ThreadPriority.AboveNormal;
break;
case "Highest":
m_Prio = ThreadPriority.Highest;
break;
default:
m_log.ErrorFormat("[XEngine] Invalid thread priority: '{0}'. Assuming BelowNormal", priority);
break;
}
lock (m_ScriptEngines)
{
m_ScriptEngines.Add(this);
}
// Needs to be here so we can queue the scripts that need starting
//
m_Scene.EventManager.OnRezScript += OnRezScript;
// Complete basic setup of the thread pool
//
SetupEngine(m_MinThreads, m_MaxThreads, m_IdleTimeout, m_Prio,
m_MaxScriptQueue, m_StackSize);
m_Scene.StackModuleInterface<IScriptModule>(this);
m_XmlRpcRouter = m_Scene.RequestModuleInterface<IXmlRpcRouter>();
if (m_XmlRpcRouter != null)
{
OnScriptRemoved += m_XmlRpcRouter.ScriptRemoved;
OnObjectRemoved += m_XmlRpcRouter.ObjectRemoved;
}
}
public void RemoveRegion(Scene scene)
{
lock (m_Scripts)
{
foreach (IScriptInstance instance in m_Scripts.Values)
{
// Force a final state save
//
if (m_Assemblies.ContainsKey(instance.AssetID))
{
string assembly = m_Assemblies[instance.AssetID];
instance.SaveState(assembly);
}
// Clear the event queue and abort the instance thread
//
instance.ClearQueue();
instance.Stop(0);
// Release events, timer, etc
//
instance.DestroyScriptInstance();
// Unload scripts and app domains
// Must be done explicitly because they have infinite
// lifetime
//
m_DomainScripts[instance.AppDomain].Remove(instance.ItemID);
if (m_DomainScripts[instance.AppDomain].Count == 0)
{
m_DomainScripts.Remove(instance.AppDomain);
UnloadAppDomain(instance.AppDomain);
}
}
m_Scripts.Clear();
m_PrimObjects.Clear();
m_Assemblies.Clear();
m_DomainScripts.Clear();
}
lock (m_ScriptEngines)
{
m_ScriptEngines.Remove(this);
}
}
public void RegionLoaded(Scene scene)
{
if (!m_Enabled)
return;
m_EventManager = new EventManager(this);
m_Compiler = new Compiler(this);
m_Scene.EventManager.OnRemoveScript += OnRemoveScript;
m_Scene.EventManager.OnScriptReset += OnScriptReset;
m_Scene.EventManager.OnStartScript += OnStartScript;
m_Scene.EventManager.OnStopScript += OnStopScript;
m_Scene.EventManager.OnGetScriptRunning += OnGetScriptRunning;
m_Scene.EventManager.OnShutdown += OnShutdown;
if (m_SleepTime > 0)
{
m_ThreadPool.QueueWorkItem(new WorkItemCallback(this.DoMaintenance),
new Object[]{ m_SleepTime });
}
if (m_SaveTime > 0)
{
m_ThreadPool.QueueWorkItem(new WorkItemCallback(this.DoBackup),
new Object[] { m_SaveTime });
}
m_ThreadPool.Start();
}
public void Close()
{
lock (m_ScriptEngines)
{
if (m_ScriptEngines.Contains(this))
m_ScriptEngines.Remove(this);
}
}
public object DoBackup(object o)
{
Object[] p = (Object[])o;
int saveTime = (int)p[0];
if (saveTime > 0)
System.Threading.Thread.Sleep(saveTime);
// m_log.Debug("[XEngine] Backing up script states");
List<IScriptInstance> instances = new List<IScriptInstance>();
lock (m_Scripts)
{
foreach (IScriptInstance instance in m_Scripts.Values)
instances.Add(instance);
}
foreach (IScriptInstance i in instances)
{
string assembly = String.Empty;
lock (m_Scripts)
{
if (!m_Assemblies.ContainsKey(i.AssetID))
continue;
assembly = m_Assemblies[i.AssetID];
}
i.SaveState(assembly);
}
instances.Clear();
if (saveTime > 0)
m_ThreadPool.QueueWorkItem(new WorkItemCallback(this.DoBackup),
new Object[] { saveTime });
return 0;
}
public object DoMaintenance(object p)
{
object[] parms = (object[])p;
int sleepTime = (int)parms[0];
foreach (IScriptInstance inst in m_Scripts.Values)
{
if (inst.EventTime() > m_EventLimit)
{
inst.Stop(100);
if (!m_KillTimedOutScripts)
inst.Start();
}
}
System.Threading.Thread.Sleep(sleepTime);
m_ThreadPool.QueueWorkItem(new WorkItemCallback(this.DoMaintenance),
new Object[]{ sleepTime });
return 0;
}
public Type ReplaceableInterface
{
get { return null; }
}
public string Name
{
get { return "XEngine"; }
}
public void OnRezScript(uint localID, UUID itemID, string script, int startParam, bool postOnRez, string engine, int stateSource)
{
if (script.StartsWith("//MRM:"))
return;
List<IScriptModule> engines = new List<IScriptModule>(m_Scene.RequestModuleInterfaces<IScriptModule>());
List<string> names = new List<string>();
foreach (IScriptModule m in engines)
names.Add(m.ScriptEngineName);
int lineEnd = script.IndexOf('\n');
if (lineEnd > 1)
{
string firstline = script.Substring(0, lineEnd).Trim();
int colon = firstline.IndexOf(':');
if (firstline.Length > 2 && firstline.Substring(0, 2) == "//" && colon != -1)
{
string engineName = firstline.Substring(2, colon-2);
if (names.Contains(engineName))
{
engine = engineName;
script = "//" + script.Substring(script.IndexOf(':')+1);
}
else
{
if (engine == ScriptEngineName)
{
SceneObjectPart part =
m_Scene.GetSceneObjectPart(
localID);
TaskInventoryItem item =
part.Inventory.GetInventoryItem(itemID);
ScenePresence presence =
m_Scene.GetScenePresence(
item.OwnerID);
if (presence != null)
{
presence.ControllingClient.SendAgentAlertMessage(
"Selected engine unavailable. "+
"Running script on "+
ScriptEngineName,
false);
}
}
}
}
}
if (engine != ScriptEngineName)
return;
// If we've seen this exact script text before, use that reference instead
if (m_uniqueScripts.ContainsKey(script))
script = m_uniqueScripts[script];
else
m_uniqueScripts[script] = script;
Object[] parms = new Object[]{localID, itemID, script, startParam, postOnRez, (StateSource)stateSource};
if (stateSource == (int)StateSource.ScriptedRez)
{
lock (m_CompileDict)
{
m_CompileDict[itemID] = 0;
}
DoOnRezScript(parms);
}
else
{
m_CompileQueue.Enqueue(parms);
lock (m_CompileDict)
{
m_CompileDict[itemID] = 0;
}
if (m_CurrentCompile == null)
{
// NOTE: Although we use a lockless queue, the lock here
// is required. It ensures that there are never two
// compile threads running, which, due to a race
// conndition, might otherwise happen
//
lock (m_CompileQueue)
{
if (m_CurrentCompile == null)
m_CurrentCompile = m_ThreadPool.QueueWorkItem(DoOnRezScriptQueue, null);
}
}
}
}
public Object DoOnRezScriptQueue(Object dummy)
{
if (m_InitialStartup)
{
m_InitialStartup = false;
System.Threading.Thread.Sleep(15000);
if (m_CompileQueue.Count == 0)
{
// No scripts on region, so won't get triggered later
// by the queue becoming empty so we trigger it here
m_Scene.EventManager.TriggerEmptyScriptCompileQueue(0, String.Empty);
}
}
object[] o;
while (m_CompileQueue.Dequeue(out o))
DoOnRezScript(o);
// NOTE: Despite having a lockless queue, this lock is required
// to make sure there is never no compile thread while there
// are still scripts to compile. This could otherwise happen
// due to a race condition
//
lock (m_CompileQueue)
{
m_CurrentCompile = null;
}
m_Scene.EventManager.TriggerEmptyScriptCompileQueue(m_ScriptFailCount,
m_ScriptErrorMessage);
m_ScriptFailCount = 0;
return null;
}
private bool DoOnRezScript(object[] parms)
{
Object[] p = parms;
uint localID = (uint)p[0];
UUID itemID = (UUID)p[1];
string script =(string)p[2];
int startParam = (int)p[3];
bool postOnRez = (bool)p[4];
StateSource stateSource = (StateSource)p[5];
lock(m_CompileDict)
{
if (!m_CompileDict.ContainsKey(itemID))
return false;
m_CompileDict.Remove(itemID);
}
// Get the asset ID of the script, so we can check if we
// already have it.
// We must look for the part outside the m_Scripts lock because GetSceneObjectPart later triggers the
// m_parts lock on SOG. At the same time, a scene object that is being deleted will take the m_parts lock
// and then later on try to take the m_scripts lock in this class when it calls OnRemoveScript()
SceneObjectPart part = m_Scene.GetSceneObjectPart(localID);
if (part == null)
{
m_log.Error("[Script] SceneObjectPart unavailable. Script NOT started.");
m_ScriptErrorMessage += "SceneObjectPart unavailable. Script NOT started.\n";
m_ScriptFailCount++;
return false;
}
TaskInventoryItem item = part.Inventory.GetInventoryItem(itemID);
if (item == null)
{
m_ScriptErrorMessage += "Can't find script inventory item.\n";
m_ScriptFailCount++;
return false;
}
UUID assetID = item.AssetID;
//m_log.DebugFormat("[XEngine] Compiling script {0} ({1} on object {2})",
// item.Name, itemID.ToString(), part.ParentGroup.RootPart.Name);
ScenePresence presence = m_Scene.GetScenePresence(item.OwnerID);
string assembly = "";
CultureInfo USCulture = new CultureInfo("en-US");
Thread.CurrentThread.CurrentCulture = USCulture;
Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> linemap;
lock (m_ScriptErrors)
{
try
{
lock (m_AddingAssemblies)
{
m_Compiler.PerformScriptCompile(script, assetID.ToString(), item.OwnerID, out assembly, out linemap);
if (!m_AddingAssemblies.ContainsKey(assembly)) {
m_AddingAssemblies[assembly] = 1;
} else {
m_AddingAssemblies[assembly]++;
}
}
string[] warnings = m_Compiler.GetWarnings();
if (warnings != null && warnings.Length != 0)
{
foreach (string warning in warnings)
{
if (!m_ScriptErrors.ContainsKey(itemID))
m_ScriptErrors[itemID] = new ArrayList();
m_ScriptErrors[itemID].Add(warning);
// try
// {
// // DISPLAY WARNING INWORLD
// string text = "Warning:\n" + warning;
// if (text.Length > 1000)
// text = text.Substring(0, 1000);
// if (!ShowScriptSaveResponse(item.OwnerID,
// assetID, text, true))
// {
// if (presence != null && (!postOnRez))
// presence.ControllingClient.SendAgentAlertMessage("Script saved with warnings, check debug window!", false);
//
// World.SimChat(Utils.StringToBytes(text),
// ChatTypeEnum.DebugChannel, 2147483647,
// part.AbsolutePosition,
// part.Name, part.UUID, false);
// }
// }
// catch (Exception e2) // LEGIT: User Scripting
// {
// m_log.Error("[XEngine]: " +
// "Error displaying warning in-world: " +
// e2.ToString());
// m_log.Error("[XEngine]: " +
// "Warning:\r\n" +
// warning);
// }
}
}
}
catch (Exception e)
{
// try
// {
if (!m_ScriptErrors.ContainsKey(itemID))
m_ScriptErrors[itemID] = new ArrayList();
// DISPLAY ERROR INWORLD
// m_ScriptErrorMessage += "Failed to compile script in object: '" + part.ParentGroup.RootPart.Name + "' Script name: '" + item.Name + "' Error message: " + e.Message.ToString();
//
m_ScriptFailCount++;
m_ScriptErrors[itemID].Add(e.Message.ToString());
// string text = "Error compiling script '" + item.Name + "':\n" + e.Message.ToString();
// if (text.Length > 1000)
// text = text.Substring(0, 1000);
// if (!ShowScriptSaveResponse(item.OwnerID,
// assetID, text, false))
// {
// if (presence != null && (!postOnRez))
// presence.ControllingClient.SendAgentAlertMessage("Script saved with errors, check debug window!", false);
// World.SimChat(Utils.StringToBytes(text),
// ChatTypeEnum.DebugChannel, 2147483647,
// part.AbsolutePosition,
// part.Name, part.UUID, false);
// }
// }
// catch (Exception e2) // LEGIT: User Scripting
// {
// m_log.Error("[XEngine]: "+
// "Error displaying error in-world: " +
// e2.ToString());
// m_log.Error("[XEngine]: " +
// "Errormessage: Error compiling script:\r\n" +
// e.Message.ToString());
// }
return false;
}
}
lock (m_Scripts)
{
ScriptInstance instance = null;
// Create the object record
if ((!m_Scripts.ContainsKey(itemID)) ||
(m_Scripts[itemID].AssetID != assetID))
{
UUID appDomain = assetID;
if (part.ParentGroup.IsAttachment)
appDomain = part.ParentGroup.RootPart.UUID;
if (!m_AppDomains.ContainsKey(appDomain))
{
try
{
AppDomainSetup appSetup = new AppDomainSetup();
// appSetup.ApplicationBase = Path.Combine(
// "ScriptEngines",
// m_Scene.RegionInfo.RegionID.ToString());
Evidence baseEvidence = AppDomain.CurrentDomain.Evidence;
Evidence evidence = new Evidence(baseEvidence);
AppDomain sandbox;
if (m_AppDomainLoading)
sandbox = AppDomain.CreateDomain(
m_Scene.RegionInfo.RegionID.ToString(),
evidence, appSetup);
else
sandbox = AppDomain.CurrentDomain;
//PolicyLevel sandboxPolicy = PolicyLevel.CreateAppDomainLevel();
//AllMembershipCondition sandboxMembershipCondition = new AllMembershipCondition();
//PermissionSet sandboxPermissionSet = sandboxPolicy.GetNamedPermissionSet("Internet");
//PolicyStatement sandboxPolicyStatement = new PolicyStatement(sandboxPermissionSet);
//CodeGroup sandboxCodeGroup = new UnionCodeGroup(sandboxMembershipCondition, sandboxPolicyStatement);
//sandboxPolicy.RootCodeGroup = sandboxCodeGroup;
//sandbox.SetAppDomainPolicy(sandboxPolicy);
m_AppDomains[appDomain] = sandbox;
m_AppDomains[appDomain].AssemblyResolve +=
new ResolveEventHandler(
AssemblyResolver.OnAssemblyResolve);
m_DomainScripts[appDomain] = new List<UUID>();
}
catch (Exception e)
{
m_log.ErrorFormat("[XEngine] Exception creating app domain:\n {0}", e.ToString());
m_ScriptErrorMessage += "Exception creating app domain:\n";
m_ScriptFailCount++;
lock (m_AddingAssemblies)
{
m_AddingAssemblies[assembly]--;
}
return false;
}
}
m_DomainScripts[appDomain].Add(itemID);
instance = new ScriptInstance(this, part,
itemID, assetID, assembly,
m_AppDomains[appDomain],
part.ParentGroup.RootPart.Name,
item.Name, startParam, postOnRez,
stateSource, m_MaxScriptQueue);
m_log.DebugFormat("[XEngine] Loaded script {0}.{1}, script UUID {2}, prim UUID {3} @ {4}",
part.ParentGroup.RootPart.Name, item.Name, assetID, part.UUID, part.ParentGroup.RootPart.AbsolutePosition.ToString());
if (presence != null)
{
ShowScriptSaveResponse(item.OwnerID,
assetID, "Compile successful", true);
}
instance.AppDomain = appDomain;
instance.LineMap = linemap;
m_Scripts[itemID] = instance;
}
lock (m_PrimObjects)
{
if (!m_PrimObjects.ContainsKey(localID))
m_PrimObjects[localID] = new List<UUID>();
if (!m_PrimObjects[localID].Contains(itemID))
m_PrimObjects[localID].Add(itemID);
}
if (!m_Assemblies.ContainsKey(assetID))
m_Assemblies[assetID] = assembly;
lock (m_AddingAssemblies)
{
m_AddingAssemblies[assembly]--;
}
if (instance!=null)
instance.Init();
}
return true;
}
public void OnRemoveScript(uint localID, UUID itemID)
{
// If it's not yet been compiled, make sure we don't try
lock (m_CompileDict)
{
if (m_CompileDict.ContainsKey(itemID))
m_CompileDict.Remove(itemID);
}
lock (m_Scripts)
{
// Do we even have it?
if (!m_Scripts.ContainsKey(itemID))
return;
IScriptInstance instance=m_Scripts[itemID];
m_Scripts.Remove(itemID);
instance.ClearQueue();
instance.Stop(0);
// bool objectRemoved = false;
lock (m_PrimObjects)
{
// Remove the script from it's prim
if (m_PrimObjects.ContainsKey(localID))
{
// Remove inventory item record
if (m_PrimObjects[localID].Contains(itemID))
m_PrimObjects[localID].Remove(itemID);
// If there are no more scripts, remove prim
if (m_PrimObjects[localID].Count == 0)
{
m_PrimObjects.Remove(localID);
// objectRemoved = true;
}
}
}
instance.RemoveState();
instance.DestroyScriptInstance();
m_DomainScripts[instance.AppDomain].Remove(instance.ItemID);
if (m_DomainScripts[instance.AppDomain].Count == 0)
{
m_DomainScripts.Remove(instance.AppDomain);
UnloadAppDomain(instance.AppDomain);
}
instance = null;
ObjectRemoved handlerObjectRemoved = OnObjectRemoved;
if (handlerObjectRemoved != null)
{
SceneObjectPart part = m_Scene.GetSceneObjectPart(localID);
handlerObjectRemoved(part.UUID);
}
CleanAssemblies();
}
ScriptRemoved handlerScriptRemoved = OnScriptRemoved;
if (handlerScriptRemoved != null)
handlerScriptRemoved(itemID);
}
public void OnScriptReset(uint localID, UUID itemID)
{
ResetScript(itemID);
}
public void OnStartScript(uint localID, UUID itemID)
{
StartScript(itemID);
}
public void OnStopScript(uint localID, UUID itemID)
{
StopScript(itemID);
}
private void CleanAssemblies()
{
List<UUID> assetIDList = new List<UUID>(m_Assemblies.Keys);
foreach (IScriptInstance i in m_Scripts.Values)
{
if (assetIDList.Contains(i.AssetID))
assetIDList.Remove(i.AssetID);
}
lock (m_AddingAssemblies)
{
foreach (UUID assetID in assetIDList)
{
// Do not remove assembly files if another instance of the script
// is currently initialising
if (!m_AddingAssemblies.ContainsKey(m_Assemblies[assetID])
|| m_AddingAssemblies[m_Assemblies[assetID]] == 0)
{
// m_log.DebugFormat("[XEngine] Removing unreferenced assembly {0}", m_Assemblies[assetID]);
try
{
if (File.Exists(m_Assemblies[assetID]))
File.Delete(m_Assemblies[assetID]);
if (File.Exists(m_Assemblies[assetID]+".text"))
File.Delete(m_Assemblies[assetID]+".text");
if (File.Exists(m_Assemblies[assetID]+".mdb"))
File.Delete(m_Assemblies[assetID]+".mdb");
if (File.Exists(m_Assemblies[assetID]+".map"))
File.Delete(m_Assemblies[assetID]+".map");
}
catch (Exception)
{
}
m_Assemblies.Remove(assetID);
}
}
}
}
private void UnloadAppDomain(UUID id)
{
if (m_AppDomains.ContainsKey(id))
{
AppDomain domain = m_AppDomains[id];
m_AppDomains.Remove(id);
if (domain != AppDomain.CurrentDomain)
AppDomain.Unload(domain);
domain = null;
// m_log.DebugFormat("[XEngine] Unloaded app domain {0}", id.ToString());
}
}
//
// Start processing
//
private void SetupEngine(int minThreads, int maxThreads,
int idleTimeout, ThreadPriority threadPriority,
int maxScriptQueue, int stackSize)
{
m_MaxScriptQueue = maxScriptQueue;
STPStartInfo startInfo = new STPStartInfo();
startInfo.IdleTimeout = idleTimeout*1000; // convert to seconds as stated in .ini
startInfo.MaxWorkerThreads = maxThreads;
startInfo.MinWorkerThreads = minThreads;
startInfo.ThreadPriority = threadPriority;
startInfo.StackSize = stackSize;
startInfo.StartSuspended = true;
m_ThreadPool = new SmartThreadPool(startInfo);
}
//
// Used by script instances to queue event handler jobs
//
public IScriptWorkItem QueueEventHandler(object parms)
{
return new XWorkItem(m_ThreadPool.QueueWorkItem(
new WorkItemCallback(this.ProcessEventHandler),
parms));
}
/// <summary>
/// Process a previously posted script event.
/// </summary>
/// <param name="parms"></param>
/// <returns></returns>
private object ProcessEventHandler(object parms)
{
CultureInfo USCulture = new CultureInfo("en-US");
Thread.CurrentThread.CurrentCulture = USCulture;
IScriptInstance instance = (ScriptInstance) parms;
//m_log.DebugFormat("[XENGINE]: Processing event for {0}", instance);
return instance.EventProcessor();
}
/// <summary>
/// Post event to an entire prim
/// </summary>
/// <param name="localID"></param>
/// <param name="p"></param>
/// <returns></returns>
public bool PostObjectEvent(uint localID, EventParams p)
{
bool result = false;
lock (m_PrimObjects)
{
if (!m_PrimObjects.ContainsKey(localID))
return false;
foreach (UUID itemID in m_PrimObjects[localID])
{
if (m_Scripts.ContainsKey(itemID))
{
IScriptInstance instance = m_Scripts[itemID];
if (instance != null)
{
instance.PostEvent(p);
result = true;
}
}
}
}
return result;
}
/// <summary>
/// Post an event to a single script
/// </summary>
/// <param name="itemID"></param>
/// <param name="p"></param>
/// <returns></returns>
public bool PostScriptEvent(UUID itemID, EventParams p)
{
if (m_Scripts.ContainsKey(itemID))
{
IScriptInstance instance = m_Scripts[itemID];
if (instance != null)
instance.PostEvent(p);
return true;
}
return false;
}
public bool PostScriptEvent(UUID itemID, string name, Object[] p)
{
Object[] lsl_p = new Object[p.Length];
for (int i = 0; i < p.Length ; i++)
{
if (p[i] is int)
lsl_p[i] = new LSL_Types.LSLInteger((int)p[i]);
else if (p[i] is string)
lsl_p[i] = new LSL_Types.LSLString((string)p[i]);
else if (p[i] is Vector3)
lsl_p[i] = new LSL_Types.Vector3(((Vector3)p[i]).X, ((Vector3)p[i]).Y, ((Vector3)p[i]).Z);
else if (p[i] is Quaternion)
lsl_p[i] = new LSL_Types.Quaternion(((Quaternion)p[i]).X, ((Quaternion)p[i]).Y, ((Quaternion)p[i]).Z, ((Quaternion)p[i]).W);
else if (p[i] is float)
lsl_p[i] = new LSL_Types.LSLFloat((float)p[i]);
else
lsl_p[i] = p[i];
}
return PostScriptEvent(itemID, new EventParams(name, lsl_p, new DetectParams[0]));
}
public bool PostObjectEvent(UUID itemID, string name, Object[] p)
{
SceneObjectPart part = m_Scene.GetSceneObjectPart(itemID);
if (part == null)
return false;
Object[] lsl_p = new Object[p.Length];
for (int i = 0; i < p.Length ; i++)
{
if (p[i] is int)
lsl_p[i] = new LSL_Types.LSLInteger((int)p[i]);
else if (p[i] is string)
lsl_p[i] = new LSL_Types.LSLString((string)p[i]);
else if (p[i] is Vector3)
lsl_p[i] = new LSL_Types.Vector3(((Vector3)p[i]).X, ((Vector3)p[i]).Y, ((Vector3)p[i]).Z);
else if (p[i] is Quaternion)
lsl_p[i] = new LSL_Types.Quaternion(((Quaternion)p[i]).X, ((Quaternion)p[i]).Y, ((Quaternion)p[i]).Z, ((Quaternion)p[i]).W);
else if (p[i] is float)
lsl_p[i] = new LSL_Types.LSLFloat((float)p[i]);
else
lsl_p[i] = p[i];
}
return PostObjectEvent(part.LocalId, new EventParams(name, lsl_p, new DetectParams[0]));
}
public Assembly OnAssemblyResolve(object sender,
ResolveEventArgs args)
{
if (!(sender is System.AppDomain))
return null;
string[] pathList = new string[] {"bin", "ScriptEngines",
Path.Combine("ScriptEngines",
m_Scene.RegionInfo.RegionID.ToString())};
string assemblyName = args.Name;
if (assemblyName.IndexOf(",") != -1)
assemblyName = args.Name.Substring(0, args.Name.IndexOf(","));
foreach (string s in pathList)
{
string path = Path.Combine(Directory.GetCurrentDirectory(),
Path.Combine(s, assemblyName))+".dll";
if (File.Exists(path))
return Assembly.LoadFrom(path);
}
return null;
}
private IScriptInstance GetInstance(UUID itemID)
{
IScriptInstance instance;
lock (m_Scripts)
{
if (!m_Scripts.ContainsKey(itemID))
return null;
instance = m_Scripts[itemID];
}
return instance;
}
public void SetScriptState(UUID itemID, bool running)
{
IScriptInstance instance = GetInstance(itemID);
if (instance != null)
{
if (running)
instance.Start();
else
instance.Stop(100);
}
}
public bool GetScriptState(UUID itemID)
{
IScriptInstance instance = GetInstance(itemID);
if (instance != null)
return instance.Running;
return false;
}
public void ApiResetScript(UUID itemID)
{
IScriptInstance instance = GetInstance(itemID);
if (instance != null)
instance.ApiResetScript();
}
public void ResetScript(UUID itemID)
{
IScriptInstance instance = GetInstance(itemID);
if (instance != null)
instance.ResetScript();
}
public void StartScript(UUID itemID)
{
IScriptInstance instance = GetInstance(itemID);
if (instance != null)
instance.Start();
}
public void StopScript(UUID itemID)
{
IScriptInstance instance = GetInstance(itemID);
if (instance != null)
instance.Stop(0);
}
public DetectParams GetDetectParams(UUID itemID, int idx)
{
IScriptInstance instance = GetInstance(itemID);
if (instance != null)
return instance.GetDetectParams(idx);
return null;
}
public void SetMinEventDelay(UUID itemID, double delay)
{
IScriptInstance instance = GetInstance(itemID);
if (instance != null)
instance.MinEventDelay = delay;
}
public UUID GetDetectID(UUID itemID, int idx)
{
IScriptInstance instance = GetInstance(itemID);
if (instance != null)
return instance.GetDetectID(idx);
return UUID.Zero;
}
public void SetState(UUID itemID, string newState)
{
IScriptInstance instance = GetInstance(itemID);
if (instance == null)
return;
instance.SetState(newState);
}
public int GetStartParameter(UUID itemID)
{
IScriptInstance instance = GetInstance(itemID);
if (instance == null)
return 0;
return instance.StartParam;
}
public void OnShutdown()
{
List<IScriptInstance> instances = new List<IScriptInstance>();
lock (m_Scripts)
{
foreach (IScriptInstance instance in m_Scripts.Values)
instances.Add(instance);
}
foreach (IScriptInstance i in instances)
{
// Stop the script, even forcibly if needed. Then flag
// it as shutting down and restore the previous run state
// for serialization, so the scripts don't come back
// dead after region restart
//
bool prevRunning = i.Running;
i.Stop(50);
i.ShuttingDown = true;
i.Running = prevRunning;
}
DoBackup(new Object[] {0});
}
public IScriptApi GetApi(UUID itemID, string name)
{
IScriptInstance instance = GetInstance(itemID);
if (instance == null)
return null;
return instance.GetApi(name);
}
public void OnGetScriptRunning(IClientAPI controllingClient, UUID objectID, UUID itemID)
{
IScriptInstance instance = GetInstance(itemID);
if (instance == null)
return;
IEventQueue eq = World.RequestModuleInterface<IEventQueue>();
if (eq == null)
{
controllingClient.SendScriptRunningReply(objectID, itemID,
GetScriptState(itemID));
}
else
{
eq.Enqueue(EventQueueHelper.ScriptRunningReplyEvent(objectID, itemID, GetScriptState(itemID), true),
controllingClient.AgentId);
}
}
public string GetXMLState(UUID itemID)
{
IScriptInstance instance = GetInstance(itemID);
if (instance == null)
return "";
string xml = instance.GetXMLState();
XmlDocument sdoc = new XmlDocument();
bool loadedState = true;
try
{
sdoc.LoadXml(xml);
}
catch (System.Xml.XmlException e)
{
loadedState = false;
}
XmlNodeList rootL = null;
XmlNode rootNode = null;
if (loadedState)
{
rootL = sdoc.GetElementsByTagName("ScriptState");
rootNode = rootL[0];
}
// Create <State UUID="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx">
XmlDocument doc = new XmlDocument();
XmlElement stateData = doc.CreateElement("", "State", "");
XmlAttribute stateID = doc.CreateAttribute("", "UUID", "");
stateID.Value = itemID.ToString();
stateData.Attributes.Append(stateID);
XmlAttribute assetID = doc.CreateAttribute("", "Asset", "");
assetID.Value = instance.AssetID.ToString();
stateData.Attributes.Append(assetID);
XmlAttribute engineName = doc.CreateAttribute("", "Engine", "");
engineName.Value = ScriptEngineName;
stateData.Attributes.Append(engineName);
doc.AppendChild(stateData);
XmlNode xmlstate = null;
// Add <ScriptState>...</ScriptState>
if (loadedState)
{
xmlstate = doc.ImportNode(rootNode, true);
}
else
{
xmlstate = doc.CreateElement("", "ScriptState", "");
}
stateData.AppendChild(xmlstate);
string assemName = instance.GetAssemblyName();
string fn = Path.GetFileName(assemName);
string assem = String.Empty;
if (File.Exists(assemName + ".text"))
{
FileInfo tfi = new FileInfo(assemName + ".text");
if (tfi != null)
{
Byte[] tdata = new Byte[tfi.Length];
try
{
using (FileStream tfs = File.Open(assemName + ".text",
FileMode.Open, FileAccess.Read))
{
tfs.Read(tdata, 0, tdata.Length);
tfs.Close();
}
assem = new System.Text.ASCIIEncoding().GetString(tdata);
}
catch (Exception e)
{
m_log.DebugFormat("[XEngine]: Unable to open script textfile {0}, reason: {1}", assemName+".text", e.Message);
}
}
}
else
{
FileInfo fi = new FileInfo(assemName);
if (fi != null)
{
Byte[] data = new Byte[fi.Length];
try
{
using (FileStream fs = File.Open(assemName, FileMode.Open, FileAccess.Read))
{
fs.Read(data, 0, data.Length);
fs.Close();
}
assem = System.Convert.ToBase64String(data);
}
catch (Exception e)
{
m_log.DebugFormat("[XEngine]: Unable to open script assembly {0}, reason: {1}", assemName, e.Message);
}
}
}
string map = String.Empty;
if (File.Exists(fn + ".map"))
{
using (FileStream mfs = File.Open(fn + ".map", FileMode.Open, FileAccess.Read))
{
using (StreamReader msr = new StreamReader(mfs))
{
map = msr.ReadToEnd();
msr.Close();
}
mfs.Close();
}
}
XmlElement assemblyData = doc.CreateElement("", "Assembly", "");
XmlAttribute assemblyName = doc.CreateAttribute("", "Filename", "");
assemblyName.Value = fn;
assemblyData.Attributes.Append(assemblyName);
assemblyData.InnerText = assem;
stateData.AppendChild(assemblyData);
XmlElement mapData = doc.CreateElement("", "LineMap", "");
XmlAttribute mapName = doc.CreateAttribute("", "Filename", "");
mapName.Value = fn + ".map";
mapData.Attributes.Append(mapName);
mapData.InnerText = map;
stateData.AppendChild(mapData);
return doc.InnerXml;
}
private bool ShowScriptSaveResponse(UUID ownerID, UUID assetID, string text, bool compiled)
{
return false;
}
public bool SetXMLState(UUID itemID, string xml)
{
if (xml == String.Empty)
return false;
XmlDocument doc = new XmlDocument();
try
{
doc.LoadXml(xml);
}
catch (Exception)
{
m_log.Error("[XEngine]: Exception decoding XML data from region transfer");
return false;
}
XmlNodeList rootL = doc.GetElementsByTagName("State");
if (rootL.Count < 1)
return false;
XmlElement rootE = (XmlElement)rootL[0];
if (rootE.GetAttribute("Engine") != ScriptEngineName)
return false;
// On rez from inventory, that ID will have changed. It was only
// advisory anyway. So we don't check it anymore.
//
// if (rootE.GetAttribute("UUID") != itemID.ToString())
// return;
XmlNodeList stateL = rootE.GetElementsByTagName("ScriptState");
if (stateL.Count != 1)
return false;
XmlElement stateE = (XmlElement)stateL[0];
if (World.m_trustBinaries)
{
XmlNodeList assemL = rootE.GetElementsByTagName("Assembly");
if (assemL.Count != 1)
return false;
XmlElement assemE = (XmlElement)assemL[0];
string fn = assemE.GetAttribute("Filename");
string base64 = assemE.InnerText;
string path = Path.Combine("ScriptEngines", World.RegionInfo.RegionID.ToString());
path = Path.Combine(path, fn);
if (!File.Exists(path))
{
Byte[] filedata = Convert.FromBase64String(base64);
try
{
using (FileStream fs = File.Create(path))
{
fs.Write(filedata, 0, filedata.Length);
fs.Close();
}
}
catch (IOException ex)
{
// if there already exists a file at that location, it may be locked.
m_log.ErrorFormat("[XEngine]: File {0} already exists! {1}", path, ex.Message);
}
try
{
using (FileStream fs = File.Create(path + ".text"))
{
using (StreamWriter sw = new StreamWriter(fs))
{
sw.Write(base64);
sw.Close();
}
fs.Close();
}
}
catch (IOException ex)
{
// if there already exists a file at that location, it may be locked.
m_log.ErrorFormat("[XEngine]: File {0} already exists! {1}", path, ex.Message);
}
}
}
string statepath = Path.Combine("ScriptEngines", World.RegionInfo.RegionID.ToString());
statepath = Path.Combine(statepath, itemID.ToString() + ".state");
try
{
using (FileStream sfs = File.Create(statepath))
{
using (StreamWriter ssw = new StreamWriter(sfs))
{
ssw.Write(stateE.OuterXml);
ssw.Close();
}
sfs.Close();
}
}
catch (IOException ex)
{
// if there already exists a file at that location, it may be locked.
m_log.ErrorFormat("[XEngine]: File {0} already exists! {1}", statepath, ex.Message);
}
XmlNodeList mapL = rootE.GetElementsByTagName("LineMap");
if (mapL.Count > 0)
{
XmlElement mapE = (XmlElement)mapL[0];
string mappath = Path.Combine("ScriptEngines", World.RegionInfo.RegionID.ToString());
mappath = Path.Combine(mappath, mapE.GetAttribute("Filename"));
try
{
using (FileStream mfs = File.Create(mappath))
{
using (StreamWriter msw = new StreamWriter(mfs))
{
msw.Write(mapE.InnerText);
msw.Close();
}
mfs.Close();
}
}
catch (IOException ex)
{
// if there already exists a file at that location, it may be locked.
m_log.ErrorFormat("[XEngine]: File {0} already exists! {1}", statepath, ex.Message);
}
}
return true;
}
public ArrayList GetScriptErrors(UUID itemID)
{
System.Threading.Thread.Sleep(1000);
lock (m_ScriptErrors)
{
if (m_ScriptErrors.ContainsKey(itemID))
{
ArrayList ret = m_ScriptErrors[itemID];
m_ScriptErrors.Remove(itemID);
return ret;
}
return new ArrayList();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using Avalonia.Controls;
using Avalonia.Controls.Platform;
using Avalonia.Controls.Platform.Surfaces;
using Avalonia.Input;
using Avalonia.Input.Raw;
using Avalonia.Native.Interop;
using Avalonia.OpenGL;
using Avalonia.Platform;
using Avalonia.Rendering;
using Avalonia.Threading;
namespace Avalonia.Native
{
internal class MacOSTopLevelWindowHandle : IPlatformHandle, IMacOSTopLevelPlatformHandle
{
IAvnWindowBase _native;
public MacOSTopLevelWindowHandle(IAvnWindowBase native)
{
_native = native;
}
public IntPtr Handle => NSWindow;
public string HandleDescriptor => "NSWindow";
public IntPtr NSView => _native.ObtainNSViewHandle();
public IntPtr NSWindow => _native.ObtainNSWindowHandle();
public IntPtr GetNSViewRetained()
{
return _native.ObtainNSViewHandleRetained();
}
public IntPtr GetNSWindowRetained()
{
return _native.ObtainNSWindowHandleRetained();
}
}
internal abstract class WindowBaseImpl : IWindowBaseImpl,
IFramebufferPlatformSurface, ITopLevelImplWithNativeControlHost
{
protected IInputRoot _inputRoot;
IAvnWindowBase _native;
private object _syncRoot = new object();
private bool _deferredRendering = false;
private bool _gpu = false;
private readonly MouseDevice _mouse;
private readonly IKeyboardDevice _keyboard;
private readonly ICursorFactory _cursorFactory;
private Size _savedLogicalSize;
private Size _lastRenderedLogicalSize;
private double _savedScaling;
private GlPlatformSurface _glSurface;
private NativeControlHostImpl _nativeControlHost;
private IGlContext _glContext;
internal WindowBaseImpl(AvaloniaNativePlatformOptions opts, AvaloniaNativePlatformOpenGlInterface glFeature)
{
_gpu = opts.UseGpu && glFeature != null;
_deferredRendering = opts.UseDeferredRendering;
_keyboard = AvaloniaLocator.Current.GetService<IKeyboardDevice>();
_mouse = new MouseDevice();
_cursorFactory = AvaloniaLocator.Current.GetService<ICursorFactory>();
}
protected void Init(IAvnWindowBase window, IAvnScreens screens, IGlContext glContext)
{
_native = window;
_glContext = glContext;
Handle = new MacOSTopLevelWindowHandle(window);
if (_gpu)
_glSurface = new GlPlatformSurface(window, _glContext);
Screen = new ScreenImpl(screens);
_savedLogicalSize = ClientSize;
_savedScaling = RenderScaling;
_nativeControlHost = new NativeControlHostImpl(_native.CreateNativeControlHost());
var monitor = Screen.AllScreens.OrderBy(x => x.PixelDensity)
.FirstOrDefault(m => m.Bounds.Contains(Position));
Resize(new Size(monitor.WorkingArea.Width * 0.75d, monitor.WorkingArea.Height * 0.7d), PlatformResizeReason.Layout);
}
public Size ClientSize
{
get
{
if (_native != null)
{
var s = _native.ClientSize;
return new Size(s.Width, s.Height);
}
return default;
}
}
public Size? FrameSize
{
get
{
if (_native != null)
{
var s = _native.FrameSize;
return new Size(s.Width, s.Height);
}
return default;
}
}
public IEnumerable<object> Surfaces => new[] {
(_gpu ? _glSurface : (object)null),
this
};
public INativeControlHostImpl NativeControlHost => _nativeControlHost;
public ILockedFramebuffer Lock()
{
var w = _savedLogicalSize.Width * _savedScaling;
var h = _savedLogicalSize.Height * _savedScaling;
var dpi = _savedScaling * 96;
return new DeferredFramebuffer(cb =>
{
lock (_syncRoot)
{
if (_native == null)
return false;
cb(_native);
_lastRenderedLogicalSize = _savedLogicalSize;
return true;
}
}, (int)w, (int)h, new Vector(dpi, dpi));
}
public Action LostFocus { get; set; }
public Action<Rect> Paint { get; set; }
public Action<Size, PlatformResizeReason> Resized { get; set; }
public Action Closed { get; set; }
public IMouseDevice MouseDevice => _mouse;
public abstract IPopupImpl CreatePopup();
protected unsafe class WindowBaseEvents : CallbackBase, IAvnWindowBaseEvents
{
private readonly WindowBaseImpl _parent;
public WindowBaseEvents(WindowBaseImpl parent)
{
_parent = parent;
}
void IAvnWindowBaseEvents.Closed()
{
var n = _parent._native;
try
{
_parent?.Closed?.Invoke();
}
finally
{
_parent?.Dispose();
n?.Dispose();
}
}
void IAvnWindowBaseEvents.Activated() => _parent.Activated?.Invoke();
void IAvnWindowBaseEvents.Deactivated() => _parent.Deactivated?.Invoke();
void IAvnWindowBaseEvents.Paint()
{
Dispatcher.UIThread.RunJobs(DispatcherPriority.Render);
var s = _parent.ClientSize;
_parent.Paint?.Invoke(new Rect(0, 0, s.Width, s.Height));
}
void IAvnWindowBaseEvents.Resized(AvnSize* size, AvnPlatformResizeReason reason)
{
if (_parent?._native != null)
{
var s = new Size(size->Width, size->Height);
_parent._savedLogicalSize = s;
_parent.Resized?.Invoke(s, (PlatformResizeReason)reason);
}
}
void IAvnWindowBaseEvents.PositionChanged(AvnPoint position)
{
_parent.PositionChanged?.Invoke(position.ToAvaloniaPixelPoint());
}
void IAvnWindowBaseEvents.RawMouseEvent(AvnRawMouseEventType type, uint timeStamp, AvnInputModifiers modifiers, AvnPoint point, AvnVector delta)
{
_parent.RawMouseEvent(type, timeStamp, modifiers, point, delta);
}
int IAvnWindowBaseEvents.RawKeyEvent(AvnRawKeyEventType type, uint timeStamp, AvnInputModifiers modifiers, uint key)
{
return _parent.RawKeyEvent(type, timeStamp, modifiers, key).AsComBool();
}
int IAvnWindowBaseEvents.RawTextInputEvent(uint timeStamp, string text)
{
return _parent.RawTextInputEvent(timeStamp, text).AsComBool();
}
void IAvnWindowBaseEvents.ScalingChanged(double scaling)
{
_parent._savedScaling = scaling;
_parent.ScalingChanged?.Invoke(scaling);
}
void IAvnWindowBaseEvents.RunRenderPriorityJobs()
{
Dispatcher.UIThread.RunJobs(DispatcherPriority.Render);
}
void IAvnWindowBaseEvents.LostFocus()
{
_parent.LostFocus?.Invoke();
}
public AvnDragDropEffects DragEvent(AvnDragEventType type, AvnPoint position,
AvnInputModifiers modifiers,
AvnDragDropEffects effects,
IAvnClipboard clipboard, IntPtr dataObjectHandle)
{
var device = AvaloniaLocator.Current.GetService<IDragDropDevice>();
IDataObject dataObject = null;
if (dataObjectHandle != IntPtr.Zero)
dataObject = GCHandle.FromIntPtr(dataObjectHandle).Target as IDataObject;
using(var clipboardDataObject = new ClipboardDataObject(clipboard))
{
if (dataObject == null)
dataObject = clipboardDataObject;
var args = new RawDragEvent(device, (RawDragEventType)type,
_parent._inputRoot, position.ToAvaloniaPoint(), dataObject, (DragDropEffects)effects,
(RawInputModifiers)modifiers);
_parent.Input(args);
return (AvnDragDropEffects)args.Effects;
}
}
}
public void Activate()
{
_native.Activate();
}
public bool RawTextInputEvent(uint timeStamp, string text)
{
if (_inputRoot is null)
return false;
Dispatcher.UIThread.RunJobs(DispatcherPriority.Input + 1);
var args = new RawTextInputEventArgs(_keyboard, timeStamp, _inputRoot, text);
Input?.Invoke(args);
return args.Handled;
}
public bool RawKeyEvent(AvnRawKeyEventType type, uint timeStamp, AvnInputModifiers modifiers, uint key)
{
if (_inputRoot is null)
return false;
Dispatcher.UIThread.RunJobs(DispatcherPriority.Input + 1);
var args = new RawKeyEventArgs(_keyboard, timeStamp, _inputRoot, (RawKeyEventType)type, (Key)key, (RawInputModifiers)modifiers);
Input?.Invoke(args);
return args.Handled;
}
protected virtual bool ChromeHitTest(RawPointerEventArgs e)
{
return false;
}
public void RawMouseEvent(AvnRawMouseEventType type, uint timeStamp, AvnInputModifiers modifiers, AvnPoint point, AvnVector delta)
{
if (_inputRoot is null)
return;
Dispatcher.UIThread.RunJobs(DispatcherPriority.Input + 1);
switch (type)
{
case AvnRawMouseEventType.Wheel:
Input?.Invoke(new RawMouseWheelEventArgs(_mouse, timeStamp, _inputRoot, point.ToAvaloniaPoint(), new Vector(delta.X, delta.Y), (RawInputModifiers)modifiers));
break;
default:
var e = new RawPointerEventArgs(_mouse, timeStamp, _inputRoot, (RawPointerEventType)type, point.ToAvaloniaPoint(), (RawInputModifiers)modifiers);
if(!ChromeHitTest(e))
{
Input?.Invoke(e);
}
break;
}
}
public void Resize(Size clientSize, PlatformResizeReason reason)
{
_native.Resize(clientSize.Width, clientSize.Height, (AvnPlatformResizeReason)reason);
}
public IRenderer CreateRenderer(IRenderRoot root)
{
if (_deferredRendering)
{
var loop = AvaloniaLocator.Current.GetService<IRenderLoop>();
var customRendererFactory = AvaloniaLocator.Current.GetService<IRendererFactory>();
if (customRendererFactory != null)
return customRendererFactory.Create(root, loop);
return new DeferredRenderer(root, loop);
}
return new ImmediateRenderer(root);
}
public virtual void Dispose()
{
_native?.Close();
_native?.Dispose();
_native = null;
_nativeControlHost?.Dispose();
_nativeControlHost = null;
(Screen as ScreenImpl)?.Dispose();
_mouse.Dispose();
}
public void Invalidate(Rect rect)
{
_native?.Invalidate(new AvnRect { Height = rect.Height, Width = rect.Width, X = rect.X, Y = rect.Y });
}
public void SetInputRoot(IInputRoot inputRoot)
{
_inputRoot = inputRoot;
}
public virtual void Show(bool activate, bool isDialog)
{
_native.Show(activate.AsComBool(), isDialog.AsComBool());
}
public PixelPoint Position
{
get => _native.Position.ToAvaloniaPixelPoint();
set => _native.SetPosition(value.ToAvnPoint());
}
public Point PointToClient(PixelPoint point)
{
return _native?.PointToClient(point.ToAvnPoint()).ToAvaloniaPoint() ?? default;
}
public PixelPoint PointToScreen(Point point)
{
return _native?.PointToScreen(point.ToAvnPoint()).ToAvaloniaPixelPoint() ?? default;
}
public void Hide()
{
_native.Hide();
}
public void BeginMoveDrag(PointerPressedEventArgs e)
{
_native.BeginMoveDrag();
}
public Size MaxAutoSizeHint => Screen.AllScreens.Select(s => s.Bounds.Size.ToSize(1))
.OrderByDescending(x => x.Width + x.Height).FirstOrDefault();
public void SetTopmost(bool value)
{
_native.SetTopMost(value.AsComBool());
}
public double RenderScaling => _native?.Scaling ?? 1;
public double DesktopScaling => 1;
public Action Deactivated { get; set; }
public Action Activated { get; set; }
public void SetCursor(ICursorImpl cursor)
{
if (_native == null)
{
return;
}
var newCursor = cursor as AvaloniaNativeCursor;
newCursor = newCursor ?? (_cursorFactory.GetCursor(StandardCursorType.Arrow) as AvaloniaNativeCursor);
_native.SetCursor(newCursor.Cursor);
}
public Action<PixelPoint> PositionChanged { get; set; }
public Action<RawInputEventArgs> Input { get; set; }
public Action<double> ScalingChanged { get; set; }
public Action<WindowTransparencyLevel> TransparencyLevelChanged { get; set; }
public IScreenImpl Screen { get; private set; }
// TODO
public void SetMinMaxSize(Size minSize, Size maxSize)
{
_native.SetMinMaxSize(minSize.ToAvnSize(), maxSize.ToAvnSize());
}
public void BeginResizeDrag(WindowEdge edge, PointerPressedEventArgs e)
{
}
internal void BeginDraggingSession(AvnDragDropEffects effects, AvnPoint point, IAvnClipboard clipboard,
IAvnDndResultCallback callback, IntPtr sourceHandle)
{
_native.BeginDragAndDropOperation(effects, point, clipboard, callback, sourceHandle);
}
public void SetTransparencyLevelHint(WindowTransparencyLevel transparencyLevel)
{
if (TransparencyLevel != transparencyLevel)
{
if (transparencyLevel >= WindowTransparencyLevel.Blur)
{
transparencyLevel = WindowTransparencyLevel.AcrylicBlur;
}
if(transparencyLevel == WindowTransparencyLevel.None)
{
transparencyLevel = WindowTransparencyLevel.Transparent;
}
TransparencyLevel = transparencyLevel;
_native?.SetBlurEnabled((TransparencyLevel >= WindowTransparencyLevel.Blur).AsComBool());
TransparencyLevelChanged?.Invoke(TransparencyLevel);
}
}
public WindowTransparencyLevel TransparencyLevel { get; private set; } = WindowTransparencyLevel.Transparent;
public AcrylicPlatformCompensationLevels AcrylicCompensationLevels { get; } = new AcrylicPlatformCompensationLevels(1, 0, 0);
public IPlatformHandle Handle { get; private set; }
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System.Collections.Generic;
using QuantConnect.Data;
using QuantConnect.Indicators;
using QuantConnect.Orders;
using QuantConnect.Securities;
namespace QuantConnect.Algorithm.CSharp
{
public class HistoryAndWarmupRegressionAlgorithm : QCAlgorithm
{
private const string SPY = "SPY";
private const string GOOG = "GOOG";
private const string IBM = "IBM";
private const string BAC = "BAC";
private const string GOOGL = "GOOGL";
private readonly Dictionary<Symbol, SymbolData> _sd = new Dictionary<Symbol, SymbolData>();
public override void Initialize()
{
SetStartDate(2013, 10, 08);
SetEndDate(2013, 10, 11);
SetCash(1000000);
AddSecurity(SecurityType.Equity, SPY, Resolution.Minute);
AddSecurity(SecurityType.Equity, IBM, Resolution.Minute);
AddSecurity(SecurityType.Equity, BAC, Resolution.Minute);
AddSecurity(SecurityType.Equity, GOOG, Resolution.Daily);
AddSecurity(SecurityType.Equity, GOOGL, Resolution.Daily);
foreach (var security in Securities)
{
_sd.Add(security.Key, new SymbolData(security.Key, this));
}
// we want to warm up our algorithm
SetWarmup(SymbolData.RequiredBarsWarmup);
}
public override void OnData(Slice data)
{
// we are only using warmup for indicator spooling, so wait for us to be warm then continue
if (IsWarmingUp) return;
foreach (var sd in _sd.Values)
{
var lastPriceTime = sd.Close.Current.Time;
// only make decisions when we have data on our requested resolution
if (lastPriceTime.RoundDown(sd.Security.Resolution.ToTimeSpan()) == lastPriceTime)
{
sd.Update();
}
}
}
public override void OnOrderEvent(OrderEvent fill)
{
SymbolData sd;
if (_sd.TryGetValue(fill.Symbol, out sd))
{
sd.OnOrderEvent(fill);
}
}
class SymbolData
{
public const int RequiredBarsWarmup = 40;
public const decimal PercentTolerance = 0.001m;
public const decimal PercentGlobalStopLoss = 0.01m;
private const int LotSize = 10;
public readonly Symbol Symbol;
public readonly Security Security;
public decimal Quantity
{
get { return Security.Holdings.Quantity; }
}
public readonly Identity Close;
public readonly AverageDirectionalIndex ADX;
public readonly ExponentialMovingAverage EMA;
public readonly MovingAverageConvergenceDivergence MACD;
private readonly QCAlgorithm _algorithm;
private OrderTicket _currentStopLoss;
public SymbolData(Symbol symbol, QCAlgorithm algorithm)
{
Symbol = symbol;
Security = algorithm.Securities[symbol];
Close = algorithm.Identity(symbol);
ADX = algorithm.ADX(symbol, 14);
EMA = algorithm.EMA(symbol, 14);
MACD = algorithm.MACD(symbol, 12, 26, 9);
// if we're receiving daily
_algorithm = algorithm;
}
public bool IsReady
{
get { return Close.IsReady && ADX.IsReady & EMA.IsReady && MACD.IsReady; }
}
public bool IsUptrend
{
get
{
const decimal tolerance = 1 + PercentTolerance;
return MACD.Signal > MACD*tolerance
&& EMA > Close*tolerance;
}
}
public bool IsDowntrend
{
get
{
const decimal tolerance = 1 - PercentTolerance;
return MACD.Signal < MACD*tolerance
&& EMA < Close*tolerance;
}
}
public void OnOrderEvent(OrderEvent fill)
{
if (fill.Status != OrderStatus.Filled)
{
return;
}
// if we just finished entering, place a stop loss as well
if (Security.Invested)
{
var stop = Security.Holdings.IsLong
? fill.FillPrice*(1 - PercentGlobalStopLoss)
: fill.FillPrice*(1 + PercentGlobalStopLoss);
_currentStopLoss = _algorithm.StopMarketOrder(Symbol, -Quantity, stop, "StopLoss at: " + stop);
}
// check for an exit, cancel the stop loss
else
{
if (_currentStopLoss != null && _currentStopLoss.Status.IsOpen())
{
// cancel our current stop loss
_currentStopLoss.Cancel("Exited position");
_currentStopLoss = null;
}
}
}
public void Update()
{
OrderTicket ticket;
TryEnter(out ticket);
TryExit(out ticket);
}
public bool TryEnter(out OrderTicket ticket)
{
ticket = null;
if (Security.Invested)
{
// can't enter if we're already in
return false;
}
int qty = 0;
decimal limit = 0m;
if (IsUptrend)
{
// 100 order lots
qty = LotSize;
limit = Security.Low;
}
else if (IsDowntrend)
{
limit = Security.High;
qty = -LotSize;
}
if (qty != 0)
{
ticket = _algorithm.LimitOrder(Symbol, qty, limit, "TryEnter at: " + limit);
}
return qty != 0;
}
public bool TryExit(out OrderTicket ticket)
{
const decimal exitTolerance = 1 + 2 * PercentTolerance;
ticket = null;
if (!Security.Invested)
{
// can't exit if we haven't entered
return false;
}
decimal limit = 0m;
if (Security.Holdings.IsLong && Close*exitTolerance < EMA)
{
limit = Security.High;
}
else if (Security.Holdings.IsShort && Close > EMA*exitTolerance)
{
limit = Security.Low;
}
if (limit != 0)
{
ticket = _algorithm.LimitOrder(Symbol, -Quantity, limit, "TryExit at: " + limit);
}
return -Quantity != 0;
}
}
}
}
| |
using System;
using System.Globalization;
/// <summary>
/// Convert.ToUInt32(String,IFormatProvider)
/// </summary>
public class ConvertToUInt3218
{
public static int Main()
{
ConvertToUInt3218 convertToUInt3218 = new ConvertToUInt3218();
TestLibrary.TestFramework.BeginTestCase("ConvertToUInt3218");
if (convertToUInt3218.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
retVal = PosTest5() && retVal;
retVal = PosTest6() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
retVal = NegTest4() && retVal;
return retVal;
}
#region PositiveTest
public bool PosTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest1: Convert to UInt32 from string 1");
try
{
string strVal = UInt32.MaxValue.ToString();
uint uintVal = Convert.ToUInt32(strVal, null);
if (uintVal != UInt32.MaxValue)
{
TestLibrary.TestFramework.LogError("001", "The ExpectResult is not the ActualResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest2: Convert to UInt32 from string 2");
try
{
string strVal = UInt32.MaxValue.ToString();
CultureInfo myculture = new CultureInfo("en-us");
IFormatProvider provider = myculture.NumberFormat;
uint uintVal = Convert.ToUInt32(strVal, provider);
if (uintVal != UInt32.MaxValue)
{
TestLibrary.TestFramework.LogError("003", "The ExpectResult is not the ActualResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest3: Convert to UInt32 from string 3");
try
{
string strVal = UInt32.MinValue.ToString();
uint uintVal = Convert.ToUInt32(strVal, null);
if (uintVal != UInt32.MinValue)
{
TestLibrary.TestFramework.LogError("005", "The ExpectResult is not the ActualResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest4: Convert to UInt32 from string 4");
try
{
string strVal = "-" + UInt32.MinValue.ToString();
uint uintVal = Convert.ToUInt32(strVal, null);
if (uintVal != UInt32.MinValue)
{
TestLibrary.TestFramework.LogError("007", "The ExpectResult is not the ActualResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest5()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest5: Convert to UInt32 from string 5");
try
{
uint sourceVal = (UInt32)this.GetInt32(0, Int32.MaxValue) + (UInt32)this.GetInt32(0, Int32.MaxValue);
string strVal = "+" + sourceVal.ToString();
uint uintVal = Convert.ToUInt32(strVal, null);
if (uintVal != sourceVal)
{
TestLibrary.TestFramework.LogError("009", "The ExpectResult is not the ActualResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("010", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest6()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest6: Convert to UInt32 from string 6");
try
{
string strVal = null;
uint uintVal = Convert.ToUInt32(strVal, null);
if (uintVal != 0)
{
TestLibrary.TestFramework.LogError("011", "The ExpectResult is not the ActualResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("012", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
#endregion
#region NegativeTest
public bool NegTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest1: the string represents a number less than MinValue");
try
{
int intVal = this.GetInt32(1, Int32.MaxValue);
string strVal = "-" + intVal.ToString();
uint uintVal = Convert.ToUInt32(strVal, null);
TestLibrary.TestFramework.LogError("N001", "the string represents a number less than MinValue but not throw exception");
retVal = false;
}
catch (OverflowException) { }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("N002", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest2: the string represents a number greater than MaxValue");
try
{
UInt64 intVal = (UInt64)UInt32.MaxValue + (UInt64)this.GetInt32(1, Int32.MaxValue);
string strVal = intVal.ToString();
uint uintVal = Convert.ToUInt32(strVal, null);
TestLibrary.TestFramework.LogError("N003", "the string represents a number greater than MaxValue but not throw exception");
retVal = false;
}
catch (OverflowException) { }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("N004", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool NegTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest3: the string does not consist of an optional sign followed by a sequence of digits ");
try
{
string strVal = "helloworld";
uint uintVal = Convert.ToUInt32(strVal, null);
TestLibrary.TestFramework.LogError("N005", "the string does not consist of an optional sign followed by a sequence of digits but not throw exception");
retVal = false;
}
catch (FormatException) { }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("N006", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool NegTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest4: the string is empty string");
try
{
string strVal = string.Empty;
uint uintVal = Convert.ToUInt32(strVal, null);
TestLibrary.TestFramework.LogError("N007", "the string is empty string but not throw exception");
retVal = false;
}
catch (FormatException) { }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("N008", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
#endregion
#region HelpMethod
private Int32 GetInt32(Int32 minValue, Int32 maxValue)
{
try
{
if (minValue == maxValue)
{
return minValue;
}
if (minValue < maxValue)
{
return minValue + TestLibrary.Generator.GetInt32(-55) % (maxValue - minValue);
}
}
catch
{
throw;
}
return minValue;
}
#endregion
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime;
using System.Runtime.Serialization;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Orleans.CodeGeneration;
using Orleans.GrainDirectory;
using Orleans.Providers;
using Orleans.Runtime.Configuration;
using Orleans.Runtime.ConsistentRing;
using Orleans.Runtime.Placement;
using Orleans.Runtime.Counters;
using Orleans.Runtime.MultiClusterNetwork;
using Orleans.Runtime.GrainDirectory;
using Orleans.Runtime.MembershipService;
using Orleans.Runtime.Messaging;
using Orleans.Runtime.Providers;
using Orleans.Runtime.Scheduler;
using Orleans.Runtime.Startup;
using Orleans.Runtime.Storage;
using Orleans.Serialization;
using Orleans.Storage;
using Orleans.Streams;
using Orleans.Timers;
using Orleans.MultiCluster;
namespace Orleans.Runtime
{
/// <summary>
/// Orleans silo.
/// </summary>
public class Silo : MarshalByRefObject // for hosting multiple silos in app domains of the same process
{
/// <summary> Standard name for Primary silo. </summary>
public const string PrimarySiloName = "Primary";
/// <summary> Silo Types. </summary>
public enum SiloType
{
/// <summary> No silo type specified. </summary>
None = 0,
/// <summary> Primary silo. </summary>
Primary,
/// <summary> Secondary silo. </summary>
Secondary,
}
/// <summary> Type of this silo. </summary>
public SiloType Type
{
get { return siloType; }
}
private readonly GlobalConfiguration globalConfig;
private NodeConfiguration nodeConfig;
private readonly ISiloMessageCenter messageCenter;
private readonly OrleansTaskScheduler scheduler;
private readonly LocalGrainDirectory localGrainDirectory;
private readonly ActivationDirectory activationDirectory;
private readonly IncomingMessageAgent incomingAgent;
private readonly IncomingMessageAgent incomingSystemAgent;
private readonly IncomingMessageAgent incomingPingAgent;
private readonly Logger logger;
private readonly GrainTypeManager typeManager;
private readonly ManualResetEvent siloTerminatedEvent;
private readonly SiloType siloType;
private readonly SiloStatisticsManager siloStatistics;
private readonly MembershipFactory membershipFactory;
private readonly MultiClusterOracleFactory multiClusterFactory;
private StorageProviderManager storageProviderManager;
private StatisticsProviderManager statisticsProviderManager;
private BootstrapProviderManager bootstrapProviderManager;
private readonly LocalReminderServiceFactory reminderFactory;
private IReminderService reminderService;
private ProviderManagerSystemTarget providerManagerSystemTarget;
private IMembershipOracle membershipOracle;
private IMultiClusterOracle multiClusterOracle;
private ClientObserverRegistrar clientRegistrar;
private Watchdog platformWatchdog;
private readonly TimeSpan initTimeout;
private readonly TimeSpan stopTimeout = TimeSpan.FromMinutes(1);
private readonly Catalog catalog;
private readonly List<IHealthCheckParticipant> healthCheckParticipants;
private readonly object lockable = new object();
private readonly GrainFactory grainFactory;
private readonly IGrainRuntime grainRuntime;
private readonly List<IProvider> allSiloProviders;
internal readonly string Name;
internal readonly string SiloIdentity;
internal ClusterConfiguration OrleansConfig { get; private set; }
internal GlobalConfiguration GlobalConfig { get { return globalConfig; } }
internal NodeConfiguration LocalConfig { get { return nodeConfig; } }
internal ISiloMessageCenter LocalMessageCenter { get { return messageCenter; } }
internal OrleansTaskScheduler LocalScheduler { get { return scheduler; } }
internal GrainTypeManager LocalTypeManager { get { return typeManager; } }
internal ILocalGrainDirectory LocalGrainDirectory { get { return localGrainDirectory; } }
internal ISiloStatusOracle LocalSiloStatusOracle { get { return membershipOracle; } }
internal IMultiClusterOracle LocalMultiClusterOracle { get { return multiClusterOracle; } }
internal IConsistentRingProvider RingProvider { get; private set; }
internal IStorageProviderManager StorageProviderManager { get { return storageProviderManager; } }
internal IProviderManager StatisticsProviderManager { get { return statisticsProviderManager; } }
internal IList<IBootstrapProvider> BootstrapProviders { get; private set; }
internal ISiloPerformanceMetrics Metrics { get { return siloStatistics.MetricsTable; } }
internal static Silo CurrentSilo { get; private set; }
internal IReadOnlyCollection<IProvider> AllSiloProviders
{
get { return allSiloProviders.AsReadOnly(); }
}
internal IServiceProvider Services { get; }
/// <summary> Get the id of the cluster this silo is part of. </summary>
public string ClusterId
{
get { return globalConfig.HasMultiClusterNetwork ? globalConfig.ClusterId : null; }
}
/// <summary> SiloAddress for this silo. </summary>
public SiloAddress SiloAddress { get { return messageCenter.MyAddress; } }
/// <summary>
/// Silo termination event used to signal shutdown of this silo.
/// </summary>
public WaitHandle SiloTerminatedEvent { get { return siloTerminatedEvent; } } // one event for all types of termination (shutdown, stop and fast kill).
/// <summary>
/// Test hook connection for white-box testing of silo.
/// </summary>
public TestHooks TestHook;
/// <summary>
/// Creates and initializes the silo from the specified config data.
/// </summary>
/// <param name="name">Name of this silo.</param>
/// <param name="siloType">Type of this silo.</param>
/// <param name="config">Silo config data to be used for this silo.</param>
public Silo(string name, SiloType siloType, ClusterConfiguration config)
: this(name, siloType, config, null)
{
}
/// <summary>
/// Creates and initializes the silo from the specified config data.
/// </summary>
/// <param name="name">Name of this silo.</param>
/// <param name="siloType">Type of this silo.</param>
/// <param name="config">Silo config data to be used for this silo.</param>
/// <param name="keyStore">Local data store, mostly used for testing, shared between all silos running in same process.</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope",
Justification = "Should not Dispose of messageCenter in this method because it continues to run / exist after this point.")]
internal Silo(string name, SiloType siloType, ClusterConfiguration config, ILocalDataStore keyStore)
{
SystemStatus.Current = SystemStatus.Creating;
CurrentSilo = this;
var startTime = DateTime.UtcNow;
this.siloType = siloType;
Name = name;
siloTerminatedEvent = new ManualResetEvent(false);
OrleansConfig = config;
globalConfig = config.Globals;
config.OnConfigChange("Defaults", () => nodeConfig = config.GetOrCreateNodeConfigurationForSilo(name));
if (!LogManager.IsInitialized)
LogManager.Initialize(nodeConfig);
config.OnConfigChange("Defaults/Tracing", () => LogManager.Initialize(nodeConfig, true), false);
MultiClusterRegistrationStrategy.Initialize();
ActivationData.Init(config, nodeConfig);
StatisticsCollector.Initialize(nodeConfig);
SerializationManager.Initialize(globalConfig.UseStandardSerializer, globalConfig.SerializationProviders, globalConfig.UseJsonFallbackSerializer);
initTimeout = globalConfig.MaxJoinAttemptTime;
if (Debugger.IsAttached)
{
initTimeout = StandardExtensions.Max(TimeSpan.FromMinutes(10), globalConfig.MaxJoinAttemptTime);
stopTimeout = initTimeout;
}
IPEndPoint here = nodeConfig.Endpoint;
int generation = nodeConfig.Generation;
if (generation == 0)
{
generation = SiloAddress.AllocateNewGeneration();
nodeConfig.Generation = generation;
}
LogManager.MyIPEndPoint = here;
logger = LogManager.GetLogger("Silo", LoggerType.Runtime);
logger.Info(ErrorCode.SiloGcSetting, "Silo starting with GC settings: ServerGC={0} GCLatencyMode={1}", GCSettings.IsServerGC, Enum.GetName(typeof(GCLatencyMode), GCSettings.LatencyMode));
if (!GCSettings.IsServerGC || !GCSettings.LatencyMode.Equals(GCLatencyMode.Batch))
{
logger.Warn(ErrorCode.SiloGcWarning, "Note: Silo not running with ServerGC turned on or with GCLatencyMode.Batch enabled - recommend checking app config : <configuration>-<runtime>-<gcServer enabled=\"true\"> and <configuration>-<runtime>-<gcConcurrent enabled=\"false\"/>");
logger.Warn(ErrorCode.SiloGcWarning, "Note: ServerGC only kicks in on multi-core systems (settings enabling ServerGC have no effect on single-core machines).");
}
logger.Info(ErrorCode.SiloInitializing, "-------------- Initializing {0} silo on host {1} MachineName {2} at {3}, gen {4} --------------",
siloType, nodeConfig.DNSHostName, Environment.MachineName, here, generation);
logger.Info(ErrorCode.SiloInitConfig, "Starting silo {0} with runtime Version='{1}' .NET version='{2}' Is .NET 4.5={3} OS version='{4}' Config= " + Environment.NewLine + "{5}",
name, RuntimeVersion.Current, Environment.Version, ConfigUtilities.IsNet45OrNewer(), Environment.OSVersion, config.ToString(name));
if (keyStore != null)
{
// Re-establish reference to shared local key store in this app domain
LocalDataStoreInstance.LocalDataStore = keyStore;
}
// Configure DI using Startup type
bool usingCustomServiceProvider;
Services = StartupBuilder.ConfigureStartup(nodeConfig.StartupTypeName, out usingCustomServiceProvider);
healthCheckParticipants = new List<IHealthCheckParticipant>();
allSiloProviders = new List<IProvider>();
BufferPool.InitGlobalBufferPool(globalConfig);
PlacementStrategy.Initialize(globalConfig);
UnobservedExceptionsHandlerClass.SetUnobservedExceptionHandler(UnobservedExceptionHandler);
AppDomain.CurrentDomain.UnhandledException +=
(obj, ev) => DomainUnobservedExceptionHandler(obj, (Exception)ev.ExceptionObject);
grainFactory = new GrainFactory();
typeManager = new GrainTypeManager(
here.Address.Equals(IPAddress.Loopback),
grainFactory,
new SiloAssemblyLoader(OrleansConfig.Defaults.AdditionalAssemblyDirectories));
// Performance metrics
siloStatistics = new SiloStatisticsManager(globalConfig, nodeConfig);
config.OnConfigChange("Defaults/LoadShedding", () => siloStatistics.MetricsTable.NodeConfig = nodeConfig, false);
// The scheduler
scheduler = new OrleansTaskScheduler(globalConfig, nodeConfig);
healthCheckParticipants.Add(scheduler);
// Initialize the message center
var mc = new MessageCenter(here, generation, globalConfig, siloStatistics.MetricsTable);
if (nodeConfig.IsGatewayNode)
mc.InstallGateway(nodeConfig.ProxyGatewayEndpoint);
messageCenter = mc;
SiloIdentity = SiloAddress.ToLongString();
// GrainRuntime can be created only here, after messageCenter was created.
grainRuntime = new GrainRuntime(
globalConfig.ServiceId,
SiloIdentity,
grainFactory,
new TimerRegistry(),
new ReminderRegistry(),
new StreamProviderManager(),
Services);
// Now the router/directory service
// This has to come after the message center //; note that it then gets injected back into the message center.;
localGrainDirectory = new LocalGrainDirectory(this);
RegistrarManager.InitializeGrainDirectoryManager(localGrainDirectory);
// Now the activation directory.
// This needs to know which router to use so that it can keep the global directory in synch with the local one.
activationDirectory = new ActivationDirectory();
// Now the consistent ring provider
RingProvider = GlobalConfig.UseVirtualBucketsConsistentRing ?
(IConsistentRingProvider) new VirtualBucketsRingProvider(SiloAddress, GlobalConfig.NumVirtualBucketsConsistentRing)
: new ConsistentRingProvider(SiloAddress);
// to preserve backwards compatibility, only use the service provider to inject grain dependencies if the user supplied his own
// service provider, meaning that he is explicitly opting into it.
var grainCreator = new GrainCreator(grainRuntime, usingCustomServiceProvider ? Services : null);
Action<Dispatcher> setDispatcher;
catalog = new Catalog(Constants.CatalogId, SiloAddress, Name, LocalGrainDirectory, typeManager, scheduler, activationDirectory, config, grainCreator, out setDispatcher);
var dispatcher = new Dispatcher(scheduler, messageCenter, catalog, config);
setDispatcher(dispatcher);
RuntimeClient.Current = new InsideRuntimeClient(
dispatcher,
catalog,
LocalGrainDirectory,
SiloAddress,
config,
RingProvider,
typeManager,
grainFactory);
messageCenter.RerouteHandler = InsideRuntimeClient.Current.RerouteMessage;
messageCenter.SniffIncomingMessage = InsideRuntimeClient.Current.SniffIncomingMessage;
siloStatistics.MetricsTable.Scheduler = scheduler;
siloStatistics.MetricsTable.ActivationDirectory = activationDirectory;
siloStatistics.MetricsTable.ActivationCollector = catalog.ActivationCollector;
siloStatistics.MetricsTable.MessageCenter = messageCenter;
DeploymentLoadPublisher.CreateDeploymentLoadPublisher(this, globalConfig);
PlacementDirectorsManager.CreatePlacementDirectorsManager(globalConfig);
// Now the incoming message agents
incomingSystemAgent = new IncomingMessageAgent(Message.Categories.System, messageCenter, activationDirectory, scheduler, dispatcher);
incomingPingAgent = new IncomingMessageAgent(Message.Categories.Ping, messageCenter, activationDirectory, scheduler, dispatcher);
incomingAgent = new IncomingMessageAgent(Message.Categories.Application, messageCenter, activationDirectory, scheduler, dispatcher);
membershipFactory = new MembershipFactory();
multiClusterFactory = new MultiClusterOracleFactory();
reminderFactory = new LocalReminderServiceFactory();
SystemStatus.Current = SystemStatus.Created;
StringValueStatistic.FindOrCreate(StatisticNames.SILO_START_TIME,
() => LogFormatter.PrintDate(startTime)); // this will help troubleshoot production deployment when looking at MDS logs.
TestHook = new TestHooks(this);
logger.Info(ErrorCode.SiloInitializingFinished, "-------------- Started silo {0}, ConsistentHashCode {1:X} --------------", SiloAddress.ToLongString(), SiloAddress.GetConsistentHashCode());
}
private void CreateSystemTargets()
{
logger.Verbose("Creating System Targets for this silo.");
logger.Verbose("Creating {0} System Target", "SiloControl");
RegisterSystemTarget(new SiloControl(this));
logger.Verbose("Creating {0} System Target", "DeploymentLoadPublisher");
RegisterSystemTarget(DeploymentLoadPublisher.Instance);
logger.Verbose("Creating {0} System Target", "RemGrainDirectory + CacheValidator");
RegisterSystemTarget(LocalGrainDirectory.RemGrainDirectory);
RegisterSystemTarget(LocalGrainDirectory.CacheValidator);
logger.Verbose("Creating {0} System Target", "ClientObserverRegistrar + TypeManager");
clientRegistrar = new ClientObserverRegistrar(SiloAddress, LocalGrainDirectory, LocalScheduler, OrleansConfig);
RegisterSystemTarget(clientRegistrar);
RegisterSystemTarget(new TypeManager(SiloAddress, LocalTypeManager));
logger.Verbose("Creating {0} System Target", "MembershipOracle");
RegisterSystemTarget((SystemTarget) membershipOracle);
if (multiClusterOracle != null)
{
logger.Verbose("Creating {0} System Target", "MultiClusterOracle");
RegisterSystemTarget((SystemTarget)multiClusterOracle);
}
logger.Verbose("Finished creating System Targets for this silo.");
}
private void InjectDependencies()
{
healthCheckParticipants.Add(membershipOracle);
catalog.SiloStatusOracle = LocalSiloStatusOracle;
localGrainDirectory.CatalogSiloStatusListener = catalog;
LocalSiloStatusOracle.SubscribeToSiloStatusEvents(localGrainDirectory);
messageCenter.SiloDeadOracle = LocalSiloStatusOracle.IsDeadSilo;
// consistentRingProvider is not a system target per say, but it behaves like the localGrainDirectory, so it is here
LocalSiloStatusOracle.SubscribeToSiloStatusEvents((ISiloStatusListener)RingProvider);
LocalSiloStatusOracle.SubscribeToSiloStatusEvents(DeploymentLoadPublisher.Instance);
if (!globalConfig.ReminderServiceType.Equals(GlobalConfiguration.ReminderServiceProviderType.Disabled))
{
// start the reminder service system target
reminderService = reminderFactory.CreateReminderService(this, grainFactory, initTimeout);
RegisterSystemTarget((SystemTarget) reminderService);
}
RegisterSystemTarget(catalog);
scheduler.QueueAction(catalog.Start, catalog.SchedulingContext)
.WaitWithThrow(initTimeout);
// SystemTarget for provider init calls
providerManagerSystemTarget = new ProviderManagerSystemTarget(this);
RegisterSystemTarget(providerManagerSystemTarget);
}
private async Task CreateSystemGrains()
{
if (siloType == SiloType.Primary)
await membershipFactory.CreateMembershipTableProvider(catalog, this).WithTimeout(initTimeout);
}
/// <summary> Perform silo startup operations. </summary>
public void Start()
{
try
{
DoStart();
}
catch (Exception exc)
{
logger.Error(ErrorCode.SiloStartError, "Exception during Silo.Start", exc);
throw;
}
}
private void DoStart()
{
lock (lockable)
{
if (!SystemStatus.Current.Equals(SystemStatus.Created))
throw new InvalidOperationException(String.Format("Calling Silo.Start() on a silo which is not in the Created state. This silo is in the {0} state.", SystemStatus.Current));
SystemStatus.Current = SystemStatus.Starting;
}
logger.Info(ErrorCode.SiloStarting, "Silo Start()");
// Hook up to receive notification of process exit / Ctrl-C events
AppDomain.CurrentDomain.ProcessExit += HandleProcessExit;
Console.CancelKeyPress += HandleProcessExit;
ConfigureThreadPoolAndServicePointSettings();
// This has to start first so that the directory system target factory gets loaded before we start the router.
typeManager.Start();
InsideRuntimeClient.Current.Start();
// The order of these 4 is pretty much arbitrary.
scheduler.Start();
messageCenter.Start();
incomingPingAgent.Start();
incomingSystemAgent.Start();
incomingAgent.Start();
LocalGrainDirectory.Start();
// Set up an execution context for this thread so that the target creation steps can use asynch values.
RuntimeContext.InitializeMainThread();
SiloProviderRuntime.Initialize(GlobalConfig, SiloIdentity, grainFactory, Services);
InsideRuntimeClient.Current.CurrentStreamProviderRuntime = SiloProviderRuntime.Instance;
statisticsProviderManager = new StatisticsProviderManager("Statistics", SiloProviderRuntime.Instance);
string statsProviderName = statisticsProviderManager.LoadProvider(GlobalConfig.ProviderConfigurations)
.WaitForResultWithThrow(initTimeout);
if (statsProviderName != null)
LocalConfig.StatisticsProviderName = statsProviderName;
allSiloProviders.AddRange(statisticsProviderManager.GetProviders());
// can call SetSiloMetricsTableDataManager only after MessageCenter is created (dependency on this.SiloAddress).
siloStatistics.SetSiloStatsTableDataManager(this, nodeConfig).WaitWithThrow(initTimeout);
siloStatistics.SetSiloMetricsTableDataManager(this, nodeConfig).WaitWithThrow(initTimeout);
IMembershipTable membershipTable = membershipFactory.GetMembershipTable(GlobalConfig.LivenessType, GlobalConfig.MembershipTableAssembly);
membershipOracle = membershipFactory.CreateMembershipOracle(this, membershipTable);
multiClusterOracle = multiClusterFactory.CreateGossipOracle(this).WaitForResultWithThrow(initTimeout);
// This has to follow the above steps that start the runtime components
CreateSystemTargets();
InjectDependencies();
// Validate the configuration.
GlobalConfig.Application.ValidateConfiguration(logger);
// ensure this runs in the grain context, wait for it to complete
scheduler.QueueTask(CreateSystemGrains, catalog.SchedulingContext)
.WaitWithThrow(initTimeout);
if (logger.IsVerbose) { logger.Verbose("System grains created successfully."); }
// Initialize storage providers once we have a basic silo runtime environment operating
storageProviderManager = new StorageProviderManager(grainFactory, Services);
scheduler.QueueTask(
() => storageProviderManager.LoadStorageProviders(GlobalConfig.ProviderConfigurations),
providerManagerSystemTarget.SchedulingContext)
.WaitWithThrow(initTimeout);
catalog.SetStorageManager(storageProviderManager);
allSiloProviders.AddRange(storageProviderManager.GetProviders());
if (logger.IsVerbose) { logger.Verbose("Storage provider manager created successfully."); }
// Load and init stream providers before silo becomes active
var siloStreamProviderManager = (StreamProviderManager) grainRuntime.StreamProviderManager;
scheduler.QueueTask(
() => siloStreamProviderManager.LoadStreamProviders(GlobalConfig.ProviderConfigurations, SiloProviderRuntime.Instance),
providerManagerSystemTarget.SchedulingContext)
.WaitWithThrow(initTimeout);
InsideRuntimeClient.Current.CurrentStreamProviderManager = siloStreamProviderManager;
allSiloProviders.AddRange(siloStreamProviderManager.GetProviders());
if (logger.IsVerbose) { logger.Verbose("Stream provider manager created successfully."); }
ISchedulingContext statusOracleContext = ((SystemTarget)LocalSiloStatusOracle).SchedulingContext;
bool waitForPrimaryToStart = globalConfig.PrimaryNodeIsRequired && siloType != SiloType.Primary;
if (waitForPrimaryToStart) // only in MembershipTableGrain case.
{
scheduler.QueueTask(() => membershipFactory.WaitForTableToInit(membershipTable), statusOracleContext)
.WaitWithThrow(initTimeout);
}
scheduler.QueueTask(() => membershipTable.InitializeMembershipTable(GlobalConfig, true, LogManager.GetLogger(membershipTable.GetType().Name)), statusOracleContext)
.WaitWithThrow(initTimeout);
scheduler.QueueTask(() => LocalSiloStatusOracle.Start(), statusOracleContext)
.WaitWithThrow(initTimeout);
if (logger.IsVerbose) { logger.Verbose("Local silo status oracle created successfully."); }
scheduler.QueueTask(LocalSiloStatusOracle.BecomeActive, statusOracleContext)
.WaitWithThrow(initTimeout);
if (logger.IsVerbose) { logger.Verbose("Local silo status oracle became active successfully."); }
//if running in multi cluster scenario, start the MultiClusterNetwork Oracle
if (GlobalConfig.HasMultiClusterNetwork)
{
logger.Info("Creating multicluster oracle with my ServiceId={0} and ClusterId={1}.",
GlobalConfig.ServiceId, GlobalConfig.ClusterId);
ISchedulingContext clusterStatusContext = ((SystemTarget) multiClusterOracle).SchedulingContext;
scheduler.QueueTask(() => multiClusterOracle.Start(LocalSiloStatusOracle), clusterStatusContext)
.WaitWithThrow(initTimeout);
if (logger.IsVerbose) { logger.Verbose("multicluster oracle created successfully."); }
}
try
{
siloStatistics.Start(LocalConfig);
if (logger.IsVerbose) { logger.Verbose("Silo statistics manager started successfully."); }
// Finally, initialize the deployment load collector, for grains with load-based placement
scheduler.QueueTask(DeploymentLoadPublisher.Instance.Start, DeploymentLoadPublisher.Instance.SchedulingContext)
.WaitWithThrow(initTimeout);
if (logger.IsVerbose) { logger.Verbose("Silo deployment load publisher started successfully."); }
// Start background timer tick to watch for platform execution stalls, such as when GC kicks in
platformWatchdog = new Watchdog(nodeConfig.StatisticsLogWriteInterval, healthCheckParticipants);
platformWatchdog.Start();
if (logger.IsVerbose) { logger.Verbose("Silo platform watchdog started successfully."); }
if (reminderService != null)
{
// so, we have the view of the membership in the consistentRingProvider. We can start the reminder service
scheduler.QueueTask(reminderService.Start, ((SystemTarget)reminderService).SchedulingContext)
.WaitWithThrow(initTimeout);
if (logger.IsVerbose)
{
logger.Verbose("Reminder service started successfully.");
}
}
bootstrapProviderManager = new BootstrapProviderManager();
scheduler.QueueTask(
() => bootstrapProviderManager.LoadAppBootstrapProviders(GlobalConfig.ProviderConfigurations),
providerManagerSystemTarget.SchedulingContext)
.WaitWithThrow(initTimeout);
BootstrapProviders = bootstrapProviderManager.GetProviders(); // Data hook for testing & diagnotics
allSiloProviders.AddRange(BootstrapProviders);
if (logger.IsVerbose) { logger.Verbose("App bootstrap calls done successfully."); }
// Start stream providers after silo is active (so the pulling agents don't start sending messages before silo is active).
// also after bootstrap provider started so bootstrap provider can initialize everything stream before events from this silo arrive.
scheduler.QueueTask(siloStreamProviderManager.StartStreamProviders, providerManagerSystemTarget.SchedulingContext)
.WaitWithThrow(initTimeout);
if (logger.IsVerbose) { logger.Verbose("Stream providers started successfully."); }
// Now that we're active, we can start the gateway
var mc = messageCenter as MessageCenter;
if (mc != null)
{
mc.StartGateway(clientRegistrar);
}
if (logger.IsVerbose) { logger.Verbose("Message gateway service started successfully."); }
SystemStatus.Current = SystemStatus.Running;
}
catch (Exception exc)
{
SafeExecute(() => logger.Error(ErrorCode.Runtime_Error_100330, String.Format("Error starting silo {0}. Going to FastKill().", SiloAddress), exc));
FastKill(); // if failed after Membership became active, mark itself as dead in Membership abale.
throw;
}
if (logger.IsVerbose) { logger.Verbose("Silo.Start complete: System status = {0}", SystemStatus.Current); }
}
private void ConfigureThreadPoolAndServicePointSettings()
{
if (nodeConfig.MinDotNetThreadPoolSize > 0)
{
int workerThreads;
int completionPortThreads;
ThreadPool.GetMinThreads(out workerThreads, out completionPortThreads);
if (nodeConfig.MinDotNetThreadPoolSize > workerThreads ||
nodeConfig.MinDotNetThreadPoolSize > completionPortThreads)
{
// if at least one of the new values is larger, set the new min values to be the larger of the prev. and new config value.
int newWorkerThreads = Math.Max(nodeConfig.MinDotNetThreadPoolSize, workerThreads);
int newCompletionPortThreads = Math.Max(nodeConfig.MinDotNetThreadPoolSize, completionPortThreads);
bool ok = ThreadPool.SetMinThreads(newWorkerThreads, newCompletionPortThreads);
if (ok)
{
logger.Info(ErrorCode.SiloConfiguredThreadPool,
"Configured ThreadPool.SetMinThreads() to values: {0},{1}. Previous values are: {2},{3}.",
newWorkerThreads, newCompletionPortThreads, workerThreads, completionPortThreads);
}
else
{
logger.Warn(ErrorCode.SiloFailedToConfigureThreadPool,
"Failed to configure ThreadPool.SetMinThreads(). Tried to set values to: {0},{1}. Previous values are: {2},{3}.",
newWorkerThreads, newCompletionPortThreads, workerThreads, completionPortThreads);
}
}
}
// Set .NET ServicePointManager settings to optimize throughput performance when using Azure storage
// http://blogs.msdn.com/b/windowsazurestorage/archive/2010/06/25/nagle-s-algorithm-is-not-friendly-towards-small-requests.aspx
logger.Info(ErrorCode.SiloConfiguredServicePointManager,
"Configured .NET ServicePointManager to Expect100Continue={0}, DefaultConnectionLimit={1}, UseNagleAlgorithm={2} to improve Azure storage performance.",
nodeConfig.Expect100Continue, nodeConfig.DefaultConnectionLimit, nodeConfig.UseNagleAlgorithm);
ServicePointManager.Expect100Continue = nodeConfig.Expect100Continue;
ServicePointManager.DefaultConnectionLimit = nodeConfig.DefaultConnectionLimit;
ServicePointManager.UseNagleAlgorithm = nodeConfig.UseNagleAlgorithm;
}
/// <summary>
/// Gracefully stop the run time system only, but not the application.
/// Applications requests would be abruptly terminated, while the internal system state gracefully stopped and saved as much as possible.
/// Grains are not deactivated.
/// </summary>
public void Stop()
{
Terminate(false);
}
/// <summary>
/// Gracefully stop the run time system and the application.
/// All grains will be properly deactivated.
/// All in-flight applications requests would be awaited and finished gracefully.
/// </summary>
public void Shutdown()
{
Terminate(true);
}
/// <summary>
/// Gracefully stop the run time system only, but not the application.
/// Applications requests would be abruptly terminated, while the internal system state gracefully stopped and saved as much as possible.
/// </summary>
private void Terminate(bool gracefully)
{
string operation = gracefully ? "Shutdown()" : "Stop()";
bool stopAlreadyInProgress = false;
lock (lockable)
{
if (SystemStatus.Current.Equals(SystemStatus.Stopping) ||
SystemStatus.Current.Equals(SystemStatus.ShuttingDown) ||
SystemStatus.Current.Equals(SystemStatus.Terminated))
{
stopAlreadyInProgress = true;
// Drop through to wait below
}
else if (!SystemStatus.Current.Equals(SystemStatus.Running))
{
throw new InvalidOperationException(String.Format("Calling Silo.{0} on a silo which is not in the Running state. This silo is in the {1} state.", operation, SystemStatus.Current));
}
else
{
if (gracefully)
SystemStatus.Current = SystemStatus.ShuttingDown;
else
SystemStatus.Current = SystemStatus.Stopping;
}
}
if (stopAlreadyInProgress)
{
logger.Info(ErrorCode.SiloStopInProgress, "Silo termination is in progress - Will wait for it to finish");
var pause = TimeSpan.FromSeconds(1);
while (!SystemStatus.Current.Equals(SystemStatus.Terminated))
{
logger.Info(ErrorCode.WaitingForSiloStop, "Waiting {0} for termination to complete", pause);
Thread.Sleep(pause);
}
return;
}
try
{
try
{
if (gracefully)
{
logger.Info(ErrorCode.SiloShuttingDown, "Silo starting to Shutdown()");
// 1: Write "ShutDown" state in the table + broadcast gossip msgs to re-read the table to everyone
scheduler.QueueTask(LocalSiloStatusOracle.ShutDown, ((SystemTarget)LocalSiloStatusOracle).SchedulingContext)
.WaitWithThrow(stopTimeout);
}
else
{
logger.Info(ErrorCode.SiloStopping, "Silo starting to Stop()");
// 1: Write "Stopping" state in the table + broadcast gossip msgs to re-read the table to everyone
scheduler.QueueTask(LocalSiloStatusOracle.Stop, ((SystemTarget)LocalSiloStatusOracle).SchedulingContext)
.WaitWithThrow(stopTimeout);
}
}
catch (Exception exc)
{
logger.Error(ErrorCode.SiloFailedToStopMembership, String.Format("Failed to {0} LocalSiloStatusOracle. About to FastKill this silo.", operation), exc);
return; // will go to finally
}
if (reminderService != null)
{
// 2: Stop reminder service
scheduler.QueueTask(reminderService.Stop, ((SystemTarget) reminderService).SchedulingContext)
.WaitWithThrow(stopTimeout);
}
if (gracefully)
{
// 3: Deactivate all grains
SafeExecute(() => catalog.DeactivateAllActivations().WaitWithThrow(stopTimeout));
}
// 3: Stop the gateway
SafeExecute(messageCenter.StopAcceptingClientMessages);
// 4: Start rejecting all silo to silo application messages
SafeExecute(messageCenter.BlockApplicationMessages);
// 5: Stop scheduling/executing application turns
SafeExecute(scheduler.StopApplicationTurns);
// 6: Directory: Speed up directory handoff
// will be started automatically when directory receives SiloStatusChangeNotification(Stopping)
// 7:
SafeExecute(() => LocalGrainDirectory.StopPreparationCompletion.WaitWithThrow(stopTimeout));
// The order of closing providers might be importan: Stats, streams, boostrap, storage.
// Stats first since no one depends on it.
// Storage should definitely be last since other providers ma ybe using it, potentilay indirectly.
// Streams and Bootstrap - the order is less clear. Seems like Bootstrap may indirecly depend on Streams, but not the other way around.
// 8:
SafeExecute(() =>
{
scheduler.QueueTask(() => statisticsProviderManager.CloseProviders(), providerManagerSystemTarget.SchedulingContext)
.WaitWithThrow(initTimeout);
});
// 9:
SafeExecute(() =>
{
var siloStreamProviderManager = (StreamProviderManager)grainRuntime.StreamProviderManager;
scheduler.QueueTask(() => siloStreamProviderManager.CloseProviders(), providerManagerSystemTarget.SchedulingContext)
.WaitWithThrow(initTimeout);
});
// 10:
SafeExecute(() =>
{
scheduler.QueueTask(() => bootstrapProviderManager.CloseProviders(), providerManagerSystemTarget.SchedulingContext)
.WaitWithThrow(initTimeout);
});
// 11:
SafeExecute(() =>
{
scheduler.QueueTask(() => storageProviderManager.CloseProviders(), providerManagerSystemTarget.SchedulingContext)
.WaitWithThrow(initTimeout);
});
}
finally
{
// 10, 11, 12: Write Dead in the table, Drain scheduler, Stop msg center, ...
logger.Info(ErrorCode.SiloStopped, "Silo is Stopped()");
FastKill();
}
}
/// <summary>
/// Ungracefully stop the run time system and the application running on it.
/// Applications requests would be abruptly terminated, and the internal system state quickly stopped with minimal cleanup.
/// </summary>
private void FastKill()
{
if (!GlobalConfig.LivenessType.Equals(GlobalConfiguration.LivenessProviderType.MembershipTableGrain))
{
// do not execute KillMyself if using MembershipTableGrain, since it will fail, as we've already stopped app scheduler turns.
SafeExecute(() => scheduler.QueueTask( LocalSiloStatusOracle.KillMyself, ((SystemTarget)LocalSiloStatusOracle).SchedulingContext)
.WaitWithThrow(stopTimeout));
}
// incoming messages
SafeExecute(incomingSystemAgent.Stop);
SafeExecute(incomingPingAgent.Stop);
SafeExecute(incomingAgent.Stop);
// timers
SafeExecute(InsideRuntimeClient.Current.Stop);
if (platformWatchdog != null)
SafeExecute(platformWatchdog.Stop); // Silo may be dying before platformWatchdog was set up
SafeExecute(scheduler.Stop);
SafeExecute(scheduler.PrintStatistics);
SafeExecute(activationDirectory.PrintActivationDirectory);
SafeExecute(messageCenter.Stop);
SafeExecute(siloStatistics.Stop);
SafeExecute(GrainTypeManager.Stop);
UnobservedExceptionsHandlerClass.ResetUnobservedExceptionHandler();
SafeExecute(() => SystemStatus.Current = SystemStatus.Terminated);
SafeExecute(LogManager.Close);
// Setting the event should be the last thing we do.
// Do nothijng after that!
siloTerminatedEvent.Set();
}
private void SafeExecute(Action action)
{
Utils.SafeExecute(action, logger, "Silo.Stop");
}
private void HandleProcessExit(object sender, EventArgs e)
{
// NOTE: We need to minimize the amount of processing occurring on this code path -- we only have under approx 2-3 seconds before process exit will occur
logger.Warn(ErrorCode.Runtime_Error_100220, "Process is exiting");
LogManager.Flush();
try
{
lock (lockable)
{
if (!SystemStatus.Current.Equals(SystemStatus.Running)) return;
SystemStatus.Current = SystemStatus.Stopping;
}
if (!TestHook.ExecuteFastKillInProcessExit) return;
logger.Info(ErrorCode.SiloStopping, "Silo.HandleProcessExit() - starting to FastKill()");
FastKill();
}
finally
{
LogManager.Close();
}
}
/// <summary>
/// Test hook functions for white box testing.
/// </summary>
public class TestHooks : MarshalByRefObject
{
private readonly Silo silo;
internal bool ExecuteFastKillInProcessExit;
internal IConsistentRingProvider ConsistentRingProvider
{
get { return CheckReturnBoundaryReference("ring provider", silo.RingProvider); }
}
internal bool HasStatisticsProvider { get { return silo.statisticsProviderManager != null; } }
internal object StatisticsProvider
{
get
{
if (silo.statisticsProviderManager == null) return null;
var provider = silo.statisticsProviderManager.GetProvider(silo.LocalConfig.StatisticsProviderName);
return CheckReturnBoundaryReference("statistics provider", provider);
}
}
/// <summary>
/// Populates the provided <paramref name="collection"/> with the assemblies generated by this silo.
/// </summary>
/// <param name="collection">The collection to populate.</param>
public void UpdateGeneratedAssemblies(GeneratedAssemblies collection)
{
var generatedAssemblies = CodeGeneratorManager.GetGeneratedAssemblies();
foreach (var asm in generatedAssemblies)
{
collection.Add(asm.Key, asm.Value);
}
}
internal Action<GrainId> Debug_OnDecideToCollectActivation { get; set; }
internal TestHooks(Silo s)
{
silo = s;
ExecuteFastKillInProcessExit = true;
}
internal Guid ServiceId { get { return silo.GlobalConfig.ServiceId; } }
/// <summary>
/// Get list of providers loaded in this silo.
/// </summary>
/// <returns></returns>
internal IEnumerable<string> GetStorageProviderNames()
{
return silo.StorageProviderManager.GetProviderNames();
}
/// <summary>
/// Find the named storage provider loaded in this silo.
/// </summary>
/// <returns></returns>
internal IStorageProvider GetStorageProvider(string name)
{
IStorageProvider provider = silo.StorageProviderManager.GetProvider(name) as IStorageProvider;
return CheckReturnBoundaryReference("storage provider", provider);
}
internal string PrintSiloConfig()
{
return silo.OrleansConfig.ToString(silo.Name);
}
internal IBootstrapProvider GetBootstrapProvider(string name)
{
IBootstrapProvider provider = silo.BootstrapProviders.First(p => p.Name.Equals(name));
return CheckReturnBoundaryReference("bootstrap provider", provider);
}
internal void SuppressFastKillInHandleProcessExit()
{
ExecuteFastKillInProcessExit = false;
}
internal void InjectMultiClusterConfiguration(MultiClusterConfiguration config)
{
silo.LocalMultiClusterOracle.InjectMultiClusterConfiguration(config).Wait();
}
// store silos for which we simulate faulty communication
// number indicates how many percent of requests are lost
internal ConcurrentDictionary<IPEndPoint, double> SimulatedMessageLoss;
internal void BlockSiloCommunication(IPEndPoint destination, double lost_percentage)
{
if (SimulatedMessageLoss == null)
SimulatedMessageLoss = new ConcurrentDictionary<IPEndPoint, double>();
SimulatedMessageLoss[destination] = lost_percentage;
}
internal void UnblockSiloCommunication()
{
SimulatedMessageLoss = null;
}
private readonly SafeRandom random = new SafeRandom();
internal bool ShouldDrop(Message msg)
{
if (SimulatedMessageLoss != null)
{
double blockedpercentage;
CurrentSilo.TestHook.SimulatedMessageLoss.TryGetValue(msg.TargetSilo.Endpoint, out blockedpercentage);
return (random.NextDouble() * 100 < blockedpercentage);
}
else
return false;
}
// this is only for white box testing - use RuntimeClient.Current.SendRequest instead
internal void SendMessageInternal(Message message)
{
silo.messageCenter.SendMessage(message);
}
// For white-box testing only
internal int UnregisterGrainForTesting(GrainId grain)
{
return silo.catalog.UnregisterGrainForTesting(grain);
}
// For white-box testing only
internal void SetDirectoryLazyDeregistrationDelay_ForTesting(TimeSpan timeSpan)
{
silo.OrleansConfig.Globals.DirectoryLazyDeregistrationDelay = timeSpan;
}
// For white-box testing only
internal void SetMaxForwardCount_ForTesting(int val)
{
silo.OrleansConfig.Globals.MaxForwardCount = val;
}
private static T CheckReturnBoundaryReference<T>(string what, T obj) where T : class
{
if (obj == null) return null;
if (obj is MarshalByRefObject || obj is ISerializable)
{
// Referernce to the provider can safely be passed across app-domain boundary in unit test process
return obj;
}
throw new InvalidOperationException(string.Format("Cannot return reference to {0} {1} if it is not MarshalByRefObject or Serializable",
what, TypeUtils.GetFullName(obj.GetType())));
}
/// <summary>
/// Represents a collection of generated assemblies accross an application domain.
/// </summary>
public class GeneratedAssemblies : MarshalByRefObject
{
/// <summary>
/// Initializes a new instance of the <see cref="GeneratedAssemblies"/> class.
/// </summary>
public GeneratedAssemblies()
{
Assemblies = new Dictionary<string, byte[]>();
}
/// <summary>
/// Gets the assemblies which were produced by code generation.
/// </summary>
public Dictionary<string, byte[]> Assemblies { get; private set; }
/// <summary>
/// Adds a new assembly to this collection.
/// </summary>
/// <param name="key">
/// The full name of the assembly which code was generated for.
/// </param>
/// <param name="value">
/// The raw generated assembly.
/// </param>
public void Add(string key, byte[] value)
{
if (!string.IsNullOrWhiteSpace(key))
{
Assemblies[key] = value;
}
}
}
/// <summary>
/// Methods for optimizing the code generator.
/// </summary>
public class CodeGeneratorOptimizer : MarshalByRefObject
{
/// <summary>
/// Adds a cached assembly to the code generator.
/// </summary>
/// <param name="targetAssemblyName">The assembly which the cached assembly was generated for.</param>
/// <param name="cachedAssembly">The generated assembly.</param>
public void AddCachedAssembly(string targetAssemblyName, byte[] cachedAssembly)
{
CodeGeneratorManager.AddGeneratedAssembly(targetAssemblyName, cachedAssembly);
}
}
}
private void UnobservedExceptionHandler(ISchedulingContext context, Exception exception)
{
var schedulingContext = context as SchedulingContext;
if (schedulingContext == null)
{
if (context == null)
logger.Error(ErrorCode.Runtime_Error_100102, "Silo caught an UnobservedException with context==null.", exception);
else
logger.Error(ErrorCode.Runtime_Error_100103, String.Format("Silo caught an UnobservedException with context of type different than OrleansContext. The type of the context is {0}. The context is {1}",
context.GetType(), context), exception);
}
else
{
logger.Error(ErrorCode.Runtime_Error_100104, String.Format("Silo caught an UnobservedException thrown by {0}.", schedulingContext.Activation), exception);
}
}
private void DomainUnobservedExceptionHandler(object context, Exception exception)
{
if (context is ISchedulingContext)
UnobservedExceptionHandler(context as ISchedulingContext, exception);
else
logger.Error(ErrorCode.Runtime_Error_100324, String.Format("Called DomainUnobservedExceptionHandler with context {0}.", context), exception);
}
internal void RegisterSystemTarget(SystemTarget target)
{
scheduler.RegisterWorkContext(target.SchedulingContext);
activationDirectory.RecordNewSystemTarget(target);
}
internal void UnregisterSystemTarget(SystemTarget target)
{
activationDirectory.RemoveSystemTarget(target);
scheduler.UnregisterWorkContext(target.SchedulingContext);
}
/// <summary> Return dump of diagnostic data from this silo. </summary>
/// <param name="all"></param>
/// <returns>Debug data for this silo.</returns>
public string GetDebugDump(bool all = true)
{
var sb = new StringBuilder();
foreach (var sytemTarget in activationDirectory.AllSystemTargets())
sb.AppendFormat("System target {0}:", sytemTarget.GrainId.ToString()).AppendLine();
var enumerator = activationDirectory.GetEnumerator();
while(enumerator.MoveNext())
{
Utils.SafeExecute(() =>
{
var activationData = enumerator.Current.Value;
var workItemGroup = scheduler.GetWorkItemGroup(new SchedulingContext(activationData));
if (workItemGroup == null)
{
sb.AppendFormat("Activation with no work item group!! Grain {0}, activation {1}.",
activationData.Grain,
activationData.ActivationId);
sb.AppendLine();
return;
}
if (all || activationData.State.Equals(ActivationState.Valid))
{
sb.AppendLine(workItemGroup.DumpStatus());
sb.AppendLine(activationData.DumpStatus());
}
});
}
logger.Info(ErrorCode.SiloDebugDump, sb.ToString());
return sb.ToString();
}
/// <summary> Object.ToString override -- summary info for this silo. </summary>
public override string ToString()
{
return localGrainDirectory.ToString();
}
}
// A dummy system target to use for scheduling context for provider Init calls, to allow them to make grain calls
internal class ProviderManagerSystemTarget : SystemTarget
{
public ProviderManagerSystemTarget(Silo currentSilo)
: base(Constants.ProviderManagerSystemTargetId, currentSilo.SiloAddress)
{
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace SampleWebAPI.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
private const int DefaultCollectionSize = 3;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
// 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.Schema
{
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
public class XmlSchemaObjectTable
{
private Dictionary<XmlQualifiedName, XmlSchemaObject> _table = new Dictionary<XmlQualifiedName, XmlSchemaObject>();
private List<XmlSchemaObjectEntry> _entries = new List<XmlSchemaObjectEntry>();
internal XmlSchemaObjectTable()
{
}
internal void Add(XmlQualifiedName name, XmlSchemaObject value)
{
Debug.Assert(!_table.ContainsKey(name), "XmlSchemaObjectTable.Add: entry already exists");
_table.Add(name, value);
_entries.Add(new XmlSchemaObjectEntry(name, value));
}
internal void Insert(XmlQualifiedName name, XmlSchemaObject value)
{
XmlSchemaObject oldValue = null;
if (_table.TryGetValue(name, out oldValue))
{
_table[name] = value; //set new value
Debug.Assert(oldValue != null);
int matchedIndex = FindIndexByValue(oldValue);
Debug.Assert(matchedIndex >= 0);
//set new entry
Debug.Assert(_entries[matchedIndex].qname == name);
_entries[matchedIndex] = new XmlSchemaObjectEntry(name, value);
}
else
{
Add(name, value);
}
}
internal void Replace(XmlQualifiedName name, XmlSchemaObject value)
{
XmlSchemaObject oldValue;
if (_table.TryGetValue(name, out oldValue))
{
_table[name] = value; //set new value
Debug.Assert(oldValue != null);
int matchedIndex = FindIndexByValue(oldValue);
Debug.Assert(_entries[matchedIndex].qname == name);
_entries[matchedIndex] = new XmlSchemaObjectEntry(name, value);
}
}
internal void Clear()
{
_table.Clear();
_entries.Clear();
}
internal void Remove(XmlQualifiedName name)
{
XmlSchemaObject value;
if (_table.TryGetValue(name, out value))
{
_table.Remove(name);
int matchedIndex = FindIndexByValue(value);
Debug.Assert(matchedIndex >= 0);
Debug.Assert(_entries[matchedIndex].qname == name);
_entries.RemoveAt(matchedIndex);
}
}
private int FindIndexByValue(XmlSchemaObject xso)
{
int index;
for (index = 0; index < _entries.Count; index++)
{
if ((object)_entries[index].xso == (object)xso)
{
return index;
}
}
return -1;
}
public int Count
{
get
{
Debug.Assert(_table.Count == _entries.Count);
return _table.Count;
}
}
public bool Contains(XmlQualifiedName name)
{
return _table.ContainsKey(name);
}
public XmlSchemaObject this[XmlQualifiedName name]
{
get
{
XmlSchemaObject value;
if (_table.TryGetValue(name, out value))
{
return value;
}
return null;
}
}
public ICollection Names
{
get
{
return new NamesCollection(_entries, _table.Count);
}
}
public ICollection Values
{
get
{
return new ValuesCollection(_entries, _table.Count);
}
}
public IDictionaryEnumerator GetEnumerator()
{
return new XSODictionaryEnumerator(_entries, _table.Count, EnumeratorType.DictionaryEntry);
}
internal enum EnumeratorType
{
Keys,
Values,
DictionaryEntry,
}
internal struct XmlSchemaObjectEntry
{
internal XmlQualifiedName qname;
internal XmlSchemaObject xso;
public XmlSchemaObjectEntry(XmlQualifiedName name, XmlSchemaObject value)
{
qname = name;
xso = value;
}
}
internal class NamesCollection : ICollection
{
private List<XmlSchemaObjectEntry> _entries;
private int _size;
internal NamesCollection(List<XmlSchemaObjectEntry> entries, int size)
{
_entries = entries;
_size = size;
}
public int Count
{
get { return _size; }
}
public object SyncRoot
{
get
{
return ((ICollection)_entries).SyncRoot;
}
}
public bool IsSynchronized
{
get
{
return ((ICollection)_entries).IsSynchronized;
}
}
public void CopyTo(Array array, int arrayIndex)
{
if (array == null)
throw new ArgumentNullException(nameof(array));
if (arrayIndex < 0)
throw new ArgumentOutOfRangeException(nameof(arrayIndex));
Debug.Assert(array.Length >= _size, "array is not big enough to hold all the items in the ICollection");
for (int i = 0; i < _size; i++)
{
array.SetValue(_entries[i].qname, arrayIndex++);
}
}
public IEnumerator GetEnumerator()
{
return new XSOEnumerator(_entries, _size, EnumeratorType.Keys);
}
}
//ICollection for Values
internal class ValuesCollection : ICollection
{
private List<XmlSchemaObjectEntry> _entries;
private int _size;
internal ValuesCollection(List<XmlSchemaObjectEntry> entries, int size)
{
_entries = entries;
_size = size;
}
public int Count
{
get { return _size; }
}
public object SyncRoot
{
get
{
return ((ICollection)_entries).SyncRoot;
}
}
public bool IsSynchronized
{
get
{
return ((ICollection)_entries).IsSynchronized;
}
}
public void CopyTo(Array array, int arrayIndex)
{
if (array == null)
throw new ArgumentNullException(nameof(array));
if (arrayIndex < 0)
throw new ArgumentOutOfRangeException(nameof(arrayIndex));
Debug.Assert(array.Length >= _size, "array is not big enough to hold all the items in the ICollection");
for (int i = 0; i < _size; i++)
{
array.SetValue(_entries[i].xso, arrayIndex++);
}
}
public IEnumerator GetEnumerator()
{
return new XSOEnumerator(_entries, _size, EnumeratorType.Values);
}
}
internal class XSOEnumerator : IEnumerator
{
private List<XmlSchemaObjectEntry> _entries;
private EnumeratorType _enumType;
protected int currentIndex;
protected int size;
protected XmlQualifiedName currentKey;
protected XmlSchemaObject currentValue;
internal XSOEnumerator(List<XmlSchemaObjectEntry> entries, int size, EnumeratorType enumType)
{
_entries = entries;
this.size = size;
_enumType = enumType;
currentIndex = -1;
}
public object Current
{
get
{
if (currentIndex == -1)
{
throw new InvalidOperationException(SR.Format(SR.Sch_EnumNotStarted, string.Empty));
}
if (currentIndex >= size)
{
throw new InvalidOperationException(SR.Format(SR.Sch_EnumFinished, string.Empty));
}
switch (_enumType)
{
case EnumeratorType.Keys:
return currentKey;
case EnumeratorType.Values:
return currentValue;
case EnumeratorType.DictionaryEntry:
return new DictionaryEntry(currentKey, currentValue);
default:
break;
}
return null;
}
}
public bool MoveNext()
{
if (currentIndex >= size - 1)
{
currentValue = null;
currentKey = null;
return false;
}
currentIndex++;
currentValue = _entries[currentIndex].xso;
currentKey = _entries[currentIndex].qname;
return true;
}
public void Reset()
{
currentIndex = -1;
currentValue = null;
currentKey = null;
}
}
internal class XSODictionaryEnumerator : XSOEnumerator, IDictionaryEnumerator
{
internal XSODictionaryEnumerator(List<XmlSchemaObjectEntry> entries, int size, EnumeratorType enumType) : base(entries, size, enumType)
{
}
//IDictionaryEnumerator members
public DictionaryEntry Entry
{
get
{
if (currentIndex == -1)
{
throw new InvalidOperationException(SR.Format(SR.Sch_EnumNotStarted, string.Empty));
}
if (currentIndex >= size)
{
throw new InvalidOperationException(SR.Format(SR.Sch_EnumFinished, string.Empty));
}
return new DictionaryEntry(currentKey, currentValue);
}
}
public object Key
{
get
{
if (currentIndex == -1)
{
throw new InvalidOperationException(SR.Format(SR.Sch_EnumNotStarted, string.Empty));
}
if (currentIndex >= size)
{
throw new InvalidOperationException(SR.Format(SR.Sch_EnumFinished, string.Empty));
}
return currentKey;
}
}
public object Value
{
get
{
if (currentIndex == -1)
{
throw new InvalidOperationException(SR.Format(SR.Sch_EnumNotStarted, string.Empty));
}
if (currentIndex >= size)
{
throw new InvalidOperationException(SR.Format(SR.Sch_EnumFinished, string.Empty));
}
return currentValue;
}
}
}
}
}
| |
using System;
using System.IO;
using System.Windows.Forms;
using System.ComponentModel;
using System.Text;
using System.Net;
using System.Net.Cache;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Xml;
namespace XmlNotepad {
public class XmlProxyResolver : XmlUrlResolver {
WebProxyService ps;
public XmlProxyResolver(IServiceProvider site) {
ps = site.GetService(typeof(WebProxyService)) as WebProxyService;
}
public override object GetEntity(Uri absoluteUri, string role, Type ofObjectToReturn) {
if (absoluteUri == null) {
throw new ArgumentNullException("absoluteUri");
}
if (absoluteUri.Scheme == "http" && (ofObjectToReturn == null || ofObjectToReturn == typeof(Stream))) {
try {
return GetResponse(absoluteUri);
} catch (Exception e) {
if (WebProxyService.ProxyAuthenticationRequired(e)) {
WebProxyState state = ps.PrepareWebProxy(this.Proxy, absoluteUri.AbsoluteUri, WebProxyState.DefaultCredentials, true);
if (state != WebProxyState.Abort) {
// try again...
return GetResponse(absoluteUri);
}
}
throw;
}
} else {
return base.GetEntity(absoluteUri, role, ofObjectToReturn);
}
}
Stream GetResponse(Uri uri) {
WebRequest webReq = WebRequest.Create(uri);
webReq.CachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.Default);
webReq.Credentials = CredentialCache.DefaultCredentials;
webReq.Proxy = this.Proxy;
WebResponse resp = webReq.GetResponse();
return resp.GetResponseStream();
}
IWebProxy Proxy {
get { return HttpWebRequest.DefaultWebProxy; }
}
}
enum WebProxyState {
NoCredentials = 0,
DefaultCredentials = 1,
CachedCredentials = 2,
PromptForCredentials = 3,
Abort = 4
} ;
internal class WebProxyService {
private IServiceProvider site;
private NetworkCredential cachedCredentials;
private string currentProxyUrl;
public WebProxyService(IServiceProvider site) {
this.site = site;
}
//---------------------------------------------------------------------
// public methods
//---------------------------------------------------------------------
public static bool ProxyAuthenticationRequired(Exception ex) {
bool authNeeded = false;
System.Net.WebException wex = ex as System.Net.WebException;
if ((wex != null) && (wex.Status == System.Net.WebExceptionStatus.ProtocolError)) {
System.Net.HttpWebResponse hwr = wex.Response as System.Net.HttpWebResponse;
if ((hwr != null) && (hwr.StatusCode == System.Net.HttpStatusCode.ProxyAuthenticationRequired)) {
authNeeded = true;
}
}
return authNeeded;
}
/// <summary>
/// This method attaches credentials to the web proxy object.
/// </summary>
/// <param name="proxy">The proxy to attach credentials to.</param>
/// <param name="webCallUrl">The url for the web call.</param>
/// <param name="oldProxyState">The current state fo the web call.</param>
/// <param name="newProxyState">The new state for the web call.</param>
/// <param name="okToPrompt">Prompt user for credentials if they are not available.</param>
public WebProxyState PrepareWebProxy(IWebProxy proxy, string webCallUrl, WebProxyState oldProxyState, bool okToPrompt) {
WebProxyState newProxyState = WebProxyState.Abort;
if (string.IsNullOrEmpty(webCallUrl)) {
Debug.Fail("PrepareWebProxy called with an empty WebCallUrl.");
webCallUrl = "http://go.microsoft.com/fwlink/?LinkId=81947";
}
// Get the web proxy url for the the current web call.
Uri webCallProxy = null;
if (proxy != null) {
webCallProxy = proxy.GetProxy(new Uri(webCallUrl));
}
if ((proxy != null) && (webCallProxy != null)) {
// get proxy url.
string proxyUrl = webCallProxy.Host;
if (string.IsNullOrEmpty(currentProxyUrl)) {
currentProxyUrl = proxyUrl;
}
switch (oldProxyState) {
case WebProxyState.NoCredentials:
// Add the default credentials only if there aren't any credentials attached to
// the DefaultWebProxy. If the first calls attaches the correct credentials, the
// second call will just use them, instead of overwriting it with the default credentials.
// This avoids multiple web calls. Note that state is transitioned to DefaultCredentials
// instead of CachedCredentials. This ensures that web calls be tried with the
// cached credentials if the currently attached credentials don't result in successful web call.
if ((proxy.Credentials == null)) {
proxy.Credentials = CredentialCache.DefaultCredentials;
}
newProxyState = WebProxyState.DefaultCredentials;
break;
case WebProxyState.DefaultCredentials:
// Fetch cached credentials if they are null or if the proxy url has changed.
if ((cachedCredentials == null) ||
!string.Equals(currentProxyUrl, proxyUrl, StringComparison.OrdinalIgnoreCase)) {
cachedCredentials = GetCachedCredentials(proxyUrl);
}
if (cachedCredentials != null) {
proxy.Credentials = cachedCredentials;
newProxyState = WebProxyState.CachedCredentials;
break;
}
// Proceed to next step if cached credentials are not available.
goto case WebProxyState.CachedCredentials;
case WebProxyState.CachedCredentials:
case WebProxyState.PromptForCredentials:
if (okToPrompt) {
if (DialogResult.OK == PromptForCredentials(proxyUrl)) {
proxy.Credentials = cachedCredentials;
newProxyState = WebProxyState.PromptForCredentials;
} else {
newProxyState = WebProxyState.Abort;
}
} else {
newProxyState = WebProxyState.Abort;
}
break;
case WebProxyState.Abort:
throw new InvalidOperationException();
default:
throw new ArgumentException(string.Empty, "oldProxyState");
}
} else {
// No proxy for the webCallUrl scenario.
if (oldProxyState == WebProxyState.NoCredentials) {
// if it is the first call, change the state and let the web call proceed.
newProxyState = WebProxyState.DefaultCredentials;
} else {
Debug.Fail("This method is called a second time when 407 occurs. A 407 shouldn't have occurred as there is no default proxy.");
// We dont have a good idea of the circumstances under which
// WebProxy might be null for a url. To be safe, for VS 2005 SP1,
// we will just return the abort state, instead of throwing
// an exception. Abort state will ensure that no further procesing
// occurs and we will not bring down the app.
// throw new InvalidOperationException();
newProxyState = WebProxyState.Abort;
}
}
return newProxyState;
}
//---------------------------------------------------------------------
// private methods
//---------------------------------------------------------------------
/// <summary>
/// Retrieves credentials from the credential store.
/// </summary>
/// <param name="proxyUrl">The proxy url for which credentials are retrieved.</param>
/// <returns>The credentails for the proxy.</returns>
private NetworkCredential GetCachedCredentials(string proxyUrl) {
return Credentials.GetCachedCredentials(proxyUrl);
}
/// <summary>
/// Prompt the use to provider credentials and optionally store them.
/// </summary>
/// <param name="proxyUrl">The server that requires credentials.</param>
/// <returns>Returns the dialog result of the prompt dialog.</returns>
private DialogResult PromptForCredentials(string proxyUrl) {
DialogResult dialogResult = DialogResult.Cancel;
bool prompt = true;
while (prompt) {
prompt = false;
NetworkCredential cred;
dialogResult = Credentials.PromptForCredentials(proxyUrl, out cred);
if (DialogResult.OK == dialogResult) {
if (cred != null) {
cachedCredentials = cred;
currentProxyUrl = proxyUrl;
} else {
// Prompt again for credential as we are not able to create
// a NetworkCredential object from the supplied credentials.
prompt = true;
}
}
}
return dialogResult;
}
}
internal sealed class Credentials {
/// <summary>
/// Prompt the user for credentials.
/// </summary>
/// <param name="target">
/// The credential target. It is displayed in the prompt dialog and is
/// used for credential storage.
/// </param>
/// <param name="credential">The user supplied credentials.</param>
/// <returns>
/// DialogResult.OK = if Successfully prompted user for credentials.
/// DialogResult.Cancel = if user cancelled the prompt dialog.
/// </returns>
public static DialogResult PromptForCredentials(string target, out NetworkCredential credential) {
DialogResult dr = DialogResult.Cancel;
credential = null;
string username;
string password;
IntPtr hwndOwner = IntPtr.Zero;
// Show the OS credential dialog.
dr = ShowOSCredentialDialog(target, hwndOwner, out username, out password);
// Create the NetworkCredential object.
if (dr == DialogResult.OK) {
credential = CreateCredentials(username, password, target);
}
return dr;
}
/// <summary>
/// Get the cached credentials from the credentials store.
/// </summary>
/// <param name="target">The credential target.</param>
/// <returns>
/// The cached credentials. It will return null if credentails are found
/// in the cache.
/// </returns>
public static NetworkCredential GetCachedCredentials(string target) {
NetworkCredential cred = null;
string username;
string password;
// Retrieve credentials from the OS credential store.
if (ReadOSCredentials(target, out username, out password)) {
// Create the NetworkCredential object if we successfully
// retrieved the credentails from the OS store.
cred = CreateCredentials(username, password, target);
}
return cred;
}
//---------------------------------------------------------------------
// private methods
//---------------------------------------------------------------------
/// <summary>
/// This function calls the OS dialog to prompt user for credential.
/// </summary>
/// <param name="target">
/// The credential target. It is displayed in the prompt dialog and is
/// used for credential storage.
/// </param>
/// <param name="hwdOwner">The parent for the dialog.</param>
/// <param name="userName">The username supplied by the user.</param>
/// <param name="password">The password supplied by the user.</param>
/// <returns>
/// DialogResult.OK = if Successfully prompted user for credentials.
/// DialogResult.Cancel = if user cancelled the prompt dialog.
/// </returns>
private static DialogResult ShowOSCredentialDialog(string target, IntPtr hwdOwner, out string userName, out string password) {
DialogResult retValue = DialogResult.Cancel;
userName = string.Empty;
password = string.Empty;
string titleFormat = SR.CredentialDialog_TitleFormat;
string descriptionFormat = SR.CredentialDialog_DescriptionTextFormat;
// Create the CREDUI_INFO structure.
NativeMethods.CREDUI_INFO info = new NativeMethods.CREDUI_INFO();
info.pszCaptionText = string.Format(CultureInfo.CurrentUICulture, titleFormat, target);
info.pszMessageText = string.Format(CultureInfo.CurrentUICulture, descriptionFormat, target);
info.hwndParentCERParent = hwdOwner;
info.hbmBannerCERHandle = IntPtr.Zero;
info.cbSize = Marshal.SizeOf(info);
// We do not use CREDUI_FLAGS_VALIDATE_USERNAME flag as it doesn't allow plain user
// (one with no domain component). Instead we use CREDUI_FLAGS_COMPLETE_USERNAME.
// It does some basic username validation (like doesnt allow two "\" in the user name.
// It does adds the target to the username. For example, if user entered "foo" for
// taget "bar.com", it will return username as "bar.com\foo". We trim out bar.com
// while parsing the username. User can input "foo@bar.com" as workaround to provide
// "bar.com\foo" as the username.
// We specify CRED_TYPE_SERVER_CREDENTIAL flag as the stored credentials appear in the
// "Control Panel->Stored Usernames and Password". It is how IE stores and retrieve
// credentials. By using the CRED_TYPE_SERVER_CREDENTIAL flag allows IE and VS to
// share credentials.
// We dont specify the CREDUI_FLAGS_EXPECT_CONFIRMATION as the VS proxy service consumers
// dont call back into the service to confirm that the call succeeded.
NativeMethods.CREDUI_FLAGS flags = NativeMethods.CREDUI_FLAGS.SERVER_CREDENTIAL |
NativeMethods.CREDUI_FLAGS.SHOW_SAVE_CHECK_BOX |
NativeMethods.CREDUI_FLAGS.COMPLETE_USERNAME |
NativeMethods.CREDUI_FLAGS.EXCLUDE_CERTIFICATES;
StringBuilder user = new StringBuilder(Convert.ToInt32(NativeMethods.CREDUI_MAX_USERNAME_LENGTH));
StringBuilder pwd = new StringBuilder(Convert.ToInt32(NativeMethods.CREDUI_MAX_PASSWORD_LENGTH));
int saveCredentials = 0;
// Ensures that CredUPPromptForCredentials results in a prompt.
int netError = NativeMethods.ERROR_LOGON_FAILURE;
// Call the OS API to prompt for credentials.
NativeMethods.CredUIReturnCodes result = NativeMethods.CredUIPromptForCredentials(
info,
target,
IntPtr.Zero,
netError,
user,
NativeMethods.CREDUI_MAX_USERNAME_LENGTH,
pwd,
NativeMethods.CREDUI_MAX_PASSWORD_LENGTH,
ref saveCredentials,
flags);
if (result == NativeMethods.CredUIReturnCodes.NO_ERROR) {
userName = user.ToString();
password = pwd.ToString();
try {
if (Convert.ToBoolean(saveCredentials)) {
// Try reading the credentials back to ensure that we can read the stored credentials. If
// the CredUIPromptForCredentials() function is not able successfully call CredGetTargetInfo(),
// it will store credentials with credential type as DOMAIN_PASSWORD. For DOMAIN_PASSWORD
// credential type we can only retrive the user name. As a workaround, we store the credentials
// as credential type as GENERIC.
string storedUserName;
string storedPassword;
bool successfullyReadCredentials = ReadOSCredentials(target, out storedUserName, out storedPassword);
if (!successfullyReadCredentials ||
!string.Equals(userName, storedUserName, StringComparison.Ordinal) ||
!string.Equals(password, storedPassword, StringComparison.Ordinal)) {
// We are not able to retrieve the credentials. Try storing them as GENERIC credetails.
// Create the NativeCredential object.
NativeMethods.NativeCredential customCredential = new NativeMethods.NativeCredential();
customCredential.userName = userName;
customCredential.type = NativeMethods.CRED_TYPE_GENERIC;
customCredential.targetName = CreateCustomTarget(target);
// Store credentials across sessions.
customCredential.persist = (uint)NativeMethods.CRED_PERSIST.LOCAL_MACHINE;
if (!string.IsNullOrEmpty(password)) {
customCredential.credentialBlobSize = (uint)Marshal.SystemDefaultCharSize * ((uint)password.Length);
customCredential.credentialBlob = Marshal.StringToCoTaskMemAuto(password);
}
try {
NativeMethods.CredWrite(ref customCredential, 0);
} finally {
if (customCredential.credentialBlob != IntPtr.Zero) {
Marshal.FreeCoTaskMem(customCredential.credentialBlob);
}
}
}
}
} catch {
// Ignore that failure to read back the credentials. We still have
// username and password to use in the current session.
}
retValue = DialogResult.OK;
} else if (result == NativeMethods.CredUIReturnCodes.ERROR_CANCELLED) {
retValue = DialogResult.Cancel;
} else {
Debug.Fail("CredUIPromptForCredentials failed with result = " + result.ToString());
retValue = DialogResult.Cancel;
}
info.Dispose();
return retValue;
}
/// <summary>
/// Generates a NetworkCredential object from username and password. The function will
/// parse username part and invoke the correct NetworkCredential construction.
/// </summary>
/// <param name="username">username retrieved from user/registry.</param>
/// <param name="password">password retrieved from user/registry.</param>
/// <returns></returns>
private static NetworkCredential CreateCredentials(string username, string password, string targetServer) {
NetworkCredential cred = null;
if ((!string.IsNullOrEmpty(username)) && (!string.IsNullOrEmpty(password))) {
string domain;
string user;
if (ParseUsername(username, targetServer, out user, out domain)) {
if (string.IsNullOrEmpty(domain)) {
cred = new NetworkCredential(user, password);
} else {
cred = new NetworkCredential(user, password, domain);
}
}
}
return cred;
}
/// <summary>
/// This fuction calls CredUIParseUserName() to parse the user name.
/// </summary>
/// <param name="username">The username name to pass.</param>
/// <param name="targetServer">The target for which username is being parsed.</param>
/// <param name="user">The user part of the username.</param>
/// <param name="domain">The domain part of the username.</param>
/// <returns>Returns true if it successfully parsed the username.</returns>
private static bool ParseUsername(string username, string targetServer, out string user, out string domain) {
user = string.Empty;
domain = string.Empty;
if (string.IsNullOrEmpty(username)) {
return false;
}
bool successfullyParsed = true;
StringBuilder strUser = new StringBuilder(Convert.ToInt32(NativeMethods.CREDUI_MAX_USERNAME_LENGTH));
StringBuilder strDomain = new StringBuilder(Convert.ToInt32(NativeMethods.CREDUI_MAX_DOMAIN_TARGET_LENGTH));
// Call the OS API to do the parsing.
NativeMethods.CredUIReturnCodes result = NativeMethods.CredUIParseUserName(username,
strUser,
NativeMethods.CREDUI_MAX_USERNAME_LENGTH,
strDomain,
NativeMethods.CREDUI_MAX_DOMAIN_TARGET_LENGTH);
successfullyParsed = (result == NativeMethods.CredUIReturnCodes.NO_ERROR);
if (successfullyParsed) {
user = strUser.ToString();
domain = strDomain.ToString();
// Remove the domain part if domain is same as target. This is to workaround
// the COMPLETE_USERNAME flag which add the target to the user name as the
// domain component.
// Read comments in ShowOSCredentialDialog() for more details.
if (!string.IsNullOrEmpty(domain) &&
string.Equals(domain, targetServer, StringComparison.OrdinalIgnoreCase)) {
domain = string.Empty;
}
}
return successfullyParsed;
}
/// <summary>
/// Retrieves credentials from the OS store.
/// </summary>
/// <param name="target">The credential target.</param>
/// <param name="username">The retrieved username.</param>
/// <param name="password">The retrieved password.</param>
/// <returns>Returns true if it successfully reads the OS credentials.</returns>
private static bool ReadOSCredentials(string target, out string username, out string password) {
username = string.Empty;
password = string.Empty;
if (string.IsNullOrEmpty(target)) {
return false;
}
IntPtr credPtr = IntPtr.Zero;
IntPtr customCredPtr = IntPtr.Zero;
try {
bool queriedDomainPassword = false;
bool readCredentials = true;
// Query the OS credential store.
if (!NativeMethods.CredRead(
target,
NativeMethods.CRED_TYPE_GENERIC,
0,
out credPtr)) {
readCredentials = false;
// Query for the DOMAIN_PASSWORD credential type to retrieve the
// credentials. CredUPromptForCredentials will store credentials
// as DOMAIN_PASSWORD credential type if it is not able to resolve
// the target using CredGetTargetInfo() function.
if (Marshal.GetLastWin32Error() == NativeMethods.ERROR_NOT_FOUND) {
queriedDomainPassword = true;
// try queryiing for CRED_TYPE_DOMAIN_PASSWORD
if (NativeMethods.CredRead(
target,
NativeMethods.CRED_TYPE_DOMAIN_PASSWORD,
0,
out credPtr)) {
readCredentials = true;
}
}
}
if (readCredentials) {
// Get the native credentials if CredRead succeeds.
NativeMethods.NativeCredential nativeCredential = (NativeMethods.NativeCredential)Marshal.PtrToStructure(credPtr, typeof(NativeMethods.NativeCredential));
password = (nativeCredential.credentialBlob != IntPtr.Zero) ?
Marshal.PtrToStringUni(nativeCredential.credentialBlob, (int)(nativeCredential.credentialBlobSize / Marshal.SystemDefaultCharSize))
: string.Empty;
username = nativeCredential.userName;
// If we retrieved the username using the credentials type as DOMAIN_PASSWORD, and
// we are not able to retrieve password, we query the GENERIC credentials to
// retrieve the password. Read comments in the ShowOSCredentialDialog() funtion
// for more details.
if (string.IsNullOrEmpty(password) && queriedDomainPassword) {
// Read custom credentials.
if (NativeMethods.CredRead(
CreateCustomTarget(target),
NativeMethods.CRED_TYPE_GENERIC,
0,
out customCredPtr)) {
NativeMethods.NativeCredential customNativeCredential = (NativeMethods.NativeCredential)Marshal.PtrToStructure(customCredPtr, typeof(NativeMethods.NativeCredential));
if (string.Equals(username, customNativeCredential.userName, StringComparison.OrdinalIgnoreCase)) {
password = (customNativeCredential.credentialBlob != IntPtr.Zero) ?
Marshal.PtrToStringUni(customNativeCredential.credentialBlob, (int)(customNativeCredential.credentialBlobSize / Marshal.SystemDefaultCharSize))
: string.Empty;
}
}
}
}
} catch (Exception) {
username = string.Empty;
password = string.Empty;
} finally {
if (credPtr != IntPtr.Zero) {
NativeMethods.CredFree(credPtr);
}
if (customCredPtr != IntPtr.Zero) {
NativeMethods.CredFree(customCredPtr);
}
}
bool successfullyReadCredentials = true;
if (string.IsNullOrEmpty(username) ||
string.IsNullOrEmpty(password)) {
username = string.Empty;
password = string.Empty;
successfullyReadCredentials = false;
}
return successfullyReadCredentials;
}
/// <summary>
/// Generates the generic target name.
/// </summary>
/// <param name="target">The credetial target.</param>
/// <returns>The generic target.</returns>
private static string CreateCustomTarget(string target) {
if (string.IsNullOrEmpty(target)) {
return string.Empty;
}
return "Credentials_" + target;
}
}
#region NativeMethods
static class NativeMethods {
private const string advapi32Dll = "advapi32.dll";
private const string credUIDll = "credui.dll";
private const string user32Dll = "User32.dll";
private const string sensapiDll = "sensapi.dll";
public const int
ERROR_INVALID_FLAGS = 1004, // Invalid flags.
ERROR_NOT_FOUND = 1168, // Element not found.
ERROR_NO_SUCH_LOGON_SESSION = 1312, // A specified logon session does not exist. It may already have been terminated.
ERROR_LOGON_FAILURE = 1326; // Logon failure: unknown user name or bad password.
[Flags]
public enum CREDUI_FLAGS : uint {
INCORRECT_PASSWORD = 0x1,
DO_NOT_PERSIST = 0x2,
REQUEST_ADMINISTRATOR = 0x4,
EXCLUDE_CERTIFICATES = 0x8,
REQUIRE_CERTIFICATE = 0x10,
SHOW_SAVE_CHECK_BOX = 0x40,
ALWAYS_SHOW_UI = 0x80,
REQUIRE_SMARTCARD = 0x100,
PASSWORD_ONLY_OK = 0x200,
VALIDATE_USERNAME = 0x400,
COMPLETE_USERNAME = 0x800,
PERSIST = 0x1000,
SERVER_CREDENTIAL = 0x4000,
EXPECT_CONFIRMATION = 0x20000,
GENERIC_CREDENTIALS = 0x40000,
USERNAME_TARGET_CREDENTIALS = 0x80000,
KEEP_USERNAME = 0x100000,
}
[StructLayout(LayoutKind.Sequential)]
public class CREDUI_INFO : IDisposable {
public int cbSize;
public IntPtr hwndParentCERParent;
[MarshalAs(UnmanagedType.LPWStr)]
public string pszMessageText;
[MarshalAs(UnmanagedType.LPWStr)]
public string pszCaptionText;
public IntPtr hbmBannerCERHandle;
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing) {
if (disposing) {
// Release managed resources.
}
// Free the unmanaged resource ...
hwndParentCERParent = IntPtr.Zero;
hbmBannerCERHandle = IntPtr.Zero;
}
~CREDUI_INFO() {
Dispose(false);
}
}
public enum CredUIReturnCodes : uint {
NO_ERROR = 0,
ERROR_CANCELLED = 1223,
ERROR_NO_SUCH_LOGON_SESSION = 1312,
ERROR_NOT_FOUND = 1168,
ERROR_INVALID_ACCOUNT_NAME = 1315,
ERROR_INSUFFICIENT_BUFFER = 122,
ERROR_INVALID_PARAMETER = 87,
ERROR_INVALID_FLAGS = 1004,
}
// Copied from wincred.h
public const uint
// Values of the Credential Type field.
CRED_TYPE_GENERIC = 1,
CRED_TYPE_DOMAIN_PASSWORD = 2,
CRED_TYPE_DOMAIN_CERTIFICATE = 3,
CRED_TYPE_DOMAIN_VISIBLE_PASSWORD = 4,
CRED_TYPE_MAXIMUM = 5, // Maximum supported cred type
CRED_TYPE_MAXIMUM_EX = (CRED_TYPE_MAXIMUM + 1000), // Allow new applications to run on old OSes
// String limits
CRED_MAX_CREDENTIAL_BLOB_SIZE = 512, // Maximum size of the CredBlob field (in bytes)
CRED_MAX_STRING_LENGTH = 256, // Maximum length of the various credential string fields (in characters)
CRED_MAX_USERNAME_LENGTH = (256 + 1 + 256), // Maximum length of the UserName field. The worst case is <User>@<DnsDomain>
CRED_MAX_GENERIC_TARGET_NAME_LENGTH = 32767, // Maximum length of the TargetName field for CRED_TYPE_GENERIC (in characters)
CRED_MAX_DOMAIN_TARGET_NAME_LENGTH = (256 + 1 + 80), // Maximum length of the TargetName field for CRED_TYPE_DOMAIN_* (in characters). Largest one is <DfsRoot>\<DfsShare>
CRED_MAX_VALUE_SIZE = 256, // Maximum size of the Credential Attribute Value field (in bytes)
CRED_MAX_ATTRIBUTES = 64, // Maximum number of attributes per credential
CREDUI_MAX_MESSAGE_LENGTH = 32767,
CREDUI_MAX_CAPTION_LENGTH = 128,
CREDUI_MAX_GENERIC_TARGET_LENGTH = CRED_MAX_GENERIC_TARGET_NAME_LENGTH,
CREDUI_MAX_DOMAIN_TARGET_LENGTH = CRED_MAX_DOMAIN_TARGET_NAME_LENGTH,
CREDUI_MAX_USERNAME_LENGTH = CRED_MAX_USERNAME_LENGTH,
CREDUI_MAX_PASSWORD_LENGTH = (CRED_MAX_CREDENTIAL_BLOB_SIZE / 2);
internal enum CRED_PERSIST : uint {
NONE = 0,
SESSION = 1,
LOCAL_MACHINE = 2,
ENTERPRISE = 3,
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct NativeCredential {
public uint flags;
public uint type;
public string targetName;
public string comment;
public int lastWritten_lowDateTime;
public int lastWritten_highDateTime;
public uint credentialBlobSize;
public IntPtr credentialBlob;
public uint persist;
public uint attributeCount;
public IntPtr attributes;
public string targetAlias;
public string userName;
};
[DllImport(advapi32Dll, CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "CredReadW")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool
CredRead(
[MarshalAs(UnmanagedType.LPWStr)]
string targetName,
[MarshalAs(UnmanagedType.U4)]
uint type,
[MarshalAs(UnmanagedType.U4)]
uint flags,
out IntPtr credential
);
[DllImport(advapi32Dll, CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "CredWriteW")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool
CredWrite(
ref NativeCredential Credential,
[MarshalAs(UnmanagedType.U4)]
uint flags
);
[DllImport(advapi32Dll)]
public static extern void
CredFree(
IntPtr buffer
);
[DllImport(credUIDll, EntryPoint = "CredUIPromptForCredentialsW", CharSet = CharSet.Unicode)]
public static extern CredUIReturnCodes CredUIPromptForCredentials(
CREDUI_INFO pUiInfo, // Optional (one can pass null here)
[MarshalAs(UnmanagedType.LPWStr)]
string targetName,
IntPtr Reserved, // Must be 0 (IntPtr.Zero)
int iError,
[MarshalAs(UnmanagedType.LPWStr)]
StringBuilder pszUserName,
[MarshalAs(UnmanagedType.U4)]
uint ulUserNameMaxChars,
[MarshalAs(UnmanagedType.LPWStr)]
StringBuilder pszPassword,
[MarshalAs(UnmanagedType.U4)]
uint ulPasswordMaxChars,
ref int pfSave,
CREDUI_FLAGS dwFlags);
/// <returns>
/// Win32 system errors:
/// NO_ERROR
/// ERROR_INVALID_ACCOUNT_NAME
/// ERROR_INSUFFICIENT_BUFFER
/// ERROR_INVALID_PARAMETER
/// </returns>
[DllImport(credUIDll, CharSet = CharSet.Auto, SetLastError = true, EntryPoint = "CredUIParseUserNameW")]
public static extern CredUIReturnCodes CredUIParseUserName(
[MarshalAs(UnmanagedType.LPWStr)]
string strUserName,
[MarshalAs(UnmanagedType.LPWStr)]
StringBuilder strUser,
[MarshalAs(UnmanagedType.U4)]
uint iUserMaxChars,
[MarshalAs(UnmanagedType.LPWStr)]
StringBuilder strDomain,
[MarshalAs(UnmanagedType.U4)]
uint iDomainMaxChars
);
}
#endregion
}
| |
// Copyright 2009 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using System;
using NodaTime.Test.TimeZones.IO;
using NodaTime.TimeZones;
using NUnit.Framework;
namespace NodaTime.Test.TimeZones
{
public class ZoneYearOffsetTest
{
[Test]
public void Construct_InvalidMonth_Exception()
{
Assert.Throws(typeof(ArgumentOutOfRangeException), () => new ZoneYearOffset(TransitionMode.Standard, 0, 1, 1, true, LocalTime.Midnight), "Month 0");
Assert.Throws(typeof(ArgumentOutOfRangeException), () => new ZoneYearOffset(TransitionMode.Standard, 34, 1, 1, true, LocalTime.Midnight), "Month 34");
Assert.Throws(typeof(ArgumentOutOfRangeException), () => new ZoneYearOffset(TransitionMode.Standard, -3, 1, 1, true, LocalTime.Midnight), "Month -3");
}
[Test]
public void Construct_InvalidDayOfMonth_Exception()
{
Assert.Throws(typeof(ArgumentOutOfRangeException), () => new ZoneYearOffset(TransitionMode.Standard, 2, 0, 1, true, LocalTime.Midnight), "Day of Month 0");
Assert.Throws(typeof(ArgumentOutOfRangeException), () => new ZoneYearOffset(TransitionMode.Standard, 2, 32, 1, true, LocalTime.Midnight), "Day of Month 32");
Assert.Throws(typeof(ArgumentOutOfRangeException), () => new ZoneYearOffset(TransitionMode.Standard, 2, 475, 1, true, LocalTime.Midnight),
"Day of Month 475");
Assert.Throws(typeof(ArgumentOutOfRangeException), () => new ZoneYearOffset(TransitionMode.Standard, 2, -32, 1, true, LocalTime.Midnight),
"Day of Month -32");
}
[Test]
public void Construct_InvalidDayOfWeek_Exception()
{
Assert.Throws(typeof(ArgumentOutOfRangeException), () => new ZoneYearOffset(TransitionMode.Standard, 2, 3, -1, true, LocalTime.Midnight), "Day of Week -1");
Assert.Throws(typeof(ArgumentOutOfRangeException), () => new ZoneYearOffset(TransitionMode.Standard, 2, 3, 8, true, LocalTime.Midnight), "Day of Week 8");
Assert.Throws(typeof(ArgumentOutOfRangeException), () => new ZoneYearOffset(TransitionMode.Standard, 2, 3, 5756, true, LocalTime.Midnight),
"Day of Week 5856");
Assert.Throws(typeof(ArgumentOutOfRangeException), () => new ZoneYearOffset(TransitionMode.Standard, 2, 3, -347, true, LocalTime.Midnight),
"Day of Week -347");
}
[Test]
public void Construct_ValidMonths()
{
for (int month = 1; month <= 12; month++)
{
Assert.NotNull(new ZoneYearOffset(TransitionMode.Standard, month, 1, 1, true, LocalTime.Midnight), "Month " + month);
}
}
[Test]
public void Construct_ValidDays()
{
for (int day = 1; day <= 31; day++)
{
Assert.NotNull(new ZoneYearOffset(TransitionMode.Standard, 1, day, 1, true, LocalTime.Midnight), "Day " + day);
}
for (int day = -1; day >= -31; day--)
{
Assert.NotNull(new ZoneYearOffset(TransitionMode.Standard, 1, day, 1, true, LocalTime.Midnight), "Day " + day);
}
}
[Test]
public void Construct_ValidDaysOfWeek()
{
for (int dayOfWeek = 0; dayOfWeek <= 7; dayOfWeek++)
{
Assert.NotNull(new ZoneYearOffset(TransitionMode.Standard, 1, 1, dayOfWeek, true, LocalTime.Midnight), "Day of week " + dayOfWeek);
}
}
[Test]
public void GetOccurrenceForYear_Defaults_Epoch()
{
var offset = new ZoneYearOffset(TransitionMode.Utc, 1, 1, 0, true, LocalTime.Midnight);
var actual = offset.GetOccurrenceForYear(1970);
var expected = new LocalDateTime(1970, 1, 1, 0, 0).ToLocalInstant();
Assert.AreEqual(expected, actual);
}
[Test]
public void GetOccurrenceForYear_Year_1971()
{
var offset = new ZoneYearOffset(TransitionMode.Utc, 1, 1, 0, true, LocalTime.Midnight);
var actual = offset.GetOccurrenceForYear(1971);
var expected = new LocalDateTime(1971, 1, 1, 0, 0).ToLocalInstant();
Assert.AreEqual(expected, actual);
}
[Test]
public void GetOccurrenceForYear_Milliseconds()
{
var offset = new ZoneYearOffset(TransitionMode.Utc, 1, 1, 0, true, new LocalTime(0, 0, 0, 1));
var actual = offset.GetOccurrenceForYear(1970);
var expected = new LocalDateTime(1970, 1, 1, 0, 0, 0, 1).ToLocalInstant();
Assert.AreEqual(expected, actual);
}
[Test]
public void GetOccurrenceForYear_WednesdayForward()
{
var offset = new ZoneYearOffset(TransitionMode.Utc, 1, 1, (int)DayOfWeek.Wednesday, true, LocalTime.Midnight);
var actual = offset.GetOccurrenceForYear(1970);
var expected = new LocalDateTime(1970, 1, 7, 0, 0).ToLocalInstant(); // 1970-01-01 was a Thursday
Assert.AreEqual(expected, actual);
}
[Test]
public void GetOccurrenceForYear_WednesdayBackward()
{
var offset = new ZoneYearOffset(TransitionMode.Utc, 1, 15, (int)DayOfWeek.Wednesday, false, LocalTime.Midnight);
var actual = offset.GetOccurrenceForYear(1970);
var expected = new LocalDateTime(1970, 1, 14, 0, 0).ToLocalInstant(); // 1970-01-15 was a Thursday
Assert.AreEqual(expected, actual);
}
[Test]
public void GetOccurrenceForYear_JanMinusTwo()
{
var offset = new ZoneYearOffset(TransitionMode.Utc, 1, -2, 0, true, LocalTime.Midnight);
var actual = offset.GetOccurrenceForYear(1970);
var expected = new LocalDateTime(1970, 1, 30, 0, 0).ToLocalInstant();
Assert.AreEqual(expected, actual);
}
[Test]
public void GetOccurrenceForYear_JanFive()
{
var offset = new ZoneYearOffset(TransitionMode.Utc, 1, 5, 0, true, LocalTime.Midnight);
var actual = offset.GetOccurrenceForYear(1970);
var expected = new LocalDateTime(1970, 1, 5, 0, 0).ToLocalInstant();
Assert.AreEqual(expected, actual);
}
[Test]
public void GetOccurrenceForYear_Feb()
{
var offset = new ZoneYearOffset(TransitionMode.Utc, 2, 1, 0, true, LocalTime.Midnight);
var actual = offset.GetOccurrenceForYear(1970);
var expected = new LocalDateTime(1970, 2, 1, 0, 0).ToLocalInstant();
Assert.AreEqual(expected, actual);
}
[Test]
public void GetOccurrenceForYear_LastSundayInOctober()
{
ZoneYearOffset offset = new ZoneYearOffset(TransitionMode.Utc, 10, -1, (int)IsoDayOfWeek.Sunday, false, LocalTime.Midnight);
var actual = offset.GetOccurrenceForYear(1996);
var expected = new LocalDateTime(1996, 10, 27, 0, 0).ToLocalInstant();
Assert.AreEqual(expected, actual);
}
[Test]
public void GetOccurrenceForYear_ExactlyFeb29th_LeapYear()
{
ZoneYearOffset offset = new ZoneYearOffset(TransitionMode.Utc, 2, 29, 0, false, LocalTime.Midnight);
var actual = offset.GetOccurrenceForYear(2012);
var expected = new LocalDateTime(2012, 2, 29, 0, 0).ToLocalInstant();
Assert.AreEqual(expected, actual);
}
[Test]
public void GetOccurrenceForYear_ExactlyFeb29th_NotLeapYear()
{
ZoneYearOffset offset = new ZoneYearOffset(TransitionMode.Utc, 2, 29, 0, false, LocalTime.Midnight);
var actual = offset.GetOccurrenceForYear(2013);
var expected = new LocalDateTime(2013, 2, 28, 0, 0).ToLocalInstant(); // For "exact", go to Feb 28th
Assert.AreEqual(expected, actual);
}
[Test]
public void GetOccurrenceForYear_AtLeastFeb29th_LeapYear()
{
ZoneYearOffset offset = new ZoneYearOffset(TransitionMode.Utc, 2, 29, (int) IsoDayOfWeek.Sunday, true, LocalTime.Midnight);
var actual = offset.GetOccurrenceForYear(2012);
var expected = new LocalDateTime(2012, 3, 4, 0, 0).ToLocalInstant(); // March 4th is the first Sunday after 2012-02-29
Assert.AreEqual(expected, actual);
}
[Test]
public void GetOccurrenceForYear_AtLeastFeb29th_NotLeapYear()
{
ZoneYearOffset offset = new ZoneYearOffset(TransitionMode.Utc, 2, 29, (int) IsoDayOfWeek.Sunday, true, LocalTime.Midnight);
var actual = offset.GetOccurrenceForYear(2013);
var expected = new LocalDateTime(2013, 3, 3, 0, 0).ToLocalInstant(); // March 3rd is the first Sunday after the non-existent 2013-02-29
Assert.AreEqual(expected, actual);
}
[Test]
public void GetOccurrenceForYear_AtMostFeb29th_LeapYear()
{
ZoneYearOffset offset = new ZoneYearOffset(TransitionMode.Utc, 2, 29, (int) IsoDayOfWeek.Sunday, false, LocalTime.Midnight);
var actual = offset.GetOccurrenceForYear(2012);
var expected = new LocalDateTime(2012, 2, 26, 0, 0).ToLocalInstant(); // Feb 26th is the last Sunday before 2012-02-29
Assert.AreEqual(expected, actual);
}
[Test]
public void GetOccurrenceForYear_AtMostFeb29th_NotLeapYear()
{
ZoneYearOffset offset = new ZoneYearOffset(TransitionMode.Utc, 2, 29, (int) IsoDayOfWeek.Sunday, false, LocalTime.Midnight);
var actual = offset.GetOccurrenceForYear(2013);
var expected = new LocalDateTime(2013, 2, 24, 0, 0).ToLocalInstant(); // Feb 24th is the last Sunday is February 2013
Assert.AreEqual(expected, actual);
}
[Test]
public void GetOccurrenceForYear_WithAddDay()
{
// Last Thursday in October, then add 24 hours. The last Thursday in October 2013 is the 31st, so
// we should get the start of November 1st.
var offset = new ZoneYearOffset(TransitionMode.Utc, 10, -1, (int) IsoDayOfWeek.Thursday, false, LocalTime.Midnight, true);
var actual = offset.GetOccurrenceForYear(2013);
var expected = new LocalDateTime(2013, 11, 1, 0, 0).ToLocalInstant();
Assert.AreEqual(expected, actual);
}
[Test]
public void GetOccurrenceForYear_WithAddDay_December31st9999()
{
var offset = new ZoneYearOffset(TransitionMode.Utc, 12, 31, 0, false, LocalTime.Midnight, true);
var actual = offset.GetOccurrenceForYear(9999);
var expected = LocalInstant.AfterMaxValue;
Assert.AreEqual(expected, actual);
}
[Test]
public void Serialization()
{
var dio = DtzIoHelper.CreateNoStringPool();
var expected = new ZoneYearOffset(TransitionMode.Utc, 10, 31, (int)IsoDayOfWeek.Wednesday, true,
new LocalTime(12, 34, 45, 678));
dio.TestZoneYearOffset(expected);
dio.Reset();
expected = new ZoneYearOffset(TransitionMode.Utc, 10, -31, (int)IsoDayOfWeek.Wednesday, true, LocalTime.Midnight);
dio.TestZoneYearOffset(expected);
}
[Test]
public void IEquatable_Tests()
{
var value = new ZoneYearOffset(TransitionMode.Utc, 10, 31, (int)IsoDayOfWeek.Wednesday, true, LocalTime.Midnight);
var equalValue = new ZoneYearOffset(TransitionMode.Utc, 10, 31, (int)IsoDayOfWeek.Wednesday, true, LocalTime.Midnight);
var unequalValue = new ZoneYearOffset(TransitionMode.Utc, 9, 31, (int)IsoDayOfWeek.Wednesday, true, LocalTime.Midnight);
TestHelper.TestEqualsClass(value, equalValue, unequalValue);
}
}
}
| |
/* ====================================================================
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 NPOI.HSSF.Extractor
{
using System;
using System.Text;
using NPOI.HSSF.UserModel;
using NPOI.POIFS.FileSystem;
using NPOI;
using NPOI.SS.Formula.Eval;
using NPOI.SS.UserModel;
using NPOI.SS.Extractor;
/// <summary>
/// A text extractor for Excel files.
/// Returns the textual content of the file, suitable for
/// indexing by something like Lucene, but not really
/// intended for display to the user.
/// </summary>
public class ExcelExtractor : POIOLE2TextExtractor, IExcelExtractor
{
private HSSFWorkbook wb;
private HSSFDataFormatter _formatter;
private bool includeSheetNames = true;
private bool formulasNotResults = false;
private bool includeCellComments = false;
private bool includeBlankCells = false;
private bool includeHeaderFooter = true;
/// <summary>
/// Initializes a new instance of the <see cref="ExcelExtractor"/> class.
/// </summary>
/// <param name="wb">The wb.</param>
public ExcelExtractor(HSSFWorkbook wb)
: base(wb)
{
this.wb = wb;
_formatter = new HSSFDataFormatter();
}
/// <summary>
/// Initializes a new instance of the <see cref="ExcelExtractor"/> class.
/// </summary>
/// <param name="fs">The fs.</param>
public ExcelExtractor(POIFSFileSystem fs)
: this(new HSSFWorkbook(fs))
{
}
/// <summary>
/// Should header and footer be included? Default is true
/// </summary>
public bool IncludeHeaderFooter
{
get {
return this.includeHeaderFooter;
}
set {
this.includeHeaderFooter = value;
}
}
/// <summary>
/// Should sheet names be included? Default is true
/// </summary>
/// <value>if set to <c>true</c> [include sheet names].</value>
public bool IncludeSheetNames
{
get {
return this.includeSheetNames;
}
set
{
this.includeSheetNames = value;
}
}
/// <summary>
/// Should we return the formula itself, and not
/// the result it produces? Default is false
/// </summary>
/// <value>if set to <c>true</c> [formulas not results].</value>
public bool FormulasNotResults
{
get
{
return this.formulasNotResults;
}
set
{
this.formulasNotResults = value;
}
}
/// <summary>
/// Should cell comments be included? Default is false
/// </summary>
/// <value>if set to <c>true</c> [include cell comments].</value>
public bool IncludeCellComments
{
get
{
return this.includeCellComments;
}
set
{
this.includeCellComments = value;
}
}
/// <summary>
/// Should blank cells be output? Default is to only
/// output cells that are present in the file and are
/// non-blank.
/// </summary>
/// <value>if set to <c>true</c> [include blank cells].</value>
public bool IncludeBlankCells
{
get
{
return this.includeBlankCells;
}
set
{
this.includeBlankCells = value;
}
}
/// <summary>
/// Retreives the text contents of the file
/// </summary>
/// <value>All the text from the document.</value>
public override String Text
{
get
{
StringBuilder text = new StringBuilder();
// We don't care about the differnce between
// null (missing) and blank cells
wb.MissingCellPolicy = MissingCellPolicy.RETURN_BLANK_AS_NULL;
// Process each sheet in turn
for (int i = 0; i < wb.NumberOfSheets; i++)
{
HSSFSheet sheet = (HSSFSheet)wb.GetSheetAt(i);
if (sheet == null) { continue; }
if (includeSheetNames)
{
String name = wb.GetSheetName(i);
if (name != null)
{
text.Append(name);
text.Append("\n");
}
}
// Header text, if there is any
if (sheet.Header != null && includeHeaderFooter)
{
text.Append(
ExtractHeaderFooter(sheet.Header)
);
}
int firstRow = sheet.FirstRowNum;
int lastRow = sheet.LastRowNum;
for (int j = firstRow; j <= lastRow; j++)
{
IRow row = sheet.GetRow(j);
if (row == null) { continue; }
// Check each cell in turn
int firstCell = row.FirstCellNum;
int lastCell = row.LastCellNum;
if (includeBlankCells)
{
firstCell = 0;
}
for (int k = firstCell; k < lastCell; k++)
{
ICell cell = row.GetCell(k);
bool outputContents = true;
if (cell == null)
{
// Only output if requested
outputContents = includeBlankCells;
}
else
{
switch (cell.CellType)
{
case CellType.String:
text.Append(cell.RichStringCellValue.String);
break;
case CellType.Numeric:
// Note - we don't apply any formatting!
//text.Append(cell.NumericCellValue);
text.Append(_formatter.FormatCellValue(cell));
break;
case CellType.Boolean:
text.Append(cell.BooleanCellValue);
break;
case CellType.Error:
text.Append(ErrorEval.GetText(cell.ErrorCellValue));
break;
case CellType.Formula:
if (formulasNotResults)
{
text.Append(cell.CellFormula);
}
else
{
switch (cell.CachedFormulaResultType)
{
case CellType.String:
IRichTextString str = cell.RichStringCellValue;
if (str != null && str.Length > 0)
{
text.Append(str.ToString());
}
break;
case CellType.Numeric:
//text.Append(cell.NumericCellValue);
HSSFCellStyle style = (HSSFCellStyle)cell.CellStyle;
if (style == null)
{
text.Append(cell.NumericCellValue);
}
else
{
text.Append(
_formatter.FormatRawCellContents(
cell.NumericCellValue,
style.DataFormat,
style.GetDataFormatString()
)
);
}
break;
case CellType.Boolean:
text.Append(cell.BooleanCellValue);
break;
case CellType.Error:
text.Append(ErrorEval.GetText(cell.ErrorCellValue));
break;
}
}
break;
default:
throw new Exception("Unexpected cell type (" + cell.CellType + ")");
}
// Output the comment, if requested and exists
NPOI.SS.UserModel.IComment comment = cell.CellComment;
if (includeCellComments && comment != null)
{
// Replace any newlines with spaces, otherwise it
// breaks the output
String commentText = comment.String.String.Replace('\n', ' ');
text.Append(" Comment by " + comment.Author + ": " + commentText);
}
}
// Output a tab if we're not on the last cell
if (outputContents && k < (lastCell - 1))
{
text.Append("\t");
}
}
// Finish off the row
text.Append("\n");
}
// Finally Feader text, if there is any
if (sheet.Footer != null && includeHeaderFooter)
{
text.Append(
ExtractHeaderFooter(sheet.Footer)
);
}
}
return text.ToString();
}
}
/// <summary>
/// Extracts the header footer.
/// </summary>
/// <param name="hf">The header or footer</param>
/// <returns></returns>
public static String ExtractHeaderFooter(NPOI.SS.UserModel.IHeaderFooter hf)
{
StringBuilder text = new StringBuilder();
if (hf.Left != null)
{
text.Append(hf.Left);
}
if (hf.Center != null)
{
if (text.Length > 0)
text.Append("\t");
text.Append(hf.Center);
}
if (hf.Right != null)
{
if (text.Length > 0)
text.Append("\t");
text.Append(hf.Right);
}
if (text.Length > 0)
text.Append("\n");
return text.ToString();
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace CloudNotes.WebAPI.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
// 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.
#nullable enable
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
namespace System.IO
{
/// <summary>
/// Wrapper to help with path normalization.
/// </summary>
internal static class PathHelper
{
/// <summary>
/// Normalize the given path.
/// </summary>
/// <remarks>
/// Normalizes via Win32 GetFullPathName().
/// </remarks>
/// <param name="path">Path to normalize</param>
/// <exception cref="PathTooLongException">Thrown if we have a string that is too large to fit into a UNICODE_STRING.</exception>
/// <exception cref="IOException">Thrown if the path is empty.</exception>
/// <returns>Normalized path</returns>
internal static string Normalize(string path)
{
var builder = new ValueStringBuilder(stackalloc char[PathInternal.MaxShortPath]);
// Get the full path
GetFullPathName(path.AsSpan(), ref builder);
// If we have the exact same string we were passed in, don't allocate another string.
// TryExpandShortName does this input identity check.
string result = builder.AsSpan().IndexOf('~') >= 0
? TryExpandShortFileName(ref builder, originalPath: path)
: builder.AsSpan().Equals(path.AsSpan(), StringComparison.Ordinal) ? path : builder.ToString();
// Clear the buffer
builder.Dispose();
return result;
}
/// <summary>
/// Normalize the given path.
/// </summary>
/// <remarks>
/// Exceptions are the same as the string overload.
/// </remarks>
internal static string Normalize(ref ValueStringBuilder path)
{
var builder = new ValueStringBuilder(stackalloc char[PathInternal.MaxShortPath]);
// Get the full path
GetFullPathName(path.AsSpan(terminate: true), ref builder);
string result = builder.AsSpan().IndexOf('~') >= 0
? TryExpandShortFileName(ref builder, originalPath: null)
: builder.ToString();
// Clear the buffer
builder.Dispose();
return result;
}
/// <summary>
/// Calls GetFullPathName on the given path.
/// </summary>
/// <param name="path">The path name. MUST be null terminated after the span.</param>
/// <param name="builder">Builder that will store the result.</param>
private static void GetFullPathName(ReadOnlySpan<char> path, ref ValueStringBuilder builder)
{
// If the string starts with an extended prefix we would need to remove it from the path before we call GetFullPathName as
// it doesn't root extended paths correctly. We don't currently resolve extended paths, so we'll just assert here.
Debug.Assert(PathInternal.IsPartiallyQualified(path) || !PathInternal.IsExtended(path));
uint result;
while ((result = Interop.Kernel32.GetFullPathNameW(ref MemoryMarshal.GetReference(path), (uint)builder.Capacity, ref builder.GetPinnableReference(), IntPtr.Zero)) > builder.Capacity)
{
// Reported size is greater than the buffer size. Increase the capacity.
builder.EnsureCapacity(checked((int)result));
}
if (result == 0)
{
// Failure, get the error and throw
int errorCode = Marshal.GetLastWin32Error();
if (errorCode == 0)
errorCode = Interop.Errors.ERROR_BAD_PATHNAME;
throw Win32Marshal.GetExceptionForWin32Error(errorCode, path.ToString());
}
builder.Length = (int)result;
}
internal static int PrependDevicePathChars(ref ValueStringBuilder content, bool isDosUnc, ref ValueStringBuilder buffer)
{
int length = content.Length;
length += isDosUnc
? PathInternal.UncExtendedPrefixLength - PathInternal.UncPrefixLength
: PathInternal.DevicePrefixLength;
buffer.EnsureCapacity(length + 1);
buffer.Length = 0;
if (isDosUnc)
{
// Is a \\Server\Share, put \\?\UNC\ in the front
buffer.Append(PathInternal.UncExtendedPathPrefix);
// Copy Server\Share\... over to the buffer
buffer.Append(content.AsSpan(PathInternal.UncPrefixLength));
// Return the prefix difference
return PathInternal.UncExtendedPrefixLength - PathInternal.UncPrefixLength;
}
else
{
// Not an UNC, put the \\?\ prefix in front, then the original string
buffer.Append(PathInternal.ExtendedPathPrefix);
buffer.Append(content.AsSpan());
return PathInternal.DevicePrefixLength;
}
}
internal static string TryExpandShortFileName(ref ValueStringBuilder outputBuilder, string? originalPath)
{
// We guarantee we'll expand short names for paths that only partially exist. As such, we need to find the part of the path that actually does exist. To
// avoid allocating a lot we'll create only one input array and modify the contents with embedded nulls.
Debug.Assert(!PathInternal.IsPartiallyQualified(outputBuilder.AsSpan()), "should have resolved by now");
// We'll have one of a few cases by now (the normalized path will have already:
//
// 1. Dos path (C:\)
// 2. Dos UNC (\\Server\Share)
// 3. Dos device path (\\.\C:\, \\?\C:\)
//
// We want to put the extended syntax on the front if it doesn't already have it (for long path support and speed), which may mean switching from \\.\.
//
// Note that we will never get \??\ here as GetFullPathName() does not recognize \??\ and will return it as C:\??\ (or whatever the current drive is).
int rootLength = PathInternal.GetRootLength(outputBuilder.AsSpan());
bool isDevice = PathInternal.IsDevice(outputBuilder.AsSpan());
// As this is a corner case we're not going to add a stackalloc here to keep the stack pressure down.
var inputBuilder = new ValueStringBuilder();
bool isDosUnc = false;
int rootDifference = 0;
bool wasDotDevice = false;
// Add the extended prefix before expanding to allow growth over MAX_PATH
if (isDevice)
{
// We have one of the following (\\?\ or \\.\)
inputBuilder.Append(outputBuilder.AsSpan());
if (outputBuilder[2] == '.')
{
wasDotDevice = true;
inputBuilder[2] = '?';
}
}
else
{
isDosUnc = !PathInternal.IsDevice(outputBuilder.AsSpan()) && outputBuilder.Length > 1 && outputBuilder[0] == '\\' && outputBuilder[1] == '\\';
rootDifference = PrependDevicePathChars(ref outputBuilder, isDosUnc, ref inputBuilder);
}
rootLength += rootDifference;
int inputLength = inputBuilder.Length;
bool success = false;
int foundIndex = inputBuilder.Length - 1;
while (!success)
{
uint result = Interop.Kernel32.GetLongPathNameW(
ref inputBuilder.GetPinnableReference(terminate: true), ref outputBuilder.GetPinnableReference(), (uint)outputBuilder.Capacity);
// Replace any temporary null we added
if (inputBuilder[foundIndex] == '\0') inputBuilder[foundIndex] = '\\';
if (result == 0)
{
// Look to see if we couldn't find the file
int error = Marshal.GetLastWin32Error();
if (error != Interop.Errors.ERROR_FILE_NOT_FOUND && error != Interop.Errors.ERROR_PATH_NOT_FOUND)
{
// Some other failure, give up
break;
}
// We couldn't find the path at the given index, start looking further back in the string.
foundIndex--;
for (; foundIndex > rootLength && inputBuilder[foundIndex] != '\\'; foundIndex--) ;
if (foundIndex == rootLength)
{
// Can't trim the path back any further
break;
}
else
{
// Temporarily set a null in the string to get Windows to look further up the path
inputBuilder[foundIndex] = '\0';
}
}
else if (result > outputBuilder.Capacity)
{
// Not enough space. The result count for this API does not include the null terminator.
outputBuilder.EnsureCapacity(checked((int)result));
}
else
{
// Found the path
success = true;
outputBuilder.Length = checked((int)result);
if (foundIndex < inputLength - 1)
{
// It was a partial find, put the non-existent part of the path back
outputBuilder.Append(inputBuilder.AsSpan(foundIndex, inputBuilder.Length - foundIndex));
}
}
}
// If we were able to expand the path, use it, otherwise use the original full path result
ref ValueStringBuilder builderToUse = ref (success ? ref outputBuilder : ref inputBuilder);
// Switch back from \\?\ to \\.\ if necessary
if (wasDotDevice)
builderToUse[2] = '.';
// Change from \\?\UNC\ to \\?\UN\\ if needed
if (isDosUnc)
builderToUse[PathInternal.UncExtendedPrefixLength - PathInternal.UncPrefixLength] = '\\';
// Strip out any added characters at the front of the string
ReadOnlySpan<char> output = builderToUse.AsSpan(rootDifference);
string returnValue = ((originalPath != null) && output.Equals(originalPath.AsSpan(), StringComparison.Ordinal))
? originalPath : output.ToString();
inputBuilder.Dispose();
return returnValue;
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gcnv = Google.Cloud.Notebooks.V1;
using sys = System;
namespace Google.Cloud.Notebooks.V1
{
/// <summary>Resource name for the <c>Instance</c> resource.</summary>
public sealed partial class InstanceName : gax::IResourceName, sys::IEquatable<InstanceName>
{
/// <summary>The possible contents of <see cref="InstanceName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>A resource name with pattern <c>projects/{project}/instances/{instance}</c>.</summary>
ProjectInstance = 1,
}
private static gax::PathTemplate s_projectInstance = new gax::PathTemplate("projects/{project}/instances/{instance}");
/// <summary>Creates a <see cref="InstanceName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="InstanceName"/> containing the provided <paramref name="unparsedResourceName"/>
/// .
/// </returns>
public static InstanceName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new InstanceName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="InstanceName"/> with the pattern <c>projects/{project}/instances/{instance}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="instanceId">The <c>Instance</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="InstanceName"/> constructed from the provided ids.</returns>
public static InstanceName FromProjectInstance(string projectId, string instanceId) =>
new InstanceName(ResourceNameType.ProjectInstance, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), instanceId: gax::GaxPreconditions.CheckNotNullOrEmpty(instanceId, nameof(instanceId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="InstanceName"/> with pattern
/// <c>projects/{project}/instances/{instance}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="instanceId">The <c>Instance</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="InstanceName"/> with pattern
/// <c>projects/{project}/instances/{instance}</c>.
/// </returns>
public static string Format(string projectId, string instanceId) => FormatProjectInstance(projectId, instanceId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="InstanceName"/> with pattern
/// <c>projects/{project}/instances/{instance}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="instanceId">The <c>Instance</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="InstanceName"/> with pattern
/// <c>projects/{project}/instances/{instance}</c>.
/// </returns>
public static string FormatProjectInstance(string projectId, string instanceId) =>
s_projectInstance.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(instanceId, nameof(instanceId)));
/// <summary>Parses the given resource name string into a new <see cref="InstanceName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/instances/{instance}</c></description></item>
/// </list>
/// </remarks>
/// <param name="instanceName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="InstanceName"/> if successful.</returns>
public static InstanceName Parse(string instanceName) => Parse(instanceName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="InstanceName"/> instance; optionally allowing an
/// unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/instances/{instance}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="instanceName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="InstanceName"/> if successful.</returns>
public static InstanceName Parse(string instanceName, bool allowUnparsed) =>
TryParse(instanceName, allowUnparsed, out InstanceName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="InstanceName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/instances/{instance}</c></description></item>
/// </list>
/// </remarks>
/// <param name="instanceName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="InstanceName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string instanceName, out InstanceName result) => TryParse(instanceName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="InstanceName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/instances/{instance}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="instanceName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="InstanceName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string instanceName, bool allowUnparsed, out InstanceName result)
{
gax::GaxPreconditions.CheckNotNull(instanceName, nameof(instanceName));
gax::TemplatedResourceName resourceName;
if (s_projectInstance.TryParseName(instanceName, out resourceName))
{
result = FromProjectInstance(resourceName[0], resourceName[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(instanceName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private InstanceName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string instanceId = null, string projectId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
InstanceId = instanceId;
ProjectId = projectId;
}
/// <summary>
/// Constructs a new instance of a <see cref="InstanceName"/> class from the component parts of pattern
/// <c>projects/{project}/instances/{instance}</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="instanceId">The <c>Instance</c> ID. Must not be <c>null</c> or empty.</param>
public InstanceName(string projectId, string instanceId) : this(ResourceNameType.ProjectInstance, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), instanceId: gax::GaxPreconditions.CheckNotNullOrEmpty(instanceId, nameof(instanceId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Instance</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string InstanceId { get; }
/// <summary>
/// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProjectId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.ProjectInstance: return s_projectInstance.Expand(ProjectId, InstanceId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as InstanceName);
/// <inheritdoc/>
public bool Equals(InstanceName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(InstanceName a, InstanceName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(InstanceName a, InstanceName b) => !(a == b);
}
public partial class Instance
{
/// <summary>
/// <see cref="gcnv::InstanceName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcnv::InstanceName InstanceName
{
get => string.IsNullOrEmpty(Name) ? null : gcnv::InstanceName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using MySPA.Areas.HelpPage.ModelDescriptions;
using MySPA.Areas.HelpPage.Models;
namespace MySPA.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
using System.DirectoryServices.ActiveDirectory;
using DiskQuotaTypeLibrary;
using IronFrame.Utilities;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Threading;
using Xunit;
namespace IronFrame
{
public class ContainerTests
{
Container Container { get; set; }
IProcessRunner ConstrainedProcessRunner { get; set; }
Dictionary<string, string> ContainerEnvironment { get; set; }
IContainerDirectory Directory { get; set; }
JobObject JobObject { get; set; }
ProcessHelper ProcessHelper { get; set; }
IProcessRunner ProcessRunner { get; set; }
IContainerPropertyService ContainerPropertiesService { get; set; }
ILocalTcpPortManager TcpPortManager { get; set; }
IContainerUser User { get; set; }
DiskQuotaControl DiskQuotaControl { get; set; }
ContainerHostDependencyHelper DependencyHelper { get; set; }
private readonly string _containerUsername;
public ContainerTests()
{
ConstrainedProcessRunner = Substitute.For<IProcessRunner>();
ContainerEnvironment = new Dictionary<string, string>() { { "Handle", "handle" } };
Directory = Substitute.For<IContainerDirectory>();
JobObject = Substitute.For<JobObject>();
JobObject.GetCpuStatistics().Returns(new CpuStatistics
{
TotalKernelTime = TimeSpan.Zero,
TotalUserTime = TimeSpan.Zero,
});
JobObject.GetProcessIds().Returns(new int[0]);
ProcessHelper = Substitute.For<ProcessHelper>();
ProcessRunner = Substitute.For<IProcessRunner>();
ContainerPropertiesService = Substitute.For<IContainerPropertyService>();
TcpPortManager = Substitute.For<ILocalTcpPortManager>();
User = Substitute.For<IContainerUser>();
_containerUsername = string.Concat("container-username-", Guid.NewGuid().ToString());
User.UserName.Returns(_containerUsername);
DiskQuotaControl = Substitute.For<DiskQuotaControl>();
DependencyHelper = Substitute.For<ContainerHostDependencyHelper>();
Container = new Container(
string.Concat("id-", Guid.NewGuid()),
string.Concat("handle-", Guid.NewGuid()),
User,
Directory,
ContainerPropertiesService,
TcpPortManager,
JobObject,
DiskQuotaControl,
ProcessRunner,
ConstrainedProcessRunner,
ProcessHelper,
ContainerEnvironment,
DependencyHelper);
}
private EventWaitHandle CreateStopGuardEvent()
{
return new EventWaitHandle(false, EventResetMode.ManualReset, string.Concat(@"Global\discharge-", _containerUsername));
}
public class SetActiveProcessLimit : ContainerTests
{
[Fact]
public void ProxiesToJobObject()
{
uint processLimit = 8765;
this.Container.SetActiveProcessLimit(processLimit);
JobObject.Received(1).SetActiveProcessLimit(processLimit);
}
}
public class SetProcessPriority : ContainerTests
{
[Fact]
public void ProxiesToJobObject()
{
var priority = ProcessPriorityClass.RealTime;
this.Container.SetPriorityClass(priority);
JobObject.Received(1).SetPriorityClass(priority);
}
}
public class GetProperty : ContainerTests
{
public GetProperty()
{
ContainerPropertiesService.GetProperty(Container, "Name").Returns("Value");
}
[Fact]
public void ReturnsPropertyValue()
{
var value = Container.GetProperty("Name");
Assert.Equal("Value", value);
ContainerPropertiesService.Received(1).GetProperty(Container, "Name");
}
[Fact]
public void WhenPropertyDoesNotExist_ReturnsNull()
{
ContainerPropertiesService.GetProperty(Container, "Unknown").Returns((string)null);
var value = Container.GetProperty("Unknown");
Assert.Null(value);
ContainerPropertiesService.Received(1).GetProperty(Container, "Unknown");
}
}
public class GetProperties : ContainerTests
{
Dictionary<string, string> Properties { get; set; }
public GetProperties()
{
Properties = new Dictionary<string, string>();
ContainerPropertiesService.GetProperties(Container).Returns(Properties);
}
[Fact]
public void ReturnsProperties()
{
Properties["Name"] = "Value";
var properties = Container.GetProperties();
Assert.Collection(properties,
x =>
{
Assert.Equal("Name", x.Key);
Assert.Equal("Value", x.Value);
}
);
ContainerPropertiesService.Received(1).GetProperties(Container);
}
[Fact]
public void ThrowsInvalidOperationWhenIOExceptionThrownAndDestroyed()
{
Container.Destroy();
ContainerPropertiesService.GetProperties(Container).Returns(x => { throw new IOException(); });
Assert.Throws<InvalidOperationException>(() => Container.GetProperties());
}
[Fact]
public void PassesThroughExceptionIfNotDestroyed()
{
ContainerPropertiesService.GetProperties(Container).Returns(x => { throw new IOException(); });
Assert.Throws<IOException>(() => Container.GetProperties());
}
}
public class ReservePort : ContainerTests
{
[Fact]
public void ReservesPortForContainerUser()
{
Container.ReservePort(3000);
TcpPortManager.Received(1).ReserveLocalPort(3000, _containerUsername);
}
[Fact]
public void ReturnsReservedPort()
{
TcpPortManager.ReserveLocalPort(3000, _containerUsername).Returns(5000);
var port = Container.ReservePort(3000);
Assert.Equal(5000, port);
}
[Fact]
public void WhenContainerNotActive_Throws()
{
Container.Stop(false);
Action action = () => Container.ReservePort(3000);
Assert.Throws<InvalidOperationException>(action);
}
}
public class Run : ContainerTests
{
ProcessSpec Spec { get; set; }
ProcessRunSpec ExpectedRunSpec { get; set; }
public Run()
{
Spec = new ProcessSpec
{
ExecutablePath = "/.iishost/iishost.exe",
Arguments = new[] { "-p", "3000", "-r", @"/www" },
};
var containerUserPath = @"C:\Containers\handle\user\";
ExpectedRunSpec = new ProcessRunSpec
{
ExecutablePath = @"C:\Containers\handle\user\.iishost\iishost.exe",
Arguments = Spec.Arguments,
WorkingDirectory = containerUserPath,
};
Directory.MapUserPath("/.iishost/iishost.exe").Returns(ExpectedRunSpec.ExecutablePath);
Directory.MapUserPath("/").Returns(containerUserPath);
}
public class WhenPrivileged : Run
{
public WhenPrivileged()
{
Spec.Privileged = true;
}
[Fact]
public void RunsTheProcessLocally()
{
var io = Substitute.For<IProcessIO>();
var process = Container.Run(Spec, io);
Assert.NotNull(process);
var actual = ProcessRunner.Captured(x => x.Run(null)).Arg<ProcessRunSpec>();
Assert.Equal(ExpectedRunSpec.ExecutablePath, actual.ExecutablePath);
Assert.Equal(ExpectedRunSpec.Arguments, actual.Arguments);
Assert.Superset(
new HashSet<string>(ExpectedRunSpec.Environment.Keys),
new HashSet<string>(actual.Environment.Keys));
Assert.Equal(ExpectedRunSpec.WorkingDirectory, actual.WorkingDirectory);
}
[Fact]
public void ProcessIoIsRedirected()
{
var io = new TestProcessIO();
var localProcess = Substitute.For<IProcess>();
ProcessRunner.Run(Arg.Any<ProcessRunSpec>()).Returns(localProcess)
.AndDoes(call =>
{
var runSpec = call.Arg<ProcessRunSpec>();
runSpec.OutputCallback("This is STDOUT");
runSpec.ErrorCallback("This is STDERR");
});
Container.Run(Spec, io);
Assert.Equal("This is STDOUT", io.Output.ToString());
Assert.Equal("This is STDERR", io.Error.ToString());
}
[Fact]
public void WhenPathMappingIsDisabled_DoesNotMapExecutablePath()
{
var io = Substitute.For<IProcessIO>();
Spec.DisablePathMapping = true;
Spec.ExecutablePath = "cmd.exe";
var process = Container.Run(Spec, io);
Assert.NotNull(process);
var actual = ProcessRunner.Captured(x => x.Run(null)).Arg<ProcessRunSpec>();
Assert.Equal("cmd.exe", actual.ExecutablePath);
}
[Fact]
public void WhenProcessSpecHasNoEnvironment()
{
var io = Substitute.For<IProcessIO>();
var process = Container.Run(Spec, io);
var actualSpec = ProcessRunner.Captured(x => x.Run(null)).Arg<ProcessRunSpec>();
Assert.Equal(ContainerEnvironment, actualSpec.Environment);
}
[Fact]
public void WhenProcessEnvironmentConflictsWithContainerEnvironment()
{
Spec.Environment = new Dictionary<string, string>
{
{ "Handle", "procHandle" },
{ "ProcEnv", "ProcEnv" }
};
var io = Substitute.For<IProcessIO>();
var process = Container.Run(Spec, io);
var actualSpec = ProcessRunner.Captured(x => x.Run(null)).Arg<ProcessRunSpec>();
Assert.Equal(Spec.Environment, actualSpec.Environment);
}
}
public class WhenNotPrivileged : Run
{
public WhenNotPrivileged()
{
Spec.Privileged = false;
}
[Fact]
public void RunsTheProcessRemotely()
{
var io = Substitute.For<IProcessIO>();
var process = Container.Run(Spec, io);
Assert.NotNull(process);
var actual = ConstrainedProcessRunner.Captured(x => x.Run(null)).Arg<ProcessRunSpec>();
Assert.Equal(ExpectedRunSpec.ExecutablePath, actual.ExecutablePath);
Assert.Equal(ExpectedRunSpec.Arguments, actual.Arguments);
Assert.Superset(
new HashSet<string>(ExpectedRunSpec.Environment.Keys),
new HashSet<string>(actual.Environment.Keys));
Assert.Equal(ExpectedRunSpec.WorkingDirectory, actual.WorkingDirectory);
}
[Fact]
public void ProcessIoIsRedirected()
{
var io = new TestProcessIO();
var remoteProcess = Substitute.For<IProcess>();
ConstrainedProcessRunner.Run(Arg.Any<ProcessRunSpec>()).Returns(remoteProcess)
.AndDoes(call =>
{
var runSpec = call.Arg<ProcessRunSpec>();
runSpec.OutputCallback("This is STDOUT");
runSpec.ErrorCallback("This is STDERR");
});
Container.Run(Spec, io);
Assert.Equal("This is STDOUT", io.Output.ToString());
Assert.Equal("This is STDERR", io.Error.ToString());
}
[Fact]
public void ProcessIoCanBeNull()
{
var io = new TestProcessIO();
io.Output = null;
io.Error = null;
Container.Run(Spec, io);
var proc = ConstrainedProcessRunner.Captured(x => x.Run(null)).Arg<ProcessRunSpec>();
Assert.Equal(null, proc.OutputCallback);
Assert.Equal(null, proc.ErrorCallback);
}
[Fact]
public void WhenPathMappingIsDisabled_DoesNotMapExecutablePath()
{
var io = Substitute.For<IProcessIO>();
Spec.DisablePathMapping = true;
Spec.ExecutablePath = "cmd.exe";
var process = Container.Run(Spec, io);
Assert.NotNull(process);
var actual = ConstrainedProcessRunner.Captured(x => x.Run(null)).Arg<ProcessRunSpec>();
Assert.Equal("cmd.exe", actual.ExecutablePath);
}
[Fact]
public void CanFindProcessByPid()
{
var pid = 9123;
var process = Substitute.For<IProcess>();
process.Id.Returns(pid);
ConstrainedProcessRunner.FindProcessById(pid).Returns(process);
var actualProcess = Container.FindProcessById(pid);
Assert.Equal(actualProcess.Id, pid);
}
[Fact]
public void ReturnsNullWhenProcessNotFound()
{
ConstrainedProcessRunner.FindProcessById(-1).Returns(null as IProcess);
var actualProcess = Container.FindProcessById(-1);
Assert.Null(actualProcess);
}
}
[Fact]
public void WhenContainerNotActive_Throws()
{
var io = Substitute.For<IProcessIO>();
Container.Stop(false);
Action action = () => Container.Run(Spec, io);
Assert.Throws<InvalidOperationException>(action);
}
}
public class StartGuard : ContainerTests
{
public StartGuard()
{
DependencyHelper.GuardExePath.Returns(@"C:\Containers\handle\bin\Guard.exe");
const string containerUserPath = @"C:\Containers\handle\user\";
Directory.MapUserPath("/").Returns(containerUserPath);
}
[Fact]
public void StartsExeWithCorrectOptions()
{
JobObject.GetJobMemoryLimit().Returns(6789UL);
Container.StartGuard();
var actual = ProcessRunner.Captured(x => x.Run(null)).Arg<ProcessRunSpec>();
Assert.Equal(@"C:\Containers\handle\bin\Guard.exe", actual.ExecutablePath);
Assert.Equal(2, actual.Arguments.Length);
Assert.Equal(_containerUsername, actual.Arguments[0]);
Assert.Equal(Container.Id, actual.Arguments[1]);
Assert.Equal(@"C:\Containers\handle\user\", actual.WorkingDirectory);
Assert.Null(actual.Credentials);
}
[Fact]
public void DoesNotStartGuardIfAlreadyRunning()
{
Container.StartGuard();
Container.StartGuard();
ProcessRunner.Received(1).Run(Arg.Any<ProcessRunSpec>());
}
}
public class StopGuard : ContainerTests
{
[Fact]
public void WhenSomeoneListening_SetsEventWaitObject()
{
using (var stopEvent = CreateStopGuardEvent())
{
Assert.False(stopEvent.WaitOne(0));
Container.StopGuard();
Assert.True(stopEvent.WaitOne(0));
}
}
[Fact]
public void WhenNooneListening_DoesNotFail()
{
Container.StopGuard();
}
}
public class Destroy : ContainerTests
{
[Fact]
public void KillsProcesses()
{
Container.Destroy();
ProcessRunner.Received(1).StopAll(true);
ConstrainedProcessRunner.Received(1).StopAll(true);
}
[Fact]
public void ReleasesPorts()
{
TcpPortManager.ReserveLocalPort(Arg.Any<int>(), Arg.Any<string>())
.Returns(c => c.Arg<int>());
Container.ReservePort(100);
Container.ReservePort(101);
Container.Destroy();
TcpPortManager.Received(1).ReleaseLocalPort(100, User.UserName);
TcpPortManager.Received(1).ReleaseLocalPort(101, User.UserName);
}
[Fact]
public void DeletesUser()
{
Container.Destroy();
User.Received(1).Delete();
}
[Fact]
public void DisposesRunners()
{
Container.Destroy();
ProcessRunner.Received(1).Dispose();
ConstrainedProcessRunner.Received(1).Dispose();
}
[Fact]
public void DisposesJobObject_ThisEnsuresWeCanDeleteTheDirectory()
{
Container.Destroy();
JobObject.Received(1).TerminateProcessesAndWait();
JobObject.Received(1).Dispose();
}
[Fact]
public void DeletesContainerDirectory()
{
Container.Destroy();
this.Directory.Received(1).Destroy();
}
[Fact]
public void WhenContainerStopped_Runs()
{
Container.Stop(false);
Container.Destroy();
ProcessRunner.Received(1).Dispose();
}
[Fact]
public void DeletesFirewallRules()
{
Container.Destroy();
TcpPortManager.Received(1).RemoveFirewallRules(User.UserName);
}
[Fact]
public void DeletesDiskQuota()
{
var dskuser = Substitute.For<DIDiskQuotaUser>();
DiskQuotaControl.FindUser(User.SID).Returns(dskuser);
Container.Destroy();
DiskQuotaControl.Received(1).DeleteUser(dskuser);
}
}
public class GetInfo : ContainerTests
{
[Fact]
public void ReturnsListOfReservedPorts()
{
TcpPortManager.ReserveLocalPort(1000, Arg.Any<string>()).Returns(1000);
TcpPortManager.ReserveLocalPort(1001, Arg.Any<string>()).Returns(1001);
Container.ReservePort(1000);
Container.ReservePort(1001);
var info = Container.GetInfo();
Assert.Collection(info.ReservedPorts,
x => Assert.Equal(1000, x),
x => Assert.Equal(1001, x)
);
}
[Fact]
public void ReturnsProperties()
{
var properties = new Dictionary<string, string>()
{
{ "name1", "value1" },
{ "name2", "value2" },
};
ContainerPropertiesService.GetProperties(Container).Returns(properties);
var info = Container.GetInfo();
Assert.Equal(
new HashSet<string>(properties.Keys),
new HashSet<string>(info.Properties.Keys)
);
}
[Fact]
public void WhenManagingNoProcess()
{
JobObject.GetCpuStatistics().Returns(new CpuStatistics
{
TotalKernelTime = TimeSpan.Zero,
TotalUserTime = TimeSpan.Zero,
});
JobObject.GetProcessIds().Returns(new int[0]);
var metrics = Container.GetMetrics();
Assert.Equal(TimeSpan.Zero, metrics.CpuStat.TotalProcessorTime);
Assert.Equal(0ul, metrics.MemoryStat.PrivateBytes);
}
[Fact]
public void WhenManagingMultipleProcesses()
{
const long oneProcessPrivateMemory = 1024;
TimeSpan expectedTotalKernelTime = TimeSpan.FromSeconds(2);
TimeSpan expectedTotalUserTime = TimeSpan.FromSeconds(2);
var expectedCpuStats = new CpuStatistics
{
TotalKernelTime = expectedTotalKernelTime,
TotalUserTime = expectedTotalUserTime,
};
var firstProcess = Substitute.For<IProcess>();
firstProcess.Id.Returns(1);
firstProcess.PrivateMemoryBytes.Returns(oneProcessPrivateMemory);
var secondProcess = Substitute.For<IProcess>();
secondProcess.Id.Returns(2);
secondProcess.PrivateMemoryBytes.Returns(oneProcessPrivateMemory);
JobObject.GetCpuStatistics().Returns(expectedCpuStats);
JobObject.GetProcessIds().Returns(new int[] { 1, 2 });
ProcessHelper.GetProcesses(null).ReturnsForAnyArgs(new[] { firstProcess, secondProcess });
var metrics = Container.GetMetrics();
Assert.Equal(expectedTotalKernelTime + expectedTotalUserTime, metrics.CpuStat.TotalProcessorTime);
Assert.Equal((ulong)firstProcess.PrivateMemoryBytes + (ulong)secondProcess.PrivateMemoryBytes, metrics.MemoryStat.PrivateBytes);
}
[Fact]
public void WhenContainerStopped_Runs()
{
JobObject.GetCpuStatistics().Returns(new CpuStatistics
{
TotalKernelTime = TimeSpan.Zero,
TotalUserTime = TimeSpan.Zero,
});
JobObject.GetProcessIds().Returns(new int[0]);
Container.Stop(false);
var info = Container.GetInfo();
Assert.NotNull(info);
}
[Fact]
public void WhenContainerDestroyed_Throws()
{
Container.Destroy();
Action action = () => Container.GetInfo();
Assert.Throws<InvalidOperationException>(action);
}
[Fact]
public void WhenProcessHasExited()
{
var firstProcess = Substitute.For<IProcess>();
firstProcess.Id.Returns(1);
firstProcess.PrivateMemoryBytes.Throws(new InvalidOperationException());
JobObject.GetProcessIds().Returns(new int[] { 1 });
ProcessHelper.GetProcesses(null).ReturnsForAnyArgs(new[] { firstProcess });
var metrics = Container.GetMetrics();
Assert.Equal(0ul, metrics.MemoryStat.PrivateBytes);
}
}
public class LimitMemory : ContainerTests
{
[Fact]
public void SetsJobMemoryLimit()
{
Container.LimitMemory(2048);
JobObject.Received(1).SetJobMemoryLimit(2048);
}
[Fact]
public void WhenContainerNotActive_Throws()
{
Container.Stop(false);
Action action = () => Container.LimitMemory(3000);
Assert.Throws<InvalidOperationException>(action);
}
[Fact]
public void WhenGuardIsRunning_Throws()
{
Container.StartGuard();
Action action = () => Container.LimitMemory(3000);
Assert.Throws<InvalidOperationException>(action);
}
[Fact]
public void ReturnsMemoryLimit()
{
ulong limitInBytes = 2048;
JobObject.GetJobMemoryLimit().Returns(limitInBytes);
Assert.Equal(limitInBytes, Container.CurrentMemoryLimit());
}
}
public class LimitCpu : ContainerTests
{
[Fact]
public void SetsJobCpuLimit()
{
Container.LimitCpu(5);
JobObject.Received(1).SetJobCpuLimit(5);
}
[Fact]
public void WhenContainerNotActive_Throws()
{
Container.Stop(false);
Action action = () => Container.LimitCpu(3000);
Assert.Throws<InvalidOperationException>(action);
}
[Fact]
public void ReturnsCpuLimit()
{
int weight = 7;
JobObject.GetJobCpuLimit().Returns(weight);
Assert.Equal(weight, Container.CurrentCpuLimit());
}
}
public class LimitDisk : ContainerTests
{
[Fact]
public void SetsUserDiskLimit()
{
var quota = Substitute.For<DIDiskQuotaUser>();
this.DiskQuotaControl.FindUser(User.SID).Returns(quota);
Container.LimitDisk(5);
Assert.Equal(5, quota.QuotaLimit);
}
[Fact]
public void WhenContainerNotActive_Throws()
{
Container.Stop(false);
Action action = () => Container.LimitDisk(5);
Assert.Throws<InvalidOperationException>(action);
}
[Fact]
public void ReturnsDiskLimit()
{
ulong limitInBytes = 2048;
var quota = Substitute.For<DIDiskQuotaUser>();
quota.QuotaLimit = limitInBytes;
this.DiskQuotaControl.FindUser(User.SID).Returns(quota);
Assert.Equal(limitInBytes, Container.CurrentDiskLimit());
}
[Fact]
public void WhenDiskQuotaUsedFails_ReturnZero()
{
var quota = Substitute.For<DIDiskQuotaUser>();
this.DiskQuotaControl.FindUser(User.SID).Returns(quota);
quota.QuotaUsed.Throws(new System.Runtime.InteropServices.COMException());
Assert.Equal(0ul, Container.CurrentDiskUsage());
}
}
public class RemoveProperty : ContainerTests
{
[Fact]
public void RemovesProperty()
{
Container.RemoveProperty("Name");
ContainerPropertiesService.Received(1).RemoveProperty(Container, "Name");
}
}
public class SetProperty : ContainerTests
{
[Fact]
public void SetsProperty()
{
Container.SetProperty("Name", "Value");
ContainerPropertiesService.Received(1).SetProperty(Container, "Name", "Value");
}
}
public class Stop : ContainerTests
{
[Fact]
public void DisposesProcessRunners()
{
Container.Stop(false);
ProcessRunner.Received(1).Dispose();
ConstrainedProcessRunner.Received(1).Dispose();
}
[Fact]
public void WhenContainerDestroyed_Throws()
{
Container.Destroy();
Action action = () => Container.Stop(false);
Assert.Throws<InvalidOperationException>(action);
}
[Fact]
public void WhenContainerStopAllThrows_CallsJobobjectTerminate()
{
ConstrainedProcessRunner
.When(x => x.StopAll(true))
.Do(x => { throw new TimeoutException("Test timeout exception"); });
Container.Stop(true);
JobObject.Received(1).TerminateProcessesAndWait();
}
[Fact]
public void ChangesStateToStopped()
{
Container.Stop(false);
var info = Container.GetInfo();
Assert.Equal(ContainerState.Stopped, info.State);
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.ServiceModel.Channels;
using System.ServiceModel.Diagnostics;
using System.IdentityModel.Selectors;
using System.Runtime.Diagnostics;
using System.Threading.Tasks;
namespace System.ServiceModel.Security
{
internal class WrapperSecurityCommunicationObject : CommunicationObject
{
private ISecurityCommunicationObject _innerCommunicationObject;
public WrapperSecurityCommunicationObject(ISecurityCommunicationObject innerCommunicationObject)
: base()
{
if (innerCommunicationObject == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("innerCommunicationObject");
}
_innerCommunicationObject = innerCommunicationObject;
}
protected override Type GetCommunicationObjectType()
{
return _innerCommunicationObject.GetType();
}
protected override TimeSpan DefaultCloseTimeout
{
get { return _innerCommunicationObject.DefaultCloseTimeout; }
}
protected override TimeSpan DefaultOpenTimeout
{
get { return _innerCommunicationObject.DefaultOpenTimeout; }
}
protected override void OnAbort()
{
_innerCommunicationObject.OnAbort();
}
protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state)
{
return _innerCommunicationObject.OnBeginClose(timeout, callback, state);
}
protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
{
return _innerCommunicationObject.OnBeginOpen(timeout, callback, state);
}
protected override void OnClose(TimeSpan timeout)
{
_innerCommunicationObject.OnClose(timeout);
}
protected override void OnClosed()
{
_innerCommunicationObject.OnClosed();
base.OnClosed();
}
protected override void OnClosing()
{
_innerCommunicationObject.OnClosing();
base.OnClosing();
}
protected override void OnEndClose(IAsyncResult result)
{
_innerCommunicationObject.OnEndClose(result);
}
protected override void OnEndOpen(IAsyncResult result)
{
_innerCommunicationObject.OnEndOpen(result);
}
protected override void OnFaulted()
{
_innerCommunicationObject.OnFaulted();
base.OnFaulted();
}
protected override void OnOpen(TimeSpan timeout)
{
_innerCommunicationObject.OnOpen(timeout);
}
protected override void OnOpened()
{
_innerCommunicationObject.OnOpened();
base.OnOpened();
}
protected override void OnOpening()
{
_innerCommunicationObject.OnOpening();
base.OnOpening();
}
new internal void ThrowIfDisposedOrImmutable()
{
base.ThrowIfDisposedOrImmutable();
}
protected internal override async Task OnCloseAsync(TimeSpan timeout)
{
var asyncInnerCommunicationObject = _innerCommunicationObject as IAsyncCommunicationObject;
if (asyncInnerCommunicationObject != null)
{
await asyncInnerCommunicationObject.CloseAsync(timeout);
}
else
{
this.OnClose(timeout);
}
}
protected internal override async Task OnOpenAsync(TimeSpan timeout)
{
var asyncInnerCommunicationObject = _innerCommunicationObject as IAsyncCommunicationObject;
if (asyncInnerCommunicationObject != null)
{
await asyncInnerCommunicationObject.OpenAsync(timeout);
}
else
{
this.OnOpen(timeout);
}
}
}
internal abstract class CommunicationObjectSecurityTokenProvider : SecurityTokenProvider, ICommunicationObject, ISecurityCommunicationObject
{
private EventTraceActivity _eventTraceActivity;
private WrapperSecurityCommunicationObject _communicationObject;
protected CommunicationObjectSecurityTokenProvider()
{
_communicationObject = new WrapperSecurityCommunicationObject(this);
}
internal EventTraceActivity EventTraceActivity
{
get
{
if (_eventTraceActivity == null)
{
_eventTraceActivity = EventTraceActivity.GetFromThreadOrCreate();
}
return _eventTraceActivity;
}
}
protected WrapperSecurityCommunicationObject CommunicationObject
{
get { return _communicationObject; }
}
public event EventHandler Closed
{
add { _communicationObject.Closed += value; }
remove { _communicationObject.Closed -= value; }
}
public event EventHandler Closing
{
add { _communicationObject.Closing += value; }
remove { _communicationObject.Closing -= value; }
}
public event EventHandler Faulted
{
add { _communicationObject.Faulted += value; }
remove { _communicationObject.Faulted -= value; }
}
public event EventHandler Opened
{
add { _communicationObject.Opened += value; }
remove { _communicationObject.Opened -= value; }
}
public event EventHandler Opening
{
add { _communicationObject.Opening += value; }
remove { _communicationObject.Opening -= value; }
}
public CommunicationState State
{
get { return _communicationObject.State; }
}
public virtual TimeSpan DefaultOpenTimeout
{
get { return ServiceDefaults.OpenTimeout; }
}
public virtual TimeSpan DefaultCloseTimeout
{
get { return ServiceDefaults.CloseTimeout; }
}
// communication object
public void Abort()
{
_communicationObject.Abort();
}
public void Close()
{
_communicationObject.Close();
}
public void Close(TimeSpan timeout)
{
_communicationObject.Close(timeout);
}
public IAsyncResult BeginClose(AsyncCallback callback, object state)
{
return _communicationObject.BeginClose(callback, state);
}
public IAsyncResult BeginClose(TimeSpan timeout, AsyncCallback callback, object state)
{
return _communicationObject.BeginClose(timeout, callback, state);
}
public void EndClose(IAsyncResult result)
{
_communicationObject.EndClose(result);
}
public void Open()
{
_communicationObject.Open();
}
public void Open(TimeSpan timeout)
{
_communicationObject.Open(timeout);
}
public IAsyncResult BeginOpen(AsyncCallback callback, object state)
{
return _communicationObject.BeginOpen(callback, state);
}
public IAsyncResult BeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
{
return _communicationObject.BeginOpen(timeout, callback, state);
}
public void EndOpen(IAsyncResult result)
{
_communicationObject.EndOpen(result);
}
public void Dispose()
{
this.Close();
}
// ISecurityCommunicationObject methods
public virtual void OnAbort()
{
}
public IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state)
{
return new OperationWithTimeoutAsyncResult(this.OnClose, timeout, callback, state);
}
public IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
{
return new OperationWithTimeoutAsyncResult(this.OnOpen, timeout, callback, state);
}
public virtual void OnClose(TimeSpan timeout)
{
}
public virtual void OnClosed()
{
}
public virtual void OnClosing()
{
}
public void OnEndClose(IAsyncResult result)
{
OperationWithTimeoutAsyncResult.End(result);
}
public void OnEndOpen(IAsyncResult result)
{
OperationWithTimeoutAsyncResult.End(result);
}
public virtual void OnFaulted()
{
this.OnAbort();
}
public virtual void OnOpen(TimeSpan timeout)
{
}
public virtual void OnOpened()
{
}
public virtual void OnOpening()
{
}
}
internal abstract class CommunicationObjectSecurityTokenAuthenticator : SecurityTokenAuthenticator, ICommunicationObject, ISecurityCommunicationObject
{
private WrapperSecurityCommunicationObject _communicationObject;
protected CommunicationObjectSecurityTokenAuthenticator()
{
_communicationObject = new WrapperSecurityCommunicationObject(this);
}
protected WrapperSecurityCommunicationObject CommunicationObject
{
get { return _communicationObject; }
}
public event EventHandler Closed
{
add { _communicationObject.Closed += value; }
remove { _communicationObject.Closed -= value; }
}
public event EventHandler Closing
{
add { _communicationObject.Closing += value; }
remove { _communicationObject.Closing -= value; }
}
public event EventHandler Faulted
{
add { _communicationObject.Faulted += value; }
remove { _communicationObject.Faulted -= value; }
}
public event EventHandler Opened
{
add { _communicationObject.Opened += value; }
remove { _communicationObject.Opened -= value; }
}
public event EventHandler Opening
{
add { _communicationObject.Opening += value; }
remove { _communicationObject.Opening -= value; }
}
public CommunicationState State
{
get { return _communicationObject.State; }
}
public virtual TimeSpan DefaultOpenTimeout
{
get { return ServiceDefaults.OpenTimeout; }
}
public virtual TimeSpan DefaultCloseTimeout
{
get { return ServiceDefaults.CloseTimeout; }
}
// communication object
public void Abort()
{
_communicationObject.Abort();
}
public void Close()
{
_communicationObject.Close();
}
public void Close(TimeSpan timeout)
{
_communicationObject.Close(timeout);
}
public IAsyncResult BeginClose(AsyncCallback callback, object state)
{
return _communicationObject.BeginClose(callback, state);
}
public IAsyncResult BeginClose(TimeSpan timeout, AsyncCallback callback, object state)
{
return _communicationObject.BeginClose(timeout, callback, state);
}
public void EndClose(IAsyncResult result)
{
_communicationObject.EndClose(result);
}
public void Open()
{
_communicationObject.Open();
}
public void Open(TimeSpan timeout)
{
_communicationObject.Open(timeout);
}
public IAsyncResult BeginOpen(AsyncCallback callback, object state)
{
return _communicationObject.BeginOpen(callback, state);
}
public IAsyncResult BeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
{
return _communicationObject.BeginOpen(timeout, callback, state);
}
public void EndOpen(IAsyncResult result)
{
_communicationObject.EndOpen(result);
}
public void Dispose()
{
this.Close();
}
// ISecurityCommunicationObject methods
public virtual void OnAbort()
{
}
public IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state)
{
return new OperationWithTimeoutAsyncResult(this.OnClose, timeout, callback, state);
}
public IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
{
return new OperationWithTimeoutAsyncResult(this.OnOpen, timeout, callback, state);
}
public virtual void OnClose(TimeSpan timeout)
{
}
public virtual void OnClosed()
{
}
public virtual void OnClosing()
{
}
public void OnEndClose(IAsyncResult result)
{
OperationWithTimeoutAsyncResult.End(result);
}
public void OnEndOpen(IAsyncResult result)
{
OperationWithTimeoutAsyncResult.End(result);
}
public virtual void OnFaulted()
{
this.OnAbort();
}
public virtual void OnOpen(TimeSpan timeout)
{
}
public virtual void OnOpened()
{
}
public virtual void OnOpening()
{
}
}
}
| |
#if !BESTHTTP_DISABLE_SERVERSENT_EVENTS
using System;
using System.Collections.Generic;
using BestHTTP.Extensions;
#if UNITY_WEBGL && !UNITY_EDITOR
using System.Runtime.InteropServices;
#endif
namespace BestHTTP.ServerSentEvents
{
/// <summary>
/// Possible states of an EventSource object.
/// </summary>
public enum States
{
Initial,
Connecting,
Open,
Retrying,
Closing,
Closed
}
public delegate void OnGeneralEventDelegate(EventSource eventSource);
public delegate void OnMessageDelegate(EventSource eventSource, BestHTTP.ServerSentEvents.Message message);
public delegate void OnErrorDelegate(EventSource eventSource, string error);
public delegate bool OnRetryDelegate(EventSource eventSource);
public delegate void OnEventDelegate(EventSource eventSource, BestHTTP.ServerSentEvents.Message message);
public delegate void OnStateChangedDelegate(EventSource eventSource, States oldState, States newState);
#if UNITY_WEBGL && !UNITY_EDITOR
delegate void OnWebGLEventSourceOpenDelegate(uint id);
delegate void OnWebGLEventSourceMessageDelegate(uint id, string eventStr, string data, string eventId, int retry);
delegate void OnWebGLEventSourceErrorDelegate(uint id, string reason);
#endif
/// <summary>
/// http://www.w3.org/TR/eventsource/
/// </summary>
public class EventSource
#if !UNITY_WEBGL || UNITY_EDITOR
: IHeartbeat
#endif
{
#region Public Properties
/// <summary>
/// Uri of the remote endpoint.
/// </summary>
public Uri Uri { get; private set; }
/// <summary>
/// Current state of the EventSource object.
/// </summary>
public States State
{
get
{
return _state;
}
private set
{
States oldState = _state;
_state = value;
if (OnStateChanged != null)
{
try
{
OnStateChanged(this, oldState, _state);
}
catch(Exception ex)
{
HTTPManager.Logger.Exception("EventSource", "OnStateChanged", ex);
}
}
}
}
private States _state;
/// <summary>
/// Time to wait to do a reconnect attempt. Default to 2 sec. The server can overwrite this setting.
/// </summary>
public TimeSpan ReconnectionTime { get; set; }
/// <summary>
/// The last successfully received event's id.
/// </summary>
public string LastEventId { get; private set; }
#if !UNITY_WEBGL || UNITY_EDITOR
/// <summary>
/// The internal request object of the EventSource.
/// </summary>
public HTTPRequest InternalRequest { get; private set; }
#endif
#endregion
#region Public Events
/// <summary>
/// Called when successfully connected to the server.
/// </summary>
public event OnGeneralEventDelegate OnOpen;
/// <summary>
/// Called on every message received from the server.
/// </summary>
public event OnMessageDelegate OnMessage;
/// <summary>
/// Called when an error occures.
/// </summary>
public event OnErrorDelegate OnError;
#if !UNITY_WEBGL || UNITY_EDITOR
/// <summary>
/// Called when the EventSource will try to do a retry attempt. If this function returns with false, it will cancel the attempt.
/// </summary>
public event OnRetryDelegate OnRetry;
#endif
/// <summary>
/// Called when the EventSource object closed.
/// </summary>
public event OnGeneralEventDelegate OnClosed;
/// <summary>
/// Called every time when the State property changed.
/// </summary>
public event OnStateChangedDelegate OnStateChanged;
#endregion
#region Privates
/// <summary>
/// A dictionary to store eventName => delegate mapping.
/// </summary>
private Dictionary<string, OnEventDelegate> EventTable;
#if !UNITY_WEBGL || UNITY_EDITOR
/// <summary>
/// Number of retry attempts made.
/// </summary>
private byte RetryCount;
/// <summary>
/// When we called the Retry function. We will delay the Open call from here.
/// </summary>
private DateTime RetryCalled;
#else
private static Dictionary<uint, EventSource> EventSources = new Dictionary<uint, EventSource>();
private uint Id;
#endif
#endregion
public EventSource(Uri uri)
{
this.Uri = uri;
this.ReconnectionTime = TimeSpan.FromMilliseconds(2000);
#if !UNITY_WEBGL || UNITY_EDITOR
this.InternalRequest = new HTTPRequest(Uri, HTTPMethods.Get, true, true, OnRequestFinished);
// Set headers
this.InternalRequest.SetHeader("Accept", "text/event-stream");
this.InternalRequest.SetHeader("Cache-Control", "no-cache");
this.InternalRequest.SetHeader("Accept-Encoding", "identity");
// Set protocol stuff
this.InternalRequest.ProtocolHandler = SupportedProtocols.ServerSentEvents;
this.InternalRequest.OnUpgraded = OnUpgraded;
// Disable internal retry
this.InternalRequest.DisableRetry = true;
#endif
}
#region Public Functions
/// <summary>
/// Start to connect to the remote servr.
/// </summary>
public void Open()
{
if (this.State != States.Initial &&
this.State != States.Retrying &&
this.State != States.Closed)
return;
this.State = States.Connecting;
#if !UNITY_WEBGL || UNITY_EDITOR
if (!string.IsNullOrEmpty(this.LastEventId))
this.InternalRequest.SetHeader("Last-Event-ID", this.LastEventId);
this.InternalRequest.Send();
#else
this.Id = ES_Create(this.Uri.ToString(), true, OnOpenCallback, OnMessageCallback, OnErrorCallback);
EventSources.Add(this.Id, this);
#endif
}
/// <summary>
/// Start to close the connection.
/// </summary>
public void Close()
{
if (this.State == States.Closing ||
this.State == States.Closed)
return;
this.State = States.Closing;
#if !UNITY_WEBGL || UNITY_EDITOR
if (this.InternalRequest != null)
this.InternalRequest.Abort();
else
this.State = States.Closed;
#else
ES_Close(this.Id);
SetClosed("Close");
EventSources.Remove(this.Id);
ES_Release(this.Id);
#endif
}
/// <summary>
/// With this function an event handler can be subscribed for an event name.
/// </summary>
public void On(string eventName, OnEventDelegate action)
{
if (EventTable == null)
EventTable = new Dictionary<string, OnEventDelegate>();
EventTable[eventName] = action;
}
/// <summary>
/// With this function the event handler can be removed for the given event name.
/// </summary>
/// <param name="eventName"></param>
public void Off(string eventName)
{
if (eventName == null)
return;
EventTable.Remove(eventName);
}
#endregion
#region Private Helper Functions
private void CallOnError(string error, string msg)
{
if (OnError != null)
{
try
{
OnError(this, error);
}
catch (Exception ex)
{
HTTPManager.Logger.Exception("EventSource", msg + " - OnError", ex);
}
}
}
#if !UNITY_WEBGL || UNITY_EDITOR
private bool CallOnRetry()
{
if (OnRetry != null)
{
try
{
return OnRetry(this);
}
catch(Exception ex)
{
HTTPManager.Logger.Exception("EventSource", "CallOnRetry", ex);
}
}
return true;
}
#endif
private void SetClosed(string msg)
{
this.State = States.Closed;
if (OnClosed != null)
{
try
{
OnClosed(this);
}
catch (Exception ex)
{
HTTPManager.Logger.Exception("EventSource", msg + " - OnClosed", ex);
}
}
}
#if !UNITY_WEBGL || UNITY_EDITOR
private void Retry()
{
if (RetryCount > 0 ||
!CallOnRetry())
{
SetClosed("Retry");
return;
}
RetryCount++;
RetryCalled = DateTime.UtcNow;
HTTPManager.Heartbeats.Subscribe(this);
this.State = States.Retrying;
}
#endif
#endregion
#region HTTP Request Implementation
#if !UNITY_WEBGL || UNITY_EDITOR
/// <summary>
/// We are successfully upgraded to the EventSource protocol, we can start to receive and parse the incoming data.
/// </summary>
private void OnUpgraded(HTTPRequest originalRequest, HTTPResponse response)
{
EventSourceResponse esResponse = response as EventSourceResponse;
if (esResponse == null)
{
CallOnError("Not an EventSourceResponse!", "OnUpgraded");
return;
}
if (OnOpen != null)
{
try
{
OnOpen(this);
}
catch (Exception ex)
{
HTTPManager.Logger.Exception("EventSource", "OnOpen", ex);
}
}
esResponse.OnMessage += OnMessageReceived;
esResponse.StartReceive();
this.RetryCount = 0;
this.State = States.Open;
}
private void OnRequestFinished(HTTPRequest req, HTTPResponse resp)
{
if (this.State == States.Closed)
return;
if (this.State == States.Closing ||
req.State == HTTPRequestStates.Aborted)
{
SetClosed("OnRequestFinished");
return;
}
string reason = string.Empty;
// In some cases retry is prohibited
bool canRetry = true;
switch (req.State)
{
// The server sent all the data it's wanted.
case HTTPRequestStates.Processing:
canRetry = !resp.HasHeader("content-length");
break;
// The request finished without any problem.
case HTTPRequestStates.Finished:
// HTTP 200 OK responses that have a Content-Type specifying an unsupported type, or that have no Content-Type at all, must cause the user agent to fail the connection.
if (resp.StatusCode == 200 && !resp.HasHeaderWithValue("content-type", "text/event-stream"))
{
reason = "No Content-Type header with value 'text/event-stream' present.";
canRetry = false;
}
// HTTP 500 Internal Server Error, 502 Bad Gateway, 503 Service Unavailable, and 504 Gateway Timeout responses, and any network error that prevents the connection
// from being established in the first place (e.g. DNS errors), must cause the user agent to asynchronously reestablish the connection.
// Any other HTTP response code not listed here must cause the user agent to fail the connection.
if (canRetry &&
resp.StatusCode != 500 &&
resp.StatusCode != 502 &&
resp.StatusCode != 503 &&
resp.StatusCode != 504)
{
canRetry = false;
reason = string.Format("Request Finished Successfully, but the server sent an error. Status Code: {0}-{1} Message: {2}",
resp.StatusCode,
resp.Message,
resp.DataAsText);
}
break;
// The request finished with an unexpected error. The request's Exception property may contain more info about the error.
case HTTPRequestStates.Error:
reason = "Request Finished with Error! " + (req.Exception != null ? (req.Exception.Message + "\n" + req.Exception.StackTrace) : "No Exception");
break;
// The request aborted, initiated by the user.
case HTTPRequestStates.Aborted:
// If the state is Closing, then it's a normal behaviour, and we close the EventSource
reason = "OnRequestFinished - Aborted without request. EventSource's State: " + this.State;
break;
// Ceonnecting to the server is timed out.
case HTTPRequestStates.ConnectionTimedOut:
reason = "Connection Timed Out!";
break;
// The request didn't finished in the given time.
case HTTPRequestStates.TimedOut:
reason = "Processing the request Timed Out!";
break;
}
// If we are not closing the EventSource, then we will try to reconnect.
if (this.State < States.Closing)
{
if (!string.IsNullOrEmpty(reason))
CallOnError(reason, "OnRequestFinished");
if (canRetry)
Retry();
else
SetClosed("OnRequestFinished");
}
else
SetClosed("OnRequestFinished");
}
#endif
#endregion
#region EventStreamResponse Event Handlers
private void OnMessageReceived(
#if !UNITY_WEBGL || UNITY_EDITOR
EventSourceResponse resp,
#endif
BestHTTP.ServerSentEvents.Message message)
{
if (this.State >= States.Closing)
return;
// 1.) Set the last event ID string of the event source to value of the last event ID buffer.
// The buffer does not get reset, so the last event ID string of the event source remains set to this value until the next time it is set by the server.
// We check here only for null, because it can be a non-null but empty string.
if (message.Id != null)
this.LastEventId = message.Id;
if (message.Retry.TotalMilliseconds > 0)
this.ReconnectionTime = message.Retry;
// 2.) If the data buffer is an empty string, set the data buffer and the event type buffer to the empty string and abort these steps.
if (string.IsNullOrEmpty(message.Data))
return;
// 3.) If the data buffer's last character is a U+000A LINE FEED (LF) character, then remove the last character from the data buffer.
// This step can be ignored. We constructed the string to be able to skip this step.
if (OnMessage != null)
{
try
{
OnMessage(this, message);
}
catch (Exception ex)
{
HTTPManager.Logger.Exception("EventSource", "OnMessageReceived - OnMessage", ex);
}
}
if (!string.IsNullOrEmpty(message.Event))
{
OnEventDelegate action;
if (EventTable.TryGetValue(message.Event, out action))
{
if (action != null)
{
try
{
action(this, message);
}
catch(Exception ex)
{
HTTPManager.Logger.Exception("EventSource", "OnMessageReceived - action", ex);
}
}
}
}
}
#endregion
#region IHeartbeat Implementation
#if !UNITY_WEBGL || UNITY_EDITOR
void IHeartbeat.OnHeartbeatUpdate(TimeSpan dif)
{
if (this.State != States.Retrying)
{
HTTPManager.Heartbeats.Unsubscribe(this);
return;
}
if (DateTime.UtcNow - RetryCalled >= ReconnectionTime)
{
Open();
if (this.State != States.Connecting)
SetClosed("OnHeartbeatUpdate");
HTTPManager.Heartbeats.Unsubscribe(this);
}
}
#endif
#endregion
#region WebGL Static Callbacks
#if UNITY_WEBGL && !UNITY_EDITOR
[AOT.MonoPInvokeCallback(typeof(OnWebGLEventSourceOpenDelegate))]
static void OnOpenCallback(uint id)
{
EventSource es;
if (EventSources.TryGetValue(id, out es))
{
if (es.OnOpen != null)
{
try
{
es.OnOpen(es);
}
catch(Exception ex)
{
HTTPManager.Logger.Exception("EventSource", "OnOpen", ex);
}
}
es.State = States.Open;
}
else
HTTPManager.Logger.Warning("EventSource", "OnOpenCallback - No EventSource found for id: " + id.ToString());
}
[AOT.MonoPInvokeCallback(typeof(OnWebGLEventSourceMessageDelegate))]
static void OnMessageCallback(uint id, string eventStr, string data, string eventId, int retry)
{
EventSource es;
if (EventSources.TryGetValue(id, out es))
{
var msg = new BestHTTP.ServerSentEvents.Message();
msg.Id = eventId;
msg.Data = data;
msg.Event = eventStr;
msg.Retry = TimeSpan.FromSeconds(retry);
es.OnMessageReceived(msg);
}
}
[AOT.MonoPInvokeCallback(typeof(OnWebGLEventSourceErrorDelegate))]
static void OnErrorCallback(uint id, string reason)
{
EventSource es;
if (EventSources.TryGetValue(id, out es))
{
es.CallOnError(reason, "OnErrorCallback");
es.SetClosed("OnError");
EventSources.Remove(id);
}
try
{
ES_Release(id);
}
catch (Exception ex)
{
HTTPManager.Logger.Exception("EventSource", "ES_Release", ex);
}
}
#endif
#endregion
#region WebGL Interface
#if UNITY_WEBGL && !UNITY_EDITOR
[DllImport("__Internal")]
static extern uint ES_Create(string url, bool withCred, OnWebGLEventSourceOpenDelegate onOpen, OnWebGLEventSourceMessageDelegate onMessage, OnWebGLEventSourceErrorDelegate onError);
[DllImport("__Internal")]
static extern void ES_Close(uint id);
[DllImport("__Internal")]
static extern void ES_Release(uint id);
#endif
#endregion
}
}
#endif
| |
//
// System.Xml.XmlDeclarationTests.cs
//
// Author: Duncan Mak (duncan@ximian.com)
// Author: Martin Willemoes Hansen (mwh@sysrq.dk)
//
// (C) Ximian, Inc.
// (C) 2003 Martin Willemoes Hansen
//
using System;
using System.Xml;
using NUnit.Framework;
namespace MonoTests.System.Xml
{
[TestFixture]
public class XmlDeclarationTests : Assertion
{
XmlDocument document;
XmlDeclaration declaration;
[SetUp]
public void GetReady ()
{
document = new XmlDocument ();
document.LoadXml ("<foo><bar></bar></foo>");
declaration = document.CreateXmlDeclaration ("1.0", null, null);
}
[Test]
public void InnerAndOuterXml ()
{
declaration = document.CreateXmlDeclaration ("1.0", null, null);
AssertEquals (String.Empty, declaration.InnerXml);
AssertEquals ("<?xml version=\"1.0\"?>", declaration.OuterXml);
declaration = document.CreateXmlDeclaration ("1.0", "doesn't check", null);
AssertEquals (String.Empty, declaration.InnerXml);
AssertEquals ("<?xml version=\"1.0\" encoding=\"doesn't check\"?>", declaration.OuterXml);
declaration = document.CreateXmlDeclaration ("1.0", null, "yes");
AssertEquals (String.Empty, declaration.InnerXml);
AssertEquals ("<?xml version=\"1.0\" standalone=\"yes\"?>", declaration.OuterXml);
declaration = document.CreateXmlDeclaration ("1.0", "foo", "no");
AssertEquals (String.Empty, declaration.InnerXml);
AssertEquals ("<?xml version=\"1.0\" encoding=\"foo\" standalone=\"no\"?>", declaration.OuterXml);
}
internal void XmlNodeBaseProperties (XmlNode original, XmlNode cloned)
{
// assertequals (original.nodetype + " was incorrectly cloned.",
// original.baseuri, cloned.baseuri);
AssertNull (cloned.ParentNode);
AssertEquals ("Value incorrectly cloned",
original.Value, cloned.Value);
Assert ("Copies, not pointers", !Object.ReferenceEquals (original,cloned));
}
[Test]
public void Constructor ()
{
try {
XmlDeclaration broken = document.CreateXmlDeclaration ("2.0", null, null);
} catch (ArgumentException) {
return;
} catch (Exception e) {
Fail("first arg null, wrong exception: " + e.ToString());
}
}
[Test]
public void NodeType ()
{
AssertEquals ("incorrect NodeType returned", XmlNodeType.XmlDeclaration, declaration.NodeType);
}
[Test]
public void Names ()
{
AssertEquals ("Name is incorrect", "xml", declaration.Name);
AssertEquals ("LocalName is incorrect", "xml", declaration.LocalName);
}
[Test]
public void EncodingProperty ()
{
XmlDeclaration d1 = document.CreateXmlDeclaration ("1.0", "foo", null);
AssertEquals ("Encoding property", "foo", d1.Encoding);
XmlDeclaration d2 = document.CreateXmlDeclaration ("1.0", null, null);
AssertEquals ("null Encoding property", String.Empty, d2.Encoding);
}
[Test]
public void ValidInnerText ()
{
declaration.InnerText = "version='1.0'";
declaration.InnerText = "version='1.0' encoding='euc-jp'";
declaration.InnerText = "version='1.0' standalone='no'";
declaration.InnerText = "version='1.0' encoding='iso-8859-1' standalone=\"yes\"";
declaration.InnerText = @"version = '1.0' encoding =
'euc-jp' standalone = 'yes' ";
declaration.InnerText = " version = '1.0'";
}
[Test]
[ExpectedException (typeof (XmlException))]
public void InvalidInnerText ()
{
declaration.InnerText = "version='1.0a'";
}
[Test]
[ExpectedException (typeof (XmlException))]
public void InvalidInnerText2 ()
{
declaration.InnerText = "version='1.0' encoding='euc-kr\"";
}
[Test]
[ExpectedException (typeof (XmlException))]
public void InvalidInnerText3 ()
{
declaration.InnerText = "version='2.0'";
}
[Test]
[ExpectedException (typeof (XmlException))]
public void InvalidInnerText4 ()
{
declaration.InnerText = "version='1.0' standalone='Yeah!!!!!'";
}
[Test]
[ExpectedException (typeof (XmlException))]
public void InvalidInnerText5 ()
{
declaration.InnerText = "version='1.0'standalone='yes'";
}
[Test]
[ExpectedException (typeof (XmlException))]
public void InvalidInnerText6 ()
{
declaration.InnerText = "version='1.0'standalone='yes' encoding='utf-8'";
}
[Test]
public void StandaloneProperty ()
{
XmlDeclaration d1 = document.CreateXmlDeclaration ("1.0", null, "yes");
AssertEquals ("Yes standalone property", "yes", d1.Standalone);
XmlDeclaration d2 = document.CreateXmlDeclaration ("1.0", null, "no");
AssertEquals ("No standalone property", "no", d2.Standalone);
XmlDeclaration d3 = document.CreateXmlDeclaration ("1.0", null, null);
AssertEquals ("null Standalone property", String.Empty, d3.Standalone);
}
[Test]
public void ValueProperty ()
{
string expected = "version=\"1.0\" encoding=\"ISO-8859-1\" standalone=\"yes\"" ;
XmlDeclaration d = document.CreateXmlDeclaration ("1.0", "ISO-8859-1", "yes");
AssertEquals ("Value property", expected, d.Value);
d.Value = expected;
AssertEquals ("Value round-trip", expected, d.Value);
d.Value = " " + expected;
AssertEquals ("Value round-trip (padded)", expected, d.Value);
d.Value = "version=\"1.0\" encoding=\"ISO-8859-1\" standalone=\"yes\"" ;
AssertEquals ("Value round-trip (padded 2)", expected, d.Value);
d.Value = "version=\"1.0\"\tencoding=\"ISO-8859-1\" standalone=\"yes\"" ;
AssertEquals ("Value round-trip (\\t)", expected, d.Value);
d.Value = "version=\"1.0\"\n encoding=\"ISO-8859-1\" standalone=\"yes\"" ;
AssertEquals ("Value round-trip (\\n)", expected, d.Value);
d.Value = "version=\"1.0\" encoding = \"ISO-8859-1\" standalone = \"yes\"" ;
AssertEquals ("Value round-trip (spaces)", expected, d.Value);
d.Value = "version='1.0' encoding='ISO-8859-1' standalone='yes'" ;
AssertEquals ("Value round-trip ('s)", expected, d.Value);
}
[Test]
public void XmlCommentCloneNode ()
{
XmlNode original = declaration;
XmlNode shallow = declaration.CloneNode (false); // shallow
XmlNodeBaseProperties (original, shallow);
XmlNode deep = declaration.CloneNode (true); // deep
XmlNodeBaseProperties (original, deep);
AssertEquals ("deep cloning differs from shallow cloning",
deep.OuterXml, shallow.OuterXml);
}
}
}
| |
//
// PodcastService.cs
//
// Authors:
// Mike Urbanski <michael.c.urbanski@gmail.com>
// Gabriel Burt <gburt@novell.com>
//
// Copyright (C) 2008 Michael C. Urbanski
// Copyright (C) 2008 Novell, Inc.
//
// 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.Linq;
using System.IO;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Mono.Unix;
using Hyena;
using Banshee.Base;
using Banshee.ServiceStack;
using Migo.TaskCore;
using Migo.Syndication;
using Migo.DownloadCore;
using Banshee.Networking;
using Banshee.MediaEngine;
using Banshee.Podcasting.Gui;
using Banshee.Podcasting.Data;
using Banshee.Collection.Database;
using Banshee.Configuration;
namespace Banshee.Podcasting
{
public partial class PodcastService : IExtensionService, IDisposable, IDelayedInitializeService
{
private readonly string tmp_download_path = Paths.Combine (Paths.ExtensionCacheRoot, "podcasting", "partial-downloads");
private uint refresh_timeout_id = 0;
private bool disposed;
private DownloadManager download_manager;
private DownloadManagerInterface download_manager_iface;
private FeedsManager feeds_manager;
private PodcastSource source;
//private PodcastImportManager import_manager;
private readonly object sync = new object ();
public PodcastService ()
{
Migo.Net.AsyncWebClient.DefaultUserAgent = Banshee.Web.Browser.UserAgent;
}
private void MigrateLegacyIfNeeded ()
{
if (DatabaseConfigurationClient.Client.Get<int> ("Podcast", "Version", 0) == 0) {
if (ServiceManager.DbConnection.TableExists ("Podcasts") &&
ServiceManager.DbConnection.Query<int> ("select count(*) from podcastsyndications") == 0) {
Hyena.Log.Information ("Migrating Podcast Feeds and Items");
ServiceManager.DbConnection.Execute(@"
INSERT INTO PodcastSyndications (FeedID, Title, Url, Link,
Description, ImageUrl, LastBuildDate, AutoDownload, IsSubscribed)
SELECT
PodcastFeedID,
Title,
FeedUrl,
Link,
Description,
Image,
strftime(""%s"", LastUpdated),
SyncPreference,
1
FROM PodcastFeeds
");
ServiceManager.DbConnection.Execute(@"
INSERT INTO PodcastItems (ItemID, FeedID, Title, Link, PubDate,
Description, Author, Active, Guid)
SELECT
PodcastID,
PodcastFeedID,
Title,
Link,
strftime(""%s"", PubDate),
Description,
Author,
Active,
Url
FROM Podcasts
");
// Note: downloaded*3 is because the value was 0 or 1, but is now 0 or 3 (FeedDownloadStatus.None/Downloaded)
ServiceManager.DbConnection.Execute(@"
INSERT INTO PodcastEnclosures (ItemID, LocalPath, Url, MimeType, FileSize, DownloadStatus)
SELECT
PodcastID,
LocalPath,
Url,
MimeType,
Length,
Downloaded*3
FROM Podcasts
");
// Finally, move podcast items from the Music Library to the Podcast source
int [] primary_source_ids = new int [] { ServiceManager.SourceManager.MusicLibrary.DbId };
int moved = 0;
foreach (FeedEnclosure enclosure in FeedEnclosure.Provider.FetchAllMatching ("LocalPath IS NOT NULL AND LocalPath != ''")) {
SafeUri uri = new SafeUri (enclosure.LocalPath);
int track_id = DatabaseTrackInfo.GetTrackIdForUri (uri, primary_source_ids);
if (track_id > 0) {
PodcastTrackInfo pi = new PodcastTrackInfo (DatabaseTrackInfo.Provider.FetchSingle (track_id));
pi.Item = enclosure.Item;
pi.Track.PrimarySourceId = source.DbId;
pi.SyncWithFeedItem ();
pi.Track.Save (false);
moved++;
}
}
if (moved > 0) {
ServiceManager.SourceManager.MusicLibrary.Reload ();
source.Reload ();
}
Hyena.Log.Information ("Done Migrating Podcast Feeds and Items");
}
DatabaseConfigurationClient.Client.Set<int> ("Podcast", "Version", 1);
}
if (DatabaseConfigurationClient.Client.Get<int> ("Podcast", "Version", 0) < 3) {
// We were using the Link as the fallback if the actual Guid was missing, but that was a poor choice
// since it is not always unique. We now use the title and pubdate combined.
ServiceManager.DbConnection.Execute ("UPDATE PodcastItems SET Guid = NULL");
foreach (FeedItem item in FeedItem.Provider.FetchAll ()) {
item.Guid = null;
if (item.Feed == null || FeedItem.Exists (item.Feed.DbId, item.Guid)) {
item.Delete (false);
} else {
item.Save ();
}
}
DatabaseConfigurationClient.Client.Set<int> ("Podcast", "Version", 3);
}
// Intentionally skpping 4 here because this needs to get run again for anybody who ran it
// before it was fixed, but only once if you never ran it
if (DatabaseConfigurationClient.Client.Get<int> ("Podcast", "Version", 0) < 5) {
ReplaceNewlines ("CoreTracks", "Title");
ReplaceNewlines ("CoreTracks", "TitleLowered");
ReplaceNewlines ("PodcastItems", "Title");
ReplaceNewlines ("PodcastItems", "Description");
DatabaseConfigurationClient.Client.Set<int> ("Podcast", "Version", 5);
}
// Initialize the new StrippedDescription field
if (DatabaseConfigurationClient.Client.Get<int> ("Podcast", "Version", 0) < 6) {
foreach (FeedItem item in FeedItem.Provider.FetchAll ()) {
item.UpdateStrippedDescription ();
item.Save ();
}
DatabaseConfigurationClient.Client.Set<int> ("Podcast", "Version", 6);
}
}
private void MigrateDownloadCache ()
{
string old_download_dir = Path.Combine (Paths.ApplicationData, "downloads");
if (Directory.Exists (old_download_dir)) {
foreach (string old_subdir in Directory.GetDirectories (old_download_dir)) {
string subdir_name = Path.GetFileName (old_subdir);
string new_subdir = Path.Combine (tmp_download_path, subdir_name);
Directory.Move (old_subdir, new_subdir);
}
Directory.Delete (old_download_dir);
}
}
private void ReplaceNewlines (string table, string column)
{
string cmd = String.Format ("UPDATE {0} SET {1}=replace({1}, ?, ?)", table, column);
ServiceManager.DbConnection.Execute (cmd, "\r\n", String.Empty);
ServiceManager.DbConnection.Execute (cmd, "\n", String.Empty);
ServiceManager.DbConnection.Execute (cmd, "\r", String.Empty);
}
public void Initialize ()
{
}
public void DelayedInitialize ()
{
download_manager = new DownloadManager (2, tmp_download_path);
download_manager_iface = new DownloadManagerInterface (download_manager);
download_manager_iface.Initialize ();
feeds_manager = new FeedsManager (ServiceManager.DbConnection, download_manager, null);
// Migrate data from 0.13.2 podcast tables, if they exist
MigrateLegacyIfNeeded ();
// Move incomplete downloads to the new cache location
try {
MigrateDownloadCache ();
} catch (Exception e) {
Hyena.Log.Exception ("Couldn't migrate podcast download cache", e);
}
source = new PodcastSource ();
ServiceManager.SourceManager.AddSource (source);
InitializeInterface ();
ThreadAssist.SpawnFromMain (delegate {
feeds_manager.PodcastStorageDirectory = source.BaseDirectory;
feeds_manager.FeedManager.ItemAdded += OnItemAdded;
feeds_manager.FeedManager.ItemChanged += OnItemChanged;
feeds_manager.FeedManager.ItemRemoved += OnItemRemoved;
feeds_manager.FeedManager.FeedsChanged += OnFeedsChanged;
if (DatabaseConfigurationClient.Client.Get<int> ("Podcast", "Version", 0) < 7) {
Banshee.Library.LibrarySource music_lib = ServiceManager.SourceManager.MusicLibrary;
if (music_lib != null) {
string old_path = Path.Combine (music_lib.BaseDirectory, "Podcasts");
string new_path = source.BaseDirectory;
SafeUri old_uri = new SafeUri (old_path);
SafeUri new_uri = new SafeUri (new_path);
if (old_path != null && new_path != null && old_path != new_path &&
Banshee.IO.Directory.Exists (old_path) && !Banshee.IO.Directory.Exists (new_path)) {
Banshee.IO.Directory.Move (new SafeUri (old_path), new SafeUri (new_path));
ServiceManager.DbConnection.Execute (String.Format (
"UPDATE {0} SET LocalPath = REPLACE(LocalPath, ?, ?) WHERE LocalPath IS NOT NULL",
FeedEnclosure.Provider.TableName), old_path, new_path);
ServiceManager.DbConnection.Execute (
"UPDATE CoreTracks SET Uri = REPLACE(Uri, ?, ?) WHERE Uri LIKE 'file://%' AND PrimarySourceId = ?",
old_uri.AbsoluteUri, new_uri.AbsoluteUri, source.DbId);
Hyena.Log.DebugFormat ("Moved Podcasts from {0} to {1}", old_path, new_path);
}
}
DatabaseConfigurationClient.Client.Set<int> ("Podcast", "Version", 7);
}
ServiceManager.PlayerEngine.ConnectEvent (OnPlayerEvent, PlayerEvent.StateChange);
ServiceManager.Get<DBusCommandService> ().ArgumentPushed += OnCommandLineArgument;
RefreshFeeds ();
// Every 10 minutes try to refresh again
refresh_timeout_id = Application.RunTimeout (1000 * 60 * 10, RefreshFeeds);
ServiceManager.Get<Network> ().StateChanged += OnNetworkStateChanged;
});
source.UpdateFeedMessages ();
}
private void OnNetworkStateChanged (object o, NetworkStateChangedArgs args)
{
RefreshFeeds ();
}
bool disposing;
public void Dispose ()
{
lock (sync) {
if (disposing | disposed) {
return;
} else {
disposing = true;
}
}
Application.IdleTimeoutRemove (refresh_timeout_id);
refresh_timeout_id = 0;
ServiceManager.PlayerEngine.DisconnectEvent (OnPlayerEvent);
ServiceManager.Get<DBusCommandService> ().ArgumentPushed -= OnCommandLineArgument;
ServiceManager.Get<Network> ().StateChanged -= OnNetworkStateChanged;
if (download_manager_iface != null) {
download_manager_iface.Dispose ();
download_manager_iface = null;
}
if (feeds_manager != null) {
feeds_manager.Dispose ();
feeds_manager = null;
}
if (download_manager != null) {
download_manager.Dispose ();
download_manager = null;
}
DisposeInterface ();
lock (sync) {
disposing = false;
disposed = true;
}
}
private bool RefreshFeeds ()
{
if (!ServiceManager.Get<Network> ().Connected)
return true;
Hyena.Log.Debug ("Refreshing any podcasts that haven't been updated in over an hour");
Banshee.Kernel.Scheduler.Schedule (new Banshee.Kernel.DelegateJob (delegate {
DateTime now = DateTime.Now;
foreach (Feed feed in Feed.Provider.FetchAll ()) {
if (feed.IsSubscribed && (now - feed.LastDownloadTime).TotalHours > 1) {
feed.Update ();
RefreshArtworkFor (feed);
}
}
}));
return true;
}
private void OnCommandLineArgument (string uri, object value, bool isFile)
{
if (!isFile || String.IsNullOrEmpty (uri)) {
return;
}
if (uri.Contains ("opml") || uri.EndsWith (".miro") || uri.EndsWith (".democracy")) {
// Handle OPML files
try {
OpmlParser opml_parser = new OpmlParser (uri, true);
foreach (string feed in opml_parser.Feeds) {
ServiceManager.Get<DBusCommandService> ().PushFile (feed);
}
} catch (Exception e) {
Log.Exception (e);
}
} else if (uri.Contains ("xml") || uri.Contains ("rss") || uri.Contains ("feed") || uri.StartsWith ("itpc") || uri.StartsWith ("pcast")) {
// Handle normal XML/RSS URLs
if (uri.StartsWith ("feed://") || uri.StartsWith ("itpc://")) {
uri = String.Format ("http://{0}", uri.Substring (7));
} else if (uri.StartsWith ("pcast://")) {
uri = String.Format ("http://{0}", uri.Substring (8));
}
AddFeed (uri, null);
} else if (uri.StartsWith ("itms://")) {
// Handle iTunes podcast URLs
System.Threading.ThreadPool.QueueUserWorkItem (delegate {
try {
var feed = new ItmsPodcast (uri);
if (feed.FeedUrl != null) {
ThreadAssist.ProxyToMain (delegate {
AddFeed (feed.FeedUrl, feed.Title);
});
}
} catch (Exception e) {
Hyena.Log.Exception (e);
}
});
}
}
private void AddFeed (string uri, string title)
{
// TODO replace autodownload w/ actual default preference
FeedsManager.Instance.FeedManager.CreateFeed (uri, title, FeedAutoDownload.None);
source.NotifyUser ();
source.UpdateFeedMessages ();
}
private void RefreshArtworkFor (Feed feed)
{
if (!String.IsNullOrEmpty (feed.ImageUrl) && !CoverArtSpec.CoverExists (PodcastService.ArtworkIdFor (feed))) {
Banshee.Kernel.Scheduler.Schedule (new PodcastImageFetchJob (feed), Banshee.Kernel.JobPriority.BelowNormal);
}
}
private DatabaseTrackInfo GetTrackByItemId (long item_id)
{
return DatabaseTrackInfo.Provider.FetchFirstMatching ("PrimarySourceID = ? AND ExternalID = ?", source.DbId, item_id);
}
private void OnItemAdded (FeedItem item)
{
if (item.Enclosure != null) {
DatabaseTrackInfo track = new DatabaseTrackInfo ();
track.ExternalId = item.DbId;
track.PrimarySource = source;
(track.ExternalObject as PodcastTrackInfo).SyncWithFeedItem ();
track.Save (false);
RefreshArtworkFor (item.Feed);
} else {
// We're only interested in items that have enclosures
item.Delete (false);
}
}
private void OnItemRemoved (FeedItem item)
{
DatabaseTrackInfo track = GetTrackByItemId (item.DbId);
if (track != null) {
DatabaseTrackInfo.Provider.Delete (track);
}
}
internal static bool IgnoreItemChanges = false;
private void OnItemChanged (FeedItem item)
{
if (IgnoreItemChanges) {
return;
}
DatabaseTrackInfo track = GetTrackByItemId (item.DbId);
if (track != null) {
PodcastTrackInfo pi = track.ExternalObject as PodcastTrackInfo;
if (pi != null) {
pi.SyncWithFeedItem ();
track.Save (true);
}
}
}
private void OnFeedsChanged (object o, EventArgs args)
{
source.Reload ();
source.NotifyTracksChanged ();
source.UpdateFeedMessages ();
}
/*private void OnFeedAddedHandler (object sender, FeedEventArgs args)
{
lock (sync) {
source.FeedModel.Add (args.Feed);
}
}
private void OnFeedRemovedHandler (object sender, FeedEventArgs args)
{
lock (sync) {
source.FeedModel.Remove (args.Feed);
args.Feed.Delete ();
}
}
private void OnFeedRenamedHandler (object sender, FeedEventArgs args)
{
lock (sync) {
source.FeedModel.Sort ();
}
}
private void OnFeedUpdatingHandler (object sender, FeedEventArgs args)
{
lock (sync) {
source.FeedModel.Reload ();
}
}
private void OnFeedDownloadCountChangedHandler (object sender, FeedDownloadCountChangedEventArgs args)
{
lock (sync) {
source.FeedModel.Reload ();
}
}*/
/*private void OnFeedItemAddedHandler (object sender, FeedItemEventArgs args)
{
lock (sync) {
if (args.Item != null) {
AddFeedItem (args.Item);
} else if (args.Items != null) {
foreach (FeedItem item in args.Items) {
AddFeedItem (item);
}
}
}
}*/
public void AddFeedItem (FeedItem item)
{
if (item.Enclosure != null) {
PodcastTrackInfo pi = new PodcastTrackInfo (new DatabaseTrackInfo (), item);
pi.Track.PrimarySource = source;
pi.Track.Save (true);
source.NotifyUser ();
} else {
item.Delete (false);
}
}
/*private void OnFeedItemRemovedHandler (object sender, FeedItemEventArgs e)
{
lock (sync) {
if (e.Item != null) {
PodcastItem.DeleteWithFeedId (e.Item.DbId);
} else if (e.Items != null) {
foreach (FeedItem fi in e.Items) {
PodcastItem.DeleteWithFeedId (fi.DbId);
}
}
source.Reload ();
}
}
private void OnFeedItemCountChanged (object sender,
FeedItemCountChangedEventArgs e)
{
//UpdateCount ();
}*/
/*private void OnFeedDownloadCompletedHandler (object sender,
FeedDownloadCompletedEventArgs e)
{
lock (sync) {
Feed f = feedDict[e.Feed.DbId];
if (e.Error == FeedDownloadError.None) {
if (String.IsNullOrEmpty(e.Feed.LocalEnclosurePath)) {
e.Feed.LocalEnclosurePath = Path.Combine (
tmp_enclosure_path, SanitizeName (e.Feed.Name)
);
}
if (f.AutoDownload != FeedAutoDownload.None) {
ReadOnlyCollection<FeedItem> items = e.Feed.Items;
if (items != null) {
if (f.AutoDownload == FeedAutoDownload.One &&
items.Count > 0) {
items[0].Enclosure.AsyncDownload ();
} else {
foreach (FeedItem fi in items) {
fi.Enclosure.AsyncDownload ();
}
}
}
}
}
source.Reload ();
}
}*/
/*private void OnTaskAssociated (object sender, EventArgs e)
{
lock (sync) {
source.Reload ();
}
}
private void OnTaskStatusChanged (object sender,
TaskStatusChangedEventArgs e)
{
lock (sync) {
source.Reload ();
}
}
private void TaskStartedHandler (object sender,
TaskEventArgs<HttpFileDownloadTask> e)
{
lock (sync) {
source.Reload ();
}
}
private void OnTaskStoppedHandler (object sender,
TaskEventArgs<HttpFileDownloadTask> e)
{
// TODO merge
lock (sync) {
if (e.Task != null && e.Task.Status == TaskStatus.Succeeded) {
FeedEnclosure enc = e.Task.UserState as FeedEnclosure;
if (enc != null) {
FeedItem item = enc.Item;
DatabaseTrackInfo track = null;
if (itemDict.ContainsKey (item.DbId)) {
PodcastItem pi = itemDict[item.DbId];
track = import_manager.ImportPodcast (enc.LocalPath);
if (track != null) {
pi.Track = track;
pi.New = true;
pi.Save ();
}
item.IsRead = true;
}
}
}
source.Reload ();
}
}*/
private void OnPlayerEvent (PlayerEventArgs args)
{
lock (sync) {
//source.Reload ();
}
}
public static string ArtworkIdFor (Feed feed)
{
string digest = Banshee.Base.CoverArtSpec.Digest (feed.Title);
return digest == null ? null : String.Format ("podcast-{0}", digest);
}
// Via Monopod
/*private static string SanitizeName (string s)
{
// remove /, : and \ from names
return s.Replace ('/', '_').Replace ('\\', '_').Replace (':', '_').Replace (' ', '_');
}*/
public string ServiceName {
get { return "PodcastService"; }
}
}
}
| |
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using Avalonia.Controls.Platform;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Input.Raw;
using Avalonia.Layout;
using Avalonia.Logging;
using Avalonia.LogicalTree;
using Avalonia.Platform;
using Avalonia.Rendering;
using Avalonia.Styling;
using Avalonia.Utilities;
using Avalonia.VisualTree;
using JetBrains.Annotations;
namespace Avalonia.Controls
{
/// <summary>
/// Base class for top-level widgets.
/// </summary>
/// <remarks>
/// This class acts as a base for top level widget.
/// It handles scheduling layout, styling and rendering as well as
/// tracking the widget's <see cref="ClientSize"/>.
/// </remarks>
public abstract class TopLevel : ContentControl,
IInputRoot,
ILayoutRoot,
IRenderRoot,
ICloseable,
IStyleRoot,
IWeakSubscriber<ResourcesChangedEventArgs>
{
/// <summary>
/// Defines the <see cref="ClientSize"/> property.
/// </summary>
public static readonly DirectProperty<TopLevel, Size> ClientSizeProperty =
AvaloniaProperty.RegisterDirect<TopLevel, Size>(nameof(ClientSize), o => o.ClientSize);
/// <summary>
/// Defines the <see cref="IInputRoot.PointerOverElement"/> property.
/// </summary>
public static readonly StyledProperty<IInputElement> PointerOverElementProperty =
AvaloniaProperty.Register<TopLevel, IInputElement>(nameof(IInputRoot.PointerOverElement));
private readonly IInputManager _inputManager;
private readonly IAccessKeyHandler _accessKeyHandler;
private readonly IKeyboardNavigationHandler _keyboardNavigationHandler;
private readonly IApplicationLifecycle _applicationLifecycle;
private readonly IPlatformRenderInterface _renderInterface;
private Size _clientSize;
/// <summary>
/// Initializes static members of the <see cref="TopLevel"/> class.
/// </summary>
static TopLevel()
{
AffectsMeasure(ClientSizeProperty);
}
/// <summary>
/// Initializes a new instance of the <see cref="TopLevel"/> class.
/// </summary>
/// <param name="impl">The platform-specific window implementation.</param>
public TopLevel(ITopLevelImpl impl)
: this(impl, AvaloniaLocator.Current)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="TopLevel"/> class.
/// </summary>
/// <param name="impl">The platform-specific window implementation.</param>
/// <param name="dependencyResolver">
/// The dependency resolver to use. If null the default dependency resolver will be used.
/// </param>
public TopLevel(ITopLevelImpl impl, IAvaloniaDependencyResolver dependencyResolver)
{
if (impl == null)
{
throw new InvalidOperationException(
"Could not create window implementation: maybe no windowing subsystem was initialized?");
}
PlatformImpl = impl;
dependencyResolver = dependencyResolver ?? AvaloniaLocator.Current;
var styler = TryGetService<IStyler>(dependencyResolver);
_accessKeyHandler = TryGetService<IAccessKeyHandler>(dependencyResolver);
_inputManager = TryGetService<IInputManager>(dependencyResolver);
_keyboardNavigationHandler = TryGetService<IKeyboardNavigationHandler>(dependencyResolver);
_applicationLifecycle = TryGetService<IApplicationLifecycle>(dependencyResolver);
_renderInterface = TryGetService<IPlatformRenderInterface>(dependencyResolver);
var renderLoop = TryGetService<IRenderLoop>(dependencyResolver);
Renderer = impl.CreateRenderer(this);
impl.SetInputRoot(this);
impl.Closed = HandleClosed;
impl.Input = HandleInput;
impl.Paint = HandlePaint;
impl.Resized = HandleResized;
impl.ScalingChanged = HandleScalingChanged;
_keyboardNavigationHandler?.SetOwner(this);
_accessKeyHandler?.SetOwner(this);
styler?.ApplyStyles(this);
ClientSize = impl.ClientSize;
this.GetObservable(PointerOverElementProperty)
.Select(
x => (x as InputElement)?.GetObservable(CursorProperty) ?? Observable.Empty<Cursor>())
.Switch().Subscribe(cursor => PlatformImpl?.SetCursor(cursor?.PlatformCursor));
if (_applicationLifecycle != null)
{
_applicationLifecycle.OnExit += OnApplicationExiting;
}
if (((IStyleHost)this).StylingParent is IResourceProvider applicationResources)
{
WeakSubscriptionManager.Subscribe(
applicationResources,
nameof(IResourceProvider.ResourcesChanged),
this);
}
}
/// <summary>
/// Fired when the window is closed.
/// </summary>
public event EventHandler Closed;
/// <summary>
/// Gets or sets the client size of the window.
/// </summary>
public Size ClientSize
{
get { return _clientSize; }
protected set { SetAndRaise(ClientSizeProperty, ref _clientSize, value); }
}
/// <summary>
/// Gets the platform-specific window implementation.
/// </summary>
[CanBeNull]
public ITopLevelImpl PlatformImpl { get; private set; }
/// <summary>
/// Gets the renderer for the window.
/// </summary>
public IRenderer Renderer { get; private set; }
/// <summary>
/// Gets the access key handler for the window.
/// </summary>
IAccessKeyHandler IInputRoot.AccessKeyHandler => _accessKeyHandler;
/// <summary>
/// Gets or sets the keyboard navigation handler for the window.
/// </summary>
IKeyboardNavigationHandler IInputRoot.KeyboardNavigationHandler => _keyboardNavigationHandler;
/// <summary>
/// Gets or sets the input element that the pointer is currently over.
/// </summary>
IInputElement IInputRoot.PointerOverElement
{
get { return GetValue(PointerOverElementProperty); }
set { SetValue(PointerOverElementProperty, value); }
}
/// <inheritdoc/>
IMouseDevice IInputRoot.MouseDevice => PlatformImpl?.MouseDevice;
void IWeakSubscriber<ResourcesChangedEventArgs>.OnEvent(object sender, ResourcesChangedEventArgs e)
{
((ILogical)this).NotifyResourcesChanged(e);
}
/// <summary>
/// Gets or sets a value indicating whether access keys are shown in the window.
/// </summary>
bool IInputRoot.ShowAccessKeys
{
get { return GetValue(AccessText.ShowAccessKeyProperty); }
set { SetValue(AccessText.ShowAccessKeyProperty, value); }
}
/// <inheritdoc/>
Size ILayoutRoot.MaxClientSize => Size.Infinity;
/// <inheritdoc/>
double ILayoutRoot.LayoutScaling => PlatformImpl?.Scaling ?? 1;
/// <inheritdoc/>
double IRenderRoot.RenderScaling => PlatformImpl?.Scaling ?? 1;
IStyleHost IStyleHost.StylingParent
{
get { return AvaloniaLocator.Current.GetService<IGlobalStyles>(); }
}
IRenderTarget IRenderRoot.CreateRenderTarget() => CreateRenderTarget();
/// <inheritdoc/>
protected virtual IRenderTarget CreateRenderTarget()
{
if(PlatformImpl == null)
throw new InvalidOperationException("Cann't create render target, PlatformImpl is null (might be already disposed)");
return _renderInterface.CreateRenderTarget(PlatformImpl.Surfaces);
}
/// <inheritdoc/>
void IRenderRoot.Invalidate(Rect rect)
{
PlatformImpl?.Invalidate(rect);
}
/// <inheritdoc/>
Point IRenderRoot.PointToClient(Point p)
{
return PlatformImpl?.PointToClient(p) ?? default(Point);
}
/// <inheritdoc/>
Point IRenderRoot.PointToScreen(Point p)
{
return PlatformImpl?.PointToScreen(p) ?? default(Point);
}
/// <summary>
/// Handles a paint notification from <see cref="ITopLevelImpl.Resized"/>.
/// </summary>
/// <param name="rect">The dirty area.</param>
protected virtual void HandlePaint(Rect rect)
{
Renderer?.Paint(rect);
}
/// <summary>
/// Handles a closed notification from <see cref="ITopLevelImpl.Closed"/>.
/// </summary>
protected virtual void HandleClosed()
{
PlatformImpl = null;
Closed?.Invoke(this, EventArgs.Empty);
Renderer?.Dispose();
Renderer = null;
_applicationLifecycle.OnExit -= OnApplicationExiting;
}
/// <summary>
/// Handles a resize notification from <see cref="ITopLevelImpl.Resized"/>.
/// </summary>
/// <param name="clientSize">The new client size.</param>
protected virtual void HandleResized(Size clientSize)
{
ClientSize = clientSize;
Width = clientSize.Width;
Height = clientSize.Height;
LayoutManager.Instance.ExecuteLayoutPass();
Renderer?.Resized(clientSize);
}
/// <summary>
/// Handles a window scaling change notification from
/// <see cref="ITopLevelImpl.ScalingChanged"/>.
/// </summary>
/// <param name="scaling">The window scaling.</param>
protected virtual void HandleScalingChanged(double scaling)
{
foreach (ILayoutable control in this.GetSelfAndVisualDescendants())
{
control.InvalidateMeasure();
}
}
/// <inheritdoc/>
protected override void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e)
{
base.OnAttachedToVisualTree(e);
throw new InvalidOperationException(
$"Control '{GetType().Name}' is a top level control and cannot be added as a child.");
}
/// <summary>
/// Tries to get a service from an <see cref="IAvaloniaDependencyResolver"/>, logging a
/// warning if not found.
/// </summary>
/// <typeparam name="T">The service type.</typeparam>
/// <param name="resolver">The resolver.</param>
/// <returns>The service.</returns>
private T TryGetService<T>(IAvaloniaDependencyResolver resolver) where T : class
{
var result = resolver.GetService<T>();
if (result == null)
{
Logger.Warning(
LogArea.Control,
this,
"Could not create {Service} : maybe Application.RegisterServices() wasn't called?",
typeof(T));
}
return result;
}
private void OnApplicationExiting(object sender, EventArgs args)
{
HandleApplicationExiting();
}
/// <summary>
/// Handles the application exiting, either from the last window closing, or a call to <see cref="IApplicationLifecycle.Exit"/>.
/// </summary>
protected virtual void HandleApplicationExiting()
{
}
/// <summary>
/// Handles input from <see cref="ITopLevelImpl.Input"/>.
/// </summary>
/// <param name="e">The event args.</param>
private void HandleInput(RawInputEventArgs e)
{
_inputManager.ProcessInput(e);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Dynamic.Utils;
using System.Reflection;
using System.Reflection.Emit;
using static System.Linq.Expressions.CachedReflectionInfo;
namespace System.Linq.Expressions.Compiler
{
internal partial class LambdaCompiler
{
#region Conditional
private void EmitConditionalExpression(Expression expr, CompilationFlags flags)
{
ConditionalExpression node = (ConditionalExpression)expr;
Debug.Assert(node.Test.Type == typeof(bool));
Label labFalse = _ilg.DefineLabel();
EmitExpressionAndBranch(false, node.Test, labFalse);
EmitExpressionAsType(node.IfTrue, node.Type, flags);
if (NotEmpty(node.IfFalse))
{
Label labEnd = _ilg.DefineLabel();
if ((flags & CompilationFlags.EmitAsTailCallMask) == CompilationFlags.EmitAsTail)
{
// We know the conditional expression is at the end of the lambda,
// so it is safe to emit Ret here.
_ilg.Emit(OpCodes.Ret);
}
else
{
_ilg.Emit(OpCodes.Br, labEnd);
}
_ilg.MarkLabel(labFalse);
EmitExpressionAsType(node.IfFalse, node.Type, flags);
_ilg.MarkLabel(labEnd);
}
else
{
_ilg.MarkLabel(labFalse);
}
}
/// <summary>
/// returns true if the expression is not empty, otherwise false.
/// </summary>
private static bool NotEmpty(Expression node)
{
var empty = node as DefaultExpression;
if (empty == null || empty.Type != typeof(void))
{
return true;
}
return false;
}
/// <summary>
/// returns true if the expression is NOT empty and is not debug info,
/// or a block that contains only insignificant expressions.
/// </summary>
private static bool Significant(Expression node)
{
var block = node as BlockExpression;
if (block != null)
{
for (int i = 0; i < block.ExpressionCount; i++)
{
if (Significant(block.GetExpression(i)))
{
return true;
}
}
return false;
}
return NotEmpty(node) && !(node is DebugInfoExpression);
}
#endregion
#region Coalesce
private void EmitCoalesceBinaryExpression(Expression expr)
{
BinaryExpression b = (BinaryExpression)expr;
Debug.Assert(b.Method == null);
if (b.Left.Type.IsNullableType())
{
EmitNullableCoalesce(b);
}
else if (b.Left.Type.IsValueType)
{
throw Error.CoalesceUsedOnNonNullType();
}
else if (b.Conversion != null)
{
EmitLambdaReferenceCoalesce(b);
}
else
{
EmitReferenceCoalesceWithoutConversion(b);
}
}
private void EmitNullableCoalesce(BinaryExpression b)
{
Debug.Assert(b.Method == null);
LocalBuilder loc = GetLocal(b.Left.Type);
Label labIfNull = _ilg.DefineLabel();
Label labEnd = _ilg.DefineLabel();
EmitExpression(b.Left);
_ilg.Emit(OpCodes.Stloc, loc);
_ilg.Emit(OpCodes.Ldloca, loc);
_ilg.EmitHasValue(b.Left.Type);
_ilg.Emit(OpCodes.Brfalse, labIfNull);
Type nnLeftType = b.Left.Type.GetNonNullableType();
if (b.Conversion != null)
{
Debug.Assert(b.Conversion.ParameterCount == 1);
ParameterExpression p = b.Conversion.GetParameter(0);
Debug.Assert(p.Type.IsAssignableFrom(b.Left.Type) ||
p.Type.IsAssignableFrom(nnLeftType));
// emit the delegate instance
EmitLambdaExpression(b.Conversion);
// emit argument
if (!p.Type.IsAssignableFrom(b.Left.Type))
{
_ilg.Emit(OpCodes.Ldloca, loc);
_ilg.EmitGetValueOrDefault(b.Left.Type);
}
else
{
_ilg.Emit(OpCodes.Ldloc, loc);
}
// emit call to invoke
_ilg.Emit(OpCodes.Callvirt, b.Conversion.Type.GetMethod("Invoke"));
}
else if (!TypeUtils.AreEquivalent(b.Type, nnLeftType))
{
_ilg.Emit(OpCodes.Ldloca, loc);
_ilg.EmitGetValueOrDefault(b.Left.Type);
_ilg.EmitConvertToType(nnLeftType, b.Type, isChecked: true, locals: this);
}
else
{
_ilg.Emit(OpCodes.Ldloca, loc);
_ilg.EmitGetValueOrDefault(b.Left.Type);
}
FreeLocal(loc);
_ilg.Emit(OpCodes.Br, labEnd);
_ilg.MarkLabel(labIfNull);
EmitExpression(b.Right);
if (!TypeUtils.AreEquivalent(b.Right.Type, b.Type))
{
_ilg.EmitConvertToType(b.Right.Type, b.Type, isChecked: true, locals: this);
}
_ilg.MarkLabel(labEnd);
}
private void EmitLambdaReferenceCoalesce(BinaryExpression b)
{
LocalBuilder loc = GetLocal(b.Left.Type);
Label labEnd = _ilg.DefineLabel();
Label labNotNull = _ilg.DefineLabel();
EmitExpression(b.Left);
_ilg.Emit(OpCodes.Dup);
_ilg.Emit(OpCodes.Stloc, loc);
_ilg.Emit(OpCodes.Brtrue, labNotNull);
EmitExpression(b.Right);
_ilg.Emit(OpCodes.Br, labEnd);
// if not null, call conversion
_ilg.MarkLabel(labNotNull);
Debug.Assert(b.Conversion.ParameterCount == 1);
// emit the delegate instance
EmitLambdaExpression(b.Conversion);
// emit argument
_ilg.Emit(OpCodes.Ldloc, loc);
FreeLocal(loc);
// emit call to invoke
_ilg.Emit(OpCodes.Callvirt, b.Conversion.Type.GetMethod("Invoke"));
_ilg.MarkLabel(labEnd);
}
private void EmitReferenceCoalesceWithoutConversion(BinaryExpression b)
{
Label labEnd = _ilg.DefineLabel();
Label labCast = _ilg.DefineLabel();
EmitExpression(b.Left);
_ilg.Emit(OpCodes.Dup);
_ilg.Emit(OpCodes.Brtrue, labCast);
_ilg.Emit(OpCodes.Pop);
EmitExpression(b.Right);
if (!TypeUtils.AreEquivalent(b.Right.Type, b.Type))
{
if (b.Right.Type.IsValueType)
{
_ilg.Emit(OpCodes.Box, b.Right.Type);
}
_ilg.Emit(OpCodes.Castclass, b.Type);
}
_ilg.Emit(OpCodes.Br_S, labEnd);
_ilg.MarkLabel(labCast);
if (!TypeUtils.AreEquivalent(b.Left.Type, b.Type))
{
Debug.Assert(!b.Left.Type.IsValueType);
_ilg.Emit(OpCodes.Castclass, b.Type);
}
_ilg.MarkLabel(labEnd);
}
#endregion
#region AndAlso
private void EmitLiftedAndAlso(BinaryExpression b)
{
Type type = typeof(bool?);
Label labComputeRight = _ilg.DefineLabel();
Label labReturnFalse = _ilg.DefineLabel();
Label labReturnNull = _ilg.DefineLabel();
Label labReturnValue = _ilg.DefineLabel();
Label labExit = _ilg.DefineLabel();
LocalBuilder locLeft = GetLocal(type);
LocalBuilder locRight = GetLocal(type);
EmitExpression(b.Left);
_ilg.Emit(OpCodes.Stloc, locLeft);
_ilg.Emit(OpCodes.Ldloca, locLeft);
_ilg.EmitHasValue(type);
_ilg.Emit(OpCodes.Brfalse, labComputeRight);
_ilg.Emit(OpCodes.Ldloca, locLeft);
_ilg.EmitGetValueOrDefault(type);
_ilg.Emit(OpCodes.Brfalse, labReturnFalse);
// compute right
_ilg.MarkLabel(labComputeRight);
EmitExpression(b.Right);
_ilg.Emit(OpCodes.Stloc, locRight);
_ilg.Emit(OpCodes.Ldloca, locRight);
_ilg.EmitHasValue(type);
_ilg.Emit(OpCodes.Brfalse_S, labReturnNull);
_ilg.Emit(OpCodes.Ldloca, locRight);
_ilg.EmitGetValueOrDefault(type);
_ilg.Emit(OpCodes.Brfalse_S, labReturnFalse);
// check left for null again
_ilg.Emit(OpCodes.Ldloca, locLeft);
_ilg.EmitHasValue(type);
_ilg.Emit(OpCodes.Brfalse, labReturnNull);
// return true
_ilg.Emit(OpCodes.Ldc_I4_1);
_ilg.Emit(OpCodes.Br_S, labReturnValue);
// return false
_ilg.MarkLabel(labReturnFalse);
_ilg.Emit(OpCodes.Ldc_I4_0);
_ilg.Emit(OpCodes.Br_S, labReturnValue);
_ilg.MarkLabel(labReturnValue);
ConstructorInfo ci = type.GetConstructor(ArrayOfType_Bool);
_ilg.Emit(OpCodes.Newobj, ci);
_ilg.Emit(OpCodes.Stloc, locLeft);
_ilg.Emit(OpCodes.Br, labExit);
// return null
_ilg.MarkLabel(labReturnNull);
_ilg.Emit(OpCodes.Ldloca, locLeft);
_ilg.Emit(OpCodes.Initobj, type);
_ilg.MarkLabel(labExit);
_ilg.Emit(OpCodes.Ldloc, locLeft);
FreeLocal(locLeft);
FreeLocal(locRight);
}
private void EmitMethodAndAlso(BinaryExpression b, CompilationFlags flags)
{
Label labEnd = _ilg.DefineLabel();
EmitExpression(b.Left);
_ilg.Emit(OpCodes.Dup);
MethodInfo opFalse = TypeUtils.GetBooleanOperator(b.Method.DeclaringType, "op_False");
Debug.Assert(opFalse != null, "factory should check that the method exists");
_ilg.Emit(OpCodes.Call, opFalse);
_ilg.Emit(OpCodes.Brtrue, labEnd);
//store the value of the left value before emitting b.Right to empty the evaluation stack
LocalBuilder locLeft = GetLocal(b.Left.Type);
_ilg.Emit(OpCodes.Stloc, locLeft);
EmitExpression(b.Right);
//store the right value to local
LocalBuilder locRight = GetLocal(b.Right.Type);
_ilg.Emit(OpCodes.Stloc, locRight);
Debug.Assert(b.Method.IsStatic);
_ilg.Emit(OpCodes.Ldloc, locLeft);
_ilg.Emit(OpCodes.Ldloc, locRight);
if ((flags & CompilationFlags.EmitAsTailCallMask) == CompilationFlags.EmitAsTail)
{
_ilg.Emit(OpCodes.Tailcall);
}
_ilg.Emit(OpCodes.Call, b.Method);
FreeLocal(locLeft);
FreeLocal(locRight);
_ilg.MarkLabel(labEnd);
}
private void EmitUnliftedAndAlso(BinaryExpression b)
{
Label @else = _ilg.DefineLabel();
Label end = _ilg.DefineLabel();
EmitExpressionAndBranch(false, b.Left, @else);
EmitExpression(b.Right);
_ilg.Emit(OpCodes.Br, end);
_ilg.MarkLabel(@else);
_ilg.Emit(OpCodes.Ldc_I4_0);
_ilg.MarkLabel(end);
}
private void EmitAndAlsoBinaryExpression(Expression expr, CompilationFlags flags)
{
BinaryExpression b = (BinaryExpression)expr;
if (b.Method != null && !b.IsLiftedLogical)
{
EmitMethodAndAlso(b, flags);
}
else if (b.Left.Type == typeof(bool?))
{
EmitLiftedAndAlso(b);
}
else if (b.IsLiftedLogical)
{
EmitExpression(b.ReduceUserdefinedLifted());
}
else
{
EmitUnliftedAndAlso(b);
}
}
#endregion
#region OrElse
private void EmitLiftedOrElse(BinaryExpression b)
{
Type type = typeof(bool?);
Label labComputeRight = _ilg.DefineLabel();
Label labReturnTrue = _ilg.DefineLabel();
Label labReturnNull = _ilg.DefineLabel();
Label labReturnValue = _ilg.DefineLabel();
Label labExit = _ilg.DefineLabel();
LocalBuilder locLeft = GetLocal(type);
LocalBuilder locRight = GetLocal(type);
EmitExpression(b.Left);
_ilg.Emit(OpCodes.Stloc, locLeft);
_ilg.Emit(OpCodes.Ldloca, locLeft);
_ilg.EmitHasValue(type);
_ilg.Emit(OpCodes.Brfalse, labComputeRight);
_ilg.Emit(OpCodes.Ldloca, locLeft);
_ilg.EmitGetValueOrDefault(type);
_ilg.Emit(OpCodes.Brtrue, labReturnTrue);
// compute right
_ilg.MarkLabel(labComputeRight);
EmitExpression(b.Right);
_ilg.Emit(OpCodes.Stloc, locRight);
_ilg.Emit(OpCodes.Ldloca, locRight);
_ilg.EmitHasValue(type);
_ilg.Emit(OpCodes.Brfalse_S, labReturnNull);
_ilg.Emit(OpCodes.Ldloca, locRight);
_ilg.EmitGetValueOrDefault(type);
_ilg.Emit(OpCodes.Brtrue_S, labReturnTrue);
// check left for null again
_ilg.Emit(OpCodes.Ldloca, locLeft);
_ilg.EmitHasValue(type);
_ilg.Emit(OpCodes.Brfalse, labReturnNull);
// return false
_ilg.Emit(OpCodes.Ldc_I4_0);
_ilg.Emit(OpCodes.Br_S, labReturnValue);
// return true
_ilg.MarkLabel(labReturnTrue);
_ilg.Emit(OpCodes.Ldc_I4_1);
_ilg.Emit(OpCodes.Br_S, labReturnValue);
_ilg.MarkLabel(labReturnValue);
ConstructorInfo ci = type.GetConstructor(ArrayOfType_Bool);
_ilg.Emit(OpCodes.Newobj, ci);
_ilg.Emit(OpCodes.Stloc, locLeft);
_ilg.Emit(OpCodes.Br, labExit);
// return null
_ilg.MarkLabel(labReturnNull);
_ilg.Emit(OpCodes.Ldloca, locLeft);
_ilg.Emit(OpCodes.Initobj, type);
_ilg.MarkLabel(labExit);
_ilg.Emit(OpCodes.Ldloc, locLeft);
FreeLocal(locLeft);
FreeLocal(locRight);
}
private void EmitUnliftedOrElse(BinaryExpression b)
{
Label @else = _ilg.DefineLabel();
Label end = _ilg.DefineLabel();
EmitExpressionAndBranch(false, b.Left, @else);
_ilg.Emit(OpCodes.Ldc_I4_1);
_ilg.Emit(OpCodes.Br, end);
_ilg.MarkLabel(@else);
EmitExpression(b.Right);
_ilg.MarkLabel(end);
}
private void EmitMethodOrElse(BinaryExpression b, CompilationFlags flags)
{
Label labEnd = _ilg.DefineLabel();
EmitExpression(b.Left);
_ilg.Emit(OpCodes.Dup);
MethodInfo opTrue = TypeUtils.GetBooleanOperator(b.Method.DeclaringType, "op_True");
Debug.Assert(opTrue != null, "factory should check that the method exists");
_ilg.Emit(OpCodes.Call, opTrue);
_ilg.Emit(OpCodes.Brtrue, labEnd);
//store the value of the left value before emitting b.Right to empty the evaluation stack
LocalBuilder locLeft = GetLocal(b.Left.Type);
_ilg.Emit(OpCodes.Stloc, locLeft);
EmitExpression(b.Right);
//store the right value to local
LocalBuilder locRight = GetLocal(b.Right.Type);
_ilg.Emit(OpCodes.Stloc, locRight);
Debug.Assert(b.Method.IsStatic);
_ilg.Emit(OpCodes.Ldloc, locLeft);
_ilg.Emit(OpCodes.Ldloc, locRight);
if ((flags & CompilationFlags.EmitAsTailCallMask) == CompilationFlags.EmitAsTail)
{
_ilg.Emit(OpCodes.Tailcall);
}
_ilg.Emit(OpCodes.Call, b.Method);
FreeLocal(locLeft);
FreeLocal(locRight);
_ilg.MarkLabel(labEnd);
}
private void EmitOrElseBinaryExpression(Expression expr, CompilationFlags flags)
{
BinaryExpression b = (BinaryExpression)expr;
if (b.Method != null && !b.IsLiftedLogical)
{
EmitMethodOrElse(b, flags);
}
else if (b.Left.Type == typeof(bool?))
{
EmitLiftedOrElse(b);
}
else if (b.IsLiftedLogical)
{
EmitExpression(b.ReduceUserdefinedLifted());
}
else
{
EmitUnliftedOrElse(b);
}
}
#endregion
#region Optimized branching
/// <summary>
/// Emits the expression and then either brtrue/brfalse to the label.
/// </summary>
/// <param name="branchValue">True for brtrue, false for brfalse.</param>
/// <param name="node">The expression to emit.</param>
/// <param name="label">The label to conditionally branch to.</param>
/// <remarks>
/// This function optimizes equality and short circuiting logical
/// operators to avoid double-branching, minimize instruction count,
/// and generate similar IL to the C# compiler. This is important for
/// the JIT to optimize patterns like:
/// x != null AndAlso x.GetType() == typeof(SomeType)
///
/// One optimization we don't do: we always emits at least one
/// conditional branch to the label, and always possibly falls through,
/// even if we know if the branch will always succeed or always fail.
/// We do this to avoid generating unreachable code, which is fine for
/// the CLR JIT, but doesn't verify with peverify.
///
/// This kind of optimization could be implemented safely, by doing
/// constant folding over conditionals and logical expressions at the
/// tree level.
/// </remarks>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")]
private void EmitExpressionAndBranch(bool branchValue, Expression node, Label label)
{
CompilationFlags startEmitted = EmitExpressionStart(node);
try
{
if (node.Type == typeof(bool))
{
switch (node.NodeType)
{
case ExpressionType.Not:
EmitBranchNot(branchValue, (UnaryExpression)node, label);
return;
case ExpressionType.AndAlso:
case ExpressionType.OrElse:
EmitBranchLogical(branchValue, (BinaryExpression)node, label);
return;
case ExpressionType.Block:
EmitBranchBlock(branchValue, (BlockExpression)node, label);
return;
case ExpressionType.Equal:
case ExpressionType.NotEqual:
EmitBranchComparison(branchValue, (BinaryExpression)node, label);
return;
}
}
EmitExpression(node, CompilationFlags.EmitAsNoTail | CompilationFlags.EmitNoExpressionStart);
EmitBranchOp(branchValue, label);
}
finally
{
EmitExpressionEnd(startEmitted);
}
}
private void EmitBranchOp(bool branch, Label label)
{
_ilg.Emit(branch ? OpCodes.Brtrue : OpCodes.Brfalse, label);
}
private void EmitBranchNot(bool branch, UnaryExpression node, Label label)
{
if (node.Method != null)
{
EmitExpression(node, CompilationFlags.EmitAsNoTail | CompilationFlags.EmitNoExpressionStart);
EmitBranchOp(branch, label);
return;
}
EmitExpressionAndBranch(!branch, node.Operand, label);
}
private void EmitBranchComparison(bool branch, BinaryExpression node, Label label)
{
Debug.Assert(node.NodeType == ExpressionType.Equal || node.NodeType == ExpressionType.NotEqual);
Debug.Assert(!node.IsLiftedToNull);
// To share code paths, we want to treat NotEqual as an inverted Equal
bool branchWhenEqual = branch == (node.NodeType == ExpressionType.Equal);
if (node.Method != null)
{
EmitBinaryMethod(node, CompilationFlags.EmitAsNoTail);
// EmitBinaryMethod takes into account the Equal/NotEqual
// node kind, so use the original branch value
EmitBranchOp(branch, label);
}
else if (ConstantCheck.IsNull(node.Left))
{
if (node.Right.Type.IsNullableType())
{
EmitAddress(node.Right, node.Right.Type);
_ilg.EmitHasValue(node.Right.Type);
}
else
{
Debug.Assert(!node.Right.Type.IsValueType);
EmitExpression(GetEqualityOperand(node.Right));
}
EmitBranchOp(!branchWhenEqual, label);
}
else if (ConstantCheck.IsNull(node.Right))
{
if (node.Left.Type.IsNullableType())
{
EmitAddress(node.Left, node.Left.Type);
_ilg.EmitHasValue(node.Left.Type);
}
else
{
Debug.Assert(!node.Left.Type.IsValueType);
EmitExpression(GetEqualityOperand(node.Left));
}
EmitBranchOp(!branchWhenEqual, label);
}
else if (node.Left.Type.IsNullableType() || node.Right.Type.IsNullableType())
{
EmitBinaryExpression(node);
// EmitBinaryExpression takes into account the Equal/NotEqual
// node kind, so use the original branch value
EmitBranchOp(branch, label);
}
else
{
EmitExpression(GetEqualityOperand(node.Left));
EmitExpression(GetEqualityOperand(node.Right));
_ilg.Emit(branchWhenEqual ? OpCodes.Beq : OpCodes.Bne_Un, label);
}
}
// For optimized Equal/NotEqual, we can eliminate reference
// conversions. IL allows comparing managed pointers regardless of
// type. See ECMA-335 "Binary Comparison or Branch Operations", in
// Partition III, Section 1.5 Table 4.
private static Expression GetEqualityOperand(Expression expression)
{
if (expression.NodeType == ExpressionType.Convert)
{
var convert = (UnaryExpression)expression;
if (TypeUtils.AreReferenceAssignable(convert.Type, convert.Operand.Type))
{
return convert.Operand;
}
}
return expression;
}
private void EmitBranchLogical(bool branch, BinaryExpression node, Label label)
{
Debug.Assert(node.NodeType == ExpressionType.AndAlso || node.NodeType == ExpressionType.OrElse);
Debug.Assert(!node.IsLiftedToNull);
if (node.Method != null || node.IsLifted)
{
EmitExpression(node);
EmitBranchOp(branch, label);
return;
}
bool isAnd = node.NodeType == ExpressionType.AndAlso;
// To share code, we make the following substitutions:
// if (!(left || right)) branch value
// becomes:
// if (!left && !right) branch value
// and:
// if (!(left && right)) branch value
// becomes:
// if (!left || !right) branch value
//
// The observation is that "brtrue(x && y)" has the same codegen as
// "brfalse(x || y)" except the branches have the opposite sign.
// Same for "brfalse(x && y)" and "brtrue(x || y)".
//
if (branch == isAnd)
{
EmitBranchAnd(branch, node, label);
}
else
{
EmitBranchOr(branch, node, label);
}
}
// Generates optimized AndAlso with branch == true
// or optimized OrElse with branch == false
private void EmitBranchAnd(bool branch, BinaryExpression node, Label label)
{
// if (left) then
// if (right) branch label
// endif
Label endif = _ilg.DefineLabel();
EmitExpressionAndBranch(!branch, node.Left, endif);
EmitExpressionAndBranch(branch, node.Right, label);
_ilg.MarkLabel(endif);
}
// Generates optimized OrElse with branch == true
// or optimized AndAlso with branch == false
private void EmitBranchOr(bool branch, BinaryExpression node, Label label)
{
// if (left OR right) branch label
EmitExpressionAndBranch(branch, node.Left, label);
EmitExpressionAndBranch(branch, node.Right, label);
}
private void EmitBranchBlock(bool branch, BlockExpression node, Label label)
{
EnterScope(node);
int count = node.ExpressionCount;
for (int i = 0; i < count - 1; i++)
{
EmitExpressionAsVoid(node.GetExpression(i));
}
EmitExpressionAndBranch(branch, node.GetExpression(count - 1), label);
ExitScope(node);
}
#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 Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.UnitTests;
using Xunit;
namespace System.Runtime.Analyzers.UnitTests
{
public class SpecifyCultureInfoTests : DiagnosticAnalyzerTestBase
{
protected override DiagnosticAnalyzer GetBasicDiagnosticAnalyzer()
{
return new SpecifyCultureInfoAnalyzer();
}
protected override DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer()
{
return new SpecifyCultureInfoAnalyzer();
}
[Fact]
public void CA1304_PlainString_CSharp()
{
VerifyCSharp(@"
using System;
using System.Globalization;
public class CultureInfoTestClass0
{
public string SpecifyCultureInfo01()
{
return ""foo"".ToLower();
}
}",
GetCSharpResultAt(9, 16, SpecifyCultureInfoAnalyzer.Rule, "string.ToLower()", "CultureInfoTestClass0.SpecifyCultureInfo01()", "string.ToLower(CultureInfo)"));
}
[Fact]
public void CA1304_VariableStringInsideDifferentContainingSymbols_CSharp()
{
VerifyCSharp(@"
using System;
using System.Globalization;
public class CultureInfoTestClass1
{
public string LowercaseAString(string name)
{
return name.ToLower();
}
public string InsideALambda(string insideLambda)
{
Func<string> ddd = () =>
{
return insideLambda.ToLower();
};
return null;
}
public string PropertyWithALambda
{
get
{
Func<string> ddd = () =>
{
return ""InsideGetter"".ToLower();
};
return null;
}
}
}
",
GetCSharpResultAt(9, 16, SpecifyCultureInfoAnalyzer.Rule, "string.ToLower()", "CultureInfoTestClass1.LowercaseAString(string)", "string.ToLower(CultureInfo)"),
GetCSharpResultAt(16, 20, SpecifyCultureInfoAnalyzer.Rule, "string.ToLower()", "CultureInfoTestClass1.InsideALambda(string)", "string.ToLower(CultureInfo)"),
GetCSharpResultAt(28, 24, SpecifyCultureInfoAnalyzer.Rule, "string.ToLower()", "CultureInfoTestClass1.PropertyWithALambda.get", "string.ToLower(CultureInfo)"));
}
[Fact]
public void CA1304_MethodOverloadHasCultureInfoAsFirstArgument_CSharp()
{
VerifyCSharp(@"
using System;
using System.Globalization;
public class CultureInfoTestClass2
{
public static void Method()
{
MethodOverloadHasCultureInfoAsFirstArgument(""Foo"");
}
public static void MethodOverloadHasCultureInfoAsFirstArgument(string format)
{
MethodOverloadHasCultureInfoAsFirstArgument(CultureInfo.CurrentCulture, format);
}
public static void MethodOverloadHasCultureInfoAsFirstArgument(CultureInfo provider, string format)
{
Console.WriteLine(string.Format(provider, format));
}
}",
GetCSharpResultAt(9, 9, SpecifyCultureInfoAnalyzer.Rule, "CultureInfoTestClass2.MethodOverloadHasCultureInfoAsFirstArgument(string)", "CultureInfoTestClass2.Method()", "CultureInfoTestClass2.MethodOverloadHasCultureInfoAsFirstArgument(CultureInfo, string)"));
}
[Fact]
public void CA1304_MethodOverloadHasCultureInfoAsLastArgument_CSharp()
{
VerifyCSharp(@"
using System;
using System.Globalization;
public class CultureInfoTestClass2
{
public static void Method()
{
MethodOverloadHasCultureInfoAsLastArgument(""Foo"");
}
public static void MethodOverloadHasCultureInfoAsLastArgument(string format)
{
MethodOverloadHasCultureInfoAsLastArgument(format, CultureInfo.CurrentCulture);
}
public static void MethodOverloadHasCultureInfoAsLastArgument(string format, CultureInfo provider)
{
Console.WriteLine(string.Format(provider, format));
}
public static void MethodOverloadHasCultureInfoAsLastArgument(CultureInfo provider, string format)
{
Console.WriteLine(string.Format(provider, format));
}
}",
GetCSharpResultAt(9, 9, SpecifyCultureInfoAnalyzer.Rule, "CultureInfoTestClass2.MethodOverloadHasCultureInfoAsLastArgument(string)", "CultureInfoTestClass2.Method()", "CultureInfoTestClass2.MethodOverloadHasCultureInfoAsLastArgument(string, CultureInfo)"));
}
[Fact]
public void CA1304_MethodOverloadHasJustCultureInfo_CSharp()
{
VerifyCSharp(@"
using System;
using System.Globalization;
public class CultureInfoTestClass2
{
public static void Method()
{
MethodOverloadHasJustCultureInfo();
}
public static void MethodOverloadHasJustCultureInfo()
{
MethodOverloadHasJustCultureInfo(CultureInfo.CurrentCulture);
}
public static void MethodOverloadHasJustCultureInfo(CultureInfo provider)
{
Console.WriteLine(string.Format(provider, """"));
}
}",
GetCSharpResultAt(9, 9, SpecifyCultureInfoAnalyzer.Rule, "CultureInfoTestClass2.MethodOverloadHasJustCultureInfo()", "CultureInfoTestClass2.Method()", "CultureInfoTestClass2.MethodOverloadHasJustCultureInfo(CultureInfo)"));
}
[Fact]
public void CA1304_TargetMethodIsGenericsAndNonGenerics_CSharp()
{
VerifyCSharp(@"
using System;
using System.Globalization;
public class CultureInfoTestClass2
{
public static void Method()
{
TargetMethodIsNonGenerics();
TargetMethodIsGenerics<int>(); // No Diagnostics
}
public static void TargetMethodIsNonGenerics()
{
}
public static void TargetMethodIsNonGenerics<T>(CultureInfo provider)
{
}
public static void TargetMethodIsGenerics<V>()
{
}
public static void TargetMethodIsGenerics(CultureInfo provider)
{
}
}",
GetCSharpResultAt(9, 9, SpecifyCultureInfoAnalyzer.Rule, "CultureInfoTestClass2.TargetMethodIsNonGenerics()", "CultureInfoTestClass2.Method()", "CultureInfoTestClass2.TargetMethodIsNonGenerics<T>(CultureInfo)"));
}
[Fact]
public void CA1304_MethodOverloadIncludeNonCandidates_CSharp()
{
VerifyCSharp(@"
using System;
using System.Globalization;
public class CultureInfoTestClass2
{
public static void Method()
{
MethodOverloadCount3();
}
public static void MethodOverloadCount3()
{
MethodOverloadCount3(CultureInfo.CurrentCulture);
}
public static void MethodOverloadCount3(CultureInfo provider)
{
Console.WriteLine(string.Format(provider, """"));
}
public static void MethodOverloadCount3(string b)
{
}
}",
GetCSharpResultAt(9, 9, SpecifyCultureInfoAnalyzer.Rule, "CultureInfoTestClass2.MethodOverloadCount3()", "CultureInfoTestClass2.Method()", "CultureInfoTestClass2.MethodOverloadCount3(CultureInfo)"));
}
[Fact]
public void CA1304_MethodOverloadWithJustCultureInfoAsExtraParameter_CSharp()
{
VerifyCSharp(@"
using System;
using System.Globalization;
public class CultureInfoTestClass2
{
public static void Method()
{
MethodOverloadWithJustCultureInfoAsExtraParameter(2, 3);
}
public static void MethodOverloadWithJustCultureInfoAsExtraParameter(int a, int b)
{
MethodOverloadWithJustCultureInfoAsExtraParameter(a, b, CultureInfo.CurrentCulture);
}
public static void MethodOverloadWithJustCultureInfoAsExtraParameter(int a, int b, CultureInfo provider)
{
Console.WriteLine(string.Format(provider, """"));
}
}",
GetCSharpResultAt(9, 9, SpecifyCultureInfoAnalyzer.Rule, "CultureInfoTestClass2.MethodOverloadWithJustCultureInfoAsExtraParameter(int, int)", "CultureInfoTestClass2.Method()", "CultureInfoTestClass2.MethodOverloadWithJustCultureInfoAsExtraParameter(int, int, CultureInfo)"));
}
[Fact]
public void CA1304_NoDiagnostics_CSharp()
{
VerifyCSharp(@"
using System;
using System.Globalization;
public class CultureInfoTestClass2
{
public static void Method()
{
// No Diag - Inherited CultureInfo
MethodOverloadHasInheritedCultureInfo(""Foo"");
// No Diag - Since the overload has more parameters apart from CultureInfo
MethodOverloadHasMoreThanCultureInfo(""Foo"");
// No Diag - Since the CultureInfo parameter is neither as the first parameter nor as the last parameter
MethodOverloadWithJustCultureInfoAsInbetweenParameter("""", """");
}
public static void MethodOverloadHasInheritedCultureInfo(string format)
{
MethodOverloadHasInheritedCultureInfo(new DerivedCultureInfo(""""), format);
}
public static void MethodOverloadHasInheritedCultureInfo(DerivedCultureInfo provider, string format)
{
Console.WriteLine(string.Format(provider, format));
}
public static void MethodOverloadHasMoreThanCultureInfo(string format)
{
MethodOverloadHasMoreThanCultureInfo(format, null, CultureInfo.CurrentCulture);
}
public static void MethodOverloadHasMoreThanCultureInfo(string format, string what, CultureInfo provider)
{
Console.WriteLine(string.Format(provider, format));
}
public static void MethodOverloadWithJustCultureInfoAsInbetweenParameter(string a, string b)
{
MethodOverloadWithJustCultureInfoAsInbetweenParameter(a, CultureInfo.CurrentCulture, b);
}
public static void MethodOverloadWithJustCultureInfoAsInbetweenParameter(string a, CultureInfo provider, string b)
{
Console.WriteLine(string.Format(provider, """"));
}
}
public class DerivedCultureInfo : CultureInfo
{
public DerivedCultureInfo(string name):
base(name)
{
}
}");
}
[Fact]
public void CA1304_PlainString_VisualBasic()
{
VerifyBasic(@"
Imports System
Imports System.Globalization
Public Class CultureInfoTestClass0
Public Function SpecifyCultureInfo01() As String
Return ""foo"".ToLower()
End Function
End Class",
GetBasicResultAt(7, 16, SpecifyCultureInfoAnalyzer.Rule, "String.ToLower()", "CultureInfoTestClass0.SpecifyCultureInfo01()", "String.ToLower(CultureInfo)"));
}
[Fact]
public void CA1304_VariableStringInsideDifferentContainingSymbols_VisualBasic()
{
VerifyBasic(@"
Imports System
Imports System.Globalization
Public Class CultureInfoTestClass1
Public Function LowercaseAString(name As String) As String
Return name.ToLower()
End Function
Public Function InsideALambda(insideLambda As String) As String
Dim ddd As Func(Of String) = Function()
Return insideLambda.ToLower()
End Function
Return Nothing
End Function
Public ReadOnly Property PropertyWithALambda() As String
Get
Dim ddd As Func(Of String) = Function()
Return ""InsideGetter"".ToLower()
End Function
Return Nothing
End Get
End Property
End Class",
GetBasicResultAt(7, 16, SpecifyCultureInfoAnalyzer.Rule, "String.ToLower()", "CultureInfoTestClass1.LowercaseAString(String)", "String.ToLower(CultureInfo)"),
GetBasicResultAt(12, 48, SpecifyCultureInfoAnalyzer.Rule, "String.ToLower()", "CultureInfoTestClass1.InsideALambda(String)", "String.ToLower(CultureInfo)"),
GetBasicResultAt(21, 52, SpecifyCultureInfoAnalyzer.Rule, "String.ToLower()", "CultureInfoTestClass1.PropertyWithALambda()", "String.ToLower(CultureInfo)"));
}
[Fact]
public void CA1304_MethodOverloadHasCultureInfoAsFirstArgument_VisualBasic()
{
VerifyBasic(@"
Imports System
Imports System.Globalization
Public Class CultureInfoTestClass2
Public Shared Sub Method()
MethodOverloadHasCultureInfoAsFirstArgument(""Foo"")
End Sub
Public Shared Sub MethodOverloadHasCultureInfoAsFirstArgument(format As String)
MethodOverloadHasCultureInfoAsFirstArgument(CultureInfo.CurrentCulture, format)
End Sub
Public Shared Sub MethodOverloadHasCultureInfoAsFirstArgument(provider As CultureInfo, format As String)
Console.WriteLine(String.Format(provider, format))
End Sub
End Class",
GetBasicResultAt(7, 9, SpecifyCultureInfoAnalyzer.Rule, "CultureInfoTestClass2.MethodOverloadHasCultureInfoAsFirstArgument(String)", "CultureInfoTestClass2.Method()", "CultureInfoTestClass2.MethodOverloadHasCultureInfoAsFirstArgument(CultureInfo, String)"));
}
[Fact]
public void CA1304_MethodOverloadHasCultureInfoAsLastArgument_VisualBasic()
{
VerifyBasic(@"
Imports System
Imports System.Globalization
Public Class CultureInfoTestClass2
Public Shared Sub Method()
MethodOverloadHasCultureInfoAsLastArgument(""Foo"")
End Sub
Public Shared Sub MethodOverloadHasCultureInfoAsLastArgument(format As String)
MethodOverloadHasCultureInfoAsLastArgument(format, CultureInfo.CurrentCulture)
End Sub
Public Shared Sub MethodOverloadHasCultureInfoAsLastArgument(format As String, provider As CultureInfo)
Console.WriteLine(String.Format(provider, format))
End Sub
Public Shared Sub MethodOverloadHasCultureInfoAsLastArgument(provider As CultureInfo, format As String)
Console.WriteLine(String.Format(provider, format))
End Sub
End Class",
GetBasicResultAt(7, 9, SpecifyCultureInfoAnalyzer.Rule, "CultureInfoTestClass2.MethodOverloadHasCultureInfoAsLastArgument(String)", "CultureInfoTestClass2.Method()", "CultureInfoTestClass2.MethodOverloadHasCultureInfoAsLastArgument(String, CultureInfo)"));
}
[Fact]
public void CA1304_MethodOverloadHasJustCultureInfo_VisualBasic()
{
VerifyBasic(@"
Imports System
Imports System.Globalization
Public Class CultureInfoTestClass2
Public Shared Sub Method()
MethodOverloadHasJustCultureInfo()
End Sub
Public Shared Sub MethodOverloadHasJustCultureInfo()
MethodOverloadHasJustCultureInfo(CultureInfo.CurrentCulture)
End Sub
Public Shared Sub MethodOverloadHasJustCultureInfo(provider As CultureInfo)
Console.WriteLine(String.Format(provider, """"))
End Sub
End Class",
GetBasicResultAt(7, 9, SpecifyCultureInfoAnalyzer.Rule, "CultureInfoTestClass2.MethodOverloadHasJustCultureInfo()", "CultureInfoTestClass2.Method()", "CultureInfoTestClass2.MethodOverloadHasJustCultureInfo(CultureInfo)"));
}
[Fact]
public void CA1304_MethodOverloadIncludeNonCandidates_VisualBasic()
{
VerifyBasic(@"
Imports System
Imports System.Globalization
Public Class CultureInfoTestClass2
Public Shared Sub Method()
MethodOverloadCount3()
End Sub
Public Shared Sub MethodOverloadCount3()
MethodOverloadCount3(CultureInfo.CurrentCulture)
End Sub
Public Shared Sub MethodOverloadCount3(provider As CultureInfo)
Console.WriteLine(String.Format(provider, """"))
End Sub
Public Shared Sub MethodOverloadCount3(b As String)
End Sub
End Class",
GetBasicResultAt(7, 9, SpecifyCultureInfoAnalyzer.Rule, "CultureInfoTestClass2.MethodOverloadCount3()", "CultureInfoTestClass2.Method()", "CultureInfoTestClass2.MethodOverloadCount3(CultureInfo)"));
}
[Fact]
public void CA1304_MethodOverloadWithJustCultureInfoAsExtraParameter_VisualBasic()
{
VerifyBasic(@"
Imports System
Imports System.Globalization
Public Class CultureInfoTestClass2
Public Shared Sub Method()
MethodOverloadWithJustCultureInfoAsExtraParameter(2, 3)
End Sub
Public Shared Sub MethodOverloadWithJustCultureInfoAsExtraParameter(a As Integer, b As Integer)
MethodOverloadWithJustCultureInfoAsExtraParameter(a, b, CultureInfo.CurrentCulture)
End Sub
Public Shared Sub MethodOverloadWithJustCultureInfoAsExtraParameter(a As Integer, b As Integer, provider As CultureInfo)
Console.WriteLine(String.Format(provider, """"))
End Sub
End Class",
GetBasicResultAt(7, 9, SpecifyCultureInfoAnalyzer.Rule, "CultureInfoTestClass2.MethodOverloadWithJustCultureInfoAsExtraParameter(Integer, Integer)", "CultureInfoTestClass2.Method()", "CultureInfoTestClass2.MethodOverloadWithJustCultureInfoAsExtraParameter(Integer, Integer, CultureInfo)"));
}
[Fact]
public void CA1304_NoDiagnostics_VisualBasic()
{
VerifyBasic(@"
Imports System
Imports System.Globalization
Public Class CultureInfoTestClass2
Public Shared Sub Method()
' No Diag - Inherited CultureInfo
MethodOverloadHasInheritedCultureInfo(""Foo"")
' No Diag - There are more parameters apart from CultureInfo
MethodOverloadHasMoreThanCultureInfo(""Foo"")
' No Diag - The CultureInfo parameter is neither the first parameter nor the last parameter
MethodOverloadWithJustCultureInfoAsInbetweenParameter("""", """")
End Sub
Public Shared Sub MethodOverloadHasInheritedCultureInfo(format As String)
MethodOverloadHasInheritedCultureInfo(New DerivedCultureInfo(""""), format)
End Sub
Public Shared Sub MethodOverloadHasInheritedCultureInfo(provider As DerivedCultureInfo, format As String)
Console.WriteLine(String.Format(provider, format))
End Sub
Public Shared Sub MethodOverloadHasMoreThanCultureInfo(format As String)
MethodOverloadHasMoreThanCultureInfo(format, Nothing, CultureInfo.CurrentCulture)
End Sub
Public Shared Sub MethodOverloadHasMoreThanCultureInfo(format As String, what As String, provider As CultureInfo)
Console.WriteLine(String.Format(provider, format))
End Sub
Public Shared Sub MethodOverloadWithJustCultureInfoAsInbetweenParameter(a As String, b As String)
MethodOverloadWithJustCultureInfoAsInbetweenParameter(a, CultureInfo.CurrentCulture, b)
End Sub
Public Shared Sub MethodOverloadWithJustCultureInfoAsInbetweenParameter(a As String, provider As CultureInfo, b As String)
Console.WriteLine(String.Format(provider, """"))
End Sub
End Class
Public Class DerivedCultureInfo
Inherits CultureInfo
Public Sub New(name As String)
MyBase.New(name)
End Sub
End Class");
}
}
}
| |
using Signum.Entities.Workflow;
using System.Xml.Linq;
namespace Signum.Engine.Workflow;
public partial class WorkflowBuilder
{
internal partial class LaneBuilder
{
public XmlEntity<WorkflowLaneEntity> lane;
private Dictionary<string, XmlEntity<WorkflowEventEntity>> events;
private Dictionary<string, XmlEntity<WorkflowActivityEntity>> activities;
private Dictionary<string, XmlEntity<WorkflowGatewayEntity>> gateways;
private Dictionary<string, XmlEntity<WorkflowConnectionEntity>> connections;
private Dictionary<Lite<IWorkflowNodeEntity>, List<XmlEntity<WorkflowConnectionEntity>>> incoming;
private Dictionary<Lite<IWorkflowNodeEntity>, List<XmlEntity<WorkflowConnectionEntity>>> outgoing;
public LaneBuilder(WorkflowLaneEntity l,
IEnumerable<WorkflowActivityEntity> activities,
IEnumerable<WorkflowEventEntity> events,
IEnumerable<WorkflowGatewayEntity> gateways,
IEnumerable<XmlEntity<WorkflowConnectionEntity>> connections)
{
this.lane = new XmlEntity<WorkflowLaneEntity>(l);
this.events = events.Select(a => new XmlEntity<WorkflowEventEntity>(a)).ToDictionary(x => x.bpmnElementId);
this.activities = activities.Select(a => new XmlEntity<WorkflowActivityEntity>(a)).ToDictionary(x => x.bpmnElementId);
this.gateways = gateways.Select(a => new XmlEntity<WorkflowGatewayEntity>(a)).ToDictionary(x => x.bpmnElementId);
this.connections = connections.ToDictionary(a => a.bpmnElementId);
this.outgoing = this.connections.Values.GroupToDictionary(a => a.Entity.From.ToLite());
this.incoming = this.connections.Values.GroupToDictionary(a => a.Entity.To.ToLite());
}
public void ApplyChanges(XElement processElement, XElement laneElement, Locator locator)
{
var laneIds = laneElement.Elements(bpmn + "flowNodeRef").Select(a => a.Value).ToHashSet();
var laneElements = processElement.Elements().Where(a => laneIds.Contains(a.Attribute("id")?.Value!));
var events = laneElements.Where(a => WorkflowEventTypes.Where(kvp => !kvp.Key.IsBoundaryTimer()).ToDictionary().Values.Contains(a.Name.LocalName)).ToDictionary(a => a.Attribute("id")!.Value);
var oldEvents = this.events.Values.Where(a => a.Entity.BoundaryOf == null).ToDictionaryEx(a => a.bpmnElementId, "events");
Synchronizer.Synchronize(events, oldEvents,
(id, e) =>
{
var already = (WorkflowEventEntity?)locator.FindEntity(id);
if (already != null)
{
locator.FindLane(already.Lane).events.Remove(id);
already.Lane = this.lane.Entity;
}
var we = (already ?? new WorkflowEventEntity { Xml = new WorkflowXmlEmbedded(), Lane = this.lane.Entity }).ApplyXml(e, locator);
this.events.Add(id, new XmlEntity<WorkflowEventEntity>(we));
},
(id, oe) =>
{
if (!locator.ExistDiagram(id))
{
this.events.Remove(id);
if (oe.Entity.Type == WorkflowEventType.IntermediateTimer)
MoveCasesAndDelete(oe.Entity, locator);
else
oe.Entity.Delete(WorkflowEventOperation.Delete);
};
},
(id, e, oe) =>
{
var we = oe.Entity.ApplyXml(e, locator);
});
var activities = laneElements.Where(a => WorkflowActivityTypes.Values.Contains(a.Name.LocalName)).ToDictionary(a => a.Attribute("id")!.Value);
var oldActivities = this.activities.Values.ToDictionaryEx(a => a.bpmnElementId, "activities");
Synchronizer.Synchronize(activities, oldActivities,
(id, a) =>
{
var already = (WorkflowActivityEntity?)locator.FindEntity(id);
if (already != null)
{
locator.FindLane(already.Lane).activities.Remove(id);
already.Lane = this.lane.Entity;
}
var wa = (already ?? new WorkflowActivityEntity { Xml = new WorkflowXmlEmbedded(), Lane = this.lane.Entity }).ApplyXml(a, locator, this.events);
this.activities.Add(id, new XmlEntity<WorkflowActivityEntity>(wa));
},
(id, oa) =>
{
if (!locator.ExistDiagram(id))
{
this.activities.Remove(id);
MoveCasesAndDelete(oa.Entity, locator);
};
},
(id, a, oa) =>
{
var we = oa.Entity.ApplyXml(a, locator, this.events);
});
var gateways = laneElements
.Where(a => WorkflowGatewayTypes.Values.Contains(a.Name.LocalName))
.ToDictionary(a => a.Attribute("id")!.Value);
var oldGateways = this.gateways.Values.ToDictionaryEx(a => a.bpmnElementId, "gateways");
Synchronizer.Synchronize(gateways, oldGateways,
(id, g) =>
{
var already = (WorkflowGatewayEntity?)locator.FindEntity(id);
if (already != null)
{
locator.FindLane(already.Lane).gateways.Remove(id);
already.Lane = this.lane.Entity;
}
var wg = (already ?? new WorkflowGatewayEntity { Xml = new WorkflowXmlEmbedded(), Lane = this.lane.Entity }).ApplyXml(g, locator);
this.gateways.Add(id, new XmlEntity<WorkflowGatewayEntity>(wg));
},
(id, og) =>
{
if (!locator.ExistDiagram(id))
{
this.gateways.Remove(id);
og.Entity.Delete(WorkflowGatewayOperation.Delete);
};
},
(id, g, og) =>
{
var we = og.Entity.ApplyXml(g, locator);
});
}
public IWorkflowNodeEntity? FindEntity(string bpmElementId)
{
return this.events.TryGetC(bpmElementId)?.Entity ??
this.activities.TryGetC(bpmElementId)?.Entity ??
(IWorkflowNodeEntity?)this.gateways.TryGetC(bpmElementId)?.Entity;
}
internal IEnumerable<XmlEntity<WorkflowEventEntity>> GetEvents()
{
return this.events.Values;
}
internal IEnumerable<XmlEntity<WorkflowActivityEntity>> GetActivities()
{
return this.activities.Values;
}
internal IEnumerable<XmlEntity<WorkflowGatewayEntity>> GetGateways()
{
return this.gateways.Values;
}
internal IEnumerable<XmlEntity<WorkflowConnectionEntity>> GetConnections()
{
return this.connections.Values;
}
internal bool IsEmpty()
{
return (!this.GetActivities().Any() && !this.GetEvents().Any() && !this.GetGateways().Any());
}
internal string GetBpmnElementId(IWorkflowNodeEntity node)
{
return (node is WorkflowEventEntity) ? events.Values.Single(a => a.Entity.Is(node)).bpmnElementId :
(node is WorkflowActivityEntity) ? activities.Values.Single(a => a.Entity.Is(node)).bpmnElementId :
(node is WorkflowGatewayEntity) ? gateways.Values.Single(a => a.Entity.Is(node)).bpmnElementId :
throw new InvalidOperationException(WorkflowValidationMessage.NodeType0WithId1IsInvalid.NiceToString(node.GetType().NiceName(), node.Id.ToString()));
}
internal XElement GetLaneSetElement()
{
return new XElement(bpmn + "lane",
new XAttribute("id", lane.bpmnElementId),
new XAttribute("name", lane.Entity.Name),
events.Values.Select(e => GetLaneFlowNodeRefElement(e.bpmnElementId)),
activities.Values.Select(e => GetLaneFlowNodeRefElement(e.bpmnElementId)),
gateways.Values.Select(e => GetLaneFlowNodeRefElement(e.bpmnElementId)));
}
private XElement GetLaneFlowNodeRefElement(string bpmnElementId)
{
return new XElement(bpmn + "flowNodeRef", bpmnElementId);
}
internal List<XElement> GetNodesElement()
{
return events.Values.Select(e => GetEventProcessElement(e))
.Concat(activities.Values.Select(e => GetActivityProcessElement(e)))
.Concat(gateways.Values.Select(e => GetGatewayProcessElement(e))).ToList();
}
internal List<XElement> GetDiagramElement()
{
List<XElement> res = new List<XElement>();
res.Add(lane.Element);
res.AddRange(events.Values.Select(a => a.Element)
.Concat(activities.Values.Select(a => a.Element))
.Concat(gateways.Values.Select(a => a.Element)));
return res;
}
public static Dictionary<WorkflowEventType, string> WorkflowEventTypes = new Dictionary<WorkflowEventType, string>()
{
{ WorkflowEventType.Start, "startEvent" },
{ WorkflowEventType.ScheduledStart, "startEvent" },
{ WorkflowEventType.Finish, "endEvent" },
{ WorkflowEventType.BoundaryForkTimer, "boundaryEvent" },
{ WorkflowEventType.BoundaryInterruptingTimer, "boundaryEvent" },
{ WorkflowEventType.IntermediateTimer, "intermediateCatchEvent" },
};
public static Dictionary<WorkflowActivityType, string> WorkflowActivityTypes = new Dictionary<WorkflowActivityType, string>()
{
{ WorkflowActivityType.Task, "task" },
{ WorkflowActivityType.Decision, "userTask" },
{ WorkflowActivityType.CallWorkflow, "callActivity" },
{ WorkflowActivityType.DecompositionWorkflow, "callActivity" },
{ WorkflowActivityType.Script, "scriptTask" },
};
public static Dictionary<WorkflowGatewayType, string> WorkflowGatewayTypes = new Dictionary<WorkflowGatewayType, string>()
{
{ WorkflowGatewayType.Inclusive, "inclusiveGateway" },
{ WorkflowGatewayType.Parallel, "parallelGateway" },
{ WorkflowGatewayType.Exclusive, "exclusiveGateway" },
};
private XElement GetEventProcessElement(XmlEntity<WorkflowEventEntity> e)
{
var activity = e.Entity.BoundaryOf?.Let(lite => this.activities.Values.SingleEx(a => lite.Is(a.Entity))).Entity;
return new XElement(bpmn + WorkflowEventTypes.GetOrThrow(e.Entity.Type),
new XAttribute("id", e.bpmnElementId),
activity != null ? new XAttribute("attachedToRef", activity.BpmnElementId) : null!,
e.Entity.Type == WorkflowEventType.BoundaryForkTimer ? new XAttribute("cancelActivity", false) : null!,
e.Entity.Name.HasText() ? new XAttribute("name", e.Entity.Name) : null!,
e.Entity.Type.IsScheduledStart() || e.Entity.Type.IsTimer() ?
new XElement(bpmn + ((((WorkflowEventModel)e.Entity.GetModel()).Task?.TriggeredOn == TriggeredOn.Always || (e.Entity.Type.IsTimer() && e.Entity.Timer!.Duration != null)) ?
"timerEventDefinition" : "conditionalEventDefinition")) : null!,
GetConnections(e.Entity.ToLite()));
}
private XElement GetActivityProcessElement(XmlEntity<WorkflowActivityEntity> a)
{
return new XElement(bpmn + WorkflowActivityTypes.GetOrThrow(a.Entity.Type),
new XAttribute("id", a.bpmnElementId),
new XAttribute("name", a.Entity.Name),
GetConnections(a.Entity.ToLite()));
}
private XElement GetGatewayProcessElement(XmlEntity<WorkflowGatewayEntity> g)
{
return new XElement(bpmn + WorkflowGatewayTypes.GetOrThrow(g.Entity.Type),
new XAttribute("id", g.bpmnElementId),
g.Entity.Name.HasText() ? new XAttribute("name", g.Entity.Name) : null!,
GetConnections(g.Entity.ToLite()));
}
private IEnumerable<XElement> GetConnections(Lite<IWorkflowNodeEntity> lite)
{
List<XElement> result = new List<XElement>();
result.AddRange(incoming.TryGetC(lite).EmptyIfNull().Select(c => new XElement(bpmn + "incoming", c.bpmnElementId)));
result.AddRange(outgoing.TryGetC(lite).EmptyIfNull().Select(c => new XElement(bpmn + "outgoing", c.bpmnElementId)));
return result;
}
internal void DeleteAll(Locator? locator)
{
foreach (var e in events.Values.Select(a => a.Entity))
{
if (e.Type == WorkflowEventType.IntermediateTimer)
{
if (locator != null)
MoveCasesAndDelete(e, locator);
else
{
DeleteCaseActivities(e, c => true);
e.Delete(WorkflowEventOperation.Delete);
}
}
else
e.Delete(WorkflowEventOperation.Delete);
}
foreach (var g in gateways.Values.Select(a => a.Entity))
{
g.Delete(WorkflowGatewayOperation.Delete);
}
foreach (var ac in activities.Values.Select(a => a.Entity))
{
if (locator != null)
MoveCasesAndDelete(ac, locator);
else
{
DeleteCaseActivities(ac, c => true);
ac.Delete(WorkflowActivityOperation.Delete);
}
}
this.lane.Entity.Delete(WorkflowLaneOperation.Delete);
}
internal void DeleteCaseActivities(Expression<Func<CaseEntity, bool>> filter)
{
foreach (var ac in activities.Values.Select(a => a.Entity))
DeleteCaseActivities(ac, filter);
}
private static void DeleteCaseActivities(IWorkflowNodeEntity node, Expression<Func<CaseEntity, bool>> filter)
{
if (node is WorkflowActivityEntity wa && (wa.Type == WorkflowActivityType.DecompositionWorkflow || wa.Type == WorkflowActivityType.CallWorkflow))
{
var sw = wa.SubWorkflow!.Workflow;
var wb = new WorkflowBuilder(sw);
wb.DeleteCases(c => filter.Evaluate(c.ParentCase!.Entity) && c.ParentCase.Entity!.Workflow.Is(wa.Lane.Pool.Workflow));
}
var caseActivities = node.CaseActivities().Where(ca => filter.Evaluate(ca.Case));
if (caseActivities.Any())
{
caseActivities.SelectMany(a => a.Notifications()).UnsafeDelete();
Database.Query<CaseActivityEntity>()
.Where(ca => ca.Previous!.Entity.WorkflowActivity.Is(node) && filter.Evaluate(ca.Previous.Entity.Case))
.UnsafeUpdate()
.Set(ca => ca.Previous, ca => ca.Previous!.Entity.Previous)
.Execute();
var running = caseActivities.Where(a => a.State == CaseActivityState.Pending).ToList();
running.ForEach(a => {
if (a.Previous == null)
throw new ApplicationException(CaseActivityMessage.ImpossibleToDeleteCaseActivity0OnWorkflowActivity1BecauseHasNoPreviousActivity.NiceToString(a.Id, a.WorkflowActivity));
a.Previous.ExecuteLite(CaseActivityOperation.Undo);
});
caseActivities.UnsafeDelete();
}
}
private static void MoveCasesAndDelete(IWorkflowNodeEntity node, Locator? locator)
{
if (node.CaseActivities().Any())
{
if (locator!.HasReplacement(node.ToLite()))
{
var replacement = locator.GetReplacement(node.ToLite())!;
node.CaseActivities()
.Where(a => a.State == CaseActivityState.Done)
.UnsafeUpdate()
.Set(ca => ca.WorkflowActivity, ca => replacement)
.Execute();
var running = node.CaseActivities().Where(a => a.State == CaseActivityState.Pending).ToList();
running.ForEach(a =>
{
a.Notifications().UnsafeDelete();
a.WorkflowActivity = replacement;
a.Save();
CaseActivityLogic.InsertCaseActivityNotifications(a);
});
}
else
{
DeleteCaseActivities(node, a => true);
}
}
if (node is WorkflowActivityEntity wa)
wa.Delete(WorkflowActivityOperation.Delete);
else
((WorkflowEventEntity)node).Delete(WorkflowEventOperation.Delete);
}
internal void Clone(WorkflowPoolEntity pool, Dictionary<IWorkflowNodeEntity, IWorkflowNodeEntity> nodes)
{
var oldLane = this.lane.Entity;
WorkflowLaneEntity newLane = new WorkflowLaneEntity
{
Pool = pool,
Name = oldLane.Name,
BpmnElementId = oldLane.BpmnElementId,
Actors = oldLane.Actors.ToMList(),
ActorsEval = oldLane.ActorsEval?.Clone(),
Xml = oldLane.Xml,
}.Save();
var newEvents = this.events.Values.Select(e => e.Entity).ToDictionary(e => e, e => new WorkflowEventEntity
{
Lane = newLane,
Name = e.Name,
BpmnElementId = e.BpmnElementId,
Timer = e.Timer?.Clone(),
Type = e.Type,
Xml = e.Xml,
});
newEvents.Values.SaveList();
nodes.AddRange(newEvents.ToDictionary(kvp => (IWorkflowNodeEntity)kvp.Key, kvp => (IWorkflowNodeEntity)kvp.Value));
var newActivities = this.activities.Values.Select(a => a.Entity).ToDictionary(a => a, a =>
{
var na = new WorkflowActivityEntity
{
Lane = newLane,
Name = a.Name,
BpmnElementId = a.BpmnElementId,
Xml = a.Xml,
Type = a.Type,
ViewName = a.ViewName,
ViewNameProps = a.ViewNameProps.Select(p=> new ViewNamePropEmbedded
{
Name = p.Name,
Expression = p.Expression
}).ToMList(),
RequiresOpen = a.RequiresOpen,
EstimatedDuration = a.EstimatedDuration,
Script = a.Script?.Clone(),
SubWorkflow = a.SubWorkflow?.Clone(),
UserHelp = a.UserHelp,
Comments = a.Comments,
};
na.BoundaryTimers = a.BoundaryTimers.Select(t => newEvents.GetOrThrow(t)).ToMList();
return na;
});
newActivities.Values.SaveList();
nodes.AddRange(newActivities.ToDictionary(kvp => (IWorkflowNodeEntity)kvp.Key, kvp => (IWorkflowNodeEntity)kvp.Value));
var newGateways = this.gateways.Values.Select(g => g.Entity).ToDictionary(g => g, g => new WorkflowGatewayEntity
{
Lane = newLane,
Name = g.Name,
BpmnElementId = g.BpmnElementId,
Type = g.Type,
Direction = g.Direction,
Xml = g.Xml,
});
newGateways.Values.SaveList();
nodes.AddRange(newGateways.ToDictionary(kvp => (IWorkflowNodeEntity)kvp.Key, kvp => (IWorkflowNodeEntity)kvp.Value));
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using MigAz.Azure.Core.ArmTemplate;
using MigAz.Azure.Core.Interface;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
namespace MigAz.Azure.Arm
{
public class VirtualNetwork : ArmResource, IVirtualNetwork, IMigrationVirtualNetwork
{
private List<VirtualNetworkGateway> ResourceTokenGateways = new List<VirtualNetworkGateway>();
private List<ISubnet> _Subnets = new List<ISubnet>();
private List<string> _AddressPrefixes = new List<string>();
private List<string> _DnsServers = new List<string>();
private VirtualNetwork() : base(null, null) { }
public VirtualNetwork(AzureSubscription azureSubscription, JToken resourceToken) : base(azureSubscription, resourceToken)
{
var subnets = from vnet in ResourceToken["properties"]["subnets"]
select vnet;
foreach (var subnet in subnets)
{
Subnet armSubnet = new Subnet(this, subnet);
_Subnets.Add(armSubnet);
}
var addressPrefixes = from vnet in ResourceToken["properties"]["addressSpace"]["addressPrefixes"]
select vnet;
foreach (var addressPrefix in addressPrefixes)
{
_AddressPrefixes.Add(addressPrefix.ToString());
}
if (ResourceToken["properties"] != null)
{
if (ResourceToken["properties"]["dhcpOptions"] != null)
{
if (ResourceToken["properties"]["dhcpOptions"]["dnsServers"] != null)
{
var dnsPrefixes = from vnet in ResourceToken["properties"]["dhcpOptions"]["dnsServers"]
select vnet;
foreach (var dnsPrefix in dnsPrefixes)
{
_DnsServers.Add(dnsPrefix.ToString());
}
}
}
}
}
public new async Task InitializeChildrenAsync()
{
await base.InitializeChildrenAsync();
foreach (Subnet subnet in this.Subnets)
{
await subnet.InitializeChildrenAsync();
}
}
#region Properties
public string Type => (string)ResourceToken["type"];
public ISubnet GatewaySubnet
{
get
{
foreach (Subnet subnet in this.Subnets)
{
if (subnet.Name == ArmConst.GatewaySubnetName)
return subnet;
}
return null;
}
}
public List<ISubnet> Subnets => _Subnets;
public List<string> AddressPrefixes => _AddressPrefixes;
public List<string> DnsServers => _DnsServers;
public List<VirtualNetworkGateway> VirtualNetworkGateways
{
get { return ResourceTokenGateways; }
}
#endregion
#region Methods
public override string ToString()
{
return this.Name;
}
public async Task<(bool isAvailable, List<String> availableIps)> IsIpAddressAvailable(string ipAddress)
{
//https://docs.microsoft.com/en-us/rest/api/virtualnetwork/virtualnetworks/checkipaddressavailability
const String CheckIPAddressAvailability = "CheckIPAddressAvailability";
bool isAvailable = false;
List<String> ipsAvailable = null;
this.AzureSubscription.LogProvider.WriteLog("IsIpAddressAvailable", "Start");
this.AzureSubscription.StatusProvider.UpdateStatus("BUSY: Checking if IP Address '" + ipAddress + "' is available in Azure Virtual Network '" + this.Name + "'.");
if (this.AzureSubscription.SubscriptionId == Guid.Empty)
{
return (true, null);
}
AzureContext azureContext = this.AzureSubscription.AzureTenant.AzureContext;
if (this.AzureSubscription.ExistsProviderResourceType(ArmConst.MicrosoftNetwork, "virtualNetworks"))
{
if (azureContext != null && azureContext.LogProvider != null)
azureContext.LogProvider.WriteLog("CheckNameAvailability", "Storage Account '" + this.ToString());
if (azureContext != null && azureContext.StatusProvider != null)
azureContext.StatusProvider.UpdateStatus("Checking Name Availabilty for target Storage Account '" + this.ToString() + "'");
// https://docs.microsoft.com/en-us/rest/api/storagerp/storageaccounts/checknameavailability
string url = this.AzureSubscription.ApiUrl + "subscriptions/" + this.AzureSubscription.SubscriptionId + "/resourceGroups/" + this.ResourceGroup.Name + ArmConst.ProviderVirtualNetwork + this.Name + "/" + CheckIPAddressAvailability + "?api-version=" + this.AzureSubscription.GetProviderMaxApiVersion(ArmConst.MicrosoftNetwork, "virtualNetworks") + "&ipAddress=" + ipAddress;
AuthenticationResult authenticationResult = await azureContext.TokenProvider.GetToken(azureContext.AzureEnvironment.ResourceManagerEndpoint, azureContext.AzureSubscription.AzureAdTenantId);
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authenticationResult.AccessToken);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.BaseAddress = new Uri(azureContext.AzureEnvironment.ResourceManagerEndpoint);
if (azureContext != null && azureContext.LogProvider != null)
azureContext.LogProvider.WriteLog("CheckNameAvailability", "Storage Account '" + this.ToString() + "' PostAsync " + url + "");
using (var response = await client.GetAsync(url))
{
String strResponse = response.Content.ReadAsStringAsync().Result.ToString();
JObject responseJson = JObject.Parse(strResponse);
isAvailable = (response.StatusCode == System.Net.HttpStatusCode.OK &&
responseJson != null &&
responseJson["available"] != null &&
String.Compare(responseJson["available"].ToString(), "True", true) == 0);
if (responseJson["availableIPAddresses"] != null)
{
ipsAvailable = new List<String>();
var ipAddressesJson = from ipAddressJson in responseJson["availableIPAddresses"]
select ipAddressJson;
foreach (String ipAddressJson in ipAddressesJson)
{
ipsAvailable.Add(ipAddressJson);
}
}
}
}
}
else
{
azureContext.LogProvider.WriteLog("CheckNameAvailability", "Provider Resource Type does not exist. Unable to check if storage account name is available.");
isAvailable = true;
}
if (azureContext != null && azureContext.StatusProvider != null)
azureContext.StatusProvider.UpdateStatus("Ready");
return (isAvailable, ipsAvailable);
}
#endregion
public bool HasNonGatewaySubnet
{
get
{
if ((this.Subnets.Count() == 0) ||
((this.Subnets.Count() == 1) && (this.Subnets[0].Name == ArmConst.GatewaySubnetName)))
return false;
return true;
}
}
public bool HasGatewaySubnet
{
get
{
return this.GatewaySubnet != null;
}
}
public static bool operator ==(VirtualNetwork lhs, VirtualNetwork rhs)
{
bool status = false;
if (((object)lhs == null && (object)rhs == null) ||
((object)lhs != null && (object)rhs != null && lhs.Id == rhs.Id))
{
status = true;
}
return status;
}
public static bool operator !=(VirtualNetwork lhs, VirtualNetwork rhs)
{
return !(lhs == rhs);
}
}
}
| |
/*
* Copyright (c) 2007-2008, Second Life Reverse Engineering Team
* 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 Second Life Reverse Engineering Team 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.Collections.Generic;
using System.Text;
using System.Threading;
using libsecondlife.StructuredData;
using libsecondlife.Capabilities;
namespace libsecondlife
{
/// <summary>
/// Capabilities is the name of the bi-directional HTTP REST protocol that
/// Second Life uses to communicate transactions such as teleporting or
/// group messaging
/// </summary>
public class Caps
{
/// <summary>
/// Triggered when an event is received via the EventQueueGet
/// capability
/// </summary>
/// <param name="message">Event name</param>
/// <param name="body">Decoded event data</param>
/// <param name="simulator">The simulator that generated the event</param>
public delegate void EventQueueCallback(string message, StructuredData.LLSD body, Simulator simulator);
/// <summary>Reference to the simulator this system is connected to</summary>
public Simulator Simulator;
internal string _SeedCapsURI;
internal Dictionary<string, Uri> _Caps = new Dictionary<string, Uri>();
private CapsClient _SeedRequest;
private EventQueueClient _EventQueueCap = null;
/// <summary>Capabilities URI this system was initialized with</summary>
public string SeedCapsURI { get { return _SeedCapsURI; } }
/// <summary>Whether the capabilities event queue is connected and
/// listening for incoming events</summary>
public bool IsEventQueueRunning
{
get
{
if (_EventQueueCap != null)
return _EventQueueCap.Running;
else
return false;
}
}
/// <summary>
/// Default constructor
/// </summary>
/// <param name="simulator"></param>
/// <param name="seedcaps"></param>
internal Caps(Simulator simulator, string seedcaps)
{
Simulator = simulator;
_SeedCapsURI = seedcaps;
MakeSeedRequest();
}
public void Disconnect(bool immediate)
{
Logger.Log(String.Format("Caps system for {0} is {1}", Simulator,
(immediate ? "aborting" : "disconnecting")), Helpers.LogLevel.Info, Simulator.Client);
if (_SeedRequest != null)
_SeedRequest.Cancel();
if (_EventQueueCap != null)
_EventQueueCap.Stop(immediate);
}
/// <summary>
/// Request the URI of a named capability
/// </summary>
/// <param name="capability">Name of the capability to request</param>
/// <returns>The URI of the requested capability, or String.Empty if
/// the capability does not exist</returns>
public Uri CapabilityURI(string capability)
{
Uri cap;
if (_Caps.TryGetValue(capability, out cap))
return cap;
else
return null;
}
private void MakeSeedRequest()
{
if (Simulator == null || !Simulator.Client.Network.Connected)
return;
// Create a request list
LLSDArray req = new LLSDArray();
req.Add("ChatSessionRequest");
req.Add("CopyInventoryFromNotecard");
req.Add("DispatchRegionInfo");
req.Add("EstateChangeInfo");
req.Add("EventQueueGet");
req.Add("FetchInventoryDescendents");
req.Add("GroupProposalBallot");
req.Add("MapLayer");
req.Add("MapLayerGod");
req.Add("NewFileAgentInventory");
req.Add("ParcelPropertiesUpdate");
req.Add("ParcelVoiceInfoRequest");
req.Add("ProvisionVoiceAccountRequest");
req.Add("RemoteParcelRequest");
req.Add("RequestTextureDownload");
req.Add("SearchStatRequest");
req.Add("SearchStatTracking");
req.Add("SendPostcard");
req.Add("SendUserReport");
req.Add("SendUserReportWithScreenshot");
req.Add("ServerReleaseNotes");
req.Add("StartGroupProposal");
req.Add("UpdateGestureAgentInventory");
req.Add("UpdateNotecardAgentInventory");
req.Add("UpdateScriptAgentInventory");
req.Add("UpdateGestureTaskInventory");
req.Add("UpdateNotecardTaskInventory");
req.Add("UpdateScriptTaskInventory");
req.Add("ViewerStartAuction");
req.Add("UntrustedSimulatorMessage");
req.Add("ViewerStats");
_SeedRequest = new CapsClient(new Uri(_SeedCapsURI));
_SeedRequest.OnComplete += new CapsClient.CompleteCallback(SeedRequestCompleteHandler);
_SeedRequest.StartRequest(req);
}
private void SeedRequestCompleteHandler(CapsClient client, LLSD result, Exception error)
{
if (result != null && result.Type == LLSDType.Map)
{
LLSDMap respTable = (LLSDMap)result;
StringBuilder capsList = new StringBuilder();
foreach (string cap in respTable.Keys)
{
capsList.Append(cap);
capsList.Append(' ');
_Caps[cap] = respTable[cap].AsUri();
}
Logger.DebugLog("Got capabilities: " + capsList.ToString(), Simulator.Client);
if (_Caps.ContainsKey("EventQueueGet"))
{
Logger.DebugLog("Starting event queue for " + Simulator.ToString(), Simulator.Client);
_EventQueueCap = new EventQueueClient(_Caps["EventQueueGet"]);
_EventQueueCap.OnConnected += new EventQueueClient.ConnectedCallback(EventQueueConnectedHandler);
_EventQueueCap.OnEvent += new EventQueueClient.EventCallback(EventQueueEventHandler);
_EventQueueCap.Start();
}
}
else
{
// The initial CAPS connection failed, try again
MakeSeedRequest();
}
}
private void EventQueueConnectedHandler()
{
Simulator.Client.Network.RaiseConnectedEvent(Simulator);
}
private void EventQueueEventHandler(string eventName, LLSDMap body)
{
if (Simulator.Client.Settings.SYNC_PACKETCALLBACKS)
Simulator.Client.Network.CapsEvents.RaiseEvent(eventName, body, Simulator);
else
Simulator.Client.Network.CapsEvents.BeginRaiseEvent(eventName, body, Simulator);
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Threading;
using log4net;
using OpenMetaverse;
using OpenMetaverse.Assets;
using OpenMetaverse.StructuredData;
using OpenSim.Framework;
using OpenSim.Region.Framework.Scenes.Serialization;
using OpenSim.Services.Interfaces;
using OpenSimAssetType = OpenSim.Framework.SLUtil.OpenSimAssetType;
namespace OpenSim.Region.Framework.Scenes
{
/// <summary>
/// Gather uuids for a given entity.
/// </summary>
/// <remarks>
/// This does a deep inspection of the entity to retrieve all the assets it uses (whether as textures, as scripts
/// contained in inventory, as scripts contained in objects contained in another object's inventory, etc. Assets
/// are only retrieved when they are necessary to carry out the inspection (i.e. a serialized object needs to be
/// retrieved to work out which assets it references).
/// </remarks>
public class UuidGatherer
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// Is gathering complete?
/// </summary>
public bool Complete { get { return m_assetUuidsToInspect.Count <= 0; } }
/// <summary>
/// The dictionary of UUIDs gathered so far. If Complete == true then this is all the reachable UUIDs.
/// </summary>
/// <value>The gathered uuids.</value>
public IDictionary<UUID, sbyte> GatheredUuids { get; private set; }
/// <summary>
/// Gets the next UUID to inspect.
/// </summary>
/// <value>If there is no next UUID then returns null</value>
public UUID? NextUuidToInspect
{
get
{
if (Complete)
return null;
else
return m_assetUuidsToInspect.Peek();
}
}
protected IAssetService m_assetService;
protected Queue<UUID> m_assetUuidsToInspect;
/// <summary>
/// Initializes a new instance of the <see cref="OpenSim.Region.Framework.Scenes.UuidGatherer"/> class.
/// </summary>
/// <remarks>In this case the collection of gathered assets will start out blank.</remarks>
/// <param name="assetService">
/// Asset service.
/// </param>
public UuidGatherer(IAssetService assetService) : this(assetService, new Dictionary<UUID, sbyte>()) {}
/// <summary>
/// Initializes a new instance of the <see cref="OpenSim.Region.Framework.Scenes.UuidGatherer"/> class.
/// </summary>
/// <param name="assetService">
/// Asset service.
/// </param>
/// <param name="collector">
/// Gathered UUIDs will be collected in this dictinaory.
/// It can be pre-populated if you want to stop the gatherer from analyzing assets that have already been fetched and inspected.
/// </param>
public UuidGatherer(IAssetService assetService, IDictionary<UUID, sbyte> collector)
{
m_assetService = assetService;
GatheredUuids = collector;
// FIXME: Not efficient for searching, can improve.
m_assetUuidsToInspect = new Queue<UUID>();
}
/// <summary>
/// Adds the asset uuid for inspection during the gathering process.
/// </summary>
/// <returns><c>true</c>, if for inspection was added, <c>false</c> otherwise.</returns>
/// <param name="uuid">UUID.</param>
public bool AddForInspection(UUID uuid)
{
if (m_assetUuidsToInspect.Contains(uuid))
return false;
// m_log.DebugFormat("[UUID GATHERER]: Adding asset {0} for inspection", uuid);
m_assetUuidsToInspect.Enqueue(uuid);
return true;
}
/// <summary>
/// Gather all the asset uuids associated with a given object.
/// </summary>
/// <remarks>
/// This includes both those directly associated with
/// it (e.g. face textures) and recursively, those of items within it's inventory (e.g. objects contained
/// within this object).
/// </remarks>
/// <param name="sceneObject">The scene object for which to gather assets</param>
public void AddForInspection(SceneObjectGroup sceneObject)
{
// m_log.DebugFormat(
// "[ASSET GATHERER]: Getting assets for object {0}, {1}", sceneObject.Name, sceneObject.UUID);
SceneObjectPart[] parts = sceneObject.Parts;
for (int i = 0; i < parts.Length; i++)
{
SceneObjectPart part = parts[i];
// m_log.DebugFormat(
// "[ARCHIVER]: Getting part {0}, {1} for object {2}", part.Name, part.UUID, sceneObject.UUID);
try
{
Primitive.TextureEntry textureEntry = part.Shape.Textures;
if (textureEntry != null)
{
// Get the prim's default texture. This will be used for faces which don't have their own texture
if (textureEntry.DefaultTexture != null)
RecordTextureEntryAssetUuids(textureEntry.DefaultTexture);
if (textureEntry.FaceTextures != null)
{
// Loop through the rest of the texture faces (a non-null face means the face is different from DefaultTexture)
foreach (Primitive.TextureEntryFace texture in textureEntry.FaceTextures)
{
if (texture != null)
RecordTextureEntryAssetUuids(texture);
}
}
}
// If the prim is a sculpt then preserve this information too
if (part.Shape.SculptTexture != UUID.Zero)
GatheredUuids[part.Shape.SculptTexture] = (sbyte)AssetType.Texture;
if (part.Shape.ProjectionTextureUUID != UUID.Zero)
GatheredUuids[part.Shape.ProjectionTextureUUID] = (sbyte)AssetType.Texture;
UUID collisionSound = part.CollisionSound;
if ( collisionSound != UUID.Zero &&
collisionSound != part.invalidCollisionSoundUUID)
GatheredUuids[collisionSound] = (sbyte)AssetType.Sound;
if (part.ParticleSystem.Length > 0)
{
try
{
Primitive.ParticleSystem ps = new Primitive.ParticleSystem(part.ParticleSystem, 0);
if (ps.Texture != UUID.Zero)
GatheredUuids[ps.Texture] = (sbyte)AssetType.Texture;
}
catch (Exception)
{
m_log.WarnFormat(
"[UUID GATHERER]: Could not check particle system for part {0} {1} in object {2} {3} since it is corrupt. Continuing.",
part.Name, part.UUID, sceneObject.Name, sceneObject.UUID);
}
}
TaskInventoryDictionary taskDictionary = (TaskInventoryDictionary)part.TaskInventory.Clone();
// Now analyze this prim's inventory items to preserve all the uuids that they reference
foreach (TaskInventoryItem tii in taskDictionary.Values)
{
// m_log.DebugFormat(
// "[ARCHIVER]: Analysing item {0} asset type {1} in {2} {3}",
// tii.Name, tii.Type, part.Name, part.UUID);
if (!GatheredUuids.ContainsKey(tii.AssetID))
AddForInspection(tii.AssetID, (sbyte)tii.Type);
}
// FIXME: We need to make gathering modular but we cannot yet, since gatherers are not guaranteed
// to be called with scene objects that are in a scene (e.g. in the case of hg asset mapping and
// inventory transfer. There needs to be a way for a module to register a method without assuming a
// Scene.EventManager is present.
// part.ParentGroup.Scene.EventManager.TriggerGatherUuids(part, assetUuids);
// still needed to retrieve textures used as materials for any parts containing legacy materials stored in DynAttrs
RecordMaterialsUuids(part);
}
catch (Exception e)
{
m_log.ErrorFormat("[UUID GATHERER]: Failed to get part - {0}", e);
m_log.DebugFormat(
"[UUID GATHERER]: Texture entry length for prim was {0} (min is 46)",
part.Shape.TextureEntry.Length);
}
}
}
/// <summary>
/// Gathers the next set of assets returned by the next uuid to get from the asset service.
/// </summary>
/// <returns>false if gathering is already complete, true otherwise</returns>
public bool GatherNext()
{
if (Complete)
return false;
UUID nextToInspect = m_assetUuidsToInspect.Dequeue();
// m_log.DebugFormat("[UUID GATHERER]: Inspecting asset {0}", nextToInspect);
GetAssetUuids(nextToInspect);
return true;
}
/// <summary>
/// Gathers all remaining asset UUIDS no matter how many calls are required to the asset service.
/// </summary>
/// <returns>false if gathering is already complete, true otherwise</returns>
public bool GatherAll()
{
if (Complete)
return false;
while (GatherNext());
return true;
}
/// <summary>
/// Gather all the asset uuids associated with the asset referenced by a given uuid
/// </summary>
/// <remarks>
/// This includes both those directly associated with
/// it (e.g. face textures) and recursively, those of items within it's inventory (e.g. objects contained
/// within this object).
/// This method assumes that the asset type associated with this asset in persistent storage is correct (which
/// should always be the case). So with this method we always need to retrieve asset data even if the asset
/// is of a type which is known not to reference any other assets
/// </remarks>
/// <param name="assetUuid">The uuid of the asset for which to gather referenced assets</param>
private void GetAssetUuids(UUID assetUuid)
{
// avoid infinite loops
if (GatheredUuids.ContainsKey(assetUuid))
return;
try
{
AssetBase assetBase = GetAsset(assetUuid);
if (null != assetBase)
{
sbyte assetType = assetBase.Type;
GatheredUuids[assetUuid] = assetType;
if ((sbyte)AssetType.Bodypart == assetType || (sbyte)AssetType.Clothing == assetType)
{
RecordWearableAssetUuids(assetBase);
}
else if ((sbyte)AssetType.Gesture == assetType)
{
RecordGestureAssetUuids(assetBase);
}
else if ((sbyte)AssetType.Notecard == assetType)
{
RecordTextEmbeddedAssetUuids(assetBase);
}
else if ((sbyte)AssetType.LSLText == assetType)
{
RecordTextEmbeddedAssetUuids(assetBase);
}
else if ((sbyte)OpenSimAssetType.Material == assetType)
{
RecordMaterialAssetUuids(assetBase);
}
else if ((sbyte)AssetType.Object == assetType)
{
RecordSceneObjectAssetUuids(assetBase);
}
}
}
catch (Exception)
{
m_log.ErrorFormat("[UUID GATHERER]: Failed to gather uuids for asset id {0}", assetUuid);
throw;
}
}
private void AddForInspection(UUID assetUuid, sbyte assetType)
{
// Here, we want to collect uuids which require further asset fetches but mark the others as gathered
try
{
if ((sbyte)AssetType.Bodypart == assetType
|| (sbyte)AssetType.Clothing == assetType
|| (sbyte)AssetType.Gesture == assetType
|| (sbyte)AssetType.Notecard == assetType
|| (sbyte)AssetType.LSLText == assetType
|| (sbyte)OpenSimAssetType.Material == assetType
|| (sbyte)AssetType.Object == assetType)
{
AddForInspection(assetUuid);
}
else
{
GatheredUuids[assetUuid] = assetType;
}
}
catch (Exception)
{
m_log.ErrorFormat(
"[UUID GATHERER]: Failed to gather uuids for asset id {0}, type {1}",
assetUuid, assetType);
throw;
}
}
/// <summary>
/// Collect all the asset uuids found in one face of a Texture Entry.
/// </summary>
private void RecordTextureEntryAssetUuids(Primitive.TextureEntryFace texture)
{
GatheredUuids[texture.TextureID] = (sbyte)AssetType.Texture;
if (texture.MaterialID != UUID.Zero)
AddForInspection(texture.MaterialID);
}
/// <summary>
/// Gather all of the texture asset UUIDs used to reference "Materials" such as normal and specular maps
/// stored in legacy format in part.DynAttrs
/// </summary>
/// <param name="part"></param>
private void RecordMaterialsUuids(SceneObjectPart part)
{
// scan thru the dynAttrs map of this part for any textures used as materials
OSD osdMaterials = null;
lock (part.DynAttrs)
{
if (part.DynAttrs.ContainsStore("OpenSim", "Materials"))
{
OSDMap materialsStore = part.DynAttrs.GetStore("OpenSim", "Materials");
if (materialsStore == null)
return;
materialsStore.TryGetValue("Materials", out osdMaterials);
}
if (osdMaterials != null)
{
//m_log.Info("[UUID Gatherer]: found Materials: " + OSDParser.SerializeJsonString(osd));
if (osdMaterials is OSDArray)
{
OSDArray matsArr = osdMaterials as OSDArray;
foreach (OSDMap matMap in matsArr)
{
try
{
if (matMap.ContainsKey("Material"))
{
OSDMap mat = matMap["Material"] as OSDMap;
if (mat.ContainsKey("NormMap"))
{
UUID normalMapId = mat["NormMap"].AsUUID();
if (normalMapId != UUID.Zero)
{
GatheredUuids[normalMapId] = (sbyte)AssetType.Texture;
//m_log.Info("[UUID Gatherer]: found normal map ID: " + normalMapId.ToString());
}
}
if (mat.ContainsKey("SpecMap"))
{
UUID specularMapId = mat["SpecMap"].AsUUID();
if (specularMapId != UUID.Zero)
{
GatheredUuids[specularMapId] = (sbyte)AssetType.Texture;
//m_log.Info("[UUID Gatherer]: found specular map ID: " + specularMapId.ToString());
}
}
}
}
catch (Exception e)
{
m_log.Warn("[UUID Gatherer]: exception getting materials: " + e.Message);
}
}
}
}
}
}
/// <summary>
/// Get an asset synchronously, potentially using an asynchronous callback. If the
/// asynchronous callback is used, we will wait for it to complete.
/// </summary>
/// <param name="uuid"></param>
/// <returns></returns>
protected virtual AssetBase GetAsset(UUID uuid)
{
return m_assetService.Get(uuid.ToString());
}
/// <summary>
/// Record the asset uuids embedded within the given text (e.g. a script).
/// </summary>
/// <param name="textAsset"></param>
private void RecordTextEmbeddedAssetUuids(AssetBase textAsset)
{
// m_log.DebugFormat("[ASSET GATHERER]: Getting assets for uuid references in asset {0}", embeddingAssetId);
string text = Utils.BytesToString(textAsset.Data);
// m_log.DebugFormat("[UUID GATHERER]: Text {0}", text);
MatchCollection uuidMatches = Util.PermissiveUUIDPattern.Matches(text);
// m_log.DebugFormat("[UUID GATHERER]: Found {0} matches in text", uuidMatches.Count);
foreach (Match uuidMatch in uuidMatches)
{
UUID uuid = new UUID(uuidMatch.Value);
// m_log.DebugFormat("[UUID GATHERER]: Recording {0} in text", uuid);
AddForInspection(uuid);
}
}
/// <summary>
/// Record the uuids referenced by the given wearable asset
/// </summary>
/// <param name="assetBase"></param>
private void RecordWearableAssetUuids(AssetBase assetBase)
{
//m_log.Debug(new System.Text.ASCIIEncoding().GetString(bodypartAsset.Data));
AssetWearable wearableAsset = new AssetBodypart(assetBase.FullID, assetBase.Data);
wearableAsset.Decode();
//m_log.DebugFormat(
// "[ARCHIVER]: Wearable asset {0} references {1} assets", wearableAssetUuid, wearableAsset.Textures.Count);
foreach (UUID uuid in wearableAsset.Textures.Values)
GatheredUuids[uuid] = (sbyte)AssetType.Texture;
}
/// <summary>
/// Get all the asset uuids associated with a given object. This includes both those directly associated with
/// it (e.g. face textures) and recursively, those of items within it's inventory (e.g. objects contained
/// within this object).
/// </summary>
/// <param name="sceneObjectAsset"></param>
private void RecordSceneObjectAssetUuids(AssetBase sceneObjectAsset)
{
string xml = Utils.BytesToString(sceneObjectAsset.Data);
CoalescedSceneObjects coa;
if (CoalescedSceneObjectsSerializer.TryFromXml(xml, out coa))
{
foreach (SceneObjectGroup sog in coa.Objects)
AddForInspection(sog);
}
else
{
SceneObjectGroup sog = SceneObjectSerializer.FromOriginalXmlFormat(xml);
if (null != sog)
AddForInspection(sog);
}
}
/// <summary>
/// Get the asset uuid associated with a gesture
/// </summary>
/// <param name="gestureAsset"></param>
private void RecordGestureAssetUuids(AssetBase gestureAsset)
{
using (MemoryStream ms = new MemoryStream(gestureAsset.Data))
using (StreamReader sr = new StreamReader(ms))
{
sr.ReadLine(); // Unknown (Version?)
sr.ReadLine(); // Unknown
sr.ReadLine(); // Unknown
sr.ReadLine(); // Name
sr.ReadLine(); // Comment ?
int count = Convert.ToInt32(sr.ReadLine()); // Item count
for (int i = 0 ; i < count ; i++)
{
string type = sr.ReadLine();
if (type == null)
break;
string name = sr.ReadLine();
if (name == null)
break;
string id = sr.ReadLine();
if (id == null)
break;
string unknown = sr.ReadLine();
if (unknown == null)
break;
// If it can be parsed as a UUID, it is an asset ID
UUID uuid;
if (UUID.TryParse(id, out uuid))
GatheredUuids[uuid] = (sbyte)AssetType.Animation; // the asset is either an Animation or a Sound, but this distinction isn't important
}
}
}
/// <summary>
/// Get the asset uuid's referenced in a material.
/// </summary>
private void RecordMaterialAssetUuids(AssetBase materialAsset)
{
OSDMap mat;
try
{
mat = (OSDMap)OSDParser.DeserializeLLSDXml(materialAsset.Data);
}
catch (Exception e)
{
m_log.WarnFormat("[Materials]: cannot decode material asset {0}: {1}", materialAsset.ID, e.Message);
return;
}
UUID normMap = mat["NormMap"].AsUUID();
if (normMap != UUID.Zero)
GatheredUuids[normMap] = (sbyte)AssetType.Texture;
UUID specMap = mat["SpecMap"].AsUUID();
if (specMap != UUID.Zero)
GatheredUuids[specMap] = (sbyte)AssetType.Texture;
}
}
public class HGUuidGatherer : UuidGatherer
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected string m_assetServerURL;
public HGUuidGatherer(IAssetService assetService, string assetServerURL)
: this(assetService, assetServerURL, new Dictionary<UUID, sbyte>()) {}
public HGUuidGatherer(IAssetService assetService, string assetServerURL, IDictionary<UUID, sbyte> collector)
: base(assetService, collector)
{
m_assetServerURL = assetServerURL;
if (!m_assetServerURL.EndsWith("/") && !m_assetServerURL.EndsWith("="))
m_assetServerURL = m_assetServerURL + "/";
}
protected override AssetBase GetAsset(UUID uuid)
{
if (string.Empty == m_assetServerURL)
return base.GetAsset(uuid);
else
return FetchAsset(uuid);
}
public AssetBase FetchAsset(UUID assetID)
{
// Test if it's already here
AssetBase asset = m_assetService.Get(assetID.ToString());
if (asset == null)
{
// It's not, so fetch it from abroad
asset = m_assetService.Get(m_assetServerURL + assetID.ToString());
if (asset != null)
m_log.DebugFormat("[HGUUIDGatherer]: Copied asset {0} from {1} to local asset server", assetID, m_assetServerURL);
else
m_log.DebugFormat("[HGUUIDGatherer]: Failed to fetch asset {0} from {1}", assetID, m_assetServerURL);
}
//else
// m_log.DebugFormat("[HGUUIDGatherer]: Asset {0} from {1} was already here", assetID, m_assetServerURL);
return asset;
}
}
}
| |
using Microsoft.Azure.Commands.Compute.Common;
using Microsoft.Azure.Commands.Common.Authentication.Models;
using Microsoft.WindowsAzure.Commands.Common.Extensions.DSC;
using Microsoft.WindowsAzure.Commands.Common.Extensions.DSC.Publish;
using Microsoft.WindowsAzure.Storage.Auth;
using System;
using System.Management.Automation;
using Microsoft.Azure.Commands.Common.Authentication.Abstractions;
using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters;
namespace Microsoft.Azure.Commands.Compute.Extension.DSC
{
/// <summary>
/// Uploads a Desired State Configuration script to Azure blob storage, which
/// later can be applied to Azure Virtual Machines using the
/// Set-AzureRmVMDscExtension cmdlet.
/// </summary>
[Cmdlet(
VerbsData.Publish,
ProfileNouns.VirtualMachineDscConfiguration,
SupportsShouldProcess = true,
DefaultParameterSetName = UploadArchiveParameterSetName),
OutputType(
typeof(String))]
public class PublishAzureVMDscConfigurationCommand : DscExtensionPublishCmdletCommonBase
{
private const string CreateArchiveParameterSetName = "CreateArchive";
private const string UploadArchiveParameterSetName = "UploadArchive";
[Parameter(
Mandatory = true,
Position = 2,
ParameterSetName = UploadArchiveParameterSetName,
ValueFromPipelineByPropertyName = true,
HelpMessage = "The name of the resource group that contains the storage account.")]
[ResourceGroupCompleter()]
[ValidateNotNullOrEmpty]
public string ResourceGroupName { get; set; }
/// <summary>
/// Path to a file containing one or more configurations; the file can be a
/// PowerShell script (*.ps1) or MOF interface (*.mof).
/// </summary>
[Parameter(
Mandatory = true,
Position = 1,
ValueFromPipeline = true,
ValueFromPipelineByPropertyName = true,
HelpMessage = "Path to a file containing one or more configurations")]
[ValidateNotNullOrEmpty]
public string ConfigurationPath { get; set; }
/// <summary>
/// Name of the Azure Storage Container the configuration is uploaded to.
/// </summary>
[Parameter(
ValueFromPipelineByPropertyName = true,
Position = 4,
ParameterSetName = UploadArchiveParameterSetName,
HelpMessage = "Name of the Azure Storage Container the configuration is uploaded to")]
[ValidateNotNullOrEmpty]
public string ContainerName { get; set; }
/// <summary>
/// The Azure Storage Account name used to upload the configuration script to the container specified by ContainerName.
/// </summary>
[Parameter(
Mandatory = true,
Position = 3,
ValueFromPipelineByPropertyName = true,
ParameterSetName = UploadArchiveParameterSetName,
HelpMessage = "The Azure Storage Account name used to upload the configuration script to the container " +
"specified by ContainerName ")]
[ValidateNotNullOrEmpty]
public String StorageAccountName { get; set; }
/// <summary>
/// Path to a local ZIP file to write the configuration archive to.
/// When using this parameter, Publish-AzureRmVMDscConfiguration creates a
/// local ZIP archive instead of uploading it to blob storage..
/// </summary>
[Alias("ConfigurationArchivePath")]
[Parameter(
Position = 2,
ValueFromPipelineByPropertyName = true,
ParameterSetName = CreateArchiveParameterSetName,
HelpMessage = "Path to a local ZIP file to write the configuration archive to.")]
[ValidateNotNullOrEmpty]
public string OutputArchivePath { get; set; }
/// <summary>
/// Suffix for the storage end point, e.g. core.windows.net
/// </summary>
[Parameter(
ValueFromPipelineByPropertyName = true,
ParameterSetName = UploadArchiveParameterSetName,
HelpMessage = "Suffix for the storage end point, e.g. core.windows.net")]
[ValidateNotNullOrEmpty]
public string StorageEndpointSuffix { get; set; }
/// <summary>
/// By default Publish-AzureRmVMDscConfiguration will not overwrite any existing blobs.
/// Use -Force to overwrite them.
/// </summary>
[Parameter(HelpMessage = "By default Publish-AzureRmVMDscConfiguration will not overwrite any existing blobs")]
public SwitchParameter Force { get; set; }
/// <summary>
/// Excludes DSC resource dependencies from the configuration archive
/// </summary>
[Parameter(HelpMessage = "Excludes DSC resource dependencies from the configuration archive")]
public SwitchParameter SkipDependencyDetection { get; set; }
/// <summary>
///Path to a .psd1 file that specifies the data for the Configuration. This
/// file must contain a hashtable with the items described in
/// http://technet.microsoft.com/en-us/library/dn249925.aspx.
/// </summary>
[Parameter(
ValueFromPipelineByPropertyName = true,
HelpMessage = "Path to a .psd1 file that specifies the data for the Configuration. This is added to the configuration " +
"archive and then passed to the configuration function. It gets overwritten by the configuration data path " +
"provided through the Set-AzureRmVMDscExtension cmdlet")]
[ValidateNotNullOrEmpty]
public string ConfigurationDataPath { get; set; }
/// <summary>
/// Path to a file or a directory to include in the configuration archive
/// </summary>
[Parameter(
ValueFromPipelineByPropertyName = true,
HelpMessage = "Path to a file or a directory to include in the configuration archive. It gets downloaded to the " +
"VM along with the configuration")]
[ValidateNotNullOrEmpty]
public String[] AdditionalPath { get; set; }
//Private Variables
/// <summary>
/// Credentials used to access Azure Storage
/// </summary>
private StorageCredentials _storageCredentials;
public override void ExecuteCmdlet()
{
base.ExecuteCmdlet();
try
{
ValidatePsVersion();
//validate cmdlet params
ConfigurationPath = GetUnresolvedProviderPathFromPSPath(ConfigurationPath);
ValidateConfigurationPath(ConfigurationPath, ParameterSetName);
if (ConfigurationDataPath != null)
{
ConfigurationDataPath = GetUnresolvedProviderPathFromPSPath(ConfigurationDataPath);
ValidateConfigurationDataPath(ConfigurationDataPath);
}
if (AdditionalPath != null && AdditionalPath.Length > 0)
{
for (var count = 0; count < AdditionalPath.Length; count++)
{
AdditionalPath[count] = GetUnresolvedProviderPathFromPSPath(AdditionalPath[count]);
}
}
switch (ParameterSetName)
{
case CreateArchiveParameterSetName:
OutputArchivePath = GetUnresolvedProviderPathFromPSPath(OutputArchivePath);
break;
case UploadArchiveParameterSetName:
_storageCredentials = this.GetStorageCredentials(ResourceGroupName,StorageAccountName);
if (ContainerName == null)
{
ContainerName = DscExtensionCmdletConstants.DefaultContainerName;
}
if (StorageEndpointSuffix == null)
{
StorageEndpointSuffix =
DefaultProfile.DefaultContext.Environment.GetEndpoint(AzureEnvironment.Endpoint.StorageEndpointSuffix);
}
break;
}
PublishConfiguration(
ConfigurationPath,
ConfigurationDataPath,
AdditionalPath,
OutputArchivePath,
StorageEndpointSuffix,
ContainerName,
ParameterSetName,
Force.IsPresent,
SkipDependencyDetection.IsPresent,
_storageCredentials);
}
finally
{
DeleteTemporaryFiles();
}
}
}
}
| |
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 CommandSenderApi.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Microsoft.Azure;
using Microsoft.Azure.Management.Automation;
using Microsoft.Azure.Management.Automation.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.Automation
{
/// <summary>
/// Service operation for dsc nodes. (see
/// http://aka.ms/azureautomationsdk/dscnodeoperations for more
/// information)
/// </summary>
internal partial class DscNodeOperations : IServiceOperations<AutomationManagementClient>, IDscNodeOperations
{
/// <summary>
/// Initializes a new instance of the DscNodeOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal DscNodeOperations(AutomationManagementClient client)
{
this._client = client;
}
private AutomationManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.Automation.AutomationManagementClient.
/// </summary>
public AutomationManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Delete the dsc node identified by node id. (see
/// http://aka.ms/azureautomationsdk/dscnodeoperations for more
/// information)
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. Automation account name.
/// </param>
/// <param name='nodeId'>
/// Required. The node id.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> DeleteAsync(string resourceGroupName, string automationAccount, Guid nodeId, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (automationAccount == null)
{
throw new ArgumentNullException("automationAccount");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("automationAccount", automationAccount);
tracingParameters.Add("nodeId", nodeId);
TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
if (this.Client.ResourceNamespace != null)
{
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
}
url = url + "/automationAccounts/";
url = url + Uri.EscapeDataString(automationAccount);
url = url + "/nodes/";
url = url + Uri.EscapeDataString(nodeId.ToString());
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-01-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Delete;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2014-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Retrieve the dsc node identified by node id. (see
/// http://aka.ms/azureautomationsdk/dscnodeoperations for more
/// information)
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='nodeId'>
/// Required. The node id.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the get dsc node operation.
/// </returns>
public async Task<DscNodeGetResponse> GetAsync(string resourceGroupName, string automationAccount, Guid nodeId, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (automationAccount == null)
{
throw new ArgumentNullException("automationAccount");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("automationAccount", automationAccount);
tracingParameters.Add("nodeId", nodeId);
TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
if (this.Client.ResourceNamespace != null)
{
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
}
url = url + "/automationAccounts/";
url = url + Uri.EscapeDataString(automationAccount);
url = url + "/nodes/";
url = url + Uri.EscapeDataString(nodeId.ToString());
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-01-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
httpRequest.Headers.Add("x-ms-version", "2014-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
DscNodeGetResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new DscNodeGetResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
DscNode nodeInstance = new DscNode();
result.Node = nodeInstance;
JToken lastSeenValue = responseDoc["lastSeen"];
if (lastSeenValue != null && lastSeenValue.Type != JTokenType.Null)
{
DateTimeOffset lastSeenInstance = ((DateTimeOffset)lastSeenValue);
nodeInstance.LastSeen = lastSeenInstance;
}
JToken registrationTimeValue = responseDoc["registrationTime"];
if (registrationTimeValue != null && registrationTimeValue.Type != JTokenType.Null)
{
DateTimeOffset registrationTimeInstance = ((DateTimeOffset)registrationTimeValue);
nodeInstance.RegistrationTime = registrationTimeInstance;
}
JToken ipValue = responseDoc["ip"];
if (ipValue != null && ipValue.Type != JTokenType.Null)
{
string ipInstance = ((string)ipValue);
nodeInstance.Ip = ipInstance;
}
JToken accountIdValue = responseDoc["accountId"];
if (accountIdValue != null && accountIdValue.Type != JTokenType.Null)
{
Guid accountIdInstance = Guid.Parse(((string)accountIdValue));
nodeInstance.AccountId = accountIdInstance;
}
JToken nodeConfigurationValue = responseDoc["nodeConfiguration"];
if (nodeConfigurationValue != null && nodeConfigurationValue.Type != JTokenType.Null)
{
DscNodeConfigurationAssociationProperty nodeConfigurationInstance = new DscNodeConfigurationAssociationProperty();
nodeInstance.NodeConfiguration = nodeConfigurationInstance;
JToken nameValue = nodeConfigurationValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
nodeConfigurationInstance.Name = nameInstance;
}
}
JToken statusValue = responseDoc["status"];
if (statusValue != null && statusValue.Type != JTokenType.Null)
{
string statusInstance = ((string)statusValue);
nodeInstance.Status = statusInstance;
}
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
nodeInstance.Id = idInstance;
}
JToken nameValue2 = responseDoc["name"];
if (nameValue2 != null && nameValue2.Type != JTokenType.Null)
{
string nameInstance2 = ((string)nameValue2);
nodeInstance.Name = nameInstance2;
}
JToken locationValue = responseDoc["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
nodeInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)responseDoc["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey = ((string)property.Name);
string tagsValue = ((string)property.Value);
nodeInstance.Tags.Add(tagsKey, tagsValue);
}
}
JToken typeValue = responseDoc["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
nodeInstance.Type = typeInstance;
}
JToken etagValue = responseDoc["etag"];
if (etagValue != null && etagValue.Type != JTokenType.Null)
{
string etagInstance = ((string)etagValue);
nodeInstance.Etag = etagInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Retrieve a list of dsc nodes. (see
/// http://aka.ms/azureautomationsdk/dscnodeoperations for more
/// information)
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='parameters'>
/// Optional. The parameters supplied to the list operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the list dsc nodes operation.
/// </returns>
public async Task<DscNodeListResponse> ListAsync(string resourceGroupName, string automationAccount, DscNodeListParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (automationAccount == null)
{
throw new ArgumentNullException("automationAccount");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("automationAccount", automationAccount);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
if (this.Client.ResourceNamespace != null)
{
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
}
url = url + "/automationAccounts/";
url = url + Uri.EscapeDataString(automationAccount);
url = url + "/nodes";
List<string> queryParameters = new List<string>();
List<string> odataFilter = new List<string>();
if (parameters != null && parameters.Status != null)
{
odataFilter.Add("status eq '" + Uri.EscapeDataString(parameters.Status) + "'");
}
if (parameters != null && parameters.NodeConfigurationName != null)
{
odataFilter.Add("nodeConfiguration/name eq '" + Uri.EscapeDataString(parameters.NodeConfigurationName) + "'");
}
if (parameters != null && parameters.Name != null)
{
odataFilter.Add("name eq '" + Uri.EscapeDataString(parameters.Name) + "'");
}
if (odataFilter.Count > 0)
{
queryParameters.Add("$filter=" + string.Join(" and ", odataFilter));
}
queryParameters.Add("api-version=2015-01-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
httpRequest.Headers.Add("ocp-referer", url);
httpRequest.Headers.Add("x-ms-version", "2014-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
DscNodeListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new DscNodeListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
DscNode dscNodeInstance = new DscNode();
result.Nodes.Add(dscNodeInstance);
JToken lastSeenValue = valueValue["lastSeen"];
if (lastSeenValue != null && lastSeenValue.Type != JTokenType.Null)
{
DateTimeOffset lastSeenInstance = ((DateTimeOffset)lastSeenValue);
dscNodeInstance.LastSeen = lastSeenInstance;
}
JToken registrationTimeValue = valueValue["registrationTime"];
if (registrationTimeValue != null && registrationTimeValue.Type != JTokenType.Null)
{
DateTimeOffset registrationTimeInstance = ((DateTimeOffset)registrationTimeValue);
dscNodeInstance.RegistrationTime = registrationTimeInstance;
}
JToken ipValue = valueValue["ip"];
if (ipValue != null && ipValue.Type != JTokenType.Null)
{
string ipInstance = ((string)ipValue);
dscNodeInstance.Ip = ipInstance;
}
JToken accountIdValue = valueValue["accountId"];
if (accountIdValue != null && accountIdValue.Type != JTokenType.Null)
{
Guid accountIdInstance = Guid.Parse(((string)accountIdValue));
dscNodeInstance.AccountId = accountIdInstance;
}
JToken nodeConfigurationValue = valueValue["nodeConfiguration"];
if (nodeConfigurationValue != null && nodeConfigurationValue.Type != JTokenType.Null)
{
DscNodeConfigurationAssociationProperty nodeConfigurationInstance = new DscNodeConfigurationAssociationProperty();
dscNodeInstance.NodeConfiguration = nodeConfigurationInstance;
JToken nameValue = nodeConfigurationValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
nodeConfigurationInstance.Name = nameInstance;
}
}
JToken statusValue = valueValue["status"];
if (statusValue != null && statusValue.Type != JTokenType.Null)
{
string statusInstance = ((string)statusValue);
dscNodeInstance.Status = statusInstance;
}
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
dscNodeInstance.Id = idInstance;
}
JToken nameValue2 = valueValue["name"];
if (nameValue2 != null && nameValue2.Type != JTokenType.Null)
{
string nameInstance2 = ((string)nameValue2);
dscNodeInstance.Name = nameInstance2;
}
JToken locationValue = valueValue["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
dscNodeInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)valueValue["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey = ((string)property.Name);
string tagsValue = ((string)property.Value);
dscNodeInstance.Tags.Add(tagsKey, tagsValue);
}
}
JToken typeValue = valueValue["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
dscNodeInstance.Type = typeInstance;
}
JToken etagValue = valueValue["etag"];
if (etagValue != null && etagValue.Type != JTokenType.Null)
{
string etagInstance = ((string)etagValue);
dscNodeInstance.Etag = etagInstance;
}
}
}
JToken odatanextLinkValue = responseDoc["odata.nextLink"];
if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null)
{
string odatanextLinkInstance = Regex.Match(((string)odatanextLinkValue), "^.*[&\\?]\\$skiptoken=([^&]*)(&.*)?").Groups[1].Value;
result.SkipToken = odatanextLinkInstance;
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
result.NextLink = nextLinkInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Retrieve next list of configurations. (see
/// http://aka.ms/azureautomationsdk/dscnodeoperations for more
/// information)
/// </summary>
/// <param name='nextLink'>
/// Required. The link to retrieve next set of items.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the list dsc nodes operation.
/// </returns>
public async Task<DscNodeListResponse> ListNextAsync(string nextLink, CancellationToken cancellationToken)
{
// Validate
if (nextLink == null)
{
throw new ArgumentNullException("nextLink");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextLink", nextLink);
TracingAdapter.Enter(invocationId, this, "ListNextAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + nextLink;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
httpRequest.Headers.Add("ocp-referer", url);
httpRequest.Headers.Add("x-ms-version", "2014-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
DscNodeListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new DscNodeListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
DscNode dscNodeInstance = new DscNode();
result.Nodes.Add(dscNodeInstance);
JToken lastSeenValue = valueValue["lastSeen"];
if (lastSeenValue != null && lastSeenValue.Type != JTokenType.Null)
{
DateTimeOffset lastSeenInstance = ((DateTimeOffset)lastSeenValue);
dscNodeInstance.LastSeen = lastSeenInstance;
}
JToken registrationTimeValue = valueValue["registrationTime"];
if (registrationTimeValue != null && registrationTimeValue.Type != JTokenType.Null)
{
DateTimeOffset registrationTimeInstance = ((DateTimeOffset)registrationTimeValue);
dscNodeInstance.RegistrationTime = registrationTimeInstance;
}
JToken ipValue = valueValue["ip"];
if (ipValue != null && ipValue.Type != JTokenType.Null)
{
string ipInstance = ((string)ipValue);
dscNodeInstance.Ip = ipInstance;
}
JToken accountIdValue = valueValue["accountId"];
if (accountIdValue != null && accountIdValue.Type != JTokenType.Null)
{
Guid accountIdInstance = Guid.Parse(((string)accountIdValue));
dscNodeInstance.AccountId = accountIdInstance;
}
JToken nodeConfigurationValue = valueValue["nodeConfiguration"];
if (nodeConfigurationValue != null && nodeConfigurationValue.Type != JTokenType.Null)
{
DscNodeConfigurationAssociationProperty nodeConfigurationInstance = new DscNodeConfigurationAssociationProperty();
dscNodeInstance.NodeConfiguration = nodeConfigurationInstance;
JToken nameValue = nodeConfigurationValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
nodeConfigurationInstance.Name = nameInstance;
}
}
JToken statusValue = valueValue["status"];
if (statusValue != null && statusValue.Type != JTokenType.Null)
{
string statusInstance = ((string)statusValue);
dscNodeInstance.Status = statusInstance;
}
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
dscNodeInstance.Id = idInstance;
}
JToken nameValue2 = valueValue["name"];
if (nameValue2 != null && nameValue2.Type != JTokenType.Null)
{
string nameInstance2 = ((string)nameValue2);
dscNodeInstance.Name = nameInstance2;
}
JToken locationValue = valueValue["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
dscNodeInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)valueValue["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey = ((string)property.Name);
string tagsValue = ((string)property.Value);
dscNodeInstance.Tags.Add(tagsKey, tagsValue);
}
}
JToken typeValue = valueValue["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
dscNodeInstance.Type = typeInstance;
}
JToken etagValue = valueValue["etag"];
if (etagValue != null && etagValue.Type != JTokenType.Null)
{
string etagInstance = ((string)etagValue);
dscNodeInstance.Etag = etagInstance;
}
}
}
JToken odatanextLinkValue = responseDoc["odata.nextLink"];
if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null)
{
string odatanextLinkInstance = Regex.Match(((string)odatanextLinkValue), "^.*[&\\?]\\$skiptoken=([^&]*)(&.*)?").Groups[1].Value;
result.SkipToken = odatanextLinkInstance;
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
result.NextLink = nextLinkInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Update the dsc node. (see
/// http://aka.ms/azureautomationsdk/dscnodeoperations for more
/// information)
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the patch dsc node.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the patch dsc node operation.
/// </returns>
public async Task<DscNodePatchResponse> PatchAsync(string resourceGroupName, string automationAccount, DscNodePatchParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (automationAccount == null)
{
throw new ArgumentNullException("automationAccount");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("automationAccount", automationAccount);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "PatchAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
if (this.Client.ResourceNamespace != null)
{
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
}
url = url + "/automationAccounts/";
url = url + Uri.EscapeDataString(automationAccount);
url = url + "/nodes/";
url = url + Uri.EscapeDataString(parameters.Id.ToString());
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-01-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("PATCH");
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2014-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject dscNodePatchParametersValue = new JObject();
requestDoc = dscNodePatchParametersValue;
dscNodePatchParametersValue["id"] = parameters.Id.ToString();
if (parameters.NodeConfiguration != null)
{
JObject nodeConfigurationValue = new JObject();
dscNodePatchParametersValue["nodeConfiguration"] = nodeConfigurationValue;
if (parameters.NodeConfiguration.Name != null)
{
nodeConfigurationValue["name"] = parameters.NodeConfiguration.Name;
}
}
requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
DscNodePatchResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new DscNodePatchResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
DscNode nodeInstance = new DscNode();
result.Node = nodeInstance;
JToken lastSeenValue = responseDoc["lastSeen"];
if (lastSeenValue != null && lastSeenValue.Type != JTokenType.Null)
{
DateTimeOffset lastSeenInstance = ((DateTimeOffset)lastSeenValue);
nodeInstance.LastSeen = lastSeenInstance;
}
JToken registrationTimeValue = responseDoc["registrationTime"];
if (registrationTimeValue != null && registrationTimeValue.Type != JTokenType.Null)
{
DateTimeOffset registrationTimeInstance = ((DateTimeOffset)registrationTimeValue);
nodeInstance.RegistrationTime = registrationTimeInstance;
}
JToken ipValue = responseDoc["ip"];
if (ipValue != null && ipValue.Type != JTokenType.Null)
{
string ipInstance = ((string)ipValue);
nodeInstance.Ip = ipInstance;
}
JToken accountIdValue = responseDoc["accountId"];
if (accountIdValue != null && accountIdValue.Type != JTokenType.Null)
{
Guid accountIdInstance = Guid.Parse(((string)accountIdValue));
nodeInstance.AccountId = accountIdInstance;
}
JToken nodeConfigurationValue2 = responseDoc["nodeConfiguration"];
if (nodeConfigurationValue2 != null && nodeConfigurationValue2.Type != JTokenType.Null)
{
DscNodeConfigurationAssociationProperty nodeConfigurationInstance = new DscNodeConfigurationAssociationProperty();
nodeInstance.NodeConfiguration = nodeConfigurationInstance;
JToken nameValue = nodeConfigurationValue2["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
nodeConfigurationInstance.Name = nameInstance;
}
}
JToken statusValue = responseDoc["status"];
if (statusValue != null && statusValue.Type != JTokenType.Null)
{
string statusInstance = ((string)statusValue);
nodeInstance.Status = statusInstance;
}
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
nodeInstance.Id = idInstance;
}
JToken nameValue2 = responseDoc["name"];
if (nameValue2 != null && nameValue2.Type != JTokenType.Null)
{
string nameInstance2 = ((string)nameValue2);
nodeInstance.Name = nameInstance2;
}
JToken locationValue = responseDoc["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
nodeInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)responseDoc["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey = ((string)property.Name);
string tagsValue = ((string)property.Value);
nodeInstance.Tags.Add(tagsKey, tagsValue);
}
}
JToken typeValue = responseDoc["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
nodeInstance.Type = typeInstance;
}
JToken etagValue = responseDoc["etag"];
if (etagValue != null && etagValue.Type != JTokenType.Null)
{
string etagInstance = ((string)etagValue);
nodeInstance.Etag = etagInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
// 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 BinaryNullableOrTests
{
#region Test methods
[Fact]
public static void CheckNullableByteOrTest()
{
byte?[] array = new byte?[] { null, 0, 1, byte.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableByteOr(array[i], array[j]);
}
}
}
[Fact]
public static void CheckNullableSByteOrTest()
{
sbyte?[] array = new sbyte?[] { null, 0, 1, -1, sbyte.MinValue, sbyte.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableSByteOr(array[i], array[j]);
}
}
}
[Fact]
public static void CheckNullableUShortOrTest()
{
ushort?[] array = new ushort?[] { null, 0, 1, ushort.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableUShortOr(array[i], array[j]);
}
}
}
[Fact]
public static void CheckNullableShortOrTest()
{
short?[] array = new short?[] { null, 0, 1, -1, short.MinValue, short.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableShortOr(array[i], array[j]);
}
}
}
[Fact]
public static void CheckNullableUIntOrTest()
{
uint?[] array = new uint?[] { null, 0, 1, uint.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableUIntOr(array[i], array[j]);
}
}
}
[Fact]
public static void CheckNullableIntOrTest()
{
int?[] array = new int?[] { null, 0, 1, -1, int.MinValue, int.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableIntOr(array[i], array[j]);
}
}
}
[Fact]
public static void CheckNullableULongOrTest()
{
ulong?[] array = new ulong?[] { null, 0, 1, ulong.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableULongOr(array[i], array[j]);
}
}
}
[Fact]
public static void CheckNullableLongOrTest()
{
long?[] array = new long?[] { null, 0, 1, -1, long.MinValue, long.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableLongOr(array[i], array[j]);
}
}
}
#endregion
#region Test verifiers
private static void VerifyNullableByteOr(byte? a, byte? b)
{
Expression<Func<byte?>> e =
Expression.Lambda<Func<byte?>>(
Expression.Or(
Expression.Constant(a, typeof(byte?)),
Expression.Constant(b, typeof(byte?))),
Enumerable.Empty<ParameterExpression>());
Func<byte?> f = e.Compile();
// compute with expression tree
byte? etResult = default(byte);
Exception etException = null;
try
{
etResult = f();
}
catch (Exception ex)
{
etException = ex;
}
// compute with real IL
byte? csResult = default(byte);
Exception csException = null;
try
{
csResult = (byte?)(a | b);
}
catch (Exception ex)
{
csException = ex;
}
// either both should have failed the same way or they should both produce the same result
if (etException != null || csException != null)
{
Assert.NotNull(etException);
Assert.NotNull(csException);
Assert.Equal(csException.GetType(), etException.GetType());
}
else
{
Assert.Equal(csResult, etResult);
}
}
private static void VerifyNullableSByteOr(sbyte? a, sbyte? b)
{
Expression<Func<sbyte?>> e =
Expression.Lambda<Func<sbyte?>>(
Expression.Or(
Expression.Constant(a, typeof(sbyte?)),
Expression.Constant(b, typeof(sbyte?))),
Enumerable.Empty<ParameterExpression>());
Func<sbyte?> f = e.Compile();
// compute with expression tree
sbyte? etResult = default(sbyte);
Exception etException = null;
try
{
etResult = f();
}
catch (Exception ex)
{
etException = ex;
}
// compute with real IL
sbyte? csResult = default(sbyte);
Exception csException = null;
try
{
csResult = (sbyte?)(a | b);
}
catch (Exception ex)
{
csException = ex;
}
// either both should have failed the same way or they should both produce the same result
if (etException != null || csException != null)
{
Assert.NotNull(etException);
Assert.NotNull(csException);
Assert.Equal(csException.GetType(), etException.GetType());
}
else
{
Assert.Equal(csResult, etResult);
}
}
private static void VerifyNullableUShortOr(ushort? a, ushort? b)
{
Expression<Func<ushort?>> e =
Expression.Lambda<Func<ushort?>>(
Expression.Or(
Expression.Constant(a, typeof(ushort?)),
Expression.Constant(b, typeof(ushort?))),
Enumerable.Empty<ParameterExpression>());
Func<ushort?> f = e.Compile();
// compute with expression tree
ushort? etResult = default(ushort);
Exception etException = null;
try
{
etResult = f();
}
catch (Exception ex)
{
etException = ex;
}
// compute with real IL
ushort? csResult = default(ushort);
Exception csException = null;
try
{
csResult = (ushort?)(a | b);
}
catch (Exception ex)
{
csException = ex;
}
// either both should have failed the same way or they should both produce the same result
if (etException != null || csException != null)
{
Assert.NotNull(etException);
Assert.NotNull(csException);
Assert.Equal(csException.GetType(), etException.GetType());
}
else
{
Assert.Equal(csResult, etResult);
}
}
private static void VerifyNullableShortOr(short? a, short? b)
{
Expression<Func<short?>> e =
Expression.Lambda<Func<short?>>(
Expression.Or(
Expression.Constant(a, typeof(short?)),
Expression.Constant(b, typeof(short?))),
Enumerable.Empty<ParameterExpression>());
Func<short?> f = e.Compile();
// compute with expression tree
short? etResult = default(short);
Exception etException = null;
try
{
etResult = f();
}
catch (Exception ex)
{
etException = ex;
}
// compute with real IL
short? csResult = default(short);
Exception csException = null;
try
{
csResult = (short?)(a | b);
}
catch (Exception ex)
{
csException = ex;
}
// either both should have failed the same way or they should both produce the same result
if (etException != null || csException != null)
{
Assert.NotNull(etException);
Assert.NotNull(csException);
Assert.Equal(csException.GetType(), etException.GetType());
}
else
{
Assert.Equal(csResult, etResult);
}
}
private static void VerifyNullableUIntOr(uint? a, uint? b)
{
Expression<Func<uint?>> e =
Expression.Lambda<Func<uint?>>(
Expression.Or(
Expression.Constant(a, typeof(uint?)),
Expression.Constant(b, typeof(uint?))),
Enumerable.Empty<ParameterExpression>());
Func<uint?> f = e.Compile();
// compute with expression tree
uint? etResult = default(uint);
Exception etException = null;
try
{
etResult = f();
}
catch (Exception ex)
{
etException = ex;
}
// compute with real IL
uint? csResult = default(uint);
Exception csException = null;
try
{
csResult = (uint?)(a | b);
}
catch (Exception ex)
{
csException = ex;
}
// either both should have failed the same way or they should both produce the same result
if (etException != null || csException != null)
{
Assert.NotNull(etException);
Assert.NotNull(csException);
Assert.Equal(csException.GetType(), etException.GetType());
}
else
{
Assert.Equal(csResult, etResult);
}
}
private static void VerifyNullableIntOr(int? a, int? b)
{
Expression<Func<int?>> e =
Expression.Lambda<Func<int?>>(
Expression.Or(
Expression.Constant(a, typeof(int?)),
Expression.Constant(b, typeof(int?))),
Enumerable.Empty<ParameterExpression>());
Func<int?> f = e.Compile();
// compute with expression tree
int? etResult = default(int);
Exception etException = null;
try
{
etResult = f();
}
catch (Exception ex)
{
etException = ex;
}
// compute with real IL
int? csResult = default(int);
Exception csException = null;
try
{
csResult = (int?)(a | b);
}
catch (Exception ex)
{
csException = ex;
}
// either both should have failed the same way or they should both produce the same result
if (etException != null || csException != null)
{
Assert.NotNull(etException);
Assert.NotNull(csException);
Assert.Equal(csException.GetType(), etException.GetType());
}
else
{
Assert.Equal(csResult, etResult);
}
}
private static void VerifyNullableULongOr(ulong? a, ulong? b)
{
Expression<Func<ulong?>> e =
Expression.Lambda<Func<ulong?>>(
Expression.Or(
Expression.Constant(a, typeof(ulong?)),
Expression.Constant(b, typeof(ulong?))),
Enumerable.Empty<ParameterExpression>());
Func<ulong?> f = e.Compile();
// compute with expression tree
ulong? etResult = default(ulong);
Exception etException = null;
try
{
etResult = f();
}
catch (Exception ex)
{
etException = ex;
}
// compute with real IL
ulong? csResult = default(ulong);
Exception csException = null;
try
{
csResult = (ulong?)(a | b);
}
catch (Exception ex)
{
csException = ex;
}
// either both should have failed the same way or they should both produce the same result
if (etException != null || csException != null)
{
Assert.NotNull(etException);
Assert.NotNull(csException);
Assert.Equal(csException.GetType(), etException.GetType());
}
else
{
Assert.Equal(csResult, etResult);
}
}
private static void VerifyNullableLongOr(long? a, long? b)
{
Expression<Func<long?>> e =
Expression.Lambda<Func<long?>>(
Expression.Or(
Expression.Constant(a, typeof(long?)),
Expression.Constant(b, typeof(long?))),
Enumerable.Empty<ParameterExpression>());
Func<long?> f = e.Compile();
// compute with expression tree
long? etResult = default(long);
Exception etException = null;
try
{
etResult = f();
}
catch (Exception ex)
{
etException = ex;
}
// compute with real IL
long? csResult = default(long);
Exception csException = null;
try
{
csResult = (long?)(a | b);
}
catch (Exception ex)
{
csException = ex;
}
// either both should have failed the same way or they should both produce the same result
if (etException != null || csException != null)
{
Assert.NotNull(etException);
Assert.NotNull(csException);
Assert.Equal(csException.GetType(), etException.GetType());
}
else
{
Assert.Equal(csResult, etResult);
}
}
#endregion
}
}
| |
namespace SharpCompress.Common.Tar.Headers
{
using SharpCompress;
using SharpCompress.Common;
using System;
using System.IO;
using System.Runtime.CompilerServices;
using System.Text;
internal class TarHeader
{
[CompilerGenerated]
private long? _DataStartPosition_k__BackingField;
[CompilerGenerated]
private SharpCompress.Common.Tar.Headers.EntryType _EntryType_k__BackingField;
[CompilerGenerated]
private DateTime _LastModifiedTime_k__BackingField;
[CompilerGenerated]
private string _Magic_k__BackingField;
[CompilerGenerated]
private string _Name_k__BackingField;
[CompilerGenerated]
private Stream _PackedStream_k__BackingField;
[CompilerGenerated]
private long _Size_k__BackingField;
internal static readonly DateTime Epoch = new DateTime(0x7b2, 1, 1, 0, 0, 0, DateTimeKind.Utc);
internal bool Read(BinaryReader reader)
{
byte[] bytes = reader.ReadBytes(0x200);
if (bytes.Length == 0)
{
return false;
}
if (bytes.Length < 0x200)
{
throw new InvalidOperationException();
}
this.Name = Utility.TrimNulls(ArchiveEncoding.Default.GetString(bytes, 0, 100));
this.EntryType = (SharpCompress.Common.Tar.Headers.EntryType) bytes[0x9c];
if ((bytes[0x7c] & 0x80) == 0x80)
{
long network = BitConverter.ToInt64(bytes, 0x80);
this.Size = Utility.NetworkToHostOrder(network);
}
else
{
this.Size = ReadASCIIInt64Base8(bytes, 0x7c, 11);
}
long num2 = ReadASCIIInt64Base8(bytes, 0x88, 11);
this.LastModifiedTime = Epoch.AddSeconds((double) num2).ToLocalTime();
this.Magic = Utility.TrimNulls(ArchiveEncoding.Default.GetString(bytes, 0x101, 6));
if (!string.IsNullOrEmpty(this.Magic) && "ustar".Equals(this.Magic))
{
string str = Utility.TrimNulls(ArchiveEncoding.Default.GetString(bytes, 0x159, 0x9d));
if (!string.IsNullOrEmpty(str))
{
this.Name = str + "/" + this.Name;
}
}
if ((this.EntryType != SharpCompress.Common.Tar.Headers.EntryType.LongName) && (this.Name.Length == 0))
{
return false;
}
return true;
}
private static int ReadASCIIInt32Base8(byte[] buffer, int offset, int count)
{
string str = Utility.TrimNulls(Encoding.UTF8.GetString(buffer, offset, count));
if (string.IsNullOrEmpty(str))
{
return 0;
}
return Convert.ToInt32(str, 8);
}
private static long ReadASCIIInt64(byte[] buffer, int offset, int count)
{
string str = Utility.TrimNulls(Encoding.UTF8.GetString(buffer, offset, count));
if (string.IsNullOrEmpty(str))
{
return 0L;
}
return Convert.ToInt64(str);
}
private static long ReadASCIIInt64Base8(byte[] buffer, int offset, int count)
{
string str = Utility.TrimNulls(Encoding.UTF8.GetString(buffer, offset, count));
if (string.IsNullOrEmpty(str))
{
return 0L;
}
return Convert.ToInt64(str, 8);
}
internal static int RecalculateAltChecksum(byte[] buf)
{
Encoding.UTF8.GetBytes(" ").CopyTo(buf, 0x94);
int num = 0;
foreach (byte num2 in buf)
{
if ((num2 & 0x80) == 0x80)
{
num -= num2 ^ 0x80;
}
else
{
num += num2;
}
}
return num;
}
internal static int RecalculateChecksum(byte[] buf)
{
Encoding.UTF8.GetBytes(" ").CopyTo(buf, 0x94);
int num = 0;
foreach (byte num2 in buf)
{
num += num2;
}
return num;
}
internal void Write(Stream output)
{
byte[] buffer = new byte[0x200];
WriteOctalBytes(0x1ffL, buffer, 100, 8);
WriteOctalBytes(0L, buffer, 0x6c, 8);
WriteOctalBytes(0L, buffer, 0x74, 8);
if (this.Name.Length > 100)
{
WriteStringBytes("././@LongLink", buffer, 0, 100);
buffer[0x9c] = 0x4c;
WriteOctalBytes((long) (this.Name.Length + 1), buffer, 0x7c, 12);
}
else
{
WriteStringBytes(this.Name, buffer, 0, 100);
WriteOctalBytes(this.Size, buffer, 0x7c, 12);
TimeSpan span = (TimeSpan) (this.LastModifiedTime.ToUniversalTime() - Epoch);
long totalSeconds = (long) span.TotalSeconds;
WriteOctalBytes(totalSeconds, buffer, 0x88, 12);
buffer[0x9c] = (byte) this.EntryType;
if (this.Size >= 0x1ffffffffL)
{
byte[] bytes = BitConverter.GetBytes(Utility.HostToNetworkOrder(this.Size));
byte[] array = new byte[12];
bytes.CopyTo(array, (int) (12 - bytes.Length));
array[0] = (byte) (array[0] | 0x80);
array.CopyTo(buffer, 0x7c);
}
}
WriteOctalBytes((long) RecalculateChecksum(buffer), buffer, 0x94, 8);
output.Write(buffer, 0, buffer.Length);
if (this.Name.Length > 100)
{
this.WriteLongFilenameHeader(output);
this.Name = this.Name.Substring(0, 100);
this.Write(output);
}
}
private void WriteLongFilenameHeader(Stream output)
{
byte[] bytes = ArchiveEncoding.Default.GetBytes(this.Name);
output.Write(bytes, 0, bytes.Length);
int count = 0x200 - (bytes.Length % 0x200);
if (count == 0)
{
count = 0x200;
}
output.Write(new byte[count], 0, count);
}
private static void WriteOctalBytes(long value, byte[] buffer, int offset, int length)
{
int num2;
string str = Convert.ToString(value, 8);
int num = (length - str.Length) - 1;
for (num2 = 0; num2 < num; num2++)
{
buffer[offset + num2] = 0x20;
}
for (num2 = 0; num2 < str.Length; num2++)
{
buffer[(offset + num2) + num] = (byte) str[num2];
}
}
private static void WriteStringBytes(string name, byte[] buffer, int offset, int length)
{
int num = 0;
while ((num < (length - 1)) && (num < name.Length))
{
buffer[offset + num] = (byte) name[num];
num++;
}
while (num < length)
{
buffer[offset + num] = 0;
num++;
}
}
public long? DataStartPosition
{
[CompilerGenerated]
get
{
return this._DataStartPosition_k__BackingField;
}
[CompilerGenerated]
set
{
this._DataStartPosition_k__BackingField = value;
}
}
internal SharpCompress.Common.Tar.Headers.EntryType EntryType
{
[CompilerGenerated]
get
{
return this._EntryType_k__BackingField;
}
[CompilerGenerated]
set
{
this._EntryType_k__BackingField = value;
}
}
internal DateTime LastModifiedTime
{
[CompilerGenerated]
get
{
return this._LastModifiedTime_k__BackingField;
}
[CompilerGenerated]
set
{
this._LastModifiedTime_k__BackingField = value;
}
}
public string Magic
{
[CompilerGenerated]
get
{
return this._Magic_k__BackingField;
}
[CompilerGenerated]
set
{
this._Magic_k__BackingField = value;
}
}
internal string Name
{
[CompilerGenerated]
get
{
return this._Name_k__BackingField;
}
[CompilerGenerated]
set
{
this._Name_k__BackingField = value;
}
}
internal Stream PackedStream
{
[CompilerGenerated]
get
{
return this._PackedStream_k__BackingField;
}
[CompilerGenerated]
set
{
this._PackedStream_k__BackingField = value;
}
}
internal long Size
{
[CompilerGenerated]
get
{
return this._Size_k__BackingField;
}
[CompilerGenerated]
set
{
this._Size_k__BackingField = value;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CocosSharp;
namespace tests
{
public class BaseDrawNodeTest : TestNavigationLayer
{
#region Properties
public override string Title
{
get { return "Draw Demo"; }
}
#endregion Properties
#region Constructors
public BaseDrawNodeTest()
{
}
#endregion Constructors
#region Setup content
public virtual void Setup()
{
}
#endregion Setup content
#region Callbacks
public override void RestartCallback(object sender)
{
CCScene s = new DrawPrimitivesTestScene();
s.AddChild(DrawPrimitivesTestScene.restartTestAction());
Director.ReplaceScene(s);
}
public override void NextCallback(object sender)
{
CCScene s = new DrawPrimitivesTestScene();
s.AddChild(DrawPrimitivesTestScene.nextTestAction());
Director.ReplaceScene(s);
}
public override void BackCallback(object sender)
{
CCScene s = new DrawPrimitivesTestScene();
s.AddChild(DrawPrimitivesTestScene.backTestAction());
Director.ReplaceScene(s);
}
#endregion Callbacks
}
public class DrawPrimitivesWithRenderTextureTest : BaseDrawNodeTest
{
#region Setup content
public override void OnEnter()
{
base.OnEnter();
var windowSize = Layer.VisibleBoundsWorldspace.Size;
CCRenderTexture text = new CCRenderTexture(windowSize,windowSize);
AddChild(text, 24);
CCDrawNode draw = new CCDrawNode();
text.AddChild(draw, 10);
text.Begin();
// Draw polygons
CCPoint[] points = new CCPoint[]
{
new CCPoint(windowSize.Height / 4, 0),
new CCPoint(windowSize.Width, windowSize.Height / 5),
new CCPoint(windowSize.Width / 3 * 2, windowSize.Height)
};
draw.DrawPolygon(points, points.Length, new CCColor4F(1, 0, 0, 0.5f), 4, new CCColor4F(0, 0, 1, 1));
text.End();
}
#endregion Setup content
}
public class DrawPrimitivesTest : BaseDrawNodeTest
{
protected override void Draw()
{
base.Draw();
CCSize s = Layer.VisibleBoundsWorldspace.Size;
CCDrawingPrimitives.Begin();
// *NOTE* Using the Director.ContentScaleFactor for now until we work something out with the initialization
// CCDrawPriitives should be able to do this converstion themselves.
// draw a simple line
// The default state is:
// Line Width: 1
// color: 255,255,255,255 (white, non-transparent)
// Anti-Aliased
// glEnable(GL_LINE_SMOOTH);
CCDrawingPrimitives.LineWidth = 1 ;
CCDrawingPrimitives.DrawLine(CCVisibleRect.LeftBottom, CCVisibleRect.RightTop);
// line: color, width, aliased
CCDrawingPrimitives.LineWidth = 5 ;
CCDrawingPrimitives.DrawColor = CCColor4B.Red;
CCDrawingPrimitives.DrawLine(CCVisibleRect.LeftTop, CCVisibleRect.RightBottom);
// TIP:
// If you are going to use always thde same color or width, you don't
// need to call it before every draw
//
// Remember: OpenGL is a state-machine.
// draw big point in the center
CCDrawingPrimitives.PointSize = 64 ;
CCDrawingPrimitives.DrawColor = new CCColor4B(0, 0, 255, 128);
CCDrawingPrimitives.DrawPoint(CCVisibleRect.Center);
// draw 4 small points
CCPoint[] points = {new CCPoint(60, 60), new CCPoint(70, 70), new CCPoint(60, 70), new CCPoint(70, 60)};
CCDrawingPrimitives.PointSize = 8 ;
CCDrawingPrimitives.DrawColor = new CCColor4B(0, 255, 255, 255);
CCDrawingPrimitives.DrawPoints(points);
// draw a green circle with 10 segments
CCDrawingPrimitives.LineWidth = 16 ;
CCDrawingPrimitives.DrawColor = CCColor4B.Green;
CCDrawingPrimitives.DrawCircle(CCVisibleRect.Center, 100, 0, 10, false);
// draw a green circle with 50 segments with line to center
CCDrawingPrimitives.LineWidth = 2 ;
CCDrawingPrimitives.DrawColor = new CCColor4B(0, 255, 255, 255);
CCDrawingPrimitives.DrawCircle(CCVisibleRect.Center, 50, CCMacros.CCDegreesToRadians(45), 50, true);
// draw a pink solid circle with 50 segments
CCDrawingPrimitives.LineWidth = 2 ;
CCDrawingPrimitives.DrawColor = new CCColor4B(255, 0, 255, 255);
CCDrawingPrimitives.DrawSolidCircle(CCVisibleRect.Center + new CCPoint(140, 0), 40, CCMacros.CCDegreesToRadians(90), 50);
// draw an arc within rectangular region
CCDrawingPrimitives.LineWidth = 5 ;
CCDrawingPrimitives.DrawArc(new CCRect(200, 100, 100, 200), 0, 180, CCColor4B.AliceBlue);
// draw an ellipse within rectangular region
CCDrawingPrimitives.DrawEllipse(new CCRect(100, 100, 100, 200), CCColor4B.Red);
// draw an arc within rectangular region
CCDrawingPrimitives.DrawPie(new CCRect(350, 0, 100, 100), 20, 100, CCColor4B.AliceBlue);
// draw an arc within rectangular region
CCDrawingPrimitives.DrawPie(new CCRect(347, -5, 100, 100), 120, 260, CCColor4B.Aquamarine);
// open yellow poly
CCPoint[] vertices =
{
new CCPoint(0, 0), new CCPoint(50, 50), new CCPoint(100, 50), new CCPoint(100, 100),
new CCPoint(50, 100)
};
CCDrawingPrimitives.LineWidth = 10 ;
CCDrawingPrimitives.DrawColor = CCColor4B.Yellow;
CCDrawingPrimitives.DrawPoly(vertices, 5, false, new CCColor4B(255, 255, 0, 255));
// filled poly
CCDrawingPrimitives.LineWidth = 1 ;
CCPoint[] filledVertices =
{
new CCPoint(0, 120), new CCPoint(50, 120), new CCPoint(50, 170),
new CCPoint(25, 200), new CCPoint(0, 170)
};
CCDrawingPrimitives.DrawSolidPoly(filledVertices, new CCColor4F(0.5f, 0.5f, 1, 1 ));
// closed purple poly
CCDrawingPrimitives.LineWidth = 2 ;
CCDrawingPrimitives.DrawColor = new CCColor4B(255, 0, 255, 255);
CCPoint[] vertices2 = {new CCPoint(30, 130), new CCPoint(30, 230), new CCPoint(50, 200)};
CCDrawingPrimitives.DrawPoly(vertices2, true);
// draw quad bezier path
CCDrawingPrimitives.DrawQuadBezier(new CCPoint(0, s.Height),
new CCPoint(s.Width / 2, s.Height / 2),
new CCPoint(s.Width, s.Height),
50,
new CCColor4B(255, 0, 255, 255));
// draw cubic bezier path
CCDrawingPrimitives.DrawCubicBezier(new CCPoint(s.Width / 2, s.Height / 2),
new CCPoint(s.Width / 2 + 30, s.Height / 2 + 50),
new CCPoint(s.Width / 2 + 60, s.Height / 2 - 50),
new CCPoint(s.Width, s.Height / 2), 100);
//draw a solid polygon
CCPoint[] vertices3 =
{
new CCPoint(60, 160), new CCPoint(70, 190), new CCPoint(100, 190),
new CCPoint(90, 160)
};
CCDrawingPrimitives.DrawSolidPoly(vertices3, 4, new CCColor4F(1,1,0,1));
CCDrawingPrimitives.End();
}
public override string Title
{
get
{
return "Draw Primitives";
}
}
public override string Subtitle
{
get
{
return "Drawing Primitives. Use DrawNode instead";
}
}
}
public class DrawNodeTest : BaseDrawNodeTest
{
#region Setup content
CCDrawNode draw;
public DrawNodeTest()
{
draw = new CCDrawNode();
draw.BlendFunc = CCBlendFunc.NonPremultiplied;
AddChild(draw, 10);
}
public override void OnEnter()
{
base.OnEnter();
CCSize windowSize = Layer.VisibleBoundsWorldspace.Size;
CCDrawNode draw = new CCDrawNode();
AddChild(draw, 10);
var s = windowSize;
// Draw 10 circles
for (int i = 0; i < 10; i++)
{
draw.DrawDot(s.Center, 10 * (10 - i),
new CCColor4F(CCRandom.Float_0_1(), CCRandom.Float_0_1(), CCRandom.Float_0_1(), 1));
}
// Draw polygons
CCPoint[] points = new CCPoint[]
{
new CCPoint(windowSize.Height / 4, 0),
new CCPoint(windowSize.Width, windowSize.Height / 5),
new CCPoint(windowSize.Width / 3 * 2, windowSize.Height)
};
draw.DrawPolygon(points, points.Length, new CCColor4F(1.0f, 0, 0, 0.5f), 4, new CCColor4F(0, 0, 1, 1));
// star poly (triggers buggs)
{
const float o = 80;
const float w = 20;
const float h = 50;
CCPoint[] star = new CCPoint[]
{
new CCPoint(o + w, o - h), new CCPoint(o + w * 2, o), // lower spike
new CCPoint(o + w * 2 + h, o + w), new CCPoint(o + w * 2, o + w * 2), // right spike
};
draw.DrawPolygon(star, star.Length, new CCColor4F(1, 0, 0, 0.5f), 1, new CCColor4F(0, 0, 1, 1));
}
// star poly (doesn't trigger bug... order is important un tesselation is supported.
{
const float o = 180;
const float w = 20;
const float h = 50;
var star = new CCPoint[]
{
new CCPoint(o, o), new CCPoint(o + w, o - h), new CCPoint(o + w * 2, o), // lower spike
new CCPoint(o + w * 2 + h, o + w), new CCPoint(o + w * 2, o + w * 2), // right spike
new CCPoint(o + w, o + w * 2 + h), new CCPoint(o, o + w * 2), // top spike
new CCPoint(o - h, o + w), // left spike
};
draw.DrawPolygon(star, star.Length, new CCColor4F(1, 0, 0, 0.5f), 1, new CCColor4F(0, 0, 1, 1));
}
// Draw segment
draw.DrawSegment(new CCPoint(20, windowSize.Height), new CCPoint(20, windowSize.Height / 2), 10, new CCColor4F(0, 1, 0, 1));
draw.DrawSegment(new CCPoint(10, windowSize.Height / 2), new CCPoint(windowSize.Width / 2, windowSize.Height / 2), 40,
new CCColor4F(1, 0, 1, 0.5f));
}
#endregion Setup content
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Symbology.Forms.dll
// Description: The Windows Forms user interface layer for the DotSpatial.Symbology library.
// ********************************************************************************************************
//
// The Original Code is from MapWindow.dll version 6.0
//
// The Initial Developer of this Original Code is Ted Dunsford. Created 5/22/2009 11:25:31 AM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
//
// ********************************************************************************************************
using System;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Design;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
namespace DotSpatial.Symbology.Forms
{
/// <summary>
/// A Color lever is a control that shows a color on a plate, and has a knob on a lever on the side of the plate for
/// controling the opacity, where the up position is opaque and the bottom position is transparent.
/// </summary>
[DefaultEvent("ColorChanging"),
ToolboxBitmap(typeof(ColorLever), "GradientControls.ColorLever.ico")]
public class ColorLever : Control
{
#region events
/// <summary>
/// Occurs whenever either the color or the opacity for this control is adjusted
/// </summary>
public event EventHandler ColorChanged;
/// <summary>
/// Occurs as the opacity is being adjusted by the slider, but while the slider is
/// still being dragged.
/// </summary>
public event EventHandler OpacityChanging;
/// <summary>
/// Because the color is changed any time the opacity is changed, while the lever is being
/// adjusted, the color is being updated as well as the opacity. Therefore, this is fired
/// both when the color is changed directly or when the slider is being adjusted.
/// </summary>
public event EventHandler ColorChanging;
#endregion
#region Private Variables
private readonly ToolTip _ttHelp;
private double _angle;
private int _barLength;
private int _barWidth;
private int _borderWidth;
private Color _color;
private bool _flip;
private bool _isDragging;
private Color _knobColor;
private int _knobRadius;
#endregion
#region Constructors
/// <summary>
/// Creates a new instance of ColorLever
/// </summary>
public ColorLever()
{
_color = SymbologyGlobal.RandomLightColor(1F);
_borderWidth = 5;
_knobRadius = 7;
_barLength = 5;
_barWidth = 5;
_knobColor = Color.SteelBlue;
_ttHelp = new ToolTip();
_ttHelp.SetToolTip(this, "Click to change the color, or rotate the lever to control opacity.");
}
#endregion
#region Methods
#endregion
#region Properties
/// <summary>
/// Gets or sets the double valued angle for this control.
/// </summary>
[Editor(typeof(AngleEditor), typeof(UITypeEditor))]
public double Angle
{
get { return _angle; }
set { _angle = value; }
}
/// <summary>
/// Gets or sets the bar length
/// </summary>
public int BarLength
{
get { return _barLength; }
set { _barLength = value; }
}
/// <summary>
/// Gets or sets the width of the bar connecting the knob
/// </summary>
public int BarWidth
{
get { return _barWidth; }
set { _barWidth = value; }
}
/// <summary>
/// Gets or sets the border width
/// </summary>
public int BorderWidth
{
get { return _borderWidth; }
set { _borderWidth = value; }
}
/// <summary>
/// Gets or sets the color being displayed on the color plate.
/// </summary>
public Color Color
{
get { return _color; }
set { _color = value; }
}
/// <summary>
/// Gets or sets the radius to use for the knob on the opacity lever.
/// </summary>
public int KnobRadius
{
get { return _knobRadius; }
set { _knobRadius = value; }
}
/// <summary>
/// Gets or sets the knob color.
/// </summary>
public Color KnobColor
{
get { return _knobColor; }
set { _knobColor = value; }
}
/// <summary>
/// Gets or sets a boolean that can be used to reverse the lever, rather than simply rotating it.
/// </summary>
public bool Flip
{
get { return _flip; }
set { _flip = value; }
}
/// <summary>
/// Gets or sets the opacity for the color lever. This will also
/// adjust the knob position.
/// </summary>
[Editor(typeof(OpacityEditor), typeof(UITypeEditor))]
public float Opacity
{
get { return _color.GetOpacity(); }
set
{
_color = _color.ToTransparent(value);
Invalidate();
}
}
#endregion
#region Protected Methods
/// <summary>
/// Prevent flicker
/// </summary>
/// <param name="pevent"></param>
protected override void OnPaintBackground(PaintEventArgs pevent)
{
//base.OnPaintBackground(pevent);
}
/// <summary>
/// Draw the clipped portion
/// </summary>
/// <param name="e"></param>
protected override void OnPaint(PaintEventArgs e)
{
Rectangle clip = e.ClipRectangle;
if (clip.IsEmpty) clip = ClientRectangle;
Bitmap bmp = new Bitmap(clip.Width, clip.Height);
Graphics g = Graphics.FromImage(bmp);
g.TranslateTransform(-clip.X, -clip.Y);
g.Clip = new Region(clip);
g.Clear(BackColor);
g.SmoothingMode = SmoothingMode.AntiAlias;
OnDraw(g, clip);
g.Dispose();
e.Graphics.DrawImage(bmp, clip, new Rectangle(0, 0, clip.Width, clip.Height), GraphicsUnit.Pixel);
}
/// <summary>
/// Controls the actual drawing for this gradient slider control.
/// </summary>
/// <param name="g"></param>
/// <param name="clipRectangle"></param>
protected virtual void OnDraw(Graphics g, Rectangle clipRectangle)
{
Matrix old = g.Transform;
Matrix flipRot = g.Transform;
Transform(flipRot);
g.Transform = flipRot;
DrawColorSemicircle(g);
DrawKnob(g);
DrawLever(g, clipRectangle);
DrawHand(g);
g.Transform = old;
}
private void Transform(Matrix flipRot)
{
flipRot.Translate(Width / 2F, Height / 2F);
if (_flip)
{
flipRot.Scale(-1F, 1F);
}
flipRot.Rotate(-(float)_angle);
double ang = _angle * Math.PI / 180;
float scale = (float)(1 / (1 + (Math.Sqrt(2) - 1) * Math.Abs(Math.Sin(ang))));
flipRot.Scale(scale, scale); // A rotated square would go outside the bounds of the control, so resize.
flipRot.Translate(-Width / 2F, -Height / 2F);
}
private void DrawHand(Graphics g)
{
if (_isDragging == false) return;
Rectangle r = GetKnobBounds();
Icon ico = SymbologyFormsImages.Pan;
if (ico != null) g.DrawIcon(ico, r.X + r.Width / 2 - ico.Width / 2, r.Y + r.Height / 2 - ico.Height / 2);
}
private void DrawColorSemicircle(Graphics g)
{
Rectangle bounds = GetSemicircleBounds();
if (bounds.Width <= 0 || bounds.Height <= 0) return;
GraphicsPath gp = new GraphicsPath();
gp.AddPie(new Rectangle(-bounds.Width, bounds.Y, bounds.Width * 2, bounds.Height), -90, 180);
Rectangle roundBounds = new Rectangle(bounds.X, bounds.Y, bounds.Width, bounds.Height);
LinearGradientBrush lgb = new LinearGradientBrush(roundBounds, BackColor.Lighter(.5F), BackColor.Darker(.5F), LinearGradientMode.ForwardDiagonal);
g.FillPath(lgb, gp);
lgb.Dispose();
gp.Dispose();
gp = new GraphicsPath();
Rectangle innerRound = GetInnerSemicircleBounds();
if (innerRound.Width <= 0 || innerRound.Height <= 0) return;
gp.AddPie(new Rectangle(innerRound.X - innerRound.Width, innerRound.Y, innerRound.Width * 2, innerRound.Height), -90, 180);
PointF center = new PointF(innerRound.X + innerRound.Width / 2, innerRound.Y + innerRound.Height / 2);
float x = center.X - innerRound.Width;
float y = center.Y - innerRound.Height;
float w = innerRound.Width * 2;
float h = innerRound.Height * 2;
RectangleF circum = new RectangleF(x, y, w, h);
GraphicsPath coloring = new GraphicsPath();
coloring.AddEllipse(circum);
PathGradientBrush pgb = new PathGradientBrush(coloring);
pgb.CenterColor = _color.Lighter(.2F);
pgb.SurroundColors = new[] { _color.Darker(.2F) };
pgb.CenterPoint = new PointF(innerRound.X + 3, innerRound.Y + innerRound.Height / 3);
g.FillPath(pgb, gp);
lgb.Dispose();
gp.Dispose();
}
// calculate so that the bar can rotate freely all the way around the rotation axis.
private Rectangle GetSemicircleBounds()
{
int l = _barLength + _knobRadius * 2;
Rectangle result = new Rectangle(0, l, Width - l, Height - 2 * l);
return result;
}
private Rectangle GetInnerSemicircleBounds()
{
Rectangle result = GetSemicircleBounds();
result.X += _borderWidth;
result.Width -= _borderWidth * 2;
result.Y += _borderWidth;
result.Height -= _borderWidth * 2;
return result;
}
private Rectangle GetKnobBounds()
{
Rectangle result = new Rectangle();
result.Width = _knobRadius * 2;
result.Height = _knobRadius * 2;
double scale = Height - _knobRadius * 2 - 1;
result.Y = Convert.ToInt32((1 - _color.GetOpacity()) * scale);
double angle = GetKnobAngle();
scale = Width - _knobRadius * 2 - 1;
result.X = Convert.ToInt32(scale * Math.Sin(angle));
return result;
}
private double GetKnobAngle()
{
return Math.Acos((double)_color.GetOpacity() * 2 - 1);
}
private void DrawKnob(Graphics g)
{
Rectangle bounds = GetKnobBounds();
LinearGradientBrush lgb = new LinearGradientBrush(bounds, _knobColor.Lighter(.3F), _knobColor.Darker(.3F), LinearGradientMode.ForwardDiagonal);
g.FillEllipse(lgb, bounds);
lgb.Dispose();
}
private void DrawLever(Graphics g, Rectangle clipRectangle)
{
Point start = new Point(_knobRadius, Height / 2);
Rectangle knob = GetKnobBounds();
PointF center = new PointF(knob.X + _knobRadius, knob.Y + _knobRadius);
double dx = center.X - start.X;
double dy = center.Y - start.Y;
double len = Math.Sqrt(dx * dx + dy * dy);
double sx = dx / len;
double sy = dy / len;
PointF kJoint = new PointF((float)(center.X - sx * _knobRadius), (float)(center.Y - sy * _knobRadius));
PointF sJoint = new PointF((float)(center.X - sx * (_knobRadius + _barLength)), (float)(center.Y - sy * (_barLength + _knobRadius)));
Pen back = new Pen(BackColor.Darker(.2F), _barWidth);
back.EndCap = LineCap.Round;
back.StartCap = LineCap.Round;
Pen front = new Pen(BackColor, (float)_barWidth / 2);
front.EndCap = LineCap.Round;
front.StartCap = LineCap.Round;
g.DrawLine(back, sJoint, kJoint);
g.DrawLine(front, sJoint, kJoint);
back.Dispose();
front.Dispose();
}
/// <summary>
/// Uses the current transform matrix to calculate the coordinates in terms of the unrotated, unflipped image
/// </summary>
/// <param name="location"></param>
protected Point ClientToStandard(Point location)
{
Point result = location;
Matrix flipRot = new Matrix();
Transform(flipRot);
flipRot.Invert();
Point[] transformed = new[] { result };
flipRot.TransformPoints(transformed);
return transformed[0];
}
/// <summary>
/// Transforms a point from the standard orientation of the control into client coordinates.
/// </summary>
/// <param name="location"></param>
/// <returns></returns>
protected Point StandardToClient(Point location)
{
Point result = location;
Matrix flipRot = new Matrix();
Transform(flipRot);
Point[] transformed = new[] { result };
flipRot.TransformPoints(transformed);
return transformed[0];
}
/// <summary>
/// Handles the mouse down position for dragging the lever.
/// </summary>
/// <param name="e"></param>
protected override void OnMouseDown(MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
// turn the mouse coordinates into a standardized orientation where the control looks like the letter D
Point loc = ClientToStandard(e.Location);
Rectangle knob = GetKnobBounds();
if (knob.Contains(loc))
{
_isDragging = true;
Cursor.Hide();
}
}
base.OnMouseDown(e);
}
/// <summary>
/// Handles the mouse move event to handle when the lever is dragged.
/// </summary>
/// <param name="e"></param>
protected override void OnMouseMove(MouseEventArgs e)
{
if (_isDragging)
{
// turn the mouse coordinates into a standardized orientation where the control looks like the letter D
Point loc = ClientToStandard(e.Location);
Point center = new Point(_knobRadius, Height / 2);
double dx = loc.X - center.X;
double dy = (loc.Y - center.Y);
if (dx == 0 && dy == 0) return;
double h;
if (dx > 0)
{
h = (1 - (dy / Math.Sqrt((dx * dx + dy * dy)))) / 2;
}
else
{
if (dy > 0)
{
h = 0;
}
else
{
h = 1;
}
}
Opacity = (float)h;
Rectangle knob = GetKnobBounds();
if (knob.Contains(loc) == false)
{
// nudge the hidden mouse so that it at least stays in the balpark of the knob.
center = new Point(knob.X + knob.Width / 2, knob.Y + knob.Height / 2);
dx = loc.X - center.X;
dy = loc.Y - center.Y;
double len = Math.Sqrt(dx * dx + dy * dy);
double rx = dx / len;
double ry = dy / len;
Point c = new Point(Convert.ToInt32(center.X + rx), Convert.ToInt32(center.Y + ry));
Point client = StandardToClient(c);
Point screen = PointToScreen(client);
Cursor.Position = screen;
}
OnOpacityChanging();
OnColorChanging();
Invalidate();
}
base.OnMouseMove(e);
}
/// <summary>
/// Controls the mouse up for ending the drag movement, or possibly launching the color dialog to change the base color.
/// </summary>
/// <param name="e"></param>
protected override void OnMouseUp(MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
if (_isDragging)
{
_isDragging = false;
Rectangle knob = GetKnobBounds();
Point center = new Point(knob.X + knob.Width / 2, knob.Y + knob.Height / 2);
Point client = StandardToClient(center);
Point screen = PointToScreen(client);
Cursor.Position = screen;
Cursor.Show();
OnColorChanging();
OnColorChanged();
}
else
{
ColorDialog cdlg = new ColorDialog();
if (cdlg.ShowDialog() == DialogResult.OK)
{
_color = cdlg.Color;
OnColorChanging();
OnColorChanged();
}
}
Invalidate();
}
base.OnMouseUp(e);
}
/// <summary>
/// Fires a ColorChanged event whenver the opacity or color have been altered.
/// </summary>
protected virtual void OnColorChanged()
{
if (ColorChanged != null) ColorChanged(this, EventArgs.Empty);
}
/// <summary>
/// Fires the ColorChanging evetn whenever the color is changing either directly, or by the use of the opacity lever.
/// </summary>
protected virtual void OnColorChanging()
{
if (ColorChanging != null) ColorChanging(this, EventArgs.Empty);
}
/// <summary>
/// Fires the OpacityChanging event when the opacity is being changed
/// </summary>
protected virtual void OnOpacityChanging()
{
if (OpacityChanging != null) OpacityChanging(this, EventArgs.Empty);
}
#endregion
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using LanguageExt.Common;
using LanguageExt.Effects.Traits;
namespace LanguageExt.Pipes
{
/// <summary>
/// `Client` sends requests of type `REQ` and receives responses of type `RES`.
///
/// Clients only `request` and never `respond`.
/// </summary>
/// <remarks>
///
/// Upstream | Downstream
/// +---------+
/// | |
/// REQ <== <== Unit
/// | |
/// RES ==> ==> Void
/// | | |
/// +----|----+
/// |
/// A
/// </remarks>
public class Client<RT, REQ, RES, A> : Proxy<RT, REQ, RES, Unit, Void, A> where RT : struct, HasCancel<RT>
{
public readonly Proxy<RT, REQ, RES, Unit, Void, A> Value;
/// <summary>
/// Constructor
/// </summary>
/// <param name="value">Correctly shaped `Proxy` that represents a `Client`</param>
public Client(Proxy<RT, REQ, RES, Unit, Void, A> value) =>
Value = value;
/// <summary>
/// Calling this will effectively cast the sub-type to the base.
/// </summary>
/// <remarks>This type wraps up a `Proxy` for convenience, and so it's a `Proxy` proxy. So calling this method
/// isn't exactly the same as a cast operation, as it unwraps the `Proxy` from within. It has the same effect
/// however, and removes a level of indirection</remarks>
/// <returns>A general `Proxy` type from a more specialised type</returns>
[Pure]
public override Proxy<RT, REQ, RES, Unit, Void, A> ToProxy() =>
Value.ToProxy();
/// <summary>
/// Monadic bind operation, for chaining `Proxy` computations together.
/// </summary>
/// <param name="f">The bind function</param>
/// <typeparam name="B">The mapped bound value type</typeparam>
/// <returns>A new `Proxy` that represents the composition of this `Proxy` and the result of the bind operation</returns>
[Pure]
public override Proxy<RT, REQ, RES, Unit, Void, S> Bind<S>(Func<A, Proxy<RT, REQ, RES, Unit, Void, S>> f) =>
Value.Bind(f);
/// <summary>
/// Lifts a pure function into the `Proxy` domain, causing it to map the bound value within
/// </summary>
/// <param name="f">The map function</param>
/// <typeparam name="B">The mapped bound value type</typeparam>
/// <returns>A new `Proxy` that represents the composition of this `Proxy` and the result of the map operation</returns>
[Pure]
public override Proxy<RT, REQ, RES, Unit, Void, S> Map<S>(Func<A, S> f) =>
Value.Map(f);
/// <summary>
/// Monadic bind operation, for chaining `Client` computations together.
/// </summary>
/// <param name="f">The bind function</param>
/// <typeparam name="B">The mapped bound value type</typeparam>
/// <returns>A new `Proxy` that represents the composition of this `Proxy` and the result of the bind operation</returns>
[Pure]
public Client<RT, REQ, RES, B> Bind<B>(Func<A, Client<RT, REQ, RES, B>> f) =>
Value.Bind(f).ToClient();
/// <summary>
/// Monadic bind operation, for chaining `Client` computations together.
/// </summary>
/// <param name="f">The bind function</param>
/// <typeparam name="B">The mapped bound value type</typeparam>
/// <returns>A new `Proxy` that represents the composition of this `Proxy` and the result of the bind operation</returns>
[Pure]
public Client<RT, REQ, RES, B> SelectMany<B>(Func<A, Client<RT, REQ, RES, B>> f) =>
Value.Bind(f).ToClient();
/// <summary>
/// Monadic bind operation, for chaining `Client` computations together.
/// </summary>
/// <param name="f">The bind function</param>
/// <typeparam name="B">The mapped bound value type</typeparam>
/// <returns>A new `Proxy` that represents the composition of this `Proxy` and the result of the bind operation</returns>
[Pure]
public Client<RT, REQ, RES, C> SelectMany<B, C>(Func<A, Client<RT, REQ, RES, B>> f, Func<A, B, C> project) =>
Value.Bind(a => f(a).Map(b => project(a, b))).ToClient();
/// <summary>
/// Lifts a pure function into the `Proxy` domain, causing it to map the bound value within
/// </summary>
/// <param name="f">The map function</param>
/// <typeparam name="B">The mapped bound value type</typeparam>
/// <returns>A new `Proxy` that represents the composition of this `Proxy` and the result of the map operation</returns>
[Pure]
public new Client<RT, REQ, RES, B> Select<B>(Func<A, B> f) =>
Value.Map(f).ToClient();
/// <summary>
/// `For(body)` loops over the `Proxy p` replacing each `yield` with `body`
/// </summary>
/// <param name="body">Any `yield` found in the `Proxy` will be replaced with this function. It will be composed so
/// that the value yielded will be passed to the argument of the function. That returns a `Proxy` to continue the
/// processing of the computation</param>
/// <returns>A new `Proxy` that represents the composition of this `Proxy` and the function provided</returns>
[Pure]
public override Proxy<RT, REQ, RES, C1, C, A> For<C1, C>(Func<Void, Proxy<RT, REQ, RES, C1, C, Unit>> body) =>
Value.For(body);
/// <summary>
/// Applicative action
///
/// Invokes this `Proxy`, then the `Proxy r`
/// </summary>
/// <param name="r">`Proxy` to run after this one</param>
[Pure]
public override Proxy<RT, REQ, RES, Unit, Void, S> Action<S>(Proxy<RT, REQ, RES, Unit, Void, S> r) =>
Value.Action(r);
/// <summary>
/// Used by the various composition functions and when composing proxies with the `|` operator. You usually
/// wouldn't need to call this directly, instead either pipe them using `|` or call `Proxy.compose(lhs, rhs)`
/// </summary>
[Pure]
public override Proxy<RT, UOutA, AUInA, Unit, Void, A> ComposeRight<UOutA, AUInA>(Func<REQ, Proxy<RT, UOutA, AUInA, REQ, RES, A>> lhs) =>
Value.ComposeRight(lhs);
/// <summary>
/// Used by the various composition functions and when composing proxies with the `|` operator. You usually
/// wouldn't need to call this directly, instead either pipe them using `|` or call `Proxy.compose(lhs, rhs)`
/// </summary>
[Pure]
public override Proxy<RT, UOutA, AUInA, Unit, Void, A> ComposeRight<UOutA, AUInA>(Func<REQ, Proxy<RT, UOutA, AUInA, Unit, Void, RES>> lhs) =>
Value.ComposeRight(lhs);
/// <summary>
/// Used by the various composition functions and when composing proxies with the `|` operator. You usually
/// wouldn't need to call this directly, instead either pipe them using `|` or call `Proxy.compose(lhs, rhs)`
/// </summary>
[Pure]
public override Proxy<RT, REQ, RES, DInC, DOutC, A> ComposeLeft<DInC, DOutC>(Func<Void, Proxy<RT, Unit, Void, DInC, DOutC, A>> rhs) =>
Value.ComposeLeft(rhs);
/// <summary>
/// Used by the various composition functions and when composing proxies with the `|` operator. You usually
/// wouldn't need to call this directly, instead either pipe them using `|` or call `Proxy.compose(lhs, rhs)`
/// </summary>
[Pure]
public override Proxy<RT, REQ, RES, DInC, DOutC, A> ComposeLeft<DInC, DOutC>(Func<Void, Proxy<RT, REQ, RES, DInC, DOutC, Unit>> rhs) =>
Value.ComposeLeft(rhs);
/// <summary>
/// Reverse the arrows of the `Proxy` to find its dual.
/// </summary>
/// <returns>The dual of `this`</returns>
[Pure]
public override Proxy<RT, Void, Unit, RES, REQ, A> Reflect() =>
Value.Reflect();
/// <summary>
///
/// Observe(lift (Pure(r))) = Observe(Pure(r))
/// Observe(lift (m.Bind(f))) = Observe(lift(m.Bind(x => lift(f(x)))))
///
/// This correctness comes at a small cost to performance, so use this function sparingly.
/// This function is a convenience for low-level pipes implementers. You do not need to
/// use observe if you stick to the safe API.
/// </summary>
[Pure]
public override Proxy<RT, REQ, RES, Unit, Void, A> Observe() =>
Value.Observe();
[Pure]
public void Deconstruct(out Proxy<RT, REQ, RES, Unit, Void, A> value) =>
value = Value;
/// <summary>
/// Compose a `Server` and a `Client` together into an `Effect`. Note the `Server` is provided as a function
/// that takes a value of `REQ`. This is how we model the request coming into the `Server`. The resulting
/// `Server` computation can then call `Server.respond(response)` to reply to the `Client`.
///
/// The `Client` simply calls `Client.request(req)` to post a request to the `Server`, it is like an `awaiting`
/// that also posts. It will await the response from the `Server`.
/// </summary>
/// <param name="x">`Server`</param>
/// <param name="y">`Client`</param>
/// <returns>`Effect`</returns>
[Pure]
public static Effect<RT, A> operator |(Func<REQ, Server<RT, REQ, RES, A>> x, Client<RT, REQ, RES, A> y) =>
y.ComposeRight(x).ToEffect();
/// <summary>
/// Monadic bind operation, for chaining `Client` computations together.
/// </summary>
/// <param name="f">The bind function</param>
/// <typeparam name="B">The mapped bound value type</typeparam>
/// <returns>A new `Proxy` that represents the composition of this `Proxy` and the result of the bind operation</returns>
[Pure]
public Client<RT, REQ, RES, B> SelectMany<B>(Func<A, Release<B>> bind) =>
Value.Bind(a => bind(a).InterpretClient<RT, REQ, RES>()).ToClient();
/// <summary>
/// Monadic bind operation, for chaining `Client` computations together.
/// </summary>
/// <param name="f">The bind function</param>
/// <typeparam name="B">The mapped bound value type</typeparam>
/// <returns>A new `Proxy` that represents the composition of this `Proxy` and the result of the bind operation</returns>
[Pure]
public Client<RT, REQ, RES, C> SelectMany<B, C>(Func<A, Release<B>> bind, Func<A, B, C> project) =>
SelectMany(a => bind(a).Select(b => project(a, b)));
}
}
| |
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using System.ComponentModel;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Templates;
using Avalonia.Data;
using Avalonia.Markup.Xaml.Data;
using Avalonia.Styling;
using Xunit;
namespace Avalonia.Controls.UnitTests.Primitives
{
public class RangeBaseTests
{
[Fact]
public void Maximum_Should_Be_Coerced_To_Minimum()
{
var target = new TestRange
{
Minimum = 100,
Maximum = 50,
};
Assert.Equal(100, target.Minimum);
Assert.Equal(100, target.Maximum);
}
[Fact]
public void Value_Should_Be_Coerced_To_Range()
{
var target = new TestRange
{
Minimum = 0,
Maximum = 50,
Value = 100,
};
Assert.Equal(0, target.Minimum);
Assert.Equal(50, target.Maximum);
Assert.Equal(50, target.Value);
}
[Fact]
public void Changing_Minimum_Should_Coerce_Value_And_Maximum()
{
var target = new TestRange
{
Minimum = 0,
Maximum = 100,
Value = 50,
};
target.Minimum = 200;
Assert.Equal(200, target.Minimum);
Assert.Equal(200, target.Maximum);
Assert.Equal(200, target.Value);
}
[Fact]
public void Changing_Maximum_Should_Coerce_Value()
{
var target = new TestRange
{
Minimum = 0,
Maximum = 100,
Value = 100,
};
target.Maximum = 50;
Assert.Equal(0, target.Minimum);
Assert.Equal(50, target.Maximum);
Assert.Equal(50, target.Value);
}
[Fact]
public void Properties_Should_Not_Accept_Nan_And_Inifinity()
{
var target = new TestRange();
Assert.Throws<ArgumentException>(() => target.Minimum = double.NaN);
Assert.Throws<ArgumentException>(() => target.Minimum = double.PositiveInfinity);
Assert.Throws<ArgumentException>(() => target.Minimum = double.NegativeInfinity);
Assert.Throws<ArgumentException>(() => target.Maximum = double.NaN);
Assert.Throws<ArgumentException>(() => target.Maximum = double.PositiveInfinity);
Assert.Throws<ArgumentException>(() => target.Maximum = double.NegativeInfinity);
Assert.Throws<ArgumentException>(() => target.Value = double.NaN);
Assert.Throws<ArgumentException>(() => target.Value = double.PositiveInfinity);
Assert.Throws<ArgumentException>(() => target.Value = double.NegativeInfinity);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void SetValue_Should_Not_Cause_StackOverflow(bool useXamlBinding)
{
var viewModel = new TestStackOverflowViewModel()
{
Value = 50
};
Track track = null;
var target = new TestRange()
{
Template = new FuncControlTemplate<RangeBase>(c =>
{
track = new Track()
{
Width = 100,
Orientation = Orientation.Horizontal,
[~~Track.MinimumProperty] = c[~~RangeBase.MinimumProperty],
[~~Track.MaximumProperty] = c[~~RangeBase.MaximumProperty],
Name = "PART_Track",
Thumb = new Thumb()
};
if (useXamlBinding)
{
track.Bind(Track.ValueProperty, new Binding("Value")
{
Mode = BindingMode.TwoWay,
Source = c,
Priority = BindingPriority.Style
});
}
else
{
track[~~Track.ValueProperty] = c[~~RangeBase.ValueProperty];
}
return track;
}),
Minimum = 0,
Maximum = 100,
DataContext = viewModel
};
target.Bind(TestRange.ValueProperty, new Binding("Value") { Mode = BindingMode.TwoWay });
target.ApplyTemplate();
track.Measure(new Size(100, 0));
track.Arrange(new Rect(0, 0, 100, 0));
Assert.Equal(1, viewModel.SetterInvokedCount);
// Issues #855 and #824 were causing a StackOverflowException at this point.
target.Value = 51.001;
Assert.Equal(2, viewModel.SetterInvokedCount);
double expected = 51;
Assert.Equal(expected, viewModel.Value);
Assert.Equal(expected, target.Value);
Assert.Equal(expected, track.Value);
}
private class TestRange : RangeBase
{
}
private class TestStackOverflowViewModel : INotifyPropertyChanged
{
public int SetterInvokedCount { get; private set; }
public const int MaxInvokedCount = 1000;
private double _value;
public event PropertyChangedEventHandler PropertyChanged;
public double Value
{
get { return _value; }
set
{
if (_value != value)
{
SetterInvokedCount++;
if (SetterInvokedCount < MaxInvokedCount)
{
_value = (int)value;
if (_value > 75) _value = 75;
if (_value < 25) _value = 25;
}
else
{
_value = value;
}
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Value)));
}
}
}
}
}
}
| |
using System;
using System.Diagnostics;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace DotNetCross.NativeInts.TestsFramework
{
[TestClass]
public class nuintTest
{
[TestMethod]
public unsafe void TraceSize()
{
Trace.WriteLine($"Sizeof {nameof(nuint)}:{sizeof(nuint)}");
Console.WriteLine($"Sizeof {nameof(nuint)}:{sizeof(nuint)}");
//Assert.AreEqual(8, sizeof(nuint));
}
[TestMethod]
public void Zero()
{
Assert.AreEqual(nuint.Zero.Value, UIntPtr.Zero);
}
[TestMethod]
public void ctor_UIntPtr_0()
{
nuint ni = new nuint(UIntPtr.Zero);
Assert.AreEqual(ni.Value, UIntPtr.Zero);
}
[TestMethod]
public void ctor_UIntPtr_1()
{
nuint ni = new nuint(new UIntPtr(1));
Assert.AreEqual(ni.Value, new UIntPtr(1));
}
[TestMethod]
public void ctor_int_0()
{
nuint ni = new nuint(0);
Assert.AreEqual(ni.Value, new UIntPtr(0));
}
[TestMethod]
public void ctor_int_1()
{
nuint ni = new nuint(1);
Assert.AreEqual(ni.Value, new UIntPtr(1));
}
[TestMethod]
public void ctor_ulong_0()
{
nuint ni = new nuint(0UL);
Assert.AreEqual(ni.Value, new UIntPtr(0UL));
}
[TestMethod]
public void ctor_ulong_1()
{
nuint ni = new nuint(1UL);
Assert.AreEqual(ni.Value, new UIntPtr(1UL));
}
[TestMethod]
public unsafe void ctor_ulong_MaxValue()
{
if (sizeof(nuint) == sizeof(ulong))
{
nuint ni = new nuint(ulong.MaxValue);
Assert.AreEqual(ni.Value, new UIntPtr(ulong.MaxValue));
}
else
{
try
{
new nuint(ulong.MaxValue);
Assert.Fail("ctor for 64-bit checks overflow");
}
catch (OverflowException e)
{
Assert.IsNotNull(e);
}
}
}
[TestMethod]
public void implicit_conversion_from_UIntPtr()
{
nuint ni = new UIntPtr(42);
Assert.AreEqual(ni.Value, new UIntPtr(42));
}
[TestMethod]
public void implicit_conversion_from_int()
{
nuint ni = 42;
Assert.AreEqual(ni.Value, new UIntPtr(42));
}
[TestMethod]
public void explicit_conversion_from_long()
{
nuint ni = (nuint)42L;
Assert.AreEqual(ni.Value, new UIntPtr(42L));
}
[TestMethod]
public void implicit_conversion_to_UIntPtr()
{
UIntPtr ip = new nuint(42);
Assert.AreEqual(ip, new UIntPtr(42));
}
[TestMethod]
public void implicit_conversion_to_ulong()
{
ulong l = new nuint(42U);
Assert.AreEqual(l, 42UL);
}
[TestMethod]
public void explicit_conversion_to_uint()
{
uint i = (uint)new nuint(42u);
Assert.AreEqual(i, 42u);
}
[TestMethod]
public void explicit_conversion_to_byte_via_int()
{
Assert.AreEqual((byte)new nuint(0), (byte)0);
Assert.AreEqual((byte)new nuint(42), (byte)42);
Assert.AreEqual((byte)new nuint(255), byte.MaxValue);
Assert.AreEqual((byte)new nuint(256), (byte)0);
}
[TestMethod]
public void operator_Increment_Pre()
{
var ni = nuint.Zero;
++ni;
Assert.AreEqual(ni, new nuint(1));
}
[TestMethod]
public void operator_Increment_Post()
{
var ni = nuint.Zero;
ni++;
Assert.AreEqual(ni, new nuint(1));
}
[TestMethod]
public void operator_Decrement_Pre()
{
var ni = nuint.Zero + 1;
--ni;
Assert.AreEqual(ni, new nuint(0));
}
[TestMethod]
public void operator_Decrement_Post()
{
var ni = nuint.Zero + 1;
ni--;
Assert.AreEqual(ni, new nuint(0));
}
[TestMethod]
public void operator_UnaryPlus()
{
var ni = new nuint(1);
Assert.AreEqual(+ni, new nuint(1));
}
// NOTE: Not available
//[TestMethod]
//public void operator_UnaryNegate()
//{
// var ni = new nuint(1);
// Assert.AreEqual(-ni, new nuint(-1));
//}
[TestMethod]
public void operator_OnesComplement()
{
Assert.AreEqual(~new nuint(1), (nuint)(unchecked((ulong)-2)));
Assert.AreEqual(~new nuint(0), (nuint)(unchecked((ulong)-1)));
Assert.AreEqual(~(nuint)(unchecked((ulong)-1)), new nuint(0));
}
[TestMethod]
public void operator_Addition_nuint()
{
var ni = new nuint(1);
Assert.AreEqual(ni + new nuint(1), new nuint(2));
Assert.AreEqual(new nuint(1) + ni, new nuint(2));
}
[TestMethod]
public void operator_Addition_UIntPtr()
{
var ni = new nuint(1);
Assert.AreEqual(ni + new UIntPtr(1), new nuint(2));
Assert.AreEqual(new UIntPtr(1) + ni, new nuint(2));
}
[TestMethod]
public void operator_Addition_int()
{
var ni = new nuint(1);
Assert.AreEqual(ni + 1, new nuint(2));
Assert.AreEqual(1 + ni, new nuint(2));
}
[TestMethod]
public void operator_Subtraction_nuint()
{
var ni = new nuint(1);
Assert.AreEqual(ni - new nuint(1), new nuint(0));
Assert.AreEqual(new nuint(1) - ni, new nuint(0));
}
[TestMethod]
public void operator_Subtraction_UIntPtr()
{
var ni = new nuint(1);
Assert.AreEqual(ni - new UIntPtr(1), new nuint(0));
Assert.AreEqual(new UIntPtr(1) - ni, new nuint(0));
}
[TestMethod]
public void operator_Subtraction_int()
{
var ni = new nuint(1);
Assert.AreEqual(ni - 1, new nuint(0));
Assert.AreEqual(1 - ni, new nuint(0));
}
[TestMethod]
public void operator_Multiply_nuint()
{
var ni = new nuint(7);
Assert.AreEqual(ni * new nuint(2), new nuint(14));
}
[TestMethod]
public void operator_Multiply_UIntPtr()
{
var ni = new nuint(7);
Assert.AreEqual(ni * new UIntPtr(2), new nuint(14));
}
[TestMethod]
public void operator_Multiply_int()
{
var ni = new nuint(7);
Assert.AreEqual(ni * 2, new nuint(14));
}
[TestMethod]
public void operator_Division_nuint()
{
var ni = new nuint(7);
Assert.AreEqual(ni / new nuint(2), new nuint(3));
}
[TestMethod]
public void operator_Division_UIntPtr()
{
var ni = new nuint(7);
Assert.AreEqual(ni / new UIntPtr(2), new nuint(3));
}
[TestMethod]
public void operator_Division_int()
{
var ni = new nuint(7);
Assert.AreEqual(ni / 2, new nuint(3));
}
[TestMethod]
public void operator_Modulus_nuint()
{
var ni = new nuint(7);
Assert.AreEqual(ni % new nuint(4), new nuint(3));
}
[TestMethod]
public void operator_Modulus_UIntPtr()
{
var ni = new nuint(7);
Assert.AreEqual(ni % new UIntPtr(4), new nuint(3));
}
[TestMethod]
public void operator_Modulus_int()
{
var ni = new nuint(7);
Assert.AreEqual(ni % 4, new nuint(3));
}
[TestMethod]
public void operator_ExclusiveOr_nuint()
{
var ni = new nuint(7);
Assert.AreEqual(ni ^ new nuint(4), new nuint(3));
}
[TestMethod]
public void operator_ExclusiveOr_UIntPtr()
{
var ni = new nuint(7);
Assert.AreEqual(ni ^ new UIntPtr(4), new nuint(3));
}
[TestMethod]
public void operator_ExclusiveOr_int()
{
var ni = new nuint(7);
Assert.AreEqual(ni ^ 4, new nuint(3));
}
[TestMethod]
public void operator_BitwiseAnd_nuint()
{
var ni = new nuint(7);
Assert.AreEqual(ni & new nuint(12), new nuint(4));
}
[TestMethod]
public void operator_BitwiseAnd_UIntPtr()
{
var ni = new nuint(7);
Assert.AreEqual(ni & new UIntPtr(12), new nuint(4));
}
[TestMethod]
public void operator_BitwiseAnd_int()
{
var ni = new nuint(7);
Assert.AreEqual(ni & 12, new nuint(4));
}
[TestMethod]
public void operator_BitwiseOr_nuint()
{
var ni = new nuint(7);
Assert.AreEqual(ni | new nuint(8), new nuint(15));
}
[TestMethod]
public void operator_BitwiseOr_UIntPtr()
{
var ni = new nuint(7);
Assert.AreEqual(ni | new UIntPtr(8), new nuint(15));
}
[TestMethod]
public void operator_BitwiseOr_int()
{
var ni = new nuint(7);
Assert.AreEqual(ni | 8, new nuint(15));
}
[TestMethod]
public void operator_LeftShift_nuint()
{
var ni = new nuint(7);
Assert.AreEqual(ni << new nuint(2), new nuint(28));
}
[TestMethod]
public void operator_LeftShift_UIntPtr()
{
var ni = new nuint(7);
Assert.AreEqual(ni << new UIntPtr(2), new nuint(28));
}
[TestMethod]
public void operator_LeftShift_int()
{
var ni = new nuint(7);
Assert.AreEqual(ni << 2, new nuint(28));
}
[TestMethod]
public void operator_RightShift_nuint()
{
var ni = new nuint(28);
Assert.AreEqual(ni >> new nuint(2), new nuint(7));
}
[TestMethod]
public void operator_RightShift_UIntPtr()
{
var ni = new nuint(28);
Assert.AreEqual(ni >> new UIntPtr(2), new nuint(7));
}
[TestMethod]
public void operator_RightShift_int()
{
var ni = new nuint(28);
Assert.AreEqual(ni >> 2, new nuint(7));
}
[TestMethod]
public void operator_Equality_nuint()
{
Assert.IsTrue(nuint.Zero == new nuint(0));
Assert.IsTrue(new nuint(0) == new nuint(0));
Assert.IsTrue(new nuint(1) == new nuint(1));
Assert.IsTrue(new nuint(uint.MaxValue) == new nuint(uint.MaxValue));
Assert.IsTrue((nuint)(ulong.MaxValue) == (nuint)(ulong.MaxValue));
Assert.IsFalse(new nuint(0) == new nuint(1));
Assert.IsFalse(new nuint(1) == new nuint(0));
Assert.IsFalse(new nuint(1) == new nuint(2));
Assert.IsFalse(new nuint(2) == new nuint(1));
Assert.IsFalse(new nuint(uint.MaxValue - 1) == new nuint(uint.MaxValue));
Assert.IsFalse(new nuint(uint.MaxValue) == new nuint(uint.MaxValue - 1));
}
[TestMethod]
public unsafe void operator_Equality_uint()
{
Assert.IsTrue(nuint.Zero == 0u);
Assert.IsTrue(new nuint(0) == 0u);
Assert.IsTrue(new nuint(1) == 1u);
Assert.IsTrue(new nuint(uint.MaxValue) == uint.MaxValue);
Assert.AreEqual(sizeof(nuint) == sizeof(uint), (nuint)(ulong.MaxValue) == (unchecked((uint)ulong.MaxValue)));
Assert.IsFalse(new nuint(0) == 1u);
Assert.IsFalse(new nuint(1) == 0u);
Assert.IsFalse(new nuint(1) == 2u);
Assert.IsFalse(new nuint(2) == 1u);
Assert.IsTrue(0u == nuint.Zero);
Assert.IsTrue(0u == new nuint(0));
Assert.IsTrue(1u == new nuint(1));
Assert.IsTrue(uint.MaxValue == new nuint(uint.MaxValue));
Assert.AreEqual(sizeof(nuint) == sizeof(uint), (unchecked((uint)ulong.MaxValue) == (nuint)(ulong.MaxValue)));
Assert.IsFalse(0 == new nuint(1));
Assert.IsFalse(1 == new nuint(0));
Assert.IsFalse(1 == new nuint(2));
Assert.IsFalse(2 == new nuint(1));
}
[TestMethod]
public unsafe void operator_Equality_ulong()
{
Assert.IsTrue(nuint.Zero == 0UL);
Assert.IsTrue(new nuint(0) == 0UL);
Assert.IsTrue(new nuint(1) == 1UL);
Assert.AreEqual(sizeof(uint) != sizeof(UIntPtr), (nuint)(ulong.MaxValue) == ulong.MaxValue);
Assert.IsFalse(new nuint(0) == 1UL);
Assert.IsFalse(new nuint(1) == 0UL);
Assert.IsFalse(new nuint(1) == 2UL);
Assert.IsFalse(new nuint(2) == 1UL);
Assert.IsTrue(0UL == nuint.Zero);
Assert.IsTrue(0UL == new nuint(0));
Assert.IsTrue(1UL == new nuint(1));
Assert.AreEqual(sizeof(uint) != sizeof(UIntPtr), ulong.MaxValue == (nuint)(ulong.MaxValue));
Assert.IsFalse(0UL == new nuint(1));
Assert.IsFalse(1UL == new nuint(0));
Assert.IsFalse(1UL == new nuint(2));
Assert.IsFalse(2UL == new nuint(1));
}
[TestMethod]
public unsafe void operator_Equality_UIntPtr()
{
Assert.IsTrue(nuint.Zero == UIntPtr.Zero);
Assert.IsTrue(new nuint(0) == new UIntPtr(0));
Assert.IsTrue(new nuint(1) == new UIntPtr(1));
Assert.IsTrue(new nuint(uint.MaxValue) == new UIntPtr(uint.MaxValue));
if (sizeof(ulong) == sizeof(UIntPtr))
{
// ulong -> UIntPtr overflows if 32-bit, nuint doesn't
Assert.IsTrue((nuint)(ulong.MaxValue) == new UIntPtr(ulong.MaxValue));
}
Assert.IsFalse(new nuint(0) == new UIntPtr(1));
Assert.IsFalse(new nuint(1) == new UIntPtr(0));
Assert.IsFalse(new nuint(1) == new UIntPtr(2));
Assert.IsFalse(new nuint(2) == new UIntPtr(1));
Assert.IsTrue(UIntPtr.Zero == nuint.Zero);
Assert.IsTrue(new UIntPtr(0) == new nuint(0));
Assert.IsTrue(new UIntPtr(1) == new nuint(1));
Assert.IsTrue(new UIntPtr(uint.MaxValue) == new nuint(uint.MaxValue));
if (sizeof(ulong) == sizeof(UIntPtr))
{
// ulong -> UIntPtr overflows if 32-bit, nuint doesn't
Assert.IsTrue(new UIntPtr(ulong.MaxValue) == (nuint)(ulong.MaxValue));
}
Assert.IsFalse(new UIntPtr(0) == new nuint(1));
Assert.IsFalse(new UIntPtr(1) == new nuint(0));
Assert.IsFalse(new UIntPtr(1) == new nuint(2));
Assert.IsFalse(new UIntPtr(2) == new nuint(1));
}
[TestMethod]
public void operator_Inequality_nuint()
{
Assert.IsFalse(nuint.Zero != new nuint(0));
Assert.IsFalse(new nuint(0) != new nuint(0));
Assert.IsFalse(new nuint(1) != new nuint(1));
Assert.IsFalse(new nuint(uint.MaxValue) != new nuint(uint.MaxValue));
Assert.IsFalse((nuint)(ulong.MaxValue) != (nuint)(ulong.MaxValue));
Assert.IsTrue(new nuint(0) != new nuint(1));
Assert.IsTrue(new nuint(1) != new nuint(0));
Assert.IsTrue(new nuint(1) != new nuint(2));
Assert.IsTrue(new nuint(2) != new nuint(1));
}
[TestMethod]
public unsafe void operator_Inequality_uint()
{
Assert.IsFalse(nuint.Zero != 0u);
Assert.IsFalse(new nuint(0) != 0u);
Assert.IsFalse(new nuint(1) != 1u);
Assert.IsFalse(new nuint(uint.MaxValue) != uint.MaxValue);
Assert.AreEqual(sizeof(uint) != sizeof(UIntPtr), (nuint)(ulong.MaxValue) != (unchecked((uint)ulong.MaxValue)));
Assert.IsTrue(new nuint(0) != 1u);
Assert.IsTrue(new nuint(1) != 0u);
Assert.IsTrue(new nuint(1) != 2u);
Assert.IsTrue(new nuint(2) != 1u);
Assert.IsFalse(0u != nuint.Zero);
Assert.IsFalse(0u != new nuint(0));
Assert.IsFalse(1u != new nuint(1));
Assert.IsFalse(uint.MaxValue != new nuint(uint.MaxValue));
Assert.AreEqual(sizeof(uint) != sizeof(UIntPtr), (unchecked((uint)ulong.MaxValue) != (nuint)(ulong.MaxValue)));
Assert.IsTrue(0u != new nuint(1));
Assert.IsTrue(1u != new nuint(0));
Assert.IsTrue(1u != new nuint(2));
Assert.IsTrue(2u != new nuint(1));
}
[TestMethod]
public unsafe void operator_Inequality_ulong()
{
Assert.IsFalse(nuint.Zero != 0UL);
Assert.IsFalse(new nuint(0) != 0UL);
Assert.IsFalse(new nuint(1) != 1UL);
Assert.AreEqual(sizeof(uint) == sizeof(UIntPtr), (nuint)(ulong.MaxValue) != ulong.MaxValue);
Assert.IsTrue(new nuint(0) != 1UL);
Assert.IsTrue(new nuint(1) != 0UL);
Assert.IsTrue(new nuint(1) != 2UL);
Assert.IsTrue(new nuint(2) != 1UL);
Assert.IsFalse(0UL != nuint.Zero);
Assert.IsFalse(0UL != new nuint(0));
Assert.IsFalse(1UL != new nuint(1));
Assert.AreEqual(sizeof(uint) == sizeof(UIntPtr), ulong.MaxValue != (nuint)(ulong.MaxValue));
Assert.IsTrue(0UL != new nuint(1));
Assert.IsTrue(1UL != new nuint(0));
Assert.IsTrue(1UL != new nuint(2));
Assert.IsTrue(2UL != new nuint(1));
}
[TestMethod]
public unsafe void operator_Inequality_UIntPtr()
{
Assert.IsFalse(nuint.Zero != UIntPtr.Zero);
Assert.IsFalse(new nuint(0) != new UIntPtr(0));
Assert.IsFalse(new nuint(1) != new UIntPtr(1));
Assert.IsFalse(new nuint(uint.MaxValue) != new UIntPtr(uint.MaxValue));
if (sizeof(ulong) == sizeof(UIntPtr))
{
// ulong -> UIntPtr overflows if 32-bit, nuint doesn't
Assert.IsFalse((nuint)(ulong.MaxValue) != new UIntPtr(ulong.MaxValue));
}
Assert.IsTrue(new nuint(0) != new UIntPtr(1));
Assert.IsTrue(new nuint(1) != new UIntPtr(0));
Assert.IsTrue(new nuint(1) != new UIntPtr(2));
Assert.IsTrue(new nuint(2) != new UIntPtr(1));
Assert.IsFalse(UIntPtr.Zero != nuint.Zero);
Assert.IsFalse(new UIntPtr(0) != new nuint(0));
Assert.IsFalse(new UIntPtr(1) != new nuint(1));
Assert.IsFalse(new UIntPtr(uint.MaxValue) != new nuint(uint.MaxValue));
if (sizeof(ulong) == sizeof(UIntPtr))
{
// ulong -> UIntPtr overflows if 32-bit, nuint doesn't
Assert.IsFalse(new UIntPtr(ulong.MaxValue) != (nuint)(ulong.MaxValue));
}
Assert.IsTrue(new UIntPtr(0) != new nuint(1));
Assert.IsTrue(new UIntPtr(1) != new nuint(0));
Assert.IsTrue(new UIntPtr(1) != new nuint(2));
Assert.IsTrue(new UIntPtr(2) != new nuint(1));
}
[TestMethod]
public void operator_GreaterThan_nuint()
{
Assert.IsFalse(nuint.Zero > new nuint(0));
Assert.IsFalse(new nuint(0) > new nuint(0));
Assert.IsFalse(new nuint(1) > new nuint(1));
Assert.IsFalse(new nuint(uint.MaxValue) > new nuint(uint.MaxValue));
Assert.IsFalse((nuint)(ulong.MaxValue) > (nuint)(ulong.MaxValue));
Assert.IsFalse(new nuint(0) > new nuint(1));
Assert.IsFalse(new nuint(1) > new nuint(2));
Assert.IsFalse((nuint)(uint.MaxValue - 1) > (nuint)(uint.MaxValue));
Assert.IsTrue(new nuint(1) > new nuint(0));
Assert.IsTrue(new nuint(2) > new nuint(1));
Assert.IsTrue((nuint)(uint.MaxValue) > (nuint)(uint.MaxValue - 1));
}
[TestMethod]
public unsafe void operator_GreaterThan_uint()
{
// nuint left, uint right
Assert.IsFalse(nuint.Zero > 0u);
Assert.IsFalse(new nuint(0) > 0u);
Assert.IsFalse(new nuint(1) > 1u);
Assert.IsFalse(new nuint(uint.MaxValue) > uint.MaxValue);
Assert.IsFalse(new nuint(0) > 1u);
Assert.IsFalse(new nuint(1) > 2u);
Assert.IsFalse((nuint)(uint.MaxValue - 1) > uint.MaxValue);
Assert.IsTrue(new nuint(1) > 0u);
Assert.IsTrue(new nuint(2) > 1u);
Assert.IsTrue((nuint)(uint.MaxValue) > uint.MaxValue - 1);
Assert.IsTrue(ulong.MaxValue > (ulong)uint.MaxValue);
Assert.AreEqual(sizeof(ulong) == sizeof(UIntPtr), ((nuint)ulong.MaxValue) > (nuint)uint.MaxValue);
// uint left, nuint right
Assert.IsFalse(0u > new nuint(0));
Assert.IsFalse(0u > new nuint(0));
Assert.IsFalse(1u > new nuint(1));
Assert.IsFalse(uint.MaxValue > new nuint(uint.MaxValue));
Assert.IsFalse(0u > new nuint(1));
Assert.IsFalse(1u > new nuint(2));
Assert.IsFalse((uint.MaxValue - 1) > new nuint(uint.MaxValue));
Assert.IsTrue(1u > new nuint(0));
Assert.IsTrue(2u > new nuint(1));
Assert.IsTrue(uint.MaxValue > new nuint(uint.MaxValue - 1));
Assert.AreEqual(false, uint.MaxValue > (nuint)(ulong.MaxValue));
}
[TestMethod]
public unsafe void operator_GreaterThan_ulong()
{
// nuint left, ulong right
Assert.IsFalse(nuint.Zero > 0UL);
Assert.IsFalse(new nuint(0) > 0UL);
Assert.IsFalse(new nuint(1) > 1UL);
Assert.IsFalse(new nuint(uint.MaxValue) > (ulong)uint.MaxValue);
Assert.IsFalse((nuint)(ulong.MaxValue) > ulong.MaxValue);
Assert.IsFalse(new nuint(0) > 1UL);
Assert.IsFalse(new nuint(1) > 2UL);
Assert.IsFalse((nuint)(uint.MaxValue - 1) > (ulong)uint.MaxValue);
Assert.IsFalse((nuint)(ulong.MaxValue - 1) > ulong.MaxValue);
Assert.IsTrue(new nuint(1) > 0UL);
Assert.IsTrue(new nuint(2) > 1UL);
Assert.IsTrue((nuint)(uint.MaxValue) > (ulong)(uint.MaxValue - 1));
Assert.AreEqual(sizeof(ulong) == sizeof(UIntPtr), (nuint)(ulong.MaxValue) > (ulong.MaxValue - 1));
Assert.AreEqual(sizeof(ulong) == sizeof(UIntPtr), (nuint)(ulong.MaxValue) > (ulong)uint.MaxValue);
Assert.AreEqual(sizeof(ulong) == sizeof(UIntPtr), (nuint)(ulong.MaxValue) > (ulong)uint.MaxValue);
// ulong left, nuint right
Assert.IsFalse(0UL > new nuint(0));
Assert.IsFalse(0UL > new nuint(0));
Assert.IsFalse(1UL > new nuint(1));
Assert.IsFalse((ulong)uint.MaxValue > new nuint(uint.MaxValue));
Assert.AreEqual(sizeof(ulong) != sizeof(UIntPtr), ulong.MaxValue > (nuint)(ulong.MaxValue));
Assert.IsFalse(0UL > new nuint(1));
Assert.IsFalse(1UL > new nuint(2));
Assert.IsFalse((ulong)(uint.MaxValue - 1) > new nuint(uint.MaxValue));
Assert.IsTrue((ulong.MaxValue - 1) > new nuint(uint.MaxValue));
Assert.IsTrue(1UL > new nuint(0));
Assert.IsTrue(2UL > new nuint(1));
Assert.IsTrue((ulong)uint.MaxValue > new nuint(uint.MaxValue - 1));
Assert.IsTrue(ulong.MaxValue > (nuint)(ulong.MaxValue - 1));
Assert.IsFalse((ulong)uint.MaxValue > (nuint)(ulong.MaxValue));
}
[TestMethod]
public unsafe void operator_GreaterThan_UIntPtr()
{
// nuint left, UIntPtr right
Assert.IsFalse(nuint.Zero > new UIntPtr(0L));
Assert.IsFalse(new nuint(0) > new UIntPtr(0));
Assert.IsFalse(new nuint(1) > new UIntPtr(1));
Assert.IsFalse(new nuint(uint.MaxValue) > new UIntPtr((ulong)uint.MaxValue));
if (sizeof(ulong) == sizeof(UIntPtr))
{
Assert.IsFalse((nuint)(ulong.MaxValue) > new UIntPtr(ulong.MaxValue));
}
Assert.IsFalse(new nuint(0) > new UIntPtr(1));
Assert.IsFalse(new nuint(1) > new UIntPtr(2));
Assert.IsFalse((nuint)(uint.MaxValue - 1) > new UIntPtr((ulong)uint.MaxValue));
if (sizeof(ulong) == sizeof(UIntPtr))
{
Assert.IsFalse((nuint)(ulong.MaxValue - 1) > new UIntPtr(ulong.MaxValue));
}
Assert.IsTrue(new nuint(1) > new UIntPtr(0));
Assert.IsTrue(new nuint(2) > new UIntPtr(1));
Assert.IsTrue((nuint)(uint.MaxValue) > new UIntPtr((ulong)(uint.MaxValue - 1)));
if (sizeof(ulong) == sizeof(UIntPtr))
{
Assert.AreEqual(sizeof(ulong) == sizeof(UIntPtr), (nuint)(ulong.MaxValue) > new UIntPtr((ulong.MaxValue - 1)));
}
Assert.AreEqual(sizeof(ulong) == sizeof(UIntPtr), (nuint)(ulong.MaxValue) > new UIntPtr((ulong)uint.MaxValue));
Assert.AreEqual(sizeof(ulong) == sizeof(UIntPtr), (nuint)(ulong.MaxValue) > new UIntPtr((ulong)uint.MaxValue));
// UIntPtr left, nuint right
Assert.IsFalse(new UIntPtr(0) > new nuint(0));
Assert.IsFalse(new UIntPtr(1) > new nuint(1));
Assert.IsFalse((ulong)uint.MaxValue > new nuint(uint.MaxValue));
Assert.AreEqual(sizeof(ulong) != sizeof(UIntPtr), ulong.MaxValue > (nuint)(ulong.MaxValue));
Assert.IsFalse((nuint)(ulong.MaxValue) > ulong.MaxValue);
Assert.IsFalse(new UIntPtr(0) > new nuint(1));
Assert.IsFalse(new UIntPtr(1) > new nuint(2));
Assert.IsFalse((ulong)(uint.MaxValue - 1) > new nuint(uint.MaxValue));
Assert.IsTrue((ulong.MaxValue - 1) > new nuint(uint.MaxValue));
Assert.IsTrue(new UIntPtr(1) > new nuint(0));
Assert.IsTrue(new UIntPtr(2) > new nuint(1));
Assert.IsTrue((ulong)uint.MaxValue > new nuint(uint.MaxValue - 1));
Assert.IsTrue(ulong.MaxValue > (nuint)(ulong.MaxValue - 1));
Assert.IsFalse((ulong)uint.MaxValue > (nuint)(ulong.MaxValue));
}
[TestMethod]
public void operator_GreaterThanOrEqual_nuint()
{
Assert.IsTrue(nuint.Zero >= new nuint(0));
Assert.IsTrue(new nuint(0) >= new nuint(0));
Assert.IsTrue(new nuint(1) >= new nuint(1));
Assert.IsTrue(new nuint(uint.MaxValue) >= new nuint(uint.MaxValue));
Assert.IsTrue((nuint)(ulong.MaxValue) >= (nuint)(ulong.MaxValue));
Assert.IsFalse(new nuint(0) >= new nuint(1));
Assert.IsFalse(new nuint(1) >= new nuint(2));
Assert.IsFalse((nuint)(uint.MaxValue - 1) >= (nuint)(uint.MaxValue));
Assert.IsTrue(new nuint(1) >= new nuint(0));
Assert.IsTrue(new nuint(2) >= new nuint(1));
Assert.IsTrue((nuint)(uint.MaxValue) >= (nuint)(uint.MaxValue - 1));
}
[TestMethod]
public unsafe void operator_GreaterThanOrEqual_int()
{
// nuint left, uint right
Assert.IsTrue(nuint.Zero >= 0);
Assert.IsTrue(new nuint(0) >= 0);
Assert.IsTrue(new nuint(1) >= 1);
Assert.IsTrue(new nuint(uint.MaxValue) >= uint.MaxValue);
Assert.IsFalse(new nuint(0) >= 1);
Assert.IsFalse(new nuint(1) >= 2);
Assert.IsFalse((nuint)(uint.MaxValue - 1) >= uint.MaxValue);
Assert.IsTrue(new nuint(1) >= 0);
Assert.IsTrue(new nuint(2) >= 1);
Assert.IsTrue((nuint)(uint.MaxValue) >= uint.MaxValue - 1);
Assert.IsTrue((nuint)(ulong.MaxValue) >= uint.MaxValue);
// uint left, nuint right
Assert.IsTrue(0 >= new nuint(0));
Assert.IsTrue(0 >= new nuint(0));
Assert.IsTrue(1 >= new nuint(1));
Assert.IsTrue(uint.MaxValue >= new nuint(uint.MaxValue));
Assert.IsFalse(0 >= new nuint(1));
Assert.IsFalse(1 >= new nuint(2));
Assert.IsFalse((uint.MaxValue - 1) >= new nuint(uint.MaxValue));
Assert.IsTrue(1 >= new nuint(0));
Assert.IsTrue(2 >= new nuint(1));
Assert.IsTrue(uint.MaxValue >= new nuint(uint.MaxValue - 1));
Assert.AreEqual(sizeof(ulong) != sizeof(UIntPtr), uint.MaxValue >= (nuint)(ulong.MaxValue));
Assert.AreEqual(sizeof(ulong) != sizeof(UIntPtr), uint.MaxValue >= (nuint)(ulong.MaxValue));
}
[TestMethod]
public unsafe void operator_GreaterThanOrEqual_long()
{
// nuint left, ulong right
Assert.IsTrue(nuint.Zero >= 0L);
Assert.IsTrue(new nuint(0) >= 0L);
Assert.IsTrue(new nuint(1) >= 1L);
Assert.IsTrue(new nuint(uint.MaxValue) >= (ulong)uint.MaxValue);
Assert.AreEqual(sizeof(ulong) == sizeof(UIntPtr), (nuint)(ulong.MaxValue) >= ulong.MaxValue);
Assert.IsFalse(new nuint(0) >= 1L);
Assert.IsFalse(new nuint(1) >= 2L);
Assert.IsFalse((nuint)(uint.MaxValue - 1) >= (ulong)uint.MaxValue);
Assert.IsFalse((nuint)(ulong.MaxValue - 1) >= ulong.MaxValue);
Assert.IsTrue(new nuint(1) >= 0L);
Assert.IsTrue(new nuint(2) >= 1L);
Assert.IsTrue((nuint)(uint.MaxValue) >= (ulong)(uint.MaxValue - 1));
Assert.AreEqual(sizeof(ulong) == sizeof(UIntPtr), (nuint)(ulong.MaxValue) >= (ulong.MaxValue - 1));
Assert.IsTrue((nuint)(ulong.MaxValue) >= (ulong)uint.MaxValue);
// ulong left, nuint right
Assert.IsTrue(0L >= new nuint(0));
Assert.IsTrue(0L >= new nuint(0));
Assert.IsTrue(1L >= new nuint(1));
Assert.IsTrue((ulong)uint.MaxValue >= new nuint(uint.MaxValue));
Assert.IsTrue(ulong.MaxValue >= (nuint)(ulong.MaxValue));
Assert.IsFalse(0L >= new nuint(1));
Assert.IsFalse(1L >= new nuint(2));
Assert.IsFalse((ulong)(uint.MaxValue - 1) >= new nuint(uint.MaxValue));
Assert.IsTrue((ulong.MaxValue - 1) >= new nuint(uint.MaxValue));
Assert.IsTrue(1L >= new nuint(0));
Assert.IsTrue(2L >= new nuint(1));
Assert.IsTrue((ulong)uint.MaxValue >= new nuint(uint.MaxValue - 1));
Assert.IsTrue(ulong.MaxValue >= (nuint)(ulong.MaxValue - 1));
Assert.AreEqual(sizeof(ulong) != sizeof(UIntPtr), (ulong)uint.MaxValue >= (nuint)(ulong.MaxValue));
}
[TestMethod]
public unsafe void operator_GreaterThanOrEqual_UIntPtr()
{
// nuint left, UIntPtr right
Assert.IsTrue(nuint.Zero >= new UIntPtr(0L));
Assert.IsTrue(new nuint(0) >= new UIntPtr(0));
Assert.IsTrue(new nuint(1) >= new UIntPtr(1));
Assert.IsTrue(new nuint(uint.MaxValue) >= new UIntPtr((ulong)uint.MaxValue));
if (sizeof(ulong) == sizeof(UIntPtr))
{
Assert.IsTrue((nuint)(ulong.MaxValue) >= new UIntPtr(ulong.MaxValue));
}
Assert.IsFalse(new nuint(0) >= new UIntPtr(1));
Assert.IsFalse(new nuint(1) >= new UIntPtr(2));
Assert.IsFalse((nuint)(uint.MaxValue - 1) >= new UIntPtr((ulong)uint.MaxValue));
if (sizeof(ulong) == sizeof(UIntPtr))
{
Assert.IsFalse((nuint)(ulong.MaxValue - 1) >= new UIntPtr(ulong.MaxValue));
}
Assert.IsTrue(new nuint(1) >= new UIntPtr(0));
Assert.IsTrue(new nuint(2) >= new UIntPtr(1));
Assert.IsTrue((nuint)(uint.MaxValue) >= new UIntPtr((ulong)(uint.MaxValue - 1)));
if (sizeof(ulong) == sizeof(UIntPtr))
{
Assert.AreEqual(sizeof(ulong) == sizeof(UIntPtr), (nuint)(ulong.MaxValue) >= new UIntPtr((ulong.MaxValue - 1)));
}
Assert.IsTrue((nuint)(ulong.MaxValue) >= new UIntPtr((ulong)uint.MaxValue));
// UIntPtr left, nuint right
Assert.IsTrue(new UIntPtr(0) >= new nuint(0));
Assert.IsTrue(new UIntPtr(1) >= new nuint(1));
Assert.IsTrue((ulong)uint.MaxValue >= new nuint(uint.MaxValue));
Assert.IsTrue(ulong.MaxValue >= (nuint)(ulong.MaxValue));
Assert.IsFalse(new UIntPtr(0) >= new nuint(1));
Assert.IsFalse(new UIntPtr(1) >= new nuint(2));
Assert.IsFalse((ulong)(uint.MaxValue - 1) >= new nuint(uint.MaxValue));
Assert.IsTrue((ulong.MaxValue - 1) >= new nuint(uint.MaxValue));
Assert.IsTrue(new UIntPtr(1) >= new nuint(0));
Assert.IsTrue(new UIntPtr(2) >= new nuint(1));
Assert.IsTrue((ulong)uint.MaxValue >= new nuint(uint.MaxValue - 1));
Assert.IsTrue(ulong.MaxValue >= (nuint)(ulong.MaxValue - 1));
Assert.AreEqual(sizeof(ulong) != sizeof(UIntPtr), (ulong)uint.MaxValue >= (nuint)(ulong.MaxValue));
}
[TestMethod]
public void operator_LessThan_nuint()
{
Assert.IsFalse(nuint.Zero < new nuint(0));
Assert.IsFalse(new nuint(0) < new nuint(0));
Assert.IsFalse(new nuint(1) < new nuint(1));
Assert.IsFalse(new nuint(uint.MaxValue) < new nuint(uint.MaxValue));
Assert.IsFalse((nuint)(ulong.MaxValue) < (nuint)(ulong.MaxValue));
Assert.IsTrue(new nuint(0) < new nuint(1));
Assert.IsTrue(new nuint(1) < new nuint(2));
Assert.IsTrue((nuint)(uint.MaxValue - 1) < (nuint)(uint.MaxValue));
Assert.IsFalse(new nuint(1) < new nuint(0));
Assert.IsFalse(new nuint(2) < new nuint(1));
Assert.IsFalse((nuint)(uint.MaxValue) < (nuint)(uint.MaxValue - 1));
}
[TestMethod]
public unsafe void operator_LessThan_int()
{
// nuint left, uint right
Assert.IsFalse(nuint.Zero < 0);
Assert.IsFalse(new nuint(0) < 0);
Assert.IsFalse(new nuint(1) < 1);
Assert.IsFalse(new nuint(uint.MaxValue) < uint.MaxValue);
Assert.IsTrue(new nuint(0) < 1);
Assert.IsTrue(new nuint(1) < 2);
Assert.IsTrue((nuint)(uint.MaxValue - 1) < uint.MaxValue);
Assert.IsFalse(new nuint(1) < 0);
Assert.IsFalse(new nuint(2) < 1);
Assert.IsFalse((nuint)(uint.MaxValue) < uint.MaxValue - 1);
Assert.IsFalse((nuint)(ulong.MaxValue) < uint.MaxValue);
Assert.IsFalse((nuint)(ulong.MaxValue) < uint.MaxValue);
// uint left, nuint right
Assert.IsFalse(0 < new nuint(0));
Assert.IsFalse(1 < new nuint(1));
Assert.IsFalse(uint.MaxValue < new nuint(uint.MaxValue));
Assert.IsTrue(0 < new nuint(1));
Assert.IsTrue(1 < new nuint(2));
Assert.IsTrue((uint.MaxValue - 1) < new nuint(uint.MaxValue));
Assert.IsFalse(1 < new nuint(0));
Assert.IsFalse(2 < new nuint(1));
Assert.IsFalse(uint.MaxValue < new nuint(uint.MaxValue - 1));
Assert.AreEqual(sizeof(ulong) == sizeof(UIntPtr), uint.MaxValue < (nuint)(ulong.MaxValue));
Assert.AreEqual(sizeof(ulong) == sizeof(UIntPtr), uint.MaxValue < (nuint)(ulong.MaxValue));
}
[TestMethod]
public unsafe void operator_LessThan_long()
{
// nuint left, ulong right
Assert.IsFalse(nuint.Zero < 0L);
Assert.IsFalse(new nuint(0) < 0L);
Assert.IsFalse(new nuint(1) < 1L);
Assert.IsFalse(new nuint(uint.MaxValue) < (ulong)uint.MaxValue);
Assert.AreEqual(sizeof(ulong) != sizeof(UIntPtr), (nuint)(ulong.MaxValue) < ulong.MaxValue);
Assert.IsTrue(new nuint(0) < 1L);
Assert.IsTrue(new nuint(1) < 2L);
Assert.IsTrue((nuint)(uint.MaxValue - 1) < (ulong)uint.MaxValue);
Assert.IsTrue((nuint)(ulong.MaxValue - 1) < ulong.MaxValue);
Assert.IsFalse(new nuint(1) < 0L);
Assert.IsFalse(new nuint(2) < 1L);
Assert.IsFalse((nuint)(uint.MaxValue) < (ulong)(uint.MaxValue - 1));
Assert.AreEqual(sizeof(ulong) != sizeof(UIntPtr), (nuint)(ulong.MaxValue) < (ulong.MaxValue - 1));
Assert.IsFalse((nuint)(ulong.MaxValue) < (ulong)uint.MaxValue);
// ulong left, nuint right
Assert.IsFalse(0L < new nuint(0));
Assert.IsFalse(1L < new nuint(1));
Assert.IsFalse((ulong)uint.MaxValue < new nuint(uint.MaxValue));
Assert.IsFalse(ulong.MaxValue < (nuint)(ulong.MaxValue));
Assert.IsTrue(0L < new nuint(1));
Assert.IsTrue(1L < new nuint(2));
Assert.IsTrue((ulong)(uint.MaxValue - 1) < new nuint(uint.MaxValue));
Assert.IsFalse((ulong.MaxValue - 1) < new nuint(uint.MaxValue));
Assert.IsFalse(1L < new nuint(0));
Assert.IsFalse(2L < new nuint(1));
Assert.IsFalse((ulong)uint.MaxValue < new nuint(uint.MaxValue - 1));
Assert.IsFalse(ulong.MaxValue < (nuint)(ulong.MaxValue - 1));
Assert.AreEqual(sizeof(ulong) == sizeof(UIntPtr), (ulong)uint.MaxValue < (nuint)(ulong.MaxValue));
}
[TestMethod]
public unsafe void operator_LessThan_UIntPtr()
{
// nuint left, UIntPtr right
Assert.IsFalse(nuint.Zero < new UIntPtr(0));
Assert.IsFalse(new nuint(0) < new UIntPtr(0));
Assert.IsFalse(new nuint(1) < new UIntPtr(1));
Assert.IsFalse(new nuint(uint.MaxValue) < new UIntPtr((ulong)uint.MaxValue));
if (sizeof(ulong) == sizeof(UIntPtr))
{
Assert.IsFalse((nuint)(ulong.MaxValue) < new UIntPtr(ulong.MaxValue));
}
Assert.IsTrue(new nuint(0) < new UIntPtr(1));
Assert.IsTrue(new nuint(1) < new UIntPtr(2));
Assert.IsTrue((nuint)(uint.MaxValue - 1) < new UIntPtr((ulong)uint.MaxValue));
if (sizeof(ulong) == sizeof(UIntPtr))
{
Assert.IsTrue((nuint)(ulong.MaxValue - 1) < new UIntPtr(ulong.MaxValue));
}
Assert.IsFalse(new nuint(1) < new UIntPtr(0));
Assert.IsFalse(new nuint(2) < new UIntPtr(1));
Assert.IsFalse((nuint)(uint.MaxValue) < new UIntPtr((ulong)(uint.MaxValue - 1)));
if (sizeof(ulong) == sizeof(UIntPtr))
{
Assert.IsFalse((nuint)(ulong.MaxValue) < new UIntPtr((ulong.MaxValue - 1)));
}
Assert.IsFalse((nuint)(ulong.MaxValue) < new UIntPtr((ulong)uint.MaxValue));
// UIntPtr left, nuint right
Assert.IsFalse(new UIntPtr(0) < new nuint(0));
Assert.IsFalse(new UIntPtr(1) < new nuint(1));
Assert.IsFalse((ulong)uint.MaxValue < new nuint(uint.MaxValue));
Assert.IsFalse(ulong.MaxValue < (nuint)(ulong.MaxValue));
Assert.IsTrue(new UIntPtr(0) < new nuint(1));
Assert.IsTrue(new UIntPtr(1) < new nuint(2));
Assert.IsTrue((ulong)(uint.MaxValue - 1) < new nuint(uint.MaxValue));
Assert.IsFalse((ulong.MaxValue - 1) < new nuint(uint.MaxValue));
Assert.IsFalse(new UIntPtr(1) < new nuint(0));
Assert.IsFalse(new UIntPtr(2) < new nuint(1));
Assert.IsFalse((ulong)uint.MaxValue < new nuint(uint.MaxValue - 1));
Assert.IsFalse(ulong.MaxValue < (nuint)(ulong.MaxValue - 1));
Assert.AreEqual(sizeof(ulong) == sizeof(UIntPtr), (ulong)uint.MaxValue < (nuint)(ulong.MaxValue));
}
[TestMethod]
public void operator_LessThanOrEqual_nuint()
{
Assert.IsTrue(nuint.Zero <= new nuint(0));
Assert.IsTrue(new nuint(0) <= new nuint(0));
Assert.IsTrue(new nuint(1) <= new nuint(1));
Assert.IsTrue(new nuint(uint.MaxValue) <= new nuint(uint.MaxValue));
Assert.IsTrue((nuint)(ulong.MaxValue) <= (nuint)(ulong.MaxValue));
Assert.IsTrue(new nuint(0) <= new nuint(1));
Assert.IsTrue(new nuint(1) <= new nuint(2));
Assert.IsTrue((nuint)(uint.MaxValue - 1) <= (nuint)(uint.MaxValue));
Assert.IsFalse(new nuint(1) <= new nuint(0));
Assert.IsFalse(new nuint(2) <= new nuint(1));
Assert.IsFalse((nuint)(uint.MaxValue) <= (nuint)(uint.MaxValue - 1));
}
[TestMethod]
public unsafe void operator_LessThanOrEqual_int()
{
// nuint left, uint right
Assert.IsTrue(nuint.Zero <= 0);
Assert.IsTrue(new nuint(0) <= 0);
Assert.IsTrue(new nuint(1) <= 1);
Assert.IsTrue(new nuint(uint.MaxValue) <= uint.MaxValue);
Assert.IsTrue(new nuint(0) <= 1);
Assert.IsTrue(new nuint(1) <= 2);
Assert.IsTrue((nuint)(uint.MaxValue - 1) <= uint.MaxValue);
Assert.IsFalse(new nuint(1) <= 0);
Assert.IsFalse(new nuint(2) <= 1);
Assert.IsFalse((nuint)(uint.MaxValue) <= uint.MaxValue - 1);
Assert.AreEqual(sizeof(ulong) != sizeof(UIntPtr), (nuint)(ulong.MaxValue) <= uint.MaxValue);
Assert.AreEqual(sizeof(ulong) != sizeof(UIntPtr), (nuint)(ulong.MaxValue) <= uint.MaxValue);
// uint left, nuint right
Assert.IsTrue(0 <= new nuint(0));
Assert.IsTrue(1 <= new nuint(1));
Assert.IsTrue(uint.MaxValue <= new nuint(uint.MaxValue));
Assert.IsTrue(0 <= new nuint(1));
Assert.IsTrue(1 <= new nuint(2));
Assert.IsTrue((uint.MaxValue - 1) <= new nuint(uint.MaxValue));
Assert.IsFalse(1 <= new nuint(0));
Assert.IsFalse(2 <= new nuint(1));
Assert.IsFalse(uint.MaxValue <= new nuint(uint.MaxValue - 1));
Assert.IsTrue(uint.MaxValue <= (nuint)(ulong.MaxValue));
}
[TestMethod]
public unsafe void operator_LessThanOrEqual_long()
{
// nuint left, ulong right
Assert.IsTrue(nuint.Zero <= 0L);
Assert.IsTrue(new nuint(0) <= 0L);
Assert.IsTrue(new nuint(1) <= 1L);
Assert.IsTrue(new nuint(uint.MaxValue) <= (ulong)uint.MaxValue);
Assert.IsTrue((nuint)(ulong.MaxValue) <= ulong.MaxValue);
Assert.IsTrue(new nuint(0) <= 1L);
Assert.IsTrue(new nuint(1) <= 2L);
Assert.IsTrue((nuint)(uint.MaxValue - 1) <= (ulong)uint.MaxValue);
Assert.IsTrue((nuint)(ulong.MaxValue - 1) <= ulong.MaxValue);
Assert.IsFalse(new nuint(1) <= 0L);
Assert.IsFalse(new nuint(2) <= 1L);
Assert.IsFalse((nuint)(uint.MaxValue) <= (ulong)(uint.MaxValue - 1));
Assert.AreEqual(sizeof(ulong) != sizeof(UIntPtr), (nuint)(ulong.MaxValue) <= (ulong.MaxValue - 1));
Assert.AreEqual(sizeof(ulong) != sizeof(UIntPtr), (nuint)(ulong.MaxValue) <= (ulong)uint.MaxValue);
Assert.AreEqual(sizeof(ulong) != sizeof(UIntPtr), (nuint)(ulong.MaxValue) <= (ulong)uint.MaxValue);
// ulong left, nuint right
Assert.IsTrue(0L <= new nuint(0));
Assert.IsTrue(1L <= new nuint(1));
Assert.IsTrue((ulong)uint.MaxValue <= new nuint(uint.MaxValue));
Assert.AreEqual(sizeof(ulong) == sizeof(UIntPtr), ulong.MaxValue <= (nuint)(ulong.MaxValue));
Assert.IsTrue(0L <= new nuint(1));
Assert.IsTrue(1L <= new nuint(2));
Assert.IsTrue((ulong)(uint.MaxValue - 1) <= new nuint(uint.MaxValue));
Assert.IsFalse((ulong.MaxValue - 1) <= new nuint(uint.MaxValue));
Assert.IsFalse(1L <= new nuint(0));
Assert.IsFalse(2L <= new nuint(1));
Assert.IsFalse((ulong)uint.MaxValue <= new nuint(uint.MaxValue - 1));
Assert.IsFalse(ulong.MaxValue <= (nuint)(ulong.MaxValue - 1));
Assert.IsTrue((ulong)uint.MaxValue <= (nuint)(ulong.MaxValue));
}
[TestMethod]
public unsafe void operator_LessThanOrEqual_UIntPtr()
{
// nuint left, UIntPtr right
Assert.IsTrue(nuint.Zero <= new UIntPtr(0));
Assert.IsTrue(new nuint(0) <= new UIntPtr(0));
Assert.IsTrue(new nuint(1) <= new UIntPtr(1));
Assert.IsTrue(new nuint(uint.MaxValue) <= new UIntPtr((ulong)uint.MaxValue));
if (sizeof(ulong) == sizeof(UIntPtr))
{
Assert.IsTrue((nuint)(ulong.MaxValue) <= new UIntPtr(ulong.MaxValue));
}
Assert.IsTrue(new nuint(0) <= new UIntPtr(1));
Assert.IsTrue(new nuint(1) <= new UIntPtr(2));
Assert.IsTrue((nuint)(uint.MaxValue - 1) <= new UIntPtr((ulong)uint.MaxValue));
if (sizeof(ulong) == sizeof(UIntPtr))
{
Assert.IsTrue((nuint)(ulong.MaxValue - 1) <= new UIntPtr(ulong.MaxValue));
}
Assert.IsFalse(new nuint(1) <= new UIntPtr(0));
Assert.IsFalse(new nuint(2) <= new UIntPtr(1));
Assert.IsFalse((nuint)(uint.MaxValue) <= new UIntPtr((ulong)(uint.MaxValue - 1)));
if (sizeof(ulong) == sizeof(UIntPtr))
{
Assert.AreEqual(sizeof(ulong) != sizeof(UIntPtr), (nuint)(ulong.MaxValue) <= new UIntPtr((ulong.MaxValue - 1)));
}
Assert.AreEqual(sizeof(ulong) != sizeof(UIntPtr), (nuint)(ulong.MaxValue) <= new UIntPtr((ulong)uint.MaxValue));
Assert.AreEqual(sizeof(ulong) != sizeof(UIntPtr), (nuint)(ulong.MaxValue) <= new UIntPtr((ulong)uint.MaxValue));
// UIntPtr left, nuint right
Assert.IsTrue(new UIntPtr(0) <= new nuint(0));
Assert.IsTrue(new UIntPtr(1) <= new nuint(1));
Assert.IsTrue((ulong)uint.MaxValue <= new nuint(uint.MaxValue));
Assert.AreEqual(sizeof(ulong) == sizeof(UIntPtr), ulong.MaxValue <= (nuint)(ulong.MaxValue));
Assert.IsTrue(new UIntPtr(0) <= new nuint(1));
Assert.IsTrue(new UIntPtr(1) <= new nuint(2));
Assert.IsTrue((ulong)(uint.MaxValue - 1) <= new nuint(uint.MaxValue));
Assert.IsFalse((ulong.MaxValue - 1) <= new nuint(uint.MaxValue));
Assert.IsFalse(new UIntPtr(1) <= new nuint(0));
Assert.IsFalse(new UIntPtr(2) <= new nuint(1));
Assert.IsFalse((ulong)uint.MaxValue <= new nuint(uint.MaxValue - 1));
Assert.IsFalse(ulong.MaxValue <= (nuint)(ulong.MaxValue - 1));
Assert.IsTrue((ulong)uint.MaxValue <= (nuint)(ulong.MaxValue));
}
[TestMethod]
public void Equals_nuint()
{
Assert.IsTrue(nuint.Zero.Equals(new nuint(0)));
Assert.IsTrue(new nuint(0).Equals(new nuint(0)));
Assert.IsTrue(new nuint(1).Equals(new nuint(1)));
Assert.IsTrue(new nuint(uint.MaxValue).Equals(new nuint(uint.MaxValue)));
Assert.IsTrue(((nuint)(ulong.MaxValue)).Equals((nuint)(ulong.MaxValue)));
Assert.IsFalse(new nuint(0).Equals(new nuint(1)));
Assert.IsFalse(new nuint(1).Equals(new nuint(0)));
Assert.IsFalse(new nuint(1).Equals(new nuint(2)));
Assert.IsFalse(new nuint(2).Equals(new nuint(1)));
}
[TestMethod]
public void CompareTo_nuint()
{
Assert.AreEqual(0, nuint.Zero.CompareTo(new nuint(0)));
Assert.AreEqual(0, new nuint(0).CompareTo(new nuint(0)));
Assert.AreEqual(0, new nuint(1).CompareTo(new nuint(1)));
Assert.AreEqual(0, new nuint(uint.MaxValue).CompareTo(new nuint(uint.MaxValue)));
Assert.AreEqual(0, ((nuint)(ulong.MaxValue)).CompareTo((nuint)(ulong.MaxValue)));
Assert.AreEqual(-1, new nuint(0).CompareTo(new nuint(1)));
Assert.AreEqual(-1, new nuint(1).CompareTo(new nuint(2)));
Assert.AreEqual(1, new nuint(1).CompareTo(new nuint(0)));
Assert.AreEqual(1, new nuint(2).CompareTo(new nuint(1)));
}
[TestMethod]
public void Equals_object_nuint()
{
Assert.IsTrue(nuint.Zero.Equals((object)new nuint(0)));
Assert.IsTrue(new nuint(0).Equals((object)new nuint(0)));
Assert.IsTrue(new nuint(1).Equals((object)new nuint(1)));
Assert.IsTrue(new nuint(uint.MaxValue).Equals((object)new nuint(uint.MaxValue)));
Assert.IsTrue(((nuint)(ulong.MaxValue)).Equals((object)(nuint)(ulong.MaxValue)));
Assert.IsFalse(new nuint(0).Equals((object)new nuint(1)));
Assert.IsFalse(new nuint(1).Equals((object)new nuint(0)));
Assert.IsFalse(new nuint(1).Equals((object)new nuint(2)));
Assert.IsFalse(new nuint(2).Equals((object)new nuint(1)));
Assert.IsFalse(new nuint(2).Equals((object)new nuint(1)));
Assert.IsFalse(new nuint(0).Equals((object)null));
Assert.IsFalse(new nuint(0).Equals((object)""));
Assert.IsFalse(new nuint(0).Equals((object)"test"));
}
[TestMethod]
public void GetHashCode_nuint()
{
Assert.AreEqual(0, new nuint(0).GetHashCode());
Assert.AreEqual(1, new nuint(1).GetHashCode());
Assert.AreEqual(2, new nuint(2).GetHashCode());
Assert.AreEqual(3, new nuint(3).GetHashCode());
Assert.AreEqual(4, new nuint(4).GetHashCode());
Assert.AreEqual(5, new nuint(5).GetHashCode());
Assert.AreEqual(int.MaxValue, new nuint(uint.MaxValue / 2).GetHashCode());
Assert.AreEqual(int.MaxValue, new nuint(uint.MaxValue).GetHashCode());
Assert.AreEqual(int.MaxValue, ((UIntPtr)(uint.MaxValue / 2)).GetHashCode());
Assert.AreEqual(int.MaxValue, ((UIntPtr)uint.MaxValue).GetHashCode());
// UIntPtr overflows if 32-bit
//Assert.AreEqual(int.MaxValue, ((UIntPtr)ulong.MaxValue).GetHashCode());
Assert.AreEqual(int.MaxValue, ((nuint)ulong.MaxValue).GetHashCode());
Assert.AreEqual(0, ((UIntPtr)ulong.MinValue).GetHashCode());
Assert.AreEqual(0, ((nuint)ulong.MinValue).GetHashCode());
}
// // UIntPtr hashcode impl
// public unsafe override int GetHashCode()
// {
//#if BIT64
// ulong l = (ulong)_value;
// return (unchecked((int)l) ^ (int)(l >> 32));
//#else
// return unchecked((int)_value);
//#endif
// }
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Testing.Dependencies;
namespace osu.Framework.Tests.Dependencies
{
[TestFixture]
public class CachedAttributeTest
{
[Test]
public void TestCacheType()
{
var provider = new Provider1();
var dependencies = DependencyActivator.MergeDependencies(provider, new DependencyContainer());
Assert.AreEqual(provider, dependencies.Get<Provider1>());
}
[Test]
public void TestCacheTypeAsParentType()
{
var provider = new Provider2();
var dependencies = DependencyActivator.MergeDependencies(provider, new DependencyContainer());
Assert.AreEqual(provider, dependencies.Get<object>());
}
[Test]
public void TestCacheTypeOverrideParentCache()
{
var provider = new Provider3();
var dependencies = DependencyActivator.MergeDependencies(provider, new DependencyContainer());
Assert.AreEqual(provider, dependencies.Get<Provider1>());
Assert.AreEqual(null, dependencies.Get<Provider3>());
}
[Test]
public void TestAttemptToCacheStruct()
{
var provider = new Provider4();
Assert.Throws<ArgumentException>(() => DependencyActivator.MergeDependencies(provider, new DependencyContainer()));
}
[Test]
public void TestCacheMultipleFields()
{
var provider = new Provider5();
var dependencies = DependencyActivator.MergeDependencies(provider, new DependencyContainer());
Assert.IsNotNull(dependencies.Get<ProvidedType1>());
Assert.IsNotNull(dependencies.Get<ProvidedType2>());
}
[Test]
public void TestCacheFieldsOverrideBaseFields()
{
var provider = new Provider6();
var dependencies = DependencyActivator.MergeDependencies(provider, new DependencyContainer());
Assert.AreEqual(provider.Provided3, dependencies.Get<ProvidedType1>());
}
[Test]
public void TestCacheFieldsAsMultipleTypes()
{
var provider = new Provider7();
var dependencies = DependencyActivator.MergeDependencies(provider, new DependencyContainer());
Assert.IsNotNull(dependencies.Get<object>());
Assert.IsNotNull(dependencies.Get<ProvidedType1>());
}
[Test]
public void TestCacheTypeAsMultipleTypes()
{
var provider = new Provider8();
var dependencies = DependencyActivator.MergeDependencies(provider, new DependencyContainer());
Assert.IsNotNull(dependencies.Get<object>());
Assert.IsNotNull(dependencies.Get<Provider8>());
}
[Test]
public void TestAttemptToCacheBaseAsDerived()
{
var provider = new Provider9();
Assert.Throws<ArgumentException>(() => DependencyActivator.MergeDependencies(provider, new DependencyContainer()));
}
[Test]
public void TestCacheMostDerivedType()
{
var provider = new Provider10();
var dependencies = DependencyActivator.MergeDependencies(provider, new DependencyContainer());
Assert.IsNotNull(dependencies.Get<ProvidedType1>());
}
[Test]
public void TestCacheClassAsInterface()
{
var provider = new Provider11();
var dependencies = DependencyActivator.MergeDependencies(provider, new DependencyContainer());
Assert.IsNotNull(dependencies.Get<IProvidedInterface1>());
Assert.IsNotNull(dependencies.Get<ProvidedType1>());
}
[Test]
public void TestCacheStructAsInterface()
{
var provider = new Provider12();
Assert.Throws<ArgumentException>(() => DependencyActivator.MergeDependencies(provider, new DependencyContainer()));
}
/// <summary>
/// Tests caching a struct, where the providing type is within the osu.Framework assembly.
/// </summary>
[Test]
public void TestCacheStructInternal()
{
var provider = new CachedStructProvider();
var dependencies = DependencyActivator.MergeDependencies(provider, new DependencyContainer());
Assert.AreEqual(provider.CachedObject.Value, dependencies.GetValue<CachedStructProvider.Struct>().Value);
}
[Test]
public void TestGetValueNullInternal()
{
Assert.AreEqual(default(int), new DependencyContainer().GetValue<int>());
}
/// <summary>
/// Test caching a nullable, where the providing type is within the osu.Framework assembly.
/// </summary>
[TestCase(null)]
[TestCase(10)]
public void TestCacheNullableInternal(int? testValue)
{
var provider = new CachedNullableProvider();
provider.SetValue(testValue);
var dependencies = DependencyActivator.MergeDependencies(provider, new DependencyContainer());
Assert.AreEqual(testValue, dependencies.GetValue<int?>());
}
[Test]
public void TestInvalidPublicAccessor()
{
var provider = new Provider13();
Assert.Throws<AccessModifierNotAllowedForCachedValueException>(() => DependencyActivator.MergeDependencies(provider, new DependencyContainer()));
}
[Test]
public void TestInvalidProtectedAccessor()
{
var provider = new Provider14();
Assert.Throws<AccessModifierNotAllowedForCachedValueException>(() => DependencyActivator.MergeDependencies(provider, new DependencyContainer()));
}
[Test]
public void TestInvalidInternalAccessor()
{
var provider = new Provider15();
Assert.Throws<AccessModifierNotAllowedForCachedValueException>(() => DependencyActivator.MergeDependencies(provider, new DependencyContainer()));
}
[Test]
public void TestInvalidProtectedInternalAccessor()
{
var provider = new Provider16();
Assert.Throws<AccessModifierNotAllowedForCachedValueException>(() => DependencyActivator.MergeDependencies(provider, new DependencyContainer()));
}
[Test]
public void TestValidPublicAccessor()
{
var provider = new Provider17();
Assert.DoesNotThrow(() => DependencyActivator.MergeDependencies(provider, new DependencyContainer()));
}
[Test]
public void TestCacheNullReferenceValue()
{
var provider = new Provider18();
Assert.Throws<NullDependencyException>(() => DependencyActivator.MergeDependencies(provider, new DependencyContainer()));
}
[Test]
public void TestCacheProperty()
{
var provider = new Provider19();
var dependencies = DependencyActivator.MergeDependencies(provider, new DependencyContainer());
Assert.IsNotNull(dependencies.Get<object>());
}
[Test]
public void TestCachePropertyWithNoSetter()
{
var provider = new Provider20();
Assert.DoesNotThrow(() => DependencyActivator.MergeDependencies(provider, new DependencyContainer()));
}
[Test]
public void TestCachePropertyWithPublicSetter()
{
var provider = new Provider21();
Assert.Throws<AccessModifierNotAllowedForCachedValueException>(() => DependencyActivator.MergeDependencies(provider, new DependencyContainer()));
}
[Test]
public void TestCachePropertyWithNonAutoSetter()
{
var provider = new Provider22();
Assert.Throws<AccessModifierNotAllowedForCachedValueException>(() => DependencyActivator.MergeDependencies(provider, new DependencyContainer()));
}
[Test]
public void TestCachePropertyWithNoGetter()
{
var provider = new Provider23();
Assert.Throws<AccessModifierNotAllowedForCachedValueException>(() => DependencyActivator.MergeDependencies(provider, new DependencyContainer()));
}
[Test]
public void TestCacheWithNonAutoGetter()
{
var provider = new Provider24();
Assert.Throws<AccessModifierNotAllowedForCachedValueException>(() => DependencyActivator.MergeDependencies(provider, new DependencyContainer()));
}
[Test]
public void TestCachedViaInterface()
{
var provider = new Provider25();
var dependencies = DependencyActivator.MergeDependencies(provider, new DependencyContainer());
Assert.IsNotNull(dependencies.Get<IProviderInterface3>());
Assert.IsNotNull(dependencies.Get<IProviderInterface2>());
}
private interface IProvidedInterface1
{
}
private class ProvidedType1 : IProvidedInterface1
{
}
private class ProvidedType2
{
}
private struct ProvidedType3 : IProvidedInterface1
{
}
[Cached]
private class Provider1
{
}
[Cached(Type = typeof(object))]
private class Provider2
{
}
[Cached(Type = typeof(Provider1))]
private class Provider3 : Provider1
{
}
private class Provider4
{
[Cached]
#pragma warning disable 169
private int fail;
#pragma warning restore 169
}
private class Provider5
{
[Cached]
public ProvidedType1 Provided1 { get; } = new ProvidedType1();
[Cached]
private ProvidedType2 provided2 = new ProvidedType2();
}
private class Provider6 : Provider5
{
[Cached]
public ProvidedType1 Provided3 { get; } = new ProvidedType1();
}
private class Provider7
{
[Cached]
[Cached(Type = typeof(object))]
private ProvidedType1 provided1 = new ProvidedType1();
}
[Cached]
[Cached(Type = typeof(object))]
private class Provider8
{
}
private class Provider9
{
[Cached(Type = typeof(ProvidedType1))]
private object provided1 = new object();
}
private class Provider10
{
[Cached]
private object provided1 = new ProvidedType1();
}
private class Provider11
{
[Cached]
[Cached(Type = typeof(IProvidedInterface1))]
private IProvidedInterface1 provided1 = new ProvidedType1();
}
private class Provider12
{
[Cached(Type = typeof(IProvidedInterface1))]
private IProvidedInterface1 provided1 = new ProvidedType3();
}
private class Provider13
{
[Cached]
public object Provided1 = new ProvidedType1();
}
private class Provider14
{
[Cached]
protected object Provided1 = new ProvidedType1();
}
private class Provider15
{
[Cached]
internal object Provided1 = new ProvidedType1();
}
private class Provider16
{
[Cached]
protected internal object Provided1 = new ProvidedType1();
}
private class Provider17
{
[Cached]
public readonly object Provided1 = new ProvidedType1();
}
private class Provider18
{
#pragma warning disable 649
[Cached]
public readonly object Provided1;
#pragma warning restore 649
}
private class Provider19
{
[Cached]
public object Provided1 { get; private set; } = new object();
}
private class Provider20
{
[Cached]
public object Provided1 { get; } = new object();
}
private class Provider21
{
[Cached]
public object Provided1 { get; set; }
}
private class Provider22
{
[Cached]
public object Provided1
{
get => null;
// ReSharper disable once ValueParameterNotUsed
set
{
}
}
}
private class Provider23
{
[Cached]
public object Provided1
{
// ReSharper disable once ValueParameterNotUsed
set
{
}
}
}
private class Provider24
{
[Cached]
public object Provided1 => null;
}
private class Provider25 : IProviderInterface3
{
}
[Cached]
private interface IProviderInterface3 : IProviderInterface2
{
}
[Cached]
private interface IProviderInterface2
{
}
}
}
| |
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace Infoplus.Model
{
/// <summary>
///
/// </summary>
[DataContract]
public partial class OrderLineActivity : IEquatable<OrderLineActivity>
{
/// <summary>
/// Initializes a new instance of the <see cref="OrderLineActivity" /> class.
/// Initializes a new instance of the <see cref="OrderLineActivity" />class.
/// </summary>
/// <param name="CreateDate">CreateDate.</param>
/// <param name="ModifyDate">ModifyDate.</param>
/// <param name="LobId">LobId (required).</param>
/// <param name="ItemMajorGroupId">ItemMajorGroupId (required).</param>
/// <param name="ItemSubGroupId">ItemSubGroupId (required).</param>
/// <param name="ItemProductCodeId">ItemProductCodeId.</param>
/// <param name="ItemAccountCodeId">ItemAccountCodeId (required).</param>
/// <param name="ItemSummaryCodeId">ItemSummaryCodeId (required).</param>
/// <param name="ItemLegacyLowStockContactId">ItemLegacyLowStockContactId (required).</param>
/// <param name="CustomFields">CustomFields.</param>
public OrderLineActivity(DateTime? CreateDate = null, DateTime? ModifyDate = null, int? LobId = null, int? ItemMajorGroupId = null, int? ItemSubGroupId = null, int? ItemProductCodeId = null, int? ItemAccountCodeId = null, int? ItemSummaryCodeId = null, int? ItemLegacyLowStockContactId = null, Dictionary<string, Object> CustomFields = null)
{
// to ensure "LobId" is required (not null)
if (LobId == null)
{
throw new InvalidDataException("LobId is a required property for OrderLineActivity and cannot be null");
}
else
{
this.LobId = LobId;
}
// to ensure "ItemMajorGroupId" is required (not null)
if (ItemMajorGroupId == null)
{
throw new InvalidDataException("ItemMajorGroupId is a required property for OrderLineActivity and cannot be null");
}
else
{
this.ItemMajorGroupId = ItemMajorGroupId;
}
// to ensure "ItemSubGroupId" is required (not null)
if (ItemSubGroupId == null)
{
throw new InvalidDataException("ItemSubGroupId is a required property for OrderLineActivity and cannot be null");
}
else
{
this.ItemSubGroupId = ItemSubGroupId;
}
// to ensure "ItemAccountCodeId" is required (not null)
if (ItemAccountCodeId == null)
{
throw new InvalidDataException("ItemAccountCodeId is a required property for OrderLineActivity and cannot be null");
}
else
{
this.ItemAccountCodeId = ItemAccountCodeId;
}
// to ensure "ItemSummaryCodeId" is required (not null)
if (ItemSummaryCodeId == null)
{
throw new InvalidDataException("ItemSummaryCodeId is a required property for OrderLineActivity and cannot be null");
}
else
{
this.ItemSummaryCodeId = ItemSummaryCodeId;
}
// to ensure "ItemLegacyLowStockContactId" is required (not null)
if (ItemLegacyLowStockContactId == null)
{
throw new InvalidDataException("ItemLegacyLowStockContactId is a required property for OrderLineActivity and cannot be null");
}
else
{
this.ItemLegacyLowStockContactId = ItemLegacyLowStockContactId;
}
this.CreateDate = CreateDate;
this.ModifyDate = ModifyDate;
this.ItemProductCodeId = ItemProductCodeId;
this.CustomFields = CustomFields;
}
/// <summary>
/// Gets or Sets Id
/// </summary>
[DataMember(Name="id", EmitDefaultValue=false)]
public int? Id { get; private set; }
/// <summary>
/// Gets or Sets CreateDate
/// </summary>
[DataMember(Name="createDate", EmitDefaultValue=false)]
public DateTime? CreateDate { get; set; }
/// <summary>
/// Gets or Sets ModifyDate
/// </summary>
[DataMember(Name="modifyDate", EmitDefaultValue=false)]
public DateTime? ModifyDate { get; set; }
/// <summary>
/// Gets or Sets OrderNo
/// </summary>
[DataMember(Name="orderNo", EmitDefaultValue=false)]
public double? OrderNo { get; private set; }
/// <summary>
/// Gets or Sets LobId
/// </summary>
[DataMember(Name="lobId", EmitDefaultValue=false)]
public int? LobId { get; set; }
/// <summary>
/// Gets or Sets Sku
/// </summary>
[DataMember(Name="sku", EmitDefaultValue=false)]
public string Sku { get; private set; }
/// <summary>
/// Gets or Sets PoNoId
/// </summary>
[DataMember(Name="poNoId", EmitDefaultValue=false)]
public int? PoNoId { get; private set; }
/// <summary>
/// Gets or Sets CrossDock
/// </summary>
[DataMember(Name="crossDock", EmitDefaultValue=false)]
public int? CrossDock { get; private set; }
/// <summary>
/// Gets or Sets ProcessNo
/// </summary>
[DataMember(Name="processNo", EmitDefaultValue=false)]
public int? ProcessNo { get; private set; }
/// <summary>
/// Gets or Sets OrderedQty
/// </summary>
[DataMember(Name="orderedQty", EmitDefaultValue=false)]
public int? OrderedQty { get; private set; }
/// <summary>
/// Gets or Sets AllowedQty
/// </summary>
[DataMember(Name="allowedQty", EmitDefaultValue=false)]
public int? AllowedQty { get; private set; }
/// <summary>
/// Gets or Sets ShippedQty
/// </summary>
[DataMember(Name="shippedQty", EmitDefaultValue=false)]
public int? ShippedQty { get; private set; }
/// <summary>
/// Gets or Sets BackorderQty
/// </summary>
[DataMember(Name="backorderQty", EmitDefaultValue=false)]
public int? BackorderQty { get; private set; }
/// <summary>
/// Gets or Sets AdjustCode
/// </summary>
[DataMember(Name="adjustCode", EmitDefaultValue=false)]
public int? AdjustCode { get; private set; }
/// <summary>
/// Gets or Sets ProcessFlag
/// </summary>
[DataMember(Name="processFlag", EmitDefaultValue=false)]
public string ProcessFlag { get; private set; }
/// <summary>
/// Gets or Sets RevDate
/// </summary>
[DataMember(Name="revDate", EmitDefaultValue=false)]
public string RevDate { get; private set; }
/// <summary>
/// Gets or Sets RestrictionRule
/// </summary>
[DataMember(Name="restrictionRule", EmitDefaultValue=false)]
public int? RestrictionRule { get; private set; }
/// <summary>
/// Gets or Sets UnitCost
/// </summary>
[DataMember(Name="unitCost", EmitDefaultValue=false)]
public double? UnitCost { get; private set; }
/// <summary>
/// Gets or Sets UnitSell
/// </summary>
[DataMember(Name="unitSell", EmitDefaultValue=false)]
public double? UnitSell { get; private set; }
/// <summary>
/// Gets or Sets UnitDiscount
/// </summary>
[DataMember(Name="unitDiscount", EmitDefaultValue=false)]
public double? UnitDiscount { get; private set; }
/// <summary>
/// Gets or Sets ExtendedCost
/// </summary>
[DataMember(Name="extendedCost", EmitDefaultValue=false)]
public double? ExtendedCost { get; private set; }
/// <summary>
/// Gets or Sets ExtendedSell
/// </summary>
[DataMember(Name="extendedSell", EmitDefaultValue=false)]
public double? ExtendedSell { get; private set; }
/// <summary>
/// Gets or Sets ExtendedDiscount
/// </summary>
[DataMember(Name="extendedDiscount", EmitDefaultValue=false)]
public double? ExtendedDiscount { get; private set; }
/// <summary>
/// Gets or Sets NcExtendedSell
/// </summary>
[DataMember(Name="ncExtendedSell", EmitDefaultValue=false)]
public double? NcExtendedSell { get; private set; }
/// <summary>
/// Gets or Sets Per
/// </summary>
[DataMember(Name="per", EmitDefaultValue=false)]
public string Per { get; private set; }
/// <summary>
/// Gets or Sets ChargeCode
/// </summary>
[DataMember(Name="chargeCode", EmitDefaultValue=false)]
public string ChargeCode { get; private set; }
/// <summary>
/// Gets or Sets DistributionCode
/// </summary>
[DataMember(Name="distributionCode", EmitDefaultValue=false)]
public string DistributionCode { get; private set; }
/// <summary>
/// Gets or Sets Upc
/// </summary>
[DataMember(Name="upc", EmitDefaultValue=false)]
public string Upc { get; private set; }
/// <summary>
/// Gets or Sets VendorSKU
/// </summary>
[DataMember(Name="vendorSKU", EmitDefaultValue=false)]
public string VendorSKU { get; private set; }
/// <summary>
/// Gets or Sets OrderSourceSKU
/// </summary>
[DataMember(Name="orderSourceSKU", EmitDefaultValue=false)]
public string OrderSourceSKU { get; private set; }
/// <summary>
/// Gets or Sets ItemMajorGroupId
/// </summary>
[DataMember(Name="itemMajorGroupId", EmitDefaultValue=false)]
public int? ItemMajorGroupId { get; set; }
/// <summary>
/// Gets or Sets MasterMajorGroupName
/// </summary>
[DataMember(Name="masterMajorGroupName", EmitDefaultValue=false)]
public string MasterMajorGroupName { get; private set; }
/// <summary>
/// Gets or Sets ItemSubGroupId
/// </summary>
[DataMember(Name="itemSubGroupId", EmitDefaultValue=false)]
public int? ItemSubGroupId { get; set; }
/// <summary>
/// Gets or Sets MasterSubGroupName
/// </summary>
[DataMember(Name="masterSubGroupName", EmitDefaultValue=false)]
public string MasterSubGroupName { get; private set; }
/// <summary>
/// Gets or Sets ItemProductCodeId
/// </summary>
[DataMember(Name="itemProductCodeId", EmitDefaultValue=false)]
public int? ItemProductCodeId { get; set; }
/// <summary>
/// Gets or Sets MasterProductionCodeName
/// </summary>
[DataMember(Name="masterProductionCodeName", EmitDefaultValue=false)]
public string MasterProductionCodeName { get; private set; }
/// <summary>
/// Gets or Sets ItemAccountCodeId
/// </summary>
[DataMember(Name="itemAccountCodeId", EmitDefaultValue=false)]
public int? ItemAccountCodeId { get; set; }
/// <summary>
/// Gets or Sets MasterAccountCodeName
/// </summary>
[DataMember(Name="masterAccountCodeName", EmitDefaultValue=false)]
public string MasterAccountCodeName { get; private set; }
/// <summary>
/// Gets or Sets ItemSummaryCodeId
/// </summary>
[DataMember(Name="itemSummaryCodeId", EmitDefaultValue=false)]
public int? ItemSummaryCodeId { get; set; }
/// <summary>
/// Gets or Sets MasterSummaryCodeName
/// </summary>
[DataMember(Name="masterSummaryCodeName", EmitDefaultValue=false)]
public string MasterSummaryCodeName { get; private set; }
/// <summary>
/// Gets or Sets ItemLegacyLowStockContactId
/// </summary>
[DataMember(Name="itemLegacyLowStockContactId", EmitDefaultValue=false)]
public int? ItemLegacyLowStockContactId { get; set; }
/// <summary>
/// Gets or Sets LowStockContactName
/// </summary>
[DataMember(Name="lowStockContactName", EmitDefaultValue=false)]
public string LowStockContactName { get; private set; }
/// <summary>
/// Gets or Sets Sector
/// </summary>
[DataMember(Name="sector", EmitDefaultValue=false)]
public string Sector { get; private set; }
/// <summary>
/// Gets or Sets WeightPerWrap
/// </summary>
[DataMember(Name="weightPerWrap", EmitDefaultValue=false)]
public double? WeightPerWrap { get; private set; }
/// <summary>
/// Gets or Sets ItemWeight
/// </summary>
[DataMember(Name="itemWeight", EmitDefaultValue=false)]
public double? ItemWeight { get; private set; }
/// <summary>
/// Gets or Sets ProductionLot
/// </summary>
[DataMember(Name="productionLot", EmitDefaultValue=false)]
public string ProductionLot { get; private set; }
/// <summary>
/// Gets or Sets CustomFields
/// </summary>
[DataMember(Name="customFields", EmitDefaultValue=false)]
public Dictionary<string, Object> CustomFields { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class OrderLineActivity {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" CreateDate: ").Append(CreateDate).Append("\n");
sb.Append(" ModifyDate: ").Append(ModifyDate).Append("\n");
sb.Append(" OrderNo: ").Append(OrderNo).Append("\n");
sb.Append(" LobId: ").Append(LobId).Append("\n");
sb.Append(" Sku: ").Append(Sku).Append("\n");
sb.Append(" PoNoId: ").Append(PoNoId).Append("\n");
sb.Append(" CrossDock: ").Append(CrossDock).Append("\n");
sb.Append(" ProcessNo: ").Append(ProcessNo).Append("\n");
sb.Append(" OrderedQty: ").Append(OrderedQty).Append("\n");
sb.Append(" AllowedQty: ").Append(AllowedQty).Append("\n");
sb.Append(" ShippedQty: ").Append(ShippedQty).Append("\n");
sb.Append(" BackorderQty: ").Append(BackorderQty).Append("\n");
sb.Append(" AdjustCode: ").Append(AdjustCode).Append("\n");
sb.Append(" ProcessFlag: ").Append(ProcessFlag).Append("\n");
sb.Append(" RevDate: ").Append(RevDate).Append("\n");
sb.Append(" RestrictionRule: ").Append(RestrictionRule).Append("\n");
sb.Append(" UnitCost: ").Append(UnitCost).Append("\n");
sb.Append(" UnitSell: ").Append(UnitSell).Append("\n");
sb.Append(" UnitDiscount: ").Append(UnitDiscount).Append("\n");
sb.Append(" ExtendedCost: ").Append(ExtendedCost).Append("\n");
sb.Append(" ExtendedSell: ").Append(ExtendedSell).Append("\n");
sb.Append(" ExtendedDiscount: ").Append(ExtendedDiscount).Append("\n");
sb.Append(" NcExtendedSell: ").Append(NcExtendedSell).Append("\n");
sb.Append(" Per: ").Append(Per).Append("\n");
sb.Append(" ChargeCode: ").Append(ChargeCode).Append("\n");
sb.Append(" DistributionCode: ").Append(DistributionCode).Append("\n");
sb.Append(" Upc: ").Append(Upc).Append("\n");
sb.Append(" VendorSKU: ").Append(VendorSKU).Append("\n");
sb.Append(" OrderSourceSKU: ").Append(OrderSourceSKU).Append("\n");
sb.Append(" ItemMajorGroupId: ").Append(ItemMajorGroupId).Append("\n");
sb.Append(" MasterMajorGroupName: ").Append(MasterMajorGroupName).Append("\n");
sb.Append(" ItemSubGroupId: ").Append(ItemSubGroupId).Append("\n");
sb.Append(" MasterSubGroupName: ").Append(MasterSubGroupName).Append("\n");
sb.Append(" ItemProductCodeId: ").Append(ItemProductCodeId).Append("\n");
sb.Append(" MasterProductionCodeName: ").Append(MasterProductionCodeName).Append("\n");
sb.Append(" ItemAccountCodeId: ").Append(ItemAccountCodeId).Append("\n");
sb.Append(" MasterAccountCodeName: ").Append(MasterAccountCodeName).Append("\n");
sb.Append(" ItemSummaryCodeId: ").Append(ItemSummaryCodeId).Append("\n");
sb.Append(" MasterSummaryCodeName: ").Append(MasterSummaryCodeName).Append("\n");
sb.Append(" ItemLegacyLowStockContactId: ").Append(ItemLegacyLowStockContactId).Append("\n");
sb.Append(" LowStockContactName: ").Append(LowStockContactName).Append("\n");
sb.Append(" Sector: ").Append(Sector).Append("\n");
sb.Append(" WeightPerWrap: ").Append(WeightPerWrap).Append("\n");
sb.Append(" ItemWeight: ").Append(ItemWeight).Append("\n");
sb.Append(" ProductionLot: ").Append(ProductionLot).Append("\n");
sb.Append(" CustomFields: ").Append(CustomFields).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as OrderLineActivity);
}
/// <summary>
/// Returns true if OrderLineActivity instances are equal
/// </summary>
/// <param name="other">Instance of OrderLineActivity to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(OrderLineActivity other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.Id == other.Id ||
this.Id != null &&
this.Id.Equals(other.Id)
) &&
(
this.CreateDate == other.CreateDate ||
this.CreateDate != null &&
this.CreateDate.Equals(other.CreateDate)
) &&
(
this.ModifyDate == other.ModifyDate ||
this.ModifyDate != null &&
this.ModifyDate.Equals(other.ModifyDate)
) &&
(
this.OrderNo == other.OrderNo ||
this.OrderNo != null &&
this.OrderNo.Equals(other.OrderNo)
) &&
(
this.LobId == other.LobId ||
this.LobId != null &&
this.LobId.Equals(other.LobId)
) &&
(
this.Sku == other.Sku ||
this.Sku != null &&
this.Sku.Equals(other.Sku)
) &&
(
this.PoNoId == other.PoNoId ||
this.PoNoId != null &&
this.PoNoId.Equals(other.PoNoId)
) &&
(
this.CrossDock == other.CrossDock ||
this.CrossDock != null &&
this.CrossDock.Equals(other.CrossDock)
) &&
(
this.ProcessNo == other.ProcessNo ||
this.ProcessNo != null &&
this.ProcessNo.Equals(other.ProcessNo)
) &&
(
this.OrderedQty == other.OrderedQty ||
this.OrderedQty != null &&
this.OrderedQty.Equals(other.OrderedQty)
) &&
(
this.AllowedQty == other.AllowedQty ||
this.AllowedQty != null &&
this.AllowedQty.Equals(other.AllowedQty)
) &&
(
this.ShippedQty == other.ShippedQty ||
this.ShippedQty != null &&
this.ShippedQty.Equals(other.ShippedQty)
) &&
(
this.BackorderQty == other.BackorderQty ||
this.BackorderQty != null &&
this.BackorderQty.Equals(other.BackorderQty)
) &&
(
this.AdjustCode == other.AdjustCode ||
this.AdjustCode != null &&
this.AdjustCode.Equals(other.AdjustCode)
) &&
(
this.ProcessFlag == other.ProcessFlag ||
this.ProcessFlag != null &&
this.ProcessFlag.Equals(other.ProcessFlag)
) &&
(
this.RevDate == other.RevDate ||
this.RevDate != null &&
this.RevDate.Equals(other.RevDate)
) &&
(
this.RestrictionRule == other.RestrictionRule ||
this.RestrictionRule != null &&
this.RestrictionRule.Equals(other.RestrictionRule)
) &&
(
this.UnitCost == other.UnitCost ||
this.UnitCost != null &&
this.UnitCost.Equals(other.UnitCost)
) &&
(
this.UnitSell == other.UnitSell ||
this.UnitSell != null &&
this.UnitSell.Equals(other.UnitSell)
) &&
(
this.UnitDiscount == other.UnitDiscount ||
this.UnitDiscount != null &&
this.UnitDiscount.Equals(other.UnitDiscount)
) &&
(
this.ExtendedCost == other.ExtendedCost ||
this.ExtendedCost != null &&
this.ExtendedCost.Equals(other.ExtendedCost)
) &&
(
this.ExtendedSell == other.ExtendedSell ||
this.ExtendedSell != null &&
this.ExtendedSell.Equals(other.ExtendedSell)
) &&
(
this.ExtendedDiscount == other.ExtendedDiscount ||
this.ExtendedDiscount != null &&
this.ExtendedDiscount.Equals(other.ExtendedDiscount)
) &&
(
this.NcExtendedSell == other.NcExtendedSell ||
this.NcExtendedSell != null &&
this.NcExtendedSell.Equals(other.NcExtendedSell)
) &&
(
this.Per == other.Per ||
this.Per != null &&
this.Per.Equals(other.Per)
) &&
(
this.ChargeCode == other.ChargeCode ||
this.ChargeCode != null &&
this.ChargeCode.Equals(other.ChargeCode)
) &&
(
this.DistributionCode == other.DistributionCode ||
this.DistributionCode != null &&
this.DistributionCode.Equals(other.DistributionCode)
) &&
(
this.Upc == other.Upc ||
this.Upc != null &&
this.Upc.Equals(other.Upc)
) &&
(
this.VendorSKU == other.VendorSKU ||
this.VendorSKU != null &&
this.VendorSKU.Equals(other.VendorSKU)
) &&
(
this.OrderSourceSKU == other.OrderSourceSKU ||
this.OrderSourceSKU != null &&
this.OrderSourceSKU.Equals(other.OrderSourceSKU)
) &&
(
this.ItemMajorGroupId == other.ItemMajorGroupId ||
this.ItemMajorGroupId != null &&
this.ItemMajorGroupId.Equals(other.ItemMajorGroupId)
) &&
(
this.MasterMajorGroupName == other.MasterMajorGroupName ||
this.MasterMajorGroupName != null &&
this.MasterMajorGroupName.Equals(other.MasterMajorGroupName)
) &&
(
this.ItemSubGroupId == other.ItemSubGroupId ||
this.ItemSubGroupId != null &&
this.ItemSubGroupId.Equals(other.ItemSubGroupId)
) &&
(
this.MasterSubGroupName == other.MasterSubGroupName ||
this.MasterSubGroupName != null &&
this.MasterSubGroupName.Equals(other.MasterSubGroupName)
) &&
(
this.ItemProductCodeId == other.ItemProductCodeId ||
this.ItemProductCodeId != null &&
this.ItemProductCodeId.Equals(other.ItemProductCodeId)
) &&
(
this.MasterProductionCodeName == other.MasterProductionCodeName ||
this.MasterProductionCodeName != null &&
this.MasterProductionCodeName.Equals(other.MasterProductionCodeName)
) &&
(
this.ItemAccountCodeId == other.ItemAccountCodeId ||
this.ItemAccountCodeId != null &&
this.ItemAccountCodeId.Equals(other.ItemAccountCodeId)
) &&
(
this.MasterAccountCodeName == other.MasterAccountCodeName ||
this.MasterAccountCodeName != null &&
this.MasterAccountCodeName.Equals(other.MasterAccountCodeName)
) &&
(
this.ItemSummaryCodeId == other.ItemSummaryCodeId ||
this.ItemSummaryCodeId != null &&
this.ItemSummaryCodeId.Equals(other.ItemSummaryCodeId)
) &&
(
this.MasterSummaryCodeName == other.MasterSummaryCodeName ||
this.MasterSummaryCodeName != null &&
this.MasterSummaryCodeName.Equals(other.MasterSummaryCodeName)
) &&
(
this.ItemLegacyLowStockContactId == other.ItemLegacyLowStockContactId ||
this.ItemLegacyLowStockContactId != null &&
this.ItemLegacyLowStockContactId.Equals(other.ItemLegacyLowStockContactId)
) &&
(
this.LowStockContactName == other.LowStockContactName ||
this.LowStockContactName != null &&
this.LowStockContactName.Equals(other.LowStockContactName)
) &&
(
this.Sector == other.Sector ||
this.Sector != null &&
this.Sector.Equals(other.Sector)
) &&
(
this.WeightPerWrap == other.WeightPerWrap ||
this.WeightPerWrap != null &&
this.WeightPerWrap.Equals(other.WeightPerWrap)
) &&
(
this.ItemWeight == other.ItemWeight ||
this.ItemWeight != null &&
this.ItemWeight.Equals(other.ItemWeight)
) &&
(
this.ProductionLot == other.ProductionLot ||
this.ProductionLot != null &&
this.ProductionLot.Equals(other.ProductionLot)
) &&
(
this.CustomFields == other.CustomFields ||
this.CustomFields != null &&
this.CustomFields.SequenceEqual(other.CustomFields)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.Id != null)
hash = hash * 59 + this.Id.GetHashCode();
if (this.CreateDate != null)
hash = hash * 59 + this.CreateDate.GetHashCode();
if (this.ModifyDate != null)
hash = hash * 59 + this.ModifyDate.GetHashCode();
if (this.OrderNo != null)
hash = hash * 59 + this.OrderNo.GetHashCode();
if (this.LobId != null)
hash = hash * 59 + this.LobId.GetHashCode();
if (this.Sku != null)
hash = hash * 59 + this.Sku.GetHashCode();
if (this.PoNoId != null)
hash = hash * 59 + this.PoNoId.GetHashCode();
if (this.CrossDock != null)
hash = hash * 59 + this.CrossDock.GetHashCode();
if (this.ProcessNo != null)
hash = hash * 59 + this.ProcessNo.GetHashCode();
if (this.OrderedQty != null)
hash = hash * 59 + this.OrderedQty.GetHashCode();
if (this.AllowedQty != null)
hash = hash * 59 + this.AllowedQty.GetHashCode();
if (this.ShippedQty != null)
hash = hash * 59 + this.ShippedQty.GetHashCode();
if (this.BackorderQty != null)
hash = hash * 59 + this.BackorderQty.GetHashCode();
if (this.AdjustCode != null)
hash = hash * 59 + this.AdjustCode.GetHashCode();
if (this.ProcessFlag != null)
hash = hash * 59 + this.ProcessFlag.GetHashCode();
if (this.RevDate != null)
hash = hash * 59 + this.RevDate.GetHashCode();
if (this.RestrictionRule != null)
hash = hash * 59 + this.RestrictionRule.GetHashCode();
if (this.UnitCost != null)
hash = hash * 59 + this.UnitCost.GetHashCode();
if (this.UnitSell != null)
hash = hash * 59 + this.UnitSell.GetHashCode();
if (this.UnitDiscount != null)
hash = hash * 59 + this.UnitDiscount.GetHashCode();
if (this.ExtendedCost != null)
hash = hash * 59 + this.ExtendedCost.GetHashCode();
if (this.ExtendedSell != null)
hash = hash * 59 + this.ExtendedSell.GetHashCode();
if (this.ExtendedDiscount != null)
hash = hash * 59 + this.ExtendedDiscount.GetHashCode();
if (this.NcExtendedSell != null)
hash = hash * 59 + this.NcExtendedSell.GetHashCode();
if (this.Per != null)
hash = hash * 59 + this.Per.GetHashCode();
if (this.ChargeCode != null)
hash = hash * 59 + this.ChargeCode.GetHashCode();
if (this.DistributionCode != null)
hash = hash * 59 + this.DistributionCode.GetHashCode();
if (this.Upc != null)
hash = hash * 59 + this.Upc.GetHashCode();
if (this.VendorSKU != null)
hash = hash * 59 + this.VendorSKU.GetHashCode();
if (this.OrderSourceSKU != null)
hash = hash * 59 + this.OrderSourceSKU.GetHashCode();
if (this.ItemMajorGroupId != null)
hash = hash * 59 + this.ItemMajorGroupId.GetHashCode();
if (this.MasterMajorGroupName != null)
hash = hash * 59 + this.MasterMajorGroupName.GetHashCode();
if (this.ItemSubGroupId != null)
hash = hash * 59 + this.ItemSubGroupId.GetHashCode();
if (this.MasterSubGroupName != null)
hash = hash * 59 + this.MasterSubGroupName.GetHashCode();
if (this.ItemProductCodeId != null)
hash = hash * 59 + this.ItemProductCodeId.GetHashCode();
if (this.MasterProductionCodeName != null)
hash = hash * 59 + this.MasterProductionCodeName.GetHashCode();
if (this.ItemAccountCodeId != null)
hash = hash * 59 + this.ItemAccountCodeId.GetHashCode();
if (this.MasterAccountCodeName != null)
hash = hash * 59 + this.MasterAccountCodeName.GetHashCode();
if (this.ItemSummaryCodeId != null)
hash = hash * 59 + this.ItemSummaryCodeId.GetHashCode();
if (this.MasterSummaryCodeName != null)
hash = hash * 59 + this.MasterSummaryCodeName.GetHashCode();
if (this.ItemLegacyLowStockContactId != null)
hash = hash * 59 + this.ItemLegacyLowStockContactId.GetHashCode();
if (this.LowStockContactName != null)
hash = hash * 59 + this.LowStockContactName.GetHashCode();
if (this.Sector != null)
hash = hash * 59 + this.Sector.GetHashCode();
if (this.WeightPerWrap != null)
hash = hash * 59 + this.WeightPerWrap.GetHashCode();
if (this.ItemWeight != null)
hash = hash * 59 + this.ItemWeight.GetHashCode();
if (this.ProductionLot != null)
hash = hash * 59 + this.ProductionLot.GetHashCode();
if (this.CustomFields != null)
hash = hash * 59 + this.CustomFields.GetHashCode();
return hash;
}
}
}
}
| |
/**
* Copyright 2016 Dartmouth-Hitchcock
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Web;
using System.Xml.Linq;
using Legion.Services;
using Mjolnir;
using System.Threading;
namespace Legion {
internal static class XLumberjack {
private struct EventParams {
public string Level;
public string Group;
public ApplicationType ApplicationType;
public string ApplicationName;
public string LoggingUserType;
public string LogginUserId;
public string AffectedUserType;
public string AffectedUserId;
public string Type;
public string Details;
public string Clientip;
public string Hostip;
}
#region WriteEvent
public static int WriteEvent(EventLevel level, string type, string details) {
string ip = ServerTools.IPv4Addresses.First().ToString();
return WriteEvent(level, type, details, ip, ip);
}
public static int WriteEvent(EventLevel level, string type, string details, string clientip, string hostip) {
return WriteEvent(level, "Legion", ApplicationType.Legion, "Core", type, details, clientip, hostip);
}
public static int WriteEvent(EventLevel level, string group, ApplicationType applicationType, string applicationName, string type, string details, string clientip, string hostip) {
return WriteEvent(level, group, applicationType, applicationName, null, null, null, null, type, details, clientip, hostip);
}
public static int WriteEvent(EventLevel level, string group, ApplicationType applicationType, string applicationName, string loggingUserType, string logginUserId, string affectedUserType, string affectedUserId, string type, string details, string clientip, string hostip) {
return WriteEvent(level.ToString(), group, applicationType, applicationName, loggingUserType, logginUserId, affectedUserType, affectedUserId, type, details, clientip, hostip);
}
public static int WriteEvent(string level, string group, ApplicationType applicationType, string applicationName, string loggingUserType, string logginUserId, string affectedUserType, string affectedUserId, string type, string details, string clientip, string hostip){
int? eventid = null;
string resultcode = null;
if (clientip == null)
clientip = ClientTools.IPAddress();
if (hostip == null)
hostip = ServerTools.IPv4Addresses.First().ToString();
XElement xDetails = XElement.Parse(string.Format("<details>{0}</details>", details));
using (LumberjackLinqDataContext db = new LumberjackLinqDataContext(ConfigurationManager.ConnectionStrings["LumberjackConnectionString"].ToString())) {
db.xspWriteDirectEvent(
applicationType.ToString(),
applicationName,
1,
loggingUserType,
logginUserId,
affectedUserType,
affectedUserId,
group,
level,
type,
xDetails,
clientip,
hostip,
ref eventid,
ref resultcode
);
}
return (int)eventid;
}
public static void WriteAsyncEvent(string level, string group, ApplicationType applicationType, string applicationName, string loggingUserType, string logginUserId, string affectedUserType, string affectedUserId, string type, string details, string clientip, string hostip) {
ParameterizedThreadStart work = new ParameterizedThreadStart(WriteAsyncEvent);
Thread thread = new Thread(work);
thread.Start(new EventParams() {
Level = level,
Group = group,
ApplicationType = applicationType,
ApplicationName = applicationName,
LoggingUserType = loggingUserType,
LogginUserId = logginUserId,
AffectedUserType = affectedUserType,
AffectedUserId = affectedUserId,
Type = type,
Details = details,
Clientip = clientip,
Hostip = hostip
});
}
private static void WriteAsyncEvent(object oParameters) {
EventParams parameters = (EventParams)oParameters;
int? eventid = null;
string resultcode = null;
if (parameters.Clientip == null)
parameters.Clientip = ClientTools.IPAddress();
if (parameters.Hostip == null)
parameters.Hostip = ServerTools.IPv4Addresses.First().ToString();
XElement xDetails = XElement.Parse(string.Format("<details>{0}</details>", parameters.Details));
using (LumberjackLinqDataContext db = new LumberjackLinqDataContext(ConfigurationManager.ConnectionStrings["LumberjackConnectionString"].ToString())) {
db.xspWriteDirectEvent(
parameters.ApplicationType.ToString(),
parameters.ApplicationName,
1,
parameters.LoggingUserType,
parameters.LogginUserId,
parameters.AffectedUserType,
parameters.AffectedUserId,
parameters.Group,
parameters.Level,
parameters.Type,
xDetails,
parameters.Clientip,
parameters.Hostip,
ref eventid,
ref resultcode
);
}
}
#endregion
#region WriteException
public static int WriteException(Request request, Exception e) {
return WriteException(request, e.GetType().ToString(), e.Message, e.StackTrace);
}
public static int WriteException(Request request, string type, string message, string stacktrace) {
int? eventid = null;
string resultcode = null;
Service service = ((Dictionary<string, Service>)HttpRuntime.Cache[Cache.CACHE_KEYS.Services])[request.ServiceKey];
string details = request.ToXml();
using (LumberjackLinqDataContext db = new LumberjackLinqDataContext(ConfigurationManager.ConnectionStrings["LumberjackConnectionString"].ToString())) {
db.xspWriteDirectException("Service", service.Name, service.Id, null, null, "Legion", request.Requestor.ClientIPAddress ?? request.Requestor.HostIPAddress, request.Requestor.HostIPAddress, type, message, details, stacktrace, ref eventid, ref resultcode);
}
return (int)eventid;
}
public static int WriteException(Exception e, string details) {
return WriteException(e.GetType().ToString(), e.Message, e.StackTrace, details);
}
public static int WriteException(string type, string message, string stacktrace, string details) {
string ip = ServerTools.IPv4Addresses.First().ToString();
return WriteException(type, message, stacktrace, details, ip, ip);
}
public static int WriteException(string type, string message, string stacktrace, string details, string clientip, string hostip) {
int? eventid = null;
string resultcode = null;
if (clientip == null)
clientip = ClientTools.IPAddress();
if (hostip == null)
hostip = ServerTools.IPv4Addresses.First().ToString();
using (LumberjackLinqDataContext db = new LumberjackLinqDataContext(ConfigurationManager.ConnectionStrings["LumberjackConnectionString"].ToString())) {
db.xspWriteDirectException("Legion", "Core", 1, null, null, "Legion", clientip, hostip, type, message, details, stacktrace, ref eventid, ref resultcode);
}
return (int)eventid;
}
#endregion
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using LanguageExt.Common;
using LanguageExt.Effects.Traits;
namespace LanguageExt.Pipes
{
/// <summary>
/// `Server` receives requests of type `REQ` and sends responses of type `RES`.
///
/// `Servers` only `respond` and never `request`.
/// </summary>
/// <remarks>
/// Upstream | Downstream
/// +---------+
/// | |
/// Void <== <== RES
/// | |
/// Unit ==> ==> REQ
/// | | |
/// +----|----+
/// |
/// A
/// </remarks>
public class Server<RT, REQ, RES, A> : Proxy<RT, Void, Unit, REQ, RES, A> where RT : struct, HasCancel<RT>
{
public readonly Proxy<RT, Void, Unit, REQ, RES, A> Value;
/// <summary>
/// Constructor
/// </summary>
/// <param name="value">Correctly shaped `Proxy` that represents a `Server`</param>
public Server(Proxy<RT, Void, Unit, REQ, RES, A> value) =>
Value = value;
/// <summary>
/// Calling this will effectively cast the sub-type to the base.
/// </summary>
/// <remarks>This type wraps up a `Proxy` for convenience, and so it's a `Proxy` proxy. So calling this method
/// isn't exactly the same as a cast operation, as it unwraps the `Proxy` from within. It has the same effect
/// however, and removes a level of indirection</remarks>
/// <returns>A general `Proxy` type from a more specialised type</returns>
[Pure]
public override Proxy<RT, Void, Unit, REQ, RES, A> ToProxy() =>
Value.ToProxy();
/// <summary>
/// Monadic bind operation, for chaining `Proxy` computations together.
/// </summary>
/// <param name="f">The bind function</param>
/// <typeparam name="B">The mapped bound value type</typeparam>
/// <returns>A new `Proxy` that represents the composition of this `Proxy` and the result of the bind operation</returns>
[Pure]
public override Proxy<RT, Void, Unit, REQ, RES, S> Bind<S>(Func<A, Proxy<RT, Void, Unit, REQ, RES, S>> f) =>
Value.Bind(f);
/// <summary>
/// Lifts a pure function into the `Proxy` domain, causing it to map the bound value within
/// </summary>
/// <param name="f">The map function</param>
/// <typeparam name="B">The mapped bound value type</typeparam>
/// <returns>A new `Proxy` that represents the composition of this `Proxy` and the result of the map operation</returns>
[Pure]
public override Proxy<RT, Void, Unit, REQ, RES, S> Map<S>(Func<A, S> f) =>
Value.Map(f);
/// <summary>
/// Monadic bind operation, for chaining `Server` computations together.
/// </summary>
/// <param name="f">The bind function</param>
/// <typeparam name="B">The mapped bound value type</typeparam>
/// <returns>A new `Proxy` that represents the composition of this `Proxy` and the result of the bind operation</returns>
[Pure]
public Server<RT, REQ, RES, B> Bind<B>(Func<A, Server<RT, REQ, RES, B>> f) =>
Value.Bind(f).ToServer();
/// <summary>
/// Monadic bind operation, for chaining `Server` computations together.
/// </summary>
/// <param name="f">The bind function</param>
/// <typeparam name="B">The mapped bound value type</typeparam>
/// <returns>A new `Proxy` that represents the composition of this `Proxy` and the result of the bind operation</returns>
[Pure]
public Server<RT, REQ, RES, B> SelectMany<B>(Func<A, Server<RT, REQ, RES, B>> f) =>
Value.Bind(f).ToServer();
/// <summary>
/// Monadic bind operation, for chaining `Server` computations together.
/// </summary>
/// <param name="f">The bind function</param>
/// <typeparam name="B">The mapped bound value type</typeparam>
/// <returns>A new `Proxy` that represents the composition of this `Proxy` and the result of the bind operation</returns>
[Pure]
public Server<RT, REQ, RES, C> SelectMany<B, C>(Func<A, Server<RT, REQ, RES, B>> f, Func<A, B, C> project) =>
Value.Bind(a => f(a).Map(b => project(a, b))).ToServer();
/// <summary>
/// Lifts a pure function into the `Proxy` domain, causing it to map the bound value within
/// </summary>
/// <param name="f">The map function</param>
/// <typeparam name="B">The mapped bound value type</typeparam>
/// <returns>A new `Proxy` that represents the composition of this `Proxy` and the result of the map operation</returns>
[Pure]
public new Server<RT, REQ, RES, B> Select<B>(Func<A, B> f) =>
Value.Map(f).ToServer();
/// <summary>
/// `For(body)` loops over the `Proxy p` replacing each `yield` with `body`
/// </summary>
/// <param name="body">Any `yield` found in the `Proxy` will be replaced with this function. It will be composed so
/// that the value yielded will be passed to the argument of the function. That returns a `Proxy` to continue the
/// processing of the computation</param>
/// <returns>A new `Proxy` that represents the composition of this `Proxy` and the function provided</returns>
[Pure]
public override Proxy<RT, Void, Unit, C1, C, A> For<C1, C>(Func<RES, Proxy<RT, Void, Unit, C1, C, REQ>> body) =>
Value.For(body);
/// <summary>
/// Applicative action
///
/// Invokes this `Proxy`, then the `Proxy r`
/// </summary>
/// <param name="r">`Proxy` to run after this one</param>
[Pure]
public override Proxy<RT, Void, Unit, REQ, RES, S> Action<S>(Proxy<RT, Void, Unit, REQ, RES, S> r) =>
Value.Action(r);
/// <summary>
/// Used by the various composition functions and when composing proxies with the `|` operator. You usually
/// wouldn't need to call this directly, instead either pipe them using `|` or call `Proxy.compose(lhs, rhs)`
/// </summary>
[Pure]
public override Proxy<RT, UOutA, AUInA, REQ, RES, A> ComposeRight<UOutA, AUInA>(Func<Void, Proxy<RT, UOutA, AUInA, Void, Unit, A>> lhs) =>
Value.ComposeRight(lhs);
/// <summary>
/// Used by the various composition functions and when composing proxies with the `|` operator. You usually
/// wouldn't need to call this directly, instead either pipe them using `|` or call `Proxy.compose(lhs, rhs)`
/// </summary>
[Pure]
public override Proxy<RT, UOutA, AUInA, REQ, RES, A> ComposeRight<UOutA, AUInA>(Func<Void, Proxy<RT, UOutA, AUInA, REQ, RES, Unit>> lhs) =>
Value.ComposeRight(lhs);
/// <summary>
/// Used by the various composition functions and when composing proxies with the `|` operator. You usually
/// wouldn't need to call this directly, instead either pipe them using `|` or call `Proxy.compose(lhs, rhs)`
/// </summary>
[Pure]
public override Proxy<RT, Void, Unit, DInC, DOutC, A> ComposeLeft<DInC, DOutC>(Func<RES, Proxy<RT, REQ, RES, DInC, DOutC, A>> rhs) =>
Value.ComposeLeft(rhs);
/// <summary>
/// Used by the various composition functions and when composing proxies with the `|` operator. You usually
/// wouldn't need to call this directly, instead either pipe them using `|` or call `Proxy.compose(lhs, rhs)`
/// </summary>
[Pure]
public override Proxy<RT, Void, Unit, DInC, DOutC, A> ComposeLeft<DInC, DOutC>(Func<RES, Proxy<RT, Void, Unit, DInC, DOutC, REQ>> rhs) =>
Value.ComposeLeft(rhs);
/// <summary>
/// Reverse the arrows of the `Proxy` to find its dual.
/// </summary>
/// <returns>The dual of `this`</returns>
[Pure]
public override Proxy<RT, RES, REQ, Unit, Void, A> Reflect() =>
Value.Reflect();
/// <summary>
///
/// Observe(lift (Pure(r))) = Observe(Pure(r))
/// Observe(lift (m.Bind(f))) = Observe(lift(m.Bind(x => lift(f(x)))))
///
/// This correctness comes at a small cost to performance, so use this function sparingly.
/// This function is a convenience for low-level pipes implementers. You do not need to
/// use observe if you stick to the safe API.
/// </summary>
[Pure]
public override Proxy<RT, Void, Unit, REQ, RES, A> Observe() =>
Value.Observe();
[Pure]
public void Deconstruct(out Proxy<RT, Void, Unit, REQ, RES, A> value) =>
value = Value;
/// <summary>
/// Monadic bind operation, for chaining `Server` computations together.
/// </summary>
/// <param name="f">The bind function</param>
/// <typeparam name="B">The mapped bound value type</typeparam>
/// <returns>A new `Proxy` that represents the composition of this `Proxy` and the result of the bind operation</returns>
[Pure]
public Server<RT, REQ, RES, B> SelectMany<B>(Func<A, Release<B>> bind) =>
Value.Bind(a => bind(a).InterpretServer<RT, REQ, RES>()).ToServer();
/// <summary>
/// Monadic bind operation, for chaining `Server` computations together.
/// </summary>
/// <param name="f">The bind function</param>
/// <typeparam name="B">The mapped bound value type</typeparam>
/// <returns>A new `Proxy` that represents the composition of this `Proxy` and the result of the bind operation</returns>
[Pure]
public Server<RT, REQ, RES, C> SelectMany<B, C>(Func<A, Release<B>> bind, Func<A, B, C> project) =>
SelectMany(a => bind(a).Select(b => project(a, b)));
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using Hyak.Common;
using Hyak.Common.Internals;
using Microsoft.Azure;
using Microsoft.WindowsAzure.Management.Compute;
using Microsoft.WindowsAzure.Management.Compute.Models;
namespace Microsoft.WindowsAzure.Management.Compute
{
/// <summary>
/// The Service Management API includes operations for managing the service
/// and virtual machine extension images in your publisher subscription.
/// </summary>
internal partial class ExtensionImageOperations : IServiceOperations<ComputeManagementClient>, IExtensionImageOperations
{
/// <summary>
/// Initializes a new instance of the ExtensionImageOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal ExtensionImageOperations(ComputeManagementClient client)
{
this._client = client;
}
private ComputeManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.WindowsAzure.Management.Compute.ComputeManagementClient.
/// </summary>
public ComputeManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Register a new extension. An extension is identified by the
/// combination of its ProviderNamespace and Type (case-sensitive
/// string). It is not allowed to register an extension with the same
/// identity (i.e. combination of ProviderNamespace and Type) of an
/// already-registered extension. To register new version of an
/// existing extension, the Update Extension API should be used.
/// </summary>
/// <param name='parameters'>
/// Required. Parameters supplied to the Register Virtual Machine
/// Extension Image operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> BeginRegisteringAsync(ExtensionImageRegisterParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Certificate != null)
{
if (parameters.Certificate.StoreLocation == null)
{
throw new ArgumentNullException("parameters.Certificate.StoreLocation");
}
}
if (parameters.ExtensionEndpoints != null)
{
if (parameters.ExtensionEndpoints.InputEndpoints != null)
{
foreach (ExtensionEndpointConfiguration.InputEndpoint inputEndpointsParameterItem in parameters.ExtensionEndpoints.InputEndpoints)
{
if (inputEndpointsParameterItem.LocalPort == null)
{
throw new ArgumentNullException("parameters.ExtensionEndpoints.InputEndpoints.LocalPort");
}
if (inputEndpointsParameterItem.Name == null)
{
throw new ArgumentNullException("parameters.ExtensionEndpoints.InputEndpoints.Name");
}
if (inputEndpointsParameterItem.Protocol == null)
{
throw new ArgumentNullException("parameters.ExtensionEndpoints.InputEndpoints.Protocol");
}
}
}
if (parameters.ExtensionEndpoints.InstanceInputEndpoints != null)
{
foreach (ExtensionEndpointConfiguration.InstanceInputEndpoint instanceInputEndpointsParameterItem in parameters.ExtensionEndpoints.InstanceInputEndpoints)
{
if (instanceInputEndpointsParameterItem.LocalPort == null)
{
throw new ArgumentNullException("parameters.ExtensionEndpoints.InstanceInputEndpoints.LocalPort");
}
if (instanceInputEndpointsParameterItem.Name == null)
{
throw new ArgumentNullException("parameters.ExtensionEndpoints.InstanceInputEndpoints.Name");
}
if (instanceInputEndpointsParameterItem.Protocol == null)
{
throw new ArgumentNullException("parameters.ExtensionEndpoints.InstanceInputEndpoints.Protocol");
}
}
}
if (parameters.ExtensionEndpoints.InternalEndpoints != null)
{
foreach (ExtensionEndpointConfiguration.InternalEndpoint internalEndpointsParameterItem in parameters.ExtensionEndpoints.InternalEndpoints)
{
if (internalEndpointsParameterItem.Name == null)
{
throw new ArgumentNullException("parameters.ExtensionEndpoints.InternalEndpoints.Name");
}
if (internalEndpointsParameterItem.Protocol == null)
{
throw new ArgumentNullException("parameters.ExtensionEndpoints.InternalEndpoints.Protocol");
}
}
}
}
if (parameters.LocalResources != null)
{
foreach (ExtensionLocalResourceConfiguration localResourcesParameterItem in parameters.LocalResources)
{
if (localResourcesParameterItem.Name == null)
{
throw new ArgumentNullException("parameters.LocalResources.Name");
}
}
}
if (parameters.ProviderNameSpace == null)
{
throw new ArgumentNullException("parameters.ProviderNameSpace");
}
if (parameters.Type == null)
{
throw new ArgumentNullException("parameters.Type");
}
if (parameters.Version == null)
{
throw new ArgumentNullException("parameters.Version");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "BeginRegisteringAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/services/extensions";
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Post;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2015-04-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
XDocument requestDoc = new XDocument();
XElement extensionImageElement = new XElement(XName.Get("ExtensionImage", "http://schemas.microsoft.com/windowsazure"));
requestDoc.Add(extensionImageElement);
XElement providerNameSpaceElement = new XElement(XName.Get("ProviderNameSpace", "http://schemas.microsoft.com/windowsazure"));
providerNameSpaceElement.Value = parameters.ProviderNameSpace;
extensionImageElement.Add(providerNameSpaceElement);
XElement typeElement = new XElement(XName.Get("Type", "http://schemas.microsoft.com/windowsazure"));
typeElement.Value = parameters.Type;
extensionImageElement.Add(typeElement);
XElement versionElement = new XElement(XName.Get("Version", "http://schemas.microsoft.com/windowsazure"));
versionElement.Value = parameters.Version;
extensionImageElement.Add(versionElement);
if (parameters.Label != null)
{
XElement labelElement = new XElement(XName.Get("Label", "http://schemas.microsoft.com/windowsazure"));
labelElement.Value = parameters.Label;
extensionImageElement.Add(labelElement);
}
if (parameters.HostingResources != null)
{
XElement hostingResourcesElement = new XElement(XName.Get("HostingResources", "http://schemas.microsoft.com/windowsazure"));
hostingResourcesElement.Value = parameters.HostingResources;
extensionImageElement.Add(hostingResourcesElement);
}
if (parameters.MediaLink != null)
{
XElement mediaLinkElement = new XElement(XName.Get("MediaLink", "http://schemas.microsoft.com/windowsazure"));
mediaLinkElement.Value = parameters.MediaLink.AbsoluteUri;
extensionImageElement.Add(mediaLinkElement);
}
if (parameters.Certificate != null)
{
XElement certificateElement = new XElement(XName.Get("Certificate", "http://schemas.microsoft.com/windowsazure"));
extensionImageElement.Add(certificateElement);
XElement storeLocationElement = new XElement(XName.Get("StoreLocation", "http://schemas.microsoft.com/windowsazure"));
storeLocationElement.Value = parameters.Certificate.StoreLocation;
certificateElement.Add(storeLocationElement);
if (parameters.Certificate.StoreName != null)
{
XElement storeNameElement = new XElement(XName.Get("StoreName", "http://schemas.microsoft.com/windowsazure"));
storeNameElement.Value = parameters.Certificate.StoreName;
certificateElement.Add(storeNameElement);
}
if (parameters.Certificate.ThumbprintRequired != null)
{
XElement thumbprintRequiredElement = new XElement(XName.Get("ThumbprintRequired", "http://schemas.microsoft.com/windowsazure"));
thumbprintRequiredElement.Value = parameters.Certificate.ThumbprintRequired.ToString().ToLower();
certificateElement.Add(thumbprintRequiredElement);
}
if (parameters.Certificate.ThumbprintAlgorithm != null)
{
XElement thumbprintAlgorithmElement = new XElement(XName.Get("ThumbprintAlgorithm", "http://schemas.microsoft.com/windowsazure"));
thumbprintAlgorithmElement.Value = parameters.Certificate.ThumbprintAlgorithm;
certificateElement.Add(thumbprintAlgorithmElement);
}
}
if (parameters.ExtensionEndpoints != null)
{
XElement endpointsElement = new XElement(XName.Get("Endpoints", "http://schemas.microsoft.com/windowsazure"));
extensionImageElement.Add(endpointsElement);
if (parameters.ExtensionEndpoints.InputEndpoints != null)
{
if (parameters.ExtensionEndpoints.InputEndpoints is ILazyCollection == false || ((ILazyCollection)parameters.ExtensionEndpoints.InputEndpoints).IsInitialized)
{
XElement inputEndpointsSequenceElement = new XElement(XName.Get("InputEndpoints", "http://schemas.microsoft.com/windowsazure"));
foreach (ExtensionEndpointConfiguration.InputEndpoint inputEndpointsItem in parameters.ExtensionEndpoints.InputEndpoints)
{
XElement inputEndpointElement = new XElement(XName.Get("InputEndpoint", "http://schemas.microsoft.com/windowsazure"));
inputEndpointsSequenceElement.Add(inputEndpointElement);
XElement nameElement = new XElement(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
nameElement.Value = inputEndpointsItem.Name;
inputEndpointElement.Add(nameElement);
XElement protocolElement = new XElement(XName.Get("Protocol", "http://schemas.microsoft.com/windowsazure"));
protocolElement.Value = inputEndpointsItem.Protocol;
inputEndpointElement.Add(protocolElement);
XElement portElement = new XElement(XName.Get("Port", "http://schemas.microsoft.com/windowsazure"));
portElement.Value = inputEndpointsItem.Port.ToString();
inputEndpointElement.Add(portElement);
XElement localPortElement = new XElement(XName.Get("LocalPort", "http://schemas.microsoft.com/windowsazure"));
localPortElement.Value = inputEndpointsItem.LocalPort;
inputEndpointElement.Add(localPortElement);
}
endpointsElement.Add(inputEndpointsSequenceElement);
}
}
if (parameters.ExtensionEndpoints.InternalEndpoints != null)
{
if (parameters.ExtensionEndpoints.InternalEndpoints is ILazyCollection == false || ((ILazyCollection)parameters.ExtensionEndpoints.InternalEndpoints).IsInitialized)
{
XElement internalEndpointsSequenceElement = new XElement(XName.Get("InternalEndpoints", "http://schemas.microsoft.com/windowsazure"));
foreach (ExtensionEndpointConfiguration.InternalEndpoint internalEndpointsItem in parameters.ExtensionEndpoints.InternalEndpoints)
{
XElement internalEndpointElement = new XElement(XName.Get("InternalEndpoint", "http://schemas.microsoft.com/windowsazure"));
internalEndpointsSequenceElement.Add(internalEndpointElement);
XElement nameElement2 = new XElement(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
nameElement2.Value = internalEndpointsItem.Name;
internalEndpointElement.Add(nameElement2);
XElement protocolElement2 = new XElement(XName.Get("Protocol", "http://schemas.microsoft.com/windowsazure"));
protocolElement2.Value = internalEndpointsItem.Protocol;
internalEndpointElement.Add(protocolElement2);
XElement portElement2 = new XElement(XName.Get("Port", "http://schemas.microsoft.com/windowsazure"));
portElement2.Value = internalEndpointsItem.Port.ToString();
internalEndpointElement.Add(portElement2);
}
endpointsElement.Add(internalEndpointsSequenceElement);
}
}
if (parameters.ExtensionEndpoints.InstanceInputEndpoints != null)
{
if (parameters.ExtensionEndpoints.InstanceInputEndpoints is ILazyCollection == false || ((ILazyCollection)parameters.ExtensionEndpoints.InstanceInputEndpoints).IsInitialized)
{
XElement instanceInputEndpointsSequenceElement = new XElement(XName.Get("InstanceInputEndpoints", "http://schemas.microsoft.com/windowsazure"));
foreach (ExtensionEndpointConfiguration.InstanceInputEndpoint instanceInputEndpointsItem in parameters.ExtensionEndpoints.InstanceInputEndpoints)
{
XElement instanceInputEndpointElement = new XElement(XName.Get("InstanceInputEndpoint", "http://schemas.microsoft.com/windowsazure"));
instanceInputEndpointsSequenceElement.Add(instanceInputEndpointElement);
XElement nameElement3 = new XElement(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
nameElement3.Value = instanceInputEndpointsItem.Name;
instanceInputEndpointElement.Add(nameElement3);
XElement protocolElement3 = new XElement(XName.Get("Protocol", "http://schemas.microsoft.com/windowsazure"));
protocolElement3.Value = instanceInputEndpointsItem.Protocol;
instanceInputEndpointElement.Add(protocolElement3);
XElement localPortElement2 = new XElement(XName.Get("LocalPort", "http://schemas.microsoft.com/windowsazure"));
localPortElement2.Value = instanceInputEndpointsItem.LocalPort;
instanceInputEndpointElement.Add(localPortElement2);
XElement fixedPortMinElement = new XElement(XName.Get("FixedPortMin", "http://schemas.microsoft.com/windowsazure"));
fixedPortMinElement.Value = instanceInputEndpointsItem.FixedPortMin.ToString();
instanceInputEndpointElement.Add(fixedPortMinElement);
XElement fixedPortMaxElement = new XElement(XName.Get("FixedPortMax", "http://schemas.microsoft.com/windowsazure"));
fixedPortMaxElement.Value = instanceInputEndpointsItem.FixedPortMax.ToString();
instanceInputEndpointElement.Add(fixedPortMaxElement);
}
endpointsElement.Add(instanceInputEndpointsSequenceElement);
}
}
}
if (parameters.PublicConfigurationSchema != null)
{
XElement publicConfigurationSchemaElement = new XElement(XName.Get("PublicConfigurationSchema", "http://schemas.microsoft.com/windowsazure"));
publicConfigurationSchemaElement.Value = TypeConversion.ToBase64String(parameters.PublicConfigurationSchema);
extensionImageElement.Add(publicConfigurationSchemaElement);
}
if (parameters.PrivateConfigurationSchema != null)
{
XElement privateConfigurationSchemaElement = new XElement(XName.Get("PrivateConfigurationSchema", "http://schemas.microsoft.com/windowsazure"));
privateConfigurationSchemaElement.Value = TypeConversion.ToBase64String(parameters.PrivateConfigurationSchema);
extensionImageElement.Add(privateConfigurationSchemaElement);
}
if (parameters.Description != null)
{
XElement descriptionElement = new XElement(XName.Get("Description", "http://schemas.microsoft.com/windowsazure"));
descriptionElement.Value = parameters.Description;
extensionImageElement.Add(descriptionElement);
}
if (parameters.PublisherName != null)
{
XElement publisherNameElement = new XElement(XName.Get("PublisherName", "http://schemas.microsoft.com/windowsazure"));
publisherNameElement.Value = parameters.PublisherName;
extensionImageElement.Add(publisherNameElement);
}
if (parameters.PublishedDate != null)
{
XElement publishedDateElement = new XElement(XName.Get("PublishedDate", "http://schemas.microsoft.com/windowsazure"));
publishedDateElement.Value = string.Format(CultureInfo.InvariantCulture, "{0:O}", parameters.PublishedDate.Value.ToUniversalTime());
extensionImageElement.Add(publishedDateElement);
}
if (parameters.LocalResources != null)
{
XElement localResourcesSequenceElement = new XElement(XName.Get("LocalResources", "http://schemas.microsoft.com/windowsazure"));
foreach (ExtensionLocalResourceConfiguration localResourcesItem in parameters.LocalResources)
{
XElement localResourceElement = new XElement(XName.Get("LocalResource", "http://schemas.microsoft.com/windowsazure"));
localResourcesSequenceElement.Add(localResourceElement);
XElement nameElement4 = new XElement(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
nameElement4.Value = localResourcesItem.Name;
localResourceElement.Add(nameElement4);
if (localResourcesItem.SizeInMB != null)
{
XElement sizeInMBElement = new XElement(XName.Get("SizeInMB", "http://schemas.microsoft.com/windowsazure"));
sizeInMBElement.Value = localResourcesItem.SizeInMB.ToString();
localResourceElement.Add(sizeInMBElement);
}
}
extensionImageElement.Add(localResourcesSequenceElement);
}
if (parameters.BlockRoleUponFailure != null)
{
XElement blockRoleUponFailureElement = new XElement(XName.Get("BlockRoleUponFailure", "http://schemas.microsoft.com/windowsazure"));
blockRoleUponFailureElement.Value = parameters.BlockRoleUponFailure.ToString().ToLower();
extensionImageElement.Add(blockRoleUponFailureElement);
}
if (parameters.IsInternalExtension != null)
{
XElement isInternalExtensionElement = new XElement(XName.Get("IsInternalExtension", "http://schemas.microsoft.com/windowsazure"));
isInternalExtensionElement.Value = parameters.IsInternalExtension.ToString().ToLower();
extensionImageElement.Add(isInternalExtensionElement);
}
if (parameters.SampleConfig != null)
{
XElement sampleConfigElement = new XElement(XName.Get("SampleConfig", "http://schemas.microsoft.com/windowsazure"));
sampleConfigElement.Value = TypeConversion.ToBase64String(parameters.SampleConfig);
extensionImageElement.Add(sampleConfigElement);
}
if (parameters.ReplicationCompleted != null)
{
XElement replicationCompletedElement = new XElement(XName.Get("ReplicationCompleted", "http://schemas.microsoft.com/windowsazure"));
replicationCompletedElement.Value = parameters.ReplicationCompleted.ToString().ToLower();
extensionImageElement.Add(replicationCompletedElement);
}
if (parameters.Eula != null)
{
XElement eulaElement = new XElement(XName.Get("Eula", "http://schemas.microsoft.com/windowsazure"));
eulaElement.Value = parameters.Eula.AbsoluteUri;
extensionImageElement.Add(eulaElement);
}
if (parameters.PrivacyUri != null)
{
XElement privacyUriElement = new XElement(XName.Get("PrivacyUri", "http://schemas.microsoft.com/windowsazure"));
privacyUriElement.Value = parameters.PrivacyUri.AbsoluteUri;
extensionImageElement.Add(privacyUriElement);
}
if (parameters.HomepageUri != null)
{
XElement homepageUriElement = new XElement(XName.Get("HomepageUri", "http://schemas.microsoft.com/windowsazure"));
homepageUriElement.Value = parameters.HomepageUri.AbsoluteUri;
extensionImageElement.Add(homepageUriElement);
}
if (parameters.IsJsonExtension != null)
{
XElement isJsonExtensionElement = new XElement(XName.Get("IsJsonExtension", "http://schemas.microsoft.com/windowsazure"));
isJsonExtensionElement.Value = parameters.IsJsonExtension.ToString().ToLower();
extensionImageElement.Add(isJsonExtensionElement);
}
if (parameters.DisallowMajorVersionUpgrade != null)
{
XElement disallowMajorVersionUpgradeElement = new XElement(XName.Get("DisallowMajorVersionUpgrade", "http://schemas.microsoft.com/windowsazure"));
disallowMajorVersionUpgradeElement.Value = parameters.DisallowMajorVersionUpgrade.ToString().ToLower();
extensionImageElement.Add(disallowMajorVersionUpgradeElement);
}
if (parameters.SupportedOS != null)
{
XElement supportedOSElement = new XElement(XName.Get("SupportedOS", "http://schemas.microsoft.com/windowsazure"));
supportedOSElement.Value = parameters.SupportedOS;
extensionImageElement.Add(supportedOSElement);
}
if (parameters.CompanyName != null)
{
XElement companyNameElement = new XElement(XName.Get("CompanyName", "http://schemas.microsoft.com/windowsazure"));
companyNameElement.Value = parameters.CompanyName;
extensionImageElement.Add(companyNameElement);
}
if (parameters.Regions != null)
{
XElement regionsElement = new XElement(XName.Get("Regions", "http://schemas.microsoft.com/windowsazure"));
regionsElement.Value = parameters.Regions;
extensionImageElement.Add(regionsElement);
}
requestContent = requestDoc.ToString();
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Unregister a version of an extension that was previously registered
/// using either the Register Extension or Update Extension APIs. An
/// extension version is identified by the combination of its
/// ProviderNamespace, Type and Version which are specified when
/// registering the extension. Unregistering is only allowed for
/// internal extensions, that is, the extensions for which the
/// IsInternalExtension field is set to 'true' during registration or
/// during an update. There is a quota (15) on the number of
/// extensions that can be registered per subscription. If your
/// subscription runs out of quota, you will wither need to unregister
/// some of the internal extensions or contact Azure (same email used
/// to become a publisher) to increase the quota.
/// </summary>
/// <param name='providerNamespace'>
/// Required. The provider namespace of the extension image to
/// unregister.
/// </param>
/// <param name='type'>
/// Required. The type of the extension image to unregister.
/// </param>
/// <param name='version'>
/// Required. The version of the extension image to unregister.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> BeginUnregisteringAsync(string providerNamespace, string type, string version, CancellationToken cancellationToken)
{
// Validate
if (providerNamespace == null)
{
throw new ArgumentNullException("providerNamespace");
}
if (type == null)
{
throw new ArgumentNullException("type");
}
if (version == null)
{
throw new ArgumentNullException("version");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("providerNamespace", providerNamespace);
tracingParameters.Add("type", type);
tracingParameters.Add("version", version);
TracingAdapter.Enter(invocationId, this, "BeginUnregisteringAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/services/extensions/";
url = url + Uri.EscapeDataString(providerNamespace);
url = url + "/";
url = url + Uri.EscapeDataString(type);
url = url + "/";
url = url + Uri.EscapeDataString(version);
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Delete;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2015-04-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Update a new extension. It is allowed to update an extension which
/// had already been registered with the same identity (i.e.
/// combination of ProviderNamespace and Type) but with different
/// version. It will fail if the extension to update has an identity
/// that has not been registered before, or there is already an
/// extension with the same identity and same version.
/// </summary>
/// <param name='parameters'>
/// Required. Parameters supplied to the Update Virtual Machine
/// Extension Image operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> BeginUpdatingAsync(ExtensionImageUpdateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Certificate != null)
{
if (parameters.Certificate.StoreLocation == null)
{
throw new ArgumentNullException("parameters.Certificate.StoreLocation");
}
}
if (parameters.ExtensionEndpoints != null)
{
if (parameters.ExtensionEndpoints.InputEndpoints != null)
{
foreach (ExtensionEndpointConfiguration.InputEndpoint inputEndpointsParameterItem in parameters.ExtensionEndpoints.InputEndpoints)
{
if (inputEndpointsParameterItem.LocalPort == null)
{
throw new ArgumentNullException("parameters.ExtensionEndpoints.InputEndpoints.LocalPort");
}
if (inputEndpointsParameterItem.Name == null)
{
throw new ArgumentNullException("parameters.ExtensionEndpoints.InputEndpoints.Name");
}
if (inputEndpointsParameterItem.Protocol == null)
{
throw new ArgumentNullException("parameters.ExtensionEndpoints.InputEndpoints.Protocol");
}
}
}
if (parameters.ExtensionEndpoints.InstanceInputEndpoints != null)
{
foreach (ExtensionEndpointConfiguration.InstanceInputEndpoint instanceInputEndpointsParameterItem in parameters.ExtensionEndpoints.InstanceInputEndpoints)
{
if (instanceInputEndpointsParameterItem.LocalPort == null)
{
throw new ArgumentNullException("parameters.ExtensionEndpoints.InstanceInputEndpoints.LocalPort");
}
if (instanceInputEndpointsParameterItem.Name == null)
{
throw new ArgumentNullException("parameters.ExtensionEndpoints.InstanceInputEndpoints.Name");
}
if (instanceInputEndpointsParameterItem.Protocol == null)
{
throw new ArgumentNullException("parameters.ExtensionEndpoints.InstanceInputEndpoints.Protocol");
}
}
}
if (parameters.ExtensionEndpoints.InternalEndpoints != null)
{
foreach (ExtensionEndpointConfiguration.InternalEndpoint internalEndpointsParameterItem in parameters.ExtensionEndpoints.InternalEndpoints)
{
if (internalEndpointsParameterItem.Name == null)
{
throw new ArgumentNullException("parameters.ExtensionEndpoints.InternalEndpoints.Name");
}
if (internalEndpointsParameterItem.Protocol == null)
{
throw new ArgumentNullException("parameters.ExtensionEndpoints.InternalEndpoints.Protocol");
}
}
}
}
if (parameters.LocalResources != null)
{
foreach (ExtensionLocalResourceConfiguration localResourcesParameterItem in parameters.LocalResources)
{
if (localResourcesParameterItem.Name == null)
{
throw new ArgumentNullException("parameters.LocalResources.Name");
}
}
}
if (parameters.ProviderNameSpace == null)
{
throw new ArgumentNullException("parameters.ProviderNameSpace");
}
if (parameters.Type == null)
{
throw new ArgumentNullException("parameters.Type");
}
if (parameters.Version == null)
{
throw new ArgumentNullException("parameters.Version");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "BeginUpdatingAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/services/extensions";
List<string> queryParameters = new List<string>();
queryParameters.Add("action=update");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2015-04-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
XDocument requestDoc = new XDocument();
XElement extensionImageElement = new XElement(XName.Get("ExtensionImage", "http://schemas.microsoft.com/windowsazure"));
requestDoc.Add(extensionImageElement);
XElement providerNameSpaceElement = new XElement(XName.Get("ProviderNameSpace", "http://schemas.microsoft.com/windowsazure"));
providerNameSpaceElement.Value = parameters.ProviderNameSpace;
extensionImageElement.Add(providerNameSpaceElement);
XElement typeElement = new XElement(XName.Get("Type", "http://schemas.microsoft.com/windowsazure"));
typeElement.Value = parameters.Type;
extensionImageElement.Add(typeElement);
XElement versionElement = new XElement(XName.Get("Version", "http://schemas.microsoft.com/windowsazure"));
versionElement.Value = parameters.Version;
extensionImageElement.Add(versionElement);
if (parameters.Label != null)
{
XElement labelElement = new XElement(XName.Get("Label", "http://schemas.microsoft.com/windowsazure"));
labelElement.Value = parameters.Label;
extensionImageElement.Add(labelElement);
}
if (parameters.HostingResources != null)
{
XElement hostingResourcesElement = new XElement(XName.Get("HostingResources", "http://schemas.microsoft.com/windowsazure"));
hostingResourcesElement.Value = parameters.HostingResources;
extensionImageElement.Add(hostingResourcesElement);
}
if (parameters.MediaLink != null)
{
XElement mediaLinkElement = new XElement(XName.Get("MediaLink", "http://schemas.microsoft.com/windowsazure"));
mediaLinkElement.Value = parameters.MediaLink.AbsoluteUri;
extensionImageElement.Add(mediaLinkElement);
}
if (parameters.Certificate != null)
{
XElement certificateElement = new XElement(XName.Get("Certificate", "http://schemas.microsoft.com/windowsazure"));
extensionImageElement.Add(certificateElement);
XElement storeLocationElement = new XElement(XName.Get("StoreLocation", "http://schemas.microsoft.com/windowsazure"));
storeLocationElement.Value = parameters.Certificate.StoreLocation;
certificateElement.Add(storeLocationElement);
if (parameters.Certificate.StoreName != null)
{
XElement storeNameElement = new XElement(XName.Get("StoreName", "http://schemas.microsoft.com/windowsazure"));
storeNameElement.Value = parameters.Certificate.StoreName;
certificateElement.Add(storeNameElement);
}
if (parameters.Certificate.ThumbprintRequired != null)
{
XElement thumbprintRequiredElement = new XElement(XName.Get("ThumbprintRequired", "http://schemas.microsoft.com/windowsazure"));
thumbprintRequiredElement.Value = parameters.Certificate.ThumbprintRequired.ToString().ToLower();
certificateElement.Add(thumbprintRequiredElement);
}
if (parameters.Certificate.ThumbprintAlgorithm != null)
{
XElement thumbprintAlgorithmElement = new XElement(XName.Get("ThumbprintAlgorithm", "http://schemas.microsoft.com/windowsazure"));
thumbprintAlgorithmElement.Value = parameters.Certificate.ThumbprintAlgorithm;
certificateElement.Add(thumbprintAlgorithmElement);
}
}
if (parameters.ExtensionEndpoints != null)
{
XElement endpointsElement = new XElement(XName.Get("Endpoints", "http://schemas.microsoft.com/windowsazure"));
extensionImageElement.Add(endpointsElement);
if (parameters.ExtensionEndpoints.InputEndpoints != null)
{
if (parameters.ExtensionEndpoints.InputEndpoints is ILazyCollection == false || ((ILazyCollection)parameters.ExtensionEndpoints.InputEndpoints).IsInitialized)
{
XElement inputEndpointsSequenceElement = new XElement(XName.Get("InputEndpoints", "http://schemas.microsoft.com/windowsazure"));
foreach (ExtensionEndpointConfiguration.InputEndpoint inputEndpointsItem in parameters.ExtensionEndpoints.InputEndpoints)
{
XElement inputEndpointElement = new XElement(XName.Get("InputEndpoint", "http://schemas.microsoft.com/windowsazure"));
inputEndpointsSequenceElement.Add(inputEndpointElement);
XElement nameElement = new XElement(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
nameElement.Value = inputEndpointsItem.Name;
inputEndpointElement.Add(nameElement);
XElement protocolElement = new XElement(XName.Get("Protocol", "http://schemas.microsoft.com/windowsazure"));
protocolElement.Value = inputEndpointsItem.Protocol;
inputEndpointElement.Add(protocolElement);
XElement portElement = new XElement(XName.Get("Port", "http://schemas.microsoft.com/windowsazure"));
portElement.Value = inputEndpointsItem.Port.ToString();
inputEndpointElement.Add(portElement);
XElement localPortElement = new XElement(XName.Get("LocalPort", "http://schemas.microsoft.com/windowsazure"));
localPortElement.Value = inputEndpointsItem.LocalPort;
inputEndpointElement.Add(localPortElement);
}
endpointsElement.Add(inputEndpointsSequenceElement);
}
}
if (parameters.ExtensionEndpoints.InternalEndpoints != null)
{
if (parameters.ExtensionEndpoints.InternalEndpoints is ILazyCollection == false || ((ILazyCollection)parameters.ExtensionEndpoints.InternalEndpoints).IsInitialized)
{
XElement internalEndpointsSequenceElement = new XElement(XName.Get("InternalEndpoints", "http://schemas.microsoft.com/windowsazure"));
foreach (ExtensionEndpointConfiguration.InternalEndpoint internalEndpointsItem in parameters.ExtensionEndpoints.InternalEndpoints)
{
XElement internalEndpointElement = new XElement(XName.Get("InternalEndpoint", "http://schemas.microsoft.com/windowsazure"));
internalEndpointsSequenceElement.Add(internalEndpointElement);
XElement nameElement2 = new XElement(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
nameElement2.Value = internalEndpointsItem.Name;
internalEndpointElement.Add(nameElement2);
XElement protocolElement2 = new XElement(XName.Get("Protocol", "http://schemas.microsoft.com/windowsazure"));
protocolElement2.Value = internalEndpointsItem.Protocol;
internalEndpointElement.Add(protocolElement2);
XElement portElement2 = new XElement(XName.Get("Port", "http://schemas.microsoft.com/windowsazure"));
portElement2.Value = internalEndpointsItem.Port.ToString();
internalEndpointElement.Add(portElement2);
}
endpointsElement.Add(internalEndpointsSequenceElement);
}
}
if (parameters.ExtensionEndpoints.InstanceInputEndpoints != null)
{
if (parameters.ExtensionEndpoints.InstanceInputEndpoints is ILazyCollection == false || ((ILazyCollection)parameters.ExtensionEndpoints.InstanceInputEndpoints).IsInitialized)
{
XElement instanceInputEndpointsSequenceElement = new XElement(XName.Get("InstanceInputEndpoints", "http://schemas.microsoft.com/windowsazure"));
foreach (ExtensionEndpointConfiguration.InstanceInputEndpoint instanceInputEndpointsItem in parameters.ExtensionEndpoints.InstanceInputEndpoints)
{
XElement instanceInputEndpointElement = new XElement(XName.Get("InstanceInputEndpoint", "http://schemas.microsoft.com/windowsazure"));
instanceInputEndpointsSequenceElement.Add(instanceInputEndpointElement);
XElement nameElement3 = new XElement(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
nameElement3.Value = instanceInputEndpointsItem.Name;
instanceInputEndpointElement.Add(nameElement3);
XElement protocolElement3 = new XElement(XName.Get("Protocol", "http://schemas.microsoft.com/windowsazure"));
protocolElement3.Value = instanceInputEndpointsItem.Protocol;
instanceInputEndpointElement.Add(protocolElement3);
XElement localPortElement2 = new XElement(XName.Get("LocalPort", "http://schemas.microsoft.com/windowsazure"));
localPortElement2.Value = instanceInputEndpointsItem.LocalPort;
instanceInputEndpointElement.Add(localPortElement2);
XElement fixedPortMinElement = new XElement(XName.Get("FixedPortMin", "http://schemas.microsoft.com/windowsazure"));
fixedPortMinElement.Value = instanceInputEndpointsItem.FixedPortMin.ToString();
instanceInputEndpointElement.Add(fixedPortMinElement);
XElement fixedPortMaxElement = new XElement(XName.Get("FixedPortMax", "http://schemas.microsoft.com/windowsazure"));
fixedPortMaxElement.Value = instanceInputEndpointsItem.FixedPortMax.ToString();
instanceInputEndpointElement.Add(fixedPortMaxElement);
}
endpointsElement.Add(instanceInputEndpointsSequenceElement);
}
}
}
if (parameters.PublicConfigurationSchema != null)
{
XElement publicConfigurationSchemaElement = new XElement(XName.Get("PublicConfigurationSchema", "http://schemas.microsoft.com/windowsazure"));
publicConfigurationSchemaElement.Value = TypeConversion.ToBase64String(parameters.PublicConfigurationSchema);
extensionImageElement.Add(publicConfigurationSchemaElement);
}
if (parameters.PrivateConfigurationSchema != null)
{
XElement privateConfigurationSchemaElement = new XElement(XName.Get("PrivateConfigurationSchema", "http://schemas.microsoft.com/windowsazure"));
privateConfigurationSchemaElement.Value = TypeConversion.ToBase64String(parameters.PrivateConfigurationSchema);
extensionImageElement.Add(privateConfigurationSchemaElement);
}
if (parameters.Description != null)
{
XElement descriptionElement = new XElement(XName.Get("Description", "http://schemas.microsoft.com/windowsazure"));
descriptionElement.Value = parameters.Description;
extensionImageElement.Add(descriptionElement);
}
if (parameters.PublisherName != null)
{
XElement publisherNameElement = new XElement(XName.Get("PublisherName", "http://schemas.microsoft.com/windowsazure"));
publisherNameElement.Value = parameters.PublisherName;
extensionImageElement.Add(publisherNameElement);
}
if (parameters.PublishedDate != null)
{
XElement publishedDateElement = new XElement(XName.Get("PublishedDate", "http://schemas.microsoft.com/windowsazure"));
publishedDateElement.Value = string.Format(CultureInfo.InvariantCulture, "{0:O}", parameters.PublishedDate.Value.ToUniversalTime());
extensionImageElement.Add(publishedDateElement);
}
if (parameters.LocalResources != null)
{
XElement localResourcesSequenceElement = new XElement(XName.Get("LocalResources", "http://schemas.microsoft.com/windowsazure"));
foreach (ExtensionLocalResourceConfiguration localResourcesItem in parameters.LocalResources)
{
XElement localResourceElement = new XElement(XName.Get("LocalResource", "http://schemas.microsoft.com/windowsazure"));
localResourcesSequenceElement.Add(localResourceElement);
XElement nameElement4 = new XElement(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
nameElement4.Value = localResourcesItem.Name;
localResourceElement.Add(nameElement4);
if (localResourcesItem.SizeInMB != null)
{
XElement sizeInMBElement = new XElement(XName.Get("SizeInMB", "http://schemas.microsoft.com/windowsazure"));
sizeInMBElement.Value = localResourcesItem.SizeInMB.ToString();
localResourceElement.Add(sizeInMBElement);
}
}
extensionImageElement.Add(localResourcesSequenceElement);
}
if (parameters.BlockRoleUponFailure != null)
{
XElement blockRoleUponFailureElement = new XElement(XName.Get("BlockRoleUponFailure", "http://schemas.microsoft.com/windowsazure"));
blockRoleUponFailureElement.Value = parameters.BlockRoleUponFailure.ToString().ToLower();
extensionImageElement.Add(blockRoleUponFailureElement);
}
if (parameters.IsInternalExtension != null)
{
XElement isInternalExtensionElement = new XElement(XName.Get("IsInternalExtension", "http://schemas.microsoft.com/windowsazure"));
isInternalExtensionElement.Value = parameters.IsInternalExtension.ToString().ToLower();
extensionImageElement.Add(isInternalExtensionElement);
}
if (parameters.SampleConfig != null)
{
XElement sampleConfigElement = new XElement(XName.Get("SampleConfig", "http://schemas.microsoft.com/windowsazure"));
sampleConfigElement.Value = TypeConversion.ToBase64String(parameters.SampleConfig);
extensionImageElement.Add(sampleConfigElement);
}
if (parameters.ReplicationCompleted != null)
{
XElement replicationCompletedElement = new XElement(XName.Get("ReplicationCompleted", "http://schemas.microsoft.com/windowsazure"));
replicationCompletedElement.Value = parameters.ReplicationCompleted.ToString().ToLower();
extensionImageElement.Add(replicationCompletedElement);
}
if (parameters.Eula != null)
{
XElement eulaElement = new XElement(XName.Get("Eula", "http://schemas.microsoft.com/windowsazure"));
eulaElement.Value = parameters.Eula.AbsoluteUri;
extensionImageElement.Add(eulaElement);
}
if (parameters.PrivacyUri != null)
{
XElement privacyUriElement = new XElement(XName.Get("PrivacyUri", "http://schemas.microsoft.com/windowsazure"));
privacyUriElement.Value = parameters.PrivacyUri.AbsoluteUri;
extensionImageElement.Add(privacyUriElement);
}
if (parameters.HomepageUri != null)
{
XElement homepageUriElement = new XElement(XName.Get("HomepageUri", "http://schemas.microsoft.com/windowsazure"));
homepageUriElement.Value = parameters.HomepageUri.AbsoluteUri;
extensionImageElement.Add(homepageUriElement);
}
if (parameters.IsJsonExtension != null)
{
XElement isJsonExtensionElement = new XElement(XName.Get("IsJsonExtension", "http://schemas.microsoft.com/windowsazure"));
isJsonExtensionElement.Value = parameters.IsJsonExtension.ToString().ToLower();
extensionImageElement.Add(isJsonExtensionElement);
}
if (parameters.DisallowMajorVersionUpgrade != null)
{
XElement disallowMajorVersionUpgradeElement = new XElement(XName.Get("DisallowMajorVersionUpgrade", "http://schemas.microsoft.com/windowsazure"));
disallowMajorVersionUpgradeElement.Value = parameters.DisallowMajorVersionUpgrade.ToString().ToLower();
extensionImageElement.Add(disallowMajorVersionUpgradeElement);
}
if (parameters.SupportedOS != null)
{
XElement supportedOSElement = new XElement(XName.Get("SupportedOS", "http://schemas.microsoft.com/windowsazure"));
supportedOSElement.Value = parameters.SupportedOS;
extensionImageElement.Add(supportedOSElement);
}
if (parameters.CompanyName != null)
{
XElement companyNameElement = new XElement(XName.Get("CompanyName", "http://schemas.microsoft.com/windowsazure"));
companyNameElement.Value = parameters.CompanyName;
extensionImageElement.Add(companyNameElement);
}
if (parameters.Regions != null)
{
XElement regionsElement = new XElement(XName.Get("Regions", "http://schemas.microsoft.com/windowsazure"));
regionsElement.Value = parameters.Regions;
extensionImageElement.Add(regionsElement);
}
requestContent = requestDoc.ToString();
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Register a new extension. An extension is identified by the
/// combination of its ProviderNamespace and Type (case-sensitive
/// string). It is not allowed to register an extension with the same
/// identity (i.e. combination of ProviderNamespace and Type) of an
/// already-registered extension. To register new version of an
/// existing extension, the Update Extension API should be used.
/// </summary>
/// <param name='parameters'>
/// Required. Parameters supplied to the Register Virtual Machine
/// Extension Image operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request and error information regarding
/// the failure.
/// </returns>
public async Task<OperationStatusResponse> RegisterAsync(ExtensionImageRegisterParameters parameters, CancellationToken cancellationToken)
{
ComputeManagementClient client = this.Client;
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "RegisterAsync", tracingParameters);
}
cancellationToken.ThrowIfCancellationRequested();
AzureOperationResponse response = await client.ExtensionImages.BeginRegisteringAsync(parameters, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
OperationStatusResponse result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);
int delayInSeconds = 30;
if (client.LongRunningOperationInitialTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationInitialTimeout;
}
while (result.Status == OperationStatus.InProgress)
{
cancellationToken.ThrowIfCancellationRequested();
await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);
delayInSeconds = 30;
if (client.LongRunningOperationRetryTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationRetryTimeout;
}
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
if (result.Status != OperationStatus.Succeeded)
{
if (result.Error != null)
{
CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message);
ex.Error = new CloudError();
ex.Error.Code = result.Error.Code;
ex.Error.Message = result.Error.Message;
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
else
{
CloudException ex = new CloudException("");
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
}
return result;
}
/// <summary>
/// Unregister a version of an extension that was previously registered
/// using either the Register Extension or Update Extension APIs. An
/// extension version is identified by the combination of its
/// ProviderNamespace, Type and Version which are specified when
/// registering the extension. Unregistering is only allowed for
/// internal extensions, that is, the extensions for which the
/// IsInternalExtension field is set to 'true' during registration or
/// during an update. There is a quota (15) on the number of
/// extensions that can be registered per subscription. If your
/// subscription runs out of quota, you will wither need to unregister
/// some of the internal extensions or contact Azure (same email used
/// to become a publisher) to increase the quota.
/// </summary>
/// <param name='providerNamespace'>
/// Required. The provider namespace of the extension image to
/// unregister.
/// </param>
/// <param name='type'>
/// Required. The type of the extension image to unregister.
/// </param>
/// <param name='version'>
/// Required. The version of the extension image to unregister.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request and error information regarding
/// the failure.
/// </returns>
public async Task<OperationStatusResponse> UnregisterAsync(string providerNamespace, string type, string version, CancellationToken cancellationToken)
{
ComputeManagementClient client = this.Client;
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("providerNamespace", providerNamespace);
tracingParameters.Add("type", type);
tracingParameters.Add("version", version);
TracingAdapter.Enter(invocationId, this, "UnregisterAsync", tracingParameters);
}
cancellationToken.ThrowIfCancellationRequested();
AzureOperationResponse response = await client.ExtensionImages.BeginUnregisteringAsync(providerNamespace, type, version, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
OperationStatusResponse result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);
int delayInSeconds = 30;
if (client.LongRunningOperationInitialTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationInitialTimeout;
}
while (result.Status == OperationStatus.InProgress)
{
cancellationToken.ThrowIfCancellationRequested();
await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);
delayInSeconds = 30;
if (client.LongRunningOperationRetryTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationRetryTimeout;
}
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
if (result.Status != OperationStatus.Succeeded)
{
if (result.Error != null)
{
CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message);
ex.Error = new CloudError();
ex.Error.Code = result.Error.Code;
ex.Error.Message = result.Error.Message;
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
else
{
CloudException ex = new CloudException("");
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
}
return result;
}
/// <summary>
/// Update a new extension. It is allowed to update an extension which
/// had already been registered with the same identity (i.e.
/// combination of ProviderNamespace and Type) but with different
/// version. It will fail if the extension to update has an identity
/// that has not been registered before, or there is already an
/// extension with the same identity and same version.
/// </summary>
/// <param name='parameters'>
/// Required. Parameters supplied to the Update Virtual Machine
/// Extension Image operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request and error information regarding
/// the failure.
/// </returns>
public async Task<OperationStatusResponse> UpdateAsync(ExtensionImageUpdateParameters parameters, CancellationToken cancellationToken)
{
ComputeManagementClient client = this.Client;
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "UpdateAsync", tracingParameters);
}
cancellationToken.ThrowIfCancellationRequested();
AzureOperationResponse response = await client.ExtensionImages.BeginUpdatingAsync(parameters, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
OperationStatusResponse result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);
int delayInSeconds = 30;
if (client.LongRunningOperationInitialTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationInitialTimeout;
}
while (result.Status == OperationStatus.InProgress)
{
cancellationToken.ThrowIfCancellationRequested();
await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);
delayInSeconds = 30;
if (client.LongRunningOperationRetryTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationRetryTimeout;
}
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
if (result.Status != OperationStatus.Succeeded)
{
if (result.Error != null)
{
CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message);
ex.Error = new CloudError();
ex.Error.Code = result.Error.Code;
ex.Error.Message = result.Error.Message;
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
else
{
CloudException ex = new CloudException("");
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
}
return result;
}
}
}
| |
/*
* Copyright (c) 2015, InWorldz Halcyon Developers
* 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 halcyon nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Xml;
using System.Net;
using System.Reflection;
using System.Timers;
using log4net;
using Nini.Config;
using Nwc.XmlRpc;
using OpenMetaverse;
using InWorldz.JWT;
using OpenSim;
using OpenSim.Framework;
using OpenSim.Framework.Communications;
using OpenSim.Framework.Communications.Cache;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Region.CoreModules.World.Terrain;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
namespace InWorldz.RemoteAdmin
{
public class RemoteAdmin
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private Timer sessionTimer;
private Dictionary<UUID, DateTime> m_activeSessions =
new Dictionary<UUID, DateTime>();
private Dictionary<string, Dictionary<string, XmlMethodHandler>> m_commands =
new Dictionary<string, Dictionary<string, XmlMethodHandler>>();
private JWTSignatureUtil m_sigUtil;
public delegate object XmlMethodHandler(IList args, IPEndPoint client);
public RemoteAdmin(string publicKeyPath = null)
{
AddCommand("session", "login_with_password", SessionLoginWithPassword);
AddCommand("session", "login_with_token", SessionLoginWithToken);
AddCommand("session", "logout", SessionLogout);
AddCommand("Console", "Command", ConsoleCommandHandler);
// AddCommand("GridService", "Shutdown", RegionShutdownHandler);
sessionTimer = new Timer(60000); // 60 seconds
sessionTimer.Elapsed += sessionTimer_Elapsed;
sessionTimer.Enabled = true;
m_sigUtil = new JWTSignatureUtil(publicKeyPath: publicKeyPath);
}
/// <summary>
/// Called publicly by server code that is not hosting a scene, but wants remote admin support
/// </summary>
/// <param name="server"></param>
public void AddHandler(BaseHttpServer server)
{
m_log.Info("[RADMIN]: Remote Admin CoreInit");
server.AddStreamHandler(new XmlRpcStreamHandler("POST", Util.XmlRpcRequestPrefix("RemoteAdmin"), XmlRpcCommand));
}
public void AddCommand(string classname, string command, XmlMethodHandler method)
{
lock (m_commands)
{
if (!m_commands.ContainsKey(classname))
m_commands.Add(classname, new Dictionary<string, XmlMethodHandler>());
m_commands[classname].Add(command, method);
}
}
public void RemoveCommand(string classname, string command, XmlMethodHandler method)
{
lock (m_commands)
{
if (!m_commands.ContainsKey(classname))
return;
m_commands[classname].Remove(command);
}
}
private XmlMethodHandler LookupCommand(string classname, string command)
{
lock (m_commands)
{
if (!m_commands.ContainsKey(classname))
return (null);
if (m_commands[classname].ContainsKey(command))
return m_commands[classname][command];
else
return (null);
}
}
public XmlRpcResponse XmlRpcCommand(XmlRpcRequest request, IPEndPoint remoteClient)
{
XmlRpcResponse response = new XmlRpcResponse();
Hashtable responseData = new Hashtable();
try
{
responseData["Status"] = "Success";
responseData["Value"] = String.Empty;
XmlMethodHandler handler = LookupCommand(request.MethodNameObject, request.MethodNameMethod);
if (handler != null)
{
responseData["Value"] = handler(request.Params, remoteClient);
response.Value = responseData;
}
else
{
// Code set in accordance with http://xmlrpc-epi.sourceforge.net/specs/rfc.fault_codes.php
response.SetFault(
XmlRpcErrorCodes.SERVER_ERROR_METHOD,
String.Format("Requested method [{0}] not found", request.MethodNameObject + "." + request.MethodNameMethod));
}
}
catch (Exception e)
{
responseData["Status"] = "Failure";
responseData["ErrorDescription"] = e.Message;
response.Value = responseData;
}
return response;
}
public void CheckSessionValid(UUID sessionid)
{
lock (m_activeSessions)
{
if (!m_activeSessions.ContainsKey(sessionid))
throw new Exception("SESSION_INVALID");
m_activeSessions[sessionid] = DateTime.Now;
}
}
// If a session has been inactive for 10 minutes, time it out.
private void sessionTimer_Elapsed(object sender, ElapsedEventArgs e)
{
List<UUID> expiredSessions = new List<UUID>();
lock (m_activeSessions)
{
foreach (UUID key in m_activeSessions.Keys)
{
if ((DateTime.Now - m_activeSessions[key]) > TimeSpan.FromMinutes(10))
expiredSessions.Add(key);
}
foreach (UUID key in expiredSessions)
{
m_activeSessions.Remove(key);
}
}
}
private object SessionLoginWithPassword(IList args, IPEndPoint remoteClient)
{
UUID sessionId;
string username = (string)args[0];
string password = (string)args[1];
// Is the username the same as the logged in user and do they have the password correct?
if ( Util.AuthenticateAsSystemUser(username, password))
{
lock (m_activeSessions)
{
sessionId = UUID.Random();
m_activeSessions.Add(sessionId, DateTime.Now);
}
}
else
{
throw new Exception("Invalid Username or Password");
}
return (sessionId.ToString());
}
private object SessionLoginWithToken(IList args, IPEndPoint remoteClient)
{
UUID sessionId;
var token = new JWToken((string)args[0], m_sigUtil);
if (token.Payload.Scope != "remote-admin")
{
throw new Exception("Invalid Token Scope");
}
else
{
lock (m_activeSessions)
{
sessionId = UUID.Random();
m_activeSessions.Add(sessionId, DateTime.Now);
}
}
return (sessionId.ToString());
}
private object SessionLogout(IList args, IPEndPoint remoteClient)
{
UUID sessionId = new UUID((string)args[0]);
lock (m_activeSessions)
{
if (m_activeSessions.ContainsKey(sessionId))
{
m_activeSessions.Remove(sessionId);
return (true);
}
else
{
return (false);
}
}
}
private object ConsoleCommandHandler(IList args, IPEndPoint client)
{
CheckSessionValid(new UUID((string)args[0]));
string command = (string)args[1];
MainConsole.Instance.RunCommand(command);
return String.Empty;
}
public void Dispose()
{
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.IO;
using System.Runtime.ExceptionServices;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net.Security
{
//
// This is a wrapping stream that does data encryption/decryption based on a successfully authenticated SSPI context.
//
internal class SslStreamInternal
{
private static readonly AsyncCallback s_writeCallback = new AsyncCallback(WriteCallback);
private static readonly AsyncProtocolCallback s_resumeAsyncWriteCallback = new AsyncProtocolCallback(ResumeAsyncWriteCallback);
private static readonly AsyncProtocolCallback s_resumeAsyncReadCallback = new AsyncProtocolCallback(ResumeAsyncReadCallback);
private static readonly AsyncProtocolCallback s_readHeaderCallback = new AsyncProtocolCallback(ReadHeaderCallback);
private static readonly AsyncProtocolCallback s_readFrameCallback = new AsyncProtocolCallback(ReadFrameCallback);
private const int PinnableReadBufferSize = 4096 * 4 + 32; // We read in 16K chunks + headers.
private static PinnableBufferCache s_PinnableReadBufferCache = new PinnableBufferCache("System.Net.SslStream", PinnableReadBufferSize);
private const int PinnableWriteBufferSize = 4096 + 1024; // We write in 4K chunks + encryption overhead.
private static PinnableBufferCache s_PinnableWriteBufferCache = new PinnableBufferCache("System.Net.SslStream", PinnableWriteBufferSize);
private SslState _sslState;
private int _nestedWrite;
private int _nestedRead;
private AsyncProtocolRequest _readProtocolRequest; // cached, reusable AsyncProtocolRequest used for read operations
private AsyncProtocolRequest _writeProtocolRequest; // cached, reusable AsyncProtocolRequest used for write operations
// Never updated directly, special properties are used. This is the read buffer.
private byte[] _internalBuffer;
private bool _internalBufferFromPinnableCache;
private byte[] _pinnableOutputBuffer; // Used for writes when we can do it.
private byte[] _pinnableOutputBufferInUse; // Remembers what UNENCRYPTED buffer is using _PinnableOutputBuffer.
private int _internalOffset;
private int _internalBufferCount;
internal SslStreamInternal(SslState sslState)
{
if (PinnableBufferCacheEventSource.Log.IsEnabled())
{
PinnableBufferCacheEventSource.Log.DebugMessage1("CTOR: In System.Net._SslStream.SslStream", this.GetHashCode());
}
_sslState = sslState;
}
// If we have a read buffer from the pinnable cache, return it.
private void FreeReadBuffer()
{
if (_internalBufferFromPinnableCache)
{
s_PinnableReadBufferCache.FreeBuffer(_internalBuffer);
_internalBufferFromPinnableCache = false;
}
_internalBuffer = null;
}
~SslStreamInternal()
{
if (_internalBufferFromPinnableCache)
{
if (PinnableBufferCacheEventSource.Log.IsEnabled())
{
PinnableBufferCacheEventSource.Log.DebugMessage2("DTOR: In System.Net._SslStream.~SslStream Freeing Read Buffer", this.GetHashCode(), PinnableBufferCacheEventSource.AddressOfByteArray(_internalBuffer));
}
FreeReadBuffer();
}
if (_pinnableOutputBuffer != null)
{
if (PinnableBufferCacheEventSource.Log.IsEnabled())
{
PinnableBufferCacheEventSource.Log.DebugMessage2("DTOR: In System.Net._SslStream.~SslStream Freeing Write Buffer", this.GetHashCode(), PinnableBufferCacheEventSource.AddressOfByteArray(_pinnableOutputBuffer));
}
s_PinnableWriteBufferCache.FreeBuffer(_pinnableOutputBuffer);
}
}
internal int ReadByte()
{
if (Interlocked.Exchange(ref _nestedRead, 1) == 1)
{
throw new NotSupportedException(SR.Format(SR.net_io_invalidnestedcall, "ReadByte", "read"));
}
// If there's any data in the buffer, take one byte, and we're done.
try
{
if (InternalBufferCount > 0)
{
int b = InternalBuffer[InternalOffset];
SkipBytes(1);
return b;
}
}
finally
{
// Regardless of whether we were able to read a byte from the buffer,
// reset the read tracking. If we weren't able to read a byte, the
// subsequent call to Read will set the flag again.
_nestedRead = 0;
}
// Otherwise, fall back to reading a byte via Read, the same way Stream.ReadByte does.
// This allocation is unfortunate but should be relatively rare, as it'll only occur once
// per buffer fill internally by Read.
byte[] oneByte = new byte[1];
int bytesRead = Read(oneByte, 0, 1);
Debug.Assert(bytesRead == 0 || bytesRead == 1);
return bytesRead == 1 ? oneByte[0] : -1;
}
internal int Read(byte[] buffer, int offset, int count)
{
return ProcessRead(buffer, offset, count, null);
}
internal void Write(byte[] buffer, int offset, int count)
{
ProcessWrite(buffer, offset, count, null);
}
internal IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback asyncCallback, object asyncState)
{
var bufferResult = new BufferAsyncResult(this, buffer, offset, count, asyncState, asyncCallback);
ProcessRead(buffer, offset, count, bufferResult);
return bufferResult;
}
internal int EndRead(IAsyncResult asyncResult)
{
if (asyncResult == null)
{
throw new ArgumentNullException(nameof(asyncResult));
}
BufferAsyncResult bufferResult = asyncResult as BufferAsyncResult;
if (bufferResult == null)
{
throw new ArgumentException(SR.Format(SR.net_io_async_result, asyncResult.GetType().FullName), nameof(asyncResult));
}
if (Interlocked.Exchange(ref _nestedRead, 0) == 0)
{
throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, "EndRead"));
}
// No "artificial" timeouts implemented so far, InnerStream controls timeout.
bufferResult.InternalWaitForCompletion();
if (bufferResult.Result is Exception)
{
if (bufferResult.Result is IOException)
{
throw (Exception)bufferResult.Result;
}
throw new IOException(SR.net_io_read, (Exception)bufferResult.Result);
}
return bufferResult.Int32Result;
}
internal IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback asyncCallback, object asyncState)
{
var lazyResult = new LazyAsyncResult(this, asyncState, asyncCallback);
ProcessWrite(buffer, offset, count, lazyResult);
return lazyResult;
}
internal void EndWrite(IAsyncResult asyncResult)
{
if (asyncResult == null)
{
throw new ArgumentNullException(nameof(asyncResult));
}
LazyAsyncResult lazyResult = asyncResult as LazyAsyncResult;
if (lazyResult == null)
{
throw new ArgumentException(SR.Format(SR.net_io_async_result, asyncResult.GetType().FullName), nameof(asyncResult));
}
if (Interlocked.Exchange(ref _nestedWrite, 0) == 0)
{
throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, "EndWrite"));
}
// No "artificial" timeouts implemented so far, InnerStream controls timeout.
lazyResult.InternalWaitForCompletion();
if (lazyResult.Result is Exception e)
{
if (e is IOException)
{
ExceptionDispatchInfo.Capture(e).Throw();
}
throw new IOException(SR.net_io_write, e);
}
}
internal bool DataAvailable
{
get { return InternalBufferCount != 0; }
}
private byte[] InternalBuffer
{
get
{
return _internalBuffer;
}
}
private int InternalOffset
{
get
{
return _internalOffset;
}
}
private int InternalBufferCount
{
get
{
return _internalBufferCount;
}
}
private void SkipBytes(int decrCount)
{
_internalOffset += decrCount;
_internalBufferCount -= decrCount;
}
//
// This will set the internal offset to "curOffset" and ensure internal buffer.
// If not enough, reallocate and copy up to "curOffset".
//
private void EnsureInternalBufferSize(int curOffset, int addSize)
{
if (_internalBuffer == null || _internalBuffer.Length < addSize + curOffset)
{
bool wasPinnable = _internalBufferFromPinnableCache;
byte[] saved = _internalBuffer;
int newSize = addSize + curOffset;
if (newSize <= PinnableReadBufferSize)
{
if (PinnableBufferCacheEventSource.Log.IsEnabled())
{
PinnableBufferCacheEventSource.Log.DebugMessage2("In System.Net._SslStream.EnsureInternalBufferSize IS pinnable", this.GetHashCode(), newSize);
}
_internalBufferFromPinnableCache = true;
_internalBuffer = s_PinnableReadBufferCache.AllocateBuffer();
}
else
{
if (PinnableBufferCacheEventSource.Log.IsEnabled())
{
PinnableBufferCacheEventSource.Log.DebugMessage2("In System.Net._SslStream.EnsureInternalBufferSize NOT pinnable", this.GetHashCode(), newSize);
}
_internalBufferFromPinnableCache = false;
_internalBuffer = new byte[newSize];
}
if (saved != null && curOffset != 0)
{
Buffer.BlockCopy(saved, 0, _internalBuffer, 0, curOffset);
}
if (wasPinnable)
{
s_PinnableReadBufferCache.FreeBuffer(saved);
}
}
_internalOffset = curOffset;
_internalBufferCount = curOffset + addSize;
}
//
// Validates user parameters for all Read/Write methods.
//
private void ValidateParameters(byte[] buffer, int offset, int count)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
if (offset < 0)
{
throw new ArgumentOutOfRangeException(nameof(offset));
}
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count));
}
if (count > buffer.Length - offset)
{
throw new ArgumentOutOfRangeException(nameof(count), SR.net_offset_plus_count);
}
}
private AsyncProtocolRequest GetOrCreateProtocolRequest(ref AsyncProtocolRequest aprField, LazyAsyncResult asyncResult)
{
AsyncProtocolRequest request = null;
if (asyncResult != null)
{
// SslStreamInternal supports only a single read and a single write operation at a time.
// As such, we can cache and reuse the AsyncProtocolRequest object that's used throughout
// the implementation.
request = aprField;
if (request != null)
{
request.Reset(asyncResult);
}
else
{
aprField = request = new AsyncProtocolRequest(asyncResult);
}
}
return request;
}
//
// Sync write method.
//
private void ProcessWrite(byte[] buffer, int offset, int count, LazyAsyncResult asyncResult)
{
_sslState.CheckThrow(authSuccessCheck:true, shutdownCheck:true);
ValidateParameters(buffer, offset, count);
if (Interlocked.Exchange(ref _nestedWrite, 1) == 1)
{
throw new NotSupportedException(SR.Format(SR.net_io_invalidnestedcall, "Write", "write"));
}
// If this is an async operation, get the AsyncProtocolRequest to use.
// We do this only after we verify we're the sole write operation in flight.
AsyncProtocolRequest asyncRequest = GetOrCreateProtocolRequest(ref _writeProtocolRequest, asyncResult);
bool failed = false;
try
{
StartWriting(buffer, offset, count, asyncRequest);
}
catch (Exception e)
{
_sslState.FinishWrite();
failed = true;
if (e is IOException)
{
throw;
}
throw new IOException(SR.net_io_write, e);
}
finally
{
if (asyncRequest == null || failed)
{
_nestedWrite = 0;
}
}
}
private void StartWriting(byte[] buffer, int offset, int count, AsyncProtocolRequest asyncRequest)
{
if (asyncRequest != null)
{
asyncRequest.SetNextRequest(buffer, offset, count, s_resumeAsyncWriteCallback);
}
// We loop to this method from the callback.
// If the last chunk was just completed from async callback (count < 0), we complete user request.
if (count >= 0 )
{
byte[] outBuffer = null;
if (_pinnableOutputBufferInUse == null)
{
if (_pinnableOutputBuffer == null)
{
_pinnableOutputBuffer = s_PinnableWriteBufferCache.AllocateBuffer();
}
_pinnableOutputBufferInUse = buffer;
outBuffer = _pinnableOutputBuffer;
if (PinnableBufferCacheEventSource.Log.IsEnabled())
{
PinnableBufferCacheEventSource.Log.DebugMessage3("In System.Net._SslStream.StartWriting Trying Pinnable", this.GetHashCode(), count, PinnableBufferCacheEventSource.AddressOfByteArray(outBuffer));
}
}
else
{
if (PinnableBufferCacheEventSource.Log.IsEnabled())
{
PinnableBufferCacheEventSource.Log.DebugMessage2("In System.Net._SslStream.StartWriting BufferInUse", this.GetHashCode(), count);
}
}
do
{
if (count == 0 && !SslStreamPal.CanEncryptEmptyMessage)
{
// If it's an empty message and the PAL doesn't support that,
// we're done.
break;
}
// Request a write IO slot.
if (_sslState.CheckEnqueueWrite(asyncRequest))
{
// Operation is async and has been queued, return.
return;
}
int chunkBytes = Math.Min(count, _sslState.MaxDataSize);
int encryptedBytes;
SecurityStatusPal status = _sslState.EncryptData(buffer, offset, chunkBytes, ref outBuffer, out encryptedBytes);
if (status.ErrorCode != SecurityStatusPalErrorCode.OK)
{
// Re-handshake status is not supported.
ProtocolToken message = new ProtocolToken(null, status);
throw new IOException(SR.net_io_encrypt, message.GetException());
}
if (PinnableBufferCacheEventSource.Log.IsEnabled())
{
PinnableBufferCacheEventSource.Log.DebugMessage3("In System.Net._SslStream.StartWriting Got Encrypted Buffer",
this.GetHashCode(), encryptedBytes, PinnableBufferCacheEventSource.AddressOfByteArray(outBuffer));
}
if (asyncRequest != null)
{
// Prepare for the next request.
asyncRequest.SetNextRequest(buffer, offset + chunkBytes, count - chunkBytes, s_resumeAsyncWriteCallback);
Task t = _sslState.InnerStream.WriteAsync(outBuffer, 0, encryptedBytes);
if (t.IsCompleted)
{
t.GetAwaiter().GetResult();
}
else
{
IAsyncResult ar = TaskToApm.Begin(t, s_writeCallback, asyncRequest);
if (!ar.CompletedSynchronously)
{
return;
}
TaskToApm.End(ar);
}
}
else
{
_sslState.InnerStream.Write(outBuffer, 0, encryptedBytes);
}
offset += chunkBytes;
count -= chunkBytes;
// Release write IO slot.
_sslState.FinishWrite();
} while (count != 0);
}
if (asyncRequest != null)
{
asyncRequest.CompleteUser();
}
if (buffer == _pinnableOutputBufferInUse)
{
_pinnableOutputBufferInUse = null;
if (PinnableBufferCacheEventSource.Log.IsEnabled())
{
PinnableBufferCacheEventSource.Log.DebugMessage1("In System.Net._SslStream.StartWriting Freeing buffer.", this.GetHashCode());
}
}
}
//
// Combined sync/async read method. For sync request asyncRequest==null.
//
private int ProcessRead(byte[] buffer, int offset, int count, BufferAsyncResult asyncResult)
{
ValidateParameters(buffer, offset, count);
if (Interlocked.Exchange(ref _nestedRead, 1) == 1)
{
throw new NotSupportedException(SR.Format(SR.net_io_invalidnestedcall, (asyncResult!=null? "BeginRead":"Read"), "read"));
}
// If this is an async operation, get the AsyncProtocolRequest to use.
// We do this only after we verify we're the sole write operation in flight.
AsyncProtocolRequest asyncRequest = GetOrCreateProtocolRequest(ref _readProtocolRequest, asyncResult);
bool failed = false;
try
{
int copyBytes;
if (InternalBufferCount != 0)
{
copyBytes = InternalBufferCount > count ? count : InternalBufferCount;
if (copyBytes != 0)
{
Buffer.BlockCopy(InternalBuffer, InternalOffset, buffer, offset, copyBytes);
SkipBytes(copyBytes);
}
asyncRequest?.CompleteUser(copyBytes);
return copyBytes;
}
return StartReading(buffer, offset, count, asyncRequest);
}
catch (Exception e)
{
_sslState.FinishRead(null);
failed = true;
if (e is IOException)
{
throw;
}
throw new IOException(SR.net_io_read, e);
}
finally
{
if (asyncRequest == null || failed)
{
_nestedRead = 0;
}
}
}
//
// To avoid recursion when decrypted 0 bytes this method will loop until a decrypted result at least 1 byte.
//
private int StartReading(byte[] buffer, int offset, int count, AsyncProtocolRequest asyncRequest)
{
int result = 0;
if (InternalBufferCount != 0)
{
NetEventSource.Fail(this, $"Previous frame was not consumed. InternalBufferCount: {InternalBufferCount}");
}
do
{
if (asyncRequest != null)
{
asyncRequest.SetNextRequest(buffer, offset, count, s_resumeAsyncReadCallback);
}
int copyBytes = _sslState.CheckEnqueueRead(buffer, offset, count, asyncRequest);
if (copyBytes == 0)
{
// Queued but not completed!
return 0;
}
if (copyBytes != -1)
{
asyncRequest?.CompleteUser(copyBytes);
return copyBytes;
}
}
// When we read -1 bytes means we have decrypted 0 bytes or rehandshaking, need looping.
while ((result = StartFrameHeader(buffer, offset, count, asyncRequest)) == -1);
return result;
}
private int StartFrameHeader(byte[] buffer, int offset, int count, AsyncProtocolRequest asyncRequest)
{
int readBytes = 0;
//
// Always pass InternalBuffer for SSPI "in place" decryption.
// A user buffer can be shared by many threads in that case decryption/integrity check may fail cause of data corruption.
//
// Reset internal buffer for a new frame.
EnsureInternalBufferSize(0, SecureChannel.ReadHeaderSize);
if (asyncRequest != null)
{
asyncRequest.SetNextRequest(InternalBuffer, 0, SecureChannel.ReadHeaderSize, s_readHeaderCallback);
FixedSizeReader.ReadPacketAsync(_sslState.InnerStream, asyncRequest);
if (!asyncRequest.MustCompleteSynchronously)
{
return 0;
}
readBytes = asyncRequest.Result;
}
else
{
readBytes = FixedSizeReader.ReadPacket(_sslState.InnerStream, InternalBuffer, 0, SecureChannel.ReadHeaderSize);
}
return StartFrameBody(readBytes, buffer, offset, count, asyncRequest);
}
private int StartFrameBody(int readBytes, byte[] buffer, int offset, int count, AsyncProtocolRequest asyncRequest)
{
if (readBytes == 0)
{
//EOF : Reset the buffer as we did not read anything into it.
SkipBytes(InternalBufferCount);
asyncRequest?.CompleteUser(0);
return 0;
}
// Now readBytes is a payload size.
readBytes = _sslState.GetRemainingFrameSize(InternalBuffer, readBytes);
if (readBytes < 0)
{
throw new IOException(SR.net_frame_read_size);
}
EnsureInternalBufferSize(SecureChannel.ReadHeaderSize, readBytes);
if (asyncRequest != null)
{
asyncRequest.SetNextRequest(InternalBuffer, SecureChannel.ReadHeaderSize, readBytes, s_readFrameCallback);
FixedSizeReader.ReadPacketAsync(_sslState.InnerStream, asyncRequest);
if (!asyncRequest.MustCompleteSynchronously)
{
return 0;
}
readBytes = asyncRequest.Result;
}
else
{
readBytes = FixedSizeReader.ReadPacket(_sslState.InnerStream, InternalBuffer, SecureChannel.ReadHeaderSize, readBytes);
}
return ProcessFrameBody(readBytes, buffer, offset, count, asyncRequest);
}
//
// readBytes == SSL Data Payload size on input or 0 on EOF.
//
private int ProcessFrameBody(int readBytes, byte[] buffer, int offset, int count, AsyncProtocolRequest asyncRequest)
{
if (readBytes == 0)
{
// EOF
throw new IOException(SR.net_io_eof);
}
// Set readBytes to total number of received bytes.
readBytes += SecureChannel.ReadHeaderSize;
// Decrypt into internal buffer, change "readBytes" to count now _Decrypted Bytes_.
int data_offset = 0;
SecurityStatusPal status = _sslState.DecryptData(InternalBuffer, ref data_offset, ref readBytes);
if (status.ErrorCode != SecurityStatusPalErrorCode.OK)
{
byte[] extraBuffer = null;
if (readBytes != 0)
{
extraBuffer = new byte[readBytes];
Buffer.BlockCopy(InternalBuffer, data_offset, extraBuffer, 0, readBytes);
}
// Reset internal buffer count.
SkipBytes(InternalBufferCount);
return ProcessReadErrorCode(status, buffer, offset, count, asyncRequest, extraBuffer);
}
if (readBytes == 0 && count != 0)
{
// Read again since remote side has sent encrypted 0 bytes.
SkipBytes(InternalBufferCount);
return -1;
}
// Decrypted data start from "data_offset" offset, the total count can be shrunk after decryption.
EnsureInternalBufferSize(0, data_offset + readBytes);
SkipBytes(data_offset);
if (readBytes > count)
{
readBytes = count;
}
Buffer.BlockCopy(InternalBuffer, InternalOffset, buffer, offset, readBytes);
// This will adjust both the remaining internal buffer count and the offset.
SkipBytes(readBytes);
_sslState.FinishRead(null);
asyncRequest?.CompleteUser(readBytes);
return readBytes;
}
private int ProcessReadErrorCode(SecurityStatusPal status, byte[] buffer, int offset, int count, AsyncProtocolRequest asyncRequest, byte[] extraBuffer)
{
ProtocolToken message = new ProtocolToken(null, status);
if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"***Processing an error Status = {message.Status}");
if (message.Renegotiate)
{
_sslState.ReplyOnReAuthentication(extraBuffer);
// Loop on read.
return -1;
}
if (message.CloseConnection)
{
_sslState.FinishRead(null);
asyncRequest?.CompleteUser(0);
return 0;
}
throw new IOException(SR.net_io_decrypt, message.GetException());
}
private static void WriteCallback(IAsyncResult transportResult)
{
if (transportResult.CompletedSynchronously)
{
return;
}
if (!(transportResult.AsyncState is AsyncProtocolRequest))
{
NetEventSource.Fail(transportResult, "State type is wrong, expected AsyncProtocolRequest.");
}
AsyncProtocolRequest asyncRequest = (AsyncProtocolRequest)transportResult.AsyncState;
var sslStream = (SslStreamInternal)asyncRequest.AsyncObject;
try
{
TaskToApm.End(transportResult);
sslStream._sslState.FinishWrite();
if (asyncRequest.Count == 0)
{
// This was the last chunk.
asyncRequest.Count = -1;
}
sslStream.StartWriting(asyncRequest.Buffer, asyncRequest.Offset, asyncRequest.Count, asyncRequest);
}
catch (Exception e)
{
if (asyncRequest.IsUserCompleted)
{
// This will throw on a worker thread.
throw;
}
sslStream._sslState.FinishWrite();
asyncRequest.CompleteUserWithError(e);
}
}
//
// This is used in a rare situation when async Read is resumed from completed handshake.
//
private static void ResumeAsyncReadCallback(AsyncProtocolRequest request)
{
try
{
((SslStreamInternal)request.AsyncObject).StartReading(request.Buffer, request.Offset, request.Count, request);
}
catch (Exception e)
{
if (request.IsUserCompleted)
{
// This will throw on a worker thread.
throw;
}
((SslStreamInternal)request.AsyncObject)._sslState.FinishRead(null);
request.CompleteUserWithError(e);
}
}
//
// This is used in a rare situation when async Write is resumed from completed handshake.
//
private static void ResumeAsyncWriteCallback(AsyncProtocolRequest asyncRequest)
{
try
{
((SslStreamInternal)asyncRequest.AsyncObject).StartWriting(asyncRequest.Buffer, asyncRequest.Offset, asyncRequest.Count, asyncRequest);
}
catch (Exception e)
{
if (asyncRequest.IsUserCompleted)
{
// This will throw on a worker thread.
throw;
}
((SslStreamInternal)asyncRequest.AsyncObject)._sslState.FinishWrite();
asyncRequest.CompleteUserWithError(e);
}
}
private static void ReadHeaderCallback(AsyncProtocolRequest asyncRequest)
{
try
{
SslStreamInternal sslStream = (SslStreamInternal)asyncRequest.AsyncObject;
BufferAsyncResult bufferResult = (BufferAsyncResult)asyncRequest.UserAsyncResult;
if (-1 == sslStream.StartFrameBody(asyncRequest.Result, bufferResult.Buffer, bufferResult.Offset, bufferResult.Count, asyncRequest))
{
// in case we decrypted 0 bytes start another reading.
sslStream.StartReading(bufferResult.Buffer, bufferResult.Offset, bufferResult.Count, asyncRequest);
}
}
catch (Exception e)
{
if (asyncRequest.IsUserCompleted)
{
// This will throw on a worker thread.
throw;
}
asyncRequest.CompleteUserWithError(e);
}
}
private static void ReadFrameCallback(AsyncProtocolRequest asyncRequest)
{
try
{
SslStreamInternal sslStream = (SslStreamInternal)asyncRequest.AsyncObject;
BufferAsyncResult bufferResult = (BufferAsyncResult)asyncRequest.UserAsyncResult;
if (-1 == sslStream.ProcessFrameBody(asyncRequest.Result, bufferResult.Buffer, bufferResult.Offset, bufferResult.Count, asyncRequest))
{
// in case we decrypted 0 bytes start another reading.
sslStream.StartReading(bufferResult.Buffer, bufferResult.Offset, bufferResult.Count, asyncRequest);
}
}
catch (Exception e)
{
if (asyncRequest.IsUserCompleted)
{
// This will throw on a worker thread.
throw;
}
asyncRequest.CompleteUserWithError(e);
}
}
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="InflateManager.cs" company="XamlNinja">
// 2011 Richard Griffin and Ollie Riches
// </copyright>
// <summary>
// http://www.sharpgis.net/post/2011/08/28/GZIP-Compressed-Web-Requests-in-WP7-Take-2.aspx
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace WP7Contrib.Communications.Compression
{
internal sealed class InflateManager
{
static byte[] Mark = { (byte) 0, (byte) 0, byte.MaxValue, byte.MaxValue };
const int PRESET_DICT = 32;
const int Z_DEFLATED = 8;
const int METHOD = 0;
const int FLAG = 1;
const int DICT4 = 2;
const int DICT3 = 3;
const int DICT2 = 4;
const int DICT1 = 5;
const int DICT0 = 6;
const int BLOCKS = 7;
const int CHECK4 = 8;
const int CHECK3 = 9;
const int CHECK2 = 10;
const int CHECK1 = 11;
const int DONE = 12;
const int BAD = 13;
internal int Mode;
internal int Method;
internal int Marker;
internal int Wbits;
internal ZlibCodec Codec;
internal InflateBlocks Blocks;
internal long Need;
internal long[] Was = new long[1];
#region Properties
internal bool HandleRfc1950HeaderBytes { get; set; }
#endregion Properties
#region Constructors
static InflateManager()
{
}
public InflateManager() : this(true)
{
}
public InflateManager(bool expectRfc1950HeaderBytes=true)
{
HandleRfc1950HeaderBytes = expectRfc1950HeaderBytes;
}
#endregion Constructors
internal int Reset()
{
this.Codec.TotalBytesIn = this.Codec.TotalBytesOut = 0L;
this.Codec.Message = (string)null;
this.Mode = this.HandleRfc1950HeaderBytes ? 0 : 7;
this.Blocks.Reset((long[])null);
return 0;
}
internal int End()
{
if (this.Blocks != null)
this.Blocks.Free();
this.Blocks = (InflateBlocks)null;
return 0;
}
internal int Initialize(ZlibCodec codec, int w)
{
this.Codec = codec;
this.Codec.Message = (string)null;
this.Blocks = (InflateBlocks)null;
if (w < 8 || w > 15)
{
this.End();
throw new ZlibException("Bad window size.");
}
else
{
this.Wbits = w;
this.Blocks = new InflateBlocks(codec, this.HandleRfc1950HeaderBytes ? (object)this : (object)(InflateManager)null, 1 << w);
this.Reset();
return 0;
}
}
internal int Inflate(FlushType flush)
{
int num1 = (int)flush;
if (this.Codec.InputBuffer == null)
throw new ZlibException("InputBuffer is null. ");
int num2 = num1 == 4 ? -5 : 0;
int r = -5;
while (true)
{
switch (this.Mode)
{
case 0:
if (this.Codec.AvailableBytesIn != 0)
{
r = num2;
--this.Codec.AvailableBytesIn;
++this.Codec.TotalBytesIn;
InflateManager inflateManager = this;
byte[] numArray = this.Codec.InputBuffer;
int index = this.Codec.NextIn++;
int num3;
int num4 = num3 = (int)numArray[index];
inflateManager.Method = num3;
if ((num4 & 15) != 8)
{
this.Mode = 13;
this.Codec.Message = string.Format("unknown compression Method (0x{0:X2})", (object)this.Method);
this.Marker = 5;
break;
}
else if ((this.Method >> 4) + 8 > this.Wbits)
{
this.Mode = 13;
this.Codec.Message = string.Format("invalid window size ({0})", (object)((this.Method >> 4) + 8));
this.Marker = 5;
break;
}
else
{
this.Mode = 1;
goto case 1;
}
}
else
goto label_4;
case 1:
if (this.Codec.AvailableBytesIn != 0)
{
r = num2;
--this.Codec.AvailableBytesIn;
++this.Codec.TotalBytesIn;
int num3 = (int)this.Codec.InputBuffer[this.Codec.NextIn++] & (int)byte.MaxValue;
if (((this.Method << 8) + num3) % 31 != 0)
{
this.Mode = 13;
this.Codec.Message = "incorrect header check";
this.Marker = 5;
break;
}
else if ((num3 & 32) == 0)
{
this.Mode = 7;
break;
}
else
goto label_16;
}
else
goto label_11;
case 2:
goto label_17;
case 3:
goto label_20;
case 4:
goto label_23;
case 5:
goto label_26;
case 6:
goto label_29;
case 7:
r = this.Blocks.Process(r);
if (r == -3)
{
this.Mode = 13;
this.Marker = 0;
break;
}
else
{
if (r == 0)
r = num2;
if (r == 1)
{
r = num2;
this.Blocks.Reset(this.Was);
if (!this.HandleRfc1950HeaderBytes)
{
this.Mode = 12;
break;
}
else
{
this.Mode = 8;
goto case 8;
}
}
else
goto label_35;
}
case 8:
if (this.Codec.AvailableBytesIn != 0)
{
r = num2;
--this.Codec.AvailableBytesIn;
++this.Codec.TotalBytesIn;
this.Need = (long)(((int)this.Codec.InputBuffer[this.Codec.NextIn++] & (int)byte.MaxValue) << 24 & -16777216);
this.Mode = 9;
goto case 9;
}
else
goto label_40;
case 9:
if (this.Codec.AvailableBytesIn != 0)
{
r = num2;
--this.Codec.AvailableBytesIn;
++this.Codec.TotalBytesIn;
this.Need += (long)(((int)this.Codec.InputBuffer[this.Codec.NextIn++] & (int)byte.MaxValue) << 16) & 16711680L;
this.Mode = 10;
goto case 10;
}
else
goto label_43;
case 10:
if (this.Codec.AvailableBytesIn != 0)
{
r = num2;
--this.Codec.AvailableBytesIn;
++this.Codec.TotalBytesIn;
this.Need += (long)(((int)this.Codec.InputBuffer[this.Codec.NextIn++] & (int)byte.MaxValue) << 8) & 65280L;
this.Mode = 11;
goto case 11;
}
else
goto label_46;
case 11:
if (this.Codec.AvailableBytesIn != 0)
{
r = num2;
--this.Codec.AvailableBytesIn;
++this.Codec.TotalBytesIn;
this.Need += (long)this.Codec.InputBuffer[this.Codec.NextIn++] & (long)byte.MaxValue;
if ((int)this.Was[0] != (int)this.Need)
{
this.Mode = 13;
this.Codec.Message = "incorrect data check";
this.Marker = 5;
break;
}
else
goto label_52;
}
else
goto label_49;
case 12:
goto label_53;
case 13:
goto label_54;
default:
goto label_55;
}
}
label_4:
return r;
label_11:
return r;
label_16:
this.Mode = 2;
label_17:
if (this.Codec.AvailableBytesIn == 0)
return r;
r = num2;
--this.Codec.AvailableBytesIn;
++this.Codec.TotalBytesIn;
this.Need = (long)(((int)this.Codec.InputBuffer[this.Codec.NextIn++] & (int)byte.MaxValue) << 24 & -16777216);
this.Mode = 3;
label_20:
if (this.Codec.AvailableBytesIn == 0)
return r;
r = num2;
--this.Codec.AvailableBytesIn;
++this.Codec.TotalBytesIn;
this.Need += (long)(((int)this.Codec.InputBuffer[this.Codec.NextIn++] & (int)byte.MaxValue) << 16) & 16711680L;
this.Mode = 4;
label_23:
if (this.Codec.AvailableBytesIn == 0)
return r;
r = num2;
--this.Codec.AvailableBytesIn;
++this.Codec.TotalBytesIn;
this.Need += (long)(((int)this.Codec.InputBuffer[this.Codec.NextIn++] & (int)byte.MaxValue) << 8) & 65280L;
this.Mode = 5;
label_26:
if (this.Codec.AvailableBytesIn == 0)
return r;
--this.Codec.AvailableBytesIn;
++this.Codec.TotalBytesIn;
this.Need += (long)this.Codec.InputBuffer[this.Codec.NextIn++] & (long)byte.MaxValue;
this.Codec.Adler32 = this.Need;
this.Mode = 6;
return 2;
label_29:
this.Mode = 13;
this.Codec.Message = "Need dictionary";
this.Marker = 0;
return -2;
label_35:
return r;
label_40:
return r;
label_43:
return r;
label_46:
return r;
label_49:
return r;
label_52:
this.Mode = 12;
label_53:
return 1;
label_54:
throw new ZlibException(string.Format("Bad state ({0})", (object)this.Codec.Message));
label_55:
throw new ZlibException("Stream error.");
}
internal int SetDictionary(byte[] dictionary)
{
int start = 0;
int n = dictionary.Length;
if (this.Mode != 6)
throw new ZlibException("Stream error.");
if (Adler.Adler32(1L, dictionary, 0, dictionary.Length) != this.Codec.Adler32)
return -3;
this.Codec.Adler32 = Adler.Adler32(0L, (byte[])null, 0, 0);
if (n >= 1 << this.Wbits)
{
n = (1 << this.Wbits) - 1;
start = dictionary.Length - n;
}
this.Blocks.SetDictionary(dictionary, start, n);
this.Mode = 7;
return 0;
}
internal int Sync()
{
if (this.Mode != 13)
{
this.Mode = 13;
this.Marker = 0;
}
int num1;
if ((num1 = this.Codec.AvailableBytesIn) == 0)
return -5;
int index1 = this.Codec.NextIn;
int index2;
for (index2 = this.Marker; num1 != 0 && index2 < 4; --num1)
{
if ((int)this.Codec.InputBuffer[index1] == (int)InflateManager.Mark[index2])
++index2;
else
index2 = (int)this.Codec.InputBuffer[index1] == 0 ? 4 - index2 : 0;
++index1;
}
this.Codec.TotalBytesIn += (long)(index1 - this.Codec.NextIn);
this.Codec.NextIn = index1;
this.Codec.AvailableBytesIn = num1;
this.Marker = index2;
if (index2 != 4)
return -3;
long num2 = this.Codec.TotalBytesIn;
long num3 = this.Codec.TotalBytesOut;
this.Reset();
this.Codec.TotalBytesIn = num2;
this.Codec.TotalBytesOut = num3;
this.Mode = 7;
return 0;
}
internal int SyncPoint(ZlibCodec z)
{
return this.Blocks.SyncPoint();
}
}
}
| |
// *********************************
// Message from Original Author:
//
// 2008 Jose Menendez Poo
// Please give me credit if you use this code. It's all I ask.
// Contact me for more info: menendezpoo@gmail.com
// *********************************
//
// Original project from http://ribbon.codeplex.com/
// Continue to support and maintain by http://officeribbon.codeplex.com/
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Drawing.Drawing2D;
using System.Windows.Forms.RibbonHelpers;
namespace System.Windows.Forms
{
/// <summary>
/// This class is used to make a form able to contain a ribbon on the non-client area.
/// For further instrucions search "ribbon non-client" on www.menendezpoo.com
/// </summary>
public class RibbonFormHelper
{
#region Subclasses
/// <summary>
/// Possible results of a hit test on the non client area of a form
/// </summary>
public enum NonClientHitTestResult
{
Nowhere = 0,
Client = 1,
Caption = 2,
GrowBox = 4,
MinimizeButton = 8,
MaximizeButton = 9,
Left = 10,
Right = 11,
Top = 12,
TopLeft = 13,
TopRight = 14,
Bottom = 15,
BottomLeft = 16,
BottomRight = 17
}
#endregion
#region Fields
private FormWindowState _lastState;
private Form _form;
private Padding _margins;
private bool _marginsChecked;
private int _capionHeight;
private bool _frameExtended;
private Ribbon _ribbon;
private Size _storeSize;
#endregion
#region Ctor
/// <summary>
/// Creates a new helper for the specified form
/// </summary>
/// <param name="f"></param>
public RibbonFormHelper(Form f)
{
_form = f;
_form.Load += new EventHandler(Form_Activated);
_form.ResizeEnd += new EventHandler(_form_ResizeEnd);
_form.Layout += new LayoutEventHandler(_form_Layout);
}
void _form_Layout(object sender, LayoutEventArgs e)
{
if (_lastState == _form.WindowState)
{
return;
}
if (WinApi.IsGlassEnabled)
Form.Invalidate();
else // on XP systems Invalidate is not sufficient in case the Form contains a control with DockStyle.Fill
Form.Refresh();
_lastState = _form.WindowState;
}
void _form_ResizeEnd(object sender, EventArgs e)
{
UpdateRibbonConditions();
Form.Refresh();
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the Ribbon related with the form
/// </summary>
public Ribbon Ribbon
{
get { return _ribbon; }
set { _ribbon = value; UpdateRibbonConditions(); }
}
/// <summary>
/// Gets or sets the height of the caption bar relative to the form
/// </summary>
public int CaptionHeight
{
get { return _capionHeight; }
set { _capionHeight = value; }
}
/// <summary>
/// Gets the form this class is helping
/// </summary>
public Form Form
{
get { return _form; }
}
/// <summary>
/// Gets the margins of the non-client area
/// </summary>
public Padding Margins
{
get { return _margins; }
}
/// <summary>
/// Gets or sets if the margins are already checked by WndProc
/// </summary>
private bool MarginsChecked
{
get { return _marginsChecked; }
set { _marginsChecked = value; }
}
/// <summary>
/// Gets if the <see cref="Form"/> is currently in Designer mode
/// </summary>
private bool DesignMode
{
get { return Form != null && Form.Site != null && Form.Site.DesignMode; }
}
#endregion
#region Methods
/// <summary>
/// Checks if ribbon should be docked or floating and updates its size
/// </summary>
private void UpdateRibbonConditions()
{
if (Ribbon == null) return;
if (Ribbon.Dock != DockStyle.Top)
{
Ribbon.Dock = DockStyle.Top;
}
}
/// <summary>
/// Called when helped form is activated
/// </summary>
/// <param name="sender">Object that raised the event</param>
/// <param name="e">Event data</param>
public void Form_Paint(object sender, PaintEventArgs e)
{
if (DesignMode) return;
if (WinApi.IsGlassEnabled)
{
WinApi.FillForGlass(e.Graphics, new Rectangle(0, 0, Form.Width, Form.Height));
using (Brush b = new SolidBrush(Form.BackColor))
{
e.Graphics.FillRectangle(b,
Rectangle.FromLTRB(
Margins.Left - 0,
Margins.Top + 0,
Form.Width - Margins.Right - 0,
Form.Height - Margins.Bottom - 0));
}
}
else
{
PaintTitleBar(e);
}
}
/// <summary>
/// Draws the title bar of the form when not in glass
/// </summary>
/// <param name="e"></param>
private void PaintTitleBar(PaintEventArgs e)
{
int radius1 = 4, radius2 = radius1 - 0;
Rectangle rPath = new Rectangle(Point.Empty, Form.Size);
Rectangle rInner = new Rectangle(Point.Empty, new Size(rPath.Width - 1, rPath.Height - 1));
using (GraphicsPath path = RibbonProfessionalRenderer.RoundRectangle(rPath, radius1))
{
using (GraphicsPath innerPath = RibbonProfessionalRenderer.RoundRectangle(rInner, radius2))
{
if (Ribbon != null && Ribbon.ActualBorderMode == RibbonWindowMode.NonClientAreaCustomDrawn)
{
RibbonProfessionalRenderer renderer = Ribbon.Renderer as RibbonProfessionalRenderer;
if (renderer != null)
{
e.Graphics.Clear(Theme.ColorTable.RibbonBackground); // draw the Form border explicitly, otherwise problems as MDI parent occur
using (SolidBrush p = new SolidBrush(Theme.ColorTable.Caption1))
{
e.Graphics.FillRectangle(p, new Rectangle(0, 0, Form.Width, Ribbon.CaptionBarSize));
}
renderer.DrawCaptionBarBackground(new Rectangle(0, Margins.Bottom - 1, Form.Width, Ribbon.CaptionBarSize), e.Graphics);
using (Region rgn = new Region(path))
{
//Set Window Region
Form.Region = rgn;
SmoothingMode smbuf = e.Graphics.SmoothingMode;
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
using (Pen p = new Pen(Theme.ColorTable.FormBorder, 1))
{
e.Graphics.DrawPath(p, innerPath);
}
e.Graphics.SmoothingMode = smbuf;
}
}
}
}
}
}
/// <summary>
/// Called when helped form is activated
/// </summary>
/// <param name="sender">Object that raised the event</param>
/// <param name="e">Event data</param>
protected virtual void Form_Activated(object sender, EventArgs e)
{
if (DesignMode) return;
WinApi.MARGINS dwmMargins = new WinApi.MARGINS(
Margins.Left,
Margins.Right,
Margins.Bottom + Ribbon.CaptionBarHeight,
Margins.Bottom);
if (WinApi.IsVista && !_frameExtended)
{
WinApi.DwmExtendFrameIntoClientArea(Form.Handle, ref dwmMargins);
_frameExtended = true;
}
}
/// <summary>
/// Processes the WndProc for a form with a Ribbbon. Returns true if message has been handled
/// </summary>
/// <param name="m">Message to process</param>
/// <returns><c>true</c> if message has been handled. <c>false</c> otherwise</returns>
public virtual bool WndProc(ref Message m)
{
if (DesignMode) return false;
bool handled = false;
if (WinApi.IsVista)
{
#region Checks if DWM processes the message
IntPtr result;
int dwmHandled = WinApi.DwmDefWindowProc(m.HWnd, m.Msg, m.WParam, m.LParam, out result);
if (dwmHandled == 1)
{
m.Result = result;
handled = true;
}
#endregion
}
//if (m.Msg == WinApi.WM_NCLBUTTONUP)
//{
// UpdateRibbonConditions();
//}
if (!handled)
{
if (m.Msg == WinApi.WM_NCCALCSIZE && (int)m.WParam == 1) //0x83
{
#region Catch the margins of what the client area would be
WinApi.NCCALCSIZE_PARAMS nccsp = (WinApi.NCCALCSIZE_PARAMS)Marshal.PtrToStructure(m.LParam, typeof(WinApi.NCCALCSIZE_PARAMS));
if (!MarginsChecked)
{
//Set what client area would be for passing to DwmExtendIntoClientArea
SetMargins(new Padding(
nccsp.rect2.Left - nccsp.rect1.Left,
nccsp.rect2.Top - nccsp.rect1.Top,
nccsp.rect1.Right - nccsp.rect2.Right,
nccsp.rect1.Bottom - nccsp.rect2.Bottom));
MarginsChecked = true;
}
#region Hack to get rid of the black caption bar when form is maximized on multi-monitor setups with DWM enabled
// toATwork: on multi-monitor setups the caption bar when the form is maximized the caption bar is black instead of glass
// * set handled to false and let the base implementation handle it, will work but then the default caption bar
// is also visible - not desired
// * setting the client area to some other value, e.g. descrease the size of the client area by one pixel will
// cause windows to render the caption bar a glass - not correct but the lesser of the two evils
if (Screen.AllScreens.Length > 1 && WinApi.IsGlassEnabled)
nccsp.rect0.Bottom -= 1;
#endregion
Marshal.StructureToPtr(nccsp, m.LParam, false);
m.Result = IntPtr.Zero;
handled = true;
#endregion
}
else if (m.Msg == WinApi.WM_NCACTIVATE && Ribbon != null && Ribbon.ActualBorderMode == RibbonWindowMode.NonClientAreaCustomDrawn)
{
Ribbon.Invalidate(); handled = true;
if (m.WParam == IntPtr.Zero) // if could be removed because result is ignored if WParam is TRUE
m.Result = (IntPtr)1;
}
else if ((m.Msg == WinApi.WM_ACTIVATE || m.Msg == WinApi.WM_PAINT) && WinApi.IsVista) //0x06 - 0x000F
{
m.Result = (IntPtr)1; handled = false;
}
else if (m.Msg == WinApi.WM_NCHITTEST && (int)m.Result == 0) //0x84
{
m.Result = new IntPtr(Convert.ToInt32(NonClientHitTest(new Point(WinApi.LoWord((int)m.LParam), WinApi.HiWord((int)m.LParam)))));
handled = true;
}
else if (m.Msg == WinApi.WM_SYSCOMMAND)
{
uint param = IntPtr.Size == 4 ? (uint)m.WParam.ToInt32() : (uint)m.WParam.ToInt64();
if ((param & 0xFFF0) == WinApi.SC_RESTORE)
{
Form.Size = _storeSize;
}
else if (Form.WindowState == FormWindowState.Normal)
{
_storeSize = Form.Size;
}
}
else if (m.Msg == WinApi.WM_WINDOWPOSCHANGING || m.Msg == WinApi.WM_WINDOWPOSCHANGED) // needed to update the title of MDI parent (at least)
{
Ribbon.Invalidate();
}
}
return handled;
}
/// <summary>
/// Performs hit test for mouse on the non client area of the form
/// </summary>
/// <param name="form">Form to check bounds</param>
/// <param name="dwmMargins">Margins of non client area</param>
/// <param name="lparam">Lparam of</param>
/// <returns></returns>
public virtual NonClientHitTestResult NonClientHitTest(Point hitPoint)
{
Rectangle topleft = Form.RectangleToScreen(new Rectangle(0, 0, Margins.Left, Margins.Left));
if (topleft.Contains(hitPoint))
return NonClientHitTestResult.TopLeft;
Rectangle topright = Form.RectangleToScreen(new Rectangle(Form.Width - Margins.Right, 0, Margins.Right, Margins.Right));
if (topright.Contains(hitPoint))
return NonClientHitTestResult.TopRight;
Rectangle botleft = Form.RectangleToScreen(new Rectangle(0, Form.Height - Margins.Bottom, Margins.Left, Margins.Bottom));
if (botleft.Contains(hitPoint))
return NonClientHitTestResult.BottomLeft;
Rectangle botright = Form.RectangleToScreen(new Rectangle(Form.Width - Margins.Right, Form.Height - Margins.Bottom, Margins.Right, Margins.Bottom));
if (botright.Contains(hitPoint))
return NonClientHitTestResult.BottomRight;
Rectangle top = Form.RectangleToScreen(new Rectangle(0, 0, Form.Width, Margins.Left));
if (top.Contains(hitPoint))
return NonClientHitTestResult.Top;
Rectangle cap = Form.RectangleToScreen(new Rectangle(0, Margins.Left, Form.Width, Margins.Top - Margins.Left));
if (cap.Contains(hitPoint))
return NonClientHitTestResult.Caption;
Rectangle left = Form.RectangleToScreen(new Rectangle(0, 0, Margins.Left, Form.Height));
if (left.Contains(hitPoint))
return NonClientHitTestResult.Left;
Rectangle right = Form.RectangleToScreen(new Rectangle(Form.Width - Margins.Right, 0, Margins.Right, Form.Height));
if (right.Contains(hitPoint))
return NonClientHitTestResult.Right;
Rectangle bottom = Form.RectangleToScreen(new Rectangle(0, Form.Height - Margins.Bottom, Form.Width, Margins.Bottom));
if (bottom.Contains(hitPoint))
return NonClientHitTestResult.Bottom;
return NonClientHitTestResult.Client;
}
/// <summary>
/// Sets the value of the <see cref="Margins"/> property;
/// </summary>
/// <param name="p"></param>
private void SetMargins(Padding p)
{
_margins = p;
Padding formPadding = p;
formPadding.Top = p.Bottom - 1;
if (!DesignMode)
Form.Padding = formPadding;
}
#endregion
}
}
| |
// 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.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:2.0.50727.5466
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using WebsitePanel.Providers.HeliconZoo;
//
// This source code was auto-generated by wsdl, Version=2.0.50727.42.
//
namespace WebsitePanel.EnterpriseServer {
using System.Xml.Serialization;
using System.Web.Services;
using System.ComponentModel;
using System.Web.Services.Protocols;
using System;
using System.Diagnostics;
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Web.Services.WebServiceBindingAttribute(Name="esHeliconZooSoap", Namespace="http://smbsaas/websitepanel/enterpriseserver")]
public partial class esHeliconZoo : Microsoft.Web.Services3.WebServicesClientProtocol {
private System.Threading.SendOrPostCallback GetEnginesOperationCompleted;
private System.Threading.SendOrPostCallback SetEnginesOperationCompleted;
private System.Threading.SendOrPostCallback IsEnginesEnabledOperationCompleted;
private System.Threading.SendOrPostCallback SwithEnginesEnabledOperationCompleted;
private System.Threading.SendOrPostCallback GetAllowedHeliconZooQuotasForPackageOperationCompleted;
private System.Threading.SendOrPostCallback GetEnabledEnginesForSiteOperationCompleted;
private System.Threading.SendOrPostCallback SetEnabledEnginesForSiteOperationCompleted;
private System.Threading.SendOrPostCallback IsWebCosoleEnabledOperationCompleted;
private System.Threading.SendOrPostCallback SetWebCosoleEnabledOperationCompleted;
/// <remarks/>
public esHeliconZoo() {
this.Url = "http://localhost:9002/esHeliconZoo.asmx";
}
/// <remarks/>
public event GetEnginesCompletedEventHandler GetEnginesCompleted;
/// <remarks/>
public event SetEnginesCompletedEventHandler SetEnginesCompleted;
/// <remarks/>
public event IsEnginesEnabledCompletedEventHandler IsEnginesEnabledCompleted;
/// <remarks/>
public event SwithEnginesEnabledCompletedEventHandler SwithEnginesEnabledCompleted;
/// <remarks/>
public event GetAllowedHeliconZooQuotasForPackageCompletedEventHandler GetAllowedHeliconZooQuotasForPackageCompleted;
/// <remarks/>
public event GetEnabledEnginesForSiteCompletedEventHandler GetEnabledEnginesForSiteCompleted;
/// <remarks/>
public event SetEnabledEnginesForSiteCompletedEventHandler SetEnabledEnginesForSiteCompleted;
/// <remarks/>
public event IsWebCosoleEnabledCompletedEventHandler IsWebCosoleEnabledCompleted;
/// <remarks/>
public event SetWebCosoleEnabledCompletedEventHandler SetWebCosoleEnabledCompleted;
/// <remarks/>
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/GetEngines", RequestNamespace="http://smbsaas/websitepanel/enterpriseserver", ResponseNamespace="http://smbsaas/websitepanel/enterpriseserver", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public HeliconZooEngine[] GetEngines(int serviceId) {
object[] results = this.Invoke("GetEngines", new object[] {
serviceId});
return ((HeliconZooEngine[])(results[0]));
}
/// <remarks/>
public System.IAsyncResult BeginGetEngines(int serviceId, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("GetEngines", new object[] {
serviceId}, callback, asyncState);
}
/// <remarks/>
public HeliconZooEngine[] EndGetEngines(System.IAsyncResult asyncResult) {
object[] results = this.EndInvoke(asyncResult);
return ((HeliconZooEngine[])(results[0]));
}
/// <remarks/>
public void GetEnginesAsync(int serviceId) {
this.GetEnginesAsync(serviceId, null);
}
/// <remarks/>
public void GetEnginesAsync(int serviceId, object userState) {
if ((this.GetEnginesOperationCompleted == null)) {
this.GetEnginesOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetEnginesOperationCompleted);
}
this.InvokeAsync("GetEngines", new object[] {
serviceId}, this.GetEnginesOperationCompleted, userState);
}
private void OnGetEnginesOperationCompleted(object arg) {
if ((this.GetEnginesCompleted != null)) {
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.GetEnginesCompleted(this, new GetEnginesCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/SetEngines", RequestNamespace="http://smbsaas/websitepanel/enterpriseserver", ResponseNamespace="http://smbsaas/websitepanel/enterpriseserver", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public void SetEngines(int serviceId, HeliconZooEngine[] userEngines) {
this.Invoke("SetEngines", new object[] {
serviceId,
userEngines});
}
/// <remarks/>
public System.IAsyncResult BeginSetEngines(int serviceId, HeliconZooEngine[] userEngines, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("SetEngines", new object[] {
serviceId,
userEngines}, callback, asyncState);
}
/// <remarks/>
public void EndSetEngines(System.IAsyncResult asyncResult) {
this.EndInvoke(asyncResult);
}
/// <remarks/>
public void SetEnginesAsync(int serviceId, HeliconZooEngine[] userEngines) {
this.SetEnginesAsync(serviceId, userEngines, null);
}
/// <remarks/>
public void SetEnginesAsync(int serviceId, HeliconZooEngine[] userEngines, object userState) {
if ((this.SetEnginesOperationCompleted == null)) {
this.SetEnginesOperationCompleted = new System.Threading.SendOrPostCallback(this.OnSetEnginesOperationCompleted);
}
this.InvokeAsync("SetEngines", new object[] {
serviceId,
userEngines}, this.SetEnginesOperationCompleted, userState);
}
private void OnSetEnginesOperationCompleted(object arg) {
if ((this.SetEnginesCompleted != null)) {
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.SetEnginesCompleted(this, new System.ComponentModel.AsyncCompletedEventArgs(invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/IsEnginesEnabled", RequestNamespace="http://smbsaas/websitepanel/enterpriseserver", ResponseNamespace="http://smbsaas/websitepanel/enterpriseserver", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public bool IsEnginesEnabled(int serviceId) {
object[] results = this.Invoke("IsEnginesEnabled", new object[] {
serviceId});
return ((bool)(results[0]));
}
/// <remarks/>
public System.IAsyncResult BeginIsEnginesEnabled(int serviceId, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("IsEnginesEnabled", new object[] {
serviceId}, callback, asyncState);
}
/// <remarks/>
public bool EndIsEnginesEnabled(System.IAsyncResult asyncResult) {
object[] results = this.EndInvoke(asyncResult);
return ((bool)(results[0]));
}
/// <remarks/>
public void IsEnginesEnabledAsync(int serviceId) {
this.IsEnginesEnabledAsync(serviceId, null);
}
/// <remarks/>
public void IsEnginesEnabledAsync(int serviceId, object userState) {
if ((this.IsEnginesEnabledOperationCompleted == null)) {
this.IsEnginesEnabledOperationCompleted = new System.Threading.SendOrPostCallback(this.OnIsEnginesEnabledOperationCompleted);
}
this.InvokeAsync("IsEnginesEnabled", new object[] {
serviceId}, this.IsEnginesEnabledOperationCompleted, userState);
}
private void OnIsEnginesEnabledOperationCompleted(object arg) {
if ((this.IsEnginesEnabledCompleted != null)) {
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.IsEnginesEnabledCompleted(this, new IsEnginesEnabledCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/SwithEnginesEnabled", RequestNamespace="http://smbsaas/websitepanel/enterpriseserver", ResponseNamespace="http://smbsaas/websitepanel/enterpriseserver", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public void SwithEnginesEnabled(int serviceId, bool enabled) {
this.Invoke("SwithEnginesEnabled", new object[] {
serviceId,
enabled});
}
/// <remarks/>
public System.IAsyncResult BeginSwithEnginesEnabled(int serviceId, bool enabled, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("SwithEnginesEnabled", new object[] {
serviceId,
enabled}, callback, asyncState);
}
/// <remarks/>
public void EndSwithEnginesEnabled(System.IAsyncResult asyncResult) {
this.EndInvoke(asyncResult);
}
/// <remarks/>
public void SwithEnginesEnabledAsync(int serviceId, bool enabled) {
this.SwithEnginesEnabledAsync(serviceId, enabled, null);
}
/// <remarks/>
public void SwithEnginesEnabledAsync(int serviceId, bool enabled, object userState) {
if ((this.SwithEnginesEnabledOperationCompleted == null)) {
this.SwithEnginesEnabledOperationCompleted = new System.Threading.SendOrPostCallback(this.OnSwithEnginesEnabledOperationCompleted);
}
this.InvokeAsync("SwithEnginesEnabled", new object[] {
serviceId,
enabled}, this.SwithEnginesEnabledOperationCompleted, userState);
}
private void OnSwithEnginesEnabledOperationCompleted(object arg) {
if ((this.SwithEnginesEnabledCompleted != null)) {
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.SwithEnginesEnabledCompleted(this, new System.ComponentModel.AsyncCompletedEventArgs(invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/GetAllowedHeliconZooQuotasForPackage" +
"", RequestNamespace="http://smbsaas/websitepanel/enterpriseserver", ResponseNamespace="http://smbsaas/websitepanel/enterpriseserver", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public ShortHeliconZooEngine[] GetAllowedHeliconZooQuotasForPackage(int packageId) {
object[] results = this.Invoke("GetAllowedHeliconZooQuotasForPackage", new object[] {
packageId});
return ((ShortHeliconZooEngine[])(results[0]));
}
/// <remarks/>
public System.IAsyncResult BeginGetAllowedHeliconZooQuotasForPackage(int packageId, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("GetAllowedHeliconZooQuotasForPackage", new object[] {
packageId}, callback, asyncState);
}
/// <remarks/>
public ShortHeliconZooEngine[] EndGetAllowedHeliconZooQuotasForPackage(System.IAsyncResult asyncResult) {
object[] results = this.EndInvoke(asyncResult);
return ((ShortHeliconZooEngine[])(results[0]));
}
/// <remarks/>
public void GetAllowedHeliconZooQuotasForPackageAsync(int packageId) {
this.GetAllowedHeliconZooQuotasForPackageAsync(packageId, null);
}
/// <remarks/>
public void GetAllowedHeliconZooQuotasForPackageAsync(int packageId, object userState) {
if ((this.GetAllowedHeliconZooQuotasForPackageOperationCompleted == null)) {
this.GetAllowedHeliconZooQuotasForPackageOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetAllowedHeliconZooQuotasForPackageOperationCompleted);
}
this.InvokeAsync("GetAllowedHeliconZooQuotasForPackage", new object[] {
packageId}, this.GetAllowedHeliconZooQuotasForPackageOperationCompleted, userState);
}
private void OnGetAllowedHeliconZooQuotasForPackageOperationCompleted(object arg) {
if ((this.GetAllowedHeliconZooQuotasForPackageCompleted != null)) {
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.GetAllowedHeliconZooQuotasForPackageCompleted(this, new GetAllowedHeliconZooQuotasForPackageCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/GetEnabledEnginesForSite", RequestNamespace="http://smbsaas/websitepanel/enterpriseserver", ResponseNamespace="http://smbsaas/websitepanel/enterpriseserver", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public string[] GetEnabledEnginesForSite(string siteId, int packageId) {
object[] results = this.Invoke("GetEnabledEnginesForSite", new object[] {
siteId,
packageId});
return ((string[])(results[0]));
}
/// <remarks/>
public System.IAsyncResult BeginGetEnabledEnginesForSite(string siteId, int packageId, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("GetEnabledEnginesForSite", new object[] {
siteId,
packageId}, callback, asyncState);
}
/// <remarks/>
public string[] EndGetEnabledEnginesForSite(System.IAsyncResult asyncResult) {
object[] results = this.EndInvoke(asyncResult);
return ((string[])(results[0]));
}
/// <remarks/>
public void GetEnabledEnginesForSiteAsync(string siteId, int packageId) {
this.GetEnabledEnginesForSiteAsync(siteId, packageId, null);
}
/// <remarks/>
public void GetEnabledEnginesForSiteAsync(string siteId, int packageId, object userState) {
if ((this.GetEnabledEnginesForSiteOperationCompleted == null)) {
this.GetEnabledEnginesForSiteOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetEnabledEnginesForSiteOperationCompleted);
}
this.InvokeAsync("GetEnabledEnginesForSite", new object[] {
siteId,
packageId}, this.GetEnabledEnginesForSiteOperationCompleted, userState);
}
private void OnGetEnabledEnginesForSiteOperationCompleted(object arg) {
if ((this.GetEnabledEnginesForSiteCompleted != null)) {
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.GetEnabledEnginesForSiteCompleted(this, new GetEnabledEnginesForSiteCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/SetEnabledEnginesForSite", RequestNamespace="http://smbsaas/websitepanel/enterpriseserver", ResponseNamespace="http://smbsaas/websitepanel/enterpriseserver", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public void SetEnabledEnginesForSite(string siteId, int packageId, string[] engines) {
this.Invoke("SetEnabledEnginesForSite", new object[] {
siteId,
packageId,
engines});
}
/// <remarks/>
public System.IAsyncResult BeginSetEnabledEnginesForSite(string siteId, int packageId, string[] engines, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("SetEnabledEnginesForSite", new object[] {
siteId,
packageId,
engines}, callback, asyncState);
}
/// <remarks/>
public void EndSetEnabledEnginesForSite(System.IAsyncResult asyncResult) {
this.EndInvoke(asyncResult);
}
/// <remarks/>
public void SetEnabledEnginesForSiteAsync(string siteId, int packageId, string[] engines) {
this.SetEnabledEnginesForSiteAsync(siteId, packageId, engines, null);
}
/// <remarks/>
public void SetEnabledEnginesForSiteAsync(string siteId, int packageId, string[] engines, object userState) {
if ((this.SetEnabledEnginesForSiteOperationCompleted == null)) {
this.SetEnabledEnginesForSiteOperationCompleted = new System.Threading.SendOrPostCallback(this.OnSetEnabledEnginesForSiteOperationCompleted);
}
this.InvokeAsync("SetEnabledEnginesForSite", new object[] {
siteId,
packageId,
engines}, this.SetEnabledEnginesForSiteOperationCompleted, userState);
}
private void OnSetEnabledEnginesForSiteOperationCompleted(object arg) {
if ((this.SetEnabledEnginesForSiteCompleted != null)) {
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.SetEnabledEnginesForSiteCompleted(this, new System.ComponentModel.AsyncCompletedEventArgs(invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/IsWebCosoleEnabled", RequestNamespace="http://smbsaas/websitepanel/enterpriseserver", ResponseNamespace="http://smbsaas/websitepanel/enterpriseserver", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public bool IsWebCosoleEnabled(int serviceId) {
object[] results = this.Invoke("IsWebCosoleEnabled", new object[] {
serviceId});
return ((bool)(results[0]));
}
/// <remarks/>
public System.IAsyncResult BeginIsWebCosoleEnabled(int serviceId, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("IsWebCosoleEnabled", new object[] {
serviceId}, callback, asyncState);
}
/// <remarks/>
public bool EndIsWebCosoleEnabled(System.IAsyncResult asyncResult) {
object[] results = this.EndInvoke(asyncResult);
return ((bool)(results[0]));
}
/// <remarks/>
public void IsWebCosoleEnabledAsync(int serviceId) {
this.IsWebCosoleEnabledAsync(serviceId, null);
}
/// <remarks/>
public void IsWebCosoleEnabledAsync(int serviceId, object userState) {
if ((this.IsWebCosoleEnabledOperationCompleted == null)) {
this.IsWebCosoleEnabledOperationCompleted = new System.Threading.SendOrPostCallback(this.OnIsWebCosoleEnabledOperationCompleted);
}
this.InvokeAsync("IsWebCosoleEnabled", new object[] {
serviceId}, this.IsWebCosoleEnabledOperationCompleted, userState);
}
private void OnIsWebCosoleEnabledOperationCompleted(object arg) {
if ((this.IsWebCosoleEnabledCompleted != null)) {
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.IsWebCosoleEnabledCompleted(this, new IsWebCosoleEnabledCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/SetWebCosoleEnabled", RequestNamespace="http://smbsaas/websitepanel/enterpriseserver", ResponseNamespace="http://smbsaas/websitepanel/enterpriseserver", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public void SetWebCosoleEnabled(int serviceId, bool enabled) {
this.Invoke("SetWebCosoleEnabled", new object[] {
serviceId,
enabled});
}
/// <remarks/>
public System.IAsyncResult BeginSetWebCosoleEnabled(int serviceId, bool enabled, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("SetWebCosoleEnabled", new object[] {
serviceId,
enabled}, callback, asyncState);
}
/// <remarks/>
public void EndSetWebCosoleEnabled(System.IAsyncResult asyncResult) {
this.EndInvoke(asyncResult);
}
/// <remarks/>
public void SetWebCosoleEnabledAsync(int serviceId, bool enabled) {
this.SetWebCosoleEnabledAsync(serviceId, enabled, null);
}
/// <remarks/>
public void SetWebCosoleEnabledAsync(int serviceId, bool enabled, object userState) {
if ((this.SetWebCosoleEnabledOperationCompleted == null)) {
this.SetWebCosoleEnabledOperationCompleted = new System.Threading.SendOrPostCallback(this.OnSetWebCosoleEnabledOperationCompleted);
}
this.InvokeAsync("SetWebCosoleEnabled", new object[] {
serviceId,
enabled}, this.SetWebCosoleEnabledOperationCompleted, userState);
}
private void OnSetWebCosoleEnabledOperationCompleted(object arg) {
if ((this.SetWebCosoleEnabledCompleted != null)) {
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.SetWebCosoleEnabledCompleted(this, new System.ComponentModel.AsyncCompletedEventArgs(invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
public new void CancelAsync(object userState) {
base.CancelAsync(userState);
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
public delegate void GetEnginesCompletedEventHandler(object sender, GetEnginesCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class GetEnginesCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {
private object[] results;
internal GetEnginesCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) :
base(exception, cancelled, userState) {
this.results = results;
}
/// <remarks/>
public HeliconZooEngine[] Result {
get {
this.RaiseExceptionIfNecessary();
return ((HeliconZooEngine[])(this.results[0]));
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
public delegate void SetEnginesCompletedEventHandler(object sender, System.ComponentModel.AsyncCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
public delegate void IsEnginesEnabledCompletedEventHandler(object sender, IsEnginesEnabledCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class IsEnginesEnabledCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {
private object[] results;
internal IsEnginesEnabledCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) :
base(exception, cancelled, userState) {
this.results = results;
}
/// <remarks/>
public bool Result {
get {
this.RaiseExceptionIfNecessary();
return ((bool)(this.results[0]));
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
public delegate void SwithEnginesEnabledCompletedEventHandler(object sender, System.ComponentModel.AsyncCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
public delegate void GetAllowedHeliconZooQuotasForPackageCompletedEventHandler(object sender, GetAllowedHeliconZooQuotasForPackageCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class GetAllowedHeliconZooQuotasForPackageCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {
private object[] results;
internal GetAllowedHeliconZooQuotasForPackageCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) :
base(exception, cancelled, userState) {
this.results = results;
}
/// <remarks/>
public ShortHeliconZooEngine[] Result {
get {
this.RaiseExceptionIfNecessary();
return ((ShortHeliconZooEngine[])(this.results[0]));
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
public delegate void GetEnabledEnginesForSiteCompletedEventHandler(object sender, GetEnabledEnginesForSiteCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class GetEnabledEnginesForSiteCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {
private object[] results;
internal GetEnabledEnginesForSiteCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) :
base(exception, cancelled, userState) {
this.results = results;
}
/// <remarks/>
public string[] Result {
get {
this.RaiseExceptionIfNecessary();
return ((string[])(this.results[0]));
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
public delegate void SetEnabledEnginesForSiteCompletedEventHandler(object sender, System.ComponentModel.AsyncCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
public delegate void IsWebCosoleEnabledCompletedEventHandler(object sender, IsWebCosoleEnabledCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class IsWebCosoleEnabledCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {
private object[] results;
internal IsWebCosoleEnabledCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) :
base(exception, cancelled, userState) {
this.results = results;
}
/// <remarks/>
public bool Result {
get {
this.RaiseExceptionIfNecessary();
return ((bool)(this.results[0]));
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
public delegate void SetWebCosoleEnabledCompletedEventHandler(object sender, System.ComponentModel.AsyncCompletedEventArgs e);
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace OpenLeczna.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
/* ====================================================================
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 NPOI.XSSF.UserModel
{
using System;
using NUnit.Framework;
using System.Drawing;
using System.Collections.Generic;
[TestFixture]
public class TestXSSFTextParagraph
{
[Test]
public void XSSFTextParagraph_()
{
XSSFWorkbook wb = new XSSFWorkbook();
try
{
XSSFSheet sheet = wb.CreateSheet() as XSSFSheet;
XSSFDrawing Drawing = sheet.CreateDrawingPatriarch() as XSSFDrawing;
XSSFTextBox shape = Drawing.CreateTextbox(new XSSFClientAnchor(0, 0, 0, 0, 2, 2, 3, 4)) as XSSFTextBox;
XSSFRichTextString rt = new XSSFRichTextString("Test String");
XSSFFont font = wb.CreateFont() as XSSFFont;
Color color = Color.FromArgb(0, 255, 255);
font.SetColor(new XSSFColor(color));
font.FontName = (/*setter*/"Arial");
rt.ApplyFont(font);
shape.SetText(rt);
List<XSSFTextParagraph> paras = shape.TextParagraphs;
Assert.AreEqual(1, paras.Count);
XSSFTextParagraph text = paras[(0)];
Assert.AreEqual("Test String", text.Text);
Assert.IsFalse(text.IsBullet);
Assert.IsNotNull(text.GetXmlObject());
Assert.AreEqual(shape.GetCTShape(), text.ParentShape);
Assert.IsNotNull(text.GetEnumerator());
Assert.IsNotNull(text.AddLineBreak());
Assert.IsNotNull(text.TextRuns);
Assert.AreEqual(2, text.TextRuns.Count);
text.AddNewTextRun();
Assert.AreEqual(3, text.TextRuns.Count);
Assert.AreEqual(TextAlign.LEFT, text.TextAlign);
text.TextAlign = TextAlign.None;
Assert.AreEqual(TextAlign.LEFT, text.TextAlign);
text.TextAlign = (/*setter*/TextAlign.CENTER);
Assert.AreEqual(TextAlign.CENTER, text.TextAlign);
text.TextAlign = (/*setter*/TextAlign.RIGHT);
Assert.AreEqual(TextAlign.RIGHT, text.TextAlign);
text.TextAlign = TextAlign.None;
Assert.AreEqual(TextAlign.LEFT, text.TextAlign);
text.TextFontAlign = (/*setter*/TextFontAlign.BASELINE);
Assert.AreEqual(TextFontAlign.BASELINE, text.TextFontAlign);
text.TextFontAlign = (/*setter*/TextFontAlign.BOTTOM);
Assert.AreEqual(TextFontAlign.BOTTOM, text.TextFontAlign);
text.TextFontAlign = TextFontAlign.None;
Assert.AreEqual(TextFontAlign.BASELINE, text.TextFontAlign);
text.TextFontAlign = TextFontAlign.None;
Assert.AreEqual(TextFontAlign.BASELINE, text.TextFontAlign);
Assert.IsNull(text.BulletFont);
text.BulletFont = (/*setter*/"Arial");
Assert.AreEqual("Arial", text.BulletFont);
Assert.IsNull(text.BulletCharacter);
text.BulletCharacter = (/*setter*/".");
Assert.AreEqual(".", text.BulletCharacter);
//Assert.IsNull(text.BulletFontColor);
Assert.AreEqual(Color.Empty, text.BulletFontColor);
text.BulletFontColor = (/*setter*/color);
Assert.AreEqual(color, text.BulletFontColor);
Assert.AreEqual(100.0, text.BulletFontSize, 0.01);
text.BulletFontSize = (/*setter*/1.0);
Assert.AreEqual(1.0, text.BulletFontSize, 0.01);
text.BulletFontSize = (/*setter*/1.0);
Assert.AreEqual(1.0, text.BulletFontSize, 0.01);
text.BulletFontSize = (/*setter*/-9.0);
Assert.AreEqual(-9.0, text.BulletFontSize, 0.01);
text.BulletFontSize = (/*setter*/-9.0);
Assert.AreEqual(-9.0, text.BulletFontSize, 0.01);
text.BulletFontSize = (/*setter*/1.0);
Assert.AreEqual(1.0, text.BulletFontSize, 0.01);
text.BulletFontSize = (/*setter*/-9.0);
Assert.AreEqual(-9.0, text.BulletFontSize, 0.01);
Assert.AreEqual(0.0, text.Indent, 0.01);
text.Indent = (/*setter*/2.0);
Assert.AreEqual(2.0, text.Indent, 0.01);
text.Indent = (/*setter*/-1.0);
Assert.AreEqual(0.0, text.Indent, 0.01);
text.Indent = (/*setter*/-1.0);
Assert.AreEqual(0.0, text.Indent, 0.01);
Assert.AreEqual(0.0, text.LeftMargin, 0.01);
text.LeftMargin = (/*setter*/3.0);
Assert.AreEqual(3.0, text.LeftMargin, 0.01);
text.LeftMargin = (/*setter*/-1.0);
Assert.AreEqual(0.0, text.LeftMargin, 0.01);
text.LeftMargin = (/*setter*/-1.0);
Assert.AreEqual(0.0, text.LeftMargin, 0.01);
Assert.AreEqual(0.0, text.RightMargin, 0.01);
text.RightMargin = (/*setter*/4.5);
Assert.AreEqual(4.5, text.RightMargin, 0.01);
text.RightMargin = (/*setter*/-1.0);
Assert.AreEqual(0.0, text.RightMargin, 0.01);
text.RightMargin = (/*setter*/-1.0);
Assert.AreEqual(0.0, text.RightMargin, 0.01);
Assert.AreEqual(0.0, text.DefaultTabSize, 0.01);
Assert.AreEqual(0.0, text.GetTabStop(0), 0.01);
text.AddTabStop(3.14);
Assert.AreEqual(3.14, text.GetTabStop(0), 0.01);
Assert.AreEqual(100.0, text.LineSpacing, 0.01);
text.LineSpacing = (/*setter*/3.15);
Assert.AreEqual(3.15, text.LineSpacing, 0.01);
text.LineSpacing = (/*setter*/-2.13);
Assert.AreEqual(-2.13, text.LineSpacing, 0.01);
Assert.AreEqual(0.0, text.SpaceBefore, 0.01);
text.SpaceBefore = (/*setter*/3.17);
Assert.AreEqual(3.17, text.SpaceBefore, 0.01);
text.SpaceBefore = (/*setter*/-4.7);
Assert.AreEqual(-4.7, text.SpaceBefore, 0.01);
Assert.AreEqual(0.0, text.SpaceAfter, 0.01);
text.SpaceAfter = (/*setter*/6.17);
Assert.AreEqual(6.17, text.SpaceAfter, 0.01);
text.SpaceAfter = (/*setter*/-8.17);
Assert.AreEqual(-8.17, text.SpaceAfter, 0.01);
Assert.AreEqual(0, text.Level);
text.Level = (/*setter*/1);
Assert.AreEqual(1, text.Level);
text.Level = (/*setter*/4);
Assert.AreEqual(4, text.Level);
Assert.IsTrue(text.IsBullet);
Assert.IsFalse(text.IsBulletAutoNumber);
text.IsBullet = (false);
text.IsBullet = (false);
Assert.IsFalse(text.IsBullet);
Assert.IsFalse(text.IsBulletAutoNumber);
text.IsBullet = (true);
Assert.IsTrue(text.IsBullet);
Assert.IsFalse(text.IsBulletAutoNumber);
Assert.AreEqual(0, text.BulletAutoNumberStart);
Assert.AreEqual(ListAutoNumber.ARABIC_PLAIN, text.BulletAutoNumberScheme);
text.IsBullet = (false);
Assert.IsFalse(text.IsBullet);
text.SetBullet(ListAutoNumber.CIRCLE_NUM_DB_PLAIN);
Assert.IsTrue(text.IsBullet);
Assert.IsTrue(text.IsBulletAutoNumber);
//Assert.AreEqual(0, text.BulletAutoNumberStart);
//This value should be 1, see CT_TextAutonumberBullet.startAt, default value is 1;
Assert.AreEqual(1, text.BulletAutoNumberStart);
Assert.AreEqual(ListAutoNumber.CIRCLE_NUM_DB_PLAIN, text.BulletAutoNumberScheme);
text.IsBullet = (false);
Assert.IsFalse(text.IsBullet);
Assert.IsFalse(text.IsBulletAutoNumber);
text.SetBullet(ListAutoNumber.CIRCLE_NUM_WD_BLACK_PLAIN, 10);
Assert.IsTrue(text.IsBullet);
Assert.IsTrue(text.IsBulletAutoNumber);
Assert.AreEqual(10, text.BulletAutoNumberStart);
Assert.AreEqual(ListAutoNumber.CIRCLE_NUM_WD_BLACK_PLAIN, text.BulletAutoNumberScheme);
Assert.IsNotNull(text.ToString());
new XSSFTextParagraph(text.GetXmlObject(), shape.GetCTShape());
}
finally
{
wb.Close();
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Compute
{
using System.Threading.Tasks;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// Extension methods for VirtualMachinesOperations.
/// </summary>
public static partial class VirtualMachinesOperationsExtensions
{
/// <summary>
/// Captures the VM by copying virtual hard disks of the VM and outputs a
/// template that can be used to create similar VMs.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Capture Virtual Machine operation.
/// </param>
public static VirtualMachineCaptureResult Capture(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, VirtualMachineCaptureParameters parameters)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IVirtualMachinesOperations)s).CaptureAsync(resourceGroupName, vmName, parameters), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Captures the VM by copying virtual hard disks of the VM and outputs a
/// template that can be used to create similar VMs.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Capture Virtual Machine operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<VirtualMachineCaptureResult> CaptureAsync(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, VirtualMachineCaptureParameters parameters, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.CaptureWithHttpMessagesAsync(resourceGroupName, vmName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Captures the VM by copying virtual hard disks of the VM and outputs a
/// template that can be used to create similar VMs.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Capture Virtual Machine operation.
/// </param>
public static VirtualMachineCaptureResult BeginCapture(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, VirtualMachineCaptureParameters parameters)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IVirtualMachinesOperations)s).BeginCaptureAsync(resourceGroupName, vmName, parameters), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Captures the VM by copying virtual hard disks of the VM and outputs a
/// template that can be used to create similar VMs.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Capture Virtual Machine operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<VirtualMachineCaptureResult> BeginCaptureAsync(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, VirtualMachineCaptureParameters parameters, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.BeginCaptureWithHttpMessagesAsync(resourceGroupName, vmName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The operation to create or update a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Create Virtual Machine operation.
/// </param>
public static VirtualMachine CreateOrUpdate(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, VirtualMachine parameters)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IVirtualMachinesOperations)s).CreateOrUpdateAsync(resourceGroupName, vmName, parameters), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The operation to create or update a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Create Virtual Machine operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<VirtualMachine> CreateOrUpdateAsync(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, VirtualMachine parameters, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, vmName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The operation to create or update a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Create Virtual Machine operation.
/// </param>
public static VirtualMachine BeginCreateOrUpdate(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, VirtualMachine parameters)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IVirtualMachinesOperations)s).BeginCreateOrUpdateAsync(resourceGroupName, vmName, parameters), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The operation to create or update a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Create Virtual Machine operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<VirtualMachine> BeginCreateOrUpdateAsync(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, VirtualMachine parameters, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, vmName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The operation to delete a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
public static void Delete(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName)
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((IVirtualMachinesOperations)s).DeleteAsync(resourceGroupName, vmName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The operation to delete a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task DeleteAsync(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.DeleteWithHttpMessagesAsync(resourceGroupName, vmName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// The operation to delete a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
public static void BeginDelete(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName)
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((IVirtualMachinesOperations)s).BeginDeleteAsync(resourceGroupName, vmName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The operation to delete a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task BeginDeleteAsync(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, vmName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// The operation to get a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='expand'>
/// The expand expression to apply on the operation. Possible values include:
/// 'instanceView'
/// </param>
public static VirtualMachine Get(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, InstanceViewTypes? expand = default(InstanceViewTypes?))
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IVirtualMachinesOperations)s).GetAsync(resourceGroupName, vmName, expand), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The operation to get a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='expand'>
/// The expand expression to apply on the operation. Possible values include:
/// 'instanceView'
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<VirtualMachine> GetAsync(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, InstanceViewTypes? expand = default(InstanceViewTypes?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, vmName, expand, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Shuts down the Virtual Machine and releases the compute resources. You are
/// not billed for the compute resources that this Virtual Machine uses.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
public static void Deallocate(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName)
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((IVirtualMachinesOperations)s).DeallocateAsync(resourceGroupName, vmName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Shuts down the Virtual Machine and releases the compute resources. You are
/// not billed for the compute resources that this Virtual Machine uses.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task DeallocateAsync(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.DeallocateWithHttpMessagesAsync(resourceGroupName, vmName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Shuts down the Virtual Machine and releases the compute resources. You are
/// not billed for the compute resources that this Virtual Machine uses.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
public static void BeginDeallocate(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName)
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((IVirtualMachinesOperations)s).BeginDeallocateAsync(resourceGroupName, vmName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Shuts down the Virtual Machine and releases the compute resources. You are
/// not billed for the compute resources that this Virtual Machine uses.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task BeginDeallocateAsync(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.BeginDeallocateWithHttpMessagesAsync(resourceGroupName, vmName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Sets the state of the VM as Generalized.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
public static void Generalize(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName)
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((IVirtualMachinesOperations)s).GeneralizeAsync(resourceGroupName, vmName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Sets the state of the VM as Generalized.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task GeneralizeAsync(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.GeneralizeWithHttpMessagesAsync(resourceGroupName, vmName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// The operation to list virtual machines under a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
public static Microsoft.Rest.Azure.IPage<VirtualMachine> List(this IVirtualMachinesOperations operations, string resourceGroupName)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IVirtualMachinesOperations)s).ListAsync(resourceGroupName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The operation to list virtual machines under a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Microsoft.Rest.Azure.IPage<VirtualMachine>> ListAsync(this IVirtualMachinesOperations operations, string resourceGroupName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets the list of Virtual Machines in the subscription. Use nextLink
/// property in the response to get the next page of Virtual Machines. Do
/// this till nextLink is not null to fetch all the Virtual Machines.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static Microsoft.Rest.Azure.IPage<VirtualMachine> ListAll(this IVirtualMachinesOperations operations)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IVirtualMachinesOperations)s).ListAllAsync(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets the list of Virtual Machines in the subscription. Use nextLink
/// property in the response to get the next page of Virtual Machines. Do
/// this till nextLink is not null to fetch all the Virtual Machines.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Microsoft.Rest.Azure.IPage<VirtualMachine>> ListAllAsync(this IVirtualMachinesOperations operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.ListAllWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists all available virtual machine sizes it can be resized to for a
/// virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
public static System.Collections.Generic.IEnumerable<VirtualMachineSize> ListAvailableSizes(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IVirtualMachinesOperations)s).ListAvailableSizesAsync(resourceGroupName, vmName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Lists all available virtual machine sizes it can be resized to for a
/// virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<System.Collections.Generic.IEnumerable<VirtualMachineSize>> ListAvailableSizesAsync(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.ListAvailableSizesWithHttpMessagesAsync(resourceGroupName, vmName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The operation to power off (stop) a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
public static void PowerOff(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName)
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((IVirtualMachinesOperations)s).PowerOffAsync(resourceGroupName, vmName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The operation to power off (stop) a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task PowerOffAsync(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.PowerOffWithHttpMessagesAsync(resourceGroupName, vmName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// The operation to power off (stop) a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
public static void BeginPowerOff(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName)
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((IVirtualMachinesOperations)s).BeginPowerOffAsync(resourceGroupName, vmName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The operation to power off (stop) a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task BeginPowerOffAsync(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.BeginPowerOffWithHttpMessagesAsync(resourceGroupName, vmName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// The operation to restart a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
public static void Restart(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName)
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((IVirtualMachinesOperations)s).RestartAsync(resourceGroupName, vmName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The operation to restart a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task RestartAsync(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.RestartWithHttpMessagesAsync(resourceGroupName, vmName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// The operation to restart a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
public static void BeginRestart(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName)
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((IVirtualMachinesOperations)s).BeginRestartAsync(resourceGroupName, vmName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The operation to restart a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task BeginRestartAsync(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.BeginRestartWithHttpMessagesAsync(resourceGroupName, vmName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// The operation to start a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
public static void Start(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName)
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((IVirtualMachinesOperations)s).StartAsync(resourceGroupName, vmName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The operation to start a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task StartAsync(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.StartWithHttpMessagesAsync(resourceGroupName, vmName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// The operation to start a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
public static void BeginStart(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName)
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((IVirtualMachinesOperations)s).BeginStartAsync(resourceGroupName, vmName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The operation to start a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task BeginStartAsync(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.BeginStartWithHttpMessagesAsync(resourceGroupName, vmName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// The operation to redeploy a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
public static void Redeploy(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName)
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((IVirtualMachinesOperations)s).RedeployAsync(resourceGroupName, vmName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The operation to redeploy a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task RedeployAsync(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.RedeployWithHttpMessagesAsync(resourceGroupName, vmName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// The operation to redeploy a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
public static void BeginRedeploy(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName)
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((IVirtualMachinesOperations)s).BeginRedeployAsync(resourceGroupName, vmName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The operation to redeploy a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task BeginRedeployAsync(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.BeginRedeployWithHttpMessagesAsync(resourceGroupName, vmName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// The operation to list virtual machines under a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static Microsoft.Rest.Azure.IPage<VirtualMachine> ListNext(this IVirtualMachinesOperations operations, string nextPageLink)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IVirtualMachinesOperations)s).ListNextAsync(nextPageLink), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The operation to list virtual machines under a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Microsoft.Rest.Azure.IPage<VirtualMachine>> ListNextAsync(this IVirtualMachinesOperations operations, string nextPageLink, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets the list of Virtual Machines in the subscription. Use nextLink
/// property in the response to get the next page of Virtual Machines. Do
/// this till nextLink is not null to fetch all the Virtual Machines.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static Microsoft.Rest.Azure.IPage<VirtualMachine> ListAllNext(this IVirtualMachinesOperations operations, string nextPageLink)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IVirtualMachinesOperations)s).ListAllNextAsync(nextPageLink), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets the list of Virtual Machines in the subscription. Use nextLink
/// property in the response to get the next page of Virtual Machines. Do
/// this till nextLink is not null to fetch all the Virtual Machines.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Microsoft.Rest.Azure.IPage<VirtualMachine>> ListAllNextAsync(this IVirtualMachinesOperations operations, string nextPageLink, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.ListAllNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
// Copyright (c) Charlie Poole, Rob Prouse and Contributors. MIT License - see LICENSE.txt
using System;
using System.Diagnostics;
using System.Reflection;
using System.Threading;
using System.Globalization;
using System.IO;
using NUnit.Framework.Constraints;
using NUnit.Framework.Internal.Execution;
using NUnit.Framework.Interfaces;
using System.Security.Principal;
using System.Threading.Tasks;
namespace NUnit.Framework.Internal
{
/// <summary>
/// Summary description for TestExecutionContextTests.
/// </summary>
[TestFixture][Property("Question", "Why?")]
public class TestExecutionContextTests
{
private TestExecutionContext _fixtureContext;
private TestExecutionContext _setupContext;
private ResultState _fixtureResult;
string originalDirectory;
CultureInfo originalCulture;
CultureInfo originalUICulture;
IPrincipal originalPrincipal;
readonly DateTime _fixtureCreateTime = DateTime.UtcNow;
readonly long _fixtureCreateTicks = Stopwatch.GetTimestamp();
[OneTimeSetUp]
public void OneTimeSetUp()
{
_fixtureContext = TestExecutionContext.CurrentContext;
_fixtureResult = _fixtureContext.CurrentResult.ResultState;
}
[OneTimeTearDown]
public void OneTimeTearDown()
{
// TODO: We put some tests in one time teardown to verify that
// the context is still valid. It would be better if these tests
// were placed in a second-level test, invoked from this test class.
TestExecutionContext ec = TestExecutionContext.CurrentContext;
Assert.That(ec.CurrentTest.Name, Is.EqualTo("TestExecutionContextTests"));
Assert.That(ec.CurrentTest.FullName,
Is.EqualTo("NUnit.Framework.Internal.TestExecutionContextTests"));
Assert.That(_fixtureContext.CurrentTest.Id, Is.Not.Null.And.Not.Empty);
Assert.That(_fixtureContext.CurrentTest.Properties.Get("Question"), Is.EqualTo("Why?"));
}
[SetUp]
public void Initialize()
{
_setupContext = TestExecutionContext.CurrentContext;
originalDirectory = Directory.GetCurrentDirectory();
originalCulture = CultureInfo.CurrentCulture;
originalUICulture = CultureInfo.CurrentUICulture;
originalPrincipal = Thread.CurrentPrincipal;
}
[TearDown]
public void Cleanup()
{
Directory.SetCurrentDirectory(originalDirectory);
Thread.CurrentThread.CurrentCulture = originalCulture;
Thread.CurrentThread.CurrentUICulture = originalUICulture;
Thread.CurrentPrincipal = originalPrincipal;
Assert.That(
TestExecutionContext.CurrentContext.CurrentTest.FullName,
Is.EqualTo(_setupContext.CurrentTest.FullName),
"Context at TearDown failed to match that saved from SetUp");
Assert.That(
TestExecutionContext.CurrentContext.CurrentResult.Name,
Is.EqualTo(_setupContext.CurrentResult.Name),
"Cannot access CurrentResult in TearDown");
}
#region CurrentContext
[Test]
public async Task CurrentContextFlowsWithAsyncExecution()
{
var context = TestExecutionContext.CurrentContext;
await YieldAsync();
Assert.AreSame(context, TestExecutionContext.CurrentContext);
}
[Test]
public async Task CurrentContextFlowsWithParallelAsyncExecution()
{
var expected = TestExecutionContext.CurrentContext;
var parallelResult = await WhenAllAsync(YieldAndReturnContext(), YieldAndReturnContext());
Assert.AreSame(expected, TestExecutionContext.CurrentContext);
Assert.AreSame(expected, parallelResult[0]);
Assert.AreSame(expected, parallelResult[1]);
}
[Test]
public void CurrentContextFlowsToUserCreatedThread()
{
TestExecutionContext threadContext = null;
Thread thread = new Thread(() =>
{
threadContext = TestExecutionContext.CurrentContext;
});
thread.Start();
thread.Join();
Assert.That(threadContext, Is.Not.Null.And.SameAs(TestExecutionContext.CurrentContext));
}
#endregion
#region CurrentTest
[Test]
public void FixtureSetUpCanAccessFixtureName()
{
Assert.That(_fixtureContext.CurrentTest.Name, Is.EqualTo("TestExecutionContextTests"));
}
[Test]
public void FixtureSetUpCanAccessFixtureFullName()
{
Assert.That(_fixtureContext.CurrentTest.FullName,
Is.EqualTo("NUnit.Framework.Internal.TestExecutionContextTests"));
}
[Test]
public void FixtureSetUpHasNullMethodName()
{
Assert.That(_fixtureContext.CurrentTest.MethodName, Is.Null);
}
[Test]
public void FixtureSetUpCanAccessFixtureId()
{
Assert.That(_fixtureContext.CurrentTest.Id, Is.Not.Null.And.Not.Empty);
}
[Test]
public void FixtureSetUpCanAccessFixtureProperties()
{
Assert.That(_fixtureContext.CurrentTest.Properties.Get("Question"), Is.EqualTo("Why?"));
}
[Test]
public void SetUpCanAccessTestName()
{
Assert.That(_setupContext.CurrentTest.Name, Is.EqualTo("SetUpCanAccessTestName"));
}
[Test]
public void SetUpCanAccessTestFullName()
{
Assert.That(_setupContext.CurrentTest.FullName,
Is.EqualTo("NUnit.Framework.Internal.TestExecutionContextTests.SetUpCanAccessTestFullName"));
}
[Test]
public void SetUpCanAccessTestMethodName()
{
Assert.That(_setupContext.CurrentTest.MethodName,
Is.EqualTo("SetUpCanAccessTestMethodName"));
}
[Test]
public void SetUpCanAccessTestId()
{
Assert.That(_setupContext.CurrentTest.Id, Is.Not.Null.And.Not.Empty);
}
[Test]
[Property("Answer", 42)]
public void SetUpCanAccessTestProperties()
{
Assert.That(_setupContext.CurrentTest.Properties.Get("Answer"), Is.EqualTo(42));
}
[Test]
public void TestCanAccessItsOwnName()
{
Assert.That(TestExecutionContext.CurrentContext.CurrentTest.Name, Is.EqualTo("TestCanAccessItsOwnName"));
}
[Test]
public void TestCanAccessItsOwnFullName()
{
Assert.That(TestExecutionContext.CurrentContext.CurrentTest.FullName,
Is.EqualTo("NUnit.Framework.Internal.TestExecutionContextTests.TestCanAccessItsOwnFullName"));
}
[Test]
public void TestCanAccessItsOwnMethodName()
{
Assert.That(TestExecutionContext.CurrentContext.CurrentTest.MethodName,
Is.EqualTo("TestCanAccessItsOwnMethodName"));
}
[Test]
public void TestCanAccessItsOwnId()
{
Assert.That(TestExecutionContext.CurrentContext.CurrentTest.Id, Is.Not.Null.And.Not.Empty);
}
[Test]
[Property("Answer", 42)]
public void TestCanAccessItsOwnProperties()
{
Assert.That(TestExecutionContext.CurrentContext.CurrentTest.Properties.Get("Answer"), Is.EqualTo(42));
}
[TestCase(123, "abc")]
public void TestCanAccessItsOwnArguments(int i, string s)
{
Assert.That(TestExecutionContext.CurrentContext.CurrentTest.Arguments, Is.EqualTo(new object[] {123, "abc"}));
}
[Test]
public async Task AsyncTestCanAccessItsOwnName()
{
Assert.That(TestExecutionContext.CurrentContext.CurrentTest.Name, Is.EqualTo("AsyncTestCanAccessItsOwnName"));
await YieldAsync();
Assert.That(TestExecutionContext.CurrentContext.CurrentTest.Name, Is.EqualTo("AsyncTestCanAccessItsOwnName"));
}
[Test]
public async Task AsyncTestCanAccessItsOwnFullName()
{
Assert.That(TestExecutionContext.CurrentContext.CurrentTest.FullName,
Is.EqualTo("NUnit.Framework.Internal.TestExecutionContextTests.AsyncTestCanAccessItsOwnFullName"));
await YieldAsync();
Assert.That(TestExecutionContext.CurrentContext.CurrentTest.FullName,
Is.EqualTo("NUnit.Framework.Internal.TestExecutionContextTests.AsyncTestCanAccessItsOwnFullName"));
}
[Test]
public async Task AsyncTestCanAccessItsOwnMethodName()
{
Assert.That(TestExecutionContext.CurrentContext.CurrentTest.MethodName,
Is.EqualTo("AsyncTestCanAccessItsOwnMethodName"));
await YieldAsync();
Assert.That(TestExecutionContext.CurrentContext.CurrentTest.MethodName,
Is.EqualTo("AsyncTestCanAccessItsOwnMethodName"));
}
[Test]
public async Task AsyncTestCanAccessItsOwnId()
{
Assert.That(TestExecutionContext.CurrentContext.CurrentTest.Id, Is.Not.Null.And.Not.Empty);
await YieldAsync();
Assert.That(TestExecutionContext.CurrentContext.CurrentTest.Id, Is.Not.Null.And.Not.Empty);
}
[Test]
[Property("Answer", 42)]
public async Task AsyncTestCanAccessItsOwnProperties()
{
Assert.That(TestExecutionContext.CurrentContext.CurrentTest.Properties.Get("Answer"), Is.EqualTo(42));
await YieldAsync();
Assert.That(TestExecutionContext.CurrentContext.CurrentTest.Properties.Get("Answer"), Is.EqualTo(42));
}
[TestCase(123, "abc")]
public async Task AsyncTestCanAccessItsOwnArguments(int i, string s)
{
Assert.That(TestExecutionContext.CurrentContext.CurrentTest.Arguments, Is.EqualTo(new object[] {123, "abc"}));
await YieldAsync();
Assert.That(TestExecutionContext.CurrentContext.CurrentTest.Arguments, Is.EqualTo(new object[] {123, "abc"}));
}
[Test]
public void TestHasWorkerWhenParallel()
{
var worker = TestExecutionContext.CurrentContext.TestWorker;
var isRunningUnderTestWorker = TestExecutionContext.CurrentContext.Dispatcher is ParallelWorkItemDispatcher;
Assert.That(worker != null || !isRunningUnderTestWorker);
}
#endregion
#region CurrentResult
[Test]
public void CanAccessResultName()
{
Assert.That(_fixtureContext.CurrentResult.Name, Is.EqualTo("TestExecutionContextTests"));
Assert.That(_setupContext.CurrentResult.Name, Is.EqualTo("CanAccessResultName"));
Assert.That(TestExecutionContext.CurrentContext.CurrentResult.Name, Is.EqualTo("CanAccessResultName"));
}
[Test]
public void CanAccessResultFullName()
{
Assert.That(_fixtureContext.CurrentResult.FullName, Is.EqualTo("NUnit.Framework.Internal.TestExecutionContextTests"));
Assert.That(_setupContext.CurrentResult.FullName,
Is.EqualTo("NUnit.Framework.Internal.TestExecutionContextTests.CanAccessResultFullName"));
Assert.That(TestExecutionContext.CurrentContext.CurrentResult.FullName,
Is.EqualTo("NUnit.Framework.Internal.TestExecutionContextTests.CanAccessResultFullName"));
}
[Test]
public void CanAccessResultTest()
{
Assert.That(_fixtureContext.CurrentResult.Test, Is.SameAs(_fixtureContext.CurrentTest));
Assert.That(_setupContext.CurrentResult.Test, Is.SameAs(_setupContext.CurrentTest));
Assert.That(TestExecutionContext.CurrentContext.CurrentResult.Test, Is.SameAs(TestExecutionContext.CurrentContext.CurrentTest));
}
[Test]
public void CanAccessResultState()
{
// This is copied in setup because it can change if any test fails
Assert.That(_fixtureResult, Is.EqualTo(ResultState.Success));
Assert.That(_setupContext.CurrentResult.ResultState, Is.EqualTo(ResultState.Inconclusive));
Assert.That(TestExecutionContext.CurrentContext.CurrentResult.ResultState, Is.EqualTo(ResultState.Inconclusive));
}
[Test]
public async Task CanAccessResultName_Async()
{
Assert.That(TestExecutionContext.CurrentContext.CurrentResult.Name, Is.EqualTo("CanAccessResultName_Async"));
await YieldAsync();
Assert.That(TestExecutionContext.CurrentContext.CurrentResult.Name, Is.EqualTo("CanAccessResultName_Async"));
}
[Test]
public async Task CanAccessResultFullName_Async()
{
Assert.That(TestExecutionContext.CurrentContext.CurrentResult.FullName,
Is.EqualTo("NUnit.Framework.Internal.TestExecutionContextTests.CanAccessResultFullName_Async"));
await YieldAsync();
Assert.That(TestExecutionContext.CurrentContext.CurrentResult.FullName,
Is.EqualTo("NUnit.Framework.Internal.TestExecutionContextTests.CanAccessResultFullName_Async"));
}
[Test]
public async Task CanAccessResultTest_Async()
{
Assert.That(TestExecutionContext.CurrentContext.CurrentResult.Test,
Is.SameAs(TestExecutionContext.CurrentContext.CurrentTest));
await YieldAsync();
Assert.That(TestExecutionContext.CurrentContext.CurrentResult.Test,
Is.SameAs(TestExecutionContext.CurrentContext.CurrentTest));
}
[Test]
public async Task CanAccessResultState_Async()
{
Assert.That(TestExecutionContext.CurrentContext.CurrentResult.ResultState, Is.EqualTo(ResultState.Inconclusive));
await YieldAsync();
Assert.That(TestExecutionContext.CurrentContext.CurrentResult.ResultState, Is.EqualTo(ResultState.Inconclusive));
}
#endregion
#region StartTime
[Test]
public void CanAccessStartTime()
{
Assert.That(_fixtureContext.StartTime, Is.GreaterThan(DateTime.MinValue).And.LessThanOrEqualTo(_fixtureCreateTime));
Assert.That(_setupContext.StartTime, Is.GreaterThanOrEqualTo(_fixtureContext.StartTime));
Assert.That(TestExecutionContext.CurrentContext.StartTime, Is.GreaterThanOrEqualTo(_setupContext.StartTime));
}
[Test]
public async Task CanAccessStartTime_Async()
{
var startTime = TestExecutionContext.CurrentContext.StartTime;
Assert.That(startTime, Is.GreaterThanOrEqualTo(_setupContext.StartTime));
await YieldAsync();
Assert.That(TestExecutionContext.CurrentContext.StartTime, Is.EqualTo(startTime));
}
#endregion
#region StartTicks
[Test]
public void CanAccessStartTicks()
{
Assert.That(_fixtureContext.StartTicks, Is.LessThanOrEqualTo(_fixtureCreateTicks));
Assert.That(_setupContext.StartTicks, Is.GreaterThanOrEqualTo(_fixtureContext.StartTicks));
Assert.That(TestExecutionContext.CurrentContext.StartTicks, Is.GreaterThanOrEqualTo(_setupContext.StartTicks));
}
[Test]
public async Task AsyncTestCanAccessStartTicks()
{
var startTicks = TestExecutionContext.CurrentContext.StartTicks;
Assert.That(startTicks, Is.GreaterThanOrEqualTo(_setupContext.StartTicks));
await YieldAsync();
Assert.That(TestExecutionContext.CurrentContext.StartTicks, Is.EqualTo(startTicks));
}
#endregion
#region OutWriter
[Test]
public void CanAccessOutWriter()
{
Assert.That(_fixtureContext.OutWriter, Is.Not.Null);
Assert.That(_setupContext.OutWriter, Is.Not.Null);
Assert.That(TestExecutionContext.CurrentContext.OutWriter, Is.SameAs(_setupContext.OutWriter));
}
[Test]
public async Task AsyncTestCanAccessOutWriter()
{
var outWriter = TestExecutionContext.CurrentContext.OutWriter;
Assert.That(outWriter, Is.SameAs(_setupContext.OutWriter));
await YieldAsync();
Assert.That(TestExecutionContext.CurrentContext.OutWriter, Is.SameAs(outWriter));
}
#endregion
#region TestObject
[Test]
public void CanAccessTestObject()
{
Assert.That(_fixtureContext.TestObject, Is.Not.Null.And.TypeOf(GetType()));
Assert.That(_setupContext.TestObject, Is.SameAs(_fixtureContext.TestObject));
Assert.That(TestExecutionContext.CurrentContext.TestObject, Is.SameAs(_setupContext.TestObject));
}
[Test]
public async Task CanAccessTestObject_Async()
{
var testObject = TestExecutionContext.CurrentContext.TestObject;
Assert.That(testObject, Is.SameAs(_setupContext.TestObject));
await YieldAsync();
Assert.That(TestExecutionContext.CurrentContext.TestObject, Is.SameAs(testObject));
}
#endregion
#region StopOnError
[Test]
public void CanAccessStopOnError()
{
Assert.That(_setupContext.StopOnError, Is.EqualTo(_fixtureContext.StopOnError));
Assert.That(TestExecutionContext.CurrentContext.StopOnError, Is.EqualTo(_setupContext.StopOnError));
}
[Test]
public async Task CanAccessStopOnError_Async()
{
var stop = TestExecutionContext.CurrentContext.StopOnError;
Assert.That(stop, Is.EqualTo(_setupContext.StopOnError));
await YieldAsync();
Assert.That(TestExecutionContext.CurrentContext.StopOnError, Is.EqualTo(stop));
}
#endregion
#region Listener
[Test]
public void CanAccessListener()
{
Assert.That(_fixtureContext.Listener, Is.Not.Null);
Assert.That(_setupContext.Listener, Is.SameAs(_fixtureContext.Listener));
Assert.That(TestExecutionContext.CurrentContext.Listener, Is.SameAs(_setupContext.Listener));
}
[Test]
public async Task CanAccessListener_Async()
{
var listener = TestExecutionContext.CurrentContext.Listener;
Assert.That(listener, Is.SameAs(_setupContext.Listener));
await YieldAsync();
Assert.That(TestExecutionContext.CurrentContext.Listener, Is.SameAs(listener));
}
#endregion
#region Dispatcher
[Test]
public void CanAccessDispatcher()
{
Assert.That(_fixtureContext.RandomGenerator, Is.Not.Null);
Assert.That(_setupContext.Dispatcher, Is.SameAs(_fixtureContext.Dispatcher));
Assert.That(TestExecutionContext.CurrentContext.Dispatcher, Is.SameAs(_setupContext.Dispatcher));
}
[Test]
public async Task CanAccessDispatcher_Async()
{
var dispatcher = TestExecutionContext.CurrentContext.Dispatcher;
Assert.That(dispatcher, Is.SameAs(_setupContext.Dispatcher));
await YieldAsync();
Assert.That(TestExecutionContext.CurrentContext.Dispatcher, Is.SameAs(dispatcher));
}
#endregion
#region ParallelScope
[Test]
public void CanAccessParallelScope()
{
var scope = _fixtureContext.ParallelScope;
Assert.That(_setupContext.ParallelScope, Is.EqualTo(scope));
Assert.That(TestExecutionContext.CurrentContext.ParallelScope, Is.EqualTo(scope));
}
[Test]
public async Task CanAccessParallelScope_Async()
{
var scope = TestExecutionContext.CurrentContext.ParallelScope;
Assert.That(scope, Is.EqualTo(_setupContext.ParallelScope));
await YieldAsync();
Assert.That(TestExecutionContext.CurrentContext.ParallelScope, Is.EqualTo(scope));
}
#endregion
#region TestWorker
[Test]
public void CanAccessTestWorker()
{
if (TestExecutionContext.CurrentContext.Dispatcher is ParallelWorkItemDispatcher)
{
Assert.That(_fixtureContext.TestWorker, Is.Not.Null);
Assert.That(_setupContext.TestWorker, Is.SameAs(_fixtureContext.TestWorker));
Assert.That(TestExecutionContext.CurrentContext.TestWorker, Is.SameAs(_setupContext.TestWorker));
}
}
[Test]
public async Task CanAccessTestWorker_Async()
{
var worker = TestExecutionContext.CurrentContext.TestWorker;
Assert.That(worker, Is.SameAs(_setupContext.TestWorker));
await YieldAsync();
Assert.That(TestExecutionContext.CurrentContext.TestWorker, Is.SameAs(worker));
}
#endregion
#region RandomGenerator
[Test]
public void CanAccessRandomGenerator()
{
Assert.That(_fixtureContext.RandomGenerator, Is.Not.Null);
Assert.That(_setupContext.RandomGenerator, Is.Not.Null);
Assert.That(TestExecutionContext.CurrentContext.RandomGenerator, Is.SameAs(_setupContext.RandomGenerator));
}
[Test]
public async Task CanAccessRandomGenerator_Async()
{
var random = TestExecutionContext.CurrentContext.RandomGenerator;
Assert.That(random, Is.SameAs(_setupContext.RandomGenerator));
await YieldAsync();
Assert.That(TestExecutionContext.CurrentContext.RandomGenerator, Is.SameAs(random));
}
#endregion
#region AssertCount
[Test]
public void CanAccessAssertCount()
{
Assert.That(_fixtureContext.AssertCount, Is.EqualTo(0));
Assert.That(_setupContext.AssertCount, Is.EqualTo(1));
Assert.That(TestExecutionContext.CurrentContext.AssertCount, Is.EqualTo(2));
Assert.That(2 + 2, Is.EqualTo(4));
Assert.That(TestExecutionContext.CurrentContext.AssertCount, Is.EqualTo(4));
}
[Test]
public async Task CanAccessAssertCount_Async()
{
Assert.That(2 + 2, Is.EqualTo(4));
Assert.That(TestExecutionContext.CurrentContext.AssertCount, Is.EqualTo(1));
await YieldAsync();
Assert.That(TestExecutionContext.CurrentContext.AssertCount, Is.EqualTo(2));
Assert.That(TestExecutionContext.CurrentContext.AssertCount, Is.EqualTo(3));
}
#endregion
#region MultipleAssertLevel
[Test]
public void CanAccessMultipleAssertLevel()
{
Assert.That(_fixtureContext.MultipleAssertLevel, Is.EqualTo(0));
Assert.That(_setupContext.MultipleAssertLevel, Is.EqualTo(0));
Assert.That(TestExecutionContext.CurrentContext.MultipleAssertLevel, Is.EqualTo(0));
Assert.Multiple(() =>
{
Assert.That(TestExecutionContext.CurrentContext.MultipleAssertLevel, Is.EqualTo(1));
});
}
[Test]
public async Task CanAccessMultipleAssertLevel_Async()
{
Assert.That(TestExecutionContext.CurrentContext.MultipleAssertLevel, Is.EqualTo(0));
await YieldAsync();
Assert.That(TestExecutionContext.CurrentContext.MultipleAssertLevel, Is.EqualTo(0));
Assert.Multiple(() =>
{
Assert.That(TestExecutionContext.CurrentContext.MultipleAssertLevel, Is.EqualTo(1));
});
}
#endregion
#region TestCaseTimeout
[Test]
public void CanAccessTestCaseTimeout()
{
var timeout = _fixtureContext.TestCaseTimeout;
Assert.That(_setupContext.TestCaseTimeout, Is.EqualTo(timeout));
Assert.That(TestExecutionContext.CurrentContext.TestCaseTimeout, Is.EqualTo(timeout));
}
[Test]
public async Task CanAccessTestCaseTimeout_Async()
{
var timeout = TestExecutionContext.CurrentContext.TestCaseTimeout;
Assert.That(timeout, Is.EqualTo(_setupContext.TestCaseTimeout));
await YieldAsync();
Assert.That(TestExecutionContext.CurrentContext.TestCaseTimeout, Is.EqualTo(timeout));
}
#endregion
#region UpstreamActions
[Test]
public void CanAccessUpstreamActions()
{
var actions = _fixtureContext.UpstreamActions;
Assert.That(_setupContext.UpstreamActions, Is.EqualTo(actions));
Assert.That(TestExecutionContext.CurrentContext.UpstreamActions, Is.EqualTo(actions));
}
[Test]
public async Task CanAccessUpstreamAcxtions_Async()
{
var actions = TestExecutionContext.CurrentContext.UpstreamActions;
Assert.That(actions, Is.SameAs(_setupContext.UpstreamActions));
await YieldAsync();
Assert.That(TestExecutionContext.CurrentContext.UpstreamActions, Is.SameAs(actions));
}
#endregion
#region CurrentCulture and CurrentUICulture
[Test]
public void CanAccessCurrentCulture()
{
Assert.That(_fixtureContext.CurrentCulture, Is.EqualTo(CultureInfo.CurrentCulture));
Assert.That(_setupContext.CurrentCulture, Is.EqualTo(CultureInfo.CurrentCulture));
Assert.That(TestExecutionContext.CurrentContext.CurrentCulture, Is.EqualTo(CultureInfo.CurrentCulture));
}
[Test]
public void CanAccessCurrentUICulture()
{
Assert.That(_fixtureContext.CurrentUICulture, Is.EqualTo(CultureInfo.CurrentUICulture));
Assert.That(_setupContext.CurrentUICulture, Is.EqualTo(CultureInfo.CurrentUICulture));
Assert.That(TestExecutionContext.CurrentContext.CurrentUICulture, Is.EqualTo(CultureInfo.CurrentUICulture));
}
[Test]
public async Task CanAccessCurrentCulture_Async()
{
Assert.That(TestExecutionContext.CurrentContext.CurrentCulture, Is.EqualTo(CultureInfo.CurrentCulture));
await YieldAsync();
Assert.That(TestExecutionContext.CurrentContext.CurrentCulture, Is.EqualTo(CultureInfo.CurrentCulture));
}
[Test]
public async Task CanAccessCurrentUICulture_Async()
{
Assert.That(TestExecutionContext.CurrentContext.CurrentUICulture, Is.EqualTo(CultureInfo.CurrentUICulture));
await YieldAsync();
Assert.That(TestExecutionContext.CurrentContext.CurrentUICulture, Is.EqualTo(CultureInfo.CurrentUICulture));
}
[Test]
public void SetAndRestoreCurrentCulture()
{
var context = new TestExecutionContext(_setupContext);
try
{
CultureInfo otherCulture =
new CultureInfo(originalCulture.Name == "fr-FR" ? "en-GB" : "fr-FR");
context.CurrentCulture = otherCulture;
Assert.AreEqual(otherCulture, CultureInfo.CurrentCulture, "Culture was not set");
Assert.AreEqual(otherCulture, context.CurrentCulture, "Culture not in new context");
Assert.AreEqual(_setupContext.CurrentCulture, originalCulture, "Original context should not change");
}
finally
{
_setupContext.EstablishExecutionEnvironment();
}
Assert.AreEqual(CultureInfo.CurrentCulture, originalCulture, "Culture was not restored");
Assert.AreEqual(_setupContext.CurrentCulture, originalCulture, "Culture not in final context");
}
[Test]
public void SetAndRestoreCurrentUICulture()
{
var context = new TestExecutionContext(_setupContext);
try
{
CultureInfo otherCulture =
new CultureInfo(originalUICulture.Name == "fr-FR" ? "en-GB" : "fr-FR");
context.CurrentUICulture = otherCulture;
Assert.AreEqual(otherCulture, CultureInfo.CurrentUICulture, "UICulture was not set");
Assert.AreEqual(otherCulture, context.CurrentUICulture, "UICulture not in new context");
Assert.AreEqual(_setupContext.CurrentUICulture, originalUICulture, "Original context should not change");
}
finally
{
_setupContext.EstablishExecutionEnvironment();
}
Assert.AreEqual(CultureInfo.CurrentUICulture, originalUICulture, "UICulture was not restored");
Assert.AreEqual(_setupContext.CurrentUICulture, originalUICulture, "UICulture not in final context");
}
#endregion
#region CurrentPrincipal
[Test]
public void CanAccessCurrentPrincipal()
{
var expectedInstance = Thread.CurrentPrincipal;
Assert.That(_fixtureContext.CurrentPrincipal, Is.SameAs(expectedInstance), "Fixture");
Assert.That(_setupContext.CurrentPrincipal, Is.SameAs(expectedInstance), "SetUp");
Assert.That(TestExecutionContext.CurrentContext.CurrentPrincipal, Is.SameAs(expectedInstance), "Test");
}
[Test]
public async Task CanAccessCurrentPrincipal_Async()
{
var expectedInstance = Thread.CurrentPrincipal;
Assert.That(TestExecutionContext.CurrentContext.CurrentPrincipal, Is.SameAs(expectedInstance), "Before yield");
await YieldAsync();
Assert.That(TestExecutionContext.CurrentContext.CurrentPrincipal, Is.SameAs(expectedInstance), "After yield");
}
[Test]
public void SetAndRestoreCurrentPrincipal()
{
var context = new TestExecutionContext(_setupContext);
try
{
GenericIdentity identity = new GenericIdentity("foo");
context.CurrentPrincipal = new GenericPrincipal(identity, new string[0]);
Assert.AreEqual("foo", Thread.CurrentPrincipal.Identity.Name, "Principal was not set");
Assert.AreEqual("foo", context.CurrentPrincipal.Identity.Name, "Principal not in new context");
Assert.AreEqual(_setupContext.CurrentPrincipal, originalPrincipal, "Original context should not change");
}
finally
{
_setupContext.EstablishExecutionEnvironment();
}
Assert.AreEqual(Thread.CurrentPrincipal, originalPrincipal, "Principal was not restored");
Assert.AreEqual(_setupContext.CurrentPrincipal, originalPrincipal, "Principal not in final context");
}
#endregion
#region ValueFormatter
[Test]
public void SetAndRestoreValueFormatter()
{
var context = new TestExecutionContext(_setupContext);
var originalFormatter = context.CurrentValueFormatter;
try
{
ValueFormatter f = val => "dummy";
context.AddFormatter(next => f);
Assert.That(context.CurrentValueFormatter, Is.EqualTo(f));
context.EstablishExecutionEnvironment();
Assert.That(MsgUtils.FormatValue(123), Is.EqualTo("dummy"));
}
finally
{
_setupContext.EstablishExecutionEnvironment();
}
Assert.That(TestExecutionContext.CurrentContext.CurrentValueFormatter, Is.EqualTo(originalFormatter));
Assert.That(MsgUtils.FormatValue(123), Is.EqualTo("123"));
}
#endregion
#region SingleThreaded
[Test]
public void SingleThreadedDefaultsToFalse()
{
Assert.False(new TestExecutionContext().IsSingleThreaded);
}
[Test]
public void SingleThreadedIsInherited()
{
var parent = new TestExecutionContext();
parent.IsSingleThreaded = true;
Assert.True(new TestExecutionContext(parent).IsSingleThreaded);
}
#endregion
#region ExecutionStatus
[Test]
public void ExecutionStatusIsPushedToHigherContext()
{
var topContext = new TestExecutionContext();
var bottomContext = new TestExecutionContext(new TestExecutionContext(new TestExecutionContext(topContext)));
bottomContext.ExecutionStatus = TestExecutionStatus.StopRequested;
Assert.That(topContext.ExecutionStatus, Is.EqualTo(TestExecutionStatus.StopRequested));
}
[Test]
public void ExecutionStatusIsPulledFromHigherContext()
{
var topContext = new TestExecutionContext();
var bottomContext = new TestExecutionContext(new TestExecutionContext(new TestExecutionContext(topContext)));
topContext.ExecutionStatus = TestExecutionStatus.AbortRequested;
Assert.That(bottomContext.ExecutionStatus, Is.EqualTo(TestExecutionStatus.AbortRequested));
}
[Test]
public void ExecutionStatusIsPromulgatedAcrossBranches()
{
var topContext = new TestExecutionContext();
var leftContext = new TestExecutionContext(new TestExecutionContext(new TestExecutionContext(topContext)));
var rightContext = new TestExecutionContext(new TestExecutionContext(new TestExecutionContext(topContext)));
leftContext.ExecutionStatus = TestExecutionStatus.StopRequested;
Assert.That(rightContext.ExecutionStatus, Is.EqualTo(TestExecutionStatus.StopRequested));
}
#endregion
#region Cross-domain Tests
#if NETFRAMEWORK
[Test, Platform(Exclude="Mono", Reason="Intermittent failures")]
public void CanCreateObjectInAppDomain()
{
AppDomain domain = AppDomain.CreateDomain(
"TestCanCreateAppDomain",
AppDomain.CurrentDomain.Evidence,
AssemblyHelper.GetDirectoryName(Assembly.GetExecutingAssembly()),
null,
false);
var obj = domain.CreateInstanceAndUnwrap("nunit.framework.tests", "NUnit.Framework.Internal.TestExecutionContextTests+TestClass");
Assert.NotNull(obj);
}
[Serializable]
private class TestClass
{
}
#endif
#endregion
#region CurrentRepeatCount Tests
[Test]
public void CanAccessCurrentRepeatCount()
{
Assert.That(_fixtureContext.CurrentRepeatCount, Is.EqualTo(0), "expected value to default to zero");
_fixtureContext.CurrentRepeatCount++;
Assert.That(_fixtureContext.CurrentRepeatCount, Is.EqualTo(1), "expected value to be able to be incremented from the TestExecutionContext");
}
#endregion
#region Helper Methods
private async Task YieldAsync()
{
await Task.Yield();
}
private Task<T[]> WhenAllAsync<T>(params Task<T>[] tasks)
{
return Task.WhenAll(tasks);
}
private async Task<TestExecutionContext> YieldAndReturnContext()
{
await YieldAsync();
return TestExecutionContext.CurrentContext;
}
#endregion
}
#if NETFRAMEWORK
[TestFixture, Platform(Exclude="Mono", Reason="Intermittent failures")]
public class TextExecutionContextInAppDomain
{
private RunsInAppDomain _runsInAppDomain;
[SetUp]
public void SetUp()
{
var domain = AppDomain.CreateDomain("TestDomain", null, AppDomain.CurrentDomain.BaseDirectory, AppDomain.CurrentDomain.RelativeSearchPath, false);
_runsInAppDomain = domain.CreateInstanceAndUnwrap(Assembly.GetExecutingAssembly().FullName,
"NUnit.Framework.Internal.RunsInAppDomain") as RunsInAppDomain;
Assert.That(_runsInAppDomain, Is.Not.Null);
}
[Test]
[Description("Issue 71 - NUnit swallows console output from AppDomains created within tests")]
public void CanWriteToConsoleInAppDomain()
{
_runsInAppDomain.WriteToConsole();
}
[Test]
[Description("Issue 210 - TestContext.WriteLine in an AppDomain causes an error")]
public void CanWriteToTestContextInAppDomain()
{
_runsInAppDomain.WriteToTestContext();
}
}
internal class RunsInAppDomain : MarshalByRefObject
{
public void WriteToConsole()
{
Console.WriteLine("RunsInAppDomain.WriteToConsole");
}
public void WriteToTestContext()
{
TestContext.WriteLine("RunsInAppDomain.WriteToTestContext");
}
}
#endif
}
| |
using UnityEngine;
using UnityEngine.UI.Windows;
namespace UnityEngine.UI.Windows.Animations {
[TransitionCamera]
public class WindowTransitionBasic : TransitionBase {
[System.Serializable]
public class Parameters : TransitionBase.ParametersVideoBase {
public Parameters(TransitionBase.ParametersBase baseDefaults) : base(baseDefaults) {}
[System.Serializable]
public class State {
public float to;
public State(State source) {
this.to = source.to;
}
}
public State resetState;
public State inState;
public State outState;
public override void Setup(TransitionBase.ParametersBase defaults) {
var param = defaults as Parameters;
if (param == null) return;
// Place params installation here
this.inState = new State(param.inState);
this.outState = new State(param.outState);
this.resetState = new State(param.resetState);
this.material = param.material;
}
public float GetIn() {
return this.inState.to;
}
public float GetOut() {
return this.outState.to;
}
public float GetReset() {
return this.resetState.to;
}
public float GetResult(bool forward) {
if (forward == true) {
return this.inState.to;
}
return this.outState.to;
}
}
public Parameters defaultInputParams;
public Material material {
get {
return this.defaultInputParams.material;
}
}
public bool grabEveryFrame = false;
public CameraClearFlags clearFlags = CameraClearFlags.Depth;
private Texture2D clearScreen;
private WindowBase currentWindow;
private WindowBase prevWindow;
public override TransitionBase.ParametersBase GetDefaultInputParameters() {
return this.defaultInputParams;
}
public override void OnInit() {
this.clearScreen = new Texture2D(Screen.width, Screen.height, TextureFormat.ARGB32, false);
}
public override void SetupCamera(Camera camera) {
camera.clearFlags = this.clearFlags;
}
public override bool IsValid(WindowBase window) {
return this.currentWindow == window || this.prevWindow == window;
}
public override void OnPlay(WindowBase window, ME.Tweener.MultiTag tag, TransitionInputParameters parameters, WindowComponentBase root, bool forward, System.Action callback) {
var param = this.GetParams<Parameters>(parameters);
if (param == null) {
if (callback != null) callback();
return;
}
this.currentWindow = window;
this.prevWindow = WindowSystem.GetPreviousWindow(window, (item) => item.window != null && item.window.GetState() == WindowObjectState.Shown);
if (this.prevWindow == null) {
window.transition.SaveToCache(this.clearScreen, () => {
this.material.SetTexture("_ClearScreen", this.clearScreen);
}, this.grabEveryFrame);
} else {
if (forward == true) {
// Take screenshot from current view
this.prevWindow.transition.SaveToCache(this.clearScreen, () => {
this.material.SetTexture("_ClearScreen", this.clearScreen);
}, this.grabEveryFrame);
} else {
// Take screenshot from previous view
this.prevWindow.transition.SaveToCache(this.clearScreen, () => {
this.material.SetTexture("_ClearScreen", this.clearScreen);
}, this.grabEveryFrame);
}
}
var duration = this.GetDuration(parameters, forward);
var result = param.GetResult(forward);
TweenerGlobal.instance.removeTweens(tag);
TweenerGlobal.instance.addTween(this, duration, this.material.GetFloat("_Value"), result).onUpdate((obj, value) => {
this.material.SetFloat("_Value", value);
}).onComplete((obj) => { if (callback != null) callback(); }).onCancel((obj) => { if (callback != null) callback(); }).tag(tag);
}
public override void SetInState(TransitionInputParameters parameters, WindowBase window, WindowComponentBase root) {
var param = this.GetParams<Parameters>(parameters);
if (param == null) return;
this.material.SetFloat("_Value", param.GetIn());
}
public override void SetOutState(TransitionInputParameters parameters, WindowBase window, WindowComponentBase root) {
var param = this.GetParams<Parameters>(parameters);
if (param == null) return;
this.material.SetFloat("_Value", param.GetOut());
}
public override void SetResetState(TransitionInputParameters parameters, WindowBase window, WindowComponentBase root) {
var param = this.GetParams<Parameters>(parameters);
if (param == null) return;
this.material.SetFloat("_Value", param.GetReset());
}
public override void OnRenderTransition(WindowBase window, RenderTexture source, RenderTexture destination) {
if (this.currentWindow == window) {
Graphics.Blit(source, destination, this.material);
}
}
#if UNITY_EDITOR
[UnityEditor.MenuItem("Assets/Create/UI Windows/Transitions/Screen/Basic")]
public static void CreateInstance() {
ME.EditorUtilities.CreateAsset<WindowTransitionBasic>();
}
#endif
}
}
| |
/* ====================================================================
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 System;
using System.IO;
using NPOI.HSSF.UserModel;
using NPOI.OpenXmlFormats.Spreadsheet;
using NPOI.OpenXmlFormats.Vml;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using NPOI.XSSF;
using NPOI.XSSF.Model;
using NPOI.XSSF.Streaming;
using NPOI.XSSF.UserModel;
using NUnit.Framework;
using TestCases.SS.UserModel;
namespace TestCases.XSSF.UserModel
{
/**
* @author Yegor Kozlov
*/
[TestFixture]
public class TestXSSFComment : BaseTestCellComment
{
private static String TEST_RICHTEXTSTRING = "test richtextstring";
public TestXSSFComment()
: base(XSSFITestDataProvider.instance)
{
}
/**
* Test properties of a newly constructed comment
*/
[Test]
public void Constructor()
{
CommentsTable sheetComments = new CommentsTable();
Assert.IsNotNull(sheetComments.GetCTComments().commentList);
Assert.IsNotNull(sheetComments.GetCTComments().authors);
Assert.AreEqual(1, sheetComments.GetCTComments().authors.SizeOfAuthorArray());
Assert.AreEqual(1, sheetComments.GetNumberOfAuthors());
CT_Comment ctComment = sheetComments.NewComment(CellAddress.A1);
CT_Shape vmlShape = new CT_Shape();
XSSFComment comment = new XSSFComment(sheetComments, ctComment, vmlShape);
Assert.AreEqual(null, comment.String.String);
Assert.AreEqual(0, comment.Row);
Assert.AreEqual(0, comment.Column);
Assert.AreEqual("", comment.Author);
Assert.AreEqual(false, comment.Visible);
}
[Test]
public void GetSetCol()
{
CommentsTable sheetComments = new CommentsTable();
XSSFVMLDrawing vml = new XSSFVMLDrawing();
CT_Comment ctComment = sheetComments.NewComment(CellAddress.A1);
CT_Shape vmlShape = vml.newCommentShape();
XSSFComment comment = new XSSFComment(sheetComments, ctComment, vmlShape);
comment.Column = (1);
Assert.AreEqual(1, comment.Column);
Assert.AreEqual(1, new CellReference(ctComment.@ref).Col);
Assert.AreEqual(1, vmlShape.GetClientDataArray(0).GetColumnArray(0));
comment.Column = (5);
Assert.AreEqual(5, comment.Column);
Assert.AreEqual(5, new CellReference(ctComment.@ref).Col);
Assert.AreEqual(5, vmlShape.GetClientDataArray(0).GetColumnArray(0));
}
[Test]
public void GetSetRow()
{
CommentsTable sheetComments = new CommentsTable();
XSSFVMLDrawing vml = new XSSFVMLDrawing();
CT_Comment ctComment = sheetComments.NewComment(CellAddress.A1);
CT_Shape vmlShape = vml.newCommentShape();
XSSFComment comment = new XSSFComment(sheetComments, ctComment, vmlShape);
comment.Row = (1);
Assert.AreEqual(1, comment.Row);
Assert.AreEqual(1, new CellReference(ctComment.@ref).Row);
Assert.AreEqual(1, vmlShape.GetClientDataArray(0).GetRowArray(0));
comment.Row = (5);
Assert.AreEqual(5, comment.Row);
Assert.AreEqual(5, new CellReference(ctComment.@ref).Row);
Assert.AreEqual(5, vmlShape.GetClientDataArray(0).GetRowArray(0));
}
[Test]
public void SetString()
{
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sh = (XSSFSheet)wb.CreateSheet();
XSSFComment comment = (XSSFComment)sh.CreateDrawingPatriarch().CreateCellComment(new XSSFClientAnchor());
//passing HSSFRichTextString is incorrect
try
{
comment.String = (new HSSFRichTextString(TEST_RICHTEXTSTRING));
Assert.Fail("expected exception");
}
catch (ArgumentException e)
{
Assert.AreEqual("Only XSSFRichTextString argument is supported", e.Message);
}
//simple string argument
comment.SetString(TEST_RICHTEXTSTRING);
Assert.AreEqual(TEST_RICHTEXTSTRING, comment.String.String);
//if the text is already Set, it should be overridden, not Added twice!
comment.SetString(TEST_RICHTEXTSTRING);
CT_Comment ctComment = comment.GetCTComment();
// Assert.Fail("TODO test case incomplete!?");
//XmlObject[] obj = ctComment.selectPath(
// "declare namespace w='"+XSSFRelation.NS_SPREADSHEETML+"' .//w:text");
//Assert.AreEqual(1, obj.Length);
Assert.AreEqual(TEST_RICHTEXTSTRING, comment.String.String);
//sequential call of comment.String should return the same XSSFRichTextString object
Assert.AreSame(comment.String, comment.String);
XSSFRichTextString richText = new XSSFRichTextString(TEST_RICHTEXTSTRING);
XSSFFont font1 = (XSSFFont)wb.CreateFont();
font1.FontName = ("Tahoma");
font1.FontHeightInPoints = 8.5;
font1.IsItalic = true;
font1.Color = IndexedColors.BlueGrey.Index;
richText.ApplyFont(0, 5, font1);
//check the low-level stuff
comment.String = richText;
//obj = ctComment.selectPath(
// "declare namespace w='"+XSSFRelation.NS_SPREADSHEETML+"' .//w:text");
//Assert.AreEqual(1, obj.Length);
Assert.AreSame(comment.String, richText);
//check that the rich text is Set in the comment
CT_RPrElt rPr = richText.GetCTRst().GetRArray(0).rPr;
Assert.AreEqual(true, rPr.GetIArray(0).val);
Assert.AreEqual(8.5, rPr.GetSzArray(0).val);
Assert.AreEqual(IndexedColors.BlueGrey.Index, (short)rPr.GetColorArray(0).indexed);
Assert.AreEqual("Tahoma", rPr.GetRFontArray(0).val);
Assert.IsNotNull(XSSFTestDataSamples.WriteOutAndReadBack(wb));
}
[Test]
public void Author()
{
CommentsTable sheetComments = new CommentsTable();
CT_Comment ctComment = sheetComments.NewComment(CellAddress.A1);
Assert.AreEqual(1, sheetComments.GetNumberOfAuthors());
XSSFComment comment = new XSSFComment(sheetComments, ctComment, null);
Assert.AreEqual("", comment.Author);
comment.Author = ("Apache POI");
Assert.AreEqual("Apache POI", comment.Author);
Assert.AreEqual(2, sheetComments.GetNumberOfAuthors());
comment.Author = ("Apache POI");
Assert.AreEqual(2, sheetComments.GetNumberOfAuthors());
comment.Author = ("");
Assert.AreEqual("", comment.Author);
Assert.AreEqual(2, sheetComments.GetNumberOfAuthors());
}
[Test]
public void TestBug58175()
{
IWorkbook wb = new SXSSFWorkbook();
try
{
ISheet sheet = wb.CreateSheet();
IRow row = sheet.CreateRow(1);
ICell cell = row.CreateCell(3);
cell.SetCellValue("F4");
ICreationHelper factory = wb.GetCreationHelper();
// When the comment box is visible, have it show in a 1x3 space
IClientAnchor anchor = factory.CreateClientAnchor();
anchor.Col1 = (cell.ColumnIndex);
anchor.Col2 = (cell.ColumnIndex + 1);
anchor.Row1 = (row.RowNum);
anchor.Row2 = (row.RowNum + 3);
XSSFClientAnchor ca = (XSSFClientAnchor)anchor;
// create comments and vmlDrawing parts if they don't exist
CommentsTable comments = (((SXSSFWorkbook)wb).XssfWorkbook
.GetSheetAt(0) as XSSFSheet).GetCommentsTable(true);
XSSFVMLDrawing vml = (((SXSSFWorkbook)wb).XssfWorkbook
.GetSheetAt(0) as XSSFSheet).GetVMLDrawing(true);
CT_Shape vmlShape1 = vml.newCommentShape();
if (ca.IsSet())
{
String position = ca.Col1 + ", 0, " + ca.Row1
+ ", 0, " + ca.Col2 + ", 0, " + ca.Row2
+ ", 0";
vmlShape1.GetClientDataArray(0).SetAnchorArray(0, position);
}
// create the comment in two different ways and verify that there is no difference
XSSFComment shape1 = new XSSFComment(comments, comments.NewComment(CellAddress.A1), vmlShape1);
shape1.Column = (ca.Col1);
shape1.Row = (ca.Row1);
CT_Shape vmlShape2 = vml.newCommentShape();
if (ca.IsSet())
{
String position = ca.Col1 + ", 0, " + ca.Row1
+ ", 0, " + ca.Col2 + ", 0, " + ca.Row2
+ ", 0";
vmlShape2.GetClientDataArray(0).SetAnchorArray(0, position);
}
CellAddress ref1 = new CellAddress(ca.Row1, ca.Col1);
XSSFComment shape2 = new XSSFComment(comments, comments.NewComment(ref1), vmlShape2);
Assert.AreEqual(shape1.Author, shape2.Author);
Assert.AreEqual(shape1.ClientAnchor, shape2.ClientAnchor);
Assert.AreEqual(shape1.Column, shape2.Column);
Assert.AreEqual(shape1.Row, shape2.Row);
Assert.AreEqual(shape1.GetCTComment().ToString(), shape2.GetCTComment().ToString());
Assert.AreEqual(shape1.GetCTComment().@ref, shape2.GetCTComment().@ref);
/*CommentsTable table1 = shape1.CommentsTable;
CommentsTable table2 = shape2.CommentsTable;
Assert.AreEqual(table1.CTComments.toString(), table2.CTComments.toString());
Assert.AreEqual(table1.NumberOfComments, table2.NumberOfComments);
Assert.AreEqual(table1.Relations, table2.Relations);*/
Assert.AreEqual(vmlShape1.ToString().Replace("_x0000_s\\d+", "_x0000_s0000"),
vmlShape2.ToString().Replace("_x0000_s\\d+", "_x0000_s0000"),
"The vmlShapes should have equal content afterwards");
}
finally
{
wb.Close();
}
}
[Ignore("Used for manual testing with opening the resulting Workbook in Excel")]
[Test]
public void TestBug58175a()
{
IWorkbook wb = new SXSSFWorkbook();
try
{
ISheet sheet = wb.CreateSheet();
IRow row = sheet.CreateRow(1);
ICell cell = row.CreateCell(3);
cell.SetCellValue("F4");
IDrawing drawing = sheet.CreateDrawingPatriarch();
ICreationHelper factory = wb.GetCreationHelper();
// When the comment box is visible, have it show in a 1x3 space
IClientAnchor anchor = factory.CreateClientAnchor();
anchor.Col1 = (cell.ColumnIndex);
anchor.Col2 = (cell.ColumnIndex + 1);
anchor.Row1 = (row.RowNum);
anchor.Row2 = (row.RowNum + 3);
// Create the comment and set the text+author
IComment comment = drawing.CreateCellComment(anchor);
IRichTextString str = factory.CreateRichTextString("Hello, World!");
comment.String = (str);
comment.Author = ("Apache POI");
/* fixed the problem as well
* comment.setColumn(cell.ColumnIndex);
* comment.setRow(cell.RowIndex);
*/
// Assign the comment to the cell
cell.CellComment = (comment);
FileStream out1 = new FileStream("C:\\temp\\58175.xlsx", FileMode.CreateNew, FileAccess.ReadWrite);
try
{
wb.Write(out1);
}
finally
{
out1.Close();
}
}
finally
{
wb.Close();
}
}
[Test]
public void Bug57838DeleteRowsWthCommentsBug()
{
IWorkbook wb = XSSFTestDataSamples.OpenSampleWorkbook("57838.xlsx");
ISheet sheet = wb.GetSheetAt(0);
IComment comment1 = sheet.GetCellComment(new CellAddress(2, 1));
Assert.IsNotNull(comment1);
IComment comment2 = sheet.GetCellComment(new CellAddress(2, 2));
Assert.IsNotNull(comment2);
IRow row = sheet.GetRow(2);
Assert.IsNotNull(row);
sheet.RemoveRow(row); // Remove row from index 2
row = sheet.GetRow(2);
Assert.IsNull(row); // Row is null since we deleted it.
comment1 = sheet.GetCellComment(new CellAddress(2, 1));
Assert.IsNull(comment1); // comment should be null but will Assert.Fail due to bug
comment2 = sheet.GetCellComment(new CellAddress(2, 2));
Assert.IsNull(comment2); // comment should be null but will Assert.Fail due to bug
wb.Close();
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace Cheetah.WebApi.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlServerCe;
using System.Collections;
using System.Windows.Forms;
using DowUtils;
namespace Factotum{
public class EMeterModel : IEntity
{
public static event EventHandler<EntityChangedEventArgs> Changed;
protected virtual void OnChanged(Guid? ID)
{
// Copy to a temporary variable to be thread-safe.
EventHandler<EntityChangedEventArgs> temp = Changed;
if (temp != null)
temp(this, new EntityChangedEventArgs(ID));
}
// Mapped database columns
// Use Guid?s for Primary Keys and foreign keys (whether they're nullable or not).
// Use int?, decimal?, etc for numbers (whether they're nullable or not).
// Strings, images, etc, are reference types already
private Guid? MmlDBid;
private string MmlName;
private string MmlManfName;
private bool MmlIsLclChg;
private bool MmlUsedInOutage;
private bool MmlIsActive;
// Textbox limits
public static int MmlNameCharLimit = 50;
public static int MmlManfNameCharLimit = 50;
// Field-specific error message strings (normally just needed for textbox data)
private string MmlNameErrMsg;
private string MmlManfNameErrMsg;
// Form level validation message
private string MmlErrMsg;
//--------------------------------------------------------
// Field Properties
//--------------------------------------------------------
// Primary key accessor
public Guid? ID
{
get { return MmlDBid; }
}
public string MeterModelName
{
get { return MmlName; }
set { MmlName = Util.NullifyEmpty(value); }
}
public string MeterModelManfName
{
get { return MmlManfName; }
set { MmlManfName = Util.NullifyEmpty(value); }
}
public bool MeterModelIsLclChg
{
get { return MmlIsLclChg; }
set { MmlIsLclChg = value; }
}
public bool MeterModelUsedInOutage
{
get { return MmlUsedInOutage; }
set { MmlUsedInOutage = value; }
}
public bool MeterModelIsActive
{
get { return MmlIsActive; }
set { MmlIsActive = value; }
}
//-----------------------------------------------------------------
// Field Level Error Messages.
// Include one for every text column
// In cases where we need to ensure data consistency, we may need
// them for other types.
//-----------------------------------------------------------------
public string MeterModelNameErrMsg
{
get { return MmlNameErrMsg; }
}
public string MeterModelManfNameErrMsg
{
get { return MmlManfNameErrMsg; }
}
//--------------------------------------
// Form level Error Message
//--------------------------------------
public string MeterModelErrMsg
{
get { return MmlErrMsg; }
set { MmlErrMsg = Util.NullifyEmpty(value); }
}
//--------------------------------------
// Textbox Name Length Validation
//--------------------------------------
public bool MeterModelNameLengthOk(string s)
{
if (s == null) return true;
if (s.Length > MmlNameCharLimit)
{
MmlNameErrMsg = string.Format("Meter Model Names cannot exceed {0} characters", MmlNameCharLimit);
return false;
}
else
{
MmlNameErrMsg = null;
return true;
}
}
public bool MeterModelManfNameLengthOk(string s)
{
if (s == null) return true;
if (s.Length > MmlManfNameCharLimit)
{
MmlManfNameErrMsg = string.Format("Meter Model Manufacturer Names cannot exceed {0} characters", MmlManfNameCharLimit);
return false;
}
else
{
MmlManfNameErrMsg = null;
return true;
}
}
//--------------------------------------
// Field-Specific Validation
// sets and clears error messages
//--------------------------------------
public bool MeterModelNameValid(string name)
{
bool existingIsInactive;
if (!MeterModelNameLengthOk(name)) return false;
// KEEP, MODIFY OR REMOVE THIS AS REQUIRED
// YOU MAY NEED THE NAME TO BE UNIQUE FOR A SPECIFIC PARENT, ETC..
if (NameExists(name, MmlDBid, out existingIsInactive))
{
MmlNameErrMsg = existingIsInactive ?
"A Meter Model with that Name exists but its status has been set to inactive." :
"That Meter Model Name is already in use.";
return false;
}
MmlNameErrMsg = null;
return true;
}
public bool MeterModelManfNameValid(string value)
{
if (!MeterModelManfNameLengthOk(value)) return false;
MmlManfNameErrMsg = null;
return true;
}
//--------------------------------------
// Constructors
//--------------------------------------
// Default constructor. Field defaults must be set here.
// Any defaults set by the database will be overridden.
public EMeterModel()
{
this.MmlIsLclChg = false;
this.MmlUsedInOutage = true;
this.MmlIsActive = true;
}
// Constructor which loads itself from the supplied id.
// If the id is null, this gives the same result as using the default constructor.
public EMeterModel(Guid? id) : this()
{
Load(id);
}
//--------------------------------------
// Public Methods
//--------------------------------------
//----------------------------------------------------
// Load the object from the database given a Guid?
//----------------------------------------------------
public void Load(Guid? id)
{
if (id == null) return;
SqlCeCommand cmd = Globals.cnn.CreateCommand();
SqlCeDataReader dr;
cmd.CommandType = CommandType.Text;
cmd.CommandText =
@"Select
MmlDBid,
MmlName,
MmlManfName,
MmlIsLclChg,
MmlUsedInOutage,
MmlIsActive
from MeterModels
where MmlDBid = @p0";
cmd.Parameters.Add(new SqlCeParameter("@p0", id));
if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open();
dr = cmd.ExecuteReader();
// The query should return one record.
// If it doesn't return anything (no match) the object is not affected
if (dr.Read())
{
// For all nullable values, replace dbNull with null
MmlDBid = (Guid?)dr[0];
MmlName = (string)dr[1];
MmlManfName = (string)dr[2];
MmlIsLclChg = (bool)dr[3];
MmlUsedInOutage = (bool)dr[4];
MmlIsActive = (bool)dr[5];
}
dr.Close();
}
//--------------------------------------
// Save the current record if it's valid
//--------------------------------------
public Guid? Save()
{
if (!Valid())
{
// Note: We're returning null if we fail,
// so don't just assume you're going to get your id back
// and set your id to the result of this function call.
return null;
}
SqlCeCommand cmd = Globals.cnn.CreateCommand();
cmd.CommandType = CommandType.Text;
if (ID == null)
{
// we are inserting a new record
// If this is not a master db, set the local change flag to true.
if (!Globals.IsMasterDB) MmlIsLclChg = true;
// first ask the database for a new Guid
cmd.CommandText = "Select Newid()";
if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open();
MmlDBid = (Guid?)(cmd.ExecuteScalar());
// Replace any nulls with dbnull
cmd.Parameters.AddRange(new SqlCeParameter[] {
new SqlCeParameter("@p0", MmlDBid),
new SqlCeParameter("@p1", MmlName),
new SqlCeParameter("@p2", MmlManfName),
new SqlCeParameter("@p3", MmlIsLclChg),
new SqlCeParameter("@p4", MmlUsedInOutage),
new SqlCeParameter("@p5", MmlIsActive)
});
cmd.CommandText = @"Insert Into MeterModels (
MmlDBid,
MmlName,
MmlManfName,
MmlIsLclChg,
MmlUsedInOutage,
MmlIsActive
) values (@p0,@p1,@p2,@p3,@p4,@p5)";
if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open();
if (cmd.ExecuteNonQuery() != 1)
{
throw new Exception("Unable to insert Meter Models row");
}
}
else
{
// we are updating an existing record
// Replace any nulls with dbnull
cmd.Parameters.AddRange(new SqlCeParameter[] {
new SqlCeParameter("@p0", MmlDBid),
new SqlCeParameter("@p1", MmlName),
new SqlCeParameter("@p2", MmlManfName),
new SqlCeParameter("@p3", MmlIsLclChg),
new SqlCeParameter("@p4", MmlUsedInOutage),
new SqlCeParameter("@p5", MmlIsActive)});
cmd.CommandText =
@"Update MeterModels
set
MmlName = @p1,
MmlManfName = @p2,
MmlIsLclChg = @p3,
MmlUsedInOutage = @p4,
MmlIsActive = @p5
Where MmlDBid = @p0";
if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open();
if (cmd.ExecuteNonQuery() != 1)
{
throw new Exception("Unable to update meter models row");
}
}
OnChanged(ID);
return ID;
}
//--------------------------------------
// Validate the current record
//--------------------------------------
// Make this public so that the UI can check validation itself
// if it chooses to do so. This is also called by the Save function.
public bool Valid()
{
// First check each field to see if it's valid from the UI perspective
if (!MeterModelNameValid(MeterModelName)) return false;
if (!MeterModelManfNameValid(MeterModelManfName)) return false;
// Check form to make sure all required fields have been filled in
if (!RequiredFieldsFilled()) return false;
// Check for incorrect field interactions...
return true;
}
//--------------------------------------
// Delete the current record
//--------------------------------------
public bool Delete(bool promptUser)
{
// If the current object doesn't reference a database record, there's nothing to do.
if (MmlDBid == null)
{
MeterModelErrMsg = "Unable to delete. Record not found.";
return false;
}
if (!MmlIsLclChg && !Globals.IsMasterDB)
{
MeterModelErrMsg = "Unable to delete because this Meter Model was not added during this outage.\r\nYou may wish to inactivate instead.";
return false;
}
if (HasChildren())
{
MeterModelErrMsg = "Unable to delete because this Meter Model is referenced by Meters.";
return false;
}
DialogResult rslt = DialogResult.None;
if (promptUser)
{
rslt = MessageBox.Show("Are you sure?", "Factotum: Deleting...",
MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
}
if (!promptUser || rslt == DialogResult.OK)
{
SqlCeCommand cmd = Globals.cnn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText =
@"Delete from MeterModels
where MmlDBid = @p0";
cmd.Parameters.Add("@p0", MmlDBid);
if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open();
int rowsAffected = cmd.ExecuteNonQuery();
// Todo: figure out how I really want to do this.
// Is there a problem with letting the database try to do cascading deletes?
// How should the user be notified of the problem??
if (rowsAffected < 1)
{
MeterModelErrMsg = "Unable to delete. Please try again later.";
return false;
}
else
{
MeterModelErrMsg = null;
OnChanged(ID);
return true;
}
}
else
{
return false;
}
}
private bool HasChildren()
{
SqlCeCommand cmd = Globals.cnn.CreateCommand();
cmd.CommandText =
@"Select MtrDBid from Meters
where MtrMmlID = @p0";
cmd.Parameters.Add("@p0", MmlDBid);
if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open();
object result = cmd.ExecuteScalar();
return result != null;
}
//--------------------------------------------------------------------
// Static listing methods which return collections of metermodels
//--------------------------------------------------------------------
// This helper function builds the collection for you based on the flags you send it
// I originally had a flag that would let you indicate inactive items by appending '(inactive)'
// to the name. This was a bad idea, because sometimes the objects in this collection
// will get modified and saved back to the database -- with the extra text appended to the name.
public static EMeterModelCollection ListByName(
bool showactive, bool showinactive, bool addNoSelection)
{
EMeterModel metermodel;
EMeterModelCollection metermodels = new EMeterModelCollection();
SqlCeCommand cmd = Globals.cnn.CreateCommand();
cmd.CommandType = CommandType.Text;
string qry = @"Select
MmlDBid,
MmlName,
MmlManfName,
MmlIsLclChg,
MmlUsedInOutage,
MmlIsActive
from MeterModels";
if (showactive && !showinactive)
qry += " where MmlIsActive = 1";
else if (!showactive && showinactive)
qry += " where MmlIsActive = 0";
qry += " order by MmlName";
cmd.CommandText = qry;
if (addNoSelection)
{
// Insert a default item with name "<No Selection>"
metermodel = new EMeterModel();
metermodel.MmlName = "<No Selection>";
metermodels.Add(metermodel);
}
SqlCeDataReader dr;
if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open();
dr = cmd.ExecuteReader();
// Build new objects and add them to the collection
while (dr.Read())
{
metermodel = new EMeterModel((Guid?)dr[0]);
metermodel.MmlName = (string)(dr[1]);
metermodel.MmlManfName = (string)(dr[2]);
metermodel.MmlIsLclChg = (bool)(dr[3]);
metermodel.MmlUsedInOutage = (bool)(dr[4]);
metermodel.MmlIsActive = (bool)(dr[5]);
metermodels.Add(metermodel);
}
// Finish up
dr.Close();
return metermodels;
}
// Get a Default data view with all columns that a user would likely want to see.
// You can bind this view to a DataGridView, hide the columns you don't need, filter, etc.
// I decided not to indicate inactive in the names of inactive items. The 'user'
// can always show the inactive column if they wish.
public static DataView GetDefaultDataView()
{
DataSet ds = new DataSet();
DataView dv;
SqlCeDataAdapter da = new SqlCeDataAdapter();
SqlCeCommand cmd = Globals.cnn.CreateCommand();
cmd.CommandType = CommandType.Text;
// Changing the booleans to 'Yes' and 'No' eliminates the silly checkboxes and
// makes the column sortable.
// You'll likely want to modify this query further, joining in other tables, etc.
string qry = @"Select
MmlDBid as ID,
MmlName as MeterModelName,
MmlManfName as MeterModelManfName,
CASE
WHEN MmlIsLclChg = 0 THEN 'No'
ELSE 'Yes'
END as MeterModelIsLclChg,
CASE
WHEN MmlUsedInOutage = 0 THEN 'No'
ELSE 'Yes'
END as MeterModelUsedInOutage,
CASE
WHEN MmlIsActive = 0 THEN 'No'
ELSE 'Yes'
END as MeterModelIsActive
from MeterModels";
cmd.CommandText = qry;
da.SelectCommand = cmd;
if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open();
da.Fill(ds);
dv = new DataView(ds.Tables[0]);
return dv;
}
//--------------------------------------
// Private utilities
//--------------------------------------
// Check if the name exists for any records besides the current one
// This is used to show an error when the user tabs away from the field.
// We don't want to show an error if the user has left the field blank.
// If it's a required field, we'll catch it when the user hits save.
private bool NameExists(string name, Guid? id, out bool existingIsInactive)
{
existingIsInactive = false;
if (Util.IsNullOrEmpty(name)) return false;
SqlCeCommand cmd = Globals.cnn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add(new SqlCeParameter("@p1", name));
if (id == null)
{
cmd.CommandText = "Select MmlIsActive from MeterModels where MmlName = @p1";
}
else
{
cmd.CommandText = "Select MmlIsActive from MeterModels where MmlName = @p1 and MmlDBid != @p0";
cmd.Parameters.Add(new SqlCeParameter("@p0", id));
}
if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open();
object val = cmd.ExecuteScalar();
bool exists = (val != null);
if (exists) existingIsInactive = !(bool)val;
return exists;
}
// Check for required fields, setting the individual error messages
private bool RequiredFieldsFilled()
{
bool allFilled = true;
if (MeterModelName == null)
{
MmlNameErrMsg = "A unique Meter Model Name is required";
allFilled = false;
}
else
{
MmlNameErrMsg = null;
}
if (MeterModelManfName == null)
{
MmlManfNameErrMsg = "A Meter Model Manufacturer Name is required";
allFilled = false;
}
else
{
MmlManfNameErrMsg = null;
}
return allFilled;
}
}
//--------------------------------------
// MeterModel Collection class
//--------------------------------------
public class EMeterModelCollection : CollectionBase
{
//this event is fired when the collection's items have changed
public event EventHandler Changed;
//this is the constructor of the collection.
public EMeterModelCollection()
{ }
//the indexer of the collection
public EMeterModel this[int index]
{
get
{
return (EMeterModel)this.List[index];
}
}
//this method fires the Changed event.
protected virtual void OnChanged(EventArgs e)
{
if (Changed != null)
{
Changed(this, e);
}
}
public bool ContainsID(Guid? ID)
{
if (ID == null) return false;
foreach (EMeterModel metermodel in InnerList)
{
if (metermodel.ID == ID)
return true;
}
return false;
}
//returns the index of an item in the collection
public int IndexOf(EMeterModel item)
{
return InnerList.IndexOf(item);
}
//adds an item to the collection
public void Add(EMeterModel item)
{
this.List.Add(item);
OnChanged(EventArgs.Empty);
}
//inserts an item in the collection at a specified index
public void Insert(int index, EMeterModel item)
{
this.List.Insert(index, item);
OnChanged(EventArgs.Empty);
}
//removes an item from the collection.
public void Remove(EMeterModel item)
{
this.List.Remove(item);
OnChanged(EventArgs.Empty);
}
}
}
| |
// 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 BlendUInt161()
{
var test = new ImmBinaryOpTest__BlendUInt161();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
}
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 ImmBinaryOpTest__BlendUInt161
{
private struct TestStruct
{
public Vector256<UInt16> _fld1;
public Vector256<UInt16> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
return testStruct;
}
public void RunStructFldScenario(ImmBinaryOpTest__BlendUInt161 testClass)
{
var result = Avx2.Blend(_fld1, _fld2, 1);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<UInt16>>() / sizeof(UInt16);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<UInt16>>() / sizeof(UInt16);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<UInt16>>() / sizeof(UInt16);
private static UInt16[] _data1 = new UInt16[Op1ElementCount];
private static UInt16[] _data2 = new UInt16[Op2ElementCount];
private static Vector256<UInt16> _clsVar1;
private static Vector256<UInt16> _clsVar2;
private Vector256<UInt16> _fld1;
private Vector256<UInt16> _fld2;
private SimpleBinaryOpTest__DataTable<UInt16, UInt16, UInt16> _dataTable;
static ImmBinaryOpTest__BlendUInt161()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _clsVar1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _clsVar2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
}
public ImmBinaryOpTest__BlendUInt161()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); }
_dataTable = new SimpleBinaryOpTest__DataTable<UInt16, UInt16, UInt16>(_data1, _data2, new UInt16[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx2.Blend(
Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray2Ptr),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx2.Blend(
Avx.LoadVector256((UInt16*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((UInt16*)(_dataTable.inArray2Ptr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx2.Blend(
Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArray2Ptr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx2).GetMethod(nameof(Avx2.Blend), new Type[] { typeof(Vector256<UInt16>), typeof(Vector256<UInt16>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray2Ptr),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx2).GetMethod(nameof(Avx2.Blend), new Type[] { typeof(Vector256<UInt16>), typeof(Vector256<UInt16>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadVector256((UInt16*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((UInt16*)(_dataTable.inArray2Ptr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx2).GetMethod(nameof(Avx2.Blend), new Type[] { typeof(Vector256<UInt16>), typeof(Vector256<UInt16>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArray2Ptr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx2.Blend(
_clsVar1,
_clsVar2,
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var left = Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray2Ptr);
var result = Avx2.Blend(left, right, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var left = Avx.LoadVector256((UInt16*)(_dataTable.inArray1Ptr));
var right = Avx.LoadVector256((UInt16*)(_dataTable.inArray2Ptr));
var result = Avx2.Blend(left, right, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var left = Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArray1Ptr));
var right = Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArray2Ptr));
var result = Avx2.Blend(left, right, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ImmBinaryOpTest__BlendUInt161();
var result = Avx2.Blend(test._fld1, test._fld2, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx2.Blend(_fld1, _fld2, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx2.Blend(test._fld1, test._fld2, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector256<UInt16> left, Vector256<UInt16> right, void* result, [CallerMemberName] string method = "")
{
UInt16[] inArray1 = new UInt16[Op1ElementCount];
UInt16[] inArray2 = new UInt16[Op2ElementCount];
UInt16[] outArray = new UInt16[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), left);
Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
UInt16[] inArray1 = new UInt16[Op1ElementCount];
UInt16[] inArray2 = new UInt16[Op2ElementCount];
UInt16[] outArray = new UInt16[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(UInt16[] left, UInt16[] right, UInt16[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != (((1 & (1 << 0)) == 0) ? left[0] : right[0]))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != ((i < 8) ? (((1 & (1 << i)) == 0) ? left[i] : right[i]) : (((1 & (1 << (i - 8))) == 0) ? left[i] : right[i])))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.Blend)}<UInt16>(Vector256<UInt16>.1, Vector256<UInt16>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
//---------------------------------------------------------------------------
// <copyright file="AnnotationAdorner.cs" company="Microsoft">
// Copyright(C) Microsoft Corporation. All rights reserved.
// </copyright>
//
// Description:
// AnnotationAdorner wraps an IAnnotationComponent. Its the bridge
// between the component and the adorner layer.
//
// History:
// 04/01/2004: axelk: Created AnnotationAdorner.cs
// 10/20/2004: rruiz: Moved class to MS.Internal.
//
// Copyright(C) 2002 by Microsoft Corporation. All rights reserved.
//---------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Media;
namespace MS.Internal.Annotations.Component
{
/// <summary>
/// An adorner which wraps one IAnnotationComponent. The wrapped component must be at least a UIElement.
/// Adorners are UIElements.
/// Note:-This class is sealed because it calls OnVisualChildrenChanged virtual in the
/// constructor and it does not override it, but derived classes could.
/// </summary>
internal sealed class AnnotationAdorner : Adorner
{
#region Constructors
/// <summary>
/// Return an initialized annotation adorner
/// </summary>
/// <param name="component">The annotation component to wrap in the annotation adorner</param>
/// <param name="annotatedElement">element being annotated</param>
public AnnotationAdorner(IAnnotationComponent component, UIElement annotatedElement): base(annotatedElement)
{
//The summary on top of the file says:-
//The wrapped component must be at least a UIElement
if(component is UIElement)
{
_annotationComponent = component;
// wrapped annotation component is added as visual child
this.AddVisualChild((UIElement)_annotationComponent);
}
else
{
throw new ArgumentException(SR.Get(SRID.AnnotationAdorner_NotUIElement), "component");
}
}
#endregion Constructors
#region Public Methods
/// <summary>
/// Forwarded to the annotation component to get desired transform relative to the annotated element
/// </summary>
/// <param name="transform">Transform to adorned element</param>
/// <returns>Transform to annotation component </returns>
public override GeneralTransform GetDesiredTransform(GeneralTransform transform)
{
//if the component is not visual we do not need this
if (!(_annotationComponent is UIElement))
return null;
// Give the superclass a chance to modify the transform
transform = base.GetDesiredTransform(transform);
GeneralTransform compTransform = _annotationComponent.GetDesiredTransform(transform);
//ToDo. if the annotated element is null this component must be unloaded.
//Temporary return null until the PageViewer Load/Unload bug is fixed
//Convert it to an exception after that.
if (_annotationComponent.AnnotatedElement == null)
return null;
if (compTransform == null)
{
// We need to store the element we are registering on. It may not
// be available from the annotation component later.
_annotatedElement = _annotationComponent.AnnotatedElement;
// Wait for valid text view
_annotatedElement.LayoutUpdated += OnLayoutUpdated;
return transform;
}
return compTransform;
}
#endregion Public Methods
#region Protected Methods
/// <summary>
/// Derived class must implement to support Visual children. The method must return
/// the child at the specified index. Index must be between 0 and GetVisualChildrenCount-1.
///
/// By default a Visual does not have any children.
///
/// Remark:
/// During this virtual call it is not valid to modify the Visual tree.
/// </summary>
protected override Visual GetVisualChild(int index)
{
if(index != 0 || _annotationComponent == null)
{
throw new ArgumentOutOfRangeException("index", index, SR.Get(SRID.Visual_ArgumentOutOfRange));
}
return (UIElement)_annotationComponent;
}
/// <summary>
/// Derived classes override this property to enable the Visual code to enumerate
/// the Visual children. Derived classes need to return the number of children
/// from this method.
///
/// By default a Visual does not have any children.
///
/// Remark: During this virtual method the Visual tree must not be modified.
/// </summary>
protected override int VisualChildrenCount
{
get { return _annotationComponent != null ? 1 : 0; }
}
/// <summary>
/// Measurement override. Delegated to children.
/// </summary>
/// <param name="availableSize">Available size for the component</param>
/// <returns>Return the size enclosing all children</returns>
protected override Size MeasureOverride(Size availableSize)
{
Size childConstraint = new Size(Double.PositiveInfinity, Double.PositiveInfinity);
Invariant.Assert(_annotationComponent != null, "AnnotationAdorner should only have one child - the annotation component.");
((UIElement)_annotationComponent).Measure(childConstraint);
return new Size(0,0);
}
/// <summary>
/// Override for <seealso cref="FrameworkElement.ArrangeOverride" />
/// </summary>
/// <param name="finalSize">The location reserved for this element by the parent</param>
protected override Size ArrangeOverride(Size finalSize)
{
Invariant.Assert(_annotationComponent != null, "AnnotationAdorner should only have one child - the annotation component.");
((UIElement)_annotationComponent).Arrange(new Rect(((UIElement)_annotationComponent).DesiredSize));
return finalSize;
}
#endregion ProtectedMethods
#region Internal Methods
/// <summary>
/// Remove all visual children of this AnnotationAdorner.
/// Called by AdornerPresentationContext when an annotation adorner is removed from the adorner layer hosting it.
/// </summary>
internal void RemoveChildren()
{
this.RemoveVisualChild((UIElement)_annotationComponent);
_annotationComponent = null;
}
/// <summary>
/// Call this if the visual of the annotation changes.
/// This ill invalidate the AnnotationAdorner and the AdornerLayer which
/// will invoke remeasuring of the annotation visual.
/// </summary>
internal void InvalidateTransform()
{
AdornerLayer adornerLayer = (AdornerLayer)VisualTreeHelper.GetParent(this);
InvalidateMeasure();
adornerLayer.InvalidateVisual();
}
#endregion Internal Methods
#region Internal Properties
/// <summary>
/// Return the annotation component that is being wrapped. AdornerPresentationContext needs this.
/// </summary>
/// <value>Wrapped annotation component</value>
internal IAnnotationComponent AnnotationComponent
{
get { return _annotationComponent; }
}
#endregion Internal Properties
#region Private Methods
/// <summary>
/// LayoutUpdate event handler
/// </summary>
/// <param name="sender">event sender (not used)</param>
/// <param name="args">event arguments (not used)</param>
private void OnLayoutUpdated(object sender, EventArgs args)
{
// Unregister for the event
_annotatedElement.LayoutUpdated -= OnLayoutUpdated;
_annotatedElement = null;
// If there are still annotations to display, update the UI
if (_annotationComponent.AttachedAnnotations.Count > 0)
{
_annotationComponent.PresentationContext.Host.InvalidateMeasure();
this.InvalidateMeasure();
}
}
#endregion Private Methods
#region Private Fields
/// <summary>
/// The wrapped annotation component
/// </summary>
private IAnnotationComponent _annotationComponent;
/// <summary>
/// Used to unregister for the LayoutUpdated event - necessary because in the
/// the component may have its annotated element cleared before we can unregister.
/// </summary>
private UIElement _annotatedElement;
#endregion Private Fields
}
}
| |
// 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 Microsoft.Build.Framework;
using Microsoft.Build.BackEnd;
using Microsoft.Build.Construction;
using Microsoft.Build.Shared;
using Microsoft.Build.BackEnd.Logging;
using System.Collections.Generic;
using Microsoft.Build.Execution;
using Microsoft.Build.Collections;
using System.Collections;
using Microsoft.Build.Evaluation;
using Microsoft.Build.Unittest;
using TaskItem = Microsoft.Build.Execution.ProjectItemInstance.TaskItem;
using System.Threading.Tasks;
using Xunit;
namespace Microsoft.Build.UnitTests.BackEnd
{
/// <summary>
/// Test the task host class which acts as a communication mechanism between tasks and the msbuild engine.
/// </summary>
public class TaskHost_Tests
{
/// <summary>
/// Task host for the test
/// </summary>
private TaskHost _taskHost;
/// <summary>
/// Mock host for the tests
/// </summary>
private MockHost _mockHost;
/// <summary>
/// Custom logger for the tests
/// </summary>
private MyCustomLogger _customLogger;
/// <summary>
/// Element location for the tests
/// </summary>
private ElementLocation _elementLocation;
/// <summary>
/// Logging service for the tests
/// </summary>
private ILoggingService _loggingService;
/// <summary>
/// Mock request callback that provides the build results.
/// </summary>
private MockIRequestBuilderCallback _mockRequestCallback;
/// <summary>
/// Set up and initialize before each test is run
/// </summary>
public TaskHost_Tests()
{
LoggingServiceFactory loggingFactory = new LoggingServiceFactory(LoggerMode.Synchronous, 1);
_loggingService = loggingFactory.CreateInstance(BuildComponentType.LoggingService) as LoggingService;
_customLogger = new MyCustomLogger();
_mockHost = new MockHost();
_mockHost.LoggingService = _loggingService;
_loggingService.RegisterLogger(_customLogger);
_elementLocation = ElementLocation.Create("MockFile", 5, 5);
BuildRequest buildRequest = new BuildRequest(1 /* submissionId */, 1, 1, new List<string>(), null, BuildEventContext.Invalid, null);
BuildRequestConfiguration configuration = new BuildRequestConfiguration(1, new BuildRequestData("Nothing", new Dictionary<string, string>(), "4.0", new string[0], null), "2.0");
configuration.Project = new ProjectInstance(ProjectRootElement.Create());
BuildRequestEntry entry = new BuildRequestEntry(buildRequest, configuration);
BuildResult buildResult = new BuildResult(buildRequest, false);
buildResult.AddResultsForTarget("Build", new TargetResult(new TaskItem[] { new TaskItem("IamSuper", configuration.ProjectFullPath) }, BuildResultUtilities.GetSkippedResult()));
_mockRequestCallback = new MockIRequestBuilderCallback(new BuildResult[] { buildResult });
entry.Builder = (IRequestBuilder)_mockRequestCallback;
_taskHost = new TaskHost(_mockHost, entry, _elementLocation, null /*Don't care about the callback either unless doing a build*/);
_taskHost.LoggingContext = new TaskLoggingContext(_loggingService, BuildEventContext.Invalid);
}
/// <summary>
/// Verify when pulling target outputs out that we do not get the lives ones which are in the cache.
/// This is to prevent changes to the target outputs from being reflected in the cache if the changes are made in the task which calls the msbuild callback.
/// </summary>
[Fact]
public void TestLiveTargetOutputs()
{
IDictionary targetOutputs = new Hashtable();
IDictionary projectProperties = new Hashtable();
_taskHost.BuildProjectFile("ProjectFile", new string[] { "Build" }, projectProperties, targetOutputs);
Assert.NotNull(((ITaskItem[])targetOutputs["Build"])[0]);
TaskItem targetOutputItem = ((ITaskItem[])targetOutputs["Build"])[0] as TaskItem;
TaskItem mockItemInCache = _mockRequestCallback.BuildResultsToReturn[0].ResultsByTarget["Build"].Items[0] as TaskItem;
// Assert the contents are the same
Assert.True(targetOutputItem.Equals(mockItemInCache));
// Assert they are different instances.
Assert.False(object.ReferenceEquals(targetOutputItem, mockItemInCache));
}
/// <summary>
/// Makes sure that if a task tries to log a custom error event that subclasses our own
/// BuildErrorEventArgs, that the subclass makes it all the way to the logger. In other
/// words, the engine should not try to read data out of the event args and construct
/// its own.
/// </summary>
[Fact]
public void CustomBuildErrorEventIsPreserved()
{
// Create a custom build event args that derives from MSBuild's BuildErrorEventArgs.
// Set a custom field on this event (FXCopRule).
MyCustomBuildErrorEventArgs fxcopError = new MyCustomBuildErrorEventArgs("Your code failed.");
fxcopError.FXCopRule = "CodeViolation";
// Log the custom event args. (Pretend that the task actually did this.)
_taskHost.LogErrorEvent(fxcopError);
// Make sure our custom logger received the actual custom event and not some fake.
Assert.True(_customLogger.LastError is MyCustomBuildErrorEventArgs); // "Expected Custom Error Event"
// Make sure the special fields in the custom event match what we originally logged.
fxcopError = _customLogger.LastError as MyCustomBuildErrorEventArgs;
Assert.Equal("Your code failed.", fxcopError.Message);
Assert.Equal("CodeViolation", fxcopError.FXCopRule);
}
/// <summary>
/// Makes sure that if a task tries to log a custom warning event that subclasses our own
/// BuildWarningEventArgs, that the subclass makes it all the way to the logger. In other
/// words, the engine should not try to read data out of the event args and construct
/// its own.
/// </summary>
[Fact]
public void CustomBuildWarningEventIsPreserved()
{
// Create a custom build event args that derives from MSBuild's BuildWarningEventArgs.
// Set a custom field on this event (FXCopRule).
MyCustomBuildWarningEventArgs fxcopWarning = new MyCustomBuildWarningEventArgs("Your code failed.");
fxcopWarning.FXCopRule = "CodeViolation";
_taskHost.LogWarningEvent(fxcopWarning);
// Make sure our custom logger received the actual custom event and not some fake.
Assert.True(_customLogger.LastWarning is MyCustomBuildWarningEventArgs); // "Expected Custom Warning Event"
// Make sure the special fields in the custom event match what we originally logged.
fxcopWarning = _customLogger.LastWarning as MyCustomBuildWarningEventArgs;
Assert.Equal("Your code failed.", fxcopWarning.Message);
Assert.Equal("CodeViolation", fxcopWarning.FXCopRule);
}
/// <summary>
/// Makes sure that if a task tries to log a custom message event that subclasses our own
/// BuildMessageEventArgs, that the subclass makes it all the way to the logger. In other
/// words, the engine should not try to read data out of the event args and construct
/// its own.
/// </summary>
[Fact]
public void CustomBuildMessageEventIsPreserved()
{
// Create a custom build event args that derives from MSBuild's BuildMessageEventArgs.
// Set a custom field on this event (FXCopRule).
MyCustomMessageEvent customMessage = new MyCustomMessageEvent("I am a message");
customMessage.CustomMessage = "CodeViolation";
_taskHost.LogMessageEvent(customMessage);
// Make sure our custom logger received the actual custom event and not some fake.
Assert.True(_customLogger.LastMessage is MyCustomMessageEvent); // "Expected Custom message Event"
customMessage = _customLogger.LastMessage as MyCustomMessageEvent;
Assert.Equal("I am a message", customMessage.Message);
Assert.Equal("CodeViolation", customMessage.CustomMessage);
}
/// <summary>
/// Test that error events are correctly logged and take into account continue on error
/// </summary>
[Fact]
public void TestLogErrorEventWithContinueOnError()
{
_taskHost.ContinueOnError = false;
_taskHost.LogErrorEvent(new BuildErrorEventArgs("SubCategory", "code", null, 0, 1, 2, 3, "message", "Help", "Sender"));
// Make sure our custom logger received the actual custom event and not some fake.
Assert.True(_customLogger.LastError is BuildErrorEventArgs); // "Expected Error Event"
Assert.Equal(0, _customLogger.LastError.LineNumber); // "Expected line number to be 0"
_taskHost.ContinueOnError = true;
_taskHost.ConvertErrorsToWarnings = true;
Assert.Null(_customLogger.LastWarning); // "Expected no Warning Event at this point"
// Log the custom event args. (Pretend that the task actually did this.)
_taskHost.LogErrorEvent(new BuildErrorEventArgs("SubCategory", "code", null, 0, 1, 2, 3, "message", "Help", "Sender"));
// Make sure our custom logger received the actual custom event and not some fake.
Assert.True(_customLogger.LastWarning is BuildWarningEventArgs); // "Expected Warning Event"
Assert.Equal(0, _customLogger.LastWarning.LineNumber); // "Expected line number to be 0"
_taskHost.ContinueOnError = true;
_taskHost.ConvertErrorsToWarnings = false;
Assert.Equal(1, _customLogger.NumberOfWarning); // "Expected one Warning Event at this point"
Assert.Equal(1, _customLogger.NumberOfError); // "Expected one Warning Event at this point"
// Log the custom event args. (Pretend that the task actually did this.)
_taskHost.LogErrorEvent(new BuildErrorEventArgs("SubCategory", "code", null, 0, 1, 2, 3, "message", "Help", "Sender"));
// Make sure our custom logger received the actual custom event and not some fake.
Assert.True(_customLogger.LastError is BuildErrorEventArgs); // "Expected Error Event"
Assert.Equal(0, _customLogger.LastWarning.LineNumber); // "Expected line number to be 0"
}
/// <summary>
/// Test that a null error event will cause an exception
/// </summary>
[Fact]
public void TestLogErrorEventNull()
{
Assert.Throws<ArgumentNullException>(() =>
{
_taskHost.LogErrorEvent(null);
}
);
}
/// <summary>
/// Test that a null warning event will cause an exception
/// </summary>
[Fact]
public void TestLogWarningEventNull()
{
Assert.Throws<ArgumentNullException>(() =>
{
_taskHost.LogWarningEvent(null);
}
);
}
/// <summary>
/// Test that a null message event will cause an exception
/// </summary>
[Fact]
public void TestLogMessageEventNull()
{
Assert.Throws<ArgumentNullException>(() =>
{
_taskHost.LogMessageEvent(null);
}
);
}
/// <summary>
/// Test that a null custom event will cause an exception
/// </summary>
[Fact]
public void TestLogCustomEventNull()
{
Assert.Throws<ArgumentNullException>(() =>
{
_taskHost.LogCustomEvent(null);
}
);
}
/// <summary>
/// Test that errors are logged properly
/// </summary>
[Fact]
public void TestLogErrorEvent()
{
// Log the custom event args. (Pretend that the task actually did this.)
_taskHost.LogErrorEvent(new BuildErrorEventArgs("SubCategory", "code", null, 0, 1, 2, 3, "message", "Help", "Sender"));
// Make sure our custom logger received the actual custom event and not some fake.
Assert.True(_customLogger.LastError is BuildErrorEventArgs); // "Expected Error Event"
Assert.Equal(0, _customLogger.LastError.LineNumber); // "Expected line number to be 0"
}
/// <summary>
/// Test that warnings are logged properly
/// </summary>
[Fact]
public void TestLogWarningEvent()
{
// Log the custom event args. (Pretend that the task actually did this.)
_taskHost.LogWarningEvent(new BuildWarningEventArgs("SubCategory", "code", null, 0, 1, 2, 3, "message", "Help", "Sender"));
// Make sure our custom logger received the actual custom event and not some fake.
Assert.True(_customLogger.LastWarning is BuildWarningEventArgs); // "Expected Warning Event"
Assert.Equal(0, _customLogger.LastWarning.LineNumber); // "Expected line number to be 0"
}
/// <summary>
/// Test that messages are logged properly
/// </summary>
[Fact]
public void TestLogMessageEvent()
{
// Log the custom event args. (Pretend that the task actually did this.)
_taskHost.LogMessageEvent(new BuildMessageEventArgs("message", "HelpKeyword", "senderName", MessageImportance.High));
// Make sure our custom logger received the actual custom event and not some fake.
Assert.True(_customLogger.LastMessage is BuildMessageEventArgs); // "Expected Message Event"
Assert.Equal(MessageImportance.High, _customLogger.LastMessage.Importance); // "Expected Message importance to be high"
}
/// <summary>
/// Test that custom events are logged properly
/// </summary>
[Fact]
public void TestLogCustomEvent()
{
// Log the custom event args. (Pretend that the task actually did this.)
_taskHost.LogCustomEvent(new MyCustomBuildEventArgs("testCustomBuildEvent"));
// Make sure our custom logger received the actual custom event and not some fake.
Assert.True(_customLogger.LastCustom is CustomBuildEventArgs); // "Expected custom build Event"
Assert.Equal("testCustomBuildEvent", _customLogger.LastCustom.Message);
}
#region NotSerializableEvents
/// <summary>
/// Test that errors are logged properly
/// </summary>
[Fact]
public void TestLogErrorEventNotSerializableSP()
{
// Log the custom event args. (Pretend that the task actually did this.)
_taskHost.LogErrorEvent(new MyCustomBuildErrorEventArgsNotSerializable("SubCategory"));
// Make sure our custom logger received the actual custom event and not some fake.
Assert.True(_customLogger.LastError is BuildErrorEventArgs); // "Expected Error Event"
Assert.Contains("SubCategory", _customLogger.LastError.Message); // "Expected line number to be 0"
}
/// <summary>
/// Test that warnings are logged properly
/// </summary>
[Fact]
public void TestLogWarningEventNotSerializableSP()
{
// Log the custom event args. (Pretend that the task actually did this.)
_taskHost.LogWarningEvent(new MyCustomBuildWarningEventArgsNotSerializable("SubCategory"));
// Make sure our custom logger received the actual custom event and not some fake.
Assert.True(_customLogger.LastWarning is MyCustomBuildWarningEventArgsNotSerializable); // "Expected Warning Event"
Assert.Contains("SubCategory", _customLogger.LastWarning.Message); // "Expected line number to be 0"
}
/// <summary>
/// Test that messages are logged properly
/// </summary>
[Fact]
public void TestLogMessageEventNotSerializableSP()
{
// Log the custom event args. (Pretend that the task actually did this.)
_taskHost.LogMessageEvent(new MyCustomMessageEventNotSerializable("message"));
// Make sure our custom logger received the actual custom event and not some fake.
Assert.True(_customLogger.LastMessage is MyCustomMessageEventNotSerializable); // "Expected Message Event"
Assert.Contains("message", _customLogger.LastMessage.Message); // "Expected Message importance to be high"
}
/// <summary>
/// Test that custom events are logged properly
/// </summary>
[Fact]
public void TestLogCustomEventNotSerializableSP()
{
// Log the custom event args. (Pretend that the task actually did this.)
_taskHost.LogCustomEvent(new MyCustomBuildEventArgsNotSerializable("testCustomBuildEvent"));
// Make sure our custom logger received the actual custom event and not some fake.
Assert.True(_customLogger.LastCustom is MyCustomBuildEventArgsNotSerializable); // "Expected custom build Event"
Assert.Equal("testCustomBuildEvent", _customLogger.LastCustom.Message);
}
/// <summary>
/// Test that errors are logged properly
/// </summary>
[Fact]
public void TestLogErrorEventNotSerializableMP()
{
MyCustomBuildErrorEventArgsNotSerializable e = new MyCustomBuildErrorEventArgsNotSerializable("SubCategory");
_mockHost.BuildParameters.MaxNodeCount = 4;
Assert.True(_taskHost.IsRunningMultipleNodes);
// Log the custom event args. (Pretend that the task actually did this.)
_taskHost.LogErrorEvent(e);
Assert.Null(_customLogger.LastError); // "Expected no error Event"
Assert.True(_customLogger.LastWarning is BuildWarningEventArgs); // "Expected Warning Event"
string message = ResourceUtilities.FormatResourceStringStripCodeAndKeyword("ExpectedEventToBeSerializable", e.GetType().Name);
Assert.Contains(message, _customLogger.LastWarning.Message); // "Expected line to contain NotSerializable message but it did not"
}
/// <summary>
/// Test that warnings are logged properly
/// </summary>
[Fact]
public void TestLogWarningEventNotSerializableMP()
{
MyCustomBuildWarningEventArgsNotSerializable e = new MyCustomBuildWarningEventArgsNotSerializable("SubCategory");
_mockHost.BuildParameters.MaxNodeCount = 4;
_taskHost.LogWarningEvent(e);
Assert.True(_taskHost.IsRunningMultipleNodes);
Assert.True(_customLogger.LastWarning is BuildWarningEventArgs); // "Expected Warning Event"
Assert.Equal(1, _customLogger.NumberOfWarning); // "Expected there to be only one warning"
string message = ResourceUtilities.FormatResourceStringStripCodeAndKeyword("ExpectedEventToBeSerializable", e.GetType().Name);
Assert.Contains(message, _customLogger.LastWarning.Message); // "Expected line to contain NotSerializable message but it did not"
}
/// <summary>
/// Test that messages are logged properly
/// </summary>
[Fact]
public void TestLogMessageEventNotSerializableMP()
{
MyCustomMessageEventNotSerializable e = new MyCustomMessageEventNotSerializable("Message");
_mockHost.BuildParameters.MaxNodeCount = 4;
_taskHost.LogMessageEvent(e);
Assert.True(_taskHost.IsRunningMultipleNodes);
// Make sure our custom logger received the actual custom event and not some fake.
Assert.True(_customLogger.LastWarning is BuildWarningEventArgs); // "Expected Warning Event"
Assert.Equal(1, _customLogger.NumberOfWarning); // "Expected there to be only one warning"
string message = ResourceUtilities.FormatResourceStringStripCodeAndKeyword("ExpectedEventToBeSerializable", e.GetType().Name);
Assert.Contains(message, _customLogger.LastWarning.Message); // "Expected line to contain NotSerializable message but it did not"
}
/// <summary>
/// Test that custom events are logged properly
/// </summary>
[Fact]
public void TestLogCustomEventNotSerializableMP()
{
MyCustomBuildEventArgsNotSerializable e = new MyCustomBuildEventArgsNotSerializable("testCustomBuildEvent");
_mockHost.BuildParameters.MaxNodeCount = 4;
_taskHost.LogCustomEvent(e);
Assert.True(_taskHost.IsRunningMultipleNodes);
Assert.Null(_customLogger.LastCustom as MyCustomBuildEventArgsNotSerializable); // "Expected no custom Event"
// Make sure our custom logger received the actual custom event and not some fake.
Assert.True(_customLogger.LastWarning is BuildWarningEventArgs); // "Expected Warning Event"
Assert.Equal(1, _customLogger.NumberOfWarning); // "Expected there to be only one warning"
string message = ResourceUtilities.FormatResourceStringStripCodeAndKeyword("ExpectedEventToBeSerializable", e.GetType().Name);
Assert.Contains(message, _customLogger.LastWarning.Message); // "Expected line to contain NotSerializable message but it did not"
}
#endregion
/// <summary>
/// Verify IsRunningMultipleNodes
/// </summary>
[Fact]
public void IsRunningMultipleNodes1Node()
{
_mockHost.BuildParameters.MaxNodeCount = 1;
Assert.False(_taskHost.IsRunningMultipleNodes); // "Expect IsRunningMultipleNodes to be false with 1 node"
}
/// <summary>
/// Verify IsRunningMultipleNodes
/// </summary>
[Fact]
public void IsRunningMultipleNodes4Nodes()
{
_mockHost.BuildParameters.MaxNodeCount = 4;
Assert.True(_taskHost.IsRunningMultipleNodes); // "Expect IsRunningMultipleNodes to be true with 4 nodes"
}
#if FEATURE_CODETASKFACTORY
/// <summary>
/// Task logging after it's done should not crash us.
/// </summary>
[Fact]
public void LogCustomAfterTaskIsDone()
{
string projectFileContents = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' ToolsVersion='msbuilddefaulttoolsversion'>
<UsingTask TaskName='test' TaskFactory='CodeTaskFactory' AssemblyFile='$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll' >
<Task>
<Using Namespace='System' />
<Using Namespace='System.Threading' />
<Code Type='Fragment' Language='cs'>
<![CDATA[
Log.LogWarning(""[1]"");
ThreadPool.QueueUserWorkItem(state=>
{
Thread.Sleep(100);
Log.LogExternalProjectStarted(""a"", ""b"", ""c"", ""d""); // this logs a custom event
});
]]>
</Code>
</Task>
</UsingTask>
<Target Name='Build'>
<test/>
<Warning Text=""[3]""/>
</Target>
</Project>";
MockLogger mockLogger = Helpers.BuildProjectWithNewOMExpectSuccess(projectFileContents);
mockLogger.AssertLogContains("[1]");
mockLogger.AssertLogContains("[3]"); // [2] may or may not appear.
}
/// <summary>
/// Task logging after it's done should not crash us.
/// </summary>
[Fact]
public void LogCommentAfterTaskIsDone()
{
string projectFileContents = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' ToolsVersion='msbuilddefaulttoolsversion'>
<UsingTask TaskName='test' TaskFactory='CodeTaskFactory' AssemblyFile='$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll' >
<Task>
<Using Namespace='System' />
<Using Namespace='System.Threading' />
<Code Type='Fragment' Language='cs'>
<![CDATA[
Log.LogMessage(""[1]"");
ThreadPool.QueueUserWorkItem(state=>
{
Thread.Sleep(100);
Log.LogMessage(""[2]"");
});
]]>
</Code>
</Task>
</UsingTask>
<Target Name='Build'>
<test/>
<Message Text=""[3]""/>
</Target>
</Project>";
MockLogger mockLogger = Helpers.BuildProjectWithNewOMExpectSuccess(projectFileContents);
mockLogger.AssertLogContains("[1]");
mockLogger.AssertLogContains("[3]"); // [2] may or may not appear.
}
/// <summary>
/// Task logging after it's done should not crash us.
/// </summary>
[Fact]
public void LogWarningAfterTaskIsDone()
{
string projectFileContents = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' ToolsVersion='msbuilddefaulttoolsversion'>
<UsingTask TaskName='test' TaskFactory='CodeTaskFactory' AssemblyFile='$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll' >
<Task>
<Using Namespace='System' />
<Using Namespace='System.Threading' />
<Code Type='Fragment' Language='cs'>
<![CDATA[
Log.LogWarning(""[1]"");
ThreadPool.QueueUserWorkItem(state=>
{
Thread.Sleep(100);
Log.LogWarning(""[2]"");
});
]]>
</Code>
</Task>
</UsingTask>
<Target Name='Build'>
<test/>
<Warning Text=""[3]""/>
</Target>
</Project>";
MockLogger mockLogger = Helpers.BuildProjectWithNewOMExpectSuccess(projectFileContents);
mockLogger.AssertLogContains("[1]");
mockLogger.AssertLogContains("[3]"); // [2] may or may not appear.
}
/// <summary>
/// Task logging after it's done should not crash us.
/// </summary>
[Fact]
public void LogErrorAfterTaskIsDone()
{
string projectFileContents = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' ToolsVersion='msbuilddefaulttoolsversion'>
<UsingTask TaskName='test' TaskFactory='CodeTaskFactory' AssemblyFile='$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll' >
<Task>
<Using Namespace='System' />
<Using Namespace='System.Threading' />
<Code Type='Fragment' Language='cs'>
<![CDATA[
Log.LogError(""[1]"");
ThreadPool.QueueUserWorkItem(state=>
{
Thread.Sleep(100);
Log.LogError(""[2]"");
});
]]>
</Code>
</Task>
</UsingTask>
<Target Name='Build'>
<test ContinueOnError=""true""/>
<Warning Text=""[3]""/>
</Target>
</Project>";
MockLogger mockLogger = Helpers.BuildProjectWithNewOMExpectSuccess(projectFileContents);
mockLogger.AssertLogContains("[1]");
mockLogger.AssertLogContains("[3]"); // [2] may or may not appear.
}
#endif
#region Helper Classes
/// <summary>
/// Create a custom message event to make sure it can get sent correctly
/// </summary>
[Serializable]
internal class MyCustomMessageEvent : BuildMessageEventArgs
{
/// <summary>
/// Some custom data for the custom event.
/// </summary>
private string _customMessage;
/// <summary>
/// Constructor
/// </summary>
internal MyCustomMessageEvent
(
string message
)
: base(message, null, null, MessageImportance.High)
{
}
/// <summary>
/// Some data which can be set on the custom message event to make sure it makes it to the logger.
/// </summary>
internal string CustomMessage
{
get
{
return _customMessage;
}
set
{
_customMessage = value;
}
}
}
/// <summary>
/// Create a custom build event to test the logging of custom build events against the task host
/// </summary>
[Serializable]
internal class MyCustomBuildEventArgs : CustomBuildEventArgs
{
/// <summary>
/// Constructor
/// </summary>
public MyCustomBuildEventArgs() : base()
{
}
/// <summary>
/// Constructor which adds a message
/// </summary>
public MyCustomBuildEventArgs(string message) : base(message, "HelpKeyword", "SenderName")
{
}
}
/// <summary>
/// Class which implements a simple custom build error
/// </summary>
[Serializable]
internal class MyCustomBuildErrorEventArgs : BuildErrorEventArgs
{
/// <summary>
/// Some custom data for the custom event.
/// </summary>
private string _fxcopRule;
/// <summary>
/// Constructor
/// </summary>
internal MyCustomBuildErrorEventArgs
(
string message
)
: base(null, null, null, 0, 0, 0, 0, message, null, null)
{
}
/// <summary>
/// Some data which can be set on the custom error event to make sure it makes it to the logger.
/// </summary>
internal string FXCopRule
{
get
{
return _fxcopRule;
}
set
{
_fxcopRule = value;
}
}
}
/// <summary>
/// Class which implements a simple custom build warning
/// </summary>
[Serializable]
internal class MyCustomBuildWarningEventArgs : BuildWarningEventArgs
{
/// <summary>
/// Custom data for the custom event
/// </summary>
private string _fxcopRule;
/// <summary>
/// Constructor
/// </summary>
internal MyCustomBuildWarningEventArgs
(
string message
)
: base(null, null, null, 0, 0, 0, 0, message, null, null)
{
}
/// <summary>
/// Getter for the custom data in the custom event.
/// </summary>
internal string FXCopRule
{
get
{
return _fxcopRule;
}
set
{
_fxcopRule = value;
}
}
}
/// <summary>
/// Create a custom message event to make sure it can get sent correctly
/// </summary>
internal class MyCustomMessageEventNotSerializable : BuildMessageEventArgs
{
/// <summary>
/// Some custom data for the custom event.
/// </summary>
private string _customMessage;
/// <summary>
/// Constructor
/// </summary>
internal MyCustomMessageEventNotSerializable
(
string message
)
: base(message, null, null, MessageImportance.High)
{
}
/// <summary>
/// Some data which can be set on the custom message event to make sure it makes it to the logger.
/// </summary>
internal string CustomMessage
{
get
{
return _customMessage;
}
set
{
_customMessage = value;
}
}
}
/// <summary>
/// Custom build event which is not marked serializable. This is used to make sure we warn if we try and log a not serializable type in multiproc.
/// </summary>
internal class MyCustomBuildEventArgsNotSerializable : CustomBuildEventArgs
{
// If binary serialization is not available, then we use a simple serializer which relies on a default constructor. So to test
// what happens for an event that's not serializable, don't include a default constructor.
/// <summary>
/// Default constructor
/// </summary>
public MyCustomBuildEventArgsNotSerializable() : base()
{
}
/// <summary>
/// Constructor which takes a message
/// </summary>
public MyCustomBuildEventArgsNotSerializable(string message) : base(message, "HelpKeyword", "SenderName")
{
}
}
/// <summary>
/// Class which implements a simple custom build error which is not serializable
/// </summary>
internal class MyCustomBuildErrorEventArgsNotSerializable : BuildErrorEventArgs
{
/// <summary>
/// Custom data for the custom event
/// </summary>
private string _fxcopRule;
/// <summary>
/// Constructor
/// </summary>
internal MyCustomBuildErrorEventArgsNotSerializable
(
string message
)
: base(null, null, null, 0, 0, 0, 0, message, null, null)
{
}
/// <summary>
/// Getter and setter for the custom data
/// </summary>
internal string FXCopRule
{
get
{
return _fxcopRule;
}
set
{
_fxcopRule = value;
}
}
}
/// <summary>
/// Class which implements a simple custom build warning which is not serializable
/// </summary>
internal class MyCustomBuildWarningEventArgsNotSerializable : BuildWarningEventArgs
{
/// <summary>
/// Custom data for the custom event
/// </summary>
private string _fxcopRule;
/// <summary>
/// Constructor
/// </summary>
internal MyCustomBuildWarningEventArgsNotSerializable
(
string message
)
: base(null, null, null, 0, 0, 0, 0, message, null, null)
{
}
/// <summary>
/// Getter and setter for the custom data
/// </summary>
internal string FXCopRule
{
get
{
return _fxcopRule;
}
set
{
_fxcopRule = value;
}
}
}
/// <summary>
/// Custom logger which will be used for testing
/// </summary>
internal class MyCustomLogger : ILogger
{
/// <summary>
/// Last error event the logger encountered
/// </summary>
private BuildErrorEventArgs _lastError = null;
/// <summary>
/// Last warning event the logger encountered
/// </summary>
private BuildWarningEventArgs _lastWarning = null;
/// <summary>
/// Last message event the logger encountered
/// </summary>
private BuildMessageEventArgs _lastMessage = null;
/// <summary>
/// Last custom build event the logger encountered
/// </summary>
private CustomBuildEventArgs _lastCustom = null;
/// <summary>
/// Number of errors
/// </summary>
private int _numberOfError = 0;
/// <summary>
/// Number of warnings
/// </summary>
private int _numberOfWarning = 0;
/// <summary>
/// Number of messages
/// </summary>
private int _numberOfMessage = 0;
/// <summary>
/// Number of custom build events
/// </summary>
private int _numberOfCustom = 0;
/// <summary>
/// Last error logged
/// </summary>
public BuildErrorEventArgs LastError
{
get { return _lastError; }
set { _lastError = value; }
}
/// <summary>
/// Last warning logged
/// </summary>
public BuildWarningEventArgs LastWarning
{
get { return _lastWarning; }
set { _lastWarning = value; }
}
/// <summary>
/// Last message logged
/// </summary>
public BuildMessageEventArgs LastMessage
{
get { return _lastMessage; }
set { _lastMessage = value; }
}
/// <summary>
/// Last custom event logged
/// </summary>
public CustomBuildEventArgs LastCustom
{
get { return _lastCustom; }
set { _lastCustom = value; }
}
/// <summary>
/// Number of errors logged
/// </summary>
public int NumberOfError
{
get { return _numberOfError; }
set { _numberOfError = value; }
}
/// <summary>
/// Number of warnings logged
/// </summary>
public int NumberOfWarning
{
get { return _numberOfWarning; }
set { _numberOfWarning = value; }
}
/// <summary>
/// Number of message logged
/// </summary>
public int NumberOfMessage
{
get { return _numberOfMessage; }
set { _numberOfMessage = value; }
}
/// <summary>
/// Number of custom events logged
/// </summary>
public int NumberOfCustom
{
get { return _numberOfCustom; }
set { _numberOfCustom = value; }
}
/// <summary>
/// Verbosity of the log;
/// </summary>
public LoggerVerbosity Verbosity
{
get
{
return LoggerVerbosity.Normal;
}
set
{
}
}
/// <summary>
/// Parameters for the logger
/// </summary>
public string Parameters
{
get
{
return String.Empty;
}
set
{
}
}
/// <summary>
/// Initialize the logger against the event source
/// </summary>
public void Initialize(IEventSource eventSource)
{
eventSource.ErrorRaised += new BuildErrorEventHandler(MyCustomErrorHandler);
eventSource.WarningRaised += new BuildWarningEventHandler(MyCustomWarningHandler);
eventSource.MessageRaised += new BuildMessageEventHandler(MyCustomMessageHandler);
eventSource.CustomEventRaised += new CustomBuildEventHandler(MyCustomBuildHandler);
eventSource.AnyEventRaised += new AnyEventHandler(EventSource_AnyEventRaised);
}
/// <summary>
/// Do any cleanup and shutdown once the logger is done.
/// </summary>
public void Shutdown()
{
}
/// <summary>
/// Log if we have received any event.
/// </summary>
internal void EventSource_AnyEventRaised(object sender, BuildEventArgs e)
{
if (e.Message != null)
{
Console.Out.WriteLine("AnyEvent:" + e.Message.ToString());
}
}
/// <summary>
/// Log and record the number of errors.
/// </summary>
internal void MyCustomErrorHandler(object s, BuildErrorEventArgs e)
{
_numberOfError++;
_lastError = e;
if (e.Message != null)
{
Console.Out.WriteLine("CustomError:" + e.Message.ToString());
}
}
/// <summary>
/// Log and record the number of warnings.
/// </summary>
internal void MyCustomWarningHandler(object s, BuildWarningEventArgs e)
{
_numberOfWarning++;
_lastWarning = e;
if (e.Message != null)
{
Console.Out.WriteLine("CustomWarning:" + e.Message.ToString());
}
}
/// <summary>
/// Log and record the number of messages.
/// </summary>
internal void MyCustomMessageHandler(object s, BuildMessageEventArgs e)
{
_numberOfMessage++;
_lastMessage = e;
if (e.Message != null)
{
Console.Out.WriteLine("CustomMessage:" + e.Message.ToString());
}
}
/// <summary>
/// Log and record the number of custom build events.
/// </summary>
internal void MyCustomBuildHandler(object s, CustomBuildEventArgs e)
{
_numberOfCustom++;
_lastCustom = e;
if (e.Message != null)
{
Console.Out.WriteLine("CustomEvent:" + e.Message.ToString());
}
}
}
/// <summary>
/// Mock this class so that we can determine if build results are being cloned or if the live copies are being returned to the callers of the msbuild callback.
/// </summary>
internal class MockIRequestBuilderCallback : IRequestBuilderCallback, IRequestBuilder
{
/// <summary>
/// BuildResults to return from the BuildProjects method.
/// </summary>
private BuildResult[] _buildResultsToReturn;
/// <summary>
/// Constructor which takes an array of build results to return from the BuildProjects method when it is called.
/// </summary>
internal MockIRequestBuilderCallback(BuildResult[] buildResultsToReturn)
{
_buildResultsToReturn = buildResultsToReturn;
OnNewBuildRequests += new NewBuildRequestsDelegate(MockIRequestBuilderCallback_OnNewBuildRequests);
OnBuildRequestCompleted += new BuildRequestCompletedDelegate(MockIRequestBuilderCallback_OnBuildRequestCompleted);
OnBuildRequestBlocked += new BuildRequestBlockedDelegate(MockIRequestBuilderCallback_OnBuildRequestBlocked);
}
#pragma warning disable 0067 // not used
/// <summary>
/// Not Implemented
/// </summary>
public event NewBuildRequestsDelegate OnNewBuildRequests;
/// <summary>
/// Not Implemented
/// </summary>
public event BuildRequestCompletedDelegate OnBuildRequestCompleted;
/// <summary>
/// Not Implemented
/// </summary>
public event BuildRequestBlockedDelegate OnBuildRequestBlocked;
#pragma warning restore
/// <summary>
/// BuildResults to return from the BuildProjects method.
/// </summary>
public BuildResult[] BuildResultsToReturn
{
get { return _buildResultsToReturn; }
set { _buildResultsToReturn = value; }
}
/// <summary>
/// Mock of the BuildProjects method on the callback.
/// </summary>
public Task<BuildResult[]> BuildProjects(string[] projectFiles, PropertyDictionary<ProjectPropertyInstance>[] properties, string[] toolsVersions, string[] targets, bool waitForResults, bool skipNonexistentTargets)
{
return Task<BuildResult[]>.FromResult(_buildResultsToReturn);
}
/// <summary>
/// Mock of Yield
/// </summary>
public void Yield()
{
}
/// <summary>
/// Mock of Reacquire
/// </summary>
public void Reacquire()
{
}
/// <summary>
/// Mock
/// </summary>
public void EnterMSBuildCallbackState()
{
}
/// <summary>
/// Mock
/// </summary>
public void ExitMSBuildCallbackState()
{
}
/// <summary>
/// Mock of the Block on target in progress.
/// </summary>
public Task BlockOnTargetInProgress(int blockingRequestId, string blockingTarget, BuildResult partialBuildResult)
{
throw new NotImplementedException();
}
/// <summary>
/// Not Implemented
/// </summary>
public void BuildRequest(NodeLoggingContext nodeLoggingContext, BuildRequestEntry entry)
{
throw new NotImplementedException();
}
/// <summary>
/// Not Implemented
/// </summary>
public void ContinueRequest()
{
throw new NotImplementedException();
}
/// <summary>
/// Not Implemented
/// </summary>
public void CancelRequest()
{
throw new NotImplementedException();
}
/// <summary>
/// Not Implemented
/// </summary>
public void BeginCancel()
{
throw new NotImplementedException();
}
/// <summary>
/// Not Implemented
/// </summary>
public void WaitForCancelCompletion()
{
throw new NotImplementedException();
}
/// <summary>
/// Not Implemented
/// </summary>
private void MockIRequestBuilderCallback_OnBuildRequestBlocked(BuildRequestEntry issuingEntry, int blockingGlobalRequestId, string blockingTarget, IBuildResults partialBuildResult = null)
{
throw new NotImplementedException();
}
/// <summary>
/// Not Implemented
/// </summary>
private void MockIRequestBuilderCallback_OnBuildRequestCompleted(BuildRequestEntry completedEntry)
{
throw new NotImplementedException();
}
/// <summary>
/// Not Implemented
/// </summary>
private void MockIRequestBuilderCallback_OnNewBuildRequests(BuildRequestEntry issuingEntry, FullyQualifiedBuildRequest[] requests)
{
throw new NotImplementedException();
}
}
#endregion
}
}
| |
// This file is part of Wintermute Engine
// For conditions of distribution and use, see copyright notice in license.txt
// http://dead-code.org/redir.php?target=wme
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using DeadCode.WME.DocMaker;
using Microsoft.Win32;
using System.IO;
namespace DeadCode.WME.Debugger
{
//////////////////////////////////////////////////////////////////////////
public class DebugClient : IDisposable
{
private Dictionary<IntPtr, Script> Scripts = new Dictionary<IntPtr, Script>();
public readonly IDebugServer Server;
private ScriptScope GlobalScope = new ScriptScope();
DebugWindow DebugWindow;
//////////////////////////////////////////////////////////////////////////
public DebugClient(IDebugServer Server)
{
this.Server = Server;
DebugWindow = new DebugWindow(this);
DebugWindow.Show();
}
//////////////////////////////////////////////////////////////////////////
public bool GameInit()
{
//DebugWindow.AddLine("Init");
Server.QueryData();
DebugWindow.DisplayVars(GlobalScope);
return true;
}
//////////////////////////////////////////////////////////////////////////
public bool GameShutdown()
{
DebugWindow.ClearLog();
//DebugWindow.AddLine("Shutdown");
DebugWindow.Shutdown();
Scripts.Clear();
GlobalScope = new ScriptScope();
return true;
}
private bool RefreshVars = false;
//////////////////////////////////////////////////////////////////////////
public bool GameTick()
{
if(RefreshVars)
{
DebugWindow.RefreshVars();
RefreshVars = false;
}
DebugWindow.Tick();
return true;
}
//////////////////////////////////////////////////////////////////////////
public bool Log(int ErrorCode, string Text)
{
DebugWindow.AddLogLine(DateTime.Now.ToString("T") + ": " + Text);
return true;
}
//////////////////////////////////////////////////////////////////////////
private void RefreshScripts()
{
List<Script> ScrList = new List<Script>();
foreach(Script Scr in Scripts.Values)
{
ScrList.Add(Scr);
}
DebugWindow.RefreshScripts(ScrList.ToArray());
}
//////////////////////////////////////////////////////////////////////////
public bool ScriptInit(IWmeScript NativeScript)
{
if (Scripts.ContainsKey(NativeScript.NativeID)) return true;
Scripts.Add(NativeScript.NativeID, new Script(NativeScript));
RefreshScripts();
return true;
}
//////////////////////////////////////////////////////////////////////////
public bool ScriptEventThreadInit(IWmeScript NativeScript, IntPtr ParentID, string EventName)
{
if(Scripts.ContainsKey(NativeScript.NativeID)) return true;
if(Scripts.ContainsKey(ParentID))
{
Script Parent = Scripts[ParentID];
Script Thread = new Script(NativeScript, Script.ScriptType.EventThread, Parent, EventName);
Scripts.Add(NativeScript.NativeID, Thread);
Parent.Children.Add(Thread);
RefreshScripts();
return true;
}
else return false;
}
//////////////////////////////////////////////////////////////////////////
public bool ScriptMethodThreadInit(IWmeScript NativeScript, IntPtr ParentID, string MethodName)
{
if (Scripts.ContainsKey(NativeScript.NativeID)) return true;
if (Scripts.ContainsKey(ParentID))
{
Script Parent = Scripts[ParentID];
Script Thread = new Script(NativeScript, Script.ScriptType.MethodThread, Parent, MethodName);
Scripts.Add(NativeScript.NativeID, Thread);
Parent.Children.Add(Thread);
RefreshScripts();
return true;
}
else return false;
}
//////////////////////////////////////////////////////////////////////////
public bool ScriptShutdown(IntPtr ScriptID)
{
if (!Scripts.ContainsKey(ScriptID)) return false;
Script Scr = Scripts[ScriptID];
if (Scr.Parent != null) Scr.Parent.Children.Remove(Scr);
Scripts.Remove(ScriptID);
RefreshScripts();
return true;
}
//////////////////////////////////////////////////////////////////////////
public bool ScriptChangeLine(IntPtr ScriptID, int Line)
{
if (!Scripts.ContainsKey(ScriptID)) return false;
Scripts[ScriptID].OnChangeLine(Line);
return true;
}
//////////////////////////////////////////////////////////////////////////
public bool ScriptChangeScope(IntPtr ScriptID, int ScopeID)
{
if (!Scripts.ContainsKey(ScriptID)) return false;
Scripts[ScriptID].CurrentScope = ScopeID;
return true;
}
//////////////////////////////////////////////////////////////////////////
public bool ScriptShutdownScope(IntPtr ScriptID, int ScopeID)
{
if (!Scripts.ContainsKey(ScriptID)) return false;
Scripts[ScriptID].RemoveScope(ScopeID);
return true;
}
//////////////////////////////////////////////////////////////////////////
public bool ScriptHitBreakpoint(IntPtr ScriptID, int Line)
{
if (!Scripts.ContainsKey(ScriptID)) return false;
Script Scr = Scripts[ScriptID];
//DebugWindow.AddLine("Breakpoint hit: " + Scr.Filename + ", line " + Line.ToString());
DebugWindow.SelectedScript = Scr;
DebugWindow.RefreshVars();
DebugWindow.Tick();
DebugWindow.HighlightScriptLine();
DebugWindow.Visible = true;
DebugWindow.BringToFront();
return true;
}
//////////////////////////////////////////////////////////////////////////
public bool GlobalVariableInit(IWmeValue Variable)
{
GlobalScope.AddVar(Variable);
return true;
}
//////////////////////////////////////////////////////////////////////////
public bool ScriptVariableInit(IWmeValue Variable, IntPtr ScriptID)
{
if (!Scripts.ContainsKey(ScriptID)) return false;
Scripts[ScriptID].AddGlobalVar(Variable);
return true;
}
//////////////////////////////////////////////////////////////////////////
public bool ScopeVariableInit(IWmeValue Variable, IntPtr ScriptID, int ScopeID)
{
if (!Scripts.ContainsKey(ScriptID)) return false;
Scripts[ScriptID].AddScopeVar(Variable, ScopeID);
return true;
}
//////////////////////////////////////////////////////////////////////////
public bool VariableChangeValue(IWmeValue Variable, IWmeValue Value)
{
ScriptScope Scope;
Script Script;
GetVarScope(Variable, out Script, out Scope);
if (Scope == GlobalScope || (Script != null && Script == DebugWindow.SelectedScript))
{
RefreshVars = true;
}
return true;
}
//////////////////////////////////////////////////////////////////////////
private void GetVarScope(IWmeValue Variable, out Script Script, out ScriptScope Scope)
{
if (GlobalScope.Vars.ContainsKey(Variable))
{
Scope = GlobalScope;
Script = null;
return;
}
else
{
foreach (KeyValuePair<IntPtr, Script> kvp in Scripts)
{
ScriptScope ScrScope = kvp.Value.GetVarScope(Variable);
if (ScrScope != null)
{
Scope = ScrScope;
Script = kvp.Value;
return;
}
}
Script = null;
Scope = null;
}
}
//////////////////////////////////////////////////////////////////////////
public void Dispose()
{
if (DebugWindow != null && DebugWindow.Visible) DebugWindow.Close();
}
private static Dictionary<string, string[]> ClassProps = null;
//////////////////////////////////////////////////////////////////////////
public static string[] GetClassProperties(string NativeClass)
{
if(ClassProps==null)
{
ClassProps = new Dictionary<string, string[]>();
try
{
string XmlDocsPath = "";
using (RegistryKey Key = Registry.CurrentUser.OpenSubKey(@"Software\DEAD:CODE\Wintermute Tools\Settings"))
{
XmlDocsPath = Key.GetValue("ToolsPath", "").ToString();
};
XmlDocsPath = Path.Combine(XmlDocsPath, "wme_docs_core_en.xml");
if (File.Exists(XmlDocsPath))
{
ScriptInfo Info = new ScriptInfo();
if (Info.ReadXml(XmlDocsPath))
{
foreach (ScriptObject Obj in Info.Objects)
{
if (Obj.NativeClass == null || Obj.NativeClass == string.Empty) continue;
List<string> Attrs = new List<string>(Obj.Attributes.Count);
foreach (ScriptAttribute Attr in Obj.Attributes)
{
Attrs.Add(Attr.Name);
}
ClassProps[Obj.NativeClass] = Attrs.ToArray();
}
}
}
}
catch
{
}
}
if (ClassProps.ContainsKey(NativeClass)) return ClassProps[NativeClass];
else return null;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Text;
using System.Web.Script.Serialization;
using WhatsAppApi.Helper;
using WhatsAppApi.Parser;
using WhatsAppApi.Response;
using WhatsAppApi.Settings;
namespace WhatsAppApi
{
/// <summary>
/// Main api interface
/// </summary>
public class WhatsApp : WhatsSendBase
{
public WhatsApp(string phoneNum, string imei, string nick, bool debug = false, bool hidden = false)
{
this._constructBase(phoneNum, imei, nick, debug, hidden);
}
public string SendMessage(string to, string txt)
{
var tmpMessage = new FMessage(GetJID(to), true) { data = txt };
this.SendMessage(tmpMessage, this.hidden);
return tmpMessage.identifier_key.ToString();
}
public void SendMessageVcard(string to, string name, string vcard_data)
{
var tmpMessage = new FMessage(GetJID(to), true) { data = vcard_data, media_wa_type = FMessage.Type.Contact, media_name = name };
this.SendMessage(tmpMessage, this.hidden);
}
public void SendSync(string[] numbers, SyncMode mode = SyncMode.Delta, SyncContext context = SyncContext.Background, int index = 0, bool last = true)
{
List<ProtocolTreeNode> users = new List<ProtocolTreeNode>();
foreach (string number in numbers)
{
string _number = number;
if (!_number.StartsWith("+", StringComparison.InvariantCulture))
_number = string.Format("+{0}", number);
users.Add(new ProtocolTreeNode("user", null, System.Text.Encoding.UTF8.GetBytes(_number)));
}
ProtocolTreeNode node = new ProtocolTreeNode("iq", new KeyValue[]
{
new KeyValue("to", GetJID(this.phoneNumber)),
new KeyValue("type", "get"),
new KeyValue("id", TicketCounter.MakeId()),
new KeyValue("xmlns", "urn:xmpp:whatsapp:sync")
}, new ProtocolTreeNode("sync", new KeyValue[]
{
new KeyValue("mode", mode.ToString().ToLowerInvariant()),
new KeyValue("context", context.ToString().ToLowerInvariant()),
new KeyValue("sid", DateTime.Now.ToFileTimeUtc().ToString()),
new KeyValue("index", index.ToString()),
new KeyValue("last", last.ToString())
},
users.ToArray()
)
);
this.SendNode(node);
}
public void SendMessageImage(string to, byte[] ImageData, ImageType imgtype)
{
FMessage msg = this.getFmessageImage(to, ImageData, imgtype);
if (msg != null)
{
this.SendMessage(msg);
}
}
protected FMessage getFmessageImage(string to, byte[] ImageData, ImageType imgtype)
{
string type = string.Empty;
string extension = string.Empty;
switch (imgtype)
{
case ImageType.PNG:
type = "image/png";
extension = "png";
break;
case ImageType.GIF:
type = "image/gif";
extension = "gif";
break;
default:
type = "image/jpeg";
extension = "jpg";
break;
}
//create hash
string filehash = string.Empty;
using(HashAlgorithm sha = HashAlgorithm.Create("sha256"))
{
byte[] raw = sha.ComputeHash(ImageData);
filehash = Convert.ToBase64String(raw);
}
//request upload
WaUploadResponse response = this.UploadFile(filehash, "image", ImageData.Length, ImageData, to, type, extension);
if (response != null && !String.IsNullOrEmpty(response.url))
{
//send message
FMessage msg = new FMessage(to, true)
{
media_wa_type = FMessage.Type.Image,
media_mime_type = response.mimetype,
media_name = response.url.Split('/').Last(),
media_size = response.size,
media_url = response.url,
binary_data = this.CreateThumbnail(ImageData)
};
return msg;
}
return null;
}
public void SendMessageVideo(string to, byte[] videoData, VideoType vidtype)
{
FMessage msg = this.getFmessageVideo(to, videoData, vidtype);
if (msg != null)
{
this.SendMessage(msg);
}
}
protected FMessage getFmessageVideo(string to, byte[] videoData, VideoType vidtype)
{
to = GetJID(to);
string type = string.Empty;
string extension = string.Empty;
switch (vidtype)
{
case VideoType.MOV:
type = "video/quicktime";
extension = "mov";
break;
case VideoType.AVI:
type = "video/x-msvideo";
extension = "avi";
break;
default:
type = "video/mp4";
extension = "mp4";
break;
}
//create hash
string filehash = string.Empty;
using (HashAlgorithm sha = HashAlgorithm.Create("sha256"))
{
byte[] raw = sha.ComputeHash(videoData);
filehash = Convert.ToBase64String(raw);
}
//request upload
WaUploadResponse response = this.UploadFile(filehash, "video", videoData.Length, videoData, to, type, extension);
if (response != null && !String.IsNullOrEmpty(response.url))
{
//send message
FMessage msg = new FMessage(to, true) {
media_wa_type = FMessage.Type.Video,
media_mime_type = response.mimetype,
media_name = response.url.Split('/').Last(),
media_size = response.size,
media_url = response.url,
media_duration_seconds = response.duration
};
return msg;
}
return null;
}
public void SendMessageAudio(string to, byte[] audioData, AudioType audtype)
{
FMessage msg = this.getFmessageAudio(to, audioData, audtype);
if (msg != null)
{
this.SendMessage(msg);
}
}
protected FMessage getFmessageAudio(string to, byte[] audioData, AudioType audtype)
{
to = GetJID(to);
string type = string.Empty;
string extension = string.Empty;
switch (audtype)
{
case AudioType.WAV:
type = "audio/wav";
extension = "wav";
break;
case AudioType.OGG:
type = "audio/ogg";
extension = "ogg";
break;
default:
type = "audio/mpeg";
extension = "mp3";
break;
}
//create hash
string filehash = string.Empty;
using (HashAlgorithm sha = HashAlgorithm.Create("sha256"))
{
byte[] raw = sha.ComputeHash(audioData);
filehash = Convert.ToBase64String(raw);
}
//request upload
WaUploadResponse response = this.UploadFile(filehash, "audio", audioData.Length, audioData, to, type, extension);
if (response != null && !String.IsNullOrEmpty(response.url))
{
//send message
FMessage msg = new FMessage(to, true) {
media_wa_type = FMessage.Type.Audio,
media_mime_type = response.mimetype,
media_name = response.url.Split('/').Last(),
media_size = response.size,
media_url = response.url,
media_duration_seconds = response.duration
};
return msg;
}
return null;
}
protected WaUploadResponse UploadFile(string b64hash, string type, long size, byte[] fileData, string to, string contenttype, string extension)
{
ProtocolTreeNode media = new ProtocolTreeNode("media", new KeyValue[] {
new KeyValue("hash", b64hash),
new KeyValue("type", type),
new KeyValue("size", size.ToString())
});
string id = TicketManager.GenerateId();
ProtocolTreeNode node = new ProtocolTreeNode("iq", new KeyValue[] {
new KeyValue("id", id),
new KeyValue("to", WhatsConstants.WhatsAppServer),
new KeyValue("type", "set"),
new KeyValue("xmlns", "w:m")
}, media);
this.uploadResponse = null;
this.SendNode(node);
int i = 0;
while (this.uploadResponse == null && i <= 10)
{
i++;
this.pollMessage();
}
if (this.uploadResponse != null && this.uploadResponse.GetChild("duplicate") != null)
{
WaUploadResponse res = new WaUploadResponse(this.uploadResponse);
this.uploadResponse = null;
return res;
}
else
{
try
{
string uploadUrl = this.uploadResponse.GetChild("media").GetAttribute("url");
this.uploadResponse = null;
Uri uri = new Uri(uploadUrl);
string hashname = string.Empty;
byte[] buff = MD5.Create().ComputeHash(System.Text.Encoding.Default.GetBytes(b64hash));
StringBuilder sb = new StringBuilder();
foreach (byte b in buff)
{
sb.Append(b.ToString("X2"));
}
hashname = String.Format("{0}.{1}", sb.ToString(), extension);
string boundary = "zzXXzzYYzzXXzzQQ";
sb = new StringBuilder();
sb.AppendFormat("--{0}\r\n", boundary);
sb.Append("Content-Disposition: form-data; name=\"to\"\r\n\r\n");
sb.AppendFormat("{0}\r\n", to);
sb.AppendFormat("--{0}\r\n", boundary);
sb.Append("Content-Disposition: form-data; name=\"from\"\r\n\r\n");
sb.AppendFormat("{0}\r\n", this.phoneNumber);
sb.AppendFormat("--{0}\r\n", boundary);
sb.AppendFormat("Content-Disposition: form-data; name=\"file\"; filename=\"{0}\"\r\n", hashname);
sb.AppendFormat("Content-Type: {0}\r\n\r\n", contenttype);
string header = sb.ToString();
sb = new StringBuilder();
sb.AppendFormat("\r\n--{0}--\r\n", boundary);
string footer = sb.ToString();
long clength = size + header.Length + footer.Length;
sb = new StringBuilder();
sb.AppendFormat("POST {0}\r\n", uploadUrl);
sb.AppendFormat("Content-Type: multipart/form-data; boundary={0}\r\n", boundary);
sb.AppendFormat("Host: {0}\r\n", uri.Host);
sb.AppendFormat("User-Agent: {0}\r\n", WhatsConstants.UserAgent);
sb.AppendFormat("Content-Length: {0}\r\n\r\n", clength);
string post = sb.ToString();
TcpClient tc = new TcpClient(uri.Host, 443);
SslStream ssl = new SslStream(tc.GetStream());
ssl.AuthenticateAsClient(uri.Host);
List<byte> buf = new List<byte>();
buf.AddRange(Encoding.UTF8.GetBytes(post));
buf.AddRange(Encoding.UTF8.GetBytes(header));
buf.AddRange(fileData);
buf.AddRange(Encoding.UTF8.GetBytes(footer));
ssl.Write(buf.ToArray(), 0, buf.ToArray().Length);
//moment of truth...
buff = new byte[1024];
ssl.Read(buff, 0, 1024);
string result = Encoding.UTF8.GetString(buff);
foreach (string line in result.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries))
{
if (line.StartsWith("{"))
{
string fooo = line.TrimEnd(new char[] { (char)0 });
JavaScriptSerializer jss = new JavaScriptSerializer();
WaUploadResponse resp = jss.Deserialize<WaUploadResponse>(fooo);
if (!String.IsNullOrEmpty(resp.url))
{
return resp;
}
}
}
}
catch (Exception)
{ }
}
return null;
}
protected void SendQrSync(byte[] qrkey, byte[] token = null)
{
string id = TicketCounter.MakeId();
List<ProtocolTreeNode> children = new List<ProtocolTreeNode>();
children.Add(new ProtocolTreeNode("sync", null, qrkey));
if (token != null)
{
children.Add(new ProtocolTreeNode("code", null, token));
}
ProtocolTreeNode node = new ProtocolTreeNode("iq", new[] {
new KeyValue("type", "set"),
new KeyValue("id", id),
new KeyValue("xmlns", "w:web")
}, children.ToArray());
this.SendNode(node);
}
public void SendActive()
{
var node = new ProtocolTreeNode("presence", new[] { new KeyValue("type", "active") });
this.SendNode(node);
}
public void SendAddParticipants(string gjid, IEnumerable<string> participants)
{
string id = TicketCounter.MakeId();
this.SendVerbParticipants(gjid, participants, id, "add");
}
public void SendUnavailable()
{
var node = new ProtocolTreeNode("presence", new[] { new KeyValue("type", "unavailable") });
this.SendNode(node);
}
public void SendClientConfig(string platform, string lg, string lc)
{
string v = TicketCounter.MakeId();
var child = new ProtocolTreeNode("config", new[] { new KeyValue("xmlns", "urn:xmpp:whatsapp:push"), new KeyValue("platform", platform), new KeyValue("lg", lg), new KeyValue("lc", lc) });
var node = new ProtocolTreeNode("iq", new[] { new KeyValue("id", v), new KeyValue("type", "set"), new KeyValue("to", WhatsConstants.WhatsAppRealm) }, new ProtocolTreeNode[] { child });
this.SendNode(node);
}
public void SendClientConfig(string platform, string lg, string lc, Uri pushUri, bool preview, bool defaultSetting, bool groupsSetting, IEnumerable<GroupSetting> groups, Action onCompleted, Action<int> onError)
{
string id = TicketCounter.MakeId();
var node = new ProtocolTreeNode("iq",
new[]
{
new KeyValue("id", id), new KeyValue("type", "set"),
new KeyValue("to", "") //this.Login.Domain)
},
new ProtocolTreeNode[]
{
new ProtocolTreeNode("config",
new[]
{
new KeyValue("xmlns","urn:xmpp:whatsapp:push"),
new KeyValue("platform", platform),
new KeyValue("lg", lg),
new KeyValue("lc", lc),
new KeyValue("clear", "0"),
new KeyValue("id", pushUri.ToString()),
new KeyValue("preview",preview ? "1" : "0"),
new KeyValue("default",defaultSetting ? "1" : "0"),
new KeyValue("groups",groupsSetting ? "1" : "0")
},
this.ProcessGroupSettings(groups))
});
this.SendNode(node);
}
public void SendClose()
{
var node = new ProtocolTreeNode("presence", new[] { new KeyValue("type", "unavailable") });
this.SendNode(node);
}
public void SendComposing(string to)
{
this.SendChatState(to, "composing");
}
protected void SendChatState(string to, string type)
{
var node = new ProtocolTreeNode("chatstate", new[] { new KeyValue("to", WhatsApp.GetJID(to)) }, new[] {
new ProtocolTreeNode(type, null)
});
this.SendNode(node);
}
public void SendCreateGroupChat(string subject, IEnumerable<string> participants)
{
string id = TicketCounter.MakeId();
IEnumerable<ProtocolTreeNode> participant = from jid in participants select new ProtocolTreeNode("participant", new[] { new KeyValue("jid", GetJID(jid)) });
var child = new ProtocolTreeNode("create", new[] { new KeyValue("subject", subject) }, new ProtocolTreeNode[] { (ProtocolTreeNode) participant });
var node = new ProtocolTreeNode("iq", new[] { new KeyValue("id", id), new KeyValue("type", "set"), new KeyValue("xmlns", "w:g2"), new KeyValue("to", "g.us") }, new ProtocolTreeNode[] { child });
this.SendNode(node);
}
public void SendDeleteAccount()
{
string id = TicketCounter.MakeId();
var node = new ProtocolTreeNode("iq",
new KeyValue[]
{
new KeyValue("id", id),
new KeyValue("type", "get"),
new KeyValue("to", "s.whatsapp.net"),
new KeyValue("xmlns", "urn:xmpp:whatsapp:account")
},
new ProtocolTreeNode[]
{
new ProtocolTreeNode("remove",
null
)
});
this.SendNode(node);
}
public void SendDeleteFromRoster(string jid)
{
string v = TicketCounter.MakeId();
var innerChild = new ProtocolTreeNode("item", new[] { new KeyValue("jid", jid), new KeyValue("subscription", "remove") });
var child = new ProtocolTreeNode("query", new[] { new KeyValue("xmlns", "jabber:iq:roster") }, new ProtocolTreeNode[] { innerChild });
var node = new ProtocolTreeNode("iq", new[] { new KeyValue("type", "set"), new KeyValue("id", v) }, new ProtocolTreeNode[] { child });
this.SendNode(node);
}
public void SendEndGroupChat(string gjid)
{
string id = TicketCounter.MakeId();
var child = new ProtocolTreeNode("group", new[] { new KeyValue("action", "delete") });
var node = new ProtocolTreeNode("iq", new[] { new KeyValue("id", id), new KeyValue("type", "set"), new KeyValue("xmlns", "w:g2"), new KeyValue("to", gjid) }, new ProtocolTreeNode[] { child });
this.SendNode(node);
}
public void SendGetClientConfig()
{
string id = TicketCounter.MakeId();
var child = new ProtocolTreeNode("config", new[] { new KeyValue("xmlns", "urn:xmpp:whatsapp:push") });
var node = new ProtocolTreeNode("iq", new[] { new KeyValue("id", id), new KeyValue("type", "get"), new KeyValue("to", WhatsConstants.WhatsAppRealm) }, new ProtocolTreeNode[] { child });
this.SendNode(node);
}
public void SendGetDirty()
{
string id = TicketCounter.MakeId();
var child = new ProtocolTreeNode("status", new[] { new KeyValue("xmlns", "urn:xmpp:whatsapp:dirty") });
var node = new ProtocolTreeNode("iq", new[] { new KeyValue("id", id), new KeyValue("type", "get"), new KeyValue("to", "s.whatsapp.net") }, new ProtocolTreeNode[] { child });
this.SendNode(node);
}
public void SendGetGroupInfo(string gjid)
{
string id = TicketCounter.MakeId();
var child = new ProtocolTreeNode("query", null);
var node = new ProtocolTreeNode("iq", new[] { new KeyValue("id", id), new KeyValue("type", "get"), new KeyValue("xmlns", "w:g2"), new KeyValue("to", WhatsAppApi.WhatsApp.GetJID(gjid)) }, new ProtocolTreeNode[] { child });
this.SendNode(node);
}
public void SendGetGroups()
{
string id = TicketCounter.MakeId();
this.SendGetGroups(id, "participating");
}
public void SendGetOwningGroups()
{
string id = TicketCounter.MakeId();
this.SendGetGroups(id, "owning");
}
public void SendGetParticipants(string gjid)
{
string id = TicketCounter.MakeId();
var child = new ProtocolTreeNode("list", null);
var node = new ProtocolTreeNode("iq", new[] { new KeyValue("id", id), new KeyValue("type", "get"), new KeyValue("xmlns", "w:g2"), new KeyValue("to", WhatsApp.GetJID(gjid)) }, child);
this.SendNode(node);
}
public string SendGetPhoto(string jid, string expectedPhotoId, bool largeFormat)
{
string id = TicketCounter.MakeId();
var attrList = new List<KeyValue>();
if (!largeFormat)
{
attrList.Add(new KeyValue("type", "preview"));
}
if (expectedPhotoId != null)
{
attrList.Add(new KeyValue("id", expectedPhotoId));
}
var child = new ProtocolTreeNode("picture", attrList.ToArray());
var node = new ProtocolTreeNode("iq", new[] { new KeyValue("id", id), new KeyValue("type", "get"), new KeyValue("xmlns", "w:profile:picture"), new KeyValue("to", WhatsAppApi.WhatsApp.GetJID(jid)) }, child);
this.SendNode(node);
return id;
}
public void SendGetPhotoIds(IEnumerable<string> jids)
{
string id = TicketCounter.MakeId();
var node = new ProtocolTreeNode("iq", new[] { new KeyValue("id", id), new KeyValue("type", "get"), new KeyValue("to", GetJID(this.phoneNumber)) },
new ProtocolTreeNode("list", new[] { new KeyValue("xmlns", "w:profile:picture") },
(from jid in jids select new ProtocolTreeNode("user", new[] { new KeyValue("jid", jid) })).ToArray<ProtocolTreeNode>()));
this.SendNode(node);
}
public void SendGetPrivacyList()
{
string id = TicketCounter.MakeId();
var innerChild = new ProtocolTreeNode("list", new[] { new KeyValue("name", "default") });
var child = new ProtocolTreeNode("query", null, innerChild);
var node = new ProtocolTreeNode("iq", new KeyValue[] { new KeyValue("id", id), new KeyValue("type", "get"), new KeyValue("xmlns", "jabber:iq:privacy") }, child);
this.SendNode(node);
}
public void SendGetServerProperties()
{
string id = TicketCounter.MakeId();
var node = new ProtocolTreeNode("iq", new[] { new KeyValue("id", id), new KeyValue("type", "get"), new KeyValue("xmlns", "w"), new KeyValue("to", "s.whatsapp.net") },
new ProtocolTreeNode("props", null));
this.SendNode(node);
}
public void SendGetStatuses(string[] jids)
{
List<ProtocolTreeNode> targets = new List<ProtocolTreeNode>();
foreach (string jid in jids)
{
targets.Add(new ProtocolTreeNode("user", new[] { new KeyValue("jid", GetJID(jid)) }, null, null));
}
ProtocolTreeNode node = new ProtocolTreeNode("iq", new[] {
new KeyValue("to", "s.whatsapp.net"),
new KeyValue("type", "get"),
new KeyValue("xmlns", "status"),
new KeyValue("id", TicketCounter.MakeId())
}, new[] {
new ProtocolTreeNode("status", null, targets.ToArray(), null)
}, null);
this.SendNode(node);
}
public void SendInactive()
{
var node = new ProtocolTreeNode("presence", new[] { new KeyValue("type", "inactive") });
this.SendNode(node);
}
public void SendLeaveGroup(string gjid)
{
this.SendLeaveGroups(new string[] { gjid });
}
public void SendLeaveGroups(IEnumerable<string> gjids)
{
string id = TicketCounter.MakeId();
IEnumerable<ProtocolTreeNode> innerChilds = from gjid in gjids select new ProtocolTreeNode("group", new[] { new KeyValue("id", gjid) });
var child = new ProtocolTreeNode("leave", null, innerChilds);
var node = new ProtocolTreeNode("iq", new KeyValue[] { new KeyValue("id", id), new KeyValue("type", "set"), new KeyValue("xmlns", "w:g2"), new KeyValue("to", "g.us") }, child);
this.SendNode(node);
}
public void SendMessage(FMessage message, bool hidden = false)
{
if (message.media_wa_type != FMessage.Type.Undefined)
{
this.SendMessageWithMedia(message);
}
else
{
this.SendMessageWithBody(message, hidden);
}
}
public void SendMessageBroadcast(string[] to, string message)
{
this.SendMessageBroadcast(to, new FMessage(string.Empty, true) { data = message, media_wa_type = FMessage.Type.Undefined });
}
public void SendMessageBroadcastImage(string[] recipients, byte[] ImageData, ImageType imgtype)
{
string to;
List<string> foo = new List<string>();
foreach (string s in recipients)
{
foo.Add(GetJID(s));
}
to = string.Join(",", foo.ToArray());
FMessage msg = this.getFmessageImage(to, ImageData, imgtype);
if (msg != null)
{
this.SendMessage(msg);
}
}
public void SendMessageBroadcastAudio(string[] recipients, byte[] AudioData, AudioType audtype)
{
string to;
List<string> foo = new List<string>();
foreach (string s in recipients)
{
foo.Add(GetJID(s));
}
to = string.Join(",", foo.ToArray());
FMessage msg = this.getFmessageAudio(to, AudioData, audtype);
if (msg != null)
{
this.SendMessage(msg);
}
}
public void SendMessageBroadcastVideo(string[] recipients, byte[] VideoData, VideoType vidtype)
{
string to;
List<string> foo = new List<string>();
foreach (string s in recipients)
{
foo.Add(GetJID(s));
}
to = string.Join(",", foo.ToArray());
FMessage msg = this.getFmessageVideo(to, VideoData, vidtype);
if (msg != null)
{
this.SendMessage(msg);
}
}
public void SendMessageBroadcast(string[] to, FMessage message)
{
if (to != null && to.Length > 0 && message != null && !string.IsNullOrEmpty(message.data))
{
ProtocolTreeNode child;
if (message.media_wa_type == FMessage.Type.Undefined)
{
//text broadcast
child = new ProtocolTreeNode("body", null, null, WhatsApp.SYSEncoding.GetBytes(message.data));
}
else
{
throw new NotImplementedException();
}
List<ProtocolTreeNode> toNodes = new List<ProtocolTreeNode>();
foreach (string target in to)
{
toNodes.Add(new ProtocolTreeNode("to", new KeyValue[] { new KeyValue("jid", WhatsAppApi.WhatsApp.GetJID(target)) }));
}
ProtocolTreeNode broadcastNode = new ProtocolTreeNode("broadcast", null, toNodes);
Int32 unixTimestamp = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
ProtocolTreeNode messageNode = new ProtocolTreeNode("message", new KeyValue[] {
new KeyValue("to", unixTimestamp.ToString() + "@broadcast"),
new KeyValue("type", message.media_wa_type == FMessage.Type.Undefined?"text":"media"),
new KeyValue("id", message.identifier_key.id)
}, new ProtocolTreeNode[] {
broadcastNode,
child
});
this.SendNode(messageNode);
}
}
public void SendNop()
{
this.SendNode(null);
}
public void SendPaused(string to)
{
this.SendChatState(to, "paused");
}
public void SendPing()
{
string id = TicketCounter.MakeId();
var child = new ProtocolTreeNode("ping", null);
var node = new ProtocolTreeNode("iq", new[] { new KeyValue("id", id), new KeyValue("xmlns", "w:p"), new KeyValue("type", "get"), new KeyValue("to", "s.whatsapp.net") }, child);
this.SendNode(node);
}
public void SendPresenceSubscriptionRequest(string to)
{
var node = new ProtocolTreeNode("presence", new[] { new KeyValue("type", "subscribe"), new KeyValue("to", GetJID(to)) });
this.SendNode(node);
}
public void SendQueryLastOnline(string jid)
{
string id = TicketCounter.MakeId();
var child = new ProtocolTreeNode("query", null);
var node = new ProtocolTreeNode("iq", new[] { new KeyValue("id", id), new KeyValue("type", "get"), new KeyValue("to", GetJID(jid)), new KeyValue("xmlns", "jabber:iq:last") }, child);
this.SendNode(node);
}
public void SendRemoveParticipants(string gjid, List<string> participants)
{
string id = TicketCounter.MakeId();
this.SendVerbParticipants(gjid, participants, id, "remove");
}
public void SendSetGroupSubject(string gjid, string subject)
{
string id = TicketCounter.MakeId();
var child = new ProtocolTreeNode("subject", new[] { new KeyValue("value", subject) });
var node = new ProtocolTreeNode("iq", new[] { new KeyValue("id", id), new KeyValue("type", "set"), new KeyValue("xmlns", "w:g2"), new KeyValue("to", gjid) }, child);
this.SendNode(node);
}
public void SendSetPhoto(string jid, byte[] bytes, byte[] thumbnailBytes = null)
{
string id = TicketCounter.MakeId();
bytes = this.ProcessProfilePicture(bytes);
var list = new List<ProtocolTreeNode> { new ProtocolTreeNode("picture", null, null, bytes) };
if (thumbnailBytes == null)
{
//auto generate
thumbnailBytes = this.CreateThumbnail(bytes);
}
//debug
System.IO.File.WriteAllBytes("pic.jpg", bytes);
System.IO.File.WriteAllBytes("picthumb.jpg", thumbnailBytes);
if (thumbnailBytes != null)
{
list.Add(new ProtocolTreeNode("picture", new[] { new KeyValue("type", "preview") }, null, thumbnailBytes));
}
var node = new ProtocolTreeNode("iq", new[] { new KeyValue("id", id), new KeyValue("type", "set"), new KeyValue("xmlns", "w:profile:picture"), new KeyValue("to", GetJID(jid)) }, list.ToArray());
this.SendNode(node);
}
public void SendSetPrivacyBlockedList(IEnumerable<string> jidSet)
{
string id = TicketCounter.MakeId();
ProtocolTreeNode[] nodeArray = Enumerable.Select<string, ProtocolTreeNode>(jidSet, (Func<string, int, ProtocolTreeNode>)((jid, index) => new ProtocolTreeNode("item", new KeyValue[] { new KeyValue("type", "jid"), new KeyValue("value", jid), new KeyValue("action", "deny"), new KeyValue("order", index.ToString(CultureInfo.InvariantCulture)) }))).ToArray<ProtocolTreeNode>();
var child = new ProtocolTreeNode("list", new KeyValue[] { new KeyValue("name", "default") }, (nodeArray.Length == 0) ? null : nodeArray);
var node2 = new ProtocolTreeNode("query", null, child);
var node3 = new ProtocolTreeNode("iq", new KeyValue[] { new KeyValue("id", id), new KeyValue("type", "set"), new KeyValue("xmlns", "jabber:iq:privacy") }, node2);
this.SendNode(node3);
}
public void SendStatusUpdate(string status)
{
string id = TicketCounter.MakeId();
ProtocolTreeNode node = new ProtocolTreeNode("iq", new KeyValue[] {
new KeyValue("to", "s.whatsapp.net"),
new KeyValue("type", "set"),
new KeyValue("id", id),
new KeyValue("xmlns", "status")
},
new [] {
new ProtocolTreeNode("status", null, System.Text.Encoding.UTF8.GetBytes(status))
});
this.SendNode(node);
}
public void SendSubjectReceived(string to, string id)
{
var child = new ProtocolTreeNode("received", new[] { new KeyValue("xmlns", "urn:xmpp:receipts") });
var node = GetSubjectMessage(to, id, child);
this.SendNode(node);
}
public void SendUnsubscribeHim(string jid)
{
var node = new ProtocolTreeNode("presence", new[] { new KeyValue("type", "unsubscribed"), new KeyValue("to", jid) });
this.SendNode(node);
}
public void SendUnsubscribeMe(string jid)
{
var node = new ProtocolTreeNode("presence", new[] { new KeyValue("type", "unsubscribe"), new KeyValue("to", jid) });
this.SendNode(node);
}
public void SendGetGroups(string id, string type)
{
var child = new ProtocolTreeNode(type, null);
var node = new ProtocolTreeNode("iq", new[] { new KeyValue("id", id), new KeyValue("type", "get"), new KeyValue("xmlns", "w:g2"), new KeyValue("to", "g.us") }, child);
this.SendNode(node);
}
protected void SendMessageWithBody(FMessage message, bool hidden = false)
{
var child = new ProtocolTreeNode("body", null, null, WhatsApp.SYSEncoding.GetBytes(message.data));
this.SendNode(GetMessageNode(message, child, hidden));
}
protected void SendMessageWithMedia(FMessage message)
{
ProtocolTreeNode node;
if (FMessage.Type.System == message.media_wa_type)
{
throw new SystemException("Cannot send system message over the network");
}
List<KeyValue> list = new List<KeyValue>(new KeyValue[] { new KeyValue("xmlns", "urn:xmpp:whatsapp:mms"), new KeyValue("type", FMessage.GetMessage_WA_Type_StrValue(message.media_wa_type)) });
if (FMessage.Type.Location == message.media_wa_type)
{
list.AddRange(new KeyValue[] { new KeyValue("latitude", message.latitude.ToString(CultureInfo.InvariantCulture)), new KeyValue("longitude", message.longitude.ToString(CultureInfo.InvariantCulture)) });
if (message.location_details != null)
{
list.Add(new KeyValue("name", message.location_details));
}
if (message.location_url != null)
{
list.Add(new KeyValue("url", message.location_url));
}
}
else if (((FMessage.Type.Contact != message.media_wa_type) && (message.media_name != null)) && ((message.media_url != null) && (message.media_size > 0L)))
{
list.AddRange(new KeyValue[] { new KeyValue("file", message.media_name), new KeyValue("size", message.media_size.ToString(CultureInfo.InvariantCulture)), new KeyValue("url", message.media_url) });
if (message.media_duration_seconds > 0)
{
list.Add(new KeyValue("seconds", message.media_duration_seconds.ToString(CultureInfo.InvariantCulture)));
}
}
if ((FMessage.Type.Contact == message.media_wa_type) && (message.media_name != null))
{
node = new ProtocolTreeNode("media", list.ToArray(), new ProtocolTreeNode("vcard", new KeyValue[] { new KeyValue("name", message.media_name) }, WhatsApp.SYSEncoding.GetBytes(message.data)));
}
else
{
byte[] data = message.binary_data;
if ((data == null) && !string.IsNullOrEmpty(message.data))
{
try
{
data = Convert.FromBase64String(message.data);
}
catch (Exception)
{
}
}
if (data != null)
{
list.Add(new KeyValue("encoding", "raw"));
}
node = new ProtocolTreeNode("media", list.ToArray(), null, data);
}
this.SendNode(GetMessageNode(message, node));
}
protected void SendVerbParticipants(string gjid, IEnumerable<string> participants, string id, string inner_tag)
{
IEnumerable<ProtocolTreeNode> source = from jid in participants select new ProtocolTreeNode("participant", new[] { new KeyValue("jid", GetJID(jid)) });
var child = new ProtocolTreeNode(inner_tag, null, source);
var node = new ProtocolTreeNode("iq", new[] { new KeyValue("id", id), new KeyValue("type", "set"), new KeyValue("xmlns", "w:g2"), new KeyValue("to", GetJID(gjid)) }, child);
this.SendNode(node);
}
public void SendSetPrivacySetting(VisibilityCategory category, VisibilitySetting setting)
{
ProtocolTreeNode node = new ProtocolTreeNode("iq", new[] {
new KeyValue("to", "s.whatsapp.net"),
new KeyValue("id", TicketCounter.MakeId()),
new KeyValue("type", "set"),
new KeyValue("xmlns", "privacy")
}, new ProtocolTreeNode[] {
new ProtocolTreeNode("privacy", null, new ProtocolTreeNode[] {
new ProtocolTreeNode("category", new [] {
new KeyValue("name", this.privacyCategoryToString(category)),
new KeyValue("value", this.privacySettingToString(setting))
})
})
});
this.SendNode(node);
}
public void SendGetPrivacySettings()
{
ProtocolTreeNode node = new ProtocolTreeNode("iq", new KeyValue[] {
new KeyValue("to", "s.whatsapp.net"),
new KeyValue("id", TicketCounter.MakeId()),
new KeyValue("type", "get"),
new KeyValue("xmlns", "privacy")
}, new ProtocolTreeNode[] {
new ProtocolTreeNode("privacy", null)
});
this.SendNode(node);
}
protected IEnumerable<ProtocolTreeNode> ProcessGroupSettings(IEnumerable<GroupSetting> groups)
{
ProtocolTreeNode[] nodeArray = null;
if ((groups != null) && groups.Any<GroupSetting>())
{
DateTime now = DateTime.Now;
nodeArray = (from @group in groups
select new ProtocolTreeNode("item", new[]
{ new KeyValue("jid", @group.Jid),
new KeyValue("notify", @group.Enabled ? "1" : "0"),
new KeyValue("mute", string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}", new object[] { (!@group.MuteExpiry.HasValue || (@group.MuteExpiry.Value <= now)) ? 0 : ((int) (@group.MuteExpiry.Value - now).TotalSeconds) })) })).ToArray<ProtocolTreeNode>();
}
return nodeArray;
}
protected static ProtocolTreeNode GetMessageNode(FMessage message, ProtocolTreeNode pNode, bool hidden = false)
{
Int32 unixTimestamp = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
return new ProtocolTreeNode("message", new[] {
new KeyValue("to", message.identifier_key.remote_jid),
new KeyValue("type", message.media_wa_type == FMessage.Type.Undefined?"text":"media"),
new KeyValue("id", message.identifier_key.id),
new KeyValue("t",unixTimestamp.ToString())
},
new ProtocolTreeNode[] {
pNode
});
}
protected static ProtocolTreeNode GetSubjectMessage(string to, string id, ProtocolTreeNode child)
{
return new ProtocolTreeNode("message", new[] { new KeyValue("to", to), new KeyValue("type", "subject"), new KeyValue("id", id) }, child);
}
}
}
| |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
*
* ***************************************************************************/
#if !CLR2
#else
using Microsoft.Scripting.Ast;
#endif
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Collections.Generic;
namespace System.Management.Automation.Interpreter
{
internal interface IBoxableInstruction
{
Instruction BoxIfIndexMatches(int index);
}
internal abstract class LocalAccessInstruction : Instruction
{
internal readonly int _index;
protected LocalAccessInstruction(int index)
{
_index = index;
}
public override string ToDebugString(int instructionIndex, object cookie, Func<int, int> labelIndexer, IList<object> objects)
{
return cookie == null ?
InstructionName + "(" + _index + ")" :
InstructionName + "(" + cookie + ": " + _index + ")";
}
}
#region Load
internal sealed class LoadLocalInstruction : LocalAccessInstruction, IBoxableInstruction
{
internal LoadLocalInstruction(int index)
: base(index)
{
}
public override int ProducedStack { get { return 1; } }
public override int Run(InterpretedFrame frame)
{
frame.Data[frame.StackIndex++] = frame.Data[_index];
//frame.Push(frame.Data[_index]);
return +1;
}
public Instruction BoxIfIndexMatches(int index)
{
return (index == _index) ? InstructionList.LoadLocalBoxed(index) : null;
}
}
internal sealed class LoadLocalBoxedInstruction : LocalAccessInstruction
{
internal LoadLocalBoxedInstruction(int index)
: base(index)
{
}
public override int ProducedStack { get { return 1; } }
public override int Run(InterpretedFrame frame)
{
var box = (StrongBox<object>)frame.Data[_index];
frame.Data[frame.StackIndex++] = box.Value;
return +1;
}
}
internal sealed class LoadLocalFromClosureInstruction : LocalAccessInstruction
{
internal LoadLocalFromClosureInstruction(int index)
: base(index)
{
}
public override int ProducedStack { get { return 1; } }
public override int Run(InterpretedFrame frame)
{
var box = frame.Closure[_index];
frame.Data[frame.StackIndex++] = box.Value;
return +1;
}
}
internal sealed class LoadLocalFromClosureBoxedInstruction : LocalAccessInstruction
{
internal LoadLocalFromClosureBoxedInstruction(int index)
: base(index)
{
}
public override int ProducedStack { get { return 1; } }
public override int Run(InterpretedFrame frame)
{
var box = frame.Closure[_index];
frame.Data[frame.StackIndex++] = box;
return +1;
}
}
#endregion
#region Store, Assign
internal sealed class AssignLocalInstruction : LocalAccessInstruction, IBoxableInstruction
{
internal AssignLocalInstruction(int index)
: base(index)
{
}
public override int ConsumedStack { get { return 1; } }
public override int ProducedStack { get { return 1; } }
public override int Run(InterpretedFrame frame)
{
frame.Data[_index] = frame.Peek();
return +1;
}
public Instruction BoxIfIndexMatches(int index)
{
return (index == _index) ? InstructionList.AssignLocalBoxed(index) : null;
}
}
internal sealed class StoreLocalInstruction : LocalAccessInstruction, IBoxableInstruction
{
internal StoreLocalInstruction(int index)
: base(index)
{
}
public override int ConsumedStack { get { return 1; } }
public override int Run(InterpretedFrame frame)
{
frame.Data[_index] = frame.Data[--frame.StackIndex];
//frame.Data[_index] = frame.Pop();
return +1;
}
public Instruction BoxIfIndexMatches(int index)
{
return (index == _index) ? InstructionList.StoreLocalBoxed(index) : null;
}
}
internal sealed class AssignLocalBoxedInstruction : LocalAccessInstruction
{
internal AssignLocalBoxedInstruction(int index)
: base(index)
{
}
public override int ConsumedStack { get { return 1; } }
public override int ProducedStack { get { return 1; } }
public override int Run(InterpretedFrame frame)
{
var box = (StrongBox<object>)frame.Data[_index];
box.Value = frame.Peek();
return +1;
}
}
internal sealed class StoreLocalBoxedInstruction : LocalAccessInstruction
{
internal StoreLocalBoxedInstruction(int index)
: base(index)
{
}
public override int ConsumedStack { get { return 1; } }
public override int ProducedStack { get { return 0; } }
public override int Run(InterpretedFrame frame)
{
var box = (StrongBox<object>)frame.Data[_index];
box.Value = frame.Data[--frame.StackIndex];
return +1;
}
}
internal sealed class AssignLocalToClosureInstruction : LocalAccessInstruction
{
internal AssignLocalToClosureInstruction(int index)
: base(index)
{
}
public override int ConsumedStack { get { return 1; } }
public override int ProducedStack { get { return 1; } }
public override int Run(InterpretedFrame frame)
{
var box = frame.Closure[_index];
box.Value = frame.Peek();
return +1;
}
}
#endregion
#region Initialize
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1012:AbstractTypesShouldNotHaveConstructors")]
internal abstract class InitializeLocalInstruction : LocalAccessInstruction
{
internal InitializeLocalInstruction(int index)
: base(index)
{
}
internal sealed class Reference : InitializeLocalInstruction, IBoxableInstruction
{
internal Reference(int index)
: base(index)
{
}
public override int Run(InterpretedFrame frame)
{
frame.Data[_index] = null;
return 1;
}
public Instruction BoxIfIndexMatches(int index)
{
return (index == _index) ? InstructionList.InitImmutableRefBox(index) : null;
}
public override string InstructionName
{
get { return "InitRef"; }
}
}
internal sealed class ImmutableValue : InitializeLocalInstruction, IBoxableInstruction
{
private readonly object _defaultValue;
internal ImmutableValue(int index, object defaultValue)
: base(index)
{
_defaultValue = defaultValue;
}
public override int Run(InterpretedFrame frame)
{
frame.Data[_index] = _defaultValue;
return 1;
}
public Instruction BoxIfIndexMatches(int index)
{
return (index == _index) ? new ImmutableBox(index, _defaultValue) : null;
}
public override string InstructionName
{
get { return "InitImmutableValue"; }
}
}
internal sealed class ImmutableBox : InitializeLocalInstruction
{
// immutable value:
private readonly object _defaultValue;
internal ImmutableBox(int index, object defaultValue)
: base(index)
{
_defaultValue = defaultValue;
}
public override int Run(InterpretedFrame frame)
{
frame.Data[_index] = new StrongBox<object>(_defaultValue);
return 1;
}
public override string InstructionName
{
get { return "InitImmutableBox"; }
}
}
internal sealed class ParameterBox : InitializeLocalInstruction
{
public ParameterBox(int index)
: base(index)
{
}
public override int Run(InterpretedFrame frame)
{
frame.Data[_index] = new StrongBox<object>(frame.Data[_index]);
return 1;
}
}
internal sealed class Parameter : InitializeLocalInstruction, IBoxableInstruction
{
internal Parameter(int index)
: base(index)
{
}
public override int Run(InterpretedFrame frame)
{
// nop
return 1;
}
public Instruction BoxIfIndexMatches(int index)
{
if (index == _index)
{
return InstructionList.ParameterBox(index);
}
return null;
}
public override string InstructionName
{
get { return "InitParameter"; }
}
}
internal sealed class MutableValue : InitializeLocalInstruction, IBoxableInstruction
{
private readonly Type _type;
internal MutableValue(int index, Type type)
: base(index)
{
_type = type;
}
public override int Run(InterpretedFrame frame)
{
try
{
frame.Data[_index] = Activator.CreateInstance(_type);
}
catch (TargetInvocationException e)
{
ExceptionHelpers.UpdateForRethrow(e.InnerException);
throw e.InnerException;
}
return 1;
}
public Instruction BoxIfIndexMatches(int index)
{
return (index == _index) ? new MutableBox(index, _type) : null;
}
public override string InstructionName
{
get { return "InitMutableValue"; }
}
}
internal sealed class MutableBox : InitializeLocalInstruction
{
private readonly Type _type;
internal MutableBox(int index, Type type)
: base(index)
{
_type = type;
}
public override int Run(InterpretedFrame frame)
{
frame.Data[_index] = new StrongBox<object>(Activator.CreateInstance(_type));
return 1;
}
public override string InstructionName
{
get { return "InitMutableBox"; }
}
}
}
#endregion
#region RuntimeVariables
internal sealed class RuntimeVariablesInstruction : Instruction
{
private readonly int _count;
public RuntimeVariablesInstruction(int count)
{
_count = count;
}
public override int ProducedStack { get { return 1; } }
public override int ConsumedStack { get { return _count; } }
public override int Run(InterpretedFrame frame)
{
var ret = new IStrongBox[_count];
for (int i = ret.Length - 1; i >= 0; i--)
{
ret[i] = (IStrongBox)frame.Pop();
}
frame.Push(RuntimeVariables.Create(ret));
return +1;
}
public override string ToString()
{
return "GetRuntimeVariables()";
}
}
#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.Runtime.InteropServices;
using System.Globalization;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
namespace System.Data.SqlTypes
{
/// <summary>
/// Represents the date and time data ranging in value
/// from January 1, 1753 to December 31, 9999 to an accuracy of 3.33 milliseconds
/// to be stored in or retrieved from a database.
/// </summary>
[Serializable]
[StructLayout(LayoutKind.Sequential)]
[XmlSchemaProvider("GetXsdType")]
[System.Runtime.CompilerServices.TypeForwardedFrom("System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public struct SqlDateTime : INullable, IComparable, IXmlSerializable
{
private bool m_fNotNull; // false if null. Do not rename (binary serialization)
private int m_day; // Day from 1900/1/1, could be negative. Range: Jan 1 1753 - Dec 31 9999. Do not rename (binary serialization)
private int m_time; // Time in the day in term of ticks. Do not rename (binary serialization)
// Constants
// Number of (100ns) ticks per time unit
private static readonly double s_SQLTicksPerMillisecond = 0.3;
public static readonly int SQLTicksPerSecond = 300;
public static readonly int SQLTicksPerMinute = SQLTicksPerSecond * 60;
public static readonly int SQLTicksPerHour = SQLTicksPerMinute * 60;
private static readonly int s_SQLTicksPerDay = SQLTicksPerHour * 24;
private static readonly long s_ticksPerSecond = TimeSpan.TicksPerMillisecond * 1000;
private static readonly DateTime s_SQLBaseDate = new DateTime(1900, 1, 1);
private static readonly long s_SQLBaseDateTicks = s_SQLBaseDate.Ticks;
private static readonly int s_minYear = 1753; // Jan 1 1753
private static readonly int s_maxYear = 9999; // Dec 31 9999
private static readonly int s_minDay = -53690; // Jan 1 1753
private static readonly int s_maxDay = 2958463; // Dec 31 9999 is this many days from Jan 1 1900
private static readonly int s_minTime = 0; // 00:00:0:000PM
private static readonly int s_maxTime = s_SQLTicksPerDay - 1; // = 25919999, 11:59:59:997PM
private static readonly int s_dayBase = 693595; // Jan 1 1900 is this many days from Jan 1 0001
private static readonly int[] s_daysToMonth365 = new int[] {
0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365};
private static readonly int[] s_daysToMonth366 = new int[] {
0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366};
private static readonly DateTime s_minDateTime = new DateTime(1753, 1, 1);
private static readonly DateTime s_maxDateTime = DateTime.MaxValue;
private static readonly TimeSpan s_minTimeSpan = s_minDateTime.Subtract(s_SQLBaseDate);
private static readonly TimeSpan s_maxTimeSpan = s_maxDateTime.Subtract(s_SQLBaseDate);
private static readonly string s_ISO8601_DateTimeFormat = "yyyy-MM-ddTHH:mm:ss.fff";
// These formats are valid styles in SQL Server (style 9, 12, 13, 14)
// but couldn't be recognized by the default parse. Needs to call
// ParseExact in addition to recognize them.
private static readonly string[] s_dateTimeFormats = {
"MMM d yyyy hh:mm:ss:ffftt",
"MMM d yyyy hh:mm:ss:fff",
"d MMM yyyy hh:mm:ss:ffftt",
"d MMM yyyy hh:mm:ss:fff",
"hh:mm:ss:ffftt",
"hh:mm:ss:fff",
"yyMMdd",
"yyyyMMdd"
};
private const DateTimeStyles x_DateTimeStyle = DateTimeStyles.AllowWhiteSpaces;
// construct a Null
private SqlDateTime(bool fNull)
{
m_fNotNull = false;
m_day = 0;
m_time = 0;
}
public SqlDateTime(DateTime value)
{
this = FromDateTime(value);
}
public SqlDateTime(int year, int month, int day)
: this(year, month, day, 0, 0, 0, 0.0)
{
}
public SqlDateTime(int year, int month, int day, int hour, int minute, int second)
: this(year, month, day, hour, minute, second, 0.0)
{
}
public SqlDateTime(int year, int month, int day, int hour, int minute, int second, double millisecond)
{
if (year >= s_minYear && year <= s_maxYear && month >= 1 && month <= 12)
{
int[] days = IsLeapYear(year) ? s_daysToMonth366 : s_daysToMonth365;
if (day >= 1 && day <= days[month] - days[month - 1])
{
int y = year - 1;
int dayticks = y * 365 + y / 4 - y / 100 + y / 400 + days[month - 1] + day - 1;
dayticks -= s_dayBase;
if (dayticks >= s_minDay && dayticks <= s_maxDay &&
hour >= 0 && hour < 24 && minute >= 0 && minute < 60 &&
second >= 0 && second < 60 && millisecond >= 0 && millisecond < 1000.0)
{
double ticksForMilisecond = millisecond * s_SQLTicksPerMillisecond + 0.5;
int timeticks = hour * SQLTicksPerHour + minute * SQLTicksPerMinute + second * SQLTicksPerSecond +
(int)ticksForMilisecond;
if (timeticks > s_maxTime)
{
// Only rounding up could cause time to become greater than MaxTime.
Debug.Assert(timeticks == s_maxTime + 1);
// Make time to be zero, and increment day.
timeticks = 0;
dayticks++;
}
// Success. Call ctor here which will again check dayticks and timeticks are within range.
// All other cases will throw exception below.
this = new SqlDateTime(dayticks, timeticks);
return;
}
}
}
throw new SqlTypeException(SQLResource.InvalidDateTimeMessage);
}
// constructor that take DBTIMESTAMP data members
// Note: bilisecond is same as 'fraction' in DBTIMESTAMP
public SqlDateTime(int year, int month, int day, int hour, int minute, int second, int bilisecond)
: this(year, month, day, hour, minute, second, bilisecond / 1000.0)
{
}
public SqlDateTime(int dayTicks, int timeTicks)
{
if (dayTicks < s_minDay || dayTicks > s_maxDay || timeTicks < s_minTime || timeTicks > s_maxTime)
{
m_fNotNull = false;
throw new OverflowException(SQLResource.DateTimeOverflowMessage);
}
m_day = dayTicks;
m_time = timeTicks;
m_fNotNull = true;
}
internal SqlDateTime(double dblVal)
{
if ((dblVal < s_minDay) || (dblVal >= s_maxDay + 1))
throw new OverflowException(SQLResource.DateTimeOverflowMessage);
int day = (int)dblVal;
int time = (int)((dblVal - day) * s_SQLTicksPerDay);
// Check if we need to borrow a day from the day portion.
if (time < 0)
{
day--;
time += s_SQLTicksPerDay;
}
else if (time >= s_SQLTicksPerDay)
{
// Deal with case where time portion = 24 hrs.
//
// ISSUE: Is this code reachable? For this code to be reached there
// must be a value for dblVal such that:
// dblVal - (long)dblVal = 1.0
// This seems odd, but there was a bug that resulted because
// there was a negative value for dblVal such that dblVal + 1.0 = 1.0
//
day++;
time -= s_SQLTicksPerDay;
}
this = new SqlDateTime(day, time);
}
// INullable
public bool IsNull
{
get { return !m_fNotNull; }
}
private static TimeSpan ToTimeSpan(SqlDateTime value)
{
long millisecond = (long)(value.m_time / s_SQLTicksPerMillisecond + 0.5);
return new TimeSpan(value.m_day * TimeSpan.TicksPerDay +
millisecond * TimeSpan.TicksPerMillisecond);
}
private static DateTime ToDateTime(SqlDateTime value)
{
return s_SQLBaseDate.Add(ToTimeSpan(value));
}
// Used by SqlBuffer in SqlClient.
internal static DateTime ToDateTime(int daypart, int timepart)
{
if (daypart < s_minDay || daypart > s_maxDay || timepart < s_minTime || timepart > s_maxTime)
{
throw new OverflowException(SQLResource.DateTimeOverflowMessage);
}
long dayticks = daypart * TimeSpan.TicksPerDay;
long timeticks = ((long)(timepart / s_SQLTicksPerMillisecond + 0.5)) * TimeSpan.TicksPerMillisecond;
DateTime result = new DateTime(s_SQLBaseDateTicks + dayticks + timeticks);
return result;
}
// Convert from TimeSpan, rounded to one three-hundredth second, due to loss of precision
private static SqlDateTime FromTimeSpan(TimeSpan value)
{
if (value < s_minTimeSpan || value > s_maxTimeSpan)
throw new SqlTypeException(SQLResource.DateTimeOverflowMessage);
int day = value.Days;
long ticks = value.Ticks - day * TimeSpan.TicksPerDay;
if (ticks < 0L)
{
day--;
ticks += TimeSpan.TicksPerDay;
}
int time = (int)((double)ticks / TimeSpan.TicksPerMillisecond * s_SQLTicksPerMillisecond + 0.5);
if (time > s_maxTime)
{
// Only rounding up could cause time to become greater than MaxTime.
Debug.Assert(time == s_maxTime + 1);
// Make time to be zero, and increment day.
time = 0;
day++;
}
return new SqlDateTime(day, time);
}
private static SqlDateTime FromDateTime(DateTime value)
{
// SqlDateTime has smaller precision and range than DateTime.
// Usually we round the DateTime value to the nearest SqlDateTime value.
// but for DateTime.MaxValue, if we round it up, it will overflow.
// Although the overflow would be the correct behavior, we simply
// returned SqlDateTime.MaxValue in v1. In order not to break exisiting
// code, we'll keep this logic.
//
if (value == DateTime.MaxValue)
return SqlDateTime.MaxValue;
return FromTimeSpan(value.Subtract(s_SQLBaseDate));
}
/*
internal static SqlDateTime FromDouble(double dblVal) {
return new SqlDateTime(dblVal);
}
internal static double ToDouble(SqlDateTime x) {
AssertValidSqlDateTime(x);
return(double)x.m_day + ((double)x.m_time / (double)SQLTicksPerDay);
}
internal static int ToInt(SqlDateTime x) {
AssertValidSqlDateTime(x);
return x.m_time >= MaxTime / 2 ? x.m_day + 1 : x.m_day;
}
*/
// do we still want to define a property of DateTime? If the user uses it often, it is expensive
// property: Value
public DateTime Value
{
get
{
if (m_fNotNull)
return ToDateTime(this);
else
throw new SqlNullValueException();
}
}
// Day ticks -- returns number of days since 1/1/1900
public int DayTicks
{
get
{
if (m_fNotNull)
return m_day;
else
throw new SqlNullValueException();
}
}
// Time ticks -- return daily time in unit of 1/300 second
public int TimeTicks
{
get
{
if (m_fNotNull)
return m_time;
else
throw new SqlNullValueException();
}
}
// Implicit conversion from DateTime to SqlDateTime
public static implicit operator SqlDateTime(DateTime value)
{
return new SqlDateTime(value);
}
// Explicit conversion from SqlDateTime to int. Returns 0 if x is Null.
public static explicit operator DateTime(SqlDateTime x)
{
return ToDateTime(x);
}
// Return string representation of SqlDateTime
public override string ToString()
{
if (IsNull)
return SQLResource.NullString;
DateTime dateTime = ToDateTime(this);
return dateTime.ToString((IFormatProvider)null);
}
public static SqlDateTime Parse(string s)
{
DateTime dt;
if (s == SQLResource.NullString)
return SqlDateTime.Null;
try
{
dt = DateTime.Parse(s, CultureInfo.InvariantCulture);
}
catch (FormatException)
{
DateTimeFormatInfo dtfi = (DateTimeFormatInfo)(CultureInfo.CurrentCulture.GetFormat(typeof(DateTimeFormatInfo)));
dt = DateTime.ParseExact(s, s_dateTimeFormats, dtfi, x_DateTimeStyle);
}
return new SqlDateTime(dt);
}
// Binary operators
// Arithmetic operators
// Alternative method: SqlDateTime.Add
public static SqlDateTime operator +(SqlDateTime x, TimeSpan t)
{
return x.IsNull ? Null : FromDateTime(ToDateTime(x) + t);
}
// Alternative method: SqlDateTime.Subtract
public static SqlDateTime operator -(SqlDateTime x, TimeSpan t)
{
return x.IsNull ? Null : FromDateTime(ToDateTime(x) - t);
}
//--------------------------------------------------
// Alternative methods for overloaded operators
//--------------------------------------------------
// Alternative method for operator +
public static SqlDateTime Add(SqlDateTime x, TimeSpan t)
{
return x + t;
}
// Alternative method for operator -
public static SqlDateTime Subtract(SqlDateTime x, TimeSpan t)
{
return x - t;
}
/*
// Implicit conversions
// Implicit conversion from SqlBoolean to SqlDateTime
public static implicit operator SqlDateTime(SqlBoolean x)
{
return x.IsNull ? Null : new SqlDateTime(x.Value, 0);
}
// Implicit conversion from SqlInt32 to SqlDateTime
public static implicit operator SqlDateTime(SqlInt32 x)
{
return x.IsNull ? Null : new SqlDateTime(x.Value, 0);
}
// Implicit conversion from SqlMoney to SqlDateTime
public static implicit operator SqlDateTime(SqlMoney x)
{
return x.IsNull ? Null : SqlDateTime.FromDouble(x.ToDouble());
}
// Explicit conversions
// Explicit conversion from SqlDateTime to SqlInt32
public static explicit operator SqlInt32(SqlDateTime x)
{
if (x.IsNull)
return SqlInt32.Null;
return new SqlInt32(SqlDateTime.ToInt(x));
}
// Explicit conversion from SqlDateTime to SqlBoolean
public static explicit operator SqlBoolean(SqlDateTime x)
{
if (x.IsNull)
return SqlBoolean.Null;
return new SqlBoolean(x.m_day != 0 || x.m_time != 0, false);
}
// Explicit conversion from SqlDateTime to SqlMoney
public static explicit operator SqlMoney(SqlDateTime x)
{
return x.IsNull ? SqlMoney.Null : new SqlMoney(SqlDateTime.ToDouble(x));
}
// Implicit conversion from SqlDouble to SqlDateTime
public static implicit operator SqlDateTime(SqlDouble x)
{
return x.IsNull ? Null : new SqlDateTime(x.Value);
}
// Explicit conversion from SqlDateTime to SqlDouble
public static explicit operator SqlDouble(SqlDateTime x)
{
return x.IsNull ? SqlDouble.Null : new SqlDouble(SqlDateTime.ToDouble(x));
}
// Implicit conversion from SqlDecimal to SqlDateTime
public static implicit operator SqlDateTime(SqlDecimal x)
{
return x.IsNull ? SqlDateTime.Null : new SqlDateTime(SqlDecimal.ToDouble(x));
}
// Explicit conversion from SqlDateTime to SqlDecimal
public static explicit operator SqlDecimal(SqlDateTime x)
{
return x.IsNull ? SqlDecimal.Null : new SqlDecimal(SqlDateTime.ToDouble(x));
}
*/
// Explicit conversion from SqlString to SqlDateTime
// Throws FormatException or OverflowException if necessary.
public static explicit operator SqlDateTime(SqlString x)
{
return x.IsNull ? SqlDateTime.Null : SqlDateTime.Parse(x.Value);
}
// Builtin functions
// utility functions
/*
private static void AssertValidSqlDateTime(SqlDateTime x) {
Debug.Assert(!x.IsNull, "!x.IsNull", "Datetime: Null");
Debug.Assert(x.m_day >= MinDay && x.m_day <= MaxDay, "day >= MinDay && day <= MaxDay",
"DateTime: Day out of range");
Debug.Assert(x.m_time >= MinTime && x.m_time <= MaxTime, "time >= MinTime && time <= MaxTime",
"DateTime: Time out of range");
}
*/
// Checks whether a given year is a leap year. This method returns true if
// "year" is a leap year, or false if not.
//
// @param year The year to check.
// @return true if "year" is a leap year, false otherwise.
//
private static bool IsLeapYear(int year)
{
return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
}
// Overloading comparison operators
public static SqlBoolean operator ==(SqlDateTime x, SqlDateTime y)
{
return (x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(x.m_day == y.m_day && x.m_time == y.m_time);
}
public static SqlBoolean operator !=(SqlDateTime x, SqlDateTime y)
{
return !(x == y);
}
public static SqlBoolean operator <(SqlDateTime x, SqlDateTime y)
{
return (x.IsNull || y.IsNull) ? SqlBoolean.Null :
new SqlBoolean(x.m_day < y.m_day || (x.m_day == y.m_day && x.m_time < y.m_time));
}
public static SqlBoolean operator >(SqlDateTime x, SqlDateTime y)
{
return (x.IsNull || y.IsNull) ? SqlBoolean.Null :
new SqlBoolean(x.m_day > y.m_day || (x.m_day == y.m_day && x.m_time > y.m_time));
}
public static SqlBoolean operator <=(SqlDateTime x, SqlDateTime y)
{
return (x.IsNull || y.IsNull) ? SqlBoolean.Null :
new SqlBoolean(x.m_day < y.m_day || (x.m_day == y.m_day && x.m_time <= y.m_time));
}
public static SqlBoolean operator >=(SqlDateTime x, SqlDateTime y)
{
return (x.IsNull || y.IsNull) ? SqlBoolean.Null :
new SqlBoolean(x.m_day > y.m_day || (x.m_day == y.m_day && x.m_time >= y.m_time));
}
//--------------------------------------------------
// Alternative methods for overloaded operators
//--------------------------------------------------
// Alternative method for operator ==
public static SqlBoolean Equals(SqlDateTime x, SqlDateTime y)
{
return (x == y);
}
// Alternative method for operator !=
public static SqlBoolean NotEquals(SqlDateTime x, SqlDateTime y)
{
return (x != y);
}
// Alternative method for operator <
public static SqlBoolean LessThan(SqlDateTime x, SqlDateTime y)
{
return (x < y);
}
// Alternative method for operator >
public static SqlBoolean GreaterThan(SqlDateTime x, SqlDateTime y)
{
return (x > y);
}
// Alternative method for operator <=
public static SqlBoolean LessThanOrEqual(SqlDateTime x, SqlDateTime y)
{
return (x <= y);
}
// Alternative method for operator >=
public static SqlBoolean GreaterThanOrEqual(SqlDateTime x, SqlDateTime y)
{
return (x >= y);
}
// Alternative method for conversions.
public SqlString ToSqlString()
{
return (SqlString)this;
}
// IComparable
// Compares this object to another object, returning an integer that
// indicates the relationship.
// Returns a value less than zero if this < object, zero if this = object,
// or a value greater than zero if this > object.
// null is considered to be less than any instance.
// If object is not of same type, this method throws an ArgumentException.
public int CompareTo(object value)
{
if (value is SqlDateTime)
{
SqlDateTime i = (SqlDateTime)value;
return CompareTo(i);
}
throw ADP.WrongType(value.GetType(), typeof(SqlDateTime));
}
public int CompareTo(SqlDateTime value)
{
// If both Null, consider them equal.
// Otherwise, Null is less than anything.
if (IsNull)
return value.IsNull ? 0 : -1;
else if (value.IsNull)
return 1;
if (this < value) return -1;
if (this > value) return 1;
return 0;
}
// Compares this instance with a specified object
public override bool Equals(object value)
{
if (!(value is SqlDateTime))
{
return false;
}
SqlDateTime i = (SqlDateTime)value;
if (i.IsNull || IsNull)
return (i.IsNull && IsNull);
else
return (this == i).Value;
}
// For hashing purpose
public override int GetHashCode()
{
return IsNull ? 0 : Value.GetHashCode();
}
XmlSchema IXmlSerializable.GetSchema() { return null; }
void IXmlSerializable.ReadXml(XmlReader reader)
{
string isNull = reader.GetAttribute("nil", XmlSchema.InstanceNamespace);
if (isNull != null && XmlConvert.ToBoolean(isNull))
{
// Read the next value.
reader.ReadElementString();
m_fNotNull = false;
}
else
{
DateTime dt = XmlConvert.ToDateTime(reader.ReadElementString(), XmlDateTimeSerializationMode.RoundtripKind);
// We do not support any kind of timezone information that is
// possibly included in the CLR DateTime, since SQL Server
// does not support TZ info. If any was specified, error out.
//
if (dt.Kind != System.DateTimeKind.Unspecified)
{
throw new SqlTypeException(SQLResource.TimeZoneSpecifiedMessage);
}
SqlDateTime st = FromDateTime(dt);
m_day = st.DayTicks;
m_time = st.TimeTicks;
m_fNotNull = true;
}
}
void IXmlSerializable.WriteXml(XmlWriter writer)
{
if (IsNull)
{
writer.WriteAttributeString("xsi", "nil", XmlSchema.InstanceNamespace, "true");
}
else
{
writer.WriteString(XmlConvert.ToString(Value, s_ISO8601_DateTimeFormat));
}
}
public static XmlQualifiedName GetXsdType(XmlSchemaSet schemaSet)
{
return new XmlQualifiedName("dateTime", XmlSchema.Namespace);
}
public static readonly SqlDateTime MinValue = new SqlDateTime(s_minDay, 0);
public static readonly SqlDateTime MaxValue = new SqlDateTime(s_maxDay, s_maxTime);
public static readonly SqlDateTime Null = new SqlDateTime(true);
} // SqlDateTime
} // namespace System.Data.SqlTypes
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/api/metric.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Google.Api {
/// <summary>Holder for reflection information generated from google/api/metric.proto</summary>
public static partial class MetricReflection {
#region Descriptor
/// <summary>File descriptor for google/api/metric.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static MetricReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Chdnb29nbGUvYXBpL21ldHJpYy5wcm90bxIKZ29vZ2xlLmFwaRoWZ29vZ2xl",
"L2FwaS9sYWJlbC5wcm90byLSAwoQTWV0cmljRGVzY3JpcHRvchIMCgRuYW1l",
"GAEgASgJEgwKBHR5cGUYCCABKAkSKwoGbGFiZWxzGAIgAygLMhsuZ29vZ2xl",
"LmFwaS5MYWJlbERlc2NyaXB0b3ISPAoLbWV0cmljX2tpbmQYAyABKA4yJy5n",
"b29nbGUuYXBpLk1ldHJpY0Rlc2NyaXB0b3IuTWV0cmljS2luZBI6Cgp2YWx1",
"ZV90eXBlGAQgASgOMiYuZ29vZ2xlLmFwaS5NZXRyaWNEZXNjcmlwdG9yLlZh",
"bHVlVHlwZRIMCgR1bml0GAUgASgJEhMKC2Rlc2NyaXB0aW9uGAYgASgJEhQK",
"DGRpc3BsYXlfbmFtZRgHIAEoCSJPCgpNZXRyaWNLaW5kEhsKF01FVFJJQ19L",
"SU5EX1VOU1BFQ0lGSUVEEAASCQoFR0FVR0UQARIJCgVERUxUQRACEg4KCkNV",
"TVVMQVRJVkUQAyJxCglWYWx1ZVR5cGUSGgoWVkFMVUVfVFlQRV9VTlNQRUNJ",
"RklFRBAAEggKBEJPT0wQARIJCgVJTlQ2NBACEgoKBkRPVUJMRRADEgoKBlNU",
"UklORxAEEhAKDERJU1RSSUJVVElPThAFEgkKBU1PTkVZEAYidQoGTWV0cmlj",
"EgwKBHR5cGUYAyABKAkSLgoGbGFiZWxzGAIgAygLMh4uZ29vZ2xlLmFwaS5N",
"ZXRyaWMuTGFiZWxzRW50cnkaLQoLTGFiZWxzRW50cnkSCwoDa2V5GAEgASgJ",
"Eg0KBXZhbHVlGAIgASgJOgI4AUJfCg5jb20uZ29vZ2xlLmFwaUILTWV0cmlj",
"UHJvdG9QAVo3Z29vZ2xlLmdvbGFuZy5vcmcvZ2VucHJvdG8vZ29vZ2xlYXBp",
"cy9hcGkvbWV0cmljO21ldHJpY6ICBEdBUEliBnByb3RvMw=="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::Google.Api.LabelReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Api.MetricDescriptor), global::Google.Api.MetricDescriptor.Parser, new[]{ "Name", "Type", "Labels", "MetricKind", "ValueType", "Unit", "Description", "DisplayName" }, null, new[]{ typeof(global::Google.Api.MetricDescriptor.Types.MetricKind), typeof(global::Google.Api.MetricDescriptor.Types.ValueType) }, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Api.Metric), global::Google.Api.Metric.Parser, new[]{ "Type", "Labels" }, null, null, new pbr::GeneratedClrTypeInfo[] { null, })
}));
}
#endregion
}
#region Messages
/// <summary>
/// Defines a metric type and its schema. Once a metric descriptor is created,
/// deleting or altering it stops data collection and makes the metric type's
/// existing data unusable.
/// </summary>
public sealed partial class MetricDescriptor : pb::IMessage<MetricDescriptor> {
private static readonly pb::MessageParser<MetricDescriptor> _parser = new pb::MessageParser<MetricDescriptor>(() => new MetricDescriptor());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<MetricDescriptor> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Api.MetricReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public MetricDescriptor() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public MetricDescriptor(MetricDescriptor other) : this() {
name_ = other.name_;
type_ = other.type_;
labels_ = other.labels_.Clone();
metricKind_ = other.metricKind_;
valueType_ = other.valueType_;
unit_ = other.unit_;
description_ = other.description_;
displayName_ = other.displayName_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public MetricDescriptor Clone() {
return new MetricDescriptor(this);
}
/// <summary>Field number for the "name" field.</summary>
public const int NameFieldNumber = 1;
private string name_ = "";
/// <summary>
/// The resource name of the metric descriptor. Depending on the
/// implementation, the name typically includes: (1) the parent resource name
/// that defines the scope of the metric type or of its data; and (2) the
/// metric's URL-encoded type, which also appears in the `type` field of this
/// descriptor. For example, following is the resource name of a custom
/// metric within the GCP project 123456789:
///
/// "projects/123456789/metricDescriptors/custom.googleapis.com%2Finvoice%2Fpaid%2Famount"
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Name {
get { return name_; }
set {
name_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "type" field.</summary>
public const int TypeFieldNumber = 8;
private string type_ = "";
/// <summary>
/// The metric type, including its DNS name prefix. The type is not
/// URL-encoded. All user-defined metric types have the DNS name
/// `custom.googleapis.com`. Metric types should use a natural hierarchical
/// grouping. For example:
///
/// "custom.googleapis.com/invoice/paid/amount"
/// "appengine.googleapis.com/http/server/response_latencies"
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Type {
get { return type_; }
set {
type_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "labels" field.</summary>
public const int LabelsFieldNumber = 2;
private static readonly pb::FieldCodec<global::Google.Api.LabelDescriptor> _repeated_labels_codec
= pb::FieldCodec.ForMessage(18, global::Google.Api.LabelDescriptor.Parser);
private readonly pbc::RepeatedField<global::Google.Api.LabelDescriptor> labels_ = new pbc::RepeatedField<global::Google.Api.LabelDescriptor>();
/// <summary>
/// The set of labels that can be used to describe a specific
/// instance of this metric type. For example, the
/// `appengine.googleapis.com/http/server/response_latencies` metric
/// type has a label for the HTTP response code, `response_code`, so
/// you can look at latencies for successful responses or just
/// for responses that failed.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::Google.Api.LabelDescriptor> Labels {
get { return labels_; }
}
/// <summary>Field number for the "metric_kind" field.</summary>
public const int MetricKindFieldNumber = 3;
private global::Google.Api.MetricDescriptor.Types.MetricKind metricKind_ = 0;
/// <summary>
/// Whether the metric records instantaneous values, changes to a value, etc.
/// Some combinations of `metric_kind` and `value_type` might not be supported.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Api.MetricDescriptor.Types.MetricKind MetricKind {
get { return metricKind_; }
set {
metricKind_ = value;
}
}
/// <summary>Field number for the "value_type" field.</summary>
public const int ValueTypeFieldNumber = 4;
private global::Google.Api.MetricDescriptor.Types.ValueType valueType_ = 0;
/// <summary>
/// Whether the measurement is an integer, a floating-point number, etc.
/// Some combinations of `metric_kind` and `value_type` might not be supported.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Api.MetricDescriptor.Types.ValueType ValueType {
get { return valueType_; }
set {
valueType_ = value;
}
}
/// <summary>Field number for the "unit" field.</summary>
public const int UnitFieldNumber = 5;
private string unit_ = "";
/// <summary>
/// The unit in which the metric value is reported. It is only applicable
/// if the `value_type` is `INT64`, `DOUBLE`, or `DISTRIBUTION`. The
/// supported units are a subset of [The Unified Code for Units of
/// Measure](http://unitsofmeasure.org/ucum.html) standard:
///
/// **Basic units (UNIT)**
///
/// * `bit` bit
/// * `By` byte
/// * `s` second
/// * `min` minute
/// * `h` hour
/// * `d` day
///
/// **Prefixes (PREFIX)**
///
/// * `k` kilo (10**3)
/// * `M` mega (10**6)
/// * `G` giga (10**9)
/// * `T` tera (10**12)
/// * `P` peta (10**15)
/// * `E` exa (10**18)
/// * `Z` zetta (10**21)
/// * `Y` yotta (10**24)
/// * `m` milli (10**-3)
/// * `u` micro (10**-6)
/// * `n` nano (10**-9)
/// * `p` pico (10**-12)
/// * `f` femto (10**-15)
/// * `a` atto (10**-18)
/// * `z` zepto (10**-21)
/// * `y` yocto (10**-24)
/// * `Ki` kibi (2**10)
/// * `Mi` mebi (2**20)
/// * `Gi` gibi (2**30)
/// * `Ti` tebi (2**40)
///
/// **Grammar**
///
/// The grammar includes the dimensionless unit `1`, such as `1/s`.
///
/// The grammar also includes these connectors:
///
/// * `/` division (as an infix operator, e.g. `1/s`).
/// * `.` multiplication (as an infix operator, e.g. `GBy.d`)
///
/// The grammar for a unit is as follows:
///
/// Expression = Component { "." Component } { "/" Component } ;
///
/// Component = [ PREFIX ] UNIT [ Annotation ]
/// | Annotation
/// | "1"
/// ;
///
/// Annotation = "{" NAME "}" ;
///
/// Notes:
///
/// * `Annotation` is just a comment if it follows a `UNIT` and is
/// equivalent to `1` if it is used alone. For examples,
/// `{requests}/s == 1/s`, `By{transmitted}/s == By/s`.
/// * `NAME` is a sequence of non-blank printable ASCII characters not
/// containing '{' or '}'.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Unit {
get { return unit_; }
set {
unit_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "description" field.</summary>
public const int DescriptionFieldNumber = 6;
private string description_ = "";
/// <summary>
/// A detailed description of the metric, which can be used in documentation.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Description {
get { return description_; }
set {
description_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "display_name" field.</summary>
public const int DisplayNameFieldNumber = 7;
private string displayName_ = "";
/// <summary>
/// A concise name for the metric, which can be displayed in user interfaces.
/// Use sentence case without an ending period, for example "Request count".
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string DisplayName {
get { return displayName_; }
set {
displayName_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as MetricDescriptor);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(MetricDescriptor other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Name != other.Name) return false;
if (Type != other.Type) return false;
if(!labels_.Equals(other.labels_)) return false;
if (MetricKind != other.MetricKind) return false;
if (ValueType != other.ValueType) return false;
if (Unit != other.Unit) return false;
if (Description != other.Description) return false;
if (DisplayName != other.DisplayName) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Name.Length != 0) hash ^= Name.GetHashCode();
if (Type.Length != 0) hash ^= Type.GetHashCode();
hash ^= labels_.GetHashCode();
if (MetricKind != 0) hash ^= MetricKind.GetHashCode();
if (ValueType != 0) hash ^= ValueType.GetHashCode();
if (Unit.Length != 0) hash ^= Unit.GetHashCode();
if (Description.Length != 0) hash ^= Description.GetHashCode();
if (DisplayName.Length != 0) hash ^= DisplayName.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 (Name.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Name);
}
labels_.WriteTo(output, _repeated_labels_codec);
if (MetricKind != 0) {
output.WriteRawTag(24);
output.WriteEnum((int) MetricKind);
}
if (ValueType != 0) {
output.WriteRawTag(32);
output.WriteEnum((int) ValueType);
}
if (Unit.Length != 0) {
output.WriteRawTag(42);
output.WriteString(Unit);
}
if (Description.Length != 0) {
output.WriteRawTag(50);
output.WriteString(Description);
}
if (DisplayName.Length != 0) {
output.WriteRawTag(58);
output.WriteString(DisplayName);
}
if (Type.Length != 0) {
output.WriteRawTag(66);
output.WriteString(Type);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Name.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Name);
}
if (Type.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Type);
}
size += labels_.CalculateSize(_repeated_labels_codec);
if (MetricKind != 0) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) MetricKind);
}
if (ValueType != 0) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) ValueType);
}
if (Unit.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Unit);
}
if (Description.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Description);
}
if (DisplayName.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(DisplayName);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(MetricDescriptor other) {
if (other == null) {
return;
}
if (other.Name.Length != 0) {
Name = other.Name;
}
if (other.Type.Length != 0) {
Type = other.Type;
}
labels_.Add(other.labels_);
if (other.MetricKind != 0) {
MetricKind = other.MetricKind;
}
if (other.ValueType != 0) {
ValueType = other.ValueType;
}
if (other.Unit.Length != 0) {
Unit = other.Unit;
}
if (other.Description.Length != 0) {
Description = other.Description;
}
if (other.DisplayName.Length != 0) {
DisplayName = other.DisplayName;
}
}
[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: {
Name = input.ReadString();
break;
}
case 18: {
labels_.AddEntriesFrom(input, _repeated_labels_codec);
break;
}
case 24: {
metricKind_ = (global::Google.Api.MetricDescriptor.Types.MetricKind) input.ReadEnum();
break;
}
case 32: {
valueType_ = (global::Google.Api.MetricDescriptor.Types.ValueType) input.ReadEnum();
break;
}
case 42: {
Unit = input.ReadString();
break;
}
case 50: {
Description = input.ReadString();
break;
}
case 58: {
DisplayName = input.ReadString();
break;
}
case 66: {
Type = input.ReadString();
break;
}
}
}
}
#region Nested types
/// <summary>Container for nested types declared in the MetricDescriptor message type.</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static partial class Types {
/// <summary>
/// The kind of measurement. It describes how the data is reported.
/// </summary>
public enum MetricKind {
/// <summary>
/// Do not use this default value.
/// </summary>
[pbr::OriginalName("METRIC_KIND_UNSPECIFIED")] Unspecified = 0,
/// <summary>
/// An instantaneous measurement of a value.
/// </summary>
[pbr::OriginalName("GAUGE")] Gauge = 1,
/// <summary>
/// The change in a value during a time interval.
/// </summary>
[pbr::OriginalName("DELTA")] Delta = 2,
/// <summary>
/// A value accumulated over a time interval. Cumulative
/// measurements in a time series should have the same start time
/// and increasing end times, until an event resets the cumulative
/// value to zero and sets a new start time for the following
/// points.
/// </summary>
[pbr::OriginalName("CUMULATIVE")] Cumulative = 3,
}
/// <summary>
/// The value type of a metric.
/// </summary>
public enum ValueType {
/// <summary>
/// Do not use this default value.
/// </summary>
[pbr::OriginalName("VALUE_TYPE_UNSPECIFIED")] Unspecified = 0,
/// <summary>
/// The value is a boolean.
/// This value type can be used only if the metric kind is `GAUGE`.
/// </summary>
[pbr::OriginalName("BOOL")] Bool = 1,
/// <summary>
/// The value is a signed 64-bit integer.
/// </summary>
[pbr::OriginalName("INT64")] Int64 = 2,
/// <summary>
/// The value is a double precision floating point number.
/// </summary>
[pbr::OriginalName("DOUBLE")] Double = 3,
/// <summary>
/// The value is a text string.
/// This value type can be used only if the metric kind is `GAUGE`.
/// </summary>
[pbr::OriginalName("STRING")] String = 4,
/// <summary>
/// The value is a [`Distribution`][google.api.Distribution].
/// </summary>
[pbr::OriginalName("DISTRIBUTION")] Distribution = 5,
/// <summary>
/// The value is money.
/// </summary>
[pbr::OriginalName("MONEY")] Money = 6,
}
}
#endregion
}
/// <summary>
/// A specific metric, identified by specifying values for all of the
/// labels of a [`MetricDescriptor`][google.api.MetricDescriptor].
/// </summary>
public sealed partial class Metric : pb::IMessage<Metric> {
private static readonly pb::MessageParser<Metric> _parser = new pb::MessageParser<Metric>(() => new Metric());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<Metric> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Api.MetricReflection.Descriptor.MessageTypes[1]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Metric() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Metric(Metric other) : this() {
type_ = other.type_;
labels_ = other.labels_.Clone();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Metric Clone() {
return new Metric(this);
}
/// <summary>Field number for the "type" field.</summary>
public const int TypeFieldNumber = 3;
private string type_ = "";
/// <summary>
/// An existing metric type, see [google.api.MetricDescriptor][google.api.MetricDescriptor].
/// For example, `custom.googleapis.com/invoice/paid/amount`.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Type {
get { return type_; }
set {
type_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "labels" field.</summary>
public const int LabelsFieldNumber = 2;
private static readonly pbc::MapField<string, string>.Codec _map_labels_codec
= new pbc::MapField<string, string>.Codec(pb::FieldCodec.ForString(10), pb::FieldCodec.ForString(18), 18);
private readonly pbc::MapField<string, string> labels_ = new pbc::MapField<string, string>();
/// <summary>
/// The set of label values that uniquely identify this metric. All
/// labels listed in the `MetricDescriptor` must be assigned values.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::MapField<string, string> Labels {
get { return labels_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as Metric);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(Metric other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Type != other.Type) return false;
if (!Labels.Equals(other.Labels)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Type.Length != 0) hash ^= Type.GetHashCode();
hash ^= Labels.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) {
labels_.WriteTo(output, _map_labels_codec);
if (Type.Length != 0) {
output.WriteRawTag(26);
output.WriteString(Type);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Type.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Type);
}
size += labels_.CalculateSize(_map_labels_codec);
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(Metric other) {
if (other == null) {
return;
}
if (other.Type.Length != 0) {
Type = other.Type;
}
labels_.Add(other.labels_);
}
[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: {
labels_.AddEntriesFrom(input, _map_labels_codec);
break;
}
case 26: {
Type = input.ReadString();
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using Abp;
using Abp.Configuration.Startup;
using Abp.Domain.Uow;
using Abp.Runtime.Session;
using Abp.TestBase;
using MahjongBuddy.EntityFramework;
using MahjongBuddy.Migrations.SeedData;
using MahjongBuddy.MultiTenancy;
using MahjongBuddy.Users;
using Castle.MicroKernel.Registration;
using Effort;
using EntityFramework.DynamicFilters;
namespace MahjongBuddy.Tests
{
public abstract class MahjongBuddyTestBase : AbpIntegratedTestBase<MahjongBuddyTestModule>
{
private DbConnection _hostDb;
private Dictionary<int, DbConnection> _tenantDbs; //only used for db per tenant architecture
protected MahjongBuddyTestBase()
{
//Seed initial data for host
AbpSession.TenantId = null;
UsingDbContext(context =>
{
new InitialHostDbBuilder(context).Create();
new DefaultTenantCreator(context).Create();
});
//Seed initial data for default tenant
AbpSession.TenantId = 1;
UsingDbContext(context =>
{
new TenantRoleAndUserBuilder(context, 1).Create();
});
LoginAsDefaultTenantAdmin();
}
protected override void PreInitialize()
{
base.PreInitialize();
/* You can switch database architecture here: */
UseSingleDatabase();
//UseDatabasePerTenant();
}
/* Uses single database for host and all tenants.
*/
private void UseSingleDatabase()
{
_hostDb = DbConnectionFactory.CreateTransient();
LocalIocManager.IocContainer.Register(
Component.For<DbConnection>()
.UsingFactoryMethod(() => _hostDb)
.LifestyleSingleton()
);
}
/* Uses single database for host and Default tenant,
* but dedicated databases for all other tenants.
*/
private void UseDatabasePerTenant()
{
_hostDb = DbConnectionFactory.CreateTransient();
_tenantDbs = new Dictionary<int, DbConnection>();
LocalIocManager.IocContainer.Register(
Component.For<DbConnection>()
.UsingFactoryMethod((kernel) =>
{
lock (_tenantDbs)
{
var currentUow = kernel.Resolve<ICurrentUnitOfWorkProvider>().Current;
var abpSession = kernel.Resolve<IAbpSession>();
var tenantId = currentUow != null ? currentUow.GetTenantId() : abpSession.TenantId;
if (tenantId == null || tenantId == 1) //host and default tenant are stored in host db
{
return _hostDb;
}
if (!_tenantDbs.ContainsKey(tenantId.Value))
{
_tenantDbs[tenantId.Value] = DbConnectionFactory.CreateTransient();
}
return _tenantDbs[tenantId.Value];
}
}, true)
.LifestyleTransient()
);
}
#region UsingDbContext
protected IDisposable UsingTenantId(int? tenantId)
{
var previousTenantId = AbpSession.TenantId;
AbpSession.TenantId = tenantId;
return new DisposeAction(() => AbpSession.TenantId = previousTenantId);
}
protected void UsingDbContext(Action<MahjongBuddyDbContext> action)
{
UsingDbContext(AbpSession.TenantId, action);
}
protected Task UsingDbContextAsync(Func<MahjongBuddyDbContext, Task> action)
{
return UsingDbContextAsync(AbpSession.TenantId, action);
}
protected T UsingDbContext<T>(Func<MahjongBuddyDbContext, T> func)
{
return UsingDbContext(AbpSession.TenantId, func);
}
protected Task<T> UsingDbContextAsync<T>(Func<MahjongBuddyDbContext, Task<T>> func)
{
return UsingDbContextAsync(AbpSession.TenantId, func);
}
protected void UsingDbContext(int? tenantId, Action<MahjongBuddyDbContext> action)
{
using (UsingTenantId(tenantId))
{
using (var context = LocalIocManager.Resolve<MahjongBuddyDbContext>())
{
context.DisableAllFilters();
action(context);
context.SaveChanges();
}
}
}
protected async Task UsingDbContextAsync(int? tenantId, Func<MahjongBuddyDbContext, Task> action)
{
using (UsingTenantId(tenantId))
{
using (var context = LocalIocManager.Resolve<MahjongBuddyDbContext>())
{
context.DisableAllFilters();
await action(context);
await context.SaveChangesAsync();
}
}
}
protected T UsingDbContext<T>(int? tenantId, Func<MahjongBuddyDbContext, T> func)
{
T result;
using (UsingTenantId(tenantId))
{
using (var context = LocalIocManager.Resolve<MahjongBuddyDbContext>())
{
context.DisableAllFilters();
result = func(context);
context.SaveChanges();
}
}
return result;
}
protected async Task<T> UsingDbContextAsync<T>(int? tenantId, Func<MahjongBuddyDbContext, Task<T>> func)
{
T result;
using (UsingTenantId(tenantId))
{
using (var context = LocalIocManager.Resolve<MahjongBuddyDbContext>())
{
context.DisableAllFilters();
result = await func(context);
await context.SaveChangesAsync();
}
}
return result;
}
#endregion
#region Login
protected void LoginAsHostAdmin()
{
LoginAsHost(User.AdminUserName);
}
protected void LoginAsDefaultTenantAdmin()
{
LoginAsTenant(Tenant.DefaultTenantName, User.AdminUserName);
}
protected void LoginAsHost(string userName)
{
Resolve<IMultiTenancyConfig>().IsEnabled = true;
AbpSession.TenantId = null;
var user =
UsingDbContext(
context =>
context.Users.FirstOrDefault(u => u.TenantId == AbpSession.TenantId && u.UserName == userName));
if (user == null)
{
throw new Exception("There is no user: " + userName + " for host.");
}
AbpSession.UserId = user.Id;
}
protected void LoginAsTenant(string tenancyName, string userName)
{
var tenant = UsingDbContext(context => context.Tenants.FirstOrDefault(t => t.TenancyName == tenancyName));
if (tenant == null)
{
throw new Exception("There is no tenant: " + tenancyName);
}
AbpSession.TenantId = tenant.Id;
var user =
UsingDbContext(
context =>
context.Users.FirstOrDefault(u => u.TenantId == AbpSession.TenantId && u.UserName == userName));
if (user == null)
{
throw new Exception("There is no user: " + userName + " for tenant: " + tenancyName);
}
AbpSession.UserId = user.Id;
}
#endregion
/// <summary>
/// Gets current user if <see cref="IAbpSession.UserId"/> is not null.
/// Throws exception if it's null.
/// </summary>
protected async Task<User> GetCurrentUserAsync()
{
var userId = AbpSession.GetUserId();
return await UsingDbContext(context => context.Users.SingleAsync(u => u.Id == userId));
}
/// <summary>
/// Gets current tenant if <see cref="IAbpSession.TenantId"/> is not null.
/// Throws exception if there is no current tenant.
/// </summary>
protected async Task<Tenant> GetCurrentTenantAsync()
{
var tenantId = AbpSession.GetTenantId();
return await UsingDbContext(context => context.Tenants.SingleAsync(t => t.Id == tenantId));
}
}
}
| |
/*******************************************************************************
* Copyright (c) 2013, Daniel Murphy
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
/*
* JBox2D - A Java Port of Erin Catto's Box2D
*
* JBox2D homepage: http://jbox2d.sourceforge.net/
* Box2D homepage: http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
using SharpBox2D.Common;
using SharpBox2D.Pooling;
namespace SharpBox2D.Dynamics.Joints
{
//C = norm(p2 - p1) - L
//u = (p2 - p1) / norm(p2 - p1)
//Cdot = dot(u, v2 + cross(w2, r2) - v1 - cross(w1, r1))
//J = [-u -cross(r1, u) u cross(r2, u)]
//K = J * invM * JT
//= invMass1 + invI1 * cross(r1, u)^2 + invMass2 + invI2 * cross(r2, u)^2
/**
* A distance joint constrains two points on two bodies to remain at a fixed distance from each
* other. You can view this as a massless, rigid rod.
*/
public class DistanceJoint : Joint
{
private float m_frequencyHz;
private float m_dampingRatio;
private float m_bias;
// Solver shared
private Vec2 m_localAnchorA;
private Vec2 m_localAnchorB;
private float m_gamma;
private float m_impulse;
private float m_length;
// Solver temp
private int m_indexA;
private int m_indexB;
private Vec2 m_u = new Vec2();
private Vec2 m_rA = new Vec2();
private Vec2 m_rB = new Vec2();
private Vec2 m_localCenterA = new Vec2();
private Vec2 m_localCenterB = new Vec2();
private float m_invMassA;
private float m_invMassB;
private float m_invIA;
private float m_invIB;
private float m_mass;
internal DistanceJoint(IWorldPool argWorld, DistanceJointDef def) : base(argWorld, def)
{
m_localAnchorA = def.localAnchorA.clone();
m_localAnchorB = def.localAnchorB.clone();
m_length = def.length;
m_impulse = 0.0f;
m_frequencyHz = def.frequencyHz;
m_dampingRatio = def.dampingRatio;
m_gamma = 0.0f;
m_bias = 0.0f;
}
public void setFrequency(float hz)
{
m_frequencyHz = hz;
}
public float getFrequency()
{
return m_frequencyHz;
}
public float getLength()
{
return m_length;
}
public void setLength(float argLength)
{
m_length = argLength;
}
public void setDampingRatio(float damp)
{
m_dampingRatio = damp;
}
public float getDampingRatio()
{
return m_dampingRatio;
}
public override void getAnchorA(ref Vec2 argOut)
{
m_bodyA.getWorldPointToOut(m_localAnchorA, ref argOut);
}
public override void getAnchorB(ref Vec2 argOut)
{
m_bodyB.getWorldPointToOut(m_localAnchorB, ref argOut);
}
public Vec2 getLocalAnchorA()
{
return m_localAnchorA;
}
public Vec2 getLocalAnchorB()
{
return m_localAnchorB;
}
/**
* Get the reaction force given the inverse time step. Unit is N.
*/
public override void getReactionForce(float inv_dt, ref Vec2 argOut)
{
argOut.x = m_impulse*m_u.x*inv_dt;
argOut.y = m_impulse*m_u.y*inv_dt;
}
/**
* Get the reaction torque given the inverse time step. Unit is N*m. This is always zero for a
* distance joint.
*/
public override float getReactionTorque(float inv_dt)
{
return 0.0f;
}
public override void initVelocityConstraints(SolverData data)
{
m_indexA = m_bodyA.m_islandIndex;
m_indexB = m_bodyB.m_islandIndex;
m_localCenterA.set(m_bodyA.m_sweep.localCenter);
m_localCenterB.set(m_bodyB.m_sweep.localCenter);
m_invMassA = m_bodyA.m_invMass;
m_invMassB = m_bodyB.m_invMass;
m_invIA = m_bodyA.m_invI;
m_invIB = m_bodyB.m_invI;
Vec2 cA = data.positions[m_indexA].c;
float aA = data.positions[m_indexA].a;
Vec2 vA = data.velocities[m_indexA].v;
float wA = data.velocities[m_indexA].w;
Vec2 cB = data.positions[m_indexB].c;
float aB = data.positions[m_indexB].a;
Vec2 vB = data.velocities[m_indexB].v;
float wB = data.velocities[m_indexB].w;
Rot qA = pool.popRot();
Rot qB = pool.popRot();
qA.set(aA);
qB.set(aB);
// use m_u as temporary variable
m_u.set(m_localAnchorA);
m_u.subLocal(m_localCenterA);
Rot.mulToOutUnsafe(qA, m_u, ref m_rA);
m_u.set(m_localAnchorB);
m_u.subLocal(m_localCenterB);
Rot.mulToOutUnsafe(qB, m_u, ref m_rB);
m_u.set(cB);
m_u.addLocal(m_rB);
m_u.subLocal(cA);
m_u.subLocal(m_rA);
pool.pushRot(2);
// Handle singularity.
float length = m_u.length();
if (length > Settings.linearSlop)
{
m_u.x *= 1.0f/length;
m_u.y *= 1.0f/length;
}
else
{
m_u.set(0.0f, 0.0f);
}
float crAu = Vec2.cross(m_rA, m_u);
float crBu = Vec2.cross(m_rB, m_u);
float invMass = m_invMassA + m_invIA*crAu*crAu + m_invMassB + m_invIB*crBu*crBu;
// Compute the effective mass matrix.
m_mass = invMass != 0.0f ? 1.0f/invMass : 0.0f;
if (m_frequencyHz > 0.0f)
{
float C = length - m_length;
// Frequency
float omega = 2.0f*MathUtils.PI*m_frequencyHz;
// Damping coefficient
float d = 2.0f*m_mass*m_dampingRatio*omega;
// Spring stiffness
float k = m_mass*omega*omega;
// magic formulas
float h = data.step.dt;
m_gamma = h*(d + h*k);
m_gamma = m_gamma != 0.0f ? 1.0f/m_gamma : 0.0f;
m_bias = C*h*k*m_gamma;
invMass += m_gamma;
m_mass = invMass != 0.0f ? 1.0f/invMass : 0.0f;
}
else
{
m_gamma = 0.0f;
m_bias = 0.0f;
}
if (data.step.warmStarting)
{
// Scale the impulse to support a variable time step.
m_impulse *= data.step.dtRatio;
Vec2 P = pool.popVec2();
P.set(m_u);
P.mulLocal(m_impulse);
vA.x -= m_invMassA*P.x;
vA.y -= m_invMassA*P.y;
wA -= m_invIA*Vec2.cross(m_rA, P);
vB.x += m_invMassB*P.x;
vB.y += m_invMassB*P.y;
wB += m_invIB*Vec2.cross(m_rB, P);
pool.pushVec2(1);
}
else
{
m_impulse = 0.0f;
}
// data.velocities[m_indexA].v.set(vA);
data.velocities[m_indexA].w = wA;
// data.velocities[m_indexB].v.set(vB);
data.velocities[m_indexB].w = wB;
}
public override void solveVelocityConstraints(SolverData data)
{
Vec2 vA = data.velocities[m_indexA].v;
float wA = data.velocities[m_indexA].w;
Vec2 vB = data.velocities[m_indexB].v;
float wB = data.velocities[m_indexB].w;
Vec2 vpA = pool.popVec2();
Vec2 vpB = pool.popVec2();
// Cdot = dot(u, v + cross(w, r))
Vec2.crossToOutUnsafe(wA, m_rA, ref vpA);
vpA.addLocal(vA);
Vec2.crossToOutUnsafe(wB, m_rB, ref vpB);
vpB.addLocal(vB);
vpB.subLocal(vpA);
float Cdot = Vec2.dot(m_u, vpB);
float impulse = -m_mass*(Cdot + m_bias + m_gamma*m_impulse);
m_impulse += impulse;
float Px = impulse*m_u.x;
float Py = impulse*m_u.y;
vA.x -= m_invMassA*Px;
vA.y -= m_invMassA*Py;
wA -= m_invIA*(m_rA.x*Py - m_rA.y*Px);
vB.x += m_invMassB*Px;
vB.y += m_invMassB*Py;
wB += m_invIB*(m_rB.x*Py - m_rB.y*Px);
// data.velocities[m_indexA].v.set(vA);
data.velocities[m_indexA].w = wA;
// data.velocities[m_indexB].v.set(vB);
data.velocities[m_indexB].w = wB;
pool.pushVec2(2);
}
public override bool solvePositionConstraints(SolverData data)
{
if (m_frequencyHz > 0.0f)
{
return true;
}
Rot qA = pool.popRot();
Rot qB = pool.popRot();
Vec2 rA = pool.popVec2();
Vec2 rB = pool.popVec2();
Vec2 u = pool.popVec2();
Vec2 cA = data.positions[m_indexA].c;
float aA = data.positions[m_indexA].a;
Vec2 cB = data.positions[m_indexB].c;
float aB = data.positions[m_indexB].a;
qA.set(aA);
qB.set(aB);
u.set(m_localAnchorA);
u.subLocal(m_localCenterA);
Rot.mulToOutUnsafe(qA, u , ref rA);
u.set(m_localAnchorB);
u.subLocal(m_localCenterB);
Rot.mulToOutUnsafe(qB, u, ref rB);
u.set(cB);
u.addLocal(rB);
u.subLocal(cA);
u.subLocal(rA);
float length = u.normalize();
float C = length - m_length;
C = MathUtils.clamp(C, -Settings.maxLinearCorrection, Settings.maxLinearCorrection);
float impulse = -m_mass*C;
float Px = impulse*u.x;
float Py = impulse*u.y;
cA.x -= m_invMassA*Px;
cA.y -= m_invMassA*Py;
aA -= m_invIA*(rA.x*Py - rA.y*Px);
cB.x += m_invMassB*Px;
cB.y += m_invMassB*Py;
aB += m_invIB*(rB.x*Py - rB.y*Px);
// data.positions[m_indexA].c.set(cA);
data.positions[m_indexA].a = aA;
// data.positions[m_indexB].c.set(cB);
data.positions[m_indexB].a = aB;
pool.pushVec2(3);
pool.pushRot(2);
return MathUtils.abs(C) < Settings.linearSlop;
}
}
}
| |
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using CookComputing.XmlRpc;
namespace XenAPI
{
/// <summary>
/// Represents a patch stored on a server
/// First published in XenServer 4.0.
/// </summary>
public partial class Host_patch : XenObject<Host_patch>
{
public Host_patch()
{
}
public Host_patch(string uuid,
string name_label,
string name_description,
string version,
XenRef<Host> host,
bool applied,
DateTime timestamp_applied,
long size,
XenRef<Pool_patch> pool_patch,
Dictionary<string, string> other_config)
{
this.uuid = uuid;
this.name_label = name_label;
this.name_description = name_description;
this.version = version;
this.host = host;
this.applied = applied;
this.timestamp_applied = timestamp_applied;
this.size = size;
this.pool_patch = pool_patch;
this.other_config = other_config;
}
/// <summary>
/// Creates a new Host_patch from a Proxy_Host_patch.
/// </summary>
/// <param name="proxy"></param>
public Host_patch(Proxy_Host_patch proxy)
{
this.UpdateFromProxy(proxy);
}
public override void UpdateFrom(Host_patch update)
{
uuid = update.uuid;
name_label = update.name_label;
name_description = update.name_description;
version = update.version;
host = update.host;
applied = update.applied;
timestamp_applied = update.timestamp_applied;
size = update.size;
pool_patch = update.pool_patch;
other_config = update.other_config;
}
internal void UpdateFromProxy(Proxy_Host_patch proxy)
{
uuid = proxy.uuid == null ? null : (string)proxy.uuid;
name_label = proxy.name_label == null ? null : (string)proxy.name_label;
name_description = proxy.name_description == null ? null : (string)proxy.name_description;
version = proxy.version == null ? null : (string)proxy.version;
host = proxy.host == null ? null : XenRef<Host>.Create(proxy.host);
applied = (bool)proxy.applied;
timestamp_applied = proxy.timestamp_applied;
size = proxy.size == null ? 0 : long.Parse((string)proxy.size);
pool_patch = proxy.pool_patch == null ? null : XenRef<Pool_patch>.Create(proxy.pool_patch);
other_config = proxy.other_config == null ? null : Maps.convert_from_proxy_string_string(proxy.other_config);
}
public Proxy_Host_patch ToProxy()
{
Proxy_Host_patch result_ = new Proxy_Host_patch();
result_.uuid = (uuid != null) ? uuid : "";
result_.name_label = (name_label != null) ? name_label : "";
result_.name_description = (name_description != null) ? name_description : "";
result_.version = (version != null) ? version : "";
result_.host = (host != null) ? host : "";
result_.applied = applied;
result_.timestamp_applied = timestamp_applied;
result_.size = size.ToString();
result_.pool_patch = (pool_patch != null) ? pool_patch : "";
result_.other_config = Maps.convert_to_proxy_string_string(other_config);
return result_;
}
/// <summary>
/// Creates a new Host_patch from a Hashtable.
/// </summary>
/// <param name="table"></param>
public Host_patch(Hashtable table)
{
uuid = Marshalling.ParseString(table, "uuid");
name_label = Marshalling.ParseString(table, "name_label");
name_description = Marshalling.ParseString(table, "name_description");
version = Marshalling.ParseString(table, "version");
host = Marshalling.ParseRef<Host>(table, "host");
applied = Marshalling.ParseBool(table, "applied");
timestamp_applied = Marshalling.ParseDateTime(table, "timestamp_applied");
size = Marshalling.ParseLong(table, "size");
pool_patch = Marshalling.ParseRef<Pool_patch>(table, "pool_patch");
other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config"));
}
public bool DeepEquals(Host_patch other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return Helper.AreEqual2(this._uuid, other._uuid) &&
Helper.AreEqual2(this._name_label, other._name_label) &&
Helper.AreEqual2(this._name_description, other._name_description) &&
Helper.AreEqual2(this._version, other._version) &&
Helper.AreEqual2(this._host, other._host) &&
Helper.AreEqual2(this._applied, other._applied) &&
Helper.AreEqual2(this._timestamp_applied, other._timestamp_applied) &&
Helper.AreEqual2(this._size, other._size) &&
Helper.AreEqual2(this._pool_patch, other._pool_patch) &&
Helper.AreEqual2(this._other_config, other._other_config);
}
public override string SaveChanges(Session session, string opaqueRef, Host_patch server)
{
if (opaqueRef == null)
{
System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server");
return "";
}
else
{
if (!Helper.AreEqual2(_other_config, server._other_config))
{
Host_patch.set_other_config(session, opaqueRef, _other_config);
}
return null;
}
}
/// <summary>
/// Get a record containing the current state of the given host_patch.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_patch">The opaque_ref of the given host_patch</param>
public static Host_patch get_record(Session session, string _host_patch)
{
return new Host_patch((Proxy_Host_patch)session.proxy.host_patch_get_record(session.uuid, (_host_patch != null) ? _host_patch : "").parse());
}
/// <summary>
/// Get a reference to the host_patch instance with the specified UUID.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_uuid">UUID of object to return</param>
public static XenRef<Host_patch> get_by_uuid(Session session, string _uuid)
{
return XenRef<Host_patch>.Create(session.proxy.host_patch_get_by_uuid(session.uuid, (_uuid != null) ? _uuid : "").parse());
}
/// <summary>
/// Get all the host_patch instances with the given label.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_label">label of object to return</param>
public static List<XenRef<Host_patch>> get_by_name_label(Session session, string _label)
{
return XenRef<Host_patch>.Create(session.proxy.host_patch_get_by_name_label(session.uuid, (_label != null) ? _label : "").parse());
}
/// <summary>
/// Get the uuid field of the given host_patch.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_patch">The opaque_ref of the given host_patch</param>
public static string get_uuid(Session session, string _host_patch)
{
return (string)session.proxy.host_patch_get_uuid(session.uuid, (_host_patch != null) ? _host_patch : "").parse();
}
/// <summary>
/// Get the name/label field of the given host_patch.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_patch">The opaque_ref of the given host_patch</param>
public static string get_name_label(Session session, string _host_patch)
{
return (string)session.proxy.host_patch_get_name_label(session.uuid, (_host_patch != null) ? _host_patch : "").parse();
}
/// <summary>
/// Get the name/description field of the given host_patch.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_patch">The opaque_ref of the given host_patch</param>
public static string get_name_description(Session session, string _host_patch)
{
return (string)session.proxy.host_patch_get_name_description(session.uuid, (_host_patch != null) ? _host_patch : "").parse();
}
/// <summary>
/// Get the version field of the given host_patch.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_patch">The opaque_ref of the given host_patch</param>
public static string get_version(Session session, string _host_patch)
{
return (string)session.proxy.host_patch_get_version(session.uuid, (_host_patch != null) ? _host_patch : "").parse();
}
/// <summary>
/// Get the host field of the given host_patch.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_patch">The opaque_ref of the given host_patch</param>
public static XenRef<Host> get_host(Session session, string _host_patch)
{
return XenRef<Host>.Create(session.proxy.host_patch_get_host(session.uuid, (_host_patch != null) ? _host_patch : "").parse());
}
/// <summary>
/// Get the applied field of the given host_patch.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_patch">The opaque_ref of the given host_patch</param>
public static bool get_applied(Session session, string _host_patch)
{
return (bool)session.proxy.host_patch_get_applied(session.uuid, (_host_patch != null) ? _host_patch : "").parse();
}
/// <summary>
/// Get the timestamp_applied field of the given host_patch.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_patch">The opaque_ref of the given host_patch</param>
public static DateTime get_timestamp_applied(Session session, string _host_patch)
{
return session.proxy.host_patch_get_timestamp_applied(session.uuid, (_host_patch != null) ? _host_patch : "").parse();
}
/// <summary>
/// Get the size field of the given host_patch.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_patch">The opaque_ref of the given host_patch</param>
public static long get_size(Session session, string _host_patch)
{
return long.Parse((string)session.proxy.host_patch_get_size(session.uuid, (_host_patch != null) ? _host_patch : "").parse());
}
/// <summary>
/// Get the pool_patch field of the given host_patch.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_patch">The opaque_ref of the given host_patch</param>
public static XenRef<Pool_patch> get_pool_patch(Session session, string _host_patch)
{
return XenRef<Pool_patch>.Create(session.proxy.host_patch_get_pool_patch(session.uuid, (_host_patch != null) ? _host_patch : "").parse());
}
/// <summary>
/// Get the other_config field of the given host_patch.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_patch">The opaque_ref of the given host_patch</param>
public static Dictionary<string, string> get_other_config(Session session, string _host_patch)
{
return Maps.convert_from_proxy_string_string(session.proxy.host_patch_get_other_config(session.uuid, (_host_patch != null) ? _host_patch : "").parse());
}
/// <summary>
/// Set the other_config field of the given host_patch.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_patch">The opaque_ref of the given host_patch</param>
/// <param name="_other_config">New value to set</param>
public static void set_other_config(Session session, string _host_patch, Dictionary<string, string> _other_config)
{
session.proxy.host_patch_set_other_config(session.uuid, (_host_patch != null) ? _host_patch : "", Maps.convert_to_proxy_string_string(_other_config)).parse();
}
/// <summary>
/// Add the given key-value pair to the other_config field of the given host_patch.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_patch">The opaque_ref of the given host_patch</param>
/// <param name="_key">Key to add</param>
/// <param name="_value">Value to add</param>
public static void add_to_other_config(Session session, string _host_patch, string _key, string _value)
{
session.proxy.host_patch_add_to_other_config(session.uuid, (_host_patch != null) ? _host_patch : "", (_key != null) ? _key : "", (_value != null) ? _value : "").parse();
}
/// <summary>
/// Remove the given key and its corresponding value from the other_config field of the given host_patch. If the key is not in that Map, then do nothing.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_patch">The opaque_ref of the given host_patch</param>
/// <param name="_key">Key to remove</param>
public static void remove_from_other_config(Session session, string _host_patch, string _key)
{
session.proxy.host_patch_remove_from_other_config(session.uuid, (_host_patch != null) ? _host_patch : "", (_key != null) ? _key : "").parse();
}
/// <summary>
/// Destroy the specified host patch, removing it from the disk. This does NOT reverse the patch
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_patch">The opaque_ref of the given host_patch</param>
public static void destroy(Session session, string _host_patch)
{
session.proxy.host_patch_destroy(session.uuid, (_host_patch != null) ? _host_patch : "").parse();
}
/// <summary>
/// Destroy the specified host patch, removing it from the disk. This does NOT reverse the patch
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_patch">The opaque_ref of the given host_patch</param>
public static XenRef<Task> async_destroy(Session session, string _host_patch)
{
return XenRef<Task>.Create(session.proxy.async_host_patch_destroy(session.uuid, (_host_patch != null) ? _host_patch : "").parse());
}
/// <summary>
/// Apply the selected patch and return its output
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_patch">The opaque_ref of the given host_patch</param>
public static string apply(Session session, string _host_patch)
{
return (string)session.proxy.host_patch_apply(session.uuid, (_host_patch != null) ? _host_patch : "").parse();
}
/// <summary>
/// Apply the selected patch and return its output
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_patch">The opaque_ref of the given host_patch</param>
public static XenRef<Task> async_apply(Session session, string _host_patch)
{
return XenRef<Task>.Create(session.proxy.async_host_patch_apply(session.uuid, (_host_patch != null) ? _host_patch : "").parse());
}
/// <summary>
/// Return a list of all the host_patchs known to the system.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
public static List<XenRef<Host_patch>> get_all(Session session)
{
return XenRef<Host_patch>.Create(session.proxy.host_patch_get_all(session.uuid).parse());
}
/// <summary>
/// Get all the host_patch Records at once, in a single XML RPC call
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
public static Dictionary<XenRef<Host_patch>, Host_patch> get_all_records(Session session)
{
return XenRef<Host_patch>.Create<Proxy_Host_patch>(session.proxy.host_patch_get_all_records(session.uuid).parse());
}
/// <summary>
/// Unique identifier/object reference
/// </summary>
public virtual string uuid
{
get { return _uuid; }
set
{
if (!Helper.AreEqual(value, _uuid))
{
_uuid = value;
Changed = true;
NotifyPropertyChanged("uuid");
}
}
}
private string _uuid;
/// <summary>
/// a human-readable name
/// </summary>
public virtual string name_label
{
get { return _name_label; }
set
{
if (!Helper.AreEqual(value, _name_label))
{
_name_label = value;
Changed = true;
NotifyPropertyChanged("name_label");
}
}
}
private string _name_label;
/// <summary>
/// a notes field containing human-readable description
/// </summary>
public virtual string name_description
{
get { return _name_description; }
set
{
if (!Helper.AreEqual(value, _name_description))
{
_name_description = value;
Changed = true;
NotifyPropertyChanged("name_description");
}
}
}
private string _name_description;
/// <summary>
/// Patch version number
/// </summary>
public virtual string version
{
get { return _version; }
set
{
if (!Helper.AreEqual(value, _version))
{
_version = value;
Changed = true;
NotifyPropertyChanged("version");
}
}
}
private string _version;
/// <summary>
/// Host the patch relates to
/// </summary>
public virtual XenRef<Host> host
{
get { return _host; }
set
{
if (!Helper.AreEqual(value, _host))
{
_host = value;
Changed = true;
NotifyPropertyChanged("host");
}
}
}
private XenRef<Host> _host;
/// <summary>
/// True if the patch has been applied
/// </summary>
public virtual bool applied
{
get { return _applied; }
set
{
if (!Helper.AreEqual(value, _applied))
{
_applied = value;
Changed = true;
NotifyPropertyChanged("applied");
}
}
}
private bool _applied;
/// <summary>
/// Time the patch was applied
/// </summary>
public virtual DateTime timestamp_applied
{
get { return _timestamp_applied; }
set
{
if (!Helper.AreEqual(value, _timestamp_applied))
{
_timestamp_applied = value;
Changed = true;
NotifyPropertyChanged("timestamp_applied");
}
}
}
private DateTime _timestamp_applied;
/// <summary>
/// Size of the patch
/// </summary>
public virtual long size
{
get { return _size; }
set
{
if (!Helper.AreEqual(value, _size))
{
_size = value;
Changed = true;
NotifyPropertyChanged("size");
}
}
}
private long _size;
/// <summary>
/// The patch applied
/// First published in XenServer 4.1.
/// </summary>
public virtual XenRef<Pool_patch> pool_patch
{
get { return _pool_patch; }
set
{
if (!Helper.AreEqual(value, _pool_patch))
{
_pool_patch = value;
Changed = true;
NotifyPropertyChanged("pool_patch");
}
}
}
private XenRef<Pool_patch> _pool_patch;
/// <summary>
/// additional configuration
/// First published in XenServer 4.1.
/// </summary>
public virtual Dictionary<string, string> other_config
{
get { return _other_config; }
set
{
if (!Helper.AreEqual(value, _other_config))
{
_other_config = value;
Changed = true;
NotifyPropertyChanged("other_config");
}
}
}
private Dictionary<string, string> _other_config;
}
}
| |
using System;
using UnityEngine;
using System.IO;
#if UNITY_EDITOR
using UnityEditor;
using System.Linq;
using System.Reflection;
#endif
namespace ScriptableObjectSingleton
{
public class ScriptableObjectSingletonAttribute : Attribute
{
public readonly string fileName;
public readonly string directory;
public readonly string extension;
public ScriptableObjectSingletonAttribute(string inFileName, string inDirectory)
{
fileName = inFileName;
directory = inDirectory;
}
public ScriptableObjectSingletonAttribute(string inFileName, string inDirectory, string inExtension)
{
fileName = inFileName;
directory = inDirectory;
extension = inExtension;
}
}
public abstract class ScriptableObjectSingleton<T> : ScriptableObject where T : ScriptableObjectSingleton<T>
{
static T _instance = null;
public static T Instance
{
get
{
if(_instance == null)
{
SetupInstance();
}
return _instance;
}
}
static ScriptableObjectSingletonAttribute _attribute;
public static string directory
{
get
{
GetAttribute();
return _attribute == null ? string.Empty : Application.dataPath + "/" + _attribute.directory;
}
}
public static string fileName
{
get
{
GetAttribute();
return _attribute == null ? string.Empty : _attribute.fileName;
}
}
public static string extension
{
get
{
GetAttribute();
return _attribute == null ? string.Empty : _attribute.extension;
}
}
public static string fullPath
{
get
{
return directory + "/" + fileName;
}
}
public static string fullPathWithExtension
{
get
{
GetAttribute();
return directory + "/" + fileName + _attribute.extension;
}
}
static void GetAttribute()
{
_attribute = (ScriptableObjectSingletonAttribute)Attribute.GetCustomAttribute(typeof(T), typeof(ScriptableObjectSingletonAttribute));
if(_attribute == null)
{
Debug.LogError("Class type " + typeof(T).ToString() + " does not have a ScriptableObjectSingletonAttribute assigned, and it is required.");
}
}
static string RemoveSuffix(string str, string suffix)
{
string trimmedString = str;
if(trimmedString.EndsWith(suffix))
trimmedString = trimmedString.Substring(0, trimmedString.Length - suffix.Length);
return trimmedString;
}
static string RemovePrefix(string str, string prefix)
{
string trimmedString = str;
if(trimmedString.StartsWith(prefix))
trimmedString = trimmedString.Substring(prefix.Length, trimmedString.Length - prefix.Length);
return trimmedString;
}
public static void SetupInstance()
{
GetAttribute();
if(_attribute == null || string.IsNullOrEmpty(_attribute.fileName))
{
Debug.LogError("FAILED to locate ScriptableObject attribute, or the fileName was empty for type " + typeof(T).ToString());
return;
}
//Debug.Log("Attempting to load ScriptableObjectSingleton via Resources with name " + _attribute.fileName);
var returnValue = Resources.Load(_attribute.fileName);
_instance = returnValue as T;
if(returnValue != null && _instance == null)
Debug.LogError("Loaded something via Resources but was unable to cast with name " + _attribute.fileName + ", cast attempt was to type " + typeof(T).ToString() + ", and type of Resource is " + returnValue.GetType().ToString());
#if UNITY_EDITOR
if(_instance == null)
{
var existingFilePath = Application.dataPath + "/" + _attribute.directory + "/" + _attribute.fileName + (!string.IsNullOrEmpty(_attribute.extension) ? _attribute.extension : ".asset");
Debug.Log("Checking to see if file with name " + existingFilePath + " exists.");
if(File.Exists(existingFilePath))
{
Debug.Log("ScriptableObjectSingleton at path " + existingFilePath + " exists but failed to load from Resources. Will not create default ScriptableObject with the assumption that asset processing has not completed yet.");
}
else
{
Debug.Log("Failed to load ScriptableObjectSingleton resource with name " + _attribute.fileName);
_instance = ScriptableObject.CreateInstance(typeof(T)) as T;
var directory = _attribute.directory;
var fileName = _attribute.fileName;
var slashStateOK = directory.EndsWith("/") ^ fileName.StartsWith("/");
if(!slashStateOK)
{
directory = RemoveSuffix(directory, "/");
fileName = RemovePrefix(fileName, "/");
directory = directory + "/";
}
var directoryPath = "Assets/" + directory;
if(!Directory.Exists(directoryPath))
Directory.CreateDirectory(directoryPath);
var fullPath = directoryPath + fileName + ".asset";
AssetDatabase.CreateAsset(_instance, fullPath);
AssetDatabase.Refresh();
}
}
#else
if(_instance == null)
{
Debug.LogError("FAILED to load singleton with fileName: " + _attribute.fileName + ", and directory: " + _attribute.directory + ", for type " + typeof(T).ToString());
}
#endif
}
}
#if UNITY_EDITOR
[InitializeOnLoad]
public class ScriptableObjectSingletonInitializer
{
static ScriptableObjectSingletonInitializer()
{
Initialize();
}
[MenuItem("Utilities/Scriptable Objects/Force ScriptableObjectSingleton Initialization")]
static void Initialize()
{
var assemblies = AppDomain.CurrentDomain.GetAssemblies().Where(a => !a.Location.Contains("Plugins")).ToList();
var matches = assemblies.SelectMany(
s => s.GetTypes()).Where(p => Attribute.GetCustomAttribute(p, typeof(ScriptableObjectSingletonAttribute)) != null
).Select(s => s).ToList();
foreach(Type type in matches)
{
MethodInfo methodInfo = type.GetMethod("SetupInstance", BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy);
if(methodInfo != null)
methodInfo.Invoke(null, null);
}
}
}
#endif
}
| |
/*
Copyright (c) 2010 by Genstein
This file is (or was originally) part of Trizbort, the Interactive Fiction Mapper.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Drawing;
using PdfSharp.Drawing;
namespace Trizbort
{
/// <summary>
/// An element in the project, represented visually on the canvas.
/// </summary>
/// <remarks>
/// Elements have a position and size and may be drawn.
/// Elements have zero or more ports to which connections may be made.
/// </remarks>
internal abstract class Element : IComparable<Element>
{
public Element(Project project)
{
m_ports = new ReadOnlyCollection<Port>(m_portList);
Project = project;
int id = 1;
while (Project.IsElementIDInUse(id))
{
++id;
}
ID = id;
}
// Added this second constructor to be used when loading a room
// This constructor is significantly faster as it doesn't look for gap in the element IDs
public Element(Project project, int TotalIDs)
{
m_ports = new ReadOnlyCollection<Port>(m_portList);
Project = project;
ID = TotalIDs;
}
/// <summary>
/// Get the project of which this element is part.
/// </summary>
/// <remarks>
/// The project defines the namespace in which element identifiers are unique.
/// </remarks>
public Project Project
{
get;
private set;
}
/// <summary>
/// Get the unique identifier of this element.
/// </summary>
public int ID
{
get { return m_id; }
set
{
if (!Project.IsElementIDInUse(value))
{
m_id = value;
}
}
}
/// <summary>
/// Compare this element to another.
/// </summary>
/// <param name="element">The other element.</param>
/// <remarks>
/// This method is used to sort into drawing order. Depth is the
/// primary criterion; after that a deterministic sort order is
/// guaranteed by using a unique, monotonically increasing sort
/// identifier for each element.
/// </remarks>
public int CompareTo(Element element)
{
int delta = Depth.CompareTo(element.Depth);
if (delta == 0)
{
delta = ID.CompareTo(element.ID);
}
return delta;
}
/// <summary>
/// Get the drawing priority of this element.
/// </summary>
/// <remarks>
/// Elements with a higher drawing priority are drawn last.
/// </remarks>
public virtual Depth Depth
{
get { return Depth.Low; }
}
/// <summary>
/// Event raised when the element changes.
/// </summary>
public event EventHandler Changed;
/// <summary>
/// Raise the Changed event.
/// </summary>
protected void RaiseChanged()
{
if (RaiseChangedEvents)
{
var changed = Changed;
if (changed != null)
{
changed(this, EventArgs.Empty);
}
}
}
/// <summary>
/// Get/set whether to raise change events.
/// </summary>
protected bool RaiseChangedEvents
{
get { return m_raiseChangedEvents; }
set { m_raiseChangedEvents = value; }
}
/// <summary>
/// Recompute any "smart" line segments we use when drawing.
/// </summary>
public virtual void RecomputeSmartLineSegments(DrawingContext context)
{
}
/// <summary>
/// Perform a pre-drawing pass for this element.
/// </summary>
/// <param name="context">The context in which drawing is taking place.</param>
/// <remarks>
/// Elements which wish to add to context.LinesDrawn such that
/// Connections lines will detect them may do so here.
/// </remarks>
public virtual void PreDraw(DrawingContext context)
{
}
/// <summary>
/// Draw the element.
/// </summary>
/// <param name="graphics">The graphics with which to draw.</param>
/// <param name="palette">The palette from which to obtain drawing tools.</param>
/// <param name="context">The context in which drawing is taking place.</param>
public abstract void Draw(XGraphics graphics, Palette palette, DrawingContext context);
/// <summary>
/// Enlarge the given rectangle so as to fully incorporate this element.
/// </summary>
/// <param name="rect">The rectangle to enlarge.</param>
/// <param name="includeMargins">True to include suitable margins around elements which need them; false otherwise.</param>
/// <returns>The new rectangle which incorporates this element.</returns>
/// <remarks>
/// This method is used to determine the bounds of the canvas on which
/// elements are drawn when exporting as an image or PDF.
///
/// For that usage, includeMargins should be set to true.
/// For more exacting bounds tests, includeMargins should be set to false.
/// </remarks>
public abstract Rect UnionBoundsWith(Rect rect, bool includeMargins);
/// <summary>
/// Get the distance from this element to the given point.
/// </summary>
/// <param name="includeMargins">True to include suitable margins around elements which need them; false otherwise.</param>
public abstract float Distance(Vector pos, bool includeMargins);
/// <summary>
/// Get whether this element intersects the given rectangle.
/// </summary>
public abstract bool Intersects(Rect rect);
/// <summary>
/// Get whether the element has a properties dialog which may be displayed.
/// </summary>
public virtual bool HasDialog
{
get { return false; }
}
/// <summary>
/// Display the element's properties dialog.
/// </summary>
public virtual void ShowDialog()
{
}
/// <summary>
/// Get the collection of ports on the element.
/// </summary>
public ReadOnlyCollection<Port> Ports
{
get { return m_ports; }
}
/// <summary>
/// Get the collection of ports on the element.
/// </summary>
protected List<Port> PortList
{
get { return m_portList; }
}
/// <summary>
/// Get/set whether this element is flagged. For temporary use by the Canvas when traversing elements.
/// </summary>
public bool Flagged
{
get;
set;
}
/// <summary>
/// Get the position of a given port on the element.
/// </summary>
/// <param name="port">The port in question.</param>
/// <returns>The position of the port.</returns>
public abstract Vector GetPortPosition(Port port);
/// <summary>
/// Get the position of the end of the "stalk" on the given port; or the port position if none.
/// </summary>
/// <param name="port">The port in question.</param>
/// <returns>The position of the end of the stalk, or the port position.</returns>
public abstract Vector GetPortStalkPosition(Port port);
private bool m_raiseChangedEvents = true;
private List<Port> m_portList = new List<Port>();
private ReadOnlyCollection<Port> m_ports;
private int m_id;
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="InnerListGridView.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <summary>
// Implements the InnerListGridView control.
//</summary>
//-----------------------------------------------------------------------
namespace Microsoft.Management.UI.Internal
{
using System;
using System.Collections;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Markup;
using System.Collections.ObjectModel;
/// <summary>
/// Extends the basic GrdView class to introduce the Visible concept to the
/// Columns collection.
/// </summary>
/// <!--We create our own version of Columns, that:
/// 1) Only takes InnerListColumn's
/// 2) Passes through the underlying ListView Columns, only the InnerListColumns
/// that have Visible=true.-->
[ContentProperty("AvailableColumns")]
public class InnerListGridView : GridView
{
/// <summary>
/// Set to true when we want to change the Columns collection.
/// </summary>
private bool canChangeColumns = false;
/// <summary>
/// Instanctiates a new object of this class.
/// </summary>
public InnerListGridView()
: this(new ObservableCollection<InnerListColumn>())
{
}
/// <summary>
/// Initializes a new instance of the <see cref="InnerListGridView"/> class with the specified columns.
/// </summary>
/// <param name="availableColumns">The columns this grid should display.</param>
/// <exception cref="ArgumentNullException">The specified value is a null reference.</exception>
internal InnerListGridView(ObservableCollection<InnerListColumn> availableColumns)
{
if (availableColumns == null)
{
throw new ArgumentNullException("availableColumns");
}
// Setting the AvailableColumns property won't trigger CollectionChanged, so we have to do it manually \\
this.AvailableColumns = availableColumns;
this.AvailableColumns_CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, availableColumns));
availableColumns.CollectionChanged += new NotifyCollectionChangedEventHandler(this.AvailableColumns_CollectionChanged);
this.Columns.CollectionChanged += new NotifyCollectionChangedEventHandler(this.Columns_CollectionChanged);
}
/// <summary>
/// Gets a collection of all columns which can be
/// added to the ManagementList, for example through ColumnPicker.
/// Columns is the collection of the columns which are currently
/// displayed (in the order in which they are displayed).
/// </summary>
internal ObservableCollection<InnerListColumn> AvailableColumns
{
get;
private set;
}
/// <summary>
/// Releases this instance's references to its controls.
/// This API supports the framework infrastructure and is not intended to be used directly from your code.
/// </summary>
public void ReleaseReferences()
{
this.AvailableColumns.CollectionChanged -= this.AvailableColumns_CollectionChanged;
this.Columns.CollectionChanged -= this.Columns_CollectionChanged;
foreach (InnerListColumn column in this.AvailableColumns)
{
// Unsubscribe from the column's change events \\
((INotifyPropertyChanged)column).PropertyChanged -= this.Column_PropertyChanged;
// If the column is shown, store its last width before releasing \\
if (column.Visible)
{
column.Width = column.ActualWidth;
}
}
// Remove the columns so they can be added to the next GridView \\
this.Columns.Clear();
}
/// <summary>
/// Called when the ItemsSource changes to auto populate the GridView columns
/// with reflection information on the first element of the ItemsSource.
/// </summary>
/// <param name="newValue">
/// The new ItemsSource.
/// This is used just to fetch .the first collection element.
/// </param>
internal void PopulateColumns(System.Collections.IEnumerable newValue)
{
if (newValue == null)
{
return; // No elements, so we can't populate
}
IEnumerator newValueEnumerator = newValue.GetEnumerator();
if (!newValueEnumerator.MoveNext())
{
return; // No first element, so we can't populate
}
object first = newValueEnumerator.Current;
if (first == null)
{
return;
}
Debug.Assert(this.AvailableColumns.Count == 0, "AvailabeColumns should be empty at this point");
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(first);
foreach (PropertyDescriptor property in properties)
{
UIPropertyGroupDescription dataDescription = new UIPropertyGroupDescription(property.Name, property.Name, property.PropertyType);
InnerListColumn column = new InnerListColumn(dataDescription);
this.AvailableColumns.Add(column);
}
}
/// <summary>
/// Callback for displaying the Column Picker.
/// </summary>
/// <param name="sender">The send object.</param>
/// <param name="e">The Event RoutedEventArgs.</param>
internal void OnColumnPicker(object sender, RoutedEventArgs e)
{
ColumnPicker columnPicker = new ColumnPicker(
this.Columns, this.AvailableColumns);
columnPicker.Owner = Window.GetWindow((DependencyObject)sender);
bool? retval = columnPicker.ShowDialog();
if (true != retval)
{
return;
}
this.canChangeColumns = true;
try
{
this.Columns.Clear();
ObservableCollection<InnerListColumn> newColumns = columnPicker.SelectedColumns;
Debug.Assert(null != newColumns, "SelectedColumns not found");
foreach (InnerListColumn column in newColumns)
{
Debug.Assert(column.Visible);
// 185977: ML InnerListGridView.PopulateColumns(): Always set Width on new columns
// Workaround to GridView issue suggested by Ben Carter
// Issue: Once a column has been added to a GridView
// and then removed, auto-sizing does not work
// after it is added back.
// Solution: Remove the column, change the width,
// add the column back, then change the width back.
double width = column.Width;
column.Width = 0d;
this.Columns.Add(column);
column.Width = width;
}
}
finally
{
this.canChangeColumns = false;
}
}
/// <summary>
/// Called when Columns changes so we can check we are the ones changing it.
/// </summary>
/// <param name="sender">The collection changing.</param>
/// <param name="e">The event parameters.</param>
private void Columns_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
switch (e.Action)
{
// Move happens in the GUI drag and drop operation, so we have to allow it.
case NotifyCollectionChangedAction.Move:
return;
// default means all other operations (Add, Move, Replace and Reset) those are reserved.
// only we should do it, as we keep AvailableColumns in sync with columns
default:
if (!this.canChangeColumns)
{
throw new NotSupportedException(
String.Format(
CultureInfo.InvariantCulture,
InvariantResources.CannotModified,
InvariantResources.Columns,
"AvailableColumns"));
}
break;
}
}
/// <summary>
/// Called when the AvailableColumns changes to pass through the VisibleColumns to Columns.
/// </summary>
/// <param name="sender">The collection changing.</param>
/// <param name="e">The event parameters.</param>
private void AvailableColumns_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
this.AddOrRemoveNotifications(e);
this.SynchronizeColumns();
}
/// <summary>
/// Called from availableColumns_CollectionChanged to add or remove the notifications
/// used to track the Visible property.
/// </summary>
/// <param name="e">The parameter passed to availableColumns_CollectionChanged.</param>
private void AddOrRemoveNotifications(NotifyCollectionChangedEventArgs e)
{
if (e.Action != NotifyCollectionChangedAction.Move)
{
if (e.OldItems != null)
{
foreach (InnerListColumn oldColumn in e.OldItems)
{
((INotifyPropertyChanged)oldColumn).PropertyChanged -= this.Column_PropertyChanged;
}
}
if (e.NewItems != null)
{
foreach (InnerListColumn newColumn in e.NewItems)
{
((INotifyPropertyChanged)newColumn).PropertyChanged += this.Column_PropertyChanged;
}
}
}
}
/// <summary>
/// Syncronizes AvailableColumns and Columns preserving the order from Columns that
/// comes from the user moving Columns around.
/// </summary>
private void SynchronizeColumns()
{
this.canChangeColumns = true;
try
{
// Add to listViewColumns all Visible columns in availableColumns not already in listViewColumns
foreach (InnerListColumn column in this.AvailableColumns)
{
if (column.Visible && !this.Columns.Contains(column))
{
this.Columns.Add(column);
}
}
// Remove all columns which are not visible or removed from Available columns.
for (int i = this.Columns.Count - 1; i >= 0; i--)
{
InnerListColumn listViewColumn = (InnerListColumn)this.Columns[i];
if (!listViewColumn.Visible || !this.AvailableColumns.Contains(listViewColumn))
{
this.Columns.RemoveAt(i);
}
}
}
finally
{
this.canChangeColumns = false;
}
}
/// <summary>
/// Called when the Visible property of a column changes.
/// </summary>
/// <param name="sender">The column whose property changed.</param>
/// <param name="e">The event parameters.</param>
private void Column_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == InnerListColumn.VisibleProperty.Name)
{
this.SynchronizeColumns();
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Web;
using System.Xml;
using Umbraco.Core;
using Umbraco.Core.Cache;
using Umbraco.Core.Models.Rdbms;
using umbraco.cms.businesslogic.cache;
using umbraco.BusinessLogic;
using umbraco.DataLayer;
using System.Web.Security;
using System.Text;
using System.Security.Cryptography;
using System.Linq;
namespace umbraco.cms.businesslogic.member
{
/// <summary>
/// The Member class represents a member of the public website (not to be confused with umbraco users)
///
/// Members are used when creating communities and collaborative applications using umbraco, or if there are a
/// need for identifying or authentifying the visitor. (extranets, protected/private areas of the public website)
///
/// Inherits generic datafields from it's baseclass content.
/// </summary>
public class Member : Content
{
#region Constants and static members
public static readonly string UmbracoMemberProviderName = "UmbracoMembershipProvider";
public static readonly string UmbracoRoleProviderName = "UmbracoRoleProvider";
public static readonly Guid _objectType = new Guid(Constants.ObjectTypes.Member);
private static readonly object m_Locker = new object();
// zb-00004 #29956 : refactor cookies names & handling
private const string m_SQLOptimizedMany = @"
select
umbracoNode.id, umbracoNode.uniqueId, umbracoNode.level,
umbracoNode.parentId, umbracoNode.path, umbracoNode.sortOrder, umbracoNode.createDate,
umbracoNode.nodeUser, umbracoNode.text,
cmsMember.Email, cmsMember.LoginName, cmsMember.Password
from umbracoNode
inner join cmsContent on cmsContent.nodeId = umbracoNode.id
inner join cmsMember on cmsMember.nodeId = cmsContent.nodeId
where umbracoNode.nodeObjectType = @nodeObjectType AND {0}
order by {1}";
#endregion
#region Private members
private string m_Text;
private string m_Email;
private string m_Password;
private string m_LoginName;
private Hashtable m_Groups = null;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the Member class.
/// </summary>
/// <param name="id">Identifier</param>
public Member(int id) : base(id) { }
/// <summary>
/// Initializes a new instance of the Member class.
/// </summary>
/// <param name="id">Identifier</param>
public Member(Guid id) : base(id) { }
/// <summary>
/// Initializes a new instance of the Member class, with an option to only initialize
/// the data used by the tree in the umbraco console.
/// </summary>
/// <param name="id">Identifier</param>
/// <param name="noSetup"></param>
public Member(int id, bool noSetup) : base(id, noSetup) { }
public Member(Guid id, bool noSetup) : base(id, noSetup) { }
#endregion
#region Static methods
/// <summary>
/// A list of all members in the current umbraco install
///
/// Note: is ressource intensive, use with care.
/// </summary>
public static Member[] GetAll
{
get
{
return GetAllAsList().ToArray();
}
}
public static IEnumerable<Member> GetAllAsList()
{
var tmp = new List<Member>();
using (IRecordsReader dr = SqlHelper.ExecuteReader(
string.Format(m_SQLOptimizedMany.Trim(), "1=1", "umbracoNode.text"),
SqlHelper.CreateParameter("@nodeObjectType", Member._objectType)))
{
while (dr.Read())
{
Member m = new Member(dr.GetInt("id"), true);
m.PopulateMemberFromReader(dr);
tmp.Add(m);
}
}
return tmp.ToArray();
}
/// <summary>
/// Retrieves a list of members thats not start with a-z
/// </summary>
/// <returns>array of members</returns>
public static Member[] getAllOtherMembers()
{
var tmp = new List<Member>();
using (IRecordsReader dr = SqlHelper.ExecuteReader(
string.Format(m_SQLOptimizedMany.Trim(), "LOWER(SUBSTRING(text, 1, 1)) NOT IN ('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z')", "umbracoNode.text"),
SqlHelper.CreateParameter("@nodeObjectType", Member._objectType)))
{
while (dr.Read())
{
Member m = new Member(dr.GetInt("id"), true);
m.PopulateMemberFromReader(dr);
tmp.Add(m);
}
}
return tmp.ToArray();
}
/// <summary>
/// Retrieves a list of members by the first letter in their name.
/// </summary>
/// <param name="letter">The first letter</param>
/// <returns></returns>
public static Member[] getMemberFromFirstLetter(char letter)
{
return GetMemberByName(letter.ToString(), true);
}
public static Member[] GetMemberByName(string usernameToMatch, bool matchByNameInsteadOfLogin)
{
string field = matchByNameInsteadOfLogin ? "umbracoNode.text" : "cmsMember.loginName";
var tmp = new List<Member>();
using (IRecordsReader dr = SqlHelper.ExecuteReader(
string.Format(m_SQLOptimizedMany.Trim(),
string.Format("{0} like @letter", field),
"umbracoNode.text"),
SqlHelper.CreateParameter("@nodeObjectType", Member._objectType),
SqlHelper.CreateParameter("@letter", usernameToMatch + "%")))
{
while (dr.Read())
{
Member m = new Member(dr.GetInt("id"), true);
m.PopulateMemberFromReader(dr);
tmp.Add(m);
}
}
return tmp.ToArray();
}
/// <summary>
/// Creates a new member
/// </summary>
/// <param name="Name">Membername</param>
/// <param name="mbt">Member type</param>
/// <param name="u">The umbraco usercontext</param>
/// <returns>The new member</returns>
public static Member MakeNew(string Name, MemberType mbt, User u)
{
return MakeNew(Name, "", "", mbt, u);
}
/// <summary>
/// Creates a new member
/// </summary>
/// <param name="Name">Membername</param>
/// <param name="mbt">Member type</param>
/// <param name="u">The umbraco usercontext</param>
/// <param name="Email">The email of the user</param>
/// <returns>The new member</returns>
public static Member MakeNew(string Name, string Email, MemberType mbt, User u)
{
return MakeNew(Name, "", Email, mbt, u);
}
/// <summary>
/// Creates a new member
/// </summary>
/// <param name="Name">Membername</param>
/// <param name="mbt">Member type</param>
/// <param name="u">The umbraco usercontext</param>
/// <param name="Email">The email of the user</param>
/// <returns>The new member</returns>
public static Member MakeNew(string Name, string LoginName, string Email, MemberType mbt, User u)
{
var loginName = (!String.IsNullOrEmpty(LoginName)) ? LoginName : Name;
if (String.IsNullOrEmpty(loginName))
throw new ArgumentException("The loginname must be different from an empty string", "loginName");
// Test for e-mail
if (Email != "" && Member.GetMemberFromEmail(Email) != null && Membership.Providers[UmbracoMemberProviderName].RequiresUniqueEmail)
throw new Exception(String.Format("Duplicate Email! A member with the e-mail {0} already exists", Email));
else if (Member.GetMemberFromLoginName(loginName) != null)
throw new Exception(String.Format("Duplicate User name! A member with the user name {0} already exists", loginName));
// Lowercased to prevent duplicates
Email = Email.ToLower();
Guid newId = Guid.NewGuid();
//create the cms node first
CMSNode newNode = MakeNew(-1, _objectType, u.Id, 1, Name, newId);
//we need to create an empty member and set the underlying text property
Member tmp = new Member(newId, true);
tmp.SetText(Name);
//create the content data for the new member
tmp.CreateContent(mbt);
// Create member specific data ..
SqlHelper.ExecuteNonQuery(
"insert into cmsMember (nodeId,Email,LoginName,Password) values (@id,@email,@loginName,'')",
SqlHelper.CreateParameter("@id", tmp.Id),
SqlHelper.CreateParameter("@loginName", loginName),
SqlHelper.CreateParameter("@email", Email));
//read the whole object from the db
Member m = new Member(newId);
NewEventArgs e = new NewEventArgs();
m.OnNew(e);
m.Save();
return m;
}
/// <summary>
/// Retrieve a member given the loginname
///
/// Used when authentifying the Member
/// </summary>
/// <param name="loginName">The unique Loginname</param>
/// <returns>The member with the specified loginname - null if no Member with the login exists</returns>
public static Member GetMemberFromLoginName(string loginName)
{
if (String.IsNullOrEmpty(loginName))
throw new ArgumentException("The username of a Member must be different from an emptry string", "loginName");
if (IsMember(loginName))
{
object o = SqlHelper.ExecuteScalar<object>(
"select nodeID from cmsMember where LoginName = @loginName",
SqlHelper.CreateParameter("@loginName", loginName));
if (o == null)
return null;
int tmpId;
if (!int.TryParse(o.ToString(), out tmpId))
return null;
return new Member(tmpId);
}
else
HttpContext.Current.Trace.Warn("No member with loginname: " + loginName + " Exists");
return null;
}
/// <summary>
/// Retrieve a Member given an email, the first if there multiple members with same email
///
/// Used when authentifying the Member
/// </summary>
/// <param name="email">The email of the member</param>
/// <returns>The member with the specified email - null if no Member with the email exists</returns>
public static Member GetMemberFromEmail(string email)
{
if (string.IsNullOrEmpty(email))
return null;
object o = SqlHelper.ExecuteScalar<object>(
"select nodeID from cmsMember where Email = @email",
SqlHelper.CreateParameter("@email", email.ToLower()));
if (o == null)
return null;
int tmpId;
if (!int.TryParse(o.ToString(), out tmpId))
return null;
return new Member(tmpId);
}
/// <summary>
/// Retrieve Members given an email
///
/// Used when authentifying a Member
/// </summary>
/// <param name="email">The email of the member(s)</param>
/// <returns>The members with the specified email</returns>
public static Member[] GetMembersFromEmail(string email)
{
if (string.IsNullOrEmpty(email))
return null;
var tmp = new List<Member>();
using (IRecordsReader dr = SqlHelper.ExecuteReader(string.Format(m_SQLOptimizedMany.Trim(),
"Email = @email",
"umbracoNode.text"),
SqlHelper.CreateParameter("@nodeObjectType", Member._objectType),
SqlHelper.CreateParameter("@email", email.ToLower())))
{
while (dr.Read())
{
Member m = new Member(dr.GetInt("id"), true);
m.PopulateMemberFromReader(dr);
tmp.Add(m);
}
}
return tmp.ToArray();
}
/// <summary>
/// Retrieve a Member given the credentials
///
/// Used when authentifying the member
/// </summary>
/// <param name="loginName">Member login</param>
/// <param name="password">Member password</param>
/// <returns>The member with the credentials - null if none exists</returns>
public static Member GetMemberFromLoginNameAndPassword(string loginName, string password)
{
if (IsMember(loginName))
{
// validate user via provider
if (Membership.ValidateUser(loginName, password))
{
return GetMemberFromLoginName(loginName);
}
else
{
HttpContext.Current.Trace.Warn("Incorrect login/password");
return null;
}
}
else
{
HttpContext.Current.Trace.Warn("No member with loginname: " + loginName + " Exists");
// throw new ArgumentException("No member with Loginname: " + LoginName + " exists");
return null;
}
}
public static Member GetMemberFromLoginAndEncodedPassword(string loginName, string password)
{
object o = SqlHelper.ExecuteScalar<object>(
"select nodeID from cmsMember where LoginName = @loginName and Password = @password",
SqlHelper.CreateParameter("loginName", loginName),
SqlHelper.CreateParameter("password", password));
if (o == null)
return null;
int tmpId;
if (!int.TryParse(o.ToString(), out tmpId))
return null;
return new Member(tmpId);
}
public static bool InUmbracoMemberMode()
{
return Membership.Provider.Name == UmbracoMemberProviderName;
}
public static bool IsUsingUmbracoRoles()
{
return Roles.Provider.Name == UmbracoRoleProviderName;
}
/// <summary>
/// Helper method - checks if a Member with the LoginName exists
/// </summary>
/// <param name="loginName">Member login</param>
/// <returns>True if the member exists</returns>
public static bool IsMember(string loginName)
{
Debug.Assert(loginName != null, "loginName cannot be null");
object o = SqlHelper.ExecuteScalar<object>(
"select count(nodeID) as tmp from cmsMember where LoginName = @loginName",
SqlHelper.CreateParameter("@loginName", loginName));
if (o == null)
return false;
int count;
if (!int.TryParse(o.ToString(), out count))
return false;
return count > 0;
}
/// <summary>
/// Deletes all members of the membertype specified
///
/// Used when a membertype is deleted
///
/// Use with care
/// </summary>
/// <param name="dt">The membertype which are being deleted</param>
public static void DeleteFromType(MemberType dt)
{
var objs = getContentOfContentType(dt);
foreach (Content c in objs)
{
// due to recursive structure document might already been deleted..
if (IsNode(c.UniqueId))
{
Member tmp = new Member(c.UniqueId);
tmp.delete();
}
}
}
#endregion
#region Public Properties
/// <summary>
/// The name of the member
/// </summary>
public override string Text
{
get
{
if (string.IsNullOrEmpty(m_Text))
{
m_Text = SqlHelper.ExecuteScalar<string>(
"select text from umbracoNode where id = @id",
SqlHelper.CreateParameter("@id", Id));
}
return m_Text;
}
set
{
m_Text = value;
base.Text = value;
}
}
/// <summary>
/// The members password, used when logging in on the public website
/// </summary>
public string Password
{
get
{
if (string.IsNullOrEmpty(m_Password))
{
m_Password = SqlHelper.ExecuteScalar<string>(
"select Password from cmsMember where nodeId = @id",
SqlHelper.CreateParameter("@id", Id));
}
return m_Password;
}
set
{
// We need to use the provider for this in order for hashing, etc. support
// To write directly to the db use the ChangePassword method
// this is not pretty but nessecary due to a design flaw (the membership provider should have been a part of the cms project)
MemberShipHelper helper = new MemberShipHelper();
ChangePassword(helper.EncodePassword(value, Membership.Provider.PasswordFormat));
}
}
/// <summary>
/// The loginname of the member, used when logging in
/// </summary>
public string LoginName
{
get
{
if (string.IsNullOrEmpty(m_LoginName))
{
m_LoginName = SqlHelper.ExecuteScalar<string>(
"select LoginName from cmsMember where nodeId = @id",
SqlHelper.CreateParameter("@id", Id));
}
return m_LoginName;
}
set
{
if (String.IsNullOrEmpty(value))
throw new ArgumentException("The loginname must be different from an empty string", "LoginName");
if (value.Contains(","))
throw new ArgumentException("The parameter 'LoginName' must not contain commas.");
SqlHelper.ExecuteNonQuery(
"update cmsMember set LoginName = @loginName where nodeId = @id",
SqlHelper.CreateParameter("@loginName", value),
SqlHelper.CreateParameter("@id", Id));
m_LoginName = value;
}
}
/// <summary>
/// A list of groups the member are member of
/// </summary>
public Hashtable Groups
{
get
{
if (m_Groups == null)
PopulateGroups();
return m_Groups;
}
}
/// <summary>
/// The members email
/// </summary>
public string Email
{
get
{
if (String.IsNullOrEmpty(m_Email))
{
m_Email = SqlHelper.ExecuteScalar<string>(
"select Email from cmsMember where nodeId = @id",
SqlHelper.CreateParameter("@id", Id));
}
return string.IsNullOrWhiteSpace(m_Email) ? m_Email : m_Email.ToLower();
}
set
{
var oldEmail = Email;
var newEmail = string.IsNullOrWhiteSpace(value) ? value : value.ToLower();
var requireUniqueEmail = Membership.Providers[UmbracoMemberProviderName].RequiresUniqueEmail;
var howManyMembersWithEmail = 0;
var membersWithEmail = GetMembersFromEmail(newEmail);
if (membersWithEmail != null)
howManyMembersWithEmail = membersWithEmail.Length;
if (((oldEmail == newEmail && howManyMembersWithEmail > 1) ||
(oldEmail != newEmail && howManyMembersWithEmail > 0))
&& requireUniqueEmail)
{
// If the value hasn't changed and there are more than 1 member with that email, then throw
// If the value has changed and there are any member with that new email, then throw
throw new Exception(String.Format("Duplicate Email! A member with the e-mail {0} already exists", newEmail));
}
SqlHelper.ExecuteNonQuery(
"update cmsMember set Email = @email where nodeId = @id",
SqlHelper.CreateParameter("@id", Id), SqlHelper.CreateParameter("@email", newEmail));
// Set the backing field to new value
m_Email = newEmail;
}
}
#endregion
#region Public Methods
protected override void setupNode()
{
base.setupNode();
using (IRecordsReader dr = SqlHelper.ExecuteReader(
@"SELECT Email, LoginName, Password FROM cmsMember WHERE nodeId=@nodeId",
SqlHelper.CreateParameter("@nodeId", this.Id)))
{
if (dr.Read())
{
if (!dr.IsNull("Email"))
m_Email = dr.GetString("Email");
m_LoginName = dr.GetString("LoginName");
m_Password = dr.GetString("Password");
}
else
{
throw new ArgumentException(string.Format("No Member exists with Id '{0}'", this.Id));
}
}
}
/// <summary>
/// Used to persist object changes to the database. In Version3.0 it's just a stub for future compatibility
/// </summary>
public override void Save()
{
SaveEventArgs e = new SaveEventArgs();
FireBeforeSave(e);
if (!e.Cancel)
{
var db = ApplicationContext.Current.DatabaseContext.Database;
using (var transaction = db.GetTransaction())
{
foreach (var property in GenericProperties)
{
var poco = new PropertyDataDto
{
Id = property.Id,
PropertyTypeId = property.PropertyType.Id,
NodeId = Id,
VersionId = property.VersionId
};
if (property.Value != null)
{
string dbType = property.PropertyType.DataTypeDefinition.DbType;
if (dbType.Equals("Integer"))
{
if (property.Value is bool || property.PropertyType.DataTypeDefinition.DataType.Id == new Guid("38b352c1-e9f8-4fd8-9324-9a2eab06d97a"))
{
poco.Integer = property.Value != null && string.IsNullOrEmpty(property.Value.ToString())
? 0
: Convert.ToInt32(property.Value);
}
else
{
int value = 0;
if (int.TryParse(property.Value.ToString(), out value))
{
poco.Integer = value;
}
}
}
else if (dbType.Equals("Date"))
{
DateTime date;
if(DateTime.TryParse(property.Value.ToString(), out date))
poco.Date = date;
}
else if (dbType.Equals("Nvarchar"))
{
poco.VarChar = property.Value.ToString();
}
else
{
poco.Text = property.Value.ToString();
}
}
bool isNew = db.IsNew(poco);
if (isNew)
{
db.Insert(poco);
}
else
{
db.Update(poco);
}
}
transaction.Complete();
}
// re-generate xml
XmlDocument xd = new XmlDocument();
XmlGenerate(xd);
// generate preview for blame history?
if (UmbracoSettings.EnableGlobalPreviewStorage)
{
// Version as new guid to ensure different versions are generated as members are not versioned currently!
SavePreviewXml(generateXmlWithoutSaving(xd), Guid.NewGuid());
}
FireAfterSave(e);
}
}
/// <summary>
/// Xmlrepresentation of a member
/// </summary>
/// <param name="xd">The xmldocument context</param>
/// <param name="Deep">Recursive - should always be set to false</param>
/// <returns>A the xmlrepresentation of the current member</returns>
public override XmlNode ToXml(XmlDocument xd, bool Deep)
{
XmlNode x = base.ToXml(xd, Deep);
if (x.Attributes["loginName"] == null)
{
x.Attributes.Append(xmlHelper.addAttribute(xd, "loginName", LoginName));
x.Attributes.Append(xmlHelper.addAttribute(xd, "email", Email));
}
return x;
}
/// <summary>
/// Deltes the current member
/// </summary>
public override void delete()
{
DeleteEventArgs e = new DeleteEventArgs();
FireBeforeDelete(e);
if (!e.Cancel)
{
// delete all relations to groups
foreach (int groupId in this.Groups.Keys)
{
RemoveGroup(groupId);
}
// delete memeberspecific data!
SqlHelper.ExecuteNonQuery("Delete from cmsMember where nodeId = @id",
SqlHelper.CreateParameter("@id", Id));
// Delete all content and cmsnode specific data!
base.delete();
FireAfterDelete(e);
}
}
public void ChangePassword(string newPassword)
{
SqlHelper.ExecuteNonQuery(
"update cmsMember set Password = @password where nodeId = @id",
SqlHelper.CreateParameter("@password", newPassword),
SqlHelper.CreateParameter("@id", Id));
//update this object's password
m_Password = newPassword;
}
/// <summary>
/// Adds the member to group with the specified id
/// </summary>
/// <param name="GroupId">The id of the group which the member is being added to</param>
[MethodImpl(MethodImplOptions.Synchronized)]
public void AddGroup(int GroupId)
{
AddGroupEventArgs e = new AddGroupEventArgs();
e.GroupId = GroupId;
FireBeforeAddGroup(e);
if (!e.Cancel)
{
IParameter[] parameters = new IParameter[] { SqlHelper.CreateParameter("@id", Id),
SqlHelper.CreateParameter("@groupId", GroupId) };
bool exists = SqlHelper.ExecuteScalar<int>("SELECT COUNT(member) FROM cmsMember2MemberGroup WHERE member = @id AND memberGroup = @groupId",
parameters) > 0;
if (!exists)
SqlHelper.ExecuteNonQuery("INSERT INTO cmsMember2MemberGroup (member, memberGroup) values (@id, @groupId)",
parameters);
PopulateGroups();
FireAfterAddGroup(e);
}
}
/// <summary>
/// Removes the member from the MemberGroup specified
/// </summary>
/// <param name="GroupId">The MemberGroup from which the Member is removed</param>
public void RemoveGroup(int GroupId)
{
RemoveGroupEventArgs e = new RemoveGroupEventArgs();
e.GroupId = GroupId;
FireBeforeRemoveGroup(e);
if (!e.Cancel)
{
SqlHelper.ExecuteNonQuery(
"delete from cmsMember2MemberGroup where member = @id and Membergroup = @groupId",
SqlHelper.CreateParameter("@id", Id), SqlHelper.CreateParameter("@groupId", GroupId));
PopulateGroups();
FireAfterRemoveGroup(e);
}
}
#endregion
#region Protected methods
protected override XmlNode generateXmlWithoutSaving(XmlDocument xd)
{
XmlNode node = xd.CreateNode(XmlNodeType.Element, "node", "");
XmlPopulate(xd, ref node, false);
node.Attributes.Append(xmlHelper.addAttribute(xd, "loginName", LoginName));
node.Attributes.Append(xmlHelper.addAttribute(xd, "email", Email));
return node;
}
protected void PopulateMemberFromReader(IRecordsReader dr)
{
SetupNodeForTree(dr.GetGuid("uniqueId"),
_objectType, dr.GetShort("level"),
dr.GetInt("parentId"),
dr.GetInt("nodeUser"),
dr.GetString("path"),
dr.GetString("text"),
dr.GetDateTime("createDate"), false);
if (!dr.IsNull("Email"))
m_Email = dr.GetString("Email");
m_LoginName = dr.GetString("LoginName");
m_Password = dr.GetString("Password");
}
#endregion
#region Private methods
private void PopulateGroups()
{
var temp = new Hashtable();
using (var dr = SqlHelper.ExecuteReader(
"select memberGroup from cmsMember2MemberGroup where member = @id",
SqlHelper.CreateParameter("@id", Id)))
{
while (dr.Read())
temp.Add(dr.GetInt("memberGroup"),
new MemberGroup(dr.GetInt("memberGroup")));
}
m_Groups = temp;
}
private static string GetCacheKey(int id)
{
return string.Format("{0}{1}", CacheKeys.MemberBusinessLogicCacheKey, id);
}
// zb-00035 #29931 : helper class to handle member state
class MemberState
{
public int MemberId { get; set; }
public Guid MemberGuid { get; set; }
public string MemberLogin { get; set; }
public MemberState(int memberId, Guid memberGuid, string memberLogin)
{
MemberId = memberId;
MemberGuid = memberGuid;
MemberLogin = memberLogin;
}
}
// zb-00035 #29931 : helper methods to handle member state
[Obsolete("Only use .NET Membership APIs to handle state now", true)]
static void SetMemberState(Member member)
{
SetMemberState(member.Id, member.UniqueId, member.LoginName);
}
[Obsolete("Only use .NET Membership APIs to handle state now", true)]
static void SetMemberState(int memberId, Guid memberGuid, string memberLogin)
{
string value = string.Format("{0}+{1}+{2}", memberId, memberGuid, memberLogin);
// zb-00004 #29956 : refactor cookies names & handling
StateHelper.Cookies.Member.SetValue(value);
}
[Obsolete("Only use .NET Membership APIs to handle state now", true)]
static void SetMemberState(Member member, bool useSession, double cookieDays)
{
SetMemberState(member.Id, member.UniqueId, member.LoginName, useSession, cookieDays);
}
[Obsolete("Only use .NET Membership APIs to handle state now", true)]
static void SetMemberState(int memberId, Guid memberGuid, string memberLogin, bool useSession, double cookieDays)
{
string value = string.Format("{0}+{1}+{2}", memberId, memberGuid, memberLogin);
// zb-00004 #29956 : refactor cookies names & handling
if (useSession)
HttpContext.Current.Session[StateHelper.Cookies.Member.Key] = value;
else
StateHelper.Cookies.Member.SetValue(value, cookieDays);
}
[Obsolete("Only use .NET Membership APIs to handle state now", true)]
static void ClearMemberState()
{
// zb-00004 #29956 : refactor cookies names & handling
StateHelper.Cookies.Member.Clear();
FormsAuthentication.SignOut();
}
[Obsolete("Only use .NET Membership APIs to handle state now", true)]
static MemberState GetMemberState()
{
// NH: Refactor to fix issue 30171, where auth using pure .NET Members doesn't clear old Umbraco cookie, thus this method gets the previous
// umbraco user instead of the new one
// zb-00004 #29956 : refactor cookies names & handling + bring session-related stuff here
string value = null;
if (StateHelper.Cookies.Member.HasValue)
{
value = StateHelper.Cookies.Member.GetValue();
if (!String.IsNullOrEmpty(value))
{
string validateMemberId = value.Substring(0, value.IndexOf("+"));
if (Membership.GetUser() == null || validateMemberId != Membership.GetUser().ProviderUserKey.ToString())
{
Member.RemoveMemberFromCache(int.Parse(validateMemberId));
value = String.Empty;
}
}
}
// compatibility with .NET Memberships
if (String.IsNullOrEmpty(value) && HttpContext.Current.User.Identity.IsAuthenticated)
{
int _currentMemberId = 0;
if (int.TryParse(Membership.GetUser().ProviderUserKey.ToString(), out _currentMemberId))
{
if (memberExists(_currentMemberId))
{
// current member is always in the cache, else add it!
Member m = GetMemberFromCache(_currentMemberId);
if (m == null)
{
m = new Member(_currentMemberId);
AddMemberToCache(m);
}
return new MemberState(m.Id, m.UniqueId, m.LoginName);
}
}
}
else
{
var context = HttpContext.Current;
if (context != null && context.Session != null && context.Session[StateHelper.Cookies.Member.Key] != null)
{
string v = context.Session[StateHelper.Cookies.Member.Key].ToString();
if (v != "0")
value = v;
}
}
if (value == null)
return null;
// #30350 - do not use Split as memberLogin could contain '+'
int pos1 = value.IndexOf('+');
if (pos1 < 0)
return null;
int pos2 = value.IndexOf('+', pos1 + 1);
if (pos2 < 0)
return null;
int memberId;
if (!Int32.TryParse(value.Substring(0, pos1), out memberId))
return null;
Guid memberGuid;
try
{
// Guid.TryParse is in .NET 4 only
// using try...catch for .NET 3.5 compatibility
memberGuid = new Guid(value.Substring(pos1 + 1, pos2 - pos1 - 1));
}
catch
{
return null;
}
MemberState ms = new MemberState(memberId, memberGuid, value.Substring(pos2 + 1));
return ms;
}
#endregion
#region MemberHandle functions
/// <summary>
/// Method is used when logging a member in.
///
/// Adds the member to the cache of logged in members
///
/// Uses cookiebased recognition
///
/// Can be used in the runtime
/// </summary>
/// <param name="m">The member to log in</param>
public static void AddMemberToCache(Member m)
{
if (m != null)
{
AddToCacheEventArgs e = new AddToCacheEventArgs();
m.FireBeforeAddToCache(e);
if (!e.Cancel)
{
// Add cookie with member-id, guid and loginname
// zb-00035 #29931 : cleanup member state management
// NH 4.7.1: We'll no longer use legacy cookies to handle Umbraco Members
//SetMemberState(m);
FormsAuthentication.SetAuthCookie(m.LoginName, true);
//cache the member
var cachedMember = ApplicationContext.Current.ApplicationCache.GetCacheItem(
GetCacheKey(m.Id),
TimeSpan.FromMinutes(30),
() =>
{
// Debug information
HttpContext.Current.Trace.Write("member",
string.Format("Member added to cache: {0}/{1} ({2})",
m.Text, m.LoginName, m.Id));
return m;
});
m.FireAfterAddToCache(e);
}
}
}
// zb-00035 #29931 : remove old cookie code
/// <summary>
/// Method is used when logging a member in.
///
/// Adds the member to the cache of logged in members
///
/// Uses cookie or session based recognition
///
/// Can be used in the runtime
/// </summary>
/// <param name="m">The member to log in</param>
/// <param name="UseSession">create a persistent cookie</param>
/// <param name="TimespanForCookie">Has no effect</param>
[Obsolete("Use the membership api and FormsAuthentication to log users in, this method is no longer used anymore")]
public static void AddMemberToCache(Member m, bool UseSession, TimeSpan TimespanForCookie)
{
if (m != null)
{
var e = new AddToCacheEventArgs();
m.FireBeforeAddToCache(e);
if (!e.Cancel)
{
// zb-00035 #29931 : cleanup member state management
// NH 4.7.1: We'll no longer use Umbraco legacy cookies to handle members
//SetMemberState(m, UseSession, TimespanForCookie.TotalDays);
FormsAuthentication.SetAuthCookie(m.LoginName, !UseSession);
//cache the member
var cachedMember = ApplicationContext.Current.ApplicationCache.GetCacheItem(
GetCacheKey(m.Id),
TimeSpan.FromMinutes(30),
() =>
{
// Debug information
HttpContext.Current.Trace.Write("member",
string.Format("Member added to cache: {0}/{1} ({2})",
m.Text, m.LoginName, m.Id));
return m;
});
m.FireAfterAddToCache(e);
}
}
}
/// <summary>
/// Removes the member from the cache
///
/// Can be used in the public website
/// </summary>
/// <param name="m">Member to remove</param>
[Obsolete("Obsolete, use the RemoveMemberFromCache(int NodeId) instead", false)]
public static void RemoveMemberFromCache(Member m)
{
RemoveMemberFromCache(m.Id);
}
/// <summary>
/// Removes the member from the cache
///
/// Can be used in the public website
/// </summary>
/// <param name="NodeId">Node Id of the member to remove</param>
[Obsolete("Member cache is automatically cleared when members are updated")]
public static void RemoveMemberFromCache(int NodeId)
{
ApplicationContext.Current.ApplicationCache.ClearCacheItem(GetCacheKey(NodeId));
}
/// <summary>
/// Deletes the member cookie from the browser
///
/// Can be used in the public website
/// </summary>
/// <param name="m">Member</param>
[Obsolete("Obsolete, use the ClearMemberFromClient(int NodeId) instead", false)]
public static void ClearMemberFromClient(Member m)
{
if (m != null)
ClearMemberFromClient(m.Id);
else
{
// If the member doesn't exists as an object, we'll just make sure that cookies are cleared
// zb-00035 #29931 : cleanup member state management
ClearMemberState();
}
FormsAuthentication.SignOut();
}
/// <summary>
/// Deletes the member cookie from the browser
///
/// Can be used in the public website
/// </summary>
/// <param name="NodeId">The Node id of the member to clear</param>
[Obsolete("Use FormsAuthentication.SignOut instead")]
public static void ClearMemberFromClient(int NodeId)
{
// zb-00035 #29931 : cleanup member state management
// NH 4.7.1: We'll no longer use legacy Umbraco cookies to handle members
// ClearMemberState();
FormsAuthentication.SignOut();
RemoveMemberFromCache(NodeId);
}
/// <summary>
/// Retrieve a collection of members in the cache
///
/// Can be used from the public website
/// </summary>
/// <returns>A collection of cached members</returns>
public static Hashtable CachedMembers()
{
var h = new Hashtable();
var items = ApplicationContext.Current.ApplicationCache.GetCacheItemsByKeySearch<Member>(
CacheKeys.MemberBusinessLogicCacheKey);
foreach (var i in items)
{
h.Add(i.Id, i);
}
return h;
}
/// <summary>
/// Retrieve a member from the cache
///
/// Can be used from the public website
/// </summary>
/// <param name="id">Id of the member</param>
/// <returns>If the member is cached it returns the member - else null</returns>
public static Member GetMemberFromCache(int id)
{
Hashtable members = CachedMembers();
if (members.ContainsKey(id))
return (Member)members[id];
else
return null;
}
/// <summary>
/// An indication if the current visitor is logged in
///
/// Can be used from the public website
/// </summary>
/// <returns>True if the the current visitor is logged in</returns>
public static bool IsLoggedOn()
{
if (HttpContext.Current.User == null)
return false;
//if member is not auth'd , but still might have a umb cookie saying otherwise...
if (!HttpContext.Current.User.Identity.IsAuthenticated)
{
int _currentMemberId = CurrentMemberId();
//if we have a cookie...
if (_currentMemberId > 0)
{
//log in the member so .net knows about the member..
FormsAuthentication.SetAuthCookie(new Member(_currentMemberId).LoginName, true);
//making sure that the correct status is returned first time around...
return true;
}
}
return HttpContext.Current.User.Identity.IsAuthenticated;
}
/// <summary>
/// Make a lookup in the database to verify if a member truely exists
/// </summary>
/// <param name="NodeId">The node id of the member</param>
/// <returns>True is a record exists in db</returns>
private static bool memberExists(int NodeId)
{
return SqlHelper.ExecuteScalar<int>("select count(nodeId) from cmsMember where nodeId = @nodeId", SqlHelper.CreateParameter("@nodeId", NodeId)) == 1;
}
/// <summary>
/// Gets the current visitors memberid
/// </summary>
/// <returns>The current visitors members id, if the visitor is not logged in it returns 0</returns>
public static int CurrentMemberId()
{
int _currentMemberId = 0;
// For backwards compatibility between umbraco members and .net membership
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
int.TryParse(Membership.GetUser().ProviderUserKey.ToString(), out _currentMemberId);
}
// NH 4.7.1: We'll no longer use legacy Umbraco cookies to handle members
/*
else
{
// zb-00035 #29931 : cleanup member state management
MemberState ms = GetMemberState();
if (ms != null)
_currentMemberId = ms.MemberId;
}
if (_currentMemberId > 0 && !memberExists(_currentMemberId))
{
_currentMemberId = 0;
// zb-00035 #29931 : cleanup member state management
ClearMemberState();
}
*/
return _currentMemberId;
}
/// <summary>
/// Get the current member
/// </summary>
/// <returns>Returns the member, if visitor is not logged in: null</returns>
public static Member GetCurrentMember()
{
try
{
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
// zb-00035 #29931 : cleanup member state management
/*MemberState ms = GetMemberState();
if (ms == null || ms.MemberId == 0)
return null;
// return member from cache
Member member = GetMemberFromCache(ms.MemberId);
if (member == null)
member = new Member(ms.MemberId);
*/
int _currentMemberId = 0;
if (int.TryParse(Membership.GetUser().ProviderUserKey.ToString(), out _currentMemberId))
{
Member m = new Member(_currentMemberId);
return m;
}
}
}
catch
{
}
return null;
}
#endregion
#region Events
/// <summary>
/// The save event handler
/// </summary>
public delegate void SaveEventHandler(Member sender, SaveEventArgs e);
/// <summary>
/// The new event handler
/// </summary>
public delegate void NewEventHandler(Member sender, NewEventArgs e);
/// <summary>
/// The delete event handler
/// </summary>
public delegate void DeleteEventHandler(Member sender, DeleteEventArgs e);
/// <summary>
/// The add to cache event handler
/// </summary>
public delegate void AddingToCacheEventHandler(Member sender, AddToCacheEventArgs e);
/// <summary>
/// The add group event handler
/// </summary>
public delegate void AddingGroupEventHandler(Member sender, AddGroupEventArgs e);
/// <summary>
/// The remove group event handler
/// </summary>
public delegate void RemovingGroupEventHandler(Member sender, RemoveGroupEventArgs e);
/// <summary>
/// Occurs when [before save].
/// </summary>
new public static event SaveEventHandler BeforeSave;
/// <summary>
/// Raises the <see cref="E:BeforeSave"/> event.
/// </summary>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
new protected virtual void FireBeforeSave(SaveEventArgs e)
{
if (BeforeSave != null)
{
BeforeSave(this, e);
}
}
new public static event SaveEventHandler AfterSave;
new protected virtual void FireAfterSave(SaveEventArgs e)
{
if (AfterSave != null)
{
AfterSave(this, e);
}
}
public static event NewEventHandler New;
protected virtual void OnNew(NewEventArgs e)
{
if (New != null)
{
New(this, e);
}
}
public static event AddingGroupEventHandler BeforeAddGroup;
protected virtual void FireBeforeAddGroup(AddGroupEventArgs e)
{
if (BeforeAddGroup != null)
{
BeforeAddGroup(this, e);
}
}
public static event AddingGroupEventHandler AfterAddGroup;
protected virtual void FireAfterAddGroup(AddGroupEventArgs e)
{
if (AfterAddGroup != null)
{
AfterAddGroup(this, e);
}
}
public static event RemovingGroupEventHandler BeforeRemoveGroup;
protected virtual void FireBeforeRemoveGroup(RemoveGroupEventArgs e)
{
if (BeforeRemoveGroup != null)
{
BeforeRemoveGroup(this, e);
}
}
public static event RemovingGroupEventHandler AfterRemoveGroup;
protected virtual void FireAfterRemoveGroup(RemoveGroupEventArgs e)
{
if (AfterRemoveGroup != null)
{
AfterRemoveGroup(this, e);
}
}
public static event AddingToCacheEventHandler BeforeAddToCache;
protected virtual void FireBeforeAddToCache(AddToCacheEventArgs e)
{
if (BeforeAddToCache != null)
{
BeforeAddToCache(this, e);
}
}
public static event AddingToCacheEventHandler AfterAddToCache;
protected virtual void FireAfterAddToCache(AddToCacheEventArgs e)
{
if (AfterAddToCache != null)
{
AfterAddToCache(this, e);
}
}
new public static event DeleteEventHandler BeforeDelete;
new protected virtual void FireBeforeDelete(DeleteEventArgs e)
{
if (BeforeDelete != null)
{
BeforeDelete(this, e);
}
}
new public static event DeleteEventHandler AfterDelete;
new protected virtual void FireAfterDelete(DeleteEventArgs e)
{
if (AfterDelete != null)
{
AfterDelete(this, e);
}
}
#endregion
#region Membership helper class used for encryption methods
/// <summary>
/// ONLY FOR INTERNAL USE.
/// This is needed due to a design flaw where the Umbraco membership provider is located
/// in a separate project referencing this project, which means we can't call special methods
/// directly on the UmbracoMemberShipMember class.
/// This is a helper implementation only to be able to use the encryption functionality
/// of the membership provides (which are protected).
///
/// ... which means this class should have been marked internal with a Friend reference to the other assembly right??
/// </summary>
internal class MemberShipHelper : MembershipProvider
{
public override string ApplicationName
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public override bool ChangePassword(string username, string oldPassword, string newPassword)
{
throw new NotImplementedException();
}
public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer)
{
throw new NotImplementedException();
}
public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status)
{
throw new NotImplementedException();
}
public override bool DeleteUser(string username, bool deleteAllRelatedData)
{
throw new NotImplementedException();
}
public string EncodePassword(string password, MembershipPasswordFormat pwFormat)
{
string encodedPassword = password;
switch (pwFormat)
{
case MembershipPasswordFormat.Clear:
break;
case MembershipPasswordFormat.Encrypted:
encodedPassword =
Convert.ToBase64String(EncryptPassword(Encoding.Unicode.GetBytes(password)));
break;
case MembershipPasswordFormat.Hashed:
HMACSHA1 hash = new HMACSHA1();
hash.Key = Encoding.Unicode.GetBytes(password);
encodedPassword =
Convert.ToBase64String(hash.ComputeHash(Encoding.Unicode.GetBytes(password)));
break;
}
return encodedPassword;
}
public override bool EnablePasswordReset
{
get { throw new NotImplementedException(); }
}
public override bool EnablePasswordRetrieval
{
get { throw new NotImplementedException(); }
}
public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords)
{
throw new NotImplementedException();
}
public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
{
throw new NotImplementedException();
}
public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
{
throw new NotImplementedException();
}
public override int GetNumberOfUsersOnline()
{
throw new NotImplementedException();
}
public override string GetPassword(string username, string answer)
{
throw new NotImplementedException();
}
public override MembershipUser GetUser(string username, bool userIsOnline)
{
throw new NotImplementedException();
}
public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)
{
throw new NotImplementedException();
}
public override string GetUserNameByEmail(string email)
{
throw new NotImplementedException();
}
public override int MaxInvalidPasswordAttempts
{
get { throw new NotImplementedException(); }
}
public override int MinRequiredNonAlphanumericCharacters
{
get { throw new NotImplementedException(); }
}
public override int MinRequiredPasswordLength
{
get { throw new NotImplementedException(); }
}
public override int PasswordAttemptWindow
{
get { throw new NotImplementedException(); }
}
public override MembershipPasswordFormat PasswordFormat
{
get { throw new NotImplementedException(); }
}
public override string PasswordStrengthRegularExpression
{
get { throw new NotImplementedException(); }
}
public override bool RequiresQuestionAndAnswer
{
get { throw new NotImplementedException(); }
}
public override bool RequiresUniqueEmail
{
get { throw new NotImplementedException(); }
}
public override string ResetPassword(string username, string answer)
{
throw new NotImplementedException();
}
public override bool UnlockUser(string userName)
{
throw new NotImplementedException();
}
public override void UpdateUser(MembershipUser user)
{
throw new NotImplementedException();
}
public override bool ValidateUser(string username, string password)
{
throw new NotImplementedException();
}
}
#endregion
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.Activities.DynamicUpdate
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime;
using System.Runtime.Serialization;
using System.ComponentModel;
[DataContract(IsReference = true)]
internal class DynamicUpdateMapEntry
{
static DynamicUpdateMapEntry dummyMapEntry = new DynamicUpdateMapEntry(-1, -1);
DynamicUpdateMap implementationUpdateMap;
int oldActivityId;
int newActivityId;
public DynamicUpdateMapEntry(int oldActivityId, int newActivityId)
{
this.OldActivityId = oldActivityId;
this.NewActivityId = newActivityId;
}
// this is a dummy map entry to be used for creating a NativeActivityUpdateContext
// for calling UpdateInstance() on activities without map entries.
// the OldActivityId and NewActivityId of this dummy map entry are invalid,
// and should not be used anywhere except for creating NativeActivityUpdateContext.
internal static DynamicUpdateMapEntry DummyMapEntry
{
get { return dummyMapEntry; }
}
public int OldActivityId
{
get
{
return this.oldActivityId;
}
private set
{
this.oldActivityId = value;
}
}
public int NewActivityId
{
get
{
return this.newActivityId;
}
private set
{
this.newActivityId = value;
}
}
[DataMember(EmitDefaultValue = false)]
public DynamicUpdateMapEntry Parent
{
get;
set;
}
// Only set when IsRemoval == true && IsParentRemovedOrBlock == false
[DataMember(EmitDefaultValue = false)]
public string DisplayName
{
get;
set;
}
[DataMember(EmitDefaultValue = false)]
public UpdateBlockedReason BlockReason { get; set; }
[DataMember(EmitDefaultValue = false)]
public string BlockReasonMessage { get; set; }
public bool IsRuntimeUpdateBlocked
{
get
{
return BlockReason != UpdateBlockedReason.NotBlocked;
}
}
[DataMember(EmitDefaultValue = false)]
public bool IsUpdateBlockedByUpdateAuthor { get; set; }
public bool IsParentRemovedOrBlocked
{
get
{
for (DynamicUpdateMapEntry parent = this.Parent; parent != null; parent = parent.Parent)
{
if (parent.IsRemoval || parent.IsRuntimeUpdateBlocked || parent.IsUpdateBlockedByUpdateAuthor)
{
return true;
}
}
return false;
}
}
[DataMember(EmitDefaultValue = false)]
public IDictionary<string, object> SavedOriginalValues { get; set; }
[DataMember(EmitDefaultValue = false)]
public object SavedOriginalValueFromParent { get; set; }
[DataMember(EmitDefaultValue = false)]
public EnvironmentUpdateMap EnvironmentUpdateMap
{
get;
set;
}
public DynamicUpdateMap ImplementationUpdateMap
{
get
{
return this.implementationUpdateMap;
}
internal set
{
this.implementationUpdateMap = value;
}
}
[DataMember(EmitDefaultValue = false, Name = "implementationUpdateMap")]
internal DynamicUpdateMap SerializedImplementationUpdateMap
{
get { return this.implementationUpdateMap; }
set { this.implementationUpdateMap = value; }
}
[DataMember(EmitDefaultValue = false, Name = "OldActivityId")]
internal int SerializedOldActivityId
{
get { return this.OldActivityId; }
set { this.OldActivityId = value; }
}
[DataMember(EmitDefaultValue = false, Name = "NewActivityId")]
internal int SerializedNewActivityId
{
get { return this.NewActivityId; }
set { this.NewActivityId = value; }
}
internal bool IsIdChange
{
get
{
return this.NewActivityId > 0 && this.OldActivityId > 0 && this.NewActivityId != this.OldActivityId;
}
}
internal bool IsRemoval
{
get
{
return this.NewActivityId <= 0 && this.OldActivityId > 0;
}
}
internal bool HasEnvironmentUpdates
{
get
{
return this.EnvironmentUpdateMap != null;
}
}
internal static DynamicUpdateMapEntry Merge(DynamicUpdateMapEntry first, DynamicUpdateMapEntry second,
DynamicUpdateMapEntry newParent, DynamicUpdateMap.MergeErrorContext errorContext)
{
Fx.Assert(first.NewActivityId == second.OldActivityId, "Merging mismatched entries");
Fx.Assert((first.Parent == null && second.Parent == null) || (first.Parent.NewActivityId == second.Parent.OldActivityId), "Merging mismatched parents");
DynamicUpdateMapEntry result = new DynamicUpdateMapEntry(first.OldActivityId, second.NewActivityId)
{
Parent = newParent
};
if (second.IsRemoval)
{
if (!result.IsParentRemovedOrBlocked)
{
result.DisplayName = second.DisplayName;
}
}
else
{
result.SavedOriginalValues = Merge(first.SavedOriginalValues, second.SavedOriginalValues);
result.SavedOriginalValueFromParent = first.SavedOriginalValueFromParent ?? second.SavedOriginalValueFromParent;
if (first.BlockReason == UpdateBlockedReason.NotBlocked)
{
result.BlockReason = second.BlockReason;
result.BlockReasonMessage = second.BlockReasonMessage;
}
else
{
result.BlockReason = first.BlockReason;
result.BlockReasonMessage = second.BlockReasonMessage;
}
result.IsUpdateBlockedByUpdateAuthor = first.IsUpdateBlockedByUpdateAuthor || second.IsUpdateBlockedByUpdateAuthor;
errorContext.PushIdSpace(result.NewActivityId);
result.EnvironmentUpdateMap = EnvironmentUpdateMap.Merge(first.EnvironmentUpdateMap, second.EnvironmentUpdateMap, errorContext);
if (!result.IsRuntimeUpdateBlocked && !result.IsUpdateBlockedByUpdateAuthor && !result.IsParentRemovedOrBlocked)
{
result.ImplementationUpdateMap = DynamicUpdateMap.Merge(first.ImplementationUpdateMap, second.ImplementationUpdateMap, errorContext);
}
errorContext.PopIdSpace();
};
return result;
}
internal static IDictionary<string, object> Merge(IDictionary<string, object> first, IDictionary<string, object> second)
{
if (first == null || second == null)
{
return first ?? second;
}
Dictionary<string, object> result = new Dictionary<string, object>(first);
foreach (KeyValuePair<string, object> pair in second)
{
if (!result.ContainsKey(pair.Key))
{
result.Add(pair.Key, pair.Value);
}
}
return result;
}
internal DynamicUpdateMapEntry Clone(DynamicUpdateMapEntry newParent)
{
return new DynamicUpdateMapEntry(this.OldActivityId, this.NewActivityId)
{
DisplayName = this.DisplayName,
EnvironmentUpdateMap = this.EnvironmentUpdateMap,
ImplementationUpdateMap = this.ImplementationUpdateMap,
BlockReason = this.BlockReason,
BlockReasonMessage = this.BlockReasonMessage,
IsUpdateBlockedByUpdateAuthor = this.IsUpdateBlockedByUpdateAuthor,
Parent = newParent,
SavedOriginalValues = this.SavedOriginalValues,
SavedOriginalValueFromParent = this.SavedOriginalValueFromParent
};
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using JCG = J2N.Collections.Generic;
namespace Lucene.Net.Search.Spans
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using AtomicReaderContext = Lucene.Net.Index.AtomicReaderContext;
using IBits = Lucene.Net.Util.IBits;
using IndexReader = Lucene.Net.Index.IndexReader;
using Term = Lucene.Net.Index.Term;
using TermContext = Lucene.Net.Index.TermContext;
using ToStringUtils = Lucene.Net.Util.ToStringUtils;
/// <summary>
/// Matches the union of its clauses. </summary>
public class SpanOrQuery : SpanQuery
#if FEATURE_CLONEABLE
, System.ICloneable
#endif
{
private readonly IList<SpanQuery> clauses;
private string field;
/// <summary>
/// Construct a <see cref="SpanOrQuery"/> merging the provided <paramref name="clauses"/>. </summary>
public SpanOrQuery(params SpanQuery[] clauses) : this((IList<SpanQuery>)clauses) { }
// LUCENENET specific overload.
// LUCENENET TODO: API - This constructor was added to eliminate casting with PayloadSpanUtil. Make public?
// It would be more useful if the type was an IEnumerable<SpanQuery>, but
// need to rework the allocation below. It would also be better to change AddClause() to Add() to make
// the C# collection initializer function.
internal SpanOrQuery(IList<SpanQuery> clauses)
{
// copy clauses array into an ArrayList
this.clauses = new JCG.List<SpanQuery>(clauses.Count);
for (int i = 0; i < clauses.Count; i++)
{
AddClause(clauses[i]);
}
}
/// <summary>
/// Adds a <paramref name="clause"/> to this query </summary>
public void AddClause(SpanQuery clause)
{
if (field == null)
{
field = clause.Field;
}
else if (clause.Field != null && !clause.Field.Equals(field, StringComparison.Ordinal))
{
throw new ArgumentException("Clauses must have same field.");
}
this.clauses.Add(clause);
}
/// <summary>
/// Return the clauses whose spans are matched. </summary>
public virtual SpanQuery[] GetClauses()
{
return clauses.ToArray();
}
public override string Field => field;
public override void ExtractTerms(ISet<Term> terms)
{
foreach (SpanQuery clause in clauses)
{
clause.ExtractTerms(terms);
}
}
public override object Clone()
{
int sz = clauses.Count;
SpanQuery[] newClauses = new SpanQuery[sz];
for (int i = 0; i < sz; i++)
{
newClauses[i] = (SpanQuery)clauses[i].Clone();
}
SpanOrQuery soq = new SpanOrQuery(newClauses);
soq.Boost = Boost;
return soq;
}
public override Query Rewrite(IndexReader reader)
{
SpanOrQuery clone = null;
for (int i = 0; i < clauses.Count; i++)
{
SpanQuery c = clauses[i];
SpanQuery query = (SpanQuery)c.Rewrite(reader);
if (query != c) // clause rewrote: must clone
{
if (clone == null)
{
clone = (SpanOrQuery)this.Clone();
}
clone.clauses[i] = query;
}
}
if (clone != null)
{
return clone; // some clauses rewrote
}
else
{
return this; // no clauses rewrote
}
}
public override string ToString(string field)
{
StringBuilder buffer = new StringBuilder();
buffer.Append("spanOr([");
bool first = true;
foreach (SpanQuery clause in clauses)
{
if (!first) buffer.Append(", ");
buffer.Append(clause.ToString(field));
first = false;
}
buffer.Append("])");
buffer.Append(ToStringUtils.Boost(Boost));
return buffer.ToString();
}
public override bool Equals(object o)
{
if (this == o)
{
return true;
}
if (o == null || this.GetType() != o.GetType())
{
return false;
}
SpanOrQuery that = (SpanOrQuery)o;
if (!clauses.Equals(that.clauses))
{
return false;
}
return Boost == that.Boost;
}
public override int GetHashCode()
{
//If this doesn't work, hash all elemnts together instead. This version was used to reduce time complexity
int h = clauses.GetHashCode();
h ^= (h << 10) | ((int)(((uint)h) >> 23));
h ^= J2N.BitConversion.SingleToRawInt32Bits(Boost);
return h;
}
private class SpanQueue : Util.PriorityQueue<Spans>
{
private readonly SpanOrQuery outerInstance;
public SpanQueue(SpanOrQuery outerInstance, int size)
: base(size)
{
this.outerInstance = outerInstance;
}
protected internal override bool LessThan(Spans spans1, Spans spans2)
{
if (spans1.Doc == spans2.Doc)
{
if (spans1.Start == spans2.Start)
{
return spans1.End < spans2.End;
}
else
{
return spans1.Start < spans2.Start;
}
}
else
{
return spans1.Doc < spans2.Doc;
}
}
}
public override Spans GetSpans(AtomicReaderContext context, IBits acceptDocs, IDictionary<Term, TermContext> termContexts)
{
if (clauses.Count == 1) // optimize 1-clause case
{
return (clauses[0]).GetSpans(context, acceptDocs, termContexts);
}
return new SpansAnonymousInnerClassHelper(this, context, acceptDocs, termContexts);
}
private class SpansAnonymousInnerClassHelper : Spans
{
private readonly SpanOrQuery outerInstance;
private AtomicReaderContext context;
private IBits acceptDocs;
private IDictionary<Term, TermContext> termContexts;
public SpansAnonymousInnerClassHelper(SpanOrQuery outerInstance, AtomicReaderContext context, IBits acceptDocs, IDictionary<Term, TermContext> termContexts)
{
this.outerInstance = outerInstance;
this.context = context;
this.acceptDocs = acceptDocs;
this.termContexts = termContexts;
queue = null;
}
private SpanQueue queue;
private long cost;
private bool InitSpanQueue(int target)
{
queue = new SpanQueue(outerInstance, outerInstance.clauses.Count);
foreach (var clause in outerInstance.clauses)
{
Spans spans = clause.GetSpans(context, acceptDocs, termContexts);
cost += spans.GetCost();
if (((target == -1) && spans.Next()) || ((target != -1) && spans.SkipTo(target)))
{
queue.Add(spans);
}
}
return queue.Count != 0;
}
public override bool Next()
{
if (queue == null)
{
return InitSpanQueue(-1);
}
if (queue.Count == 0) // all done
{
return false;
}
if (Top.Next()) // move to next
{
queue.UpdateTop();
return true;
}
queue.Pop(); // exhausted a clause
return queue.Count != 0;
}
private Spans Top => queue.Top;
public override bool SkipTo(int target)
{
if (queue == null)
{
return InitSpanQueue(target);
}
bool skipCalled = false;
while (queue.Count != 0 && Top.Doc < target)
{
if (Top.SkipTo(target))
{
queue.UpdateTop();
}
else
{
queue.Pop();
}
skipCalled = true;
}
if (skipCalled)
{
return queue.Count != 0;
}
return Next();
}
public override int Doc => Top.Doc;
public override int Start => Top.Start;
public override int End => Top.End;
public override ICollection<byte[]> GetPayload()
{
List<byte[]> result = null;
Spans theTop = Top;
if (theTop != null && theTop.IsPayloadAvailable)
{
result = new List<byte[]>(theTop.GetPayload());
}
return result;
}
public override bool IsPayloadAvailable
{
get
{
Spans top = Top;
return top != null && top.IsPayloadAvailable;
}
}
public override string ToString()
{
return "spans(" + outerInstance + ")@" + ((queue == null) ? "START" : (queue.Count > 0 ? (Doc + ":" + Start + "-" + End) : "END"));
}
public override long GetCost()
{
return cost;
}
}
}
}
| |
using System;
using System.IO;
using System.Collections.Generic;
using System.Diagnostics;
// ReSharper disable once CheckNamespace
namespace NAudio.Wave
{
class Mp3Index
{
public long FilePosition { get; set; }
public long SamplePosition { get; set; }
public int SampleCount { get; set; }
public int ByteCount { get; set; }
}
/// <summary>
/// Class for reading from MP3 files
/// </summary>
public class Mp3FileReader : WaveStream
{
private readonly WaveFormat waveFormat;
private Stream mp3Stream;
private readonly long mp3DataLength;
private readonly long dataStartPosition;
/// <summary>
/// The MP3 wave format (n.b. NOT the output format of this stream - see the WaveFormat property)
/// </summary>
public Mp3WaveFormat Mp3WaveFormat { get; private set; }
private readonly XingHeader xingHeader;
private readonly bool ownInputStream;
private List<Mp3Index> tableOfContents;
private int tocIndex;
private long totalSamples;
private readonly int bytesPerSample;
private readonly int bytesPerDecodedFrame;
private IMp3FrameDecompressor decompressor;
private readonly byte[] decompressBuffer;
private int decompressBufferOffset;
private int decompressLeftovers;
private bool repositionedFlag;
private long position; // decompressed data position tracker
private readonly object repositionLock = new object();
/// <summary>Supports opening a MP3 file</summary>
public Mp3FileReader(string mp3FileName)
: this(File.OpenRead(mp3FileName), CreateAcmFrameDecompressor, true)
{
}
/// <summary>Supports opening a MP3 file</summary>
/// <param name="mp3FileName">MP3 File name</param>
/// <param name="frameDecompressorBuilder">Factory method to build a frame decompressor</param>
public Mp3FileReader(string mp3FileName, FrameDecompressorBuilder frameDecompressorBuilder)
: this(File.OpenRead(mp3FileName), frameDecompressorBuilder, true)
{
}
/// <summary>
/// Opens MP3 from a stream rather than a file
/// Will not dispose of this stream itself
/// </summary>
/// <param name="inputStream">The incoming stream containing MP3 data</param>
public Mp3FileReader(Stream inputStream)
: this (inputStream, CreateAcmFrameDecompressor, false)
{
}
/// <summary>
/// Opens MP3 from a stream rather than a file
/// Will not dispose of this stream itself
/// </summary>
/// <param name="inputStream">The incoming stream containing MP3 data</param>
/// <param name="frameDecompressorBuilder">Factory method to build a frame decompressor</param>
public Mp3FileReader(Stream inputStream, FrameDecompressorBuilder frameDecompressorBuilder)
: this(inputStream, frameDecompressorBuilder, false)
{
}
private Mp3FileReader(Stream inputStream, FrameDecompressorBuilder frameDecompressorBuilder, bool ownInputStream)
{
if (inputStream == null) throw new ArgumentNullException(nameof(inputStream));
if (frameDecompressorBuilder == null) throw new ArgumentNullException(nameof(frameDecompressorBuilder));
this.ownInputStream = ownInputStream;
try
{
mp3Stream = inputStream;
Id3v2Tag = Id3v2Tag.ReadTag(mp3Stream);
dataStartPosition = mp3Stream.Position;
var firstFrame = Mp3Frame.LoadFromStream(mp3Stream);
if (firstFrame == null)
throw new InvalidDataException("Invalid MP3 file - no MP3 Frames Detected");
double bitRate = firstFrame.BitRate;
xingHeader = XingHeader.LoadXingHeader(firstFrame);
// If the header exists, we can skip over it when decoding the rest of the file
if (xingHeader != null) dataStartPosition = mp3Stream.Position;
// workaround for a longstanding issue with some files failing to load
// because they report a spurious sample rate change
var secondFrame = Mp3Frame.LoadFromStream(mp3Stream);
if (secondFrame != null &&
(secondFrame.SampleRate != firstFrame.SampleRate ||
secondFrame.ChannelMode != firstFrame.ChannelMode))
{
// assume that the first frame was some kind of VBR/LAME header that we failed to recognise properly
dataStartPosition = secondFrame.FileOffset;
// forget about the first frame, the second one is the first one we really care about
firstFrame = secondFrame;
}
mp3DataLength = mp3Stream.Length - dataStartPosition;
// try for an ID3v1 tag as well
mp3Stream.Position = mp3Stream.Length - 128;
byte[] tag = new byte[128];
mp3Stream.Read(tag, 0, 128);
if (tag[0] == 'T' && tag[1] == 'A' && tag[2] == 'G')
{
Id3v1Tag = tag;
mp3DataLength -= 128;
}
mp3Stream.Position = dataStartPosition;
// create a temporary MP3 format before we know the real bitrate
Mp3WaveFormat = new Mp3WaveFormat(firstFrame.SampleRate,
firstFrame.ChannelMode == ChannelMode.Mono ? 1 : 2, firstFrame.FrameLength, (int) bitRate);
CreateTableOfContents();
tocIndex = 0;
// [Bit rate in Kilobits/sec] = [Length in kbits] / [time in seconds]
// = [Length in bits ] / [time in milliseconds]
// Note: in audio, 1 kilobit = 1000 bits.
// Calculated as a double to minimize rounding errors
bitRate = (mp3DataLength*8.0/TotalSeconds());
mp3Stream.Position = dataStartPosition;
// now we know the real bitrate we can create an accurate MP3 WaveFormat
Mp3WaveFormat = new Mp3WaveFormat(firstFrame.SampleRate,
firstFrame.ChannelMode == ChannelMode.Mono ? 1 : 2, firstFrame.FrameLength, (int) bitRate);
decompressor = frameDecompressorBuilder(Mp3WaveFormat);
waveFormat = decompressor.OutputFormat;
bytesPerSample = (decompressor.OutputFormat.BitsPerSample)/8*decompressor.OutputFormat.Channels;
// no MP3 frames have more than 1152 samples in them
bytesPerDecodedFrame = 1152 * bytesPerSample;
// some MP3s I seem to get double
decompressBuffer = new byte[bytesPerDecodedFrame * 2];
}
catch (Exception)
{
if (ownInputStream) inputStream.Dispose();
throw;
}
}
/// <summary>
/// Function that can create an MP3 Frame decompressor
/// </summary>
/// <param name="mp3Format">A WaveFormat object describing the MP3 file format</param>
/// <returns>An MP3 Frame decompressor</returns>
public delegate IMp3FrameDecompressor FrameDecompressorBuilder(WaveFormat mp3Format);
/// <summary>
/// Creates an ACM MP3 Frame decompressor. This is the default with NAudio
/// </summary>
/// <param name="mp3Format">A WaveFormat object based </param>
/// <returns></returns>
public static IMp3FrameDecompressor CreateAcmFrameDecompressor(WaveFormat mp3Format)
{
// new DmoMp3FrameDecompressor(this.Mp3WaveFormat);
return new AcmMp3FrameDecompressor(mp3Format);
}
private void CreateTableOfContents()
{
try
{
// Just a guess at how many entries we'll need so the internal array need not resize very much
// 400 bytes per frame is probably a good enough approximation.
tableOfContents = new List<Mp3Index>((int)(mp3DataLength / 400));
Mp3Frame frame;
do
{
var index = new Mp3Index();
index.FilePosition = mp3Stream.Position;
index.SamplePosition = totalSamples;
frame = ReadNextFrame(false);
if (frame != null)
{
ValidateFrameFormat(frame);
totalSamples += frame.SampleCount;
index.SampleCount = frame.SampleCount;
index.ByteCount = (int)(mp3Stream.Position - index.FilePosition);
tableOfContents.Add(index);
}
} while (frame != null);
}
catch (EndOfStreamException)
{
// not necessarily a problem
}
}
private void ValidateFrameFormat(Mp3Frame frame)
{
if (frame.SampleRate != Mp3WaveFormat.SampleRate)
{
string message =
String.Format(
"Got a frame at sample rate {0}, in an MP3 with sample rate {1}. Mp3FileReader does not support sample rate changes.",
frame.SampleRate, Mp3WaveFormat.SampleRate);
throw new InvalidOperationException(message);
}
int channels = frame.ChannelMode == ChannelMode.Mono ? 1 : 2;
if (channels != Mp3WaveFormat.Channels)
{
string message =
String.Format(
"Got a frame with channel mode {0}, in an MP3 with {1} channels. Mp3FileReader does not support changes to channel count.",
frame.ChannelMode, Mp3WaveFormat.Channels);
throw new InvalidOperationException(message);
}
}
/// <summary>
/// Gets the total length of this file in milliseconds.
/// </summary>
private double TotalSeconds()
{
return (double)totalSamples / Mp3WaveFormat.SampleRate;
}
/// <summary>
/// ID3v2 tag if present
/// </summary>
// ReSharper disable once InconsistentNaming
public Id3v2Tag Id3v2Tag { get; }
/// <summary>
/// ID3v1 tag if present
/// </summary>
// ReSharper disable once InconsistentNaming
public byte[] Id3v1Tag { get; }
/// <summary>
/// Reads the next mp3 frame
/// </summary>
/// <returns>Next mp3 frame, or null if EOF</returns>
public Mp3Frame ReadNextFrame()
{
var frame = ReadNextFrame(true);
if (frame != null) position += frame.SampleCount*bytesPerSample;
return frame;
}
/// <summary>
/// Reads the next mp3 frame
/// </summary>
/// <returns>Next mp3 frame, or null if EOF</returns>
private Mp3Frame ReadNextFrame(bool readData)
{
Mp3Frame frame = null;
try
{
frame = Mp3Frame.LoadFromStream(mp3Stream, readData);
if (frame != null)
{
tocIndex++;
}
}
catch (EndOfStreamException)
{
// suppress for now - it means we unexpectedly got to the end of the stream
// half way through
}
return frame;
}
/// <summary>
/// This is the length in bytes of data available to be read out from the Read method
/// (i.e. the decompressed MP3 length)
/// n.b. this may return 0 for files whose length is unknown
/// </summary>
public override long Length => totalSamples * bytesPerSample;
/// <summary>
/// <see cref="WaveStream.WaveFormat"/>
/// </summary>
public override WaveFormat WaveFormat => waveFormat;
/// <summary>
/// <see cref="Stream.Position"/>
/// </summary>
public override long Position
{
get
{
return position;
}
set
{
lock (repositionLock)
{
value = Math.Max(Math.Min(value, Length), 0);
var samplePosition = value / bytesPerSample;
Mp3Index mp3Index = null;
for (int index = 0; index < tableOfContents.Count; index++)
{
if (tableOfContents[index].SamplePosition + tableOfContents[index].SampleCount > samplePosition)
{
mp3Index = tableOfContents[index];
tocIndex = index;
break;
}
}
decompressBufferOffset = 0;
decompressLeftovers = 0;
repositionedFlag = true;
if (mp3Index != null)
{
// perform the reposition
mp3Stream.Position = mp3Index.FilePosition;
// set the offset into the buffer (that is yet to be populated in Read())
var frameOffset = samplePosition - mp3Index.SamplePosition;
if (frameOffset > 0)
{
decompressBufferOffset = (int)frameOffset * bytesPerSample;
}
}
else
{
// we are repositioning to the end of the data
mp3Stream.Position = mp3DataLength + dataStartPosition;
}
position = value;
}
}
}
/// <summary>
/// Reads decompressed PCM data from our MP3 file.
/// </summary>
public override int Read(byte[] sampleBuffer, int offset, int numBytes)
{
int bytesRead = 0;
lock (repositionLock)
{
if (decompressLeftovers != 0)
{
int toCopy = Math.Min(decompressLeftovers, numBytes);
Array.Copy(decompressBuffer, decompressBufferOffset, sampleBuffer, offset, toCopy);
decompressLeftovers -= toCopy;
if (decompressLeftovers == 0)
{
decompressBufferOffset = 0;
}
else
{
decompressBufferOffset += toCopy;
}
bytesRead += toCopy;
offset += toCopy;
}
int targetTocIndex = tocIndex; // the frame index that contains the requested data
if (repositionedFlag)
{
decompressor.Reset();
// Seek back a few frames of the stream to get the reset decoder decode a few
// warm-up frames before reading the requested data. Without the warm-up phase,
// the first half of the frame after the reset is attenuated and does not resemble
// the data as it would be when reading sequentially from the beginning, because
// the decoder is missing the required overlap from the previous frame.
tocIndex = Math.Max(0, tocIndex - 3); // no warm-up at the beginning of the stream
mp3Stream.Position = tableOfContents[tocIndex].FilePosition;
repositionedFlag = false;
}
while (bytesRead < numBytes)
{
Mp3Frame frame = ReadNextFrame();
if (frame != null)
{
int decompressed = decompressor.DecompressFrame(frame, decompressBuffer, 0);
if (tocIndex <= targetTocIndex || decompressed == 0)
{
// The first frame after a reset usually does not immediately yield decoded samples.
// Because the next instructions will fail if a buffer offset is set and the frame
// decoding didn't return data, we skip the part.
// We skip the following instructions also after decoding a warm-up frame.
continue;
}
// Two special cases can happen here:
// 1. We are interested in the first frame of the stream, but need to read the second frame too
// for the decoder to return decoded data
// 2. We are interested in the second frame of the stream, but because reading the first frame
// as warm-up didn't yield any data (because the decoder needs two frames to return data), we
// get data from the first and second frame.
// This case needs special handling, and we have to purge the data of the first frame.
else if (tocIndex == targetTocIndex + 1 && decompressed == bytesPerDecodedFrame * 2)
{
// Purge the first frame's data
Array.Copy(decompressBuffer, bytesPerDecodedFrame, decompressBuffer, 0, bytesPerDecodedFrame);
decompressed = bytesPerDecodedFrame;
}
int toCopy = Math.Min(decompressed - decompressBufferOffset, numBytes - bytesRead);
Array.Copy(decompressBuffer, decompressBufferOffset, sampleBuffer, offset, toCopy);
if ((toCopy + decompressBufferOffset) < decompressed)
{
decompressBufferOffset = toCopy + decompressBufferOffset;
decompressLeftovers = decompressed - decompressBufferOffset;
}
else
{
// no lefovers
decompressBufferOffset = 0;
decompressLeftovers = 0;
}
offset += toCopy;
bytesRead += toCopy;
}
else
{
break;
}
}
}
Debug.Assert(bytesRead <= numBytes, "MP3 File Reader read too much");
position += bytesRead;
return bytesRead;
}
/// <summary>
/// Xing header if present
/// </summary>
public XingHeader XingHeader => xingHeader;
/// <summary>
/// Disposes this WaveStream
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (mp3Stream != null)
{
if (ownInputStream)
{
mp3Stream.Dispose();
}
mp3Stream = null;
}
if (decompressor != null)
{
decompressor.Dispose();
decompressor = null;
}
}
base.Dispose(disposing);
}
}
}
| |
namespace QText {
partial class OptionsForm {
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing) {
if (disposing && (components != null)) {
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent() {
this.components = new System.ComponentModel.Container();
this.tab = new System.Windows.Forms.TabControl();
this.tab_pagAppearance = new System.Windows.Forms.TabPage();
this.lblColorExample = new System.Windows.Forms.Label();
this.btnColorBackground = new System.Windows.Forms.Button();
this.btnColorForeground = new System.Windows.Forms.Button();
this.lblColor = new System.Windows.Forms.Label();
this.lblFont = new System.Windows.Forms.Label();
this.btnFont = new System.Windows.Forms.Button();
this.nudTabWidth = new System.Windows.Forms.NumericUpDown();
this.lblTabWidth = new System.Windows.Forms.Label();
this.chkFollowURLs = new System.Windows.Forms.CheckBox();
this.chkDisplayURLs = new System.Windows.Forms.CheckBox();
this.txtFont = new System.Windows.Forms.TextBox();
this.tab_pagDisplay = new System.Windows.Forms.TabPage();
this.cmbSelectionDelimiters = new System.Windows.Forms.ComboBox();
this.lblSelectionDelimiters = new System.Windows.Forms.Label();
this.chbMultilineTabs = new System.Windows.Forms.CheckBox();
this.chbVerticalScrollbar = new System.Windows.Forms.CheckBox();
this.chbHorizontalScrollbar = new System.Windows.Forms.CheckBox();
this.chbShowMinimizeMaximizeButtons = new System.Windows.Forms.CheckBox();
this.chkShowToolbar = new System.Windows.Forms.CheckBox();
this.chkShowInTaskbar = new System.Windows.Forms.CheckBox();
this.tab_pagFiles = new System.Windows.Forms.TabPage();
this.chbSavePlainWithLF = new System.Windows.Forms.CheckBox();
this.nudQuickSaveIntervalInSeconds = new System.Windows.Forms.NumericUpDown();
this.btnOpenLocationFolder = new System.Windows.Forms.Button();
this.lblQuickSaveIntervalSeconds = new System.Windows.Forms.Label();
this.lblQuickSaveInterval = new System.Windows.Forms.Label();
this.chkDeleteToRecycleBin = new System.Windows.Forms.CheckBox();
this.chkPreloadFilesOnStartup = new System.Windows.Forms.CheckBox();
this.btnChangeLocation = new System.Windows.Forms.Button();
this.tab_pagBehavior = new System.Windows.Forms.TabPage();
this.txtHotkey = new System.Windows.Forms.TextBox();
this.lblHotkey = new System.Windows.Forms.Label();
this.chkRunAtStartup = new System.Windows.Forms.CheckBox();
this.chkSingleClickTrayActivation = new System.Windows.Forms.CheckBox();
this.chkMinimizeToTray = new System.Windows.Forms.CheckBox();
this.tab_pagCarbonCopy = new System.Windows.Forms.TabPage();
this.btnCarbonCopyOpenFolder = new System.Windows.Forms.Button();
this.btnCarbonCopyFolderSelect = new System.Windows.Forms.Button();
this.chbCarbonCopyIgnoreCopyErrors = new System.Windows.Forms.CheckBox();
this.chbUseCarbonCopy = new System.Windows.Forms.CheckBox();
this.txtCarbonCopyFolder = new System.Windows.Forms.TextBox();
this.lblCarbonCopyFolder = new System.Windows.Forms.Label();
this.btnOk = new System.Windows.Forms.Button();
this.btnCancel = new System.Windows.Forms.Button();
this.btnExit = new System.Windows.Forms.Button();
this.tooltip = new System.Windows.Forms.ToolTip(this.components);
this.btnAdvanced = new System.Windows.Forms.Button();
this.chbHotkeyTogglesVisibility = new System.Windows.Forms.CheckBox();
this.tab.SuspendLayout();
this.tab_pagAppearance.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.nudTabWidth)).BeginInit();
this.tab_pagDisplay.SuspendLayout();
this.tab_pagFiles.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.nudQuickSaveIntervalInSeconds)).BeginInit();
this.tab_pagBehavior.SuspendLayout();
this.tab_pagCarbonCopy.SuspendLayout();
this.SuspendLayout();
//
// tab
//
this.tab.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.tab.Controls.Add(this.tab_pagAppearance);
this.tab.Controls.Add(this.tab_pagDisplay);
this.tab.Controls.Add(this.tab_pagFiles);
this.tab.Controls.Add(this.tab_pagBehavior);
this.tab.Controls.Add(this.tab_pagCarbonCopy);
this.tab.Location = new System.Drawing.Point(12, 12);
this.tab.Name = "tab";
this.tab.SelectedIndex = 0;
this.tab.Size = new System.Drawing.Size(498, 251);
this.tab.TabIndex = 1;
//
// tab_pagAppearance
//
this.tab_pagAppearance.Controls.Add(this.lblColorExample);
this.tab_pagAppearance.Controls.Add(this.btnColorBackground);
this.tab_pagAppearance.Controls.Add(this.btnColorForeground);
this.tab_pagAppearance.Controls.Add(this.lblColor);
this.tab_pagAppearance.Controls.Add(this.lblFont);
this.tab_pagAppearance.Controls.Add(this.btnFont);
this.tab_pagAppearance.Controls.Add(this.nudTabWidth);
this.tab_pagAppearance.Controls.Add(this.lblTabWidth);
this.tab_pagAppearance.Controls.Add(this.chkFollowURLs);
this.tab_pagAppearance.Controls.Add(this.chkDisplayURLs);
this.tab_pagAppearance.Controls.Add(this.txtFont);
this.tab_pagAppearance.Location = new System.Drawing.Point(4, 25);
this.tab_pagAppearance.Name = "tab_pagAppearance";
this.tab_pagAppearance.Size = new System.Drawing.Size(490, 222);
this.tab_pagAppearance.TabIndex = 4;
this.tab_pagAppearance.Text = "Appearance";
this.tab_pagAppearance.UseVisualStyleBackColor = true;
//
// lblColorExample
//
this.lblColorExample.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.lblColorExample.Location = new System.Drawing.Point(123, 119);
this.lblColorExample.Name = "lblColorExample";
this.lblColorExample.Size = new System.Drawing.Size(29, 29);
this.lblColorExample.TabIndex = 8;
this.lblColorExample.Text = "C";
this.lblColorExample.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.tooltip.SetToolTip(this.lblColorExample, "Background and foreground color for plain text.");
//
// btnColorBackground
//
this.btnColorBackground.Location = new System.Drawing.Point(158, 119);
this.btnColorBackground.Name = "btnColorBackground";
this.btnColorBackground.Size = new System.Drawing.Size(98, 29);
this.btnColorBackground.TabIndex = 9;
this.btnColorBackground.Text = "Background";
this.tooltip.SetToolTip(this.btnColorBackground, "Browse background color.");
this.btnColorBackground.UseVisualStyleBackColor = true;
this.btnColorBackground.Click += new System.EventHandler(this.btnColorBackground_Click);
//
// btnColorForeground
//
this.btnColorForeground.Location = new System.Drawing.Point(262, 119);
this.btnColorForeground.Name = "btnColorForeground";
this.btnColorForeground.Size = new System.Drawing.Size(98, 29);
this.btnColorForeground.TabIndex = 10;
this.btnColorForeground.Text = "Foreground";
this.tooltip.SetToolTip(this.btnColorForeground, "Browse foreground color.");
this.btnColorForeground.UseVisualStyleBackColor = true;
this.btnColorForeground.Click += new System.EventHandler(this.btnColorForeground_Click);
//
// lblColor
//
this.lblColor.AutoSize = true;
this.lblColor.Location = new System.Drawing.Point(3, 125);
this.lblColor.Name = "lblColor";
this.lblColor.Size = new System.Drawing.Size(52, 17);
this.lblColor.TabIndex = 7;
this.lblColor.Text = "Colors:";
//
// lblFont
//
this.lblFont.AutoSize = true;
this.lblFont.Location = new System.Drawing.Point(3, 94);
this.lblFont.Name = "lblFont";
this.lblFont.Size = new System.Drawing.Size(40, 17);
this.lblFont.TabIndex = 4;
this.lblFont.Text = "Font:";
//
// btnFont
//
this.btnFont.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.btnFont.Font = new System.Drawing.Font("Microsoft Sans Serif", 4.8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(238)));
this.btnFont.Location = new System.Drawing.Point(460, 91);
this.btnFont.Margin = new System.Windows.Forms.Padding(0, 3, 3, 3);
this.btnFont.Name = "btnFont";
this.btnFont.Size = new System.Drawing.Size(22, 22);
this.btnFont.TabIndex = 6;
this.btnFont.Text = "...";
this.tooltip.SetToolTip(this.btnFont, "Browse font selection.");
this.btnFont.UseVisualStyleBackColor = true;
this.btnFont.Click += new System.EventHandler(this.btnFont_Click);
//
// nudTabWidth
//
this.nudTabWidth.Location = new System.Drawing.Point(123, 63);
this.nudTabWidth.Maximum = new decimal(new int[] {
16,
0,
0,
0});
this.nudTabWidth.Minimum = new decimal(new int[] {
1,
0,
0,
0});
this.nudTabWidth.Name = "nudTabWidth";
this.nudTabWidth.Size = new System.Drawing.Size(53, 22);
this.nudTabWidth.TabIndex = 3;
this.nudTabWidth.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
this.tooltip.SetToolTip(this.nudTabWidth, "Number of characters each tab will use for alignment.");
this.nudTabWidth.Value = new decimal(new int[] {
1,
0,
0,
0});
//
// lblTabWidth
//
this.lblTabWidth.AutoSize = true;
this.lblTabWidth.Location = new System.Drawing.Point(3, 65);
this.lblTabWidth.Name = "lblTabWidth";
this.lblTabWidth.Size = new System.Drawing.Size(105, 17);
this.lblTabWidth.TabIndex = 2;
this.lblTabWidth.Text = "Tab char width:";
//
// chkFollowURLs
//
this.chkFollowURLs.AutoSize = true;
this.chkFollowURLs.Location = new System.Drawing.Point(23, 30);
this.chkFollowURLs.Name = "chkFollowURLs";
this.chkFollowURLs.Size = new System.Drawing.Size(108, 21);
this.chkFollowURLs.TabIndex = 1;
this.chkFollowURLs.Text = "Follow URLs";
this.tooltip.SetToolTip(this.chkFollowURLs, "Controls whether clicking the URL will ");
this.chkFollowURLs.UseVisualStyleBackColor = true;
//
// chkDisplayURLs
//
this.chkDisplayURLs.AutoSize = true;
this.chkDisplayURLs.Location = new System.Drawing.Point(3, 3);
this.chkDisplayURLs.Name = "chkDisplayURLs";
this.chkDisplayURLs.Size = new System.Drawing.Size(115, 21);
this.chkDisplayURLs.TabIndex = 0;
this.chkDisplayURLs.Text = "Display URLs";
this.tooltip.SetToolTip(this.chkDisplayURLs, "If checked, URLs in text will be detected and displayed as such.");
this.chkDisplayURLs.UseVisualStyleBackColor = true;
this.chkDisplayURLs.CheckedChanged += new System.EventHandler(this.chkDisplayURLs_CheckedChanged);
//
// txtFont
//
this.txtFont.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.txtFont.Location = new System.Drawing.Point(123, 91);
this.txtFont.Margin = new System.Windows.Forms.Padding(3, 3, 0, 3);
this.txtFont.Name = "txtFont";
this.txtFont.ReadOnly = true;
this.txtFont.Size = new System.Drawing.Size(337, 22);
this.txtFont.TabIndex = 5;
this.tooltip.SetToolTip(this.txtFont, "Font to use as a default. Rich text will use different fonts too if set.");
//
// tab_pagDisplay
//
this.tab_pagDisplay.Controls.Add(this.cmbSelectionDelimiters);
this.tab_pagDisplay.Controls.Add(this.lblSelectionDelimiters);
this.tab_pagDisplay.Controls.Add(this.chbMultilineTabs);
this.tab_pagDisplay.Controls.Add(this.chbVerticalScrollbar);
this.tab_pagDisplay.Controls.Add(this.chbHorizontalScrollbar);
this.tab_pagDisplay.Controls.Add(this.chbShowMinimizeMaximizeButtons);
this.tab_pagDisplay.Controls.Add(this.chkShowToolbar);
this.tab_pagDisplay.Controls.Add(this.chkShowInTaskbar);
this.tab_pagDisplay.Location = new System.Drawing.Point(4, 25);
this.tab_pagDisplay.Name = "tab_pagDisplay";
this.tab_pagDisplay.Size = new System.Drawing.Size(490, 222);
this.tab_pagDisplay.TabIndex = 1;
this.tab_pagDisplay.Text = "Display";
this.tab_pagDisplay.UseVisualStyleBackColor = true;
//
// cmbSelectionDelimiters
//
this.cmbSelectionDelimiters.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.cmbSelectionDelimiters.FormattingEnabled = true;
this.cmbSelectionDelimiters.Items.AddRange(new object[] {
"\"/()[]{}<>",
"\".,:;!?/|\\()[]{}<>"});
this.cmbSelectionDelimiters.Location = new System.Drawing.Point(167, 180);
this.cmbSelectionDelimiters.Margin = new System.Windows.Forms.Padding(3, 12, 3, 3);
this.cmbSelectionDelimiters.Name = "cmbSelectionDelimiters";
this.cmbSelectionDelimiters.Size = new System.Drawing.Size(320, 24);
this.cmbSelectionDelimiters.TabIndex = 7;
this.tooltip.SetToolTip(this.cmbSelectionDelimiters, "Delimiters that will be used for double-click selection.");
//
// lblSelectionDelimiters
//
this.lblSelectionDelimiters.AutoSize = true;
this.lblSelectionDelimiters.Location = new System.Drawing.Point(3, 183);
this.lblSelectionDelimiters.Name = "lblSelectionDelimiters";
this.lblSelectionDelimiters.Size = new System.Drawing.Size(134, 17);
this.lblSelectionDelimiters.TabIndex = 6;
this.lblSelectionDelimiters.Text = "Selection delimiters:";
//
// chbMultilineTabs
//
this.chbMultilineTabs.AutoSize = true;
this.chbMultilineTabs.Location = new System.Drawing.Point(3, 87);
this.chbMultilineTabs.Margin = new System.Windows.Forms.Padding(3, 6, 3, 3);
this.chbMultilineTabs.Name = "chbMultilineTabs";
this.chbMultilineTabs.Size = new System.Drawing.Size(161, 21);
this.chbMultilineTabs.TabIndex = 3;
this.chbMultilineTabs.Text = "Multiline tab headers";
this.tooltip.SetToolTip(this.chbMultilineTabs, "Controls if tabs are to be shown in multiple lines when they cannot fit on screen" +
".");
this.chbMultilineTabs.UseVisualStyleBackColor = true;
//
// chbVerticalScrollbar
//
this.chbVerticalScrollbar.AutoSize = true;
this.chbVerticalScrollbar.Location = new System.Drawing.Point(3, 144);
this.chbVerticalScrollbar.Name = "chbVerticalScrollbar";
this.chbVerticalScrollbar.Size = new System.Drawing.Size(135, 21);
this.chbVerticalScrollbar.TabIndex = 5;
this.chbVerticalScrollbar.Text = "Vertical scrollbar";
this.tooltip.SetToolTip(this.chbVerticalScrollbar, "If checked, vertical scrollbar will be shown.");
this.chbVerticalScrollbar.UseVisualStyleBackColor = true;
//
// chbHorizontalScrollbar
//
this.chbHorizontalScrollbar.AutoSize = true;
this.chbHorizontalScrollbar.Location = new System.Drawing.Point(3, 117);
this.chbHorizontalScrollbar.Margin = new System.Windows.Forms.Padding(3, 6, 3, 3);
this.chbHorizontalScrollbar.Name = "chbHorizontalScrollbar";
this.chbHorizontalScrollbar.Size = new System.Drawing.Size(152, 21);
this.chbHorizontalScrollbar.TabIndex = 4;
this.chbHorizontalScrollbar.Text = "Horizontal scrollbar";
this.tooltip.SetToolTip(this.chbHorizontalScrollbar, "Controls if horizontal scrolling is to be allowed. If not checked, text will wrap" +
" on right edge.");
this.chbHorizontalScrollbar.UseVisualStyleBackColor = true;
//
// chbShowMinimizeMaximizeButtons
//
this.chbShowMinimizeMaximizeButtons.AutoSize = true;
this.chbShowMinimizeMaximizeButtons.Location = new System.Drawing.Point(3, 30);
this.chbShowMinimizeMaximizeButtons.Name = "chbShowMinimizeMaximizeButtons";
this.chbShowMinimizeMaximizeButtons.Size = new System.Drawing.Size(234, 21);
this.chbShowMinimizeMaximizeButtons.TabIndex = 1;
this.chbShowMinimizeMaximizeButtons.Text = "Show minimize/maximize buttons";
this.tooltip.SetToolTip(this.chbShowMinimizeMaximizeButtons, "If checked, both minimize and maximize buttons will be shown.");
this.chbShowMinimizeMaximizeButtons.UseVisualStyleBackColor = true;
this.chbShowMinimizeMaximizeButtons.CheckedChanged += new System.EventHandler(this.chbShowMinimizeMaximizeButtons_CheckedChanged);
//
// chkShowToolbar
//
this.chkShowToolbar.AutoSize = true;
this.chkShowToolbar.Location = new System.Drawing.Point(3, 57);
this.chkShowToolbar.Name = "chkShowToolbar";
this.chkShowToolbar.Size = new System.Drawing.Size(112, 21);
this.chkShowToolbar.TabIndex = 2;
this.chkShowToolbar.Text = "Show toolbar";
this.tooltip.SetToolTip(this.chkShowToolbar, "If true, toolbar will be shown.");
this.chkShowToolbar.UseVisualStyleBackColor = true;
//
// chkShowInTaskbar
//
this.chkShowInTaskbar.AutoSize = true;
this.chkShowInTaskbar.Location = new System.Drawing.Point(3, 3);
this.chkShowInTaskbar.Name = "chkShowInTaskbar";
this.chkShowInTaskbar.Size = new System.Drawing.Size(130, 21);
this.chkShowInTaskbar.TabIndex = 0;
this.chkShowInTaskbar.Text = "Show in taskbar";
this.tooltip.SetToolTip(this.chkShowInTaskbar, "If checked, QText window will be shown in taskbar.");
this.chkShowInTaskbar.UseVisualStyleBackColor = true;
this.chkShowInTaskbar.CheckedChanged += new System.EventHandler(this.chkShowInTaskbar_CheckedChanged);
//
// tab_pagFiles
//
this.tab_pagFiles.Controls.Add(this.chbSavePlainWithLF);
this.tab_pagFiles.Controls.Add(this.nudQuickSaveIntervalInSeconds);
this.tab_pagFiles.Controls.Add(this.btnOpenLocationFolder);
this.tab_pagFiles.Controls.Add(this.lblQuickSaveIntervalSeconds);
this.tab_pagFiles.Controls.Add(this.lblQuickSaveInterval);
this.tab_pagFiles.Controls.Add(this.chkDeleteToRecycleBin);
this.tab_pagFiles.Controls.Add(this.chkPreloadFilesOnStartup);
this.tab_pagFiles.Controls.Add(this.btnChangeLocation);
this.tab_pagFiles.Location = new System.Drawing.Point(4, 25);
this.tab_pagFiles.Name = "tab_pagFiles";
this.tab_pagFiles.Padding = new System.Windows.Forms.Padding(4);
this.tab_pagFiles.Size = new System.Drawing.Size(490, 222);
this.tab_pagFiles.TabIndex = 0;
this.tab_pagFiles.Text = "Files";
this.tab_pagFiles.UseVisualStyleBackColor = true;
//
// chbSavePlainWithLF
//
this.chbSavePlainWithLF.AutoSize = true;
this.chbSavePlainWithLF.Location = new System.Drawing.Point(7, 60);
this.chbSavePlainWithLF.Name = "chbSavePlainWithLF";
this.chbSavePlainWithLF.Size = new System.Drawing.Size(243, 21);
this.chbSavePlainWithLF.TabIndex = 4;
this.chbSavePlainWithLF.Text = "Save plain text with LF line ending";
this.tooltip.SetToolTip(this.chbSavePlainWithLF, "Controls if plain text will use CRLF (Windows) or LF (Linux) line endings.");
this.chbSavePlainWithLF.UseVisualStyleBackColor = true;
//
// nudQuickSaveIntervalInSeconds
//
this.nudQuickSaveIntervalInSeconds.DecimalPlaces = 1;
this.nudQuickSaveIntervalInSeconds.Increment = new decimal(new int[] {
5,
0,
0,
65536});
this.nudQuickSaveIntervalInSeconds.Location = new System.Drawing.Point(155, 5);
this.nudQuickSaveIntervalInSeconds.Maximum = new decimal(new int[] {
10,
0,
0,
0});
this.nudQuickSaveIntervalInSeconds.Minimum = new decimal(new int[] {
5,
0,
0,
65536});
this.nudQuickSaveIntervalInSeconds.Name = "nudQuickSaveIntervalInSeconds";
this.nudQuickSaveIntervalInSeconds.Size = new System.Drawing.Size(50, 22);
this.nudQuickSaveIntervalInSeconds.TabIndex = 1;
this.nudQuickSaveIntervalInSeconds.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
this.tooltip.SetToolTip(this.nudQuickSaveIntervalInSeconds, "Number of seconds to wait before saving a file. Each key press restarts timer.");
this.nudQuickSaveIntervalInSeconds.Value = new decimal(new int[] {
3,
0,
0,
0});
//
// btnOpenLocationFolder
//
this.btnOpenLocationFolder.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.btnOpenLocationFolder.Location = new System.Drawing.Point(3, 190);
this.btnOpenLocationFolder.Name = "btnOpenLocationFolder";
this.btnOpenLocationFolder.Size = new System.Drawing.Size(196, 29);
this.btnOpenLocationFolder.TabIndex = 6;
this.btnOpenLocationFolder.Text = "Open folder";
this.tooltip.SetToolTip(this.btnOpenLocationFolder, "Show all files in Explorer.");
this.btnOpenLocationFolder.UseVisualStyleBackColor = true;
this.btnOpenLocationFolder.Click += new System.EventHandler(this.btnOpenLocationFolder_Click);
//
// lblQuickSaveIntervalSeconds
//
this.lblQuickSaveIntervalSeconds.AutoSize = true;
this.lblQuickSaveIntervalSeconds.Location = new System.Drawing.Point(211, 5);
this.lblQuickSaveIntervalSeconds.Name = "lblQuickSaveIntervalSeconds";
this.lblQuickSaveIntervalSeconds.Size = new System.Drawing.Size(61, 17);
this.lblQuickSaveIntervalSeconds.TabIndex = 2;
this.lblQuickSaveIntervalSeconds.Text = "seconds";
//
// lblQuickSaveInterval
//
this.lblQuickSaveInterval.AutoSize = true;
this.lblQuickSaveInterval.Location = new System.Drawing.Point(3, 5);
this.lblQuickSaveInterval.Name = "lblQuickSaveInterval";
this.lblQuickSaveInterval.Size = new System.Drawing.Size(133, 17);
this.lblQuickSaveInterval.TabIndex = 0;
this.lblQuickSaveInterval.Text = "Quick-save interval:";
//
// chkDeleteToRecycleBin
//
this.chkDeleteToRecycleBin.AutoSize = true;
this.chkDeleteToRecycleBin.Location = new System.Drawing.Point(7, 87);
this.chkDeleteToRecycleBin.Name = "chkDeleteToRecycleBin";
this.chkDeleteToRecycleBin.Size = new System.Drawing.Size(159, 21);
this.chkDeleteToRecycleBin.TabIndex = 5;
this.chkDeleteToRecycleBin.Text = "Delete to recycle bin";
this.tooltip.SetToolTip(this.chkDeleteToRecycleBin, "If checked, all delete will be to recycle bin.");
this.chkDeleteToRecycleBin.UseVisualStyleBackColor = true;
//
// chkPreloadFilesOnStartup
//
this.chkPreloadFilesOnStartup.AutoSize = true;
this.chkPreloadFilesOnStartup.Location = new System.Drawing.Point(7, 33);
this.chkPreloadFilesOnStartup.Name = "chkPreloadFilesOnStartup";
this.chkPreloadFilesOnStartup.Size = new System.Drawing.Size(176, 21);
this.chkPreloadFilesOnStartup.TabIndex = 3;
this.chkPreloadFilesOnStartup.Text = "Preload files on startup";
this.tooltip.SetToolTip(this.chkPreloadFilesOnStartup, "All files will be loaded in advance.");
this.chkPreloadFilesOnStartup.UseVisualStyleBackColor = true;
//
// btnChangeLocation
//
this.btnChangeLocation.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btnChangeLocation.ForeColor = System.Drawing.SystemColors.ControlText;
this.btnChangeLocation.Location = new System.Drawing.Point(291, 190);
this.btnChangeLocation.Name = "btnChangeLocation";
this.btnChangeLocation.Size = new System.Drawing.Size(196, 29);
this.btnChangeLocation.TabIndex = 7;
this.btnChangeLocation.Text = "Change location";
this.tooltip.SetToolTip(this.btnChangeLocation, "Changes location of files.");
this.btnChangeLocation.UseVisualStyleBackColor = true;
this.btnChangeLocation.Click += new System.EventHandler(this.btnChangeLocation_Click);
//
// tab_pagBehavior
//
this.tab_pagBehavior.Controls.Add(this.chbHotkeyTogglesVisibility);
this.tab_pagBehavior.Controls.Add(this.txtHotkey);
this.tab_pagBehavior.Controls.Add(this.lblHotkey);
this.tab_pagBehavior.Controls.Add(this.chkRunAtStartup);
this.tab_pagBehavior.Controls.Add(this.chkSingleClickTrayActivation);
this.tab_pagBehavior.Controls.Add(this.chkMinimizeToTray);
this.tab_pagBehavior.Location = new System.Drawing.Point(4, 25);
this.tab_pagBehavior.Name = "tab_pagBehavior";
this.tab_pagBehavior.Size = new System.Drawing.Size(490, 222);
this.tab_pagBehavior.TabIndex = 2;
this.tab_pagBehavior.Text = "Behavior";
this.tab_pagBehavior.UseVisualStyleBackColor = true;
//
// txtHotkey
//
this.txtHotkey.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.txtHotkey.Location = new System.Drawing.Point(153, 3);
this.txtHotkey.Name = "txtHotkey";
this.txtHotkey.ReadOnly = true;
this.txtHotkey.Size = new System.Drawing.Size(334, 22);
this.txtHotkey.TabIndex = 1;
this.tooltip.SetToolTip(this.txtHotkey, "Hotkey to use for bringing up the window.");
this.txtHotkey.Enter += new System.EventHandler(this.txtHotkey_Enter);
this.txtHotkey.Leave += new System.EventHandler(this.txtHotkey_Leave);
this.txtHotkey.PreviewKeyDown += new System.Windows.Forms.PreviewKeyDownEventHandler(this.txtHotkey_PreviewKeyDown);
//
// lblHotkey
//
this.lblHotkey.AutoSize = true;
this.lblHotkey.Location = new System.Drawing.Point(3, 6);
this.lblHotkey.Name = "lblHotkey";
this.lblHotkey.Size = new System.Drawing.Size(56, 17);
this.lblHotkey.TabIndex = 0;
this.lblHotkey.Text = "Hotkey:";
//
// chkRunAtStartup
//
this.chkRunAtStartup.AutoSize = true;
this.chkRunAtStartup.Location = new System.Drawing.Point(3, 95);
this.chkRunAtStartup.Name = "chkRunAtStartup";
this.chkRunAtStartup.Size = new System.Drawing.Size(184, 21);
this.chkRunAtStartup.TabIndex = 4;
this.chkRunAtStartup.Tag = "If checked, QText will be started in tray on Windows startup.";
this.chkRunAtStartup.Text = "Run on Windows startup";
this.chkRunAtStartup.UseVisualStyleBackColor = true;
//
// chkSingleClickTrayActivation
//
this.chkSingleClickTrayActivation.AutoSize = true;
this.chkSingleClickTrayActivation.Location = new System.Drawing.Point(3, 65);
this.chkSingleClickTrayActivation.Name = "chkSingleClickTrayActivation";
this.chkSingleClickTrayActivation.Size = new System.Drawing.Size(223, 21);
this.chkSingleClickTrayActivation.TabIndex = 3;
this.chkSingleClickTrayActivation.Text = "Tray activation with single click";
this.tooltip.SetToolTip(this.chkSingleClickTrayActivation, "Controls if tray icon will show window upon single or double click.");
this.chkSingleClickTrayActivation.UseVisualStyleBackColor = true;
//
// chkMinimizeToTray
//
this.chkMinimizeToTray.AutoSize = true;
this.chkMinimizeToTray.Location = new System.Drawing.Point(3, 38);
this.chkMinimizeToTray.Name = "chkMinimizeToTray";
this.chkMinimizeToTray.Size = new System.Drawing.Size(128, 21);
this.chkMinimizeToTray.TabIndex = 2;
this.chkMinimizeToTray.Text = "Minimize to tray";
this.tooltip.SetToolTip(this.chkMinimizeToTray, "If checked, QText will minimize to tray.");
this.chkMinimizeToTray.UseVisualStyleBackColor = true;
//
// tab_pagCarbonCopy
//
this.tab_pagCarbonCopy.Controls.Add(this.btnCarbonCopyOpenFolder);
this.tab_pagCarbonCopy.Controls.Add(this.btnCarbonCopyFolderSelect);
this.tab_pagCarbonCopy.Controls.Add(this.chbCarbonCopyIgnoreCopyErrors);
this.tab_pagCarbonCopy.Controls.Add(this.chbUseCarbonCopy);
this.tab_pagCarbonCopy.Controls.Add(this.txtCarbonCopyFolder);
this.tab_pagCarbonCopy.Controls.Add(this.lblCarbonCopyFolder);
this.tab_pagCarbonCopy.Location = new System.Drawing.Point(4, 25);
this.tab_pagCarbonCopy.Name = "tab_pagCarbonCopy";
this.tab_pagCarbonCopy.Size = new System.Drawing.Size(490, 222);
this.tab_pagCarbonCopy.TabIndex = 3;
this.tab_pagCarbonCopy.Text = "Carbon copy";
this.tab_pagCarbonCopy.UseVisualStyleBackColor = true;
//
// btnCarbonCopyOpenFolder
//
this.btnCarbonCopyOpenFolder.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.btnCarbonCopyOpenFolder.Location = new System.Drawing.Point(3, 190);
this.btnCarbonCopyOpenFolder.Name = "btnCarbonCopyOpenFolder";
this.btnCarbonCopyOpenFolder.Size = new System.Drawing.Size(196, 29);
this.btnCarbonCopyOpenFolder.TabIndex = 6;
this.btnCarbonCopyOpenFolder.Text = "Open folder";
this.tooltip.SetToolTip(this.btnCarbonCopyOpenFolder, "Open backup folder in Explorer.");
this.btnCarbonCopyOpenFolder.UseVisualStyleBackColor = true;
this.btnCarbonCopyOpenFolder.Click += new System.EventHandler(this.btnCarbonCopyOpenFolder_Click);
//
// btnCarbonCopyFolderSelect
//
this.btnCarbonCopyFolderSelect.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.btnCarbonCopyFolderSelect.Font = new System.Drawing.Font("Microsoft Sans Serif", 5F);
this.btnCarbonCopyFolderSelect.Location = new System.Drawing.Point(465, 32);
this.btnCarbonCopyFolderSelect.Margin = new System.Windows.Forms.Padding(0, 3, 3, 3);
this.btnCarbonCopyFolderSelect.Name = "btnCarbonCopyFolderSelect";
this.btnCarbonCopyFolderSelect.Size = new System.Drawing.Size(22, 22);
this.btnCarbonCopyFolderSelect.TabIndex = 3;
this.btnCarbonCopyFolderSelect.Text = "...";
this.tooltip.SetToolTip(this.btnCarbonCopyFolderSelect, "Browse for folder.");
this.btnCarbonCopyFolderSelect.UseVisualStyleBackColor = true;
this.btnCarbonCopyFolderSelect.Click += new System.EventHandler(this.btnCarbonCopyFolderSelect_Click);
//
// chbCarbonCopyIgnoreCopyErrors
//
this.chbCarbonCopyIgnoreCopyErrors.AutoSize = true;
this.chbCarbonCopyIgnoreCopyErrors.Location = new System.Drawing.Point(19, 60);
this.chbCarbonCopyIgnoreCopyErrors.Name = "chbCarbonCopyIgnoreCopyErrors";
this.chbCarbonCopyIgnoreCopyErrors.Size = new System.Drawing.Size(146, 21);
this.chbCarbonCopyIgnoreCopyErrors.TabIndex = 5;
this.chbCarbonCopyIgnoreCopyErrors.Text = "Ignore copy errors";
this.tooltip.SetToolTip(this.chbCarbonCopyIgnoreCopyErrors, "If true, backup copy errors are ignored.");
this.chbCarbonCopyIgnoreCopyErrors.UseVisualStyleBackColor = true;
//
// chbUseCarbonCopy
//
this.chbUseCarbonCopy.AutoSize = true;
this.chbUseCarbonCopy.Location = new System.Drawing.Point(3, 3);
this.chbUseCarbonCopy.Name = "chbUseCarbonCopy";
this.chbUseCarbonCopy.Size = new System.Drawing.Size(162, 21);
this.chbUseCarbonCopy.TabIndex = 0;
this.chbUseCarbonCopy.Text = "Activate carbon copy";
this.tooltip.SetToolTip(this.chbUseCarbonCopy, "If true, all changes will be copied to another folder.");
this.chbUseCarbonCopy.UseVisualStyleBackColor = true;
this.chbUseCarbonCopy.CheckedChanged += new System.EventHandler(this.chbUseCarbonCopy_CheckedChanged);
//
// txtCarbonCopyFolder
//
this.txtCarbonCopyFolder.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.txtCarbonCopyFolder.Location = new System.Drawing.Point(153, 32);
this.txtCarbonCopyFolder.Margin = new System.Windows.Forms.Padding(3, 3, 0, 3);
this.txtCarbonCopyFolder.Name = "txtCarbonCopyFolder";
this.txtCarbonCopyFolder.Size = new System.Drawing.Size(312, 22);
this.txtCarbonCopyFolder.TabIndex = 2;
this.tooltip.SetToolTip(this.txtCarbonCopyFolder, "Location where copies are stored.");
this.txtCarbonCopyFolder.TextChanged += new System.EventHandler(this.txtCarbonCopyFolder_TextChanged);
//
// lblCarbonCopyFolder
//
this.lblCarbonCopyFolder.AutoSize = true;
this.lblCarbonCopyFolder.Location = new System.Drawing.Point(23, 35);
this.lblCarbonCopyFolder.Name = "lblCarbonCopyFolder";
this.lblCarbonCopyFolder.Size = new System.Drawing.Size(52, 17);
this.lblCarbonCopyFolder.TabIndex = 1;
this.lblCarbonCopyFolder.Text = "Folder:";
//
// btnOk
//
this.btnOk.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btnOk.DialogResult = System.Windows.Forms.DialogResult.OK;
this.btnOk.Location = new System.Drawing.Point(308, 272);
this.btnOk.Margin = new System.Windows.Forms.Padding(3, 6, 3, 3);
this.btnOk.Name = "btnOk";
this.btnOk.Size = new System.Drawing.Size(98, 29);
this.btnOk.TabIndex = 5;
this.btnOk.Text = "OK";
this.tooltip.SetToolTip(this.btnOk, "Apply all settings and close window.");
this.btnOk.UseVisualStyleBackColor = true;
this.btnOk.Click += new System.EventHandler(this.btnOk_Click);
//
// btnCancel
//
this.btnCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.btnCancel.Location = new System.Drawing.Point(412, 272);
this.btnCancel.Margin = new System.Windows.Forms.Padding(3, 6, 3, 3);
this.btnCancel.Name = "btnCancel";
this.btnCancel.Size = new System.Drawing.Size(98, 29);
this.btnCancel.TabIndex = 0;
this.btnCancel.Text = "Cancel";
this.tooltip.SetToolTip(this.btnCancel, "Cancel changes.");
this.btnCancel.UseVisualStyleBackColor = true;
//
// btnExit
//
this.btnExit.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.btnExit.Location = new System.Drawing.Point(12, 272);
this.btnExit.Margin = new System.Windows.Forms.Padding(3, 3, 15, 3);
this.btnExit.Name = "btnExit";
this.btnExit.Size = new System.Drawing.Size(98, 29);
this.btnExit.TabIndex = 2;
this.btnExit.TabStop = false;
this.btnExit.Text = "Exit";
this.tooltip.SetToolTip(this.btnExit, "Exit the application.");
this.btnExit.UseVisualStyleBackColor = true;
this.btnExit.Click += new System.EventHandler(this.btnExit_Click);
//
// btnAdvanced
//
this.btnAdvanced.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.btnAdvanced.DialogResult = System.Windows.Forms.DialogResult.OK;
this.btnAdvanced.Location = new System.Drawing.Point(128, 272);
this.btnAdvanced.Name = "btnAdvanced";
this.btnAdvanced.Size = new System.Drawing.Size(98, 29);
this.btnAdvanced.TabIndex = 4;
this.btnAdvanced.TabStop = false;
this.btnAdvanced.Text = "Advanced";
this.tooltip.SetToolTip(this.btnAdvanced, "Allow save of settings in registry.");
this.btnAdvanced.UseVisualStyleBackColor = true;
this.btnAdvanced.Click += new System.EventHandler(this.btnAdvanced_Click);
//
// chbHotkeyTogglesVisibility
//
this.chbHotkeyTogglesVisibility.AutoSize = true;
this.chbHotkeyTogglesVisibility.Location = new System.Drawing.Point(3, 122);
this.chbHotkeyTogglesVisibility.Name = "chbHotkeyTogglesVisibility";
this.chbHotkeyTogglesVisibility.Size = new System.Drawing.Size(176, 21);
this.chbHotkeyTogglesVisibility.TabIndex = 5;
this.chbHotkeyTogglesVisibility.Text = "Hotkey toggles visibility";
this.tooltip.SetToolTip(this.chbHotkeyTogglesVisibility, "If checked, hotkey will show window if its hidden and hide it if visible.");
this.chbHotkeyTogglesVisibility.UseVisualStyleBackColor = true;
//
// OptionsForm
//
this.AcceptButton = this.btnOk;
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.CancelButton = this.btnCancel;
this.ClientSize = new System.Drawing.Size(522, 313);
this.Controls.Add(this.btnExit);
this.Controls.Add(this.tab);
this.Controls.Add(this.btnOk);
this.Controls.Add(this.btnCancel);
this.Controls.Add(this.btnAdvanced);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "OptionsForm";
this.ShowIcon = false;
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Options";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.OptionsForm_FormClosing);
this.Load += new System.EventHandler(this.OptionsForm_Load);
this.tab.ResumeLayout(false);
this.tab_pagAppearance.ResumeLayout(false);
this.tab_pagAppearance.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.nudTabWidth)).EndInit();
this.tab_pagDisplay.ResumeLayout(false);
this.tab_pagDisplay.PerformLayout();
this.tab_pagFiles.ResumeLayout(false);
this.tab_pagFiles.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.nudQuickSaveIntervalInSeconds)).EndInit();
this.tab_pagBehavior.ResumeLayout(false);
this.tab_pagBehavior.PerformLayout();
this.tab_pagCarbonCopy.ResumeLayout(false);
this.tab_pagCarbonCopy.PerformLayout();
this.ResumeLayout(false);
}
#endregion
internal System.Windows.Forms.TabControl tab;
internal System.Windows.Forms.TabPage tab_pagAppearance;
internal System.Windows.Forms.Label lblColorExample;
internal System.Windows.Forms.Button btnColorBackground;
internal System.Windows.Forms.Button btnColorForeground;
internal System.Windows.Forms.Label lblColor;
internal System.Windows.Forms.Label lblFont;
internal System.Windows.Forms.Button btnFont;
internal System.Windows.Forms.NumericUpDown nudTabWidth;
internal System.Windows.Forms.Label lblTabWidth;
internal System.Windows.Forms.CheckBox chkFollowURLs;
internal System.Windows.Forms.CheckBox chkDisplayURLs;
internal System.Windows.Forms.TextBox txtFont;
internal System.Windows.Forms.TabPage tab_pagDisplay;
internal System.Windows.Forms.CheckBox chbVerticalScrollbar;
internal System.Windows.Forms.CheckBox chbHorizontalScrollbar;
internal System.Windows.Forms.CheckBox chbShowMinimizeMaximizeButtons;
internal System.Windows.Forms.CheckBox chkShowToolbar;
internal System.Windows.Forms.CheckBox chkShowInTaskbar;
internal System.Windows.Forms.TabPage tab_pagFiles;
internal System.Windows.Forms.NumericUpDown nudQuickSaveIntervalInSeconds;
internal System.Windows.Forms.Button btnOpenLocationFolder;
internal System.Windows.Forms.Label lblQuickSaveIntervalSeconds;
internal System.Windows.Forms.Label lblQuickSaveInterval;
internal System.Windows.Forms.CheckBox chkDeleteToRecycleBin;
internal System.Windows.Forms.CheckBox chkPreloadFilesOnStartup;
internal System.Windows.Forms.Button btnChangeLocation;
internal System.Windows.Forms.TabPage tab_pagBehavior;
internal System.Windows.Forms.TextBox txtHotkey;
internal System.Windows.Forms.Label lblHotkey;
internal System.Windows.Forms.CheckBox chkRunAtStartup;
internal System.Windows.Forms.CheckBox chkSingleClickTrayActivation;
internal System.Windows.Forms.CheckBox chkMinimizeToTray;
internal System.Windows.Forms.TabPage tab_pagCarbonCopy;
internal System.Windows.Forms.Button btnCarbonCopyOpenFolder;
internal System.Windows.Forms.Button btnCarbonCopyFolderSelect;
internal System.Windows.Forms.CheckBox chbCarbonCopyIgnoreCopyErrors;
internal System.Windows.Forms.CheckBox chbUseCarbonCopy;
internal System.Windows.Forms.TextBox txtCarbonCopyFolder;
internal System.Windows.Forms.Label lblCarbonCopyFolder;
internal System.Windows.Forms.Button btnOk;
internal System.Windows.Forms.Button btnCancel;
internal System.Windows.Forms.CheckBox chbMultilineTabs;
private System.Windows.Forms.Button btnExit;
internal System.Windows.Forms.Label lblSelectionDelimiters;
private System.Windows.Forms.ComboBox cmbSelectionDelimiters;
internal System.Windows.Forms.CheckBox chbSavePlainWithLF;
private System.Windows.Forms.ToolTip tooltip;
private System.Windows.Forms.Button btnAdvanced;
internal System.Windows.Forms.CheckBox chbHotkeyTogglesVisibility;
}
}
| |
using System;
using System.IO;
using System.ComponentModel;
using System.Collections.Generic;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using ChargeBee.Internal;
using ChargeBee.Api;
using ChargeBee.Models.Enums;
using ChargeBee.Filters.Enums;
namespace ChargeBee.Models
{
public class Card : Resource
{
public Card() { }
public Card(Stream stream)
{
using (StreamReader reader = new StreamReader(stream))
{
JObj = JToken.Parse(reader.ReadToEnd());
apiVersionCheck (JObj);
}
}
public Card(TextReader reader)
{
JObj = JToken.Parse(reader.ReadToEnd());
apiVersionCheck (JObj);
}
public Card(String jsonString)
{
JObj = JToken.Parse(jsonString);
apiVersionCheck (JObj);
}
#region Methods
public static EntityRequest<Type> Retrieve(string id)
{
string url = ApiUtil.BuildUrl("cards", CheckNull(id));
return new EntityRequest<Type>(url, HttpMethod.GET);
}
public static UpdateCardForCustomerRequest UpdateCardForCustomer(string id)
{
string url = ApiUtil.BuildUrl("customers", CheckNull(id), "credit_card");
return new UpdateCardForCustomerRequest(url, HttpMethod.POST);
}
public static SwitchGatewayForCustomerRequest SwitchGatewayForCustomer(string id)
{
string url = ApiUtil.BuildUrl("customers", CheckNull(id), "switch_gateway");
return new SwitchGatewayForCustomerRequest(url, HttpMethod.POST);
}
public static CopyCardForCustomerRequest CopyCardForCustomer(string id)
{
string url = ApiUtil.BuildUrl("customers", CheckNull(id), "copy_card");
return new CopyCardForCustomerRequest(url, HttpMethod.POST);
}
public static EntityRequest<Type> DeleteCardForCustomer(string id)
{
string url = ApiUtil.BuildUrl("customers", CheckNull(id), "delete_card");
return new EntityRequest<Type>(url, HttpMethod.POST);
}
#endregion
#region Properties
public string PaymentSourceId
{
get { return GetValue<string>("payment_source_id", true); }
}
public StatusEnum Status
{
get { return GetEnum<StatusEnum>("status", true); }
}
public GatewayEnum Gateway
{
get { return GetEnum<GatewayEnum>("gateway", true); }
}
public string GatewayAccountId
{
get { return GetValue<string>("gateway_account_id", false); }
}
public string RefTxId
{
get { return GetValue<string>("ref_tx_id", false); }
}
public string FirstName
{
get { return GetValue<string>("first_name", false); }
}
public string LastName
{
get { return GetValue<string>("last_name", false); }
}
public string Iin
{
get { return GetValue<string>("iin", true); }
}
public string Last4
{
get { return GetValue<string>("last4", true); }
}
public CardTypeEnum? CardType
{
get { return GetEnum<CardTypeEnum>("card_type", false); }
}
public FundingTypeEnum FundingType
{
get { return GetEnum<FundingTypeEnum>("funding_type", true); }
}
public int ExpiryMonth
{
get { return GetValue<int>("expiry_month", true); }
}
public int ExpiryYear
{
get { return GetValue<int>("expiry_year", true); }
}
public string IssuingCountry
{
get { return GetValue<string>("issuing_country", false); }
}
public string BillingAddr1
{
get { return GetValue<string>("billing_addr1", false); }
}
public string BillingAddr2
{
get { return GetValue<string>("billing_addr2", false); }
}
public string BillingCity
{
get { return GetValue<string>("billing_city", false); }
}
public string BillingStateCode
{
get { return GetValue<string>("billing_state_code", false); }
}
public string BillingState
{
get { return GetValue<string>("billing_state", false); }
}
public string BillingCountry
{
get { return GetValue<string>("billing_country", false); }
}
public string BillingZip
{
get { return GetValue<string>("billing_zip", false); }
}
public DateTime CreatedAt
{
get { return (DateTime)GetDateTime("created_at", true); }
}
public long? ResourceVersion
{
get { return GetValue<long?>("resource_version", false); }
}
public DateTime? UpdatedAt
{
get { return GetDateTime("updated_at", false); }
}
public string IpAddress
{
get { return GetValue<string>("ip_address", false); }
}
public PoweredByEnum? PoweredBy
{
get { return GetEnum<PoweredByEnum>("powered_by", false); }
}
public string CustomerId
{
get { return GetValue<string>("customer_id", true); }
}
public string MaskedNumber
{
get { return GetValue<string>("masked_number", false); }
}
#endregion
#region Requests
public class UpdateCardForCustomerRequest : EntityRequest<UpdateCardForCustomerRequest>
{
public UpdateCardForCustomerRequest(string url, HttpMethod method)
: base(url, method)
{
}
[Obsolete]
public UpdateCardForCustomerRequest Gateway(ChargeBee.Models.Enums.GatewayEnum gateway)
{
m_params.AddOpt("gateway", gateway);
return this;
}
public UpdateCardForCustomerRequest GatewayAccountId(string gatewayAccountId)
{
m_params.AddOpt("gateway_account_id", gatewayAccountId);
return this;
}
public UpdateCardForCustomerRequest TmpToken(string tmpToken)
{
m_params.AddOpt("tmp_token", tmpToken);
return this;
}
public UpdateCardForCustomerRequest FirstName(string firstName)
{
m_params.AddOpt("first_name", firstName);
return this;
}
public UpdateCardForCustomerRequest LastName(string lastName)
{
m_params.AddOpt("last_name", lastName);
return this;
}
public UpdateCardForCustomerRequest Number(string number)
{
m_params.Add("number", number);
return this;
}
public UpdateCardForCustomerRequest ExpiryMonth(int expiryMonth)
{
m_params.Add("expiry_month", expiryMonth);
return this;
}
public UpdateCardForCustomerRequest ExpiryYear(int expiryYear)
{
m_params.Add("expiry_year", expiryYear);
return this;
}
public UpdateCardForCustomerRequest Cvv(string cvv)
{
m_params.AddOpt("cvv", cvv);
return this;
}
public UpdateCardForCustomerRequest BillingAddr1(string billingAddr1)
{
m_params.AddOpt("billing_addr1", billingAddr1);
return this;
}
public UpdateCardForCustomerRequest BillingAddr2(string billingAddr2)
{
m_params.AddOpt("billing_addr2", billingAddr2);
return this;
}
public UpdateCardForCustomerRequest BillingCity(string billingCity)
{
m_params.AddOpt("billing_city", billingCity);
return this;
}
public UpdateCardForCustomerRequest BillingStateCode(string billingStateCode)
{
m_params.AddOpt("billing_state_code", billingStateCode);
return this;
}
public UpdateCardForCustomerRequest BillingState(string billingState)
{
m_params.AddOpt("billing_state", billingState);
return this;
}
public UpdateCardForCustomerRequest BillingZip(string billingZip)
{
m_params.AddOpt("billing_zip", billingZip);
return this;
}
public UpdateCardForCustomerRequest BillingCountry(string billingCountry)
{
m_params.AddOpt("billing_country", billingCountry);
return this;
}
[Obsolete]
public UpdateCardForCustomerRequest IpAddress(string ipAddress)
{
m_params.AddOpt("ip_address", ipAddress);
return this;
}
[Obsolete]
public UpdateCardForCustomerRequest CustomerVatNumber(string customerVatNumber)
{
m_params.AddOpt("customer[vat_number]", customerVatNumber);
return this;
}
}
public class SwitchGatewayForCustomerRequest : EntityRequest<SwitchGatewayForCustomerRequest>
{
public SwitchGatewayForCustomerRequest(string url, HttpMethod method)
: base(url, method)
{
}
[Obsolete]
public SwitchGatewayForCustomerRequest Gateway(ChargeBee.Models.Enums.GatewayEnum gateway)
{
m_params.AddOpt("gateway", gateway);
return this;
}
public SwitchGatewayForCustomerRequest GatewayAccountId(string gatewayAccountId)
{
m_params.Add("gateway_account_id", gatewayAccountId);
return this;
}
}
public class CopyCardForCustomerRequest : EntityRequest<CopyCardForCustomerRequest>
{
public CopyCardForCustomerRequest(string url, HttpMethod method)
: base(url, method)
{
}
public CopyCardForCustomerRequest GatewayAccountId(string gatewayAccountId)
{
m_params.Add("gateway_account_id", gatewayAccountId);
return this;
}
}
#endregion
public enum StatusEnum
{
UnKnown, /*Indicates unexpected value for this enum. You can get this when there is a
dotnet-client version incompatibility. We suggest you to upgrade to the latest version */
[EnumMember(Value = "valid")]
Valid,
[EnumMember(Value = "expiring")]
Expiring,
[EnumMember(Value = "expired")]
Expired,
}
public enum CardTypeEnum
{
UnKnown, /*Indicates unexpected value for this enum. You can get this when there is a
dotnet-client version incompatibility. We suggest you to upgrade to the latest version */
[EnumMember(Value = "visa")]
Visa,
[EnumMember(Value = "mastercard")]
Mastercard,
[EnumMember(Value = "american_express")]
AmericanExpress,
[EnumMember(Value = "discover")]
Discover,
[EnumMember(Value = "jcb")]
Jcb,
[EnumMember(Value = "diners_club")]
DinersClub,
[EnumMember(Value = "bancontact")]
Bancontact,
[EnumMember(Value = "other")]
Other,
[EnumMember(Value = "not_applicable")]
NotApplicable,
}
public enum FundingTypeEnum
{
UnKnown, /*Indicates unexpected value for this enum. You can get this when there is a
dotnet-client version incompatibility. We suggest you to upgrade to the latest version */
[EnumMember(Value = "credit")]
Credit,
[EnumMember(Value = "debit")]
Debit,
[EnumMember(Value = "prepaid")]
Prepaid,
[EnumMember(Value = "not_known")]
NotKnown,
[EnumMember(Value = "not_applicable")]
NotApplicable,
}
public enum PoweredByEnum
{
UnKnown, /*Indicates unexpected value for this enum. You can get this when there is a
dotnet-client version incompatibility. We suggest you to upgrade to the latest version */
[EnumMember(Value = "ideal")]
Ideal,
[EnumMember(Value = "sofort")]
Sofort,
[EnumMember(Value = "bancontact")]
Bancontact,
[EnumMember(Value = "giropay")]
Giropay,
[EnumMember(Value = "card")]
Card,
[EnumMember(Value = "latam_local_card")]
LatamLocalCard,
[EnumMember(Value = "not_applicable")]
NotApplicable,
}
#region Subclasses
#endregion
}
}
| |
// Copyright 2011 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using NodaTime.Annotations;
using NodaTime.Calendars;
using NodaTime.Utility;
using System;
using System.Globalization;
namespace NodaTime.Text
{
/// <summary>
/// The result of a parse operation.
/// </summary>
/// <typeparam name="T">The type which was parsed, such as a <see cref="LocalDateTime"/>.</typeparam>
/// <threadsafety>This type is immutable reference type. See the thread safety section of the user guide for more information.</threadsafety>
[Immutable]
public sealed class ParseResult<T>
{
// Invariant: exactly one of value or exceptionProvider is null.
private readonly T value;
private readonly Func<Exception>? exceptionProvider;
internal bool ContinueAfterErrorWithMultipleFormats { get; }
private ParseResult(Func<Exception> exceptionProvider, bool continueWithMultiple)
{
this.exceptionProvider = exceptionProvider;
this.ContinueAfterErrorWithMultipleFormats = continueWithMultiple;
// Satisfy the compiler around the invariant.
value = default!;
}
private ParseResult(T value)
{
this.value = value;
}
/// <summary>
/// Gets the value from the parse operation if it was successful, or throws an exception indicating the parse failure
/// otherwise.
/// </summary>
/// <remarks>
/// This method is exactly equivalent to calling the <see cref="GetValueOrThrow"/> method, but is terser if the code is
/// already clear that it will throw if the parse failed.
/// </remarks>
/// <value>The result of the parsing operation if it was successful.</value>
public T Value => GetValueOrThrow();
/// <summary>
/// Gets an exception indicating the cause of the parse failure.
/// </summary>
/// <remarks>This property is typically used to wrap parse failures in higher level exceptions.</remarks>
/// <value>The exception indicating the cause of the parse failure.</value>
/// <exception cref="InvalidOperationException">The parse operation succeeded.</exception>
public Exception Exception
{
get
{
if (exceptionProvider is null)
{
throw new InvalidOperationException("Parse operation succeeded, so no exception is available");
}
return exceptionProvider();
}
}
/// <summary>
/// Gets the value from the parse operation if it was successful, or throws an exception indicating the parse failure
/// otherwise.
/// </summary>
/// <remarks>
/// This method is exactly equivalent to fetching the <see cref="Value"/> property, but more explicit in terms of throwing
/// an exception on failure.
/// </remarks>
/// <returns>The result of the parsing operation if it was successful.</returns>
public T GetValueOrThrow()
{
if (exceptionProvider is null)
{
return value;
}
throw exceptionProvider();
}
/// <summary>
/// Returns the success value, and sets the out parameter to either
/// the specified failure value of T or the successful parse result value.
/// </summary>
/// <param name="failureValue">The "default" value to set in <paramref name="result"/> if parsing failed.</param>
/// <param name="result">The parameter to store the parsed value in on success.</param>
/// <returns>True if this parse result was successful, or false otherwise.</returns>
public bool TryGetValue(T failureValue, out T result)
{
bool success = exceptionProvider is null;
result = success ? value : failureValue;
return success;
}
/// <summary>
/// Indicates whether the parse operation was successful.
/// </summary>
/// <remarks>
/// This returns True if and only if fetching the value with the <see cref="Value"/> property will return with no exception.
/// </remarks>
/// <value>true if the parse operation was successful; otherwise false.</value>
public bool Success => exceptionProvider is null;
/// <summary>
/// Converts this result to a new target type, either by executing the given projection
/// for a success result, or propagating the exception provider for failure.
/// </summary>
/// <typeparam name="TTarget">The target type of the conversion.</typeparam>
/// <param name="projection">The projection to apply for the value of this result,
/// if it's a success result.</param>
/// <returns>A ParseResult for the target type, either with a value obtained by applying the specified
/// projection to the value in this result, or with the same error as this result.</returns>
public ParseResult<TTarget> Convert<TTarget>(Func<T, TTarget> projection)
{
Preconditions.CheckNotNull(projection, nameof(projection));
return Success
? ParseResult<TTarget>.ForValue(projection(Value))
: new ParseResult<TTarget>(exceptionProvider!, ContinueAfterErrorWithMultipleFormats);
}
/// <summary>
/// Converts this result to a new target type by propagating the exception provider.
/// This parse result must already be an error result.
/// </summary>
/// <returns>A ParseResult for the target type, with the same error as this result.</returns>
public ParseResult<TTarget> ConvertError<TTarget>()
{
if (Success)
{
throw new InvalidOperationException("ConvertError should not be called on a successful parse result");
}
return new ParseResult<TTarget>(exceptionProvider!, ContinueAfterErrorWithMultipleFormats);
}
#region Factory methods and readonly static fields
/// <summary>
/// Produces a ParseResult which represents a successful parse operation.
/// </summary>
/// <remarks>When T is a reference type, <paramref name="value"/> should not be null,
/// but this isn't currently checked.</remarks>
/// <param name="value">The successfully parsed value.</param>
/// <returns>A ParseResult representing a successful parsing operation.</returns>
public static ParseResult<T> ForValue(T value) => new ParseResult<T>(value);
/// <summary>
/// Produces a ParseResult which represents a failed parsing operation.
/// </summary>
/// <remarks>This method accepts a delegate rather than the exception itself, as creating an
/// exception can be relatively slow: if the client doesn't need the actual exception, just the information
/// that the parse failed, there's no point in creating the exception.</remarks>
/// <param name="exceptionProvider">A delegate that produces the exception representing the error that
/// caused the parse to fail.</param>
/// <returns>A ParseResult representing a failed parsing operation.</returns>
public static ParseResult<T> ForException(Func<Exception> exceptionProvider) =>
new ParseResult<T>(Preconditions.CheckNotNull(exceptionProvider, nameof(exceptionProvider)), false);
internal static ParseResult<T> ForInvalidValue(ValueCursor cursor, string formatString, params object[] parameters) =>
ForInvalidValue(() =>
{
// Format the message which is specific to the kind of parse error.
string detailMessage = string.Format(CultureInfo.CurrentCulture, formatString, parameters);
// Format the overall message, containing the parse error and the value itself.
string overallMessage = string.Format(CultureInfo.CurrentCulture, TextErrorMessages.UnparsableValue, detailMessage, cursor);
return new UnparsableValueException(overallMessage);
});
internal static ParseResult<T> ForInvalidValuePostParse(string text, string formatString, params object[] parameters) =>
ForInvalidValue(() =>
{
// Format the message which is specific to the kind of parse error.
string detailMessage = string.Format(CultureInfo.CurrentCulture, formatString, parameters);
// Format the overall message, containing the parse error and the value itself.
string overallMessage = string.Format(CultureInfo.CurrentCulture, TextErrorMessages.UnparsableValuePostParse, detailMessage, text);
return new UnparsableValueException(overallMessage);
});
private static ParseResult<T> ForInvalidValue(Func<Exception> exceptionProvider) => new ParseResult<T>(exceptionProvider, true);
internal static ParseResult<T> ArgumentNull(string parameter) => new ParseResult<T>(() => new ArgumentNullException(parameter), false);
internal static ParseResult<T> PositiveSignInvalid(ValueCursor cursor) => ForInvalidValue(cursor, TextErrorMessages.PositiveSignInvalid);
// Special case: it's a fault with the value, but we still don't want to continue with multiple patterns.
// Also, there's no point in including the text.
internal static readonly ParseResult<T> ValueStringEmpty =
new ParseResult<T>(() => new UnparsableValueException(string.Format(CultureInfo.CurrentCulture, TextErrorMessages.ValueStringEmpty)), false);
internal static ParseResult<T> ExtraValueCharacters(ValueCursor cursor, string remainder) => ForInvalidValue(cursor, TextErrorMessages.ExtraValueCharacters, remainder);
internal static ParseResult<T> QuotedStringMismatch(ValueCursor cursor) => ForInvalidValue(cursor, TextErrorMessages.QuotedStringMismatch);
internal static ParseResult<T> EscapedCharacterMismatch(ValueCursor cursor, char patternCharacter) => ForInvalidValue(cursor, TextErrorMessages.EscapedCharacterMismatch, patternCharacter);
internal static ParseResult<T> EndOfString(ValueCursor cursor) => ForInvalidValue(cursor, TextErrorMessages.EndOfString);
internal static ParseResult<T> TimeSeparatorMismatch(ValueCursor cursor) => ForInvalidValue(cursor, TextErrorMessages.TimeSeparatorMismatch);
internal static ParseResult<T> DateSeparatorMismatch(ValueCursor cursor) => ForInvalidValue(cursor, TextErrorMessages.DateSeparatorMismatch);
internal static ParseResult<T> MissingNumber(ValueCursor cursor) => ForInvalidValue(cursor, TextErrorMessages.MissingNumber);
internal static ParseResult<T> UnexpectedNegative(ValueCursor cursor) => ForInvalidValue(cursor, TextErrorMessages.UnexpectedNegative);
/// <summary>
/// This isn't really an issue with the value so much as the pattern... but the result is the same.
/// </summary>
internal static readonly ParseResult<T> FormatOnlyPattern =
new ParseResult<T>(() => new UnparsableValueException(string.Format(CultureInfo.CurrentCulture, TextErrorMessages.FormatOnlyPattern)), true);
internal static ParseResult<T> MismatchedNumber(ValueCursor cursor, string pattern) => ForInvalidValue(cursor, TextErrorMessages.MismatchedNumber, pattern);
internal static ParseResult<T> MismatchedCharacter(ValueCursor cursor, char patternCharacter) => ForInvalidValue(cursor, TextErrorMessages.MismatchedCharacter, patternCharacter);
internal static ParseResult<T> MismatchedText(ValueCursor cursor, char field) => ForInvalidValue(cursor, TextErrorMessages.MismatchedText, field);
internal static ParseResult<T> NoMatchingFormat(ValueCursor cursor) => ForInvalidValue(cursor, TextErrorMessages.NoMatchingFormat);
internal static ParseResult<T> ValueOutOfRange(ValueCursor cursor, object value) => ForInvalidValue(cursor, TextErrorMessages.ValueOutOfRange, value, typeof(T));
internal static ParseResult<T> MissingSign(ValueCursor cursor) => ForInvalidValue(cursor, TextErrorMessages.MissingSign);
internal static ParseResult<T> MissingAmPmDesignator(ValueCursor cursor) => ForInvalidValue(cursor, TextErrorMessages.MissingAmPmDesignator);
internal static ParseResult<T> NoMatchingCalendarSystem(ValueCursor cursor) => ForInvalidValue(cursor, TextErrorMessages.NoMatchingCalendarSystem);
internal static ParseResult<T> NoMatchingZoneId(ValueCursor cursor) => ForInvalidValue(cursor, TextErrorMessages.NoMatchingZoneId);
internal static ParseResult<T> InvalidHour24(string text) => ForInvalidValuePostParse(text, TextErrorMessages.InvalidHour24);
internal static ParseResult<T> FieldValueOutOfRange(ValueCursor cursor, int value, char field) =>
ForInvalidValue(cursor, TextErrorMessages.FieldValueOutOfRange, value, field, typeof(T));
internal static ParseResult<T> FieldValueOutOfRange(ValueCursor cursor, long value, char field) =>
ForInvalidValue(cursor, TextErrorMessages.FieldValueOutOfRange, value, field, typeof(T));
internal static ParseResult<T> FieldValueOutOfRangePostParse(string text, int value, char field, Type eventualResultType) =>
ForInvalidValuePostParse(text, TextErrorMessages.FieldValueOutOfRange, value, field, eventualResultType);
/// <summary>
/// Two fields (e.g. "hour of day" and "hour of half day") were mutually inconsistent.
/// </summary>
internal static ParseResult<T> InconsistentValues(string text, char field1, char field2, Type eventualResultType) =>
ForInvalidValuePostParse(text, TextErrorMessages.InconsistentValues2, field1, field2, eventualResultType);
/// <summary>
/// The month of year is inconsistent between the text and numeric specifications.
/// We can't use InconsistentValues for this as the pattern character is the same in both cases.
/// </summary>
internal static ParseResult<T> InconsistentMonthValues(string text) => ForInvalidValuePostParse(text, TextErrorMessages.InconsistentMonthTextValue);
/// <summary>
/// The day of month is inconsistent with the day of week value.
/// We can't use InconsistentValues for this as the pattern character is the same in both cases.
/// </summary>
internal static ParseResult<T> InconsistentDayOfWeekTextValue(string text) => ForInvalidValuePostParse(text, TextErrorMessages.InconsistentDayOfWeekTextValue);
/// <summary>
/// We'd expected to get to the end of the string now, but we haven't.
/// </summary>
internal static ParseResult<T> ExpectedEndOfString(ValueCursor cursor) => ForInvalidValue(cursor, TextErrorMessages.ExpectedEndOfString);
internal static ParseResult<T> YearOfEraOutOfRange(string text, int value, Era era, CalendarSystem calendar) =>
ForInvalidValuePostParse(text, TextErrorMessages.YearOfEraOutOfRange, value, era.Name, calendar.Name);
internal static ParseResult<T> MonthOutOfRange(string text, int month, int year) => ForInvalidValuePostParse(text, TextErrorMessages.MonthOutOfRange, month, year);
internal static ParseResult<T> IsoMonthOutOfRange(string text, int month) => ForInvalidValuePostParse(text, TextErrorMessages.IsoMonthOutOfRange, month);
internal static ParseResult<T> DayOfMonthOutOfRange(string text, int day, int month, int year) => ForInvalidValuePostParse(text, TextErrorMessages.DayOfMonthOutOfRange, day, month, year);
internal static ParseResult<T> DayOfMonthOutOfRangeNoYear(string text, int day, int month) => ForInvalidValuePostParse(text, TextErrorMessages.DayOfMonthOutOfRangeNoYear, day, month);
internal static ParseResult<T> InvalidOffset(string text) => ForInvalidValuePostParse(text, TextErrorMessages.InvalidOffset);
internal static ParseResult<T> SkippedLocalTime(string text) => ForInvalidValuePostParse(text, TextErrorMessages.SkippedLocalTime);
internal static ParseResult<T> AmbiguousLocalTime(string text) => ForInvalidValuePostParse(text, TextErrorMessages.AmbiguousLocalTime);
#endregion
}
}
| |
/*
* Copyright 2013 ZXing 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.Generic;
using System.Collections.ObjectModel;
using ZXing.Common;
namespace ZXing.Aztec.Internal
{
/// <summary>
/// This produces nearly optimal encodings of text into the first-level of
/// encoding used by Aztec code.
/// It uses a dynamic algorithm. For each prefix of the string, it determines
/// a set of encodings that could lead to this prefix. We repeatedly add a
/// character and generate a new set of optimal encodings until we have read
/// through the entire input.
/// @author Frank Yellin
/// @author Rustam Abdullaev
/// </summary>
public sealed class HighLevelEncoder
{
internal static String[] MODE_NAMES = {"UPPER", "LOWER", "DIGIT", "MIXED", "PUNCT"};
internal const int MODE_UPPER = 0; // 5 bits
internal const int MODE_LOWER = 1; // 5 bits
internal const int MODE_DIGIT = 2; // 4 bits
internal const int MODE_MIXED = 3; // 5 bits
internal const int MODE_PUNCT = 4; // 5 bits
// The Latch Table shows, for each pair of Modes, the optimal method for
// getting from one mode to another. In the worst possible case, this can
// be up to 14 bits. In the best possible case, we are already there!
// The high half-word of each entry gives the number of bits.
// The low half-word of each entry are the actual bits necessary to change
internal static readonly int[][] LATCH_TABLE = new int[][]
{
new[]
{
0,
(5 << 16) + 28, // UPPER -> LOWER
(5 << 16) + 30, // UPPER -> DIGIT
(5 << 16) + 29, // UPPER -> MIXED
(10 << 16) + (29 << 5) + 30, // UPPER -> MIXED -> PUNCT
},
new[]
{
(9 << 16) + (30 << 4) + 14, // LOWER -> DIGIT -> UPPER
0,
(5 << 16) + 30, // LOWER -> DIGIT
(5 << 16) + 29, // LOWER -> MIXED
(10 << 16) + (29 << 5) + 30, // LOWER -> MIXED -> PUNCT
},
new[]
{
(4 << 16) + 14, // DIGIT -> UPPER
(9 << 16) + (14 << 5) + 28, // DIGIT -> UPPER -> LOWER
0,
(9 << 16) + (14 << 5) + 29, // DIGIT -> UPPER -> MIXED
(14 << 16) + (14 << 10) + (29 << 5) + 30,
// DIGIT -> UPPER -> MIXED -> PUNCT
},
new[]
{
(5 << 16) + 29, // MIXED -> UPPER
(5 << 16) + 28, // MIXED -> LOWER
(10 << 16) + (29 << 5) + 30, // MIXED -> UPPER -> DIGIT
0,
(5 << 16) + 30, // MIXED -> PUNCT
},
new[]
{
(5 << 16) + 31, // PUNCT -> UPPER
(10 << 16) + (31 << 5) + 28, // PUNCT -> UPPER -> LOWER
(10 << 16) + (31 << 5) + 30, // PUNCT -> UPPER -> DIGIT
(10 << 16) + (31 << 5) + 29, // PUNCT -> UPPER -> MIXED
0,
},
};
// A reverse mapping from [mode][char] to the encoding for that character
// in that mode. An entry of 0 indicates no mapping exists.
internal static readonly int[][] CHAR_MAP = new int[5][];
// A map showing the available shift codes. (The shifts to BINARY are not shown
internal static readonly int[][] SHIFT_TABLE = new int[6][]; // mode shift codes, per table
private readonly byte[] text;
static HighLevelEncoder()
{
CHAR_MAP[0] = new int[256];
CHAR_MAP[1] = new int[256];
CHAR_MAP[2] = new int[256];
CHAR_MAP[3] = new int[256];
CHAR_MAP[4] = new int[256];
SHIFT_TABLE[0] = new int[6];
SHIFT_TABLE[1] = new int[6];
SHIFT_TABLE[2] = new int[6];
SHIFT_TABLE[3] = new int[6];
SHIFT_TABLE[4] = new int[6];
SHIFT_TABLE[5] = new int[6];
CHAR_MAP[MODE_UPPER][' '] = 1;
for (int c = 'A'; c <= 'Z'; c++)
{
CHAR_MAP[MODE_UPPER][c] = c - 'A' + 2;
}
CHAR_MAP[MODE_LOWER][' '] = 1;
for (int c = 'a'; c <= 'z'; c++)
{
CHAR_MAP[MODE_LOWER][c] = c - 'a' + 2;
}
CHAR_MAP[MODE_DIGIT][' '] = 1;
for (int c = '0'; c <= '9'; c++)
{
CHAR_MAP[MODE_DIGIT][c] = c - '0' + 2;
}
CHAR_MAP[MODE_DIGIT][','] = 12;
CHAR_MAP[MODE_DIGIT]['.'] = 13;
int[] mixedTable = {
'\0', ' ', 1, 2, 3, 4, 5, 6, 7, '\b', '\t', '\n', 11, '\f', '\r',
27, 28, 29, 30, 31, '@', '\\', '^', '_', '`', '|', '~', 127
};
for (int i = 0; i < mixedTable.Length; i++)
{
CHAR_MAP[MODE_MIXED][mixedTable[i]] = i;
}
int[] punctTable =
{
'\0', '\r', '\0', '\0', '\0', '\0', '!', '\'', '#', '$', '%', '&', '\'',
'(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?',
'[', ']', '{', '}'
};
for (int i = 0; i < punctTable.Length; i++)
{
if (punctTable[i] > 0)
{
CHAR_MAP[MODE_PUNCT][punctTable[i]] = i;
}
}
foreach (int[] table in SHIFT_TABLE)
{
SupportClass.Fill(table, -1);
}
SHIFT_TABLE[MODE_UPPER][MODE_PUNCT] = 0;
SHIFT_TABLE[MODE_LOWER][MODE_PUNCT] = 0;
SHIFT_TABLE[MODE_LOWER][MODE_UPPER] = 28;
SHIFT_TABLE[MODE_MIXED][MODE_PUNCT] = 0;
SHIFT_TABLE[MODE_DIGIT][MODE_PUNCT] = 0;
SHIFT_TABLE[MODE_DIGIT][MODE_UPPER] = 15;
}
/// <summary>
///
/// </summary>
/// <param name="text"></param>
public HighLevelEncoder(byte[] text)
{
this.text = text;
}
/// <summary>
/// Convert the text represented by this High Level Encoder into a BitArray.
/// </summary>
/// <returns>text represented by this encoder encoded as a <see cref="BitArray"/></returns>
public BitArray encode()
{
ICollection<State> states = new Collection<State>();
states.Add(State.INITIAL_STATE);
for (int index = 0; index < text.Length; index++)
{
int pairCode;
// don't remove the (int) type cast, mono compiler needs it
int nextChar = (index + 1 < text.Length) ? (int)text[index + 1] : 0;
switch (text[index])
{
case (byte)'\r':
pairCode = nextChar == '\n' ? 2 : 0;
break;
case (byte)'.':
pairCode = nextChar == ' ' ? 3 : 0;
break;
case (byte)',':
pairCode = nextChar == ' ' ? 4 : 0;
break;
case (byte)':':
pairCode = nextChar == ' ' ? 5 : 0;
break;
default:
pairCode = 0;
break;
}
if (pairCode > 0)
{
// We have one of the four special PUNCT pairs. Treat them specially.
// Get a new set of states for the two new characters.
states = updateStateListForPair(states, index, pairCode);
index++;
}
else
{
// Get a new set of states for the new character.
states = updateStateListForChar(states, index);
}
}
// We are left with a set of states. Find the shortest one.
State minState = null;
foreach (var state in states)
{
if (minState == null)
{
minState = state;
}
else
{
if (state.BitCount < minState.BitCount)
{
minState = state;
}
}
}
/*
State minState = Collections.min(states, new Comparator<State>() {
@Override
public int compare(State a, State b) {
return a.getBitCount() - b.getBitCount();
}
});
*/
// Convert it to a bit array, and return.
return minState.toBitArray(text);
}
// We update a set of states for a new character by updating each state
// for the new character, merging the results, and then removing the
// non-optimal states.
private ICollection<State> updateStateListForChar(IEnumerable<State> states, int index)
{
var result = new LinkedList<State>();
foreach (State state in states)
{
updateStateForChar(state, index, result);
}
return simplifyStates(result);
}
// Return a set of states that represent the possible ways of updating this
// state for the next character. The resulting set of states are added to
// the "result" list.
private void updateStateForChar(State state, int index, ICollection<State> result)
{
char ch = (char) (text[index] & 0xFF);
bool charInCurrentTable = CHAR_MAP[state.Mode][ch] > 0;
State stateNoBinary = null;
for (int mode = 0; mode <= MODE_PUNCT; mode++)
{
int charInMode = CHAR_MAP[mode][ch];
if (charInMode > 0)
{
if (stateNoBinary == null)
{
// Only create stateNoBinary the first time it's required.
stateNoBinary = state.endBinaryShift(index);
}
// Try generating the character by latching to its mode
if (!charInCurrentTable || mode == state.Mode || mode == MODE_DIGIT)
{
// If the character is in the current table, we don't want to latch to
// any other mode except possibly digit (which uses only 4 bits). Any
// other latch would be equally successful *after* this character, and
// so wouldn't save any bits.
var latchState = stateNoBinary.latchAndAppend(mode, charInMode);
result.Add(latchState);
}
// Try generating the character by switching to its mode.
if (!charInCurrentTable && SHIFT_TABLE[state.Mode][mode] >= 0)
{
// It never makes sense to temporarily shift to another mode if the
// character exists in the current mode. That can never save bits.
var shiftState = stateNoBinary.shiftAndAppend(mode, charInMode);
result.Add(shiftState);
}
}
}
if (state.BinaryShiftByteCount > 0 || CHAR_MAP[state.Mode][ch] == 0)
{
// It's never worthwhile to go into binary shift mode if you're not already
// in binary shift mode, and the character exists in your current mode.
// That can never save bits over just outputting the char in the current mode.
var binaryState = state.addBinaryShiftChar(index);
result.Add(binaryState);
}
}
private static ICollection<State> updateStateListForPair(IEnumerable<State> states, int index, int pairCode)
{
var result = new LinkedList<State>();
foreach (State state in states)
{
updateStateForPair(state, index, pairCode, result);
}
return simplifyStates(result);
}
private static void updateStateForPair(State state, int index, int pairCode, ICollection<State> result)
{
State stateNoBinary = state.endBinaryShift(index);
// Possibility 1. Latch to MODE_PUNCT, and then append this code
result.Add(stateNoBinary.latchAndAppend(MODE_PUNCT, pairCode));
if (state.Mode != MODE_PUNCT)
{
// Possibility 2. Shift to MODE_PUNCT, and then append this code.
// Every state except MODE_PUNCT (handled above) can shift
result.Add(stateNoBinary.shiftAndAppend(MODE_PUNCT, pairCode));
}
if (pairCode == 3 || pairCode == 4)
{
// both characters are in DIGITS. Sometimes better to just add two digits
var digitState = stateNoBinary
.latchAndAppend(MODE_DIGIT, 16 - pairCode) // period or comma in DIGIT
.latchAndAppend(MODE_DIGIT, 1); // space in DIGIT
result.Add(digitState);
}
if (state.BinaryShiftByteCount > 0)
{
// It only makes sense to do the characters as binary if we're already
// in binary mode.
State binaryState = state.addBinaryShiftChar(index).addBinaryShiftChar(index + 1);
result.Add(binaryState);
}
}
private static ICollection<State> simplifyStates(IEnumerable<State> states)
{
var result = new LinkedList<State>();
var removeList = new List<State>();
foreach (State newState in states)
{
bool add = true;
removeList.Clear();
foreach (var oldState in result)
{
if (oldState.isBetterThanOrEqualTo(newState))
{
add = false;
break;
}
if (newState.isBetterThanOrEqualTo(oldState))
{
removeList.Add(oldState);
}
}
if (add)
{
result.AddLast(newState);
}
foreach (var removeItem in removeList)
{
result.Remove(removeItem);
}
}
return result;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;
using Orleans.Hosting;
using Orleans;
using Orleans.Runtime;
using Orleans.TestingHost;
using TestExtensions;
using UnitTests.GrainInterfaces;
using UnitTests.Grains;
using Xunit;
using Xunit.Abstractions;
using Orleans.Configuration;
namespace UnitTests
{
internal class ReentrancyTestsSiloBuilderConfigurator : ISiloBuilderConfigurator
{
public void Configure(ISiloHostBuilder hostBuilder)
{
hostBuilder.AddSimpleMessageStreamProvider("sms")
.AddMemoryGrainStorage("MemoryStore")
.AddMemoryGrainStorage("PubSubStore")
.AddMemoryGrainStorageAsDefault();
}
}
public class ReentrancyTests : OrleansTestingBase, IClassFixture<ReentrancyTests.Fixture>
{
public class Fixture : BaseTestClusterFixture
{
protected override void ConfigureTestCluster(TestClusterBuilder builder)
{
builder.AddSiloBuilderConfigurator<ReentrancyTestsSiloBuilderConfigurator>();
}
}
public class SiloConfigurator :ISiloBuilderConfigurator
{
public void Configure(ISiloHostBuilder hostBuilder)
{
hostBuilder.Configure<SchedulingOptions>(options => options.AllowCallChainReentrancy = true);
}
}
private readonly ITestOutputHelper output;
private readonly Fixture fixture;
private readonly TestCluster hostedCluster;
public ReentrancyTests(ITestOutputHelper output, Fixture fixture)
{
this.output = output;
this.fixture = fixture;
hostedCluster = fixture.HostedCluster;
}
// See https://github.com/dotnet/orleans/pull/5086
[Fact, TestCategory("Functional"), TestCategory("Tasks"), TestCategory("Reentrancy")]
public async Task CorrelationId_Bug()
{
var grain = this.fixture.GrainFactory.GetGrain<IFirstGrain>(Guid.NewGuid());
await grain.Start(Guid.NewGuid(), Guid.NewGuid());
}
[Fact, TestCategory("Functional"), TestCategory("Tasks"), TestCategory("Reentrancy")]
public void ReentrantGrain()
{
var reentrant = this.fixture.GrainFactory.GetGrain<IReentrantGrain>(GetRandomGrainId());
reentrant.SetSelf(reentrant).Wait();
try
{
Assert.True(reentrant.Two().Wait(2000), "Grain should reenter");
}
catch (Exception ex)
{
Assert.True(false, string.Format("Unexpected exception {0}: {1}", ex.Message, ex.StackTrace));
}
this.fixture.Logger.Info("Reentrancy ReentrantGrain Test finished OK.");
}
[Fact, TestCategory("Functional"), TestCategory("Tasks"), TestCategory("Reentrancy")]
public void NonReentrantGrain_WithMayInterleavePredicate_WhenPredicateReturnsTrue()
{
var grain = this.fixture.GrainFactory.GetGrain<IMayInterleavePredicateGrain>(GetRandomGrainId());
grain.SetSelf(grain).Wait();
try
{
Assert.True(grain.TwoReentrant().Wait(2000), "Grain should reenter when MayInterleave predicate returns true");
}
catch (Exception ex)
{
Assert.True(false, string.Format("Unexpected exception {0}: {1}", ex.Message, ex.StackTrace));
}
this.fixture.Logger.Info("Reentrancy NonReentrantGrain_WithMayInterleavePredicate_WhenPredicateReturnsTrue Test finished OK.");
}
[Fact, TestCategory("Functional"), TestCategory("Tasks"), TestCategory("Reentrancy")]
public void NonReentrantGrain_WithMayInterleavePredicate_StreamItemDelivery_WhenPredicateReturnsTrue()
{
var grain = this.fixture.GrainFactory.GetGrain<IMayInterleavePredicateGrain>(GetRandomGrainId());
grain.SubscribeToStream().Wait();
try
{
grain.PushToStream("reentrant").Wait(2000);
}
catch (Exception ex)
{
Assert.True(false, string.Format("Unexpected exception {0}: {1}", ex.Message, ex.StackTrace));
}
this.fixture.Logger.Info("Reentrancy NonReentrantGrain_WithMayInterleavePredicate_StreamItemDelivery_WhenPredicateReturnsTrue Test finished OK.");
}
[Fact, TestCategory("Functional"), TestCategory("Tasks"), TestCategory("Reentrancy")]
public void NonReentrantGrain_WithMayInterleavePredicate_WhenPredicateThrows()
{
var grain = this.fixture.GrainFactory.GetGrain<IMayInterleavePredicateGrain>(GetRandomGrainId());
grain.SetSelf(grain).Wait();
try
{
grain.Exceptional().Wait(2000);
}
catch (Exception ex)
{
Assert.IsType<OrleansException>(ex.GetBaseException());
Assert.NotNull(ex.GetBaseException().InnerException);
Assert.IsType<ApplicationException>(ex.GetBaseException().InnerException);
Assert.True(ex.GetBaseException().InnerException?.Message == "boom",
"Should fail with Orleans runtime exception having all of necessary details");
}
this.fixture.Logger.Info("Reentrancy NonReentrantGrain_WithMayInterleavePredicate_WhenPredicateThrows Test finished OK.");
}
[Fact, TestCategory("Functional"), TestCategory("Tasks"), TestCategory("Reentrancy")]
public async Task IsReentrant()
{
IReentrantTestSupportGrain grain = this.fixture.GrainFactory.GetGrain<IReentrantTestSupportGrain>(0);
var grainFullName = typeof(ReentrantGrain).FullName;
Assert.True(await grain.IsReentrant(grainFullName));
grainFullName = typeof(NonRentrantGrain).FullName;
Assert.False(await grain.IsReentrant(grainFullName));
grainFullName = typeof(UnorderedNonRentrantGrain).FullName;
Assert.False(await grain.IsReentrant(grainFullName));
}
[Fact, TestCategory("Functional"), TestCategory("Tasks"), TestCategory("Reentrancy")]
public void Reentrancy_Deadlock_1()
{
List<Task> done = new List<Task>();
var grain1 = this.fixture.GrainFactory.GetGrain<IReentrantSelfManagedGrain>(1);
grain1.SetDestination(2).Wait();
done.Add(grain1.Ping(15));
var grain2 = this.fixture.GrainFactory.GetGrain<IReentrantSelfManagedGrain>(2);
grain2.SetDestination(1).Wait();
done.Add(grain2.Ping(15));
Task.WhenAll(done).Wait();
this.fixture.Logger.Info("ReentrancyTest_Deadlock_1 OK - no deadlock.");
}
// TODO: [Fact, TestCategory("Functional"), TestCategory("Tasks"), TestCategory("Reentrancy")]
[Fact(Skip = "Ignore"), TestCategory("Failures"), TestCategory("Tasks"), TestCategory("Reentrancy")]
public void Reentrancy_Deadlock_2()
{
List<Task> done = new List<Task>();
var grain1 = this.fixture.GrainFactory.GetGrain<INonReentrantSelfManagedGrain>(1);
grain1.SetDestination(2).Wait();
var grain2 = this.fixture.GrainFactory.GetGrain<INonReentrantSelfManagedGrain>(2);
grain2.SetDestination(1).Wait();
this.fixture.Logger.Info("ReentrancyTest_Deadlock_2 is about to call grain1.Ping()");
done.Add(grain1.Ping(15));
this.fixture.Logger.Info("ReentrancyTest_Deadlock_2 is about to call grain2.Ping()");
done.Add(grain2.Ping(15));
Task.WhenAll(done).Wait();
this.fixture.Logger.Info("ReentrancyTest_Deadlock_2 OK - no deadlock.");
}
[Fact, TestCategory("Failures"), TestCategory("Tasks"), TestCategory("Reentrancy")]
private async Task NonReentrantFanOut()
{
var grain = fixture.GrainFactory.GetGrain<ILongRunningTaskGrain<int>>(Guid.NewGuid());
var target = fixture.GrainFactory.GetGrain<ILongRunningTaskGrain<int>>(Guid.NewGuid());
await grain.CallOtherLongRunningTask(target, 2, TimeSpan.FromSeconds(1));
await Assert.ThrowsAsync<TimeoutException>(
() => target.FanOutOtherLongRunningTask(grain, 2, TimeSpan.FromSeconds(10), 5));
}
[Fact, TestCategory("Functional"), TestCategory("Tasks"), TestCategory("Reentrancy")]
public async Task FanOut_Task_Reentrant()
{
await Do_FanOut_Task_Join(0, false, false);
}
[Fact, TestCategory("Functional"), TestCategory("Tasks"), TestCategory("Reentrancy")]
public async Task FanOut_Task_NonReentrant()
{
await Do_FanOut_Task_Join(0, true, false);
}
[Fact, TestCategory("Functional"), TestCategory("Tasks"), TestCategory("Reentrancy")]
public async Task FanOut_Task_Reentrant_Chain()
{
await Do_FanOut_Task_Join(0, false, true);
}
// TODO: [Fact, TestCategory("BVT"), TestCategory("Tasks"), TestCategory("Reentrancy")]
[Fact(Skip ="Ignore"), TestCategory("Failures"), TestCategory("Tasks"), TestCategory("Reentrancy")]
public async Task FanOut_Task_NonReentrant_Chain()
{
await Do_FanOut_Task_Join(0, true, true);
}
[Fact, TestCategory("Functional"), TestCategory("Tasks"), TestCategory("Reentrancy")]
public async Task FanOut_AC_Reentrant()
{
await Do_FanOut_AC_Join(0, false, false);
}
[Fact, TestCategory("Functional"), TestCategory("Tasks"), TestCategory("Reentrancy")]
public async Task FanOut_AC_NonReentrant()
{
await Do_FanOut_AC_Join(0, true, false);
}
[Fact, TestCategory("Functional"), TestCategory("Tasks"), TestCategory("Reentrancy")]
public async Task FanOut_AC_Reentrant_Chain()
{
await Do_FanOut_AC_Join(0, false, true);
}
[TestCategory("MultithreadingFailures")]
// TODO: [TestCategory("Functional")]
[Fact(Skip ="Ignore"), TestCategory("Tasks"), TestCategory("Reentrancy")]
public async Task FanOut_AC_NonReentrant_Chain()
{
await Do_FanOut_AC_Join(0, true, true);
}
[Fact, TestCategory("Stress"), TestCategory("Functional"), TestCategory("Tasks"), TestCategory("Reentrancy")]
public void FanOut_Task_Stress_Reentrant()
{
const int numLoops = 5;
const int blockSize = 10;
TimeSpan timeout = TimeSpan.FromSeconds(40);
Do_FanOut_Stress(numLoops, blockSize, timeout, false, false);
}
[Fact, TestCategory("Stress"), TestCategory("Functional"), TestCategory("Tasks"), TestCategory("Reentrancy")]
public void FanOut_Task_Stress_NonReentrant()
{
const int numLoops = 5;
const int blockSize = 10;
TimeSpan timeout = TimeSpan.FromSeconds(40);
Do_FanOut_Stress(numLoops, blockSize, timeout, true, false);
}
[Fact, TestCategory("Stress"), TestCategory("Functional"), TestCategory("Tasks"), TestCategory("Reentrancy")]
public void FanOut_AC_Stress_Reentrant()
{
const int numLoops = 5;
const int blockSize = 10;
TimeSpan timeout = TimeSpan.FromSeconds(40);
Do_FanOut_Stress(numLoops, blockSize, timeout, false, true);
}
[Fact, TestCategory("Stress"), TestCategory("Functional"), TestCategory("Tasks"), TestCategory("Reentrancy")]
public void FanOut_AC_Stress_NonReentrant()
{
const int numLoops = 5;
const int blockSize = 10;
TimeSpan timeout = TimeSpan.FromSeconds(40);
Do_FanOut_Stress(numLoops, blockSize, timeout, true, true);
}
// ---------- Utility methods ----------
private async Task Do_FanOut_Task_Join(int offset, bool doNonReentrant, bool doCallChain)
{
const int num = 10;
int id = random.Next();
if (doNonReentrant)
{
IFanOutGrain grain = this.fixture.GrainFactory.GetGrain<IFanOutGrain>(id);
if (doCallChain)
{
await grain.FanOutNonReentrant_Chain(offset*num, num);
}
else
{
await grain.FanOutNonReentrant(offset * num, num);
}
}
else
{
IFanOutGrain grain = this.fixture.GrainFactory.GetGrain<IFanOutGrain>(id);
if (doCallChain)
{
await grain.FanOutReentrant_Chain(offset*num, num);
}
else
{
await grain.FanOutReentrant(offset * num, num);
}
}
}
private async Task Do_FanOut_AC_Join(int offset, bool doNonReentrant, bool doCallChain)
{
const int num = 10;
int id = random.Next();
if (doNonReentrant)
{
IFanOutACGrain grain = this.fixture.GrainFactory.GetGrain<IFanOutACGrain>(id);
if (doCallChain)
{
await grain.FanOutACNonReentrant_Chain(offset * num, num);
}
else
{
await grain.FanOutACNonReentrant(offset * num, num);
}
}
else
{
IFanOutACGrain grain = this.fixture.GrainFactory.GetGrain<IFanOutACGrain>(id);
if (doCallChain)
{
await grain.FanOutACReentrant_Chain(offset * num, num);
}
else
{
await grain.FanOutACReentrant(offset * num, num);
}
}
}
private readonly TimeSpan MaxStressExecutionTime = TimeSpan.FromMinutes(2);
private void Do_FanOut_Stress(int numLoops, int blockSize, TimeSpan timeout,
bool doNonReentrant, bool doAC)
{
Stopwatch totalTime = Stopwatch.StartNew();
List<Task> promises = new List<Task>();
for (int i = 0; i < numLoops; i++)
{
output.WriteLine("Start loop {0}", i);
Stopwatch loopClock = Stopwatch.StartNew();
for (int j = 0; j < blockSize; j++)
{
int offset = j;
output.WriteLine("Start inner loop {0}", j);
Stopwatch innerClock = Stopwatch.StartNew();
Task promise = Task.Run(() =>
{
return doAC ? Do_FanOut_AC_Join(offset, doNonReentrant, false)
: Do_FanOut_Task_Join(offset, doNonReentrant, false);
});
promises.Add(promise);
output.WriteLine("Inner loop {0} - Created Tasks. Elapsed={1}", j, innerClock.Elapsed);
bool ok = Task.WhenAll(promises).Wait(timeout);
if (!ok) throw new TimeoutException();
output.WriteLine("Inner loop {0} - Finished Join. Elapsed={1}", j, innerClock.Elapsed);
promises.Clear();
}
output.WriteLine("End loop {0} Elapsed={1}", i, loopClock.Elapsed);
}
TimeSpan elapsed = totalTime.Elapsed;
Assert.True(elapsed < MaxStressExecutionTime, $"Stress test execution took too long: {elapsed}");
}
}
}
| |
/*
* 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 System;
using System.Threading;
namespace Apache.Geode.Client.UnitTests
{
using NUnit.Framework;
using Apache.Geode.DUnitFramework;
using Apache.Geode.Client.Tests;
using Apache.Geode.Client;
using GIRegion = Apache.Geode.Client.IRegion<int, object>;
using System.Collections.Generic;
public class CallbackListener : CacheListenerAdapter<int, object>
{
int m_creates;
int m_updates;
int m_invalidates;
int m_destroys;
int m_regionInvalidate;
int m_regionDestroy;
int m_regionClear;
object m_callbackArg;
#region Getters
public int Creates
{
get { return m_creates; }
}
public int Updates
{
get { return m_updates; }
}
public int Invalidates
{
get { return m_invalidates; }
}
public int Destroys
{
get { return m_destroys; }
}
public int RegionInvalidates
{
get { return m_regionInvalidate; }
}
public int RegionDestroys
{
get { return m_regionDestroy; }
}
public int RegionClear
{
get { return m_regionClear; }
}
public object CallbackArg
{
get { return m_callbackArg; }
}
#endregion
public void SetCallbackArg(object callbackArg)
{
m_callbackArg = callbackArg;
}
private void check(object eventCallback, ref int updateCount)
{
Log.Fine("check..");
if (eventCallback != null)
{
string callbackArg = eventCallback as string;
if (callbackArg != null)
{
string cs = m_callbackArg as string;
if (cs != null)
{
if (callbackArg == cs)
{
Log.Fine("value matched");
updateCount++;
}
else
Log.Fine("value matched NOT");
}
}
else
{
Log.Fine("Callbackarg is not cacheable string");
Portfolio pfCallback = eventCallback as Portfolio;
if (pfCallback != null)
{
Portfolio pf = m_callbackArg as Portfolio;
if (pf != null)
{
if (pf.Pkid == pfCallback.Pkid && pfCallback.ArrayNull == null
&& pfCallback.ArrayZeroSize != null && pfCallback.ArrayZeroSize.Length == 0)
{
Log.Fine("value matched");
updateCount++;
}
}
}
}
}
}
private void checkCallbackArg(EntryEvent<int, object> entryEvent, ref int updateCount)
{
check(entryEvent.CallbackArgument, ref updateCount);
}
private void checkCallbackArg(RegionEvent<int, object> regionEvent, ref int updateCount)
{
check(regionEvent.CallbackArgument, ref updateCount);
}
#region CacheListener Members
public override void AfterCreate(EntryEvent<int, object> ev)
{
checkCallbackArg(ev, ref m_creates);
}
public override void AfterUpdate(EntryEvent<int, object> ev)
{
checkCallbackArg(ev, ref m_updates);
}
public override void AfterInvalidate(EntryEvent<int, object> ev)
{
checkCallbackArg(ev, ref m_invalidates);
}
public override void AfterDestroy(EntryEvent<int, object> ev)
{
checkCallbackArg(ev, ref m_destroys);
}
public override void AfterRegionInvalidate(RegionEvent<int, object> rev)
{
checkCallbackArg(rev, ref m_regionInvalidate);
}
public override void AfterRegionDestroy(RegionEvent<int, object> rev)
{
checkCallbackArg(rev, ref m_regionDestroy);
}
public override void AfterRegionClear(RegionEvent<int, object> rev)
{
checkCallbackArg(rev, ref m_regionClear);
}
#endregion
}
[TestFixture]
[Category("generics")]
public class ThinClientCallbackArg : ThinClientRegionSteps
{
private TallyWriter<int, object> m_writer;
private TallyListener<int, object> m_listener;
private CallbackListener m_callbackListener;
RegionOperation o_region;
private UnitProcess m_client1, m_client2;
int key0 = 12;
object m_callbackarg = "Gemstone's Callback";
protected override ClientBase[] GetClients()
{
m_client1 = new UnitProcess();
m_client2 = new UnitProcess();
return new ClientBase[] { m_client1, m_client2 };
}
public void CreateRegion(string locators,
bool caching, bool listener, bool writer)
{
if (listener)
{
m_listener = new TallyListener<int, object>();
}
else
{
m_listener = null;
}
GIRegion region = null;
region = CacheHelper.CreateTCRegion_Pool<int, object>(RegionName, true, caching,
m_listener, locators, "__TESTPOOL1_", true);
if (listener)
m_listener.SetCallBackArg(key0);
if (writer)
{
m_writer = new TallyWriter<int, object>();
}
else
{
m_writer = null;
}
if (writer)
{
AttributesMutator<int, object> at = region.AttributesMutator;
at.SetCacheWriter(m_writer);
m_writer.SetCallBackArg(key0);
}
}
public void CreateRegion2(string locators,
bool caching, bool listener, bool writer)
{
CallbackListener callbackLis = null;
if (listener)
{
m_callbackListener = new CallbackListener();
m_callbackListener.SetCallbackArg(m_callbackarg);
callbackLis = m_callbackListener;
}
else
{
m_listener = null;
}
GIRegion region = null;
region = CacheHelper.CreateTCRegion_Pool<int, object>(RegionName, true, caching,
callbackLis, locators, "__TESTPOOL1_", true);
CacheHelper.DCache.TypeRegistry.RegisterTypeGeneric(Portfolio.CreateDeserializable);
CacheHelper.DCache.TypeRegistry.RegisterTypeGeneric(Position.CreateDeserializable);
}
public void ValidateLocalListenerWriterData()
{
Thread.Sleep(2000);
Assert.AreEqual(true, m_writer.IsWriterInvoked, "Writer should be invoked");
Assert.AreEqual(true, m_listener.IsListenerInvoked, "Listener should be invoked");
Assert.AreEqual(true, m_writer.IsCallBackArgCalled, "Writer CallbackArg should be invoked");
Assert.AreEqual(true, m_listener.IsCallBackArgCalled, "Listener CallbackArg should be invoked");
m_listener.ShowTallies();
m_writer.ShowTallies();
}
public void ValidateEvents()
{
Assert.AreEqual(15, m_writer.Creates, "Should be 10 creates");
Assert.AreEqual(15, m_listener.Creates, "Should be 10 creates");
Assert.AreEqual(15, m_writer.Updates, "Should be 5 updates");
Assert.AreEqual(15, m_listener.Updates, "Should be 5 updates");
Assert.AreEqual(0, m_writer.Invalidates, "Should be 0 invalidates");
Assert.AreEqual(5, m_listener.Invalidates, "Should be 5 invalidates");
Assert.AreEqual(10, m_writer.Destroys, "Should be 10 destroys"); // 5 destroys + 5 removes
Assert.AreEqual(10, m_listener.Destroys, "Should be 10 destroys"); // 5 destroys + 5 removes
}
public void CallOp()
{
o_region = new RegionOperation(RegionName);
o_region.PutOp(5, key0);
Thread.Sleep(1000); // let the events reach at other end.
o_region.PutOp(5, key0);
Thread.Sleep(1000);
o_region.InvalidateOp(5, key0);
Thread.Sleep(1000);
o_region.DestroyOp(5, key0);
Thread.Sleep(1000); // let the events reach at other end.
o_region.PutOp(5, key0);
Thread.Sleep(1000);
o_region.RemoveOp(5, key0);
Thread.Sleep(1000);
}
void RegisterPdxType8()
{
CacheHelper.DCache.TypeRegistry.RegisterPdxType(PdxTests.PdxTypes8.CreateDeserializable);
}
void runCallbackArgTest()
{
CacheHelper.SetupJavaServers(true, "cacheserver_notify_subscription.xml");
CacheHelper.StartJavaLocator(1, "GFELOC");
Util.Log("Locator started");
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1);
Util.Log("Cacheserver 1 started.");
Util.Log("Creating region in client1, no-ack, cache-enabled, with listener and writer");
m_client1.Call(CreateRegion, CacheHelper.Locators,
true, true, true);
m_client1.Call(RegisterAllKeys, new string[] { RegionName });
Util.Log("Creating region in client2 , no-ack, cache-enabled, with listener and writer");
m_client2.Call(CreateRegion, CacheHelper.Locators,
true, true, true);
m_client2.Call(RegisterAllKeys, new string[] { RegionName });
m_client2.Call(RegisterPdxType8);
m_client1.Call(CallOp);
m_client1.Call(ValidateLocalListenerWriterData);
m_client1.Call(ValidateEvents);
m_client1.Call(CacheHelper.Close);
m_client2.Call(CacheHelper.Close);
CacheHelper.StopJavaServer(1);
Util.Log("Cacheserver 1 stopped.");
CacheHelper.StopJavaLocator(1);
Util.Log("Locator stopped");
CacheHelper.ClearLocators();
CacheHelper.ClearEndpoints();
}
private bool m_isSet = false;
public void SetCallbackArg()
{
if (!m_isSet)
{
m_isSet = true;
m_callbackarg = new Portfolio(1, 1);
}
}
public void TestCreatesAndUpdates()
{
o_region = new RegionOperation(RegionName);
o_region.Region.Add("Key-1", "Val-1", m_callbackarg);
o_region.Region.Put("Key-1", "NewVal-1", m_callbackarg);
Thread.Sleep(10000);
}
public void TestInvalidates()
{
o_region = new RegionOperation(RegionName);
o_region.Region.GetLocalView().Add(1234, 1234, m_callbackarg);
o_region.Region.GetLocalView().Add(12345, 12345, m_callbackarg);
o_region.Region.GetLocalView().Add(12346, 12346, m_callbackarg);
o_region.Region.GetLocalView().Put(1234, "Val-1", m_callbackarg);
o_region.Region.GetLocalView().Invalidate(1234, m_callbackarg);
Assert.AreEqual(o_region.Region.GetLocalView().Remove(12345, 12345, m_callbackarg), true, "Result of remove should be true, as this value exists locally.");
Assert.AreEqual(o_region.Region.GetLocalView().ContainsKey(12345), false, "containsKey should be false");
Assert.AreEqual(o_region.Region.GetLocalView().Remove(12346, m_callbackarg), true, "Result of remove should be true, as this value exists locally.");
Assert.AreEqual(o_region.Region.GetLocalView().ContainsKey(12346), false, "containsKey should be false");
o_region.Region.Invalidate("Key-1", m_callbackarg);
o_region.Region.InvalidateRegion(m_callbackarg);
}
public void TestDestroy()
{
o_region = new RegionOperation(RegionName);
o_region.Region.Remove("Key-1", m_callbackarg);
//o_region.Region.DestroyRegion(m_callbackarg);
}
public void TestRemove()
{
o_region = new RegionOperation(RegionName);
o_region.Region.Remove("Key-1", "NewVal-1", m_callbackarg);
o_region.Region.DestroyRegion(m_callbackarg);
}
public void TestlocalClear()
{
o_region = new RegionOperation(RegionName);
o_region.Region.GetLocalView().Clear(m_callbackarg);
}
public void TestValidate()
{
Thread.Sleep(10000);
Assert.AreEqual(5, m_callbackListener.Creates, "Should be 5 creates");
Assert.AreEqual(3, m_callbackListener.Updates, "Should be 3 update");
Assert.AreEqual(2, m_callbackListener.Invalidates, "Should be 2 invalidate");
Assert.AreEqual(4, m_callbackListener.Destroys, "Should be 4 destroy");
Assert.AreEqual(1, m_callbackListener.RegionInvalidates, "Should be 1 region invalidates");
Assert.AreEqual(1, m_callbackListener.RegionDestroys, "Should be 1 regiondestroy");
Assert.AreEqual(1, m_callbackListener.RegionClear, "Should be 1 RegionClear");
}
void runCallbackArgTest2(int callbackArgChange)
{
if (callbackArgChange == 1)
{
//change now custom type
m_callbackarg = new Portfolio(1, 1);
m_client1.Call(SetCallbackArg);
m_client2.Call(SetCallbackArg);
}
m_callbackListener = new CallbackListener();
m_callbackListener.SetCallbackArg(m_callbackarg);
CacheHelper.SetupJavaServers(true, "cacheserver_notify_subscription5N.xml");
CacheHelper.StartJavaLocator(1, "GFELOC");
Util.Log("Locator started");
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1);
Util.Log("Cacheserver 1 started.");
Util.Log("Creating region in client1, no-ack, cache-enabled, with listener and writer");
m_client1.Call(CreateRegion2, CacheHelper.Locators,
true, true, false);
m_client1.Call(RegisterAllKeys, new string[] { RegionName });
Util.Log("Creating region in client2 , no-ack, cache-enabled, with listener and writer");
m_client2.Call(CreateRegion2, CacheHelper.Locators,
true, false, false);
m_client2.Call(TestCreatesAndUpdates);
m_client1.Call(TestInvalidates);
m_client2.Call(TestDestroy);
m_client2.Call(TestCreatesAndUpdates);
m_client1.Call(TestlocalClear);
m_client2.Call(TestRemove);
m_client1.Call(TestValidate);
m_client1.Call(CacheHelper.Close);
m_client2.Call(CacheHelper.Close);
CacheHelper.StopJavaServer(1);
Util.Log("Cacheserver 1 stopped.");
CacheHelper.StopJavaLocator(1);
Util.Log("Locator stopped");
CacheHelper.ClearLocators();
CacheHelper.ClearEndpoints();
}
private bool isRegistered = false;
public void registerDefaultCacheableType()
{
if (!isRegistered)
{
CacheHelper.DCache.TypeRegistry.RegisterTypeGeneric(DefaultType.CreateDeserializable);
isRegistered = true;
}
}
public void CallOp2()
{
o_region = new RegionOperation(RegionName);
DefaultType dc = new DefaultType(true);
o_region.Region.Put("key-1", dc, null);
Thread.Sleep(1000); // let the events reach at other end.
}
public void ValidateData()
{
o_region = new RegionOperation(RegionName);
DefaultType dc = (DefaultType)o_region.Region.Get("key-1", null);
Assert.AreEqual(dc.CBool, true, "bool is not equal");
Assert.AreEqual(dc.CInt, 1000, "int is not equal");
int[] cia = dc.CIntArray;
Assert.IsNotNull(cia, "Int array is null");
Assert.AreEqual(3, cia.Length, "Int array are not three");
string[] csa = dc.CStringArray;
Assert.IsNotNull(csa, "String array is null");
Assert.AreEqual(2, csa.Length, "String array length is not two");
Assert.AreEqual(dc.CFileName, "geode.txt", "Cacheable filename is not equal");
/*
Assert.IsNotNull(dc.CHashSet, "hashset is null");
Assert.AreEqual(2, dc.CHashSet.Count, "hashset size is not two");
* */
Assert.IsNotNull(dc.CHashMap, "hashmap is null");
Assert.AreEqual(1, dc.CHashMap.Count, "hashmap size is not one");
//Assert.IsNotNull(dc.CDate, "Date is null");
Assert.IsNotNull(dc.CVector);
Assert.AreEqual(2, dc.CVector.Count, "Vector size is not two");
//Assert.IsNotNull(dc.CObject);
//Assert.AreEqual("key", ((CustomSerializableObject)dc.CObject).key, "Object key is not same");
//Assert.AreEqual("value", ((CustomSerializableObject)dc.CObject).value, "Object value is not same");
}
void runCallbackArgTest3()
{
CacheHelper.SetupJavaServers(true, "cacheserver_notify_subscription6.xml");
CacheHelper.StartJavaLocator(1, "GFELOC");
Util.Log("Locator started");
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1);
Util.Log("Cacheserver 1 started.");
Util.Log("Creating region in client1, no-ack, cache-enabled, with listener and writer");
m_client1.Call(CreateRegion, CacheHelper.Locators,
true, false, false);
// m_client1.Call(RegisterAllKeys, new string[] { RegionName });
Util.Log("Creating region in client2 , no-ack, cache-enabled, with listener and writer");
m_client2.Call(CreateRegion, CacheHelper.Locators,
true, false, false);
m_client1.Call(registerDefaultCacheableType);
m_client2.Call(registerDefaultCacheableType);
m_client2.Call(RegisterAllKeys, new string[] { RegionName });
m_client1.Call(CallOp2);
m_client2.Call(ValidateData);
m_client1.Call(CacheHelper.Close);
m_client2.Call(CacheHelper.Close);
CacheHelper.StopJavaServer(1);
Util.Log("Cacheserver 1 stopped.");
CacheHelper.StopJavaLocator(1);
Util.Log("Locator stopped");
CacheHelper.ClearLocators();
CacheHelper.ClearEndpoints();
}
public void TestRemoveAll()
{
o_region = new RegionOperation(RegionName);
ICollection<object> keys = new LinkedList<object>();
for(int i =0; i< 10; i++)
{
o_region.Region["Key-"+i] = "Value-"+i;
keys.Add("Key-" + i);
}
o_region.Region.RemoveAll(keys, m_callbackarg);
}
public void TestPutAll()
{
o_region = new RegionOperation(RegionName);
Dictionary<Object, Object> entryMap = new Dictionary<Object, Object>();
for (Int32 item = 0; item < 10; item++)
{
int K = item;
string value = item.ToString();
entryMap.Add(K, value);
}
o_region.Region.PutAll(entryMap, TimeSpan.FromSeconds(15), m_callbackarg);
}
public void TestGetAll()
{
o_region = new RegionOperation(RegionName);
List<Object> keys = new List<Object>();
for (int item = 0; item < 10; item++)
{
Object K = item;
keys.Add(K);
}
Dictionary<Object, Object> values = new Dictionary<Object, Object>();
o_region.Region.GetAll(keys.ToArray(), values, null, true, m_callbackarg);
Dictionary<Object, Object>.Enumerator enumerator = values.GetEnumerator();
while (enumerator.MoveNext())
{
Util.Log("Values after getAll with CallBack Key = {0} Value = {1} ", enumerator.Current.Key.ToString(), enumerator.Current.Value.ToString());
}
}
public void TestValidateRemoveAllCallback()
{
Thread.Sleep(10000);
Assert.AreEqual(10, m_callbackListener.Destroys, "Should be 10 destroy");
}
public void TestValidatePutAllCallback()
{
Thread.Sleep(10000);
Assert.AreEqual(10, m_callbackListener.Creates, "Should be 10 creates");
Assert.AreEqual("Gemstone's Callback", m_callbackListener.CallbackArg, "CallBackArg for putAll should be same");
}
void runPutAllCallbackArgTest()
{
m_callbackListener = new CallbackListener();
m_callbackListener.SetCallbackArg(m_callbackarg);
CacheHelper.SetupJavaServers(true, "cacheserver_notify_subscription5N.xml");
CacheHelper.StartJavaLocator(1, "GFELOC");
Util.Log("Locator started");
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1);
Util.Log("Cacheserver 1 started.");
Util.Log("Creating region in client1, no-ack, cache-enabled, with listener and writer");
m_client1.Call(CreateRegion2, CacheHelper.Locators,
true, true, false);
m_client1.Call(RegisterAllKeys, new string[] { RegionName });
Util.Log("RegisterAllKeys completed..");
Util.Log("Creating region in client2 , no-ack, cache-enabled, with listener and writer");
m_client2.Call(CreateRegion2, CacheHelper.Locators,
true, false, false);
Util.Log("CreateRegion2 completed..");
m_client2.Call(TestPutAll);
Util.Log("TestPutAll completed..");
m_client1.Call(TestValidatePutAllCallback);
Util.Log("TestValidatePutAllCallback completed..");
m_client2.Call(TestGetAll);
Util.Log("TestGetAll completed..");
m_client1.Call(CacheHelper.Close);
m_client2.Call(CacheHelper.Close);
CacheHelper.StopJavaServer(1);
Util.Log("Cacheserver 1 stopped.");
CacheHelper.StopJavaLocator(1);
Util.Log("Locator stopped");
CacheHelper.ClearLocators();
CacheHelper.ClearEndpoints();
}
void runRemoveAllCallbackArgTest()
{
m_callbackListener = new CallbackListener();
m_callbackListener.SetCallbackArg(m_callbackarg);
CacheHelper.SetupJavaServers(true, "cacheserver_notify_subscription5N.xml");
CacheHelper.StartJavaLocator(1, "GFELOC");
Util.Log("Locator started");
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1);
Util.Log("Cacheserver 1 started.");
Util.Log("Creating region in client1, no-ack, cache-enabled, with listener and writer");
m_client1.Call(CreateRegion2, CacheHelper.Locators,
true, true, false);
m_client1.Call(RegisterAllKeys, new string[] { RegionName });
Util.Log("RegisterAllKeys completed..");
Util.Log("Creating region in client2 , no-ack, cache-enabled, with listener and writer");
m_client2.Call(CreateRegion2,CacheHelper.Locators,
true, false, false);
Util.Log("CreateRegion2 completed..");
m_client2.Call(TestRemoveAll);
Util.Log("TestRemoveAll completed..");
m_client1.Call(TestValidateRemoveAllCallback);
Util.Log("TestValidateRemoveAllCallback completed..");
m_client1.Call(CacheHelper.Close);
m_client2.Call(CacheHelper.Close);
CacheHelper.StopJavaServer(1);
Util.Log("Cacheserver 1 stopped.");
CacheHelper.StopJavaLocator(1);
Util.Log("Locator stopped");
CacheHelper.ClearLocators();
CacheHelper.ClearEndpoints();
}
[TearDown]
public override void EndTest()
{
base.EndTest();
}
[Test]
public void ThinClientCallbackArgTest()
{
runCallbackArgTest();
}
[Test]
public void ThinClientCallbackArgTest2()
{
for (int i = 0; i < 2; i++)
{
runCallbackArgTest2(i);
}
}
[Test]
public void ThinClientCallbackArgTest3()
{
runCallbackArgTest3();
}
[Test]
public void RemoveAllCallbackArgTest()
{
runRemoveAllCallbackArgTest();
}
[Test]
public void PutAllCallbackArgTest()
{
runPutAllCallbackArgTest();
}
}
}
| |
// Adaptive Quality|Scripts|0240
// Adapted from The Lab Renderer's ValveCamera.cs, available at
// https://github.com/ValveSoftware/the_lab_renderer/blob/ae64c48a8ccbe5406aba1e39b160d4f2f7156c2c/Assets/TheLabRenderer/Scripts/ValveCamera.cs
// For The Lab Renderer's license see THIRD_PARTY_NOTICES.
// **Only Compatible With Unity 5.4 and above**
#if (UNITY_5_4_OR_NEWER)
namespace VRTK
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using UnityEngine;
using UnityEngine.VR;
/// <summary>
/// Adaptive Quality dynamically changes rendering settings to maintain VR framerate while maximizing GPU utilization.
/// </summary>
/// <remarks>
/// > **Only Compatible With Unity 5.4 and above**
///
/// The Adaptive Quality script is attached to the `[CameraRig]` game object.
///
/// There are two goals:
/// <list type="bullet">
/// <item> <description>Reduce the chances of dropping frames and reprojecting</description> </item>
/// <item> <description>Increase quality when there are idle GPU cycles</description> </item>
/// </list>
/// <para />
/// This script currently changes the following to reach these goals:
/// <list type="bullet">
/// <item> <description>Rendering resolution and viewport size (aka Dynamic Resolution)</description> </item>
/// </list>
/// <para />
/// In the future it could be changed to also change the following:
/// <list type="bullet">
/// <item> <description>MSAA level</description> </item>
/// <item> <description>Fixed Foveated Rendering</description> </item>
/// <item> <description>Radial Density Masking</description> </item>
/// <item> <description>(Non-fixed) Foveated Rendering (once HMDs support eye tracking)</description> </item>
/// </list>
/// <para />
/// Some shaders, especially Image Effects, need to be modified to work with the changed render scale. To fix them
/// pass `1.0f / VRSettings.renderViewportScale` into the shader and scale all incoming UV values with it in the vertex
/// program. Do this by using `Material.SetFloat` to set the value in the script that configures the shader.
/// <para />
/// In more detail:
/// <list type="bullet">
/// <item> <description>In the `.shader` file: Add a new runtime-set property value `float _InverseOfRenderViewportScale`
/// and add `vertexInput.texcoord *= _InverseOfRenderViewportScale` to the start of the vertex program</description> </item>
/// <item> <description>In the `.cs` file: Before using the material (eg. `Graphics.Blit`) add
/// `material.SetFloat("_InverseOfRenderViewportScale", 1.0f / VRSettings.renderViewportScale)`</description> </item>
/// </list>
/// </remarks>
/// <example>
/// `VRTK/Examples/039_CameraRig_AdaptiveQuality` displays the frames per second in the centre of the headset view.
/// The debug visualization of this script is displayed near the top edge of the headset view.
/// Pressing the trigger generates a new sphere and pressing the touchpad generates ten new spheres.
/// Eventually when lots of spheres are present the FPS will drop and demonstrate the script.
/// </example>
public sealed class VRTK_AdaptiveQuality : MonoBehaviour
{
#region Public fields
[Tooltip("Toggles whether to show the debug overlay.\n\n"
+ "Each square represents a different level on the quality scale. Levels increase from left to right,"
+ " the first green box that is lit above represents the recommended render target resolution provided by the"
+ " current `VRDevice`, the box that is lit below in cyan represents the current resolution and the filled box"
+ " represents the current viewport scale. The yellow boxes represent resolutions below the recommended render target resolution.\n"
+ "The currently lit box becomes red whenever the user is likely seeing reprojection in the HMD since the"
+ " application isn't maintaining VR framerate. If lit, the box all the way on the left is almost always lit"
+ " red because it represents the lowest render scale with reprojection on.")]
public bool drawDebugVisualization;
[Tooltip("Toggles whether to allow keyboard shortcuts to control this script.\n\n"
+ "* The supported shortcuts are:\n"
+ " * `Shift+F1`: Toggle debug visualization on/off\n"
+ " * `Shift+F2`: Toggle usage of override render scale on/off\n"
+ " * `Shift+F3`: Decrease override render scale level\n"
+ " * `Shift+F4`: Increase override render scale level")]
public bool allowKeyboardShortcuts = true;
[Tooltip("Toggles whether to allow command line arguments to control this script at startup of the standalone build.\n\n"
+ "* The supported command line arguments all begin with '-' and are:\n"
+ " * `-noaq`: Disable adaptive quality\n"
+ " * `-aqminscale X`: Set minimum render scale to X\n"
+ " * `-aqmaxscale X`: Set maximum render scale to X\n"
+ " * `-aqmaxres X`: Set maximum render target dimension to X\n"
+ " * `-aqfillratestep X`: Set render scale fill rate step size in percent to X (X from 1 to 100)\n"
+ " * `-aqoverride X`: Set override render scale level to X\n"
+ " * `-vrdebug`: Enable debug visualization\n"
+ " * `-msaa X`: Set MSAA level to X")]
public bool allowCommandLineArguments = true;
[Tooltip("The MSAA level to use.")]
[Header("Quality")]
[Range(0, 8)]
public int msaaLevel = 4;
[Tooltip("Toggles whether the render viewport scale is dynamically adjusted to maintain VR framerate.\n\n"
+ "If unchecked, the renderer will render at the recommended resolution provided by the current `VRDevice`.")]
public bool scaleRenderViewport = true;
[Tooltip("The minimum allowed render scale.")]
[Range(0.01f, 5)]
public float minimumRenderScale = 0.8f;
[Tooltip("The maximum allowed render scale.")]
public float maximumRenderScale = 1.4f;
[Tooltip("The maximum allowed render target dimension.\n\n"
+ "This puts an upper limit on the size of the render target regardless of the maximum render scale.")]
public int maximumRenderTargetDimension = 4096;
[Tooltip("The fill rate step size in percent by which the render scale levels will be calculated.")]
[Range(1, 100)]
public int renderScaleFillRateStepSizeInPercent = 15;
[Tooltip("Toggles whether the render target resolution is dynamically adjusted to maintain VR framerate.\n\n"
+ "If unchecked, the renderer will use the maximum target resolution specified by `maximumRenderScale`.")]
public bool scaleRenderTargetResolution = false;
[Tooltip("Toggles whether to override the used render viewport scale level.")]
[Header("Override")]
[NonSerialized]
public bool overrideRenderViewportScale;
[Tooltip("The render viewport scale level to override the current one with.")]
[NonSerialized]
public int overrideRenderViewportScaleLevel;
#endregion
#region Public readonly fields & properties
/// <summary>
/// All the calculated render scales.
/// </summary>
/// <remarks>
/// The elements of this collection are to be interpreted as modifiers to the recommended render target
/// resolution provided by the current `VRDevice`.
/// </remarks>
public readonly ReadOnlyCollection<float> renderScales;
/// <summary>
/// The current render scale.
/// </summary>
/// <remarks>
/// A render scale of `1.0` represents the recommended render target resolution provided by the current `VRDevice`.
/// </remarks>
public static float CurrentRenderScale
{
get { return VRSettings.renderScale * VRSettings.renderViewportScale; }
}
/// <summary>
/// The recommended render target resolution provided by the current `VRDevice`.
/// </summary>
public Vector2 defaultRenderTargetResolution
{
get { return RenderTargetResolutionForRenderScale(allRenderScales[defaultRenderViewportScaleLevel]); }
}
/// <summary>
/// The current render target resolution.
/// </summary>
public Vector2 currentRenderTargetResolution
{
get { return RenderTargetResolutionForRenderScale(CurrentRenderScale); }
}
#endregion
#region Private fields
/// <summary>
/// The frame duration in milliseconds to fallback to if the current `VRDevice` specifies no refresh rate.
/// </summary>
private const float DefaultFrameDurationInMilliseconds = 1000f / 90f;
private readonly AdaptiveSetting<int> renderViewportScaleSetting = new AdaptiveSetting<int>(0, 30, 10);
private readonly AdaptiveSetting<int> renderScaleSetting = new AdaptiveSetting<int>(0, 180, 90);
private readonly List<float> allRenderScales = new List<float>();
private int defaultRenderViewportScaleLevel;
private float previousMinimumRenderScale;
private float previousMaximumRenderScale;
private float previousRenderScaleFillRateStepSizeInPercent;
private readonly Timing timing = new Timing();
private int lastRenderViewportScaleLevelBelowRenderScaleLevelFrameCount;
private bool interleavedReprojectionEnabled;
private bool hmdDisplayIsOnDesktop;
private float singleFrameDurationInMilliseconds;
private GameObject debugVisualizationQuad;
private Material debugVisualizationQuadMaterial;
#endregion
public VRTK_AdaptiveQuality()
{
renderScales = allRenderScales.AsReadOnly();
}
/// <summary>
/// Calculates and returns the render target resolution for a given render scale.
/// </summary>
/// <param name="renderScale">
/// The render scale to calculate the render target resolution with.
/// </param>
/// <returns>
/// The render target resolution for `renderScale`.
/// </returns>
public static Vector2 RenderTargetResolutionForRenderScale(float renderScale)
{
return new Vector2((int)(VRSettings.eyeTextureWidth / VRSettings.renderScale * renderScale),
(int)(VRSettings.eyeTextureHeight / VRSettings.renderScale * renderScale));
}
/// <summary>
/// Calculates and returns the biggest allowed maximum render scale to be used for `maximumRenderScale`
/// given the current `maximumRenderTargetDimension`.
/// </summary>
/// <returns>
/// The biggest allowed maximum render scale.
/// </returns>
public float BiggestAllowedMaximumRenderScale()
{
if (VRSettings.eyeTextureWidth == 0 || VRSettings.eyeTextureHeight == 0)
{
return maximumRenderScale;
}
float maximumHorizontalRenderScale = maximumRenderTargetDimension * VRSettings.renderScale
/ VRSettings.eyeTextureWidth;
float maximumVerticalRenderScale = maximumRenderTargetDimension * VRSettings.renderScale
/ VRSettings.eyeTextureHeight;
return Mathf.Min(maximumHorizontalRenderScale, maximumVerticalRenderScale);
}
/// <summary>
/// A summary of this script by listing all the calculated render scales with their
/// corresponding render target resolution.
/// </summary>
/// <returns>
/// The summary.
/// </returns>
public override string ToString()
{
var stringBuilder = new StringBuilder("Adaptive Quality\n");
stringBuilder.AppendLine("Render Scale:");
stringBuilder.AppendLine("Level - Resolution - Multiplier");
for (int index = 0; index < allRenderScales.Count; index++)
{
float renderScale = allRenderScales[index];
var renderTargetResolution = RenderTargetResolutionForRenderScale(renderScale);
stringBuilder.AppendFormat(
"{0, 3} {1, 5}x{2, -5} {3, -8}",
index,
(int)renderTargetResolution.x,
(int)renderTargetResolution.y,
renderScale);
if (index == 0)
{
stringBuilder.Append(" (Interleaved reprojection hint)");
}
else if (index == defaultRenderViewportScaleLevel)
{
stringBuilder.Append(" (Default)");
}
if (index == renderViewportScaleSetting.currentValue)
{
stringBuilder.Append(" (Current Viewport)");
}
if (index == renderScaleSetting.currentValue)
{
stringBuilder.Append(" (Current Target Resolution)");
}
if (index != allRenderScales.Count - 1)
{
stringBuilder.AppendLine();
}
}
return stringBuilder.ToString();
}
#region MonoBehaviour methods
private void OnEnable()
{
Camera.onPreCull += OnCameraPreCull;
hmdDisplayIsOnDesktop = VRTK_SDK_Bridge.IsDisplayOnDesktop();
singleFrameDurationInMilliseconds = VRDevice.refreshRate > 0.0f
? 1000.0f / VRDevice.refreshRate
: DefaultFrameDurationInMilliseconds;
HandleCommandLineArguments();
if (!Application.isEditor)
{
OnValidate();
}
CreateOrDestroyDebugVisualization();
}
private void OnDisable()
{
Camera.onPreCull -= OnCameraPreCull;
CreateOrDestroyDebugVisualization();
SetRenderScale(1.0f, 1.0f);
}
private void OnValidate()
{
minimumRenderScale = Mathf.Max(0.01f, minimumRenderScale);
maximumRenderScale = Mathf.Max(minimumRenderScale, maximumRenderScale);
maximumRenderTargetDimension = Mathf.Max(2, maximumRenderTargetDimension);
renderScaleFillRateStepSizeInPercent = Mathf.Max(1, renderScaleFillRateStepSizeInPercent);
msaaLevel = msaaLevel == 1 ? 0 : Mathf.Clamp(Mathf.ClosestPowerOfTwo(msaaLevel), 0, 8);
CreateOrDestroyDebugVisualization();
}
private void Update()
{
HandleKeyPresses();
UpdateRenderScaleLevels();
UpdateDebugVisualization();
timing.SaveCurrentFrameTiming();
}
#if UNITY_5_4_1 || UNITY_5_4_2 || UNITY_5_5_OR_NEWER
private void LateUpdate()
{
UpdateRenderScale();
}
#endif
private void OnCameraPreCull(Camera camera)
{
if (camera.transform != VRTK_SDK_Bridge.GetHeadsetCamera())
{
return;
}
#if !(UNITY_5_4_1 || UNITY_5_4_2 || UNITY_5_5_OR_NEWER)
UpdateRenderScale();
#endif
UpdateMSAALevel();
}
#endregion
private void HandleCommandLineArguments()
{
if (!allowCommandLineArguments)
{
return;
}
var commandLineArguments = Environment.GetCommandLineArgs();
for (int index = 0; index < commandLineArguments.Length; index++)
{
string argument = commandLineArguments[index];
string nextArgument = index + 1 < commandLineArguments.Length ? commandLineArguments[index + 1] : "";
switch (argument)
{
case CommandLineArguments.Disable:
scaleRenderViewport = false;
break;
case CommandLineArguments.MinimumRenderScale:
minimumRenderScale = float.Parse(nextArgument);
break;
case CommandLineArguments.MaximumRenderScale:
maximumRenderScale = float.Parse(nextArgument);
break;
case CommandLineArguments.MaximumRenderTargetDimension:
maximumRenderTargetDimension = int.Parse(nextArgument);
break;
case CommandLineArguments.RenderScaleFillRateStepSizeInPercent:
renderScaleFillRateStepSizeInPercent = int.Parse(nextArgument);
break;
case CommandLineArguments.OverrideRenderScaleLevel:
overrideRenderViewportScale = true;
overrideRenderViewportScaleLevel = int.Parse(nextArgument);
break;
case CommandLineArguments.DrawDebugVisualization:
drawDebugVisualization = true;
CreateOrDestroyDebugVisualization();
break;
case CommandLineArguments.MSAALevel:
msaaLevel = int.Parse(nextArgument);
break;
}
}
}
private void HandleKeyPresses()
{
if (!allowKeyboardShortcuts || !KeyboardShortcuts.Modifiers.Any(Input.GetKey))
{
return;
}
if (Input.GetKeyDown(KeyboardShortcuts.ToggleDrawDebugVisualization))
{
drawDebugVisualization = !drawDebugVisualization;
CreateOrDestroyDebugVisualization();
}
else if (Input.GetKeyDown(KeyboardShortcuts.ToggleOverrideRenderScale))
{
overrideRenderViewportScale = !overrideRenderViewportScale;
}
else if (Input.GetKeyDown(KeyboardShortcuts.DecreaseOverrideRenderScaleLevel))
{
overrideRenderViewportScaleLevel = ClampRenderScaleLevel(overrideRenderViewportScaleLevel - 1);
}
else if (Input.GetKeyDown(KeyboardShortcuts.IncreaseOverrideRenderScaleLevel))
{
overrideRenderViewportScaleLevel = ClampRenderScaleLevel(overrideRenderViewportScaleLevel + 1);
}
}
private void UpdateMSAALevel()
{
if (QualitySettings.antiAliasing != msaaLevel)
{
QualitySettings.antiAliasing = msaaLevel;
}
}
#region Render scale methods
private void UpdateRenderScaleLevels()
{
if (Mathf.Abs(previousMinimumRenderScale - minimumRenderScale) <= float.Epsilon
&& Mathf.Abs(previousMaximumRenderScale - maximumRenderScale) <= float.Epsilon
&& Mathf.Abs(previousRenderScaleFillRateStepSizeInPercent - renderScaleFillRateStepSizeInPercent) <= float.Epsilon)
{
return;
}
previousMinimumRenderScale = minimumRenderScale;
previousMaximumRenderScale = maximumRenderScale;
previousRenderScaleFillRateStepSizeInPercent = renderScaleFillRateStepSizeInPercent;
allRenderScales.Clear();
// Respect maximumRenderTargetDimension
float allowedMaximumRenderScale = BiggestAllowedMaximumRenderScale();
float renderScaleToAdd = Mathf.Min(minimumRenderScale, allowedMaximumRenderScale);
// Add min scale as the reprojection scale
allRenderScales.Add(renderScaleToAdd);
// Add all entries
while (renderScaleToAdd <= maximumRenderScale)
{
allRenderScales.Add(renderScaleToAdd);
renderScaleToAdd =
Mathf.Sqrt((renderScaleFillRateStepSizeInPercent + 100) / 100.0f * renderScaleToAdd * renderScaleToAdd);
if (renderScaleToAdd > allowedMaximumRenderScale)
{
// Too large
break;
}
}
// Figure out default render viewport scale level for debug visualization
defaultRenderViewportScaleLevel = Mathf.Clamp(
allRenderScales.FindIndex(renderScale => renderScale >= 1.0f),
1,
allRenderScales.Count - 1);
renderViewportScaleSetting.currentValue = defaultRenderViewportScaleLevel;
renderScaleSetting.currentValue = defaultRenderViewportScaleLevel;
overrideRenderViewportScaleLevel = ClampRenderScaleLevel(overrideRenderViewportScaleLevel);
}
private void UpdateRenderScale()
{
if (!scaleRenderViewport)
{
renderViewportScaleSetting.currentValue = defaultRenderViewportScaleLevel;
renderScaleSetting.currentValue = defaultRenderViewportScaleLevel;
SetRenderScale(1.0f, 1.0f);
return;
}
// Rendering in low resolution means adaptive quality needs to scale back the render scale target to free up gpu cycles
bool renderInLowResolution = VRTK_SDK_Bridge.ShouldAppRenderWithLowResources();
// Thresholds
float allowedSingleFrameDurationInMilliseconds = renderInLowResolution
? singleFrameDurationInMilliseconds * 0.75f
: singleFrameDurationInMilliseconds;
float lowThresholdInMilliseconds = 0.7f * allowedSingleFrameDurationInMilliseconds;
float extrapolationThresholdInMilliseconds = 0.85f * allowedSingleFrameDurationInMilliseconds;
float highThresholdInMilliseconds = 0.9f * allowedSingleFrameDurationInMilliseconds;
int newRenderViewportScaleLevel = renderViewportScaleSetting.currentValue;
// Rapidly reduce render viewport scale level if cost of last 1 or 3 frames, or the predicted next frame's cost are expensive
if (timing.WasFrameTimingBad(
1,
highThresholdInMilliseconds,
renderViewportScaleSetting.lastChangeFrameCount,
renderViewportScaleSetting.decreaseFrameCost)
|| timing.WasFrameTimingBad(
3,
highThresholdInMilliseconds,
renderViewportScaleSetting.lastChangeFrameCount,
renderViewportScaleSetting.decreaseFrameCost)
|| timing.WillFrameTimingBeBad(
extrapolationThresholdInMilliseconds,
highThresholdInMilliseconds,
renderViewportScaleSetting.lastChangeFrameCount,
renderViewportScaleSetting.decreaseFrameCost))
{
// Always drop 2 levels except when dropping from level 2 (level 0 is for reprojection)
newRenderViewportScaleLevel = ClampRenderScaleLevel(renderViewportScaleSetting.currentValue == 2
? 1
: renderViewportScaleSetting.currentValue - 2);
}
// Rapidly increase render viewport scale level if last 12 frames are cheap
else if (timing.WasFrameTimingGood(
12,
lowThresholdInMilliseconds,
renderViewportScaleSetting.lastChangeFrameCount - renderViewportScaleSetting.increaseFrameCost,
renderViewportScaleSetting.increaseFrameCost))
{
newRenderViewportScaleLevel = ClampRenderScaleLevel(renderViewportScaleSetting.currentValue + 2);
}
// Slowly increase render viewport scale level if last 6 frames are cheap
else if (timing.WasFrameTimingGood(
6,
lowThresholdInMilliseconds,
renderViewportScaleSetting.lastChangeFrameCount,
renderViewportScaleSetting.increaseFrameCost))
{
// Only increase by 1 level to prevent frame drops caused by adjusting
newRenderViewportScaleLevel = ClampRenderScaleLevel(renderViewportScaleSetting.currentValue + 1);
}
// Apply and remember when render viewport scale level changed
if (newRenderViewportScaleLevel != renderViewportScaleSetting.currentValue)
{
if (renderViewportScaleSetting.currentValue >= renderScaleSetting.currentValue
&& newRenderViewportScaleLevel < renderScaleSetting.currentValue)
{
lastRenderViewportScaleLevelBelowRenderScaleLevelFrameCount = Time.frameCount;
}
renderViewportScaleSetting.currentValue = newRenderViewportScaleLevel;
}
// Ignore frame timings if overriding
if (overrideRenderViewportScale)
{
renderViewportScaleSetting.currentValue = overrideRenderViewportScaleLevel;
}
// Force on interleaved reprojection for level 0 which is just a replica of level 1 with reprojection enabled
float additionalViewportScale = 1.0f;
if (!hmdDisplayIsOnDesktop)
{
if (renderViewportScaleSetting.currentValue == 0)
{
if (interleavedReprojectionEnabled && timing.GetFrameTiming(0) < singleFrameDurationInMilliseconds * 0.85f)
{
interleavedReprojectionEnabled = false;
}
else if (timing.GetFrameTiming(0) > singleFrameDurationInMilliseconds * 0.925f)
{
interleavedReprojectionEnabled = true;
}
}
else
{
interleavedReprojectionEnabled = false;
}
VRTK_SDK_Bridge.ForceInterleavedReprojectionOn(interleavedReprojectionEnabled);
}
// Not running in direct mode! Interleaved reprojection not supported, so scale down the viewport some more
else if (renderViewportScaleSetting.currentValue == 0)
{
additionalViewportScale = 0.8f;
}
int newRenderScaleLevel = renderScaleSetting.currentValue;
int levelInBetween = (renderViewportScaleSetting.currentValue - renderScaleSetting.currentValue) / 2;
// Increase render scale level to the level in between
if (renderScaleSetting.currentValue < renderViewportScaleSetting.currentValue
&& Time.frameCount >= renderScaleSetting.lastChangeFrameCount + renderScaleSetting.increaseFrameCost)
{
newRenderScaleLevel = ClampRenderScaleLevel(renderScaleSetting.currentValue + Mathf.Max(1, levelInBetween));
}
// Decrease render scale level
else if (renderScaleSetting.currentValue > renderViewportScaleSetting.currentValue
&& Time.frameCount >= renderScaleSetting.lastChangeFrameCount + renderScaleSetting.decreaseFrameCost
&& Time.frameCount >= lastRenderViewportScaleLevelBelowRenderScaleLevelFrameCount + renderViewportScaleSetting.increaseFrameCost)
{
// Slowly decrease render scale level to level in between if last 6 frames are cheap, otherwise rapidly
newRenderScaleLevel = timing.WasFrameTimingGood(6, lowThresholdInMilliseconds, 0, 0)
? ClampRenderScaleLevel(renderScaleSetting.currentValue + Mathf.Min(-1, levelInBetween))
: renderViewportScaleSetting.currentValue;
}
// Apply and remember when render scale level changed
renderScaleSetting.currentValue = newRenderScaleLevel;
if (!scaleRenderTargetResolution)
{
renderScaleSetting.currentValue = allRenderScales.Count - 1;
}
float newRenderScale = allRenderScales[renderScaleSetting.currentValue];
float newRenderViewportScale = allRenderScales[Mathf.Min(renderViewportScaleSetting.currentValue, renderScaleSetting.currentValue)]
/ newRenderScale * additionalViewportScale;
SetRenderScale(newRenderScale, newRenderViewportScale);
}
private static void SetRenderScale(float renderScale, float renderViewportScale)
{
if (Mathf.Abs(VRSettings.renderScale - renderScale) > float.Epsilon)
{
VRSettings.renderScale = renderScale;
}
if (Mathf.Abs(VRSettings.renderViewportScale - renderViewportScale) > float.Epsilon)
{
VRSettings.renderViewportScale = renderViewportScale;
}
}
private int ClampRenderScaleLevel(int renderScaleLevel)
{
return Mathf.Clamp(renderScaleLevel, 0, allRenderScales.Count - 1);
}
#endregion
#region Debug visualization methods
private void CreateOrDestroyDebugVisualization()
{
if (!Application.isPlaying)
{
return;
}
if (enabled && drawDebugVisualization && debugVisualizationQuad == null)
{
var mesh = new Mesh
{
vertices =
new[]
{
new Vector3(-0.5f, 0.9f, 1.0f),
new Vector3(-0.5f, 1.0f, 1.0f),
new Vector3(0.5f, 1.0f, 1.0f),
new Vector3(0.5f, 0.9f, 1.0f)
},
uv =
new[]
{
new Vector2(0.0f, 0.0f),
new Vector2(0.0f, 1.0f),
new Vector2(1.0f, 1.0f),
new Vector2(1.0f, 0.0f)
},
triangles = new[] { 0, 1, 2, 0, 2, 3 }
};
mesh.Optimize();
mesh.UploadMeshData(true);
debugVisualizationQuad = new GameObject("AdaptiveQualityDebugVisualizationQuad");
debugVisualizationQuad.transform.parent = VRTK_DeviceFinder.HeadsetTransform();
debugVisualizationQuad.transform.localPosition = Vector3.forward;
debugVisualizationQuad.transform.localRotation = Quaternion.identity;
debugVisualizationQuad.AddComponent<MeshFilter>().mesh = mesh;
debugVisualizationQuadMaterial = Resources.Load<Material>("AdaptiveQualityDebugVisualization");
debugVisualizationQuad.AddComponent<MeshRenderer>().material = debugVisualizationQuadMaterial;
}
else if ((!enabled || !drawDebugVisualization) && debugVisualizationQuad != null)
{
Destroy(debugVisualizationQuad);
debugVisualizationQuad = null;
debugVisualizationQuadMaterial = null;
}
}
private void UpdateDebugVisualization()
{
if (!drawDebugVisualization || debugVisualizationQuadMaterial == null)
{
return;
}
int lastFrameIsInBudget = interleavedReprojectionEnabled || VRStats.gpuTimeLastFrame > singleFrameDurationInMilliseconds
? 0
: 1;
debugVisualizationQuadMaterial.SetInt(ShaderPropertyIDs.RenderScaleLevelsCount, allRenderScales.Count);
debugVisualizationQuadMaterial.SetInt(ShaderPropertyIDs.DefaultRenderViewportScaleLevel, defaultRenderViewportScaleLevel);
debugVisualizationQuadMaterial.SetInt(ShaderPropertyIDs.CurrentRenderViewportScaleLevel, renderViewportScaleSetting.currentValue);
debugVisualizationQuadMaterial.SetInt(ShaderPropertyIDs.CurrentRenderScaleLevel, renderScaleSetting.currentValue);
debugVisualizationQuadMaterial.SetInt(ShaderPropertyIDs.LastFrameIsInBudget, lastFrameIsInBudget);
}
#endregion
#region Private helper classes
private sealed class AdaptiveSetting<T>
{
public T currentValue
{
get { return _currentValue; }
set
{
if (!EqualityComparer<T>.Default.Equals(value, _currentValue))
{
lastChangeFrameCount = Time.frameCount;
}
previousValue = _currentValue;
_currentValue = value;
}
}
public T previousValue { get; private set; }
public int lastChangeFrameCount { get; private set; }
public readonly int increaseFrameCost;
public readonly int decreaseFrameCost;
private T _currentValue;
public AdaptiveSetting(T currentValue, int increaseFrameCost, int decreaseFrameCost)
{
previousValue = currentValue;
this.currentValue = currentValue;
this.increaseFrameCost = increaseFrameCost;
this.decreaseFrameCost = decreaseFrameCost;
}
}
private static class CommandLineArguments
{
public const string Disable = "-noaq";
public const string MinimumRenderScale = "-aqminscale";
public const string MaximumRenderScale = "-aqmaxscale";
public const string MaximumRenderTargetDimension = "-aqmaxres";
public const string RenderScaleFillRateStepSizeInPercent = "-aqfillratestep";
public const string OverrideRenderScaleLevel = "-aqoverride";
public const string DrawDebugVisualization = "-vrdebug";
public const string MSAALevel = "-msaa";
}
private static class KeyboardShortcuts
{
public static readonly KeyCode[] Modifiers = { KeyCode.LeftShift, KeyCode.RightShift };
public const KeyCode ToggleDrawDebugVisualization = KeyCode.F1;
public const KeyCode ToggleOverrideRenderScale = KeyCode.F2;
public const KeyCode DecreaseOverrideRenderScaleLevel = KeyCode.F3;
public const KeyCode IncreaseOverrideRenderScaleLevel = KeyCode.F4;
}
private static class ShaderPropertyIDs
{
public static readonly int RenderScaleLevelsCount = Shader.PropertyToID("_RenderScaleLevelsCount");
public static readonly int DefaultRenderViewportScaleLevel = Shader.PropertyToID("_DefaultRenderViewportScaleLevel");
public static readonly int CurrentRenderViewportScaleLevel = Shader.PropertyToID("_CurrentRenderViewportScaleLevel");
public static readonly int CurrentRenderScaleLevel = Shader.PropertyToID("_CurrentRenderScaleLevel");
public static readonly int LastFrameIsInBudget = Shader.PropertyToID("_LastFrameIsInBudget");
}
private sealed class Timing
{
private readonly float[] buffer = new float[12];
private int bufferIndex;
public void SaveCurrentFrameTiming()
{
bufferIndex = (bufferIndex + 1) % buffer.Length;
buffer[bufferIndex] = VRStats.gpuTimeLastFrame;
}
public float GetFrameTiming(int framesAgo)
{
return buffer[(bufferIndex - framesAgo + buffer.Length) % buffer.Length];
}
public bool WasFrameTimingBad(int framesAgo, float thresholdInMilliseconds, int lastChangeFrameCount, int changeFrameCost)
{
if (!AreFramesAvailable(framesAgo, lastChangeFrameCount, changeFrameCost))
{
// Too early to know
return false;
}
for (int frame = 0; frame < framesAgo; frame++)
{
if (GetFrameTiming(frame) <= thresholdInMilliseconds)
{
return false;
}
}
return true;
}
public bool WasFrameTimingGood(int framesAgo, float thresholdInMilliseconds, int lastChangeFrameCount, int changeFrameCost)
{
if (!AreFramesAvailable(framesAgo, lastChangeFrameCount, changeFrameCost))
{
// Too early to know
return false;
}
for (int frame = 0; frame < framesAgo; frame++)
{
if (GetFrameTiming(frame) > thresholdInMilliseconds)
{
return false;
}
}
return true;
}
public bool WillFrameTimingBeBad(float extrapolationThresholdInMilliseconds, float thresholdInMilliseconds,
int lastChangeFrameCount, int changeFrameCost)
{
if (!AreFramesAvailable(2, lastChangeFrameCount, changeFrameCost))
{
// Too early to know
return false;
}
// Predict next frame's cost using linear extrapolation: max(frame-1 to frame+1, frame-2 to frame+1)
float frameMinus0Timing = GetFrameTiming(0);
if (frameMinus0Timing <= extrapolationThresholdInMilliseconds)
{
return false;
}
float delta = frameMinus0Timing - GetFrameTiming(1);
if (!AreFramesAvailable(3, lastChangeFrameCount, changeFrameCost))
{
delta = Mathf.Max(delta, (frameMinus0Timing - GetFrameTiming(2)) / 2f);
}
return frameMinus0Timing + delta > thresholdInMilliseconds;
}
private static bool AreFramesAvailable(int framesAgo, int lastChangeFrameCount, int changeFrameCost)
{
return Time.frameCount >= framesAgo + lastChangeFrameCount + changeFrameCost;
}
}
#endregion
}
}
#endif
| |
/*
* Copyright 2007 ZXing 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.Generic;
using System.Text;
using ZXing.Common;
namespace ZXing.QrCode.Internal
{
/// <summary> <p>QR Codes can encode text as bits in one of several modes, and can use multiple modes
/// in one QR Code. This class decodes the bits back into text.</p>
///
/// <p>See ISO 18004:2006, 6.4.3 - 6.4.7</p>
/// <author>Sean Owen</author>
/// </summary>
internal static class DecodedBitStreamParser
{
/// <summary>
/// See ISO 18004:2006, 6.4.4 Table 5
/// </summary>
private static readonly char[] ALPHANUMERIC_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:".ToCharArray();
private const int GB2312_SUBSET = 1;
internal static DecoderResult decode(byte[] bytes,
Version version,
ErrorCorrectionLevel ecLevel,
IDictionary<DecodeHintType, object> hints)
{
var bits = new BitSource(bytes);
var result = new StringBuilder(50);
var byteSegments = new List<byte[]>(1);
var symbolSequence = -1;
var parityData = -1;
int symbologyModifier;
try
{
CharacterSetECI currentCharacterSetECI = null;
bool fc1InEffect = false;
bool hasFNC1first = false;
bool hasFNC1second = false;
Mode mode;
do
{
// While still another segment to read...
if (bits.available() < 4)
{
// OK, assume we're done. Really, a TERMINATOR mode should have been recorded here
mode = Mode.TERMINATOR;
}
else
{
try
{
mode = Mode.forBits(bits.readBits(4)); // mode is encoded by 4 bits
}
catch (ArgumentException)
{
return null;
}
}
switch (mode.Name)
{
case Mode.Names.TERMINATOR:
break;
case Mode.Names.FNC1_FIRST_POSITION:
hasFNC1first = true; // symbology detection
// We do little with FNC1 except alter the parsed result a bit according to the spec
fc1InEffect = true;
break;
case Mode.Names.FNC1_SECOND_POSITION:
hasFNC1second = true; // symbology detection
// We do little with FNC1 except alter the parsed result a bit according to the spec
fc1InEffect = true;
break;
case Mode.Names.STRUCTURED_APPEND:
if (bits.available() < 16)
{
return null;
}
// not really supported; but sequence number and parity is added later to the result metadata
// Read next 8 bits (symbol sequence #) and 8 bits (parity data), then continue
symbolSequence = bits.readBits(8);
parityData = bits.readBits(8);
break;
case Mode.Names.ECI:
// Count doesn't apply to ECI
int value = parseECIValue(bits);
currentCharacterSetECI = CharacterSetECI.getCharacterSetECIByValue(value);
if (currentCharacterSetECI == null)
{
return null;
}
break;
case Mode.Names.HANZI:
// First handle Hanzi mode which does not start with character count
//chinese mode contains a sub set indicator right after mode indicator
int subset = bits.readBits(4);
int countHanzi = bits.readBits(mode.getCharacterCountBits(version));
if (subset == GB2312_SUBSET)
{
if (!decodeHanziSegment(bits, result, countHanzi))
return null;
}
break;
default:
// "Normal" QR code modes:
// How many characters will follow, encoded in this mode?
int count = bits.readBits(mode.getCharacterCountBits(version));
switch (mode.Name)
{
case Mode.Names.NUMERIC:
if (!decodeNumericSegment(bits, result, count))
return null;
break;
case Mode.Names.ALPHANUMERIC:
if (!decodeAlphanumericSegment(bits, result, count, fc1InEffect))
return null;
break;
case Mode.Names.BYTE:
if (!decodeByteSegment(bits, result, count, currentCharacterSetECI, byteSegments, hints))
return null;
break;
case Mode.Names.KANJI:
if (!decodeKanjiSegment(bits, result, count))
return null;
break;
default:
return null;
}
break;
}
} while (mode != Mode.TERMINATOR);
if (currentCharacterSetECI != null)
{
if (hasFNC1first)
{
symbologyModifier = 4;
}
else if (hasFNC1second)
{
symbologyModifier = 6;
}
else
{
symbologyModifier = 2;
}
}
else
{
if (hasFNC1first)
{
symbologyModifier = 3;
}
else if (hasFNC1second)
{
symbologyModifier = 5;
}
else
{
symbologyModifier = 1;
}
}
}
catch (ArgumentException)
{
// from readBits() calls
return null;
}
return new DecoderResult(bytes,
result.ToString(),
byteSegments.Count == 0 ? null : byteSegments,
ecLevel == null ? null : ecLevel.ToString(),
symbolSequence, parityData, symbologyModifier);
}
/// <summary>
/// See specification GBT 18284-2000
/// </summary>
/// <param name="bits">The bits.</param>
/// <param name="result">The result.</param>
/// <param name="count">The count.</param>
/// <returns></returns>
private static bool decodeHanziSegment(BitSource bits,
StringBuilder result,
int count)
{
// Don't crash trying to read more bits than we have available.
if (count * 13 > bits.available())
{
return false;
}
// Each character will require 2 bytes. Read the characters as 2-byte pairs
// and decode as GB2312 afterwards
byte[] buffer = new byte[2 * count];
int offset = 0;
while (count > 0)
{
// Each 13 bits encodes a 2-byte character
int twoBytes = bits.readBits(13);
int assembledTwoBytes = ((twoBytes / 0x060) << 8) | (twoBytes % 0x060);
if (assembledTwoBytes < 0x00A00)
{
// In the 0xA1A1 to 0xAAFE range
assembledTwoBytes += 0x0A1A1;
}
else
{
// In the 0xB0A1 to 0xFAFE range
assembledTwoBytes += 0x0A6A1;
}
buffer[offset] = (byte)((assembledTwoBytes >> 8) & 0xFF);
buffer[offset + 1] = (byte)(assembledTwoBytes & 0xFF);
offset += 2;
count--;
}
var encoding = StringUtils.GB2312_ENCODING;
if (encoding == null)
encoding = StringUtils.PLATFORM_DEFAULT_ENCODING_T;
result.Append(encoding.GetString(buffer, 0, buffer.Length));
return true;
}
private static bool decodeKanjiSegment(BitSource bits,
StringBuilder result,
int count)
{
// Don't crash trying to read more bits than we have available.
if (count * 13 > bits.available())
{
return false;
}
// Each character will require 2 bytes. Read the characters as 2-byte pairs
// and decode as Shift_JIS afterwards
byte[] buffer = new byte[2 * count];
int offset = 0;
while (count > 0)
{
// Each 13 bits encodes a 2-byte character
int twoBytes = bits.readBits(13);
int assembledTwoBytes = ((twoBytes / 0x0C0) << 8) | (twoBytes % 0x0C0);
if (assembledTwoBytes < 0x01F00)
{
// In the 0x8140 to 0x9FFC range
assembledTwoBytes += 0x08140;
}
else
{
// In the 0xE040 to 0xEBBF range
assembledTwoBytes += 0x0C140;
}
buffer[offset] = (byte)(assembledTwoBytes >> 8);
buffer[offset + 1] = (byte)assembledTwoBytes;
offset += 2;
count--;
}
// Shift_JIS may not be supported in some environments:
var encoding = StringUtils.SHIFT_JIS_ENCODING;
if (encoding == null)
encoding = StringUtils.PLATFORM_DEFAULT_ENCODING_T;
result.Append(encoding.GetString(buffer, 0, buffer.Length));
return true;
}
private static bool decodeByteSegment(BitSource bits,
StringBuilder result,
int count,
CharacterSetECI currentCharacterSetECI,
IList<byte[]> byteSegments,
IDictionary<DecodeHintType, object> hints)
{
// Don't crash trying to read more bits than we have available.
if (count << 3 > bits.available())
{
return false;
}
byte[] readBytes = new byte[count];
for (int i = 0; i < count; i++)
{
readBytes[i] = (byte)bits.readBits(8);
}
Encoding encoding;
if (currentCharacterSetECI == null)
{
// The spec isn't clear on this mode; see
// section 6.4.5: t does not say which encoding to assuming
// upon decoding. I have seen ISO-8859-1 used as well as
// Shift_JIS -- without anything like an ECI designator to
// give a hint.
encoding = StringUtils.guessCharset(readBytes, hints);
}
else
{
encoding = CharacterSetECI.getEncoding(currentCharacterSetECI.EncodingName);
}
if (encoding == null)
{
encoding = StringUtils.PLATFORM_DEFAULT_ENCODING_T;
}
result.Append(encoding.GetString(readBytes, 0, readBytes.Length));
byteSegments.Add(readBytes);
return true;
}
private static char toAlphaNumericChar(int value)
{
if (value >= ALPHANUMERIC_CHARS.Length)
{
throw new FormatException();
}
return ALPHANUMERIC_CHARS[value];
}
private static bool decodeAlphanumericSegment(BitSource bits,
StringBuilder result,
int count,
bool fc1InEffect)
{
// Read two characters at a time
int start = result.Length;
while (count > 1)
{
if (bits.available() < 11)
{
return false;
}
int nextTwoCharsBits = bits.readBits(11);
result.Append(toAlphaNumericChar(nextTwoCharsBits / 45));
result.Append(toAlphaNumericChar(nextTwoCharsBits % 45));
count -= 2;
}
if (count == 1)
{
// special case: one character left
if (bits.available() < 6)
{
return false;
}
result.Append(toAlphaNumericChar(bits.readBits(6)));
}
// See section 6.4.8.1, 6.4.8.2
if (fc1InEffect)
{
// We need to massage the result a bit if in an FNC1 mode:
for (int i = start; i < result.Length; i++)
{
if (result[i] == '%')
{
if (i < result.Length - 1 && result[i + 1] == '%')
{
// %% is rendered as %
result.Remove(i + 1, 1);
}
else
{
// In alpha mode, % should be converted to FNC1 separator 0x1D
result.Remove(i, 1);
result.Insert(i, new[] { (char)0x1D });
}
}
}
}
return true;
}
private static bool decodeNumericSegment(BitSource bits,
StringBuilder result,
int count)
{
// Read three digits at a time
while (count >= 3)
{
// Each 10 bits encodes three digits
if (bits.available() < 10)
{
return false;
}
int threeDigitsBits = bits.readBits(10);
if (threeDigitsBits >= 1000)
{
return false;
}
result.Append(toAlphaNumericChar(threeDigitsBits / 100));
result.Append(toAlphaNumericChar((threeDigitsBits / 10) % 10));
result.Append(toAlphaNumericChar(threeDigitsBits % 10));
count -= 3;
}
if (count == 2)
{
// Two digits left over to read, encoded in 7 bits
if (bits.available() < 7)
{
return false;
}
int twoDigitsBits = bits.readBits(7);
if (twoDigitsBits >= 100)
{
return false;
}
result.Append(toAlphaNumericChar(twoDigitsBits / 10));
result.Append(toAlphaNumericChar(twoDigitsBits % 10));
}
else if (count == 1)
{
// One digit left over to read
if (bits.available() < 4)
{
return false;
}
int digitBits = bits.readBits(4);
if (digitBits >= 10)
{
return false;
}
result.Append(toAlphaNumericChar(digitBits));
}
return true;
}
private static int parseECIValue(BitSource bits)
{
int firstByte = bits.readBits(8);
if ((firstByte & 0x80) == 0)
{
// just one byte
return firstByte & 0x7F;
}
if ((firstByte & 0xC0) == 0x80)
{
// two bytes
int secondByte = bits.readBits(8);
return ((firstByte & 0x3F) << 8) | secondByte;
}
if ((firstByte & 0xE0) == 0xC0)
{
// three bytes
int secondThirdBytes = bits.readBits(16);
return ((firstByte & 0x1F) << 16) | secondThirdBytes;
}
throw new ArgumentException("Bad ECI bits starting with byte " + firstByte);
}
}
}
| |
//---------------------------------------------------------------------------
//
// <copyright file="DropShadowBitmapEffect.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 DropShadowBitmapEffect : BitmapEffect
{
//------------------------------------------------------
//
// Public Methods
//
//------------------------------------------------------
#region Public Methods
/// <summary>
/// Shadows inherited Clone() with a strongly typed
/// version for convenience.
/// </summary>
public new DropShadowBitmapEffect Clone()
{
return (DropShadowBitmapEffect)base.Clone();
}
/// <summary>
/// Shadows inherited CloneCurrentValue() with a strongly typed
/// version for convenience.
/// </summary>
public new DropShadowBitmapEffect CloneCurrentValue()
{
return (DropShadowBitmapEffect)base.CloneCurrentValue();
}
#endregion Public Methods
//------------------------------------------------------
//
// Public Properties
//
//------------------------------------------------------
private static void ShadowDepthPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
DropShadowBitmapEffect target = ((DropShadowBitmapEffect) d);
target.PropertyChanged(ShadowDepthProperty);
}
private static void ColorPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
DropShadowBitmapEffect target = ((DropShadowBitmapEffect) d);
target.PropertyChanged(ColorProperty);
}
private static void DirectionPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
DropShadowBitmapEffect target = ((DropShadowBitmapEffect) d);
target.PropertyChanged(DirectionProperty);
}
private static void NoisePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
DropShadowBitmapEffect target = ((DropShadowBitmapEffect) d);
target.PropertyChanged(NoiseProperty);
}
private static void OpacityPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
DropShadowBitmapEffect target = ((DropShadowBitmapEffect) d);
target.PropertyChanged(OpacityProperty);
}
private static void SoftnessPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
DropShadowBitmapEffect target = ((DropShadowBitmapEffect) d);
target.PropertyChanged(SoftnessProperty);
}
#region Public Properties
/// <summary>
/// ShadowDepth - double. Default value is 5.0.
/// </summary>
public double ShadowDepth
{
get
{
return (double) GetValue(ShadowDepthProperty);
}
set
{
SetValueInternal(ShadowDepthProperty, value);
}
}
/// <summary>
/// Color - Color. Default value is Colors.Black.
/// </summary>
public Color Color
{
get
{
return (Color) GetValue(ColorProperty);
}
set
{
SetValueInternal(ColorProperty, value);
}
}
/// <summary>
/// Direction - double. Default value is 315.0.
/// </summary>
public double Direction
{
get
{
return (double) GetValue(DirectionProperty);
}
set
{
SetValueInternal(DirectionProperty, value);
}
}
/// <summary>
/// Noise - double. Default value is 0.0.
/// </summary>
public double Noise
{
get
{
return (double) GetValue(NoiseProperty);
}
set
{
SetValueInternal(NoiseProperty, value);
}
}
/// <summary>
/// Opacity - double. Default value is 1.0.
/// </summary>
public double Opacity
{
get
{
return (double) GetValue(OpacityProperty);
}
set
{
SetValueInternal(OpacityProperty, value);
}
}
/// <summary>
/// Softness - double. Default value is 0.5.
/// </summary>
public double Softness
{
get
{
return (double) GetValue(SoftnessProperty);
}
set
{
SetValueInternal(SoftnessProperty, 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 DropShadowBitmapEffect();
}
#endregion ProtectedMethods
//------------------------------------------------------
//
// Internal Methods
//
//------------------------------------------------------
#region Internal Methods
#endregion Internal Methods
//------------------------------------------------------
//
// Internal Properties
//
//------------------------------------------------------
#region Internal Properties
#endregion Internal Properties
//------------------------------------------------------
//
// Dependency Properties
//
//------------------------------------------------------
#region Dependency Properties
/// <summary>
/// The DependencyProperty for the DropShadowBitmapEffect.ShadowDepth property.
/// </summary>
public static readonly DependencyProperty ShadowDepthProperty;
/// <summary>
/// The DependencyProperty for the DropShadowBitmapEffect.Color property.
/// </summary>
public static readonly DependencyProperty ColorProperty;
/// <summary>
/// The DependencyProperty for the DropShadowBitmapEffect.Direction property.
/// </summary>
public static readonly DependencyProperty DirectionProperty;
/// <summary>
/// The DependencyProperty for the DropShadowBitmapEffect.Noise property.
/// </summary>
public static readonly DependencyProperty NoiseProperty;
/// <summary>
/// The DependencyProperty for the DropShadowBitmapEffect.Opacity property.
/// </summary>
public static readonly DependencyProperty OpacityProperty;
/// <summary>
/// The DependencyProperty for the DropShadowBitmapEffect.Softness property.
/// </summary>
public static readonly DependencyProperty SoftnessProperty;
#endregion Dependency Properties
//------------------------------------------------------
//
// Internal Fields
//
//------------------------------------------------------
#region Internal Fields
internal const double c_ShadowDepth = 5.0;
internal static Color s_Color = Colors.Black;
internal const double c_Direction = 315.0;
internal const double c_Noise = 0.0;
internal const double c_Opacity = 1.0;
internal const double c_Softness = 0.5;
#endregion Internal Fields
#region Constructors
//------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
static DropShadowBitmapEffect()
{
// 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(DropShadowBitmapEffect);
ShadowDepthProperty =
RegisterProperty("ShadowDepth",
typeof(double),
typeofThis,
5.0,
new PropertyChangedCallback(ShadowDepthPropertyChanged),
null,
/* isIndependentlyAnimated = */ true,
/* coerceValueCallback */ null);
ColorProperty =
RegisterProperty("Color",
typeof(Color),
typeofThis,
Colors.Black,
new PropertyChangedCallback(ColorPropertyChanged),
null,
/* isIndependentlyAnimated = */ true,
/* coerceValueCallback */ null);
DirectionProperty =
RegisterProperty("Direction",
typeof(double),
typeofThis,
315.0,
new PropertyChangedCallback(DirectionPropertyChanged),
null,
/* isIndependentlyAnimated = */ true,
/* coerceValueCallback */ null);
NoiseProperty =
RegisterProperty("Noise",
typeof(double),
typeofThis,
0.0,
new PropertyChangedCallback(NoisePropertyChanged),
null,
/* isIndependentlyAnimated = */ true,
/* coerceValueCallback */ null);
OpacityProperty =
RegisterProperty("Opacity",
typeof(double),
typeofThis,
1.0,
new PropertyChangedCallback(OpacityPropertyChanged),
null,
/* isIndependentlyAnimated = */ true,
/* coerceValueCallback */ null);
SoftnessProperty =
RegisterProperty("Softness",
typeof(double),
typeofThis,
0.5,
new PropertyChangedCallback(SoftnessPropertyChanged),
null,
/* isIndependentlyAnimated = */ true,
/* coerceValueCallback */ null);
}
#endregion Constructors
}
}
| |
#region License
/*
* 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.
*/
#endregion
using System;
using System.Collections;
using System.Collections.Specialized;
using Spring.Util;
namespace Spring.Collections
{
/// <summary>
/// Synchronized <see cref="Hashtable"/> that, unlike hashtable created
/// using <see cref="Hashtable.Synchronized"/> method, synchronizes
/// reads from the underlying hashtable in addition to writes.
/// </summary>
/// <remarks>
/// <p>
/// In addition to synchronizing reads, this implementation also fixes
/// IEnumerator/ICollection issue described at
/// http://msdn.microsoft.com/en-us/netframework/aa570326.aspx
/// (search for SynchronizedHashtable for issue description), by implementing
/// <see cref="IEnumerator"/> interface explicitly, and returns thread safe enumerator
/// implementations as well.
/// </p>
/// <p>
/// This class should be used whenever a truly synchronized <see cref="Hashtable"/>
/// is needed.
/// </p>
/// </remarks>
/// <author>Aleksandar Seovic</author>
[Serializable]
public class SynchronizedHashtable : IDictionary, ICollection, IEnumerable, ICloneable
{
private readonly bool _ignoreCase;
private readonly Hashtable _table;
#region Constructors
/// <summary>
/// Initializes a new instance of <see cref="SynchronizedHashtable"/>
/// </summary>
public SynchronizedHashtable()
: this(new Hashtable(), false)
{ }
/// <summary>
/// Initializes a new instance of <see cref="SynchronizedHashtable"/>
/// </summary>
public SynchronizedHashtable(bool ignoreCase)
: this(new Hashtable(), ignoreCase)
{ }
/// <summary>
/// Initializes a new instance of <see cref="SynchronizedHashtable"/>, copying initial entries from <param name="dictionary"/>
/// handling keys depending on <param name="ignoreCase"/>.
/// </summary>
public SynchronizedHashtable(IDictionary dictionary, bool ignoreCase)
{
AssertUtils.ArgumentNotNull(dictionary, "dictionary");
this._table = (ignoreCase) ? CollectionsUtil.CreateCaseInsensitiveHashtable(dictionary) : new Hashtable(dictionary);
this._ignoreCase = ignoreCase;
}
/// <summary>
/// Creates a <see cref="SynchronizedHashtable"/> instance that
/// synchronizes access to the underlying <see cref="Hashtable"/>.
/// </summary>
/// <param name="other">the hashtable to be synchronized</param>
protected SynchronizedHashtable(Hashtable other)
{
AssertUtils.ArgumentNotNull(other, "other");
this._table = other;
}
/// <summary>
/// Creates a <see cref="SynchronizedHashtable"/> wrapper that synchronizes
/// access to the passed <see cref="Hashtable"/>.
/// </summary>
/// <param name="other">the hashtable to be synchronized</param>
public static SynchronizedHashtable Wrap(Hashtable other)
{
return new SynchronizedHashtable(other);
}
#endregion
#region Properties
///<summary>
///Gets a value indicating whether the <see cref="T:System.Collections.IDictionary"></see> object is read-only.
///</summary>
///<returns>
///true if the <see cref="T:System.Collections.IDictionary"></see> object is read-only; otherwise, false.
///</returns>
public bool IsReadOnly
{
get
{
lock (SyncRoot)
{
return _table.IsReadOnly;
}
}
}
///<summary>
///Gets a value indicating whether the <see cref="T:System.Collections.IDictionary"></see> object has a fixed size.
///</summary>
///<returns>
///true if the <see cref="T:System.Collections.IDictionary"></see> object has a fixed size; otherwise, false.
///</returns>
public bool IsFixedSize
{
get
{
lock (SyncRoot)
{
return _table.IsFixedSize;
}
}
}
///<summary>
///Gets a value indicating whether access to the <see cref="T:System.Collections.ICollection"></see> is synchronized (thread safe).
///</summary>
///<returns>
///true if access to the <see cref="T:System.Collections.ICollection"></see> is synchronized (thread safe); otherwise, false.
///</returns>
public bool IsSynchronized
{
get { return true; }
}
///<summary>
///Gets an <see cref="T:System.Collections.ICollection"></see> object containing the keys of the <see cref="T:System.Collections.IDictionary"></see> object.
///</summary>
///<returns>
///An <see cref="T:System.Collections.ICollection"></see> object containing the keys of the <see cref="T:System.Collections.IDictionary"></see> object.
///</returns>
public ICollection Keys
{
get
{
lock (SyncRoot)
{
return _table.Keys;
}
}
}
///<summary>
///Gets an <see cref="T:System.Collections.ICollection"></see> object containing the values in the <see cref="T:System.Collections.IDictionary"></see> object.
///</summary>
///<returns>
///An <see cref="T:System.Collections.ICollection"></see> object containing the values in the <see cref="T:System.Collections.IDictionary"></see> object.
///</returns>
public ICollection Values
{
get
{
lock (SyncRoot)
{
return _table.Values;
}
}
}
///<summary>
///Gets an object that can be used to synchronize access to the <see cref="T:System.Collections.ICollection"></see>.
///</summary>
///<returns>
///An object that can be used to synchronize access to the <see cref="T:System.Collections.ICollection"></see>.
///</returns>
public object SyncRoot
{
get { return _table.SyncRoot; }
}
///<summary>
///Gets the number of elements contained in the <see cref="T:System.Collections.ICollection"></see>.
///</summary>
///<returns>
///The number of elements contained in the <see cref="T:System.Collections.ICollection"></see>.
///</returns>
public int Count
{
get
{
lock (SyncRoot)
{
return _table.Count;
}
}
}
#endregion
#region Methods
///<summary>
///Adds an element with the provided key and value to the <see cref="T:System.Collections.IDictionary"></see> object.
///</summary>
///<param name="value">The <see cref="T:System.Object"></see> to use as the value of the element to add. </param>
///<param name="key">The <see cref="T:System.Object"></see> to use as the key of the element to add. </param>
///<exception cref="T:System.ArgumentException">An element with the same key already exists in the <see cref="T:System.Collections.IDictionary"></see> object. </exception>
///<exception cref="T:System.ArgumentNullException">key is null. </exception>
///<exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.IDictionary"></see> is read-only.-or- The <see cref="T:System.Collections.IDictionary"></see> has a fixed size. </exception><filterpriority>2</filterpriority>
public void Add(object key, object value)
{
lock (SyncRoot)
{
_table.Add(key, value);
}
}
///<summary>
///Removes all elements from the <see cref="T:System.Collections.IDictionary"></see> object.
///</summary>
///<exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.IDictionary"></see> object is read-only. </exception><filterpriority>2</filterpriority>
public void Clear()
{
lock (SyncRoot)
{
_table.Clear();
}
}
///<summary>
///Creates a new object that is a copy of the current instance.
///</summary>
///<returns>
///A new object that is a copy of this instance.
///</returns>
public object Clone()
{
lock (SyncRoot)
{
return new SynchronizedHashtable(this, _ignoreCase);
}
}
///<summary>
///Determines whether the <see cref="T:System.Collections.IDictionary"></see> object contains an element with the specified key.
///</summary>
///<returns>
///true if the <see cref="T:System.Collections.IDictionary"></see> contains an element with the key; otherwise, false.
///</returns>
///<param name="key">The key to locate in the <see cref="T:System.Collections.IDictionary"></see> object.</param>
///<exception cref="T:System.ArgumentNullException">key is null. </exception><filterpriority>2</filterpriority>
public bool Contains(object key)
{
lock (SyncRoot)
{
return _table.Contains(key);
}
}
///<summary>
/// Returns, whether this <see cref="IDictionary"/> contains an entry with the specified <paramref name="key"/>.
///</summary>
///<param name="key">The key to look for</param>
///<returns><see lang="true"/>, if this <see cref="IDictionary"/> contains an entry with this <paramref name="key"/></returns>
public bool ContainsKey(object key)
{
lock (SyncRoot)
{
return _table.ContainsKey(key);
}
}
///<summary>
/// Returns, whether this <see cref="IDictionary"/> contains an entry with the specified <paramref name="value"/>.
///</summary>
///<param name="value">The value to look for</param>
///<returns><see lang="true"/>, if this <see cref="IDictionary"/> contains an entry with this <paramref name="value"/></returns>
public bool ContainsValue(object value)
{
lock (SyncRoot)
{
return _table.ContainsValue(value);
}
}
///<summary>
///Copies the elements of the <see cref="T:System.Collections.ICollection"></see> to an <see cref="T:System.Array"></see>, starting at a particular <see cref="T:System.Array"></see> index.
///</summary>
///<param name="array">The one-dimensional <see cref="T:System.Array"></see> that is the destination of the elements copied from <see cref="T:System.Collections.ICollection"></see>. The <see cref="T:System.Array"></see> must have zero-based indexing. </param>
///<param name="index">The zero-based index in array at which copying begins. </param>
///<exception cref="T:System.ArgumentNullException">array is null. </exception>
///<exception cref="T:System.ArgumentException">The type of the source <see cref="T:System.Collections.ICollection"></see> cannot be cast automatically to the type of the destination array. </exception>
///<exception cref="T:System.ArgumentOutOfRangeException">index is less than zero. </exception>
///<exception cref="T:System.ArgumentException">array is multidimensional.-or- index is equal to or greater than the length of array.-or- The number of elements in the source <see cref="T:System.Collections.ICollection"></see> is greater than the available space from index to the end of the destination array. </exception><filterpriority>2</filterpriority>
public void CopyTo(Array array, int index)
{
lock (SyncRoot)
{
_table.CopyTo(array, index);
}
}
///<summary>
///Returns an <see cref="T:System.Collections.IDictionaryEnumerator"></see> object for the <see cref="T:System.Collections.IDictionary"></see> object.
///</summary>
///<returns>
///An <see cref="T:System.Collections.IDictionaryEnumerator"></see> object for the <see cref="T:System.Collections.IDictionary"></see> object.
///</returns>
public IDictionaryEnumerator GetEnumerator()
{
lock (SyncRoot)
{
return new SynchronizedDictionaryEnumerator(SyncRoot, _table.GetEnumerator());
}
}
///<summary>
///Removes the element with the specified key from the <see cref="T:System.Collections.IDictionary"></see> object.
///</summary>
///<param name="key">The key of the element to remove. </param>
///<exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.IDictionary"></see> object is read-only.-or- The <see cref="T:System.Collections.IDictionary"></see> has a fixed size. </exception>
///<exception cref="T:System.ArgumentNullException">key is null. </exception><filterpriority>2</filterpriority>
public void Remove(object key)
{
lock (SyncRoot)
{
_table.Remove(key);
}
}
#endregion
#region IEnumerable implementation
///<summary>
///Returns an enumerator that iterates through a collection.
///</summary>
///<returns>
///An <see cref="T:System.Collections.IEnumerator"></see> object that can be used to iterate through the collection.
///</returns>
IEnumerator IEnumerable.GetEnumerator()
{
lock (SyncRoot)
{
return new SynchronizedEnumerator(SyncRoot, ((IEnumerable)_table).GetEnumerator());
}
}
#endregion
#region Indexer
///<summary>
///Gets or sets the element with the specified key.
///</summary>
///<returns>
///The element with the specified key.
///</returns>
///<param name="key">The key of the element to get or set. </param>
///<exception cref="T:System.NotSupportedException">The property is set and the <see cref="T:System.Collections.IDictionary"></see> object is read-only.-or- The property is set, key does not exist in the collection, and the <see cref="T:System.Collections.IDictionary"></see> has a fixed size. </exception>
///<exception cref="T:System.ArgumentNullException">key is null. </exception><filterpriority>2</filterpriority>
public object this[object key]
{
get
{
lock (SyncRoot)
{
return _table[key];
}
}
set
{
lock (SyncRoot)
{
_table[key] = value;
}
}
}
#endregion
}
}
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Reflection;
using System.Management.Automation.Host;
using Dbg = System.Management.Automation.Diagnostics;
using InternalHostUserInterface = System.Management.Automation.Internal.Host.InternalHostUserInterface;
namespace System.Management.Automation.Remoting
{
/// <summary>
/// Executes methods; can be encoded and decoded for transmission over the
/// wire.
/// </summary>
internal class RemoteHostCall
{
/// <summary>
/// Method name.
/// </summary>
internal string MethodName
{
get
{
return _methodInfo.Name;
}
}
/// <summary>
/// Method id.
/// </summary>
internal RemoteHostMethodId MethodId { get; }
/// <summary>
/// Parameters.
/// </summary>
internal object[] Parameters { get; }
/// <summary>
/// Method info.
/// </summary>
private RemoteHostMethodInfo _methodInfo;
/// <summary>
/// Call id.
/// </summary>
private long _callId;
/// <summary>
/// Call id.
/// </summary>
internal long CallId
{
get
{
return _callId;
}
}
/// <summary>
/// Computer name to be used in messages
/// </summary>
private string _computerName;
/// <summary>
/// Constructor for RemoteHostCall.
/// </summary>
internal RemoteHostCall(long callId, RemoteHostMethodId methodId, object[] parameters)
{
Dbg.Assert(parameters != null, "Expected parameters != null");
_callId = callId;
MethodId = methodId;
Parameters = parameters;
_methodInfo = RemoteHostMethodInfo.LookUp(methodId);
}
/// <summary>
/// Encode parameters.
/// </summary>
private static PSObject EncodeParameters(object[] parameters)
{
// Encode the parameters and wrap the array into an ArrayList and then into a PSObject.
ArrayList parameterList = new ArrayList();
for (int i = 0; i < parameters.Length; ++i)
{
object parameter = parameters[i] == null ? null : RemoteHostEncoder.EncodeObject(parameters[i]);
parameterList.Add(parameter);
}
return new PSObject(parameterList);
}
/// <summary>
/// Decode parameters.
/// </summary>
private static object[] DecodeParameters(PSObject parametersPSObject, Type[] parameterTypes)
{
// Extract the ArrayList and decode the parameters.
ArrayList parameters = (ArrayList)parametersPSObject.BaseObject;
List<object> decodedParameters = new List<object>();
Dbg.Assert(parameters.Count == parameterTypes.Length, "Expected parameters.Count == parameterTypes.Length");
for (int i = 0; i < parameters.Count; ++i)
{
object parameter = parameters[i] == null ? null : RemoteHostEncoder.DecodeObject(parameters[i], parameterTypes[i]);
decodedParameters.Add(parameter);
}
return decodedParameters.ToArray();
}
/// <summary>
/// Encode.
/// </summary>
internal PSObject Encode()
{
// Add all host information as data.
PSObject data = RemotingEncoder.CreateEmptyPSObject();
// Encode the parameters for transport.
PSObject parametersPSObject = EncodeParameters(Parameters);
// Embed everything into the main PSobject.
data.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.CallId, _callId));
data.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.MethodId, MethodId));
data.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.MethodParameters, parametersPSObject));
return data;
}
/// <summary>
/// Decode.
/// </summary>
internal static RemoteHostCall Decode(PSObject data)
{
Dbg.Assert(data != null, "Expected data != null");
// Extract all the fields from data.
long callId = RemotingDecoder.GetPropertyValue<long>(data, RemoteDataNameStrings.CallId);
PSObject parametersPSObject = RemotingDecoder.GetPropertyValue<PSObject>(data, RemoteDataNameStrings.MethodParameters);
RemoteHostMethodId methodId = RemotingDecoder.GetPropertyValue<RemoteHostMethodId>(data, RemoteDataNameStrings.MethodId);
// Look up all the info related to the method.
RemoteHostMethodInfo methodInfo = RemoteHostMethodInfo.LookUp(methodId);
// Decode the parameters.
object[] parameters = DecodeParameters(parametersPSObject, methodInfo.ParameterTypes);
// Create and return the RemoteHostCall.
return new RemoteHostCall(callId, methodId, parameters);
}
/// <summary>
/// Is void method.
/// </summary>
internal bool IsVoidMethod
{
get
{
return _methodInfo.ReturnType == typeof(void);
}
}
/// <summary>
/// Execute void method.
/// </summary>
internal void ExecuteVoidMethod(PSHost clientHost)
{
// The clientHost can be null if the user creates a runspace object without providing
// a host parameter.
if (clientHost == null)
{
return;
}
RemoteRunspace remoteRunspaceToClose = null;
if (this.IsSetShouldExitOrPopRunspace)
{
remoteRunspaceToClose = GetRemoteRunspaceToClose(clientHost);
}
try
{
object targetObject = this.SelectTargetObject(clientHost);
MyMethodBase.Invoke(targetObject, Parameters);
}
finally
{
if (remoteRunspaceToClose != null)
{
remoteRunspaceToClose.Close();
}
}
}
/// <summary>
/// Get remote runspace to close.
/// </summary>
private RemoteRunspace GetRemoteRunspaceToClose(PSHost clientHost)
{
// Figure out if we need to close the remote runspace. Return null if we don't.
// Are we a Start-PSSession enabled host?
IHostSupportsInteractiveSession host = clientHost as IHostSupportsInteractiveSession;
if (host == null || !host.IsRunspacePushed)
{
return null;
}
// Now inspect the runspace.
RemoteRunspace remoteRunspace = host.Runspace as RemoteRunspace;
if (remoteRunspace == null || !remoteRunspace.ShouldCloseOnPop)
{
return null;
}
// At this point it is clear we have to close the remote runspace, so return it.
return remoteRunspace;
}
/// <summary>
/// My method base.
/// </summary>
private MethodBase MyMethodBase
{
get
{
return (MethodBase)_methodInfo.InterfaceType.GetMethod(_methodInfo.Name, _methodInfo.ParameterTypes);
}
}
/// <summary>
/// Execute non void method.
/// </summary>
internal RemoteHostResponse ExecuteNonVoidMethod(PSHost clientHost)
{
// The clientHost can be null if the user creates a runspace object without providing
// a host parameter.
if (clientHost == null)
{
throw RemoteHostExceptions.NewNullClientHostException();
}
object targetObject = this.SelectTargetObject(clientHost);
RemoteHostResponse remoteHostResponse = this.ExecuteNonVoidMethodOnObject(targetObject);
return remoteHostResponse;
}
/// <summary>
/// Execute non void method on object.
/// </summary>
private RemoteHostResponse ExecuteNonVoidMethodOnObject(object instance)
{
// Create variables to store result of execution.
Exception exception = null;
object returnValue = null;
// Invoke the method and store its return values.
try
{
if (MethodId == RemoteHostMethodId.GetBufferContents)
{
throw new PSRemotingDataStructureException(RemotingErrorIdStrings.RemoteHostGetBufferContents,
_computerName.ToUpper());
}
returnValue = MyMethodBase.Invoke(instance, Parameters);
}
catch (Exception e)
{
// Catch-all OK, 3rd party callout.
CommandProcessorBase.CheckForSevereException(e);
exception = e.InnerException;
}
// Create a RemoteHostResponse object to store the return value and exceptions.
return new RemoteHostResponse(_callId, MethodId, returnValue, exception);
}
/// <summary>
/// Get the object that this method should be invoked on.
/// </summary>
private object SelectTargetObject(PSHost host)
{
if (host == null || host.UI == null) { return null; }
if (_methodInfo.InterfaceType == typeof(PSHost)) { return host; }
if (_methodInfo.InterfaceType == typeof(IHostSupportsInteractiveSession)) { return host; }
if (_methodInfo.InterfaceType == typeof(PSHostUserInterface)) { return host.UI; }
if (_methodInfo.InterfaceType == typeof(IHostUISupportsMultipleChoiceSelection)) { return host.UI; }
if (_methodInfo.InterfaceType == typeof(PSHostRawUserInterface)) { return host.UI.RawUI; }
throw RemoteHostExceptions.NewUnknownTargetClassException(_methodInfo.InterfaceType.ToString());
}
/// <summary>
/// Is set should exit.
/// </summary>
internal bool IsSetShouldExit
{
get
{
return MethodId == RemoteHostMethodId.SetShouldExit;
}
}
/// <summary>
/// Is set should exit or pop runspace.
/// </summary>
internal bool IsSetShouldExitOrPopRunspace
{
get
{
return
MethodId == RemoteHostMethodId.SetShouldExit ||
MethodId == RemoteHostMethodId.PopRunspace;
}
}
/// <summary>
/// This message performs various security checks on the
/// remote host call message. If there is a need to modify
/// the message or discard it for security reasons then
/// such modifications will be made here
/// </summary>
/// <param name="computerName">computer name to use in
/// warning messages</param>
/// <returns>a collection of remote host calls which will
/// have to be executed before this host call can be
/// executed</returns>
internal Collection<RemoteHostCall> PerformSecurityChecksOnHostMessage(String computerName)
{
Dbg.Assert(!String.IsNullOrEmpty(computerName),
"Computer Name must be passed for use in warning messages");
_computerName = computerName;
Collection<RemoteHostCall> prerequisiteCalls = new Collection<RemoteHostCall>();
// check if the incoming message is a PromptForCredential message
// if so, do the following:
// (a) prepend "Windows PowerShell Credential Request" in the title
// (b) prepend "Message from Server XXXXX" to the text message
if (MethodId == RemoteHostMethodId.PromptForCredential1 ||
MethodId == RemoteHostMethodId.PromptForCredential2)
{
// modify the caption which is _parameters[0]
string modifiedCaption = ModifyCaption((string)Parameters[0]);
// modify the message which is _parameters[1]
string modifiedMessage = ModifyMessage((string)Parameters[1], computerName);
Parameters[0] = modifiedCaption;
Parameters[1] = modifiedMessage;
}
// Check if the incoming message is a Prompt message
// if so, then do the following:
// (a) check if any of the field descriptions
// correspond to PSCredential
// (b) if field descriptions correspond to
// PSCredential modify the caption and
// message as in the previous case above
else if (MethodId == RemoteHostMethodId.Prompt)
{
// check if any of the field descriptions is for type
// PSCredential
if (Parameters.Length == 3)
{
Collection<FieldDescription> fieldDescs =
(Collection<FieldDescription>)Parameters[2];
bool havePSCredential = false;
foreach (FieldDescription fieldDesc in fieldDescs)
{
fieldDesc.IsFromRemoteHost = true;
Type fieldType = InternalHostUserInterface.GetFieldType(fieldDesc);
if (fieldType != null)
{
if (fieldType == typeof(PSCredential))
{
havePSCredential = true;
fieldDesc.ModifiedByRemotingProtocol = true;
}
else if (fieldType == typeof(System.Security.SecureString))
{
prerequisiteCalls.Add(ConstructWarningMessageForSecureString(
computerName, RemotingErrorIdStrings.RemoteHostPromptSecureStringPrompt));
}
}
}// end of foreach
if (havePSCredential)
{
// modify the caption which is parameter[0]
string modifiedCaption = ModifyCaption((string)Parameters[0]);
// modify the message which is parameter[1]
string modifiedMessage = ModifyMessage((string)Parameters[1], computerName);
Parameters[0] = modifiedCaption;
Parameters[1] = modifiedMessage;
}
}// end of if (parameters ...
}// if (remoteHostCall.MethodId ...
// Check if the incoming message is a readline as secure string
// if so do the following:
// (a) Specify a warning message that the server is
// attempting to read something securely on the client
else if (MethodId == RemoteHostMethodId.ReadLineAsSecureString)
{
prerequisiteCalls.Add(ConstructWarningMessageForSecureString(
computerName, RemotingErrorIdStrings.RemoteHostReadLineAsSecureStringPrompt));
}
// check if the incoming call is GetBufferContents
// if so do the following:
// (a) Specify a warning message that the server is
// attempting to read the screen buffer contents
// on screen and it has been blocked
// (b) Modify the message so that call is not executed
else if (MethodId == RemoteHostMethodId.GetBufferContents)
{
prerequisiteCalls.Add(ConstructWarningMessageForGetBufferContents(computerName));
}
return prerequisiteCalls;
}
/// <summary>
/// Provides the modified caption for the given caption
/// Used in ensuring that remote prompt messages are
/// tagged with "Windows PowerShell Credential Request"
/// </summary>
/// <param name="caption">caption to modify</param>
/// <returns>new modified caption</returns>
private String ModifyCaption(string caption)
{
string pscaption = CredUI.PromptForCredential_DefaultCaption;
if (!caption.Equals(pscaption, StringComparison.OrdinalIgnoreCase))
{
string modifiedCaption = PSRemotingErrorInvariants.FormatResourceString(
RemotingErrorIdStrings.RemoteHostPromptForCredentialModifiedCaption, caption);
return modifiedCaption;
}
return caption;
}
/// <summary>
/// Provides the modified message for the given one
/// Used in ensuring that remote prompt messages
/// contain a warning that they originate from a
/// different computer
/// </summary>
/// <param name="message">original message to modify</param>
/// <param name="computerName">computername to include in the
/// message</param>
/// <returns>message which contains a warning as well</returns>
private String ModifyMessage(string message, string computerName)
{
string modifiedMessage = PSRemotingErrorInvariants.FormatResourceString(
RemotingErrorIdStrings.RemoteHostPromptForCredentialModifiedMessage,
computerName.ToUpper(),
message);
return modifiedMessage;
}
/// <summary>
/// Creates a warning message which displays to the user a
/// warning stating that the remote host computer is
/// actually attempting to read a line as a secure string
/// </summary>
/// <param name="computerName">computer name to include
/// in warning</param>
/// <param name="resourceString">resource string to use</param>
/// <returns>a constructed remote host call message
/// which will display the warning</returns>
private RemoteHostCall ConstructWarningMessageForSecureString(string computerName,
string resourceString)
{
string warning = PSRemotingErrorInvariants.FormatResourceString(
resourceString,
computerName.ToUpper());
return new RemoteHostCall(ServerDispatchTable.VoidCallId,
RemoteHostMethodId.WriteWarningLine, new object[] { warning });
}
/// <summary>
/// Creates a warning message which displays to the user a
/// warning stating that the remote host computer is
/// attempting to read the host's buffer contents and that
/// it was suppressed
/// </summary>
/// <param name="computerName">computer name to include
/// in warning</param>
/// <returns>a constructed remote host call message
/// which will display the warning</returns>
private RemoteHostCall ConstructWarningMessageForGetBufferContents(string computerName)
{
string warning = PSRemotingErrorInvariants.FormatResourceString(
RemotingErrorIdStrings.RemoteHostGetBufferContents,
computerName.ToUpper());
return new RemoteHostCall(ServerDispatchTable.VoidCallId,
RemoteHostMethodId.WriteWarningLine, new object[] { warning });
}
}
/// <summary>
/// Encapsulates the method response semantics. Method responses are generated when
/// RemoteHostCallPacket objects are executed. They can contain both the return values of
/// the execution as well as exceptions that were thrown in the RemoteHostCallPacket
/// execution. They can be encoded and decoded for transporting over the wire. A
/// method response can be used to transport the result of an execution and then to
/// simulate the execution on the other end.
/// </summary>
internal class RemoteHostResponse
{
/// <summary>
/// Call id.
/// </summary>
private long _callId;
/// <summary>
/// Call id.
/// </summary>
internal long CallId
{
get
{
return _callId;
}
}
/// <summary>
/// Method id.
/// </summary>
private RemoteHostMethodId _methodId;
/// <summary>
/// Return value.
/// </summary>
private object _returnValue;
/// <summary>
/// Exception.
/// </summary>
private Exception _exception;
/// <summary>
/// Constructor for RemoteHostResponse.
/// </summary>
internal RemoteHostResponse(long callId, RemoteHostMethodId methodId, object returnValue, Exception exception)
{
_callId = callId;
_methodId = methodId;
_returnValue = returnValue;
_exception = exception;
}
/// <summary>
/// Simulate execution.
/// </summary>
internal object SimulateExecution()
{
if (_exception != null)
{
throw _exception;
}
return _returnValue;
}
/// <summary>
/// Encode and add return value.
/// </summary>
private static void EncodeAndAddReturnValue(PSObject psObject, object returnValue)
{
// Do nothing if the return value is null.
if (returnValue == null) { return; }
// Otherwise add the property.
RemoteHostEncoder.EncodeAndAddAsProperty(psObject, RemoteDataNameStrings.MethodReturnValue, returnValue);
}
/// <summary>
/// Decode return value.
/// </summary>
private static object DecodeReturnValue(PSObject psObject, Type returnType)
{
object returnValue = RemoteHostEncoder.DecodePropertyValue(psObject, RemoteDataNameStrings.MethodReturnValue, returnType);
return returnValue;
}
/// <summary>
/// Encode and add exception.
/// </summary>
private static void EncodeAndAddException(PSObject psObject, Exception exception)
{
RemoteHostEncoder.EncodeAndAddAsProperty(psObject, RemoteDataNameStrings.MethodException, exception);
}
/// <summary>
/// Decode exception.
/// </summary>
private static Exception DecodeException(PSObject psObject)
{
object result = RemoteHostEncoder.DecodePropertyValue(psObject, RemoteDataNameStrings.MethodException, typeof(Exception));
if (result == null) { return null; }
if (result is Exception) { return (Exception)result; }
throw RemoteHostExceptions.NewDecodingFailedException();
}
/// <summary>
/// Encode.
/// </summary>
internal PSObject Encode()
{
// Create a data object and put everything in that and return it.
PSObject data = RemotingEncoder.CreateEmptyPSObject();
EncodeAndAddReturnValue(data, _returnValue);
EncodeAndAddException(data, _exception);
data.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.CallId, _callId));
data.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.MethodId, _methodId));
return data;
}
/// <summary>
/// Decode.
/// </summary>
internal static RemoteHostResponse Decode(PSObject data)
{
Dbg.Assert(data != null, "Expected data != null");
// Extract all the fields from data.
long callId = RemotingDecoder.GetPropertyValue<long>(data, RemoteDataNameStrings.CallId);
RemoteHostMethodId methodId = RemotingDecoder.GetPropertyValue<RemoteHostMethodId>(data, RemoteDataNameStrings.MethodId);
// Decode the return value and the exception.
RemoteHostMethodInfo methodInfo = RemoteHostMethodInfo.LookUp(methodId);
object returnValue = DecodeReturnValue(data, methodInfo.ReturnType);
Exception exception = DecodeException(data);
// Use these values to create a RemoteHostResponse and return it.
return new RemoteHostResponse(callId, methodId, returnValue, exception);
}
}
/// <summary>
/// The RemoteHostExceptions class.
/// </summary>
internal static class RemoteHostExceptions
{
/// <summary>
/// New remote runspace does not support push runspace exception.
/// </summary>
internal static Exception NewRemoteRunspaceDoesNotSupportPushRunspaceException()
{
string resourceString = PSRemotingErrorInvariants.FormatResourceString(
RemotingErrorIdStrings.RemoteRunspaceDoesNotSupportPushRunspace);
return new PSRemotingDataStructureException(resourceString);
}
/// <summary>
/// New decoding failed exception.
/// </summary>
internal static Exception NewDecodingFailedException()
{
string resourceString = PSRemotingErrorInvariants.FormatResourceString(
RemotingErrorIdStrings.RemoteHostDecodingFailed);
return new PSRemotingDataStructureException(resourceString);
}
/// <summary>
/// New not implemented exception.
/// </summary>
internal static Exception NewNotImplementedException(RemoteHostMethodId methodId)
{
RemoteHostMethodInfo methodInfo = RemoteHostMethodInfo.LookUp(methodId);
string resourceString = PSRemotingErrorInvariants.FormatResourceString(
RemotingErrorIdStrings.RemoteHostMethodNotImplemented, methodInfo.Name);
return new PSRemotingDataStructureException(resourceString, new PSNotImplementedException());
}
/// <summary>
/// New remote host call failed exception.
/// </summary>
internal static Exception NewRemoteHostCallFailedException(RemoteHostMethodId methodId)
{
RemoteHostMethodInfo methodInfo = RemoteHostMethodInfo.LookUp(methodId);
string resourceString = PSRemotingErrorInvariants.FormatResourceString(
RemotingErrorIdStrings.RemoteHostCallFailed, methodInfo.Name);
return new PSRemotingDataStructureException(resourceString);
}
/// <summary>
/// New decoding error for error record exception.
/// </summary>
internal static Exception NewDecodingErrorForErrorRecordException()
{
return new PSRemotingDataStructureException(RemotingErrorIdStrings.DecodingErrorForErrorRecord);
}
/// <summary>
/// New remote host data encoding not supported exception.
/// </summary>
internal static Exception NewRemoteHostDataEncodingNotSupportedException(Type type)
{
Dbg.Assert(type != null, "Expected type != null");
return new PSRemotingDataStructureException(
RemotingErrorIdStrings.RemoteHostDataEncodingNotSupported,
type.ToString());
}
/// <summary>
/// New remote host data decoding not supported exception.
/// </summary>
internal static Exception NewRemoteHostDataDecodingNotSupportedException(Type type)
{
Dbg.Assert(type != null, "Expected type != null");
return new PSRemotingDataStructureException(
RemotingErrorIdStrings.RemoteHostDataDecodingNotSupported,
type.ToString());
}
/// <summary>
/// New unknown target class exception.
/// </summary>
internal static Exception NewUnknownTargetClassException(string className)
{
Dbg.Assert(className != null, "Expected className != null");
return new PSRemotingDataStructureException(RemotingErrorIdStrings.UnknownTargetClass, className);
}
internal static Exception NewNullClientHostException()
{
return new PSRemotingDataStructureException(RemotingErrorIdStrings.RemoteHostNullClientHost);
}
}
}
| |
namespace MVCexample
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.textBox = new System.Windows.Forms.TextBox();
this.button1 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.button3 = new System.Windows.Forms.Button();
this.button4 = new System.Windows.Forms.Button();
this.button5 = new System.Windows.Forms.Button();
this.button6 = new System.Windows.Forms.Button();
this.button7 = new System.Windows.Forms.Button();
this.button8 = new System.Windows.Forms.Button();
this.button9 = new System.Windows.Forms.Button();
this.button0 = new System.Windows.Forms.Button();
this.buttonClear = new System.Windows.Forms.Button();
this.buttonAdd = new System.Windows.Forms.Button();
this.buttonSubtract = new System.Windows.Forms.Button();
this.buttonEquals = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// textBox
//
this.textBox.Location = new System.Drawing.Point(13, 13);
this.textBox.Name = "textBox";
this.textBox.Size = new System.Drawing.Size(267, 20);
this.textBox.TabIndex = 0;
this.textBox.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
//
// button1
//
this.button1.Location = new System.Drawing.Point(24, 53);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 1;
this.button1.Text = "1";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// button2
//
this.button2.Location = new System.Drawing.Point(106, 53);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(75, 23);
this.button2.TabIndex = 2;
this.button2.Text = "2";
this.button2.UseVisualStyleBackColor = true;
this.button2.Click += new System.EventHandler(this.button2_Click);
//
// button3
//
this.button3.Location = new System.Drawing.Point(188, 53);
this.button3.Name = "button3";
this.button3.Size = new System.Drawing.Size(75, 23);
this.button3.TabIndex = 3;
this.button3.Text = "3";
this.button3.UseVisualStyleBackColor = true;
this.button3.Click += new System.EventHandler(this.button3_Click);
//
// button4
//
this.button4.Location = new System.Drawing.Point(24, 83);
this.button4.Name = "button4";
this.button4.Size = new System.Drawing.Size(75, 23);
this.button4.TabIndex = 4;
this.button4.Text = "4";
this.button4.UseVisualStyleBackColor = true;
this.button4.Click += new System.EventHandler(this.button4_Click);
//
// button5
//
this.button5.Location = new System.Drawing.Point(106, 83);
this.button5.Name = "button5";
this.button5.Size = new System.Drawing.Size(75, 23);
this.button5.TabIndex = 5;
this.button5.Text = "5";
this.button5.UseVisualStyleBackColor = true;
this.button5.Click += new System.EventHandler(this.button5_Click);
//
// button6
//
this.button6.Location = new System.Drawing.Point(188, 83);
this.button6.Name = "button6";
this.button6.Size = new System.Drawing.Size(75, 23);
this.button6.TabIndex = 6;
this.button6.Text = "6";
this.button6.UseVisualStyleBackColor = true;
this.button6.Click += new System.EventHandler(this.button6_Click);
//
// button7
//
this.button7.Location = new System.Drawing.Point(24, 113);
this.button7.Name = "button7";
this.button7.Size = new System.Drawing.Size(75, 23);
this.button7.TabIndex = 7;
this.button7.Text = "7";
this.button7.UseVisualStyleBackColor = true;
this.button7.Click += new System.EventHandler(this.button7_Click);
//
// button8
//
this.button8.Location = new System.Drawing.Point(106, 113);
this.button8.Name = "button8";
this.button8.Size = new System.Drawing.Size(75, 23);
this.button8.TabIndex = 8;
this.button8.Text = "8";
this.button8.UseVisualStyleBackColor = true;
this.button8.Click += new System.EventHandler(this.button8_Click);
//
// button9
//
this.button9.Location = new System.Drawing.Point(188, 113);
this.button9.Name = "button9";
this.button9.Size = new System.Drawing.Size(75, 23);
this.button9.TabIndex = 9;
this.button9.Text = "9";
this.button9.UseVisualStyleBackColor = true;
this.button9.Click += new System.EventHandler(this.button9_Click);
//
// button0
//
this.button0.Location = new System.Drawing.Point(106, 143);
this.button0.Name = "button0";
this.button0.Size = new System.Drawing.Size(75, 23);
this.button0.TabIndex = 10;
this.button0.Text = "0";
this.button0.UseVisualStyleBackColor = true;
this.button0.Click += new System.EventHandler(this.button0_Click);
//
// buttonClear
//
this.buttonClear.Location = new System.Drawing.Point(188, 143);
this.buttonClear.Name = "buttonClear";
this.buttonClear.Size = new System.Drawing.Size(75, 23);
this.buttonClear.TabIndex = 11;
this.buttonClear.Text = "C";
this.buttonClear.UseVisualStyleBackColor = true;
this.buttonClear.Click += new System.EventHandler(this.buttonClear_Click);
//
// buttonAdd
//
this.buttonAdd.Location = new System.Drawing.Point(24, 185);
this.buttonAdd.Name = "buttonAdd";
this.buttonAdd.Size = new System.Drawing.Size(75, 23);
this.buttonAdd.TabIndex = 12;
this.buttonAdd.Text = "+";
this.buttonAdd.UseVisualStyleBackColor = true;
this.buttonAdd.Click += new System.EventHandler(this.buttonAdd_Click);
//
// buttonSubtract
//
this.buttonSubtract.Location = new System.Drawing.Point(106, 185);
this.buttonSubtract.Name = "buttonSubtract";
this.buttonSubtract.Size = new System.Drawing.Size(75, 23);
this.buttonSubtract.TabIndex = 13;
this.buttonSubtract.Text = "-";
this.buttonSubtract.UseVisualStyleBackColor = true;
this.buttonSubtract.Click += new System.EventHandler(this.buttonSubtract_Click);
//
// buttonEquals
//
this.buttonEquals.Location = new System.Drawing.Point(188, 185);
this.buttonEquals.Name = "buttonEquals";
this.buttonEquals.Size = new System.Drawing.Size(75, 23);
this.buttonEquals.TabIndex = 14;
this.buttonEquals.Text = "=";
this.buttonEquals.UseVisualStyleBackColor = true;
this.buttonEquals.Click += new System.EventHandler(this.buttonEquals_Click);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(292, 229);
this.Controls.Add(this.buttonEquals);
this.Controls.Add(this.buttonSubtract);
this.Controls.Add(this.buttonAdd);
this.Controls.Add(this.buttonClear);
this.Controls.Add(this.button0);
this.Controls.Add(this.button9);
this.Controls.Add(this.button8);
this.Controls.Add(this.button7);
this.Controls.Add(this.button6);
this.Controls.Add(this.button5);
this.Controls.Add(this.button4);
this.Controls.Add(this.button3);
this.Controls.Add(this.button2);
this.Controls.Add(this.button1);
this.Controls.Add(this.textBox);
this.Name = "Form1";
this.Text = "MVCexample";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.TextBox textBox;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.Button button3;
private System.Windows.Forms.Button button4;
private System.Windows.Forms.Button button5;
private System.Windows.Forms.Button button6;
private System.Windows.Forms.Button button7;
private System.Windows.Forms.Button button8;
private System.Windows.Forms.Button button9;
private System.Windows.Forms.Button button0;
private System.Windows.Forms.Button buttonClear;
private System.Windows.Forms.Button buttonAdd;
private System.Windows.Forms.Button buttonSubtract;
private System.Windows.Forms.Button buttonEquals;
}
}
| |
// 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.Collections.Immutable;
using System.Diagnostics;
using System.Reflection.PortableExecutable;
#if SRM
using System.Reflection.Internal;
using BitArithmeticUtilities = System.Reflection.Internal.BitArithmetic;
#else
using Roslyn.Utilities;
#endif
#if SRM
namespace System.Reflection.PortableExecutable
#else
namespace Roslyn.Reflection.PortableExecutable
#endif
{
#if SRM && FUTURE
public
#endif
sealed class PEBuilder
{
// COFF:
public Machine Machine { get; }
public Characteristics ImageCharacteristics { get; set; }
public bool IsDeterministic { get; }
// PE:
public byte MajorLinkerVersion { get; }
public byte MinorLinkerVersion { get; }
public ulong ImageBase { get; }
public int SectionAlignment { get; }
public int FileAlignment { get; }
public ushort MajorOperatingSystemVersion { get; }
public ushort MinorOperatingSystemVersion { get; }
public ushort MajorImageVersion { get; }
public ushort MinorImageVersion { get; }
public ushort MajorSubsystemVersion { get; }
public ushort MinorSubsystemVersion { get; }
public Subsystem Subsystem { get; }
public DllCharacteristics DllCharacteristics { get; }
public ulong SizeOfStackReserve { get; }
public ulong SizeOfStackCommit { get; }
public ulong SizeOfHeapReserve { get; }
public ulong SizeOfHeapCommit { get; }
public Func<BlobBuilder, ContentId> IdProvider { get; }
private readonly List<Section> _sections;
private struct Section
{
public readonly string Name;
public readonly SectionCharacteristics Characteristics;
public readonly Func<PESectionLocation, BlobBuilder> Builder;
public Section(string name, SectionCharacteristics characteristics, Func<PESectionLocation, BlobBuilder> builder)
{
Name = name;
Characteristics = characteristics;
Builder = builder;
}
}
private struct SerializedSection
{
public readonly BlobBuilder Builder;
public readonly string Name;
public readonly SectionCharacteristics Characteristics;
public readonly int RelativeVirtualAddress;
public readonly int SizeOfRawData;
public readonly int PointerToRawData;
public SerializedSection(BlobBuilder builder, string name, SectionCharacteristics characteristics, int relativeVirtualAddress, int sizeOfRawData, int pointerToRawData)
{
Name = name;
Characteristics = characteristics;
Builder = builder;
RelativeVirtualAddress = relativeVirtualAddress;
SizeOfRawData = sizeOfRawData;
PointerToRawData = pointerToRawData;
}
public int VirtualSize => Builder.Count;
}
public PEBuilder(
Machine machine,
int sectionAlignment,
int fileAlignment,
ulong imageBase,
byte majorLinkerVersion,
byte minorLinkerVersion,
ushort majorOperatingSystemVersion,
ushort minorOperatingSystemVersion,
ushort majorImageVersion,
ushort minorImageVersion,
ushort majorSubsystemVersion,
ushort minorSubsystemVersion,
Subsystem subsystem,
DllCharacteristics dllCharacteristics,
Characteristics imageCharacteristics,
ulong sizeOfStackReserve,
ulong sizeOfStackCommit,
ulong sizeOfHeapReserve,
ulong sizeOfHeapCommit,
Func<BlobBuilder, ContentId> deterministicIdProvider = null)
{
Machine = machine;
SectionAlignment = sectionAlignment;
FileAlignment = fileAlignment;
ImageBase = imageBase;
MajorLinkerVersion = majorLinkerVersion;
MinorLinkerVersion = minorLinkerVersion;
MajorOperatingSystemVersion = majorOperatingSystemVersion;
MinorOperatingSystemVersion = minorOperatingSystemVersion;
MajorImageVersion = majorImageVersion;
MinorImageVersion = minorImageVersion;
MajorSubsystemVersion = majorSubsystemVersion;
MinorSubsystemVersion = minorSubsystemVersion;
Subsystem = subsystem;
DllCharacteristics = dllCharacteristics;
ImageCharacteristics = imageCharacteristics;
SizeOfStackReserve = sizeOfStackReserve;
SizeOfStackCommit = sizeOfStackCommit;
SizeOfHeapReserve = sizeOfHeapReserve;
SizeOfHeapCommit = sizeOfHeapCommit;
IsDeterministic = deterministicIdProvider != null;
IdProvider = deterministicIdProvider ?? GetCurrentTimeBasedIdProvider();
_sections = new List<Section>();
}
private static Func<BlobBuilder, ContentId> GetCurrentTimeBasedIdProvider()
{
// In the PE File Header this is a "Time/Date Stamp" whose description is "Time and date
// the file was created in seconds since January 1st 1970 00:00:00 or 0"
// However, when we want to make it deterministic we fill it in (later) with bits from the hash of the full PE file.
int timestamp = (int)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds;
return content => new ContentId(Guid.NewGuid(), timestamp);
}
private bool Is32Bit => Machine != Machine.Amd64 && Machine != Machine.IA64;
public void AddSection(string name, SectionCharacteristics characteristics, Func<PESectionLocation, BlobBuilder> builder)
{
_sections.Add(new Section(name, characteristics, builder));
}
public void Serialize(BlobBuilder builder, PEDirectoriesBuilder headers, out ContentId contentId)
{
var serializedSections = SerializeSections();
Blob stampFixup;
WritePESignature(builder);
WriteCoffHeader(builder, serializedSections, out stampFixup);
WritePEHeader(builder, headers, serializedSections);
WriteSectionHeaders(builder, serializedSections);
builder.Align(FileAlignment);
foreach (var section in serializedSections)
{
builder.LinkSuffix(section.Builder);
builder.Align(FileAlignment);
}
contentId = IdProvider(builder);
// patch timestamp in COFF header:
var stampWriter = new BlobWriter(stampFixup);
stampWriter.WriteBytes(contentId.Stamp);
Debug.Assert(stampWriter.RemainingBytes == 0);
}
private ImmutableArray<SerializedSection> SerializeSections()
{
var result = ImmutableArray.CreateBuilder<SerializedSection>(_sections.Count);
int sizeOfPeHeaders = ComputeSizeOfPeHeaders(_sections.Count, Is32Bit);
var nextRva = BitArithmeticUtilities.Align(sizeOfPeHeaders, SectionAlignment);
var nextPointer = BitArithmeticUtilities.Align(sizeOfPeHeaders, FileAlignment);
foreach (var section in _sections)
{
var builder = section.Builder(new PESectionLocation(nextRva, nextPointer));
var serialized = new SerializedSection(
builder,
section.Name,
section.Characteristics,
relativeVirtualAddress: nextRva,
sizeOfRawData: BitArithmeticUtilities.Align(builder.Count, FileAlignment),
pointerToRawData: nextPointer);
result.Add(serialized);
nextRva = BitArithmeticUtilities.Align(serialized.RelativeVirtualAddress + serialized.VirtualSize, SectionAlignment);
nextPointer = serialized.PointerToRawData + serialized.SizeOfRawData;
}
return result.MoveToImmutable();
}
private static int ComputeSizeOfPeHeaders(int sectionCount, bool is32Bit)
{
// TODO: constants
int sizeOfPeHeaders = 128 + 4 + 20 + 224 + 40 * sectionCount;
if (!is32Bit)
{
sizeOfPeHeaders += 16;
}
return sizeOfPeHeaders;
}
private void WritePESignature(BlobBuilder builder)
{
// MS-DOS stub (128 bytes)
builder.WriteBytes(s_dosHeader);
// PE Signature "PE\0\0"
builder.WriteUInt32(0x00004550);
}
private static readonly byte[] s_dosHeader = new byte[]
{
0x4d, 0x5a, 0x90, 0x00, 0x03, 0x00, 0x00, 0x00,
0x04, 0x00, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00,
0xb8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00,
0x0e, 0x1f, 0xba, 0x0e, 0x00, 0xb4, 0x09, 0xcd,
0x21, 0xb8, 0x01, 0x4c, 0xcd, 0x21, 0x54, 0x68,
0x69, 0x73, 0x20, 0x70, 0x72, 0x6f, 0x67, 0x72,
0x61, 0x6d, 0x20, 0x63, 0x61, 0x6e, 0x6e, 0x6f,
0x74, 0x20, 0x62, 0x65, 0x20, 0x72, 0x75, 0x6e,
0x20, 0x69, 0x6e, 0x20, 0x44, 0x4f, 0x53, 0x20,
0x6d, 0x6f, 0x64, 0x65, 0x2e, 0x0d, 0x0d, 0x0a,
0x24, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
private void WriteCoffHeader(BlobBuilder builder, ImmutableArray<SerializedSection> sections, out Blob stampFixup)
{
// Machine
builder.WriteUInt16((ushort)(Machine == 0 ? Machine.I386 : Machine));
// NumberOfSections
builder.WriteUInt16((ushort)sections.Length);
// TimeDateStamp:
stampFixup = builder.ReserveBytes(sizeof(uint));
// PointerToSymbolTable (TODO: not supported):
// The file pointer to the COFF symbol table, or zero if no COFF symbol table is present.
// This value should be zero for a PE image.
builder.WriteUInt32(0);
// NumberOfSymbols (TODO: not supported):
// The number of entries in the symbol table. This data can be used to locate the string table,
// which immediately follows the symbol table. This value should be zero for a PE image.
builder.WriteUInt32(0);
// SizeOfOptionalHeader:
// The size of the optional header, which is required for executable files but not for object files.
// This value should be zero for an object file (TODO).
builder.WriteUInt16((ushort)(Is32Bit ? 224 : 240));
// Characteristics
builder.WriteUInt16((ushort)ImageCharacteristics);
}
private void WritePEHeader(BlobBuilder builder, PEDirectoriesBuilder headers, ImmutableArray<SerializedSection> sections)
{
builder.WriteUInt16((ushort)(Is32Bit ? PEMagic.PE32 : PEMagic.PE32Plus));
builder.WriteByte(MajorLinkerVersion);
builder.WriteByte(MinorLinkerVersion);
// SizeOfCode:
builder.WriteUInt32((uint)SumRawDataSizes(sections, SectionCharacteristics.ContainsCode));
// SizeOfInitializedData:
builder.WriteUInt32((uint)SumRawDataSizes(sections, SectionCharacteristics.ContainsInitializedData));
// SizeOfUninitializedData:
builder.WriteUInt32((uint)SumRawDataSizes(sections, SectionCharacteristics.ContainsUninitializedData));
// AddressOfEntryPoint:
builder.WriteUInt32((uint)headers.AddressOfEntryPoint);
// BaseOfCode:
int codeSectionIndex = IndexOfSection(sections, SectionCharacteristics.ContainsCode);
builder.WriteUInt32((uint)(codeSectionIndex != -1 ? sections[codeSectionIndex].RelativeVirtualAddress : 0));
if (Is32Bit)
{
// BaseOfData:
int dataSectionIndex = IndexOfSection(sections, SectionCharacteristics.ContainsInitializedData);
builder.WriteUInt32((uint)(dataSectionIndex != -1 ? sections[dataSectionIndex].RelativeVirtualAddress : 0));
builder.WriteUInt32((uint)ImageBase);
}
else
{
builder.WriteUInt64(ImageBase);
}
// NT additional fields:
builder.WriteUInt32((uint)SectionAlignment);
builder.WriteUInt32((uint)FileAlignment);
builder.WriteUInt16(MajorOperatingSystemVersion);
builder.WriteUInt16(MinorOperatingSystemVersion);
builder.WriteUInt16(MajorImageVersion);
builder.WriteUInt16(MinorImageVersion);
builder.WriteUInt16(MajorSubsystemVersion);
builder.WriteUInt16(MinorSubsystemVersion);
// Win32VersionValue (reserved, should be 0)
builder.WriteUInt32(0);
// SizeOfImage:
var lastSection = sections[sections.Length - 1];
builder.WriteUInt32((uint)BitArithmeticUtilities.Align(lastSection.RelativeVirtualAddress + lastSection.VirtualSize, SectionAlignment));
// SizeOfHeaders:
builder.WriteUInt32((uint)BitArithmeticUtilities.Align(ComputeSizeOfPeHeaders(sections.Length, Is32Bit), FileAlignment));
// Checksum (TODO: not supported):
builder.WriteUInt32(0);
builder.WriteUInt16((ushort)Subsystem);
builder.WriteUInt16((ushort)DllCharacteristics);
if (Is32Bit)
{
builder.WriteUInt32((uint)SizeOfStackReserve);
builder.WriteUInt32((uint)SizeOfStackCommit);
builder.WriteUInt32((uint)SizeOfHeapReserve);
builder.WriteUInt32((uint)SizeOfHeapCommit);
}
else
{
builder.WriteUInt64(SizeOfStackReserve);
builder.WriteUInt64(SizeOfStackCommit);
builder.WriteUInt64(SizeOfHeapReserve);
builder.WriteUInt64(SizeOfHeapCommit);
}
// LoaderFlags
builder.WriteUInt32(0);
// The number of data-directory entries in the remainder of the header.
builder.WriteUInt32(16);
// directory entries:
builder.WriteUInt32((uint)headers.ExportTable.RelativeVirtualAddress);
builder.WriteUInt32((uint)headers.ExportTable.Size);
builder.WriteUInt32((uint)headers.ImportTable.RelativeVirtualAddress);
builder.WriteUInt32((uint)headers.ImportTable.Size);
builder.WriteUInt32((uint)headers.ResourceTable.RelativeVirtualAddress);
builder.WriteUInt32((uint)headers.ResourceTable.Size);
builder.WriteUInt32((uint)headers.ExceptionTable.RelativeVirtualAddress);
builder.WriteUInt32((uint)headers.ExceptionTable.Size);
builder.WriteUInt32((uint)headers.CertificateTable.RelativeVirtualAddress);
builder.WriteUInt32((uint)headers.CertificateTable.Size);
builder.WriteUInt32((uint)headers.BaseRelocationTable.RelativeVirtualAddress);
builder.WriteUInt32((uint)headers.BaseRelocationTable.Size);
builder.WriteUInt32((uint)headers.DebugTable.RelativeVirtualAddress);
builder.WriteUInt32((uint)headers.DebugTable.Size);
builder.WriteUInt32((uint)headers.CopyrightTable.RelativeVirtualAddress);
builder.WriteUInt32((uint)headers.CopyrightTable.Size);
builder.WriteUInt32((uint)headers.GlobalPointerTable.RelativeVirtualAddress);
builder.WriteUInt32((uint)headers.GlobalPointerTable.Size);
builder.WriteUInt32((uint)headers.ThreadLocalStorageTable.RelativeVirtualAddress);
builder.WriteUInt32((uint)headers.ThreadLocalStorageTable.Size);
builder.WriteUInt32((uint)headers.LoadConfigTable.RelativeVirtualAddress);
builder.WriteUInt32((uint)headers.LoadConfigTable.Size);
builder.WriteUInt32((uint)headers.BoundImportTable.RelativeVirtualAddress);
builder.WriteUInt32((uint)headers.BoundImportTable.Size);
builder.WriteUInt32((uint)headers.ImportAddressTable.RelativeVirtualAddress);
builder.WriteUInt32((uint)headers.ImportAddressTable.Size);
builder.WriteUInt32((uint)headers.DelayImportTable.RelativeVirtualAddress);
builder.WriteUInt32((uint)headers.DelayImportTable.Size);
builder.WriteUInt32((uint)headers.CorHeaderTable.RelativeVirtualAddress);
builder.WriteUInt32((uint)headers.CorHeaderTable.Size);
// Reserved, should be 0
builder.WriteUInt64(0);
}
private void WriteSectionHeaders(BlobBuilder builder, ImmutableArray<SerializedSection> serializedSections)
{
for (int i = 0; i < serializedSections.Length; i++)
{
WriteSectionHeader(builder, _sections[i], serializedSections[i]);
}
}
private static void WriteSectionHeader(BlobBuilder builder, Section section, SerializedSection serializedSection)
{
if (serializedSection.VirtualSize == 0)
{
return;
}
for (int j = 0, m = section.Name.Length; j < 8; j++)
{
if (j < m)
{
builder.WriteByte((byte)section.Name[j]);
}
else
{
builder.WriteByte(0);
}
}
builder.WriteUInt32((uint)serializedSection.VirtualSize);
builder.WriteUInt32((uint)serializedSection.RelativeVirtualAddress);
builder.WriteUInt32((uint)serializedSection.SizeOfRawData);
builder.WriteUInt32((uint)serializedSection.PointerToRawData);
// PointerToRelocations (TODO: not supported):
builder.WriteUInt32(0);
// PointerToLinenumbers (TODO: not supported):
builder.WriteUInt32(0);
// NumberOfRelocations (TODO: not supported):
builder.WriteUInt16(0);
// NumberOfLinenumbers (TODO: not supported):
builder.WriteUInt16(0);
builder.WriteUInt32((uint)section.Characteristics);
}
private static int IndexOfSection(ImmutableArray<SerializedSection> sections, SectionCharacteristics characteristics)
{
for (int i = 0; i < sections.Length; i++)
{
if ((sections[i].Characteristics & characteristics) == characteristics)
{
return i;
}
}
return -1;
}
private static int SumRawDataSizes(ImmutableArray<SerializedSection> sections,SectionCharacteristics characteristics)
{
int result = 0;
for (int i = 0; i < sections.Length; i++)
{
if ((sections[i].Characteristics & characteristics) == characteristics)
{
result += sections[i].SizeOfRawData;
}
}
return result;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
/// <summary>
/// System.Decimal.Compare(Decimal,Decimal)
/// </summary>
public class DecimalCompare
{
public static int Main()
{
DecimalCompare dCompare = new DecimalCompare();
TestLibrary.TestFramework.BeginTestCase("for Method:System.Decimal.DecimalCompare(Decimal,Decimal)");
if (dCompare.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
retVal = PosTest5() && retVal;
retVal = PosTest6() && retVal;
retVal = PosTest7() && retVal;
return retVal;
}
#region PositiveTesting
public bool PosTest1()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest1:Verify two decimal both are plus...";
const string c_TEST_ID = "P001";
Decimal dec1 = 12345.678m;
Decimal dec2 = 87654.321m;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
int result = Decimal.Compare(dec1, dec2);
if (result>0)
{
string errorDesc = "Value is not less than zero as expected: Actual (" + result.ToString()+")";
errorDesc += GetDataString(dec1, dec2);
TestLibrary.TestFramework.LogError("001" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002" + " TestId-" + c_TEST_ID + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(dec1, dec2));
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest2:Verify two decimal are equal...";
const string c_TEST_ID = "P002";
Decimal dec1 = 623512345.678m;
Decimal dec2 = 623512345.678m;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
int result = Decimal.Compare(dec1, dec2); ;
if (result != 0)
{
string errorDesc = "Value is not zero as expected: Actual (" + result.ToString()+")";
errorDesc += GetDataString(dec1, dec2);
TestLibrary.TestFramework.LogError("003" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004" + " TestId-" + c_TEST_ID + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(dec1, dec2));
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest3:Verify a decimal is negative...";
const string c_TEST_ID = "P003";
Decimal dec1 = 87654.321234m;
Decimal dec2 = -12345.678321m;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
int result = Decimal.Compare(dec1, dec2); ;
if (result < 0)
{
string errorDesc = "Value is not greater than zero as expected: Actual (" + result.ToString() + ")";
errorDesc += GetDataString(dec1, dec2);
TestLibrary.TestFramework.LogError("005" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006" + " TestId-" + c_TEST_ID + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(dec1, dec2));
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest4:Verify two decimal both are negative...";
const string c_TEST_ID = "P004";
Decimal dec1 = -87654.321234m;
Decimal dec2 = -12345.678321m;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
int result = Decimal.Compare(dec1, dec2); ;
if (result >0)
{
string errorDesc = "Value is not less than zero as expected: Actual (" + result.ToString() + ")";
errorDesc += GetDataString(dec1, dec2);
TestLibrary.TestFramework.LogError("007" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008" + " TestId-" + c_TEST_ID + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(dec1, dec2));
retVal = false;
}
return retVal;
}
public bool PosTest5()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest5:Verify a decimal is zero...";
const string c_TEST_ID = "P005";
Decimal dec1 = -87654.321234m;
Decimal dec2 = 0m;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
int result = Decimal.Compare(dec1, dec2);
if (result > 0)
{
string errorDesc = "Value is not less than zero as expected: Actual (" + result.ToString() + ")";
errorDesc += GetDataString(dec1, dec2);
TestLibrary.TestFramework.LogError("009" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("010" + " TestId-" + c_TEST_ID + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(dec1, dec2));
retVal = false;
}
return retVal;
}
public bool PosTest6()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest6:Verify a decimal is Decimal.MinValue...";
const string c_TEST_ID = "P006";
Decimal dec1 = -87654.321234m;
Decimal dec2 = Decimal.MinValue;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
int result = Decimal.Compare(dec1, dec2);
if (result < 0)
{
string errorDesc = "Value is not greater than zero as expected: Actual (" + result.ToString() + ")";
errorDesc += GetDataString(dec1, dec2);
TestLibrary.TestFramework.LogError("011" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("012" + " TestId-" + c_TEST_ID + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(dec1, dec2));
retVal = false;
}
return retVal;
}
public bool PosTest7()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest7:Verify a decimal is Decimal.MaxValue...";
const string c_TEST_ID = "P007";
Decimal dec1 = 87654.321234m;
Decimal dec2 = Decimal.MaxValue;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
int result = Decimal.Compare(dec1, dec2);
if (result > 0)
{
string errorDesc = "Value is not less than zero as expected: Actual (" + result.ToString() + ")";
errorDesc += GetDataString(dec1, dec2);
TestLibrary.TestFramework.LogError("013" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("014" + " TestId-" + c_TEST_ID + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(dec1, dec2));
retVal = false;
}
return retVal;
}
#endregion
#region Helper methords for testing
private string GetDataString(Decimal dec1, Decimal dec2)
{
string str;
str = string.Format("\n[decimal1 value]\n {0}", dec1.ToString());
str += string.Format("\n[decimal2 value]\n {0}", dec2.ToString());
return str;
}
#endregion
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using log4net;
using Mono.Addins;
using Nini.Config;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using PresenceInfo = OpenSim.Services.Interfaces.PresenceInfo;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
namespace OpenSim.Groups
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "GroupsMessagingModule")]
public class GroupsMessagingModule : ISharedRegionModule, IGroupsMessagingModule
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private List<Scene> m_sceneList = new List<Scene>();
private IPresenceService m_presenceService;
private IMessageTransferModule m_msgTransferModule = null;
private IUserManagement m_UserManagement = null;
private IGroupsServicesConnector m_groupData = null;
// Config Options
private bool m_groupMessagingEnabled = false;
private bool m_debugEnabled = true;
/// <summary>
/// If enabled, module only tries to send group IMs to online users by querying cached presence information.
/// </summary>
private bool m_messageOnlineAgentsOnly;
/// <summary>
/// Cache for online users.
/// </summary>
/// <remarks>
/// Group ID is key, presence information for online members is value.
/// Will only be non-null if m_messageOnlineAgentsOnly = true
/// We cache here so that group messages don't constantly have to re-request the online user list to avoid
/// attempted expensive sending of messages to offline users.
/// The tradeoff is that a user that comes online will not receive messages consistently from all other users
/// until caches have updated.
/// Therefore, we set the cache expiry to just 20 seconds.
/// </remarks>
private ExpiringCache<UUID, PresenceInfo[]> m_usersOnlineCache;
private int m_usersOnlineCacheExpirySeconds = 20;
private Dictionary<UUID, List<string>> m_groupsAgentsDroppedFromChatSession = new Dictionary<UUID, List<string>>();
private Dictionary<UUID, List<string>> m_groupsAgentsInvitedToChatSession = new Dictionary<UUID, List<string>>();
#region Region Module interfaceBase Members
public void Initialise(IConfigSource config)
{
IConfig groupsConfig = config.Configs["Groups"];
if (groupsConfig == null)
// Do not run this module by default.
return;
// if groups aren't enabled, we're not needed.
// if we're not specified as the connector to use, then we're not wanted
if ((groupsConfig.GetBoolean("Enabled", false) == false)
|| (groupsConfig.GetString("MessagingModule", "") != Name))
{
m_groupMessagingEnabled = false;
return;
}
m_groupMessagingEnabled = groupsConfig.GetBoolean("MessagingEnabled", true);
if (!m_groupMessagingEnabled)
return;
m_messageOnlineAgentsOnly = groupsConfig.GetBoolean("MessageOnlineUsersOnly", false);
if (m_messageOnlineAgentsOnly)
m_usersOnlineCache = new ExpiringCache<UUID, PresenceInfo[]>();
m_debugEnabled = groupsConfig.GetBoolean("DebugEnabled", true);
m_log.InfoFormat(
"[Groups.Messaging]: GroupsMessagingModule enabled with MessageOnlineOnly = {0}, DebugEnabled = {1}",
m_messageOnlineAgentsOnly, m_debugEnabled);
}
public void AddRegion(Scene scene)
{
if (!m_groupMessagingEnabled)
return;
scene.RegisterModuleInterface<IGroupsMessagingModule>(this);
m_sceneList.Add(scene);
scene.EventManager.OnNewClient += OnNewClient;
scene.EventManager.OnMakeRootAgent += OnMakeRootAgent;
scene.EventManager.OnMakeChildAgent += OnMakeChildAgent;
scene.EventManager.OnIncomingInstantMessage += OnGridInstantMessage;
scene.EventManager.OnClientLogin += OnClientLogin;
}
public void RegionLoaded(Scene scene)
{
if (!m_groupMessagingEnabled)
return;
if (m_debugEnabled) m_log.DebugFormat("[Groups.Messaging]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
m_groupData = scene.RequestModuleInterface<IGroupsServicesConnector>();
// No groups module, no groups messaging
if (m_groupData == null)
{
m_log.Error("[Groups.Messaging]: Could not get IGroupsServicesConnector, GroupsMessagingModule is now disabled.");
RemoveRegion(scene);
return;
}
m_msgTransferModule = scene.RequestModuleInterface<IMessageTransferModule>();
// No message transfer module, no groups messaging
if (m_msgTransferModule == null)
{
m_log.Error("[Groups.Messaging]: Could not get MessageTransferModule");
RemoveRegion(scene);
return;
}
m_UserManagement = scene.RequestModuleInterface<IUserManagement>();
// No groups module, no groups messaging
if (m_UserManagement == null)
{
m_log.Error("[Groups.Messaging]: Could not get IUserManagement, GroupsMessagingModule is now disabled.");
RemoveRegion(scene);
return;
}
if (m_presenceService == null)
m_presenceService = scene.PresenceService;
}
public void RemoveRegion(Scene scene)
{
if (!m_groupMessagingEnabled)
return;
if (m_debugEnabled) m_log.DebugFormat("[Groups.Messaging]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
m_sceneList.Remove(scene);
scene.EventManager.OnNewClient -= OnNewClient;
scene.EventManager.OnIncomingInstantMessage -= OnGridInstantMessage;
scene.EventManager.OnClientLogin -= OnClientLogin;
scene.UnregisterModuleInterface<IGroupsMessagingModule>(this);
}
public void Close()
{
if (!m_groupMessagingEnabled)
return;
if (m_debugEnabled) m_log.Debug("[Groups.Messaging]: Shutting down GroupsMessagingModule module.");
m_sceneList.Clear();
m_groupData = null;
m_msgTransferModule = null;
}
public Type ReplaceableInterface
{
get { return null; }
}
public string Name
{
get { return "Groups Messaging Module V2"; }
}
public void PostInitialise()
{
// NoOp
}
#endregion
/// <summary>
/// Not really needed, but does confirm that the group exists.
/// </summary>
public bool StartGroupChatSession(UUID agentID, UUID groupID)
{
if (m_debugEnabled)
m_log.DebugFormat("[Groups.Messaging]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
GroupRecord groupInfo = m_groupData.GetGroupRecord(agentID.ToString(), groupID, null);
if (groupInfo != null)
{
return true;
}
else
{
return false;
}
}
public void SendMessageToGroup(GridInstantMessage im, UUID groupID)
{
UUID fromAgentID = new UUID(im.fromAgentID);
List<GroupMembersData> groupMembers = m_groupData.GetGroupMembers(UUID.Zero.ToString(), groupID);
int groupMembersCount = groupMembers.Count;
PresenceInfo[] onlineAgents = null;
// In V2 we always only send to online members.
// Sending to offline members is not an option.
string[] t1 = groupMembers.ConvertAll<string>(gmd => gmd.AgentID.ToString()).ToArray();
// We cache in order not to overwhlem the presence service on large grids with many groups. This does
// mean that members coming online will not see all group members until after m_usersOnlineCacheExpirySeconds has elapsed.
// (assuming this is the same across all grid simulators).
if (!m_usersOnlineCache.TryGetValue(groupID, out onlineAgents))
{
onlineAgents = m_presenceService.GetAgents(t1);
m_usersOnlineCache.Add(groupID, onlineAgents, m_usersOnlineCacheExpirySeconds);
}
HashSet<string> onlineAgentsUuidSet = new HashSet<string>();
Array.ForEach<PresenceInfo>(onlineAgents, pi => onlineAgentsUuidSet.Add(pi.UserID));
groupMembers = groupMembers.Where(gmd => onlineAgentsUuidSet.Contains(gmd.AgentID.ToString())).ToList();
// if (m_debugEnabled)
// m_log.DebugFormat(
// "[Groups.Messaging]: SendMessageToGroup called for group {0} with {1} visible members, {2} online",
// groupID, groupMembersCount, groupMembers.Count());
int requestStartTick = Environment.TickCount;
im.imSessionID = groupID.Guid;
im.fromGroup = true;
IClientAPI thisClient = GetActiveClient(fromAgentID);
if (thisClient != null)
{
im.RegionID = thisClient.Scene.RegionInfo.RegionID.Guid;
}
// Send to self first of all
im.toAgentID = im.fromAgentID;
im.fromGroup = true;
ProcessMessageFromGroupSession(im);
List<UUID> regions = new List<UUID>();
List<UUID> clientsAlreadySent = new List<UUID>();
// Then send to everybody else
foreach (GroupMembersData member in groupMembers)
{
if (member.AgentID.Guid == im.fromAgentID)
continue;
if (clientsAlreadySent.Contains(member.AgentID))
continue;
clientsAlreadySent.Add(member.AgentID);
if (hasAgentDroppedGroupChatSession(member.AgentID.ToString(), groupID))
{
// Don't deliver messages to people who have dropped this session
if (m_debugEnabled) m_log.DebugFormat("[Groups.Messaging]: {0} has dropped session, not delivering to them", member.AgentID);
continue;
}
im.toAgentID = member.AgentID.Guid;
IClientAPI client = GetActiveClient(member.AgentID);
if (client == null)
{
// If they're not local, forward across the grid
// BUT do it only once per region, please! Sim would be even better!
if (m_debugEnabled) m_log.DebugFormat("[Groups.Messaging]: Delivering to {0} via Grid", member.AgentID);
bool reallySend = true;
if (onlineAgents != null)
{
PresenceInfo presence = onlineAgents.First(p => p.UserID == member.AgentID.ToString());
if (regions.Contains(presence.RegionID))
reallySend = false;
else
regions.Add(presence.RegionID);
}
if (reallySend)
{
// We have to create a new IM structure because the transfer module
// uses async send
GridInstantMessage msg = new GridInstantMessage(im, true);
m_msgTransferModule.SendInstantMessage(msg, delegate(bool success) { });
}
}
else
{
// Deliver locally, directly
if (m_debugEnabled) m_log.DebugFormat("[Groups.Messaging]: Passing to ProcessMessageFromGroupSession to deliver to {0} locally", client.Name);
ProcessMessageFromGroupSession(im);
}
}
if (m_debugEnabled)
m_log.DebugFormat(
"[Groups.Messaging]: SendMessageToGroup for group {0} with {1} visible members, {2} online took {3}ms",
groupID, groupMembersCount, groupMembers.Count(), Environment.TickCount - requestStartTick);
}
#region SimGridEventHandlers
void OnClientLogin(IClientAPI client)
{
if (m_debugEnabled) m_log.DebugFormat("[Groups.Messaging]: OnInstantMessage registered for {0}", client.Name);
}
private void OnNewClient(IClientAPI client)
{
if (m_debugEnabled) m_log.DebugFormat("[Groups.Messaging]: OnInstantMessage registered for {0}", client.Name);
ResetAgentGroupChatSessions(client.AgentId.ToString());
}
void OnMakeRootAgent(ScenePresence sp)
{
sp.ControllingClient.OnInstantMessage += OnInstantMessage;
}
void OnMakeChildAgent(ScenePresence sp)
{
sp.ControllingClient.OnInstantMessage -= OnInstantMessage;
}
private void OnGridInstantMessage(GridInstantMessage msg)
{
// The instant message module will only deliver messages of dialog types:
// MessageFromAgent, StartTyping, StopTyping, MessageFromObject
//
// Any other message type will not be delivered to a client by the
// Instant Message Module
UUID regionID = new UUID(msg.RegionID);
if (m_debugEnabled)
{
m_log.DebugFormat("[Groups.Messaging]: {0} called, IM from region {1}",
System.Reflection.MethodBase.GetCurrentMethod().Name, regionID);
DebugGridInstantMessage(msg);
}
// Incoming message from a group
if ((msg.fromGroup == true) && (msg.dialog == (byte)InstantMessageDialog.SessionSend))
{
// We have to redistribute the message across all members of the group who are here
// on this sim
UUID GroupID = new UUID(msg.imSessionID);
Scene aScene = m_sceneList[0];
GridRegion regionOfOrigin = aScene.GridService.GetRegionByUUID(aScene.RegionInfo.ScopeID, regionID);
List<GroupMembersData> groupMembers = m_groupData.GetGroupMembers(UUID.Zero.ToString(), GroupID);
//if (m_debugEnabled)
// foreach (GroupMembersData m in groupMembers)
// m_log.DebugFormat("[Groups.Messaging]: member {0}", m.AgentID);
foreach (Scene s in m_sceneList)
{
s.ForEachScenePresence(sp =>
{
// If we got this via grid messaging, it's because the caller thinks
// that the root agent is here. We should only send the IM to root agents.
if (sp.IsChildAgent)
return;
GroupMembersData m = groupMembers.Find(gmd =>
{
return gmd.AgentID == sp.UUID;
});
if (m.AgentID == UUID.Zero)
{
if (m_debugEnabled)
m_log.DebugFormat("[Groups.Messaging]: skipping agent {0} because he is not a member of the group", sp.UUID);
return;
}
// Check if the user has an agent in the region where
// the IM came from, and if so, skip it, because the IM
// was already sent via that agent
if (regionOfOrigin != null)
{
AgentCircuitData aCircuit = s.AuthenticateHandler.GetAgentCircuitData(sp.UUID);
if (aCircuit != null)
{
if (aCircuit.ChildrenCapSeeds.Keys.Contains(regionOfOrigin.RegionHandle))
{
if (m_debugEnabled)
m_log.DebugFormat("[Groups.Messaging]: skipping agent {0} because he has an agent in region of origin", sp.UUID);
return;
}
else
{
if (m_debugEnabled)
m_log.DebugFormat("[Groups.Messaging]: not skipping agent {0}", sp.UUID);
}
}
}
UUID AgentID = sp.UUID;
msg.toAgentID = AgentID.Guid;
if (!hasAgentDroppedGroupChatSession(AgentID.ToString(), GroupID))
{
if (!hasAgentBeenInvitedToGroupChatSession(AgentID.ToString(), GroupID))
AddAgentToSession(AgentID, GroupID, msg);
else
{
if (m_debugEnabled) m_log.DebugFormat("[Groups.Messaging]: Passing to ProcessMessageFromGroupSession to deliver to {0} locally", sp.Name);
ProcessMessageFromGroupSession(msg);
}
}
});
}
}
}
private void ProcessMessageFromGroupSession(GridInstantMessage msg)
{
if (m_debugEnabled) m_log.DebugFormat("[Groups.Messaging]: Session message from {0} going to agent {1}", msg.fromAgentName, msg.toAgentID);
UUID AgentID = new UUID(msg.fromAgentID);
UUID GroupID = new UUID(msg.imSessionID);
UUID toAgentID = new UUID(msg.toAgentID);
switch (msg.dialog)
{
case (byte)InstantMessageDialog.SessionAdd:
AgentInvitedToGroupChatSession(AgentID.ToString(), GroupID);
break;
case (byte)InstantMessageDialog.SessionDrop:
AgentDroppedFromGroupChatSession(AgentID.ToString(), GroupID);
break;
case (byte)InstantMessageDialog.SessionSend:
// User hasn't dropped, so they're in the session,
// maybe we should deliver it.
IClientAPI client = GetActiveClient(new UUID(msg.toAgentID));
if (client != null)
{
// Deliver locally, directly
if (m_debugEnabled) m_log.DebugFormat("[Groups.Messaging]: Delivering to {0} locally", client.Name);
if (!hasAgentDroppedGroupChatSession(toAgentID.ToString(), GroupID))
{
if (!hasAgentBeenInvitedToGroupChatSession(toAgentID.ToString(), GroupID))
// This actually sends the message too, so no need to resend it
// with client.SendInstantMessage
AddAgentToSession(toAgentID, GroupID, msg);
else
client.SendInstantMessage(msg);
}
}
else
{
m_log.WarnFormat("[Groups.Messaging]: Received a message over the grid for a client that isn't here: {0}", msg.toAgentID);
}
break;
default:
m_log.WarnFormat("[Groups.Messaging]: I don't know how to proccess a {0} message.", ((InstantMessageDialog)msg.dialog).ToString());
break;
}
}
private void AddAgentToSession(UUID AgentID, UUID GroupID, GridInstantMessage msg)
{
// Agent not in session and hasn't dropped from session
// Add them to the session for now, and Invite them
AgentInvitedToGroupChatSession(AgentID.ToString(), GroupID);
IClientAPI activeClient = GetActiveClient(AgentID);
if (activeClient != null)
{
GroupRecord groupInfo = m_groupData.GetGroupRecord(UUID.Zero.ToString(), GroupID, null);
if (groupInfo != null)
{
if (m_debugEnabled) m_log.DebugFormat("[Groups.Messaging]: Sending chatterbox invite instant message");
// Force? open the group session dialog???
// and simultanously deliver the message, so we don't need to do a seperate client.SendInstantMessage(msg);
IEventQueue eq = activeClient.Scene.RequestModuleInterface<IEventQueue>();
eq.ChatterboxInvitation(
GroupID
, groupInfo.GroupName
, new UUID(msg.fromAgentID)
, msg.message
, AgentID
, msg.fromAgentName
, msg.dialog
, msg.timestamp
, msg.offline == 1
, (int)msg.ParentEstateID
, msg.Position
, 1
, new UUID(msg.imSessionID)
, msg.fromGroup
, OpenMetaverse.Utils.StringToBytes(groupInfo.GroupName)
);
eq.ChatterBoxSessionAgentListUpdates(
new UUID(GroupID)
, AgentID
, new UUID(msg.toAgentID)
, false //canVoiceChat
, false //isModerator
, false //text mute
);
}
}
}
#endregion
#region ClientEvents
private void OnInstantMessage(IClientAPI remoteClient, GridInstantMessage im)
{
if (m_debugEnabled)
{
m_log.DebugFormat("[Groups.Messaging]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
DebugGridInstantMessage(im);
}
// Start group IM session
if ((im.dialog == (byte)InstantMessageDialog.SessionGroupStart))
{
if (m_debugEnabled) m_log.InfoFormat("[Groups.Messaging]: imSessionID({0}) toAgentID({1})", im.imSessionID, im.toAgentID);
UUID GroupID = new UUID(im.imSessionID);
UUID AgentID = new UUID(im.fromAgentID);
GroupRecord groupInfo = m_groupData.GetGroupRecord(UUID.Zero.ToString(), GroupID, null);
if (groupInfo != null)
{
AgentInvitedToGroupChatSession(AgentID.ToString(), GroupID);
ChatterBoxSessionStartReplyViaCaps(remoteClient, groupInfo.GroupName, GroupID);
IEventQueue queue = remoteClient.Scene.RequestModuleInterface<IEventQueue>();
queue.ChatterBoxSessionAgentListUpdates(
GroupID
, AgentID
, new UUID(im.toAgentID)
, false //canVoiceChat
, false //isModerator
, false //text mute
);
}
}
// Send a message from locally connected client to a group
if ((im.dialog == (byte)InstantMessageDialog.SessionSend))
{
UUID GroupID = new UUID(im.imSessionID);
UUID AgentID = new UUID(im.fromAgentID);
if (m_debugEnabled)
m_log.DebugFormat("[Groups.Messaging]: Send message to session for group {0} with session ID {1}", GroupID, im.imSessionID.ToString());
//If this agent is sending a message, then they want to be in the session
AgentInvitedToGroupChatSession(AgentID.ToString(), GroupID);
SendMessageToGroup(im, GroupID);
}
}
#endregion
void ChatterBoxSessionStartReplyViaCaps(IClientAPI remoteClient, string groupName, UUID groupID)
{
if (m_debugEnabled) m_log.DebugFormat("[Groups.Messaging]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
OSDMap moderatedMap = new OSDMap(4);
moderatedMap.Add("voice", OSD.FromBoolean(false));
OSDMap sessionMap = new OSDMap(4);
sessionMap.Add("moderated_mode", moderatedMap);
sessionMap.Add("session_name", OSD.FromString(groupName));
sessionMap.Add("type", OSD.FromInteger(0));
sessionMap.Add("voice_enabled", OSD.FromBoolean(false));
OSDMap bodyMap = new OSDMap(4);
bodyMap.Add("session_id", OSD.FromUUID(groupID));
bodyMap.Add("temp_session_id", OSD.FromUUID(groupID));
bodyMap.Add("success", OSD.FromBoolean(true));
bodyMap.Add("session_info", sessionMap);
IEventQueue queue = remoteClient.Scene.RequestModuleInterface<IEventQueue>();
if (queue != null)
{
queue.Enqueue(queue.BuildEvent("ChatterBoxSessionStartReply", bodyMap), remoteClient.AgentId);
}
}
private void DebugGridInstantMessage(GridInstantMessage im)
{
// Don't log any normal IMs (privacy!)
if (m_debugEnabled && im.dialog != (byte)InstantMessageDialog.MessageFromAgent)
{
m_log.WarnFormat("[Groups.Messaging]: IM: fromGroup({0})", im.fromGroup ? "True" : "False");
m_log.WarnFormat("[Groups.Messaging]: IM: Dialog({0})", ((InstantMessageDialog)im.dialog).ToString());
m_log.WarnFormat("[Groups.Messaging]: IM: fromAgentID({0})", im.fromAgentID.ToString());
m_log.WarnFormat("[Groups.Messaging]: IM: fromAgentName({0})", im.fromAgentName.ToString());
m_log.WarnFormat("[Groups.Messaging]: IM: imSessionID({0})", im.imSessionID.ToString());
m_log.WarnFormat("[Groups.Messaging]: IM: message({0})", im.message.ToString());
m_log.WarnFormat("[Groups.Messaging]: IM: offline({0})", im.offline.ToString());
m_log.WarnFormat("[Groups.Messaging]: IM: toAgentID({0})", im.toAgentID.ToString());
m_log.WarnFormat("[Groups.Messaging]: IM: binaryBucket({0})", OpenMetaverse.Utils.BytesToHexString(im.binaryBucket, "BinaryBucket"));
}
}
#region Client Tools
/// <summary>
/// Try to find an active IClientAPI reference for agentID giving preference to root connections
/// </summary>
private IClientAPI GetActiveClient(UUID agentID)
{
if (m_debugEnabled) m_log.WarnFormat("[Groups.Messaging]: Looking for local client {0}", agentID);
IClientAPI child = null;
// Try root avatar first
foreach (Scene scene in m_sceneList)
{
ScenePresence sp = scene.GetScenePresence(agentID);
if (sp != null)
{
if (!sp.IsChildAgent)
{
if (m_debugEnabled) m_log.DebugFormat("[Groups.Messaging]: Found root agent for client : {0}", sp.ControllingClient.Name);
return sp.ControllingClient;
}
else
{
if (m_debugEnabled) m_log.DebugFormat("[Groups.Messaging]: Found child agent for client : {0}", sp.ControllingClient.Name);
child = sp.ControllingClient;
}
}
}
// If we didn't find a root, then just return whichever child we found, or null if none
if (child == null)
{
if (m_debugEnabled) m_log.WarnFormat("[Groups.Messaging]: Could not find local client for agent : {0}", agentID);
}
else
{
if (m_debugEnabled) m_log.WarnFormat("[Groups.Messaging]: Returning child agent for client : {0}", child.Name);
}
return child;
}
#endregion
#region GroupSessionTracking
public void ResetAgentGroupChatSessions(string agentID)
{
foreach (List<string> agentList in m_groupsAgentsDroppedFromChatSession.Values)
agentList.Remove(agentID);
foreach (List<string> agentList in m_groupsAgentsInvitedToChatSession.Values)
agentList.Remove(agentID);
}
public bool hasAgentBeenInvitedToGroupChatSession(string agentID, UUID groupID)
{
// If we're tracking this group, and we can find them in the tracking, then they've been invited
return m_groupsAgentsInvitedToChatSession.ContainsKey(groupID)
&& m_groupsAgentsInvitedToChatSession[groupID].Contains(agentID);
}
public bool hasAgentDroppedGroupChatSession(string agentID, UUID groupID)
{
// If we're tracking drops for this group,
// and we find them, well... then they've dropped
return m_groupsAgentsDroppedFromChatSession.ContainsKey(groupID)
&& m_groupsAgentsDroppedFromChatSession[groupID].Contains(agentID);
}
public void AgentDroppedFromGroupChatSession(string agentID, UUID groupID)
{
if (m_groupsAgentsDroppedFromChatSession.ContainsKey(groupID))
{
// If not in dropped list, add
if (!m_groupsAgentsDroppedFromChatSession[groupID].Contains(agentID))
{
m_groupsAgentsDroppedFromChatSession[groupID].Add(agentID);
}
}
}
public void AgentInvitedToGroupChatSession(string agentID, UUID groupID)
{
// Add Session Status if it doesn't exist for this session
CreateGroupChatSessionTracking(groupID);
// If nessesary, remove from dropped list
if (m_groupsAgentsDroppedFromChatSession[groupID].Contains(agentID))
{
m_groupsAgentsDroppedFromChatSession[groupID].Remove(agentID);
}
// Add to invited
if (!m_groupsAgentsInvitedToChatSession[groupID].Contains(agentID))
m_groupsAgentsInvitedToChatSession[groupID].Add(agentID);
}
private void CreateGroupChatSessionTracking(UUID groupID)
{
if (!m_groupsAgentsDroppedFromChatSession.ContainsKey(groupID))
{
m_groupsAgentsDroppedFromChatSession.Add(groupID, new List<string>());
m_groupsAgentsInvitedToChatSession.Add(groupID, new List<string>());
}
}
#endregion
}
}
| |
using System.Collections.Generic;
using SadConsole;
using SadRogue.Primitives;
namespace ZReader
{
public class ZElement
{
public enum Types : byte
{
Empty = 0,
BoardEdge = 1,
Messenger = 2,
Monitor = 3,
Player = 4,
Ammo = 5,
Torch = 6,
Gem = 7,
Key = 8,
Door = 9,
Scroll = 10,
Passage = 11,
Duplicator = 12,
Bomb = 13,
Energizer = 14,
Star = 15,
Clockwise = 16,
Counter = 17,
Bullet = 18,
Water = 19,
Forest = 20,
SolidWall = 21,
NormalWall = 22,
BreakableWall = 23,
Boulder = 24,
SliderNS = 25,
SliderEW = 26,
FakeWall = 27,
Invisible = 28,
BlinkWall = 29,
Transporter = 30,
Line = 31,
Ricochet = 32,
BlinkRayHorizontal = 33,
Bear = 34,
Ruffian = 35,
Object = 36,
Slime = 37,
Shark = 38,
SpinningGun = 39,
Pusher = 40,
Lion = 41,
Tiger = 42,
BlinkRayVertical = 43,
Head = 44,
Segment = 45,
TextBlue = 47,
TextGreen = 48,
TextCyan = 49,
TextRed = 50,
TextPurple = 51,
TextBrown = 52,
TextBlack = 53
}
public enum Categories
{
Other,
Item,
Creature,
Terrain
}
public Types Type { get; }
public Categories Category { get; }
public byte Glyph { get; set; }
public byte ForeColor { get; set; }
public byte BackColor { get; set; }
public byte Data { get; set; }
public byte GetHighNibble(byte value) => (byte)((value & 0x70) >> 4);
public byte GetLowNibble(byte value) => (byte)(value & 0x0F);
public void ParseColor(byte value)
{
if (value > 15)
{
ForeColor = GetLowNibble(value);
BackColor = GetHighNibble(value);
}
else
ForeColor = value;
}
public ZElement(Types type, byte data = 0x00)
{
Type = type;
Data = data;
switch (type)
{
case Types.Empty:
Glyph = 0x20;
ForeColor = GetHighNibble(0x70);
break;
case Types.BoardEdge:
case Types.Messenger:
Glyph = 0x20;
ParseColor(data);
break;
case Types.Monitor:
Glyph = 0x20;
ForeColor = 0x07;
break;
case Types.Player:
Glyph = 0x02;
ForeColor = GetLowNibble(0x1F);
BackColor = GetHighNibble(0x1F);
break;
case Types.Ammo:
Glyph = 0x84;
ForeColor = 0x03;
break;
case Types.Torch:
Glyph = 0x9D;
ForeColor = 0x06;
break;
case Types.Gem:
Glyph = 0x04;
ParseColor(data);
break;
case Types.Key:
Glyph = 0x0C;
ParseColor(data);
break;
case Types.Door:
Glyph = 0x0A;
ForeColor = 0x0F;
BackColor = GetHighNibble(data);
break;
case Types.Scroll:
Glyph = 0xE8;
ForeColor = 0x0F;
break;
case Types.Passage:
Glyph = 0xF0;
ForeColor = 0x0F;
BackColor = GetHighNibble(data);
break;
case Types.Duplicator:
Glyph = 0xFA;
ForeColor = 0x0F;
break;
case Types.Bomb:
Glyph = 0x0B;
ParseColor(data);
break;
case Types.Energizer:
Glyph = 0x7F;
ForeColor = 0x05;
break;
case Types.Star:
Glyph = 0x53;
ForeColor = 0x0F;
break;
case Types.Clockwise:
Glyph = 0x2F;
ParseColor(data);
break;
case Types.Counter:
Glyph = 0x5C;
ParseColor(data);
break;
case Types.Bullet:
Glyph = 0xF8;
ForeColor = 0x0F;
break;
case Types.Water:
Glyph = 0xB0;
ParseColor(0xF9);
break;
case Types.Forest:
Glyph = 0xB0;
ParseColor(0x20);
break;
case Types.SolidWall:
Glyph = 0xDB;
ParseColor(data);
break;
case Types.NormalWall:
Glyph = 0xB2;
ParseColor(data);
break;
case Types.BreakableWall:
Glyph = 0xB1;
ParseColor(data);
break;
case Types.Boulder:
Glyph = 0xFE;
ParseColor(data);
break;
case Types.SliderNS:
Glyph = 0x12;
ParseColor(data);
break;
case Types.SliderEW:
Glyph = 0x1D;
ParseColor(data);
break;
case Types.FakeWall:
Glyph = 0xB2;
ParseColor(data);
break;
case Types.Invisible:
Glyph = 0xB0;
ParseColor(data);
break;
case Types.BlinkWall:
Glyph = 0xCE;
ParseColor(data);
break;
case Types.Transporter:
Glyph = 0xC5;
ParseColor(data);
break;
case Types.Line:
Glyph = 0xCE;
ParseColor(data);
break;
case Types.Ricochet:
Glyph = 0x2A;
ForeColor = 0x0A;
break;
case Types.BlinkRayHorizontal:
Glyph = 0xCD;
ParseColor(data);
break;
case Types.Bear:
Glyph = 0x99;
ForeColor = 0x06;
break;
case Types.Ruffian:
Glyph = 0x05;
ForeColor = 0x0D;
break;
case Types.Object:
Glyph = 0x02;
ParseColor(data);
break;
case Types.Slime:
Glyph = 0x2A;
ParseColor(data);
break;
case Types.Shark:
Glyph = 0x5E;
ForeColor = 0x07;
break;
case Types.SpinningGun:
Glyph = 0x18;
ParseColor(data);
break;
case Types.Pusher:
Glyph = 0x10;
ParseColor(data);
break;
case Types.Lion:
Glyph = 0xEA;
ForeColor = 0x0C;
break;
case Types.Tiger:
Glyph = 0xE3;
ForeColor = 0x0B;
break;
case Types.BlinkRayVertical:
Glyph = 0xBA;
ParseColor(data);
break;
case Types.Head:
Glyph = 0xE9;
ParseColor(data);
break;
case Types.Segment:
Glyph = 0x4F;
ParseColor(data);
break;
case Types.TextBlue:
Glyph = data;
ForeColor = 15;
BackColor = 1;
break;
case Types.TextGreen:
Glyph = data;
ForeColor = 15;
BackColor = 2;
break;
case Types.TextCyan:
Glyph = data;
ForeColor = 15;
BackColor = 3;
break;
case Types.TextRed:
Glyph = data;
ForeColor = 15;
BackColor = 4;
break;
case Types.TextPurple:
Glyph = data;
ForeColor = 15;
BackColor = 5;
break;
case Types.TextBrown:
Glyph = data;
ForeColor = 15;
BackColor = 6;
break;
case Types.TextBlack:
Glyph = data;
ForeColor = 15;
BackColor = 0;
break;
default:
break;
}
if ((Type >= Types.Player && Type <= Types.Energizer) ||
(Type == Types.Clockwise || Type == Types.Counter))
Category = Categories.Item;
else if ((Type >= Types.Empty && type <= Types.Monitor) ||
(Type >= Types.Water && type <= Types.BlinkRayHorizontal) ||
Type == Types.BlinkRayVertical ||
(Type >= Types.TextBlue && Type <= Types.TextBlack))
Category = Categories.Terrain;
else if (Type == Types.Bullet || type == Types.Star || Type == Types.Head || type == Types.Segment ||
(Type >= Types.Bear && type <= Types.Tiger))
Category = Categories.Creature;
}
public static bool IsTerrain(Types type) =>
new ZElement(type, 0).Category == Categories.Terrain;
public static bool IsObjectType(Types type)
{
var element = new ZElement(type, 0);
return element.Category == Categories.Creature || element.Category == Categories.Item;
}
public static bool IsItem(Types type) =>
new ZElement(type, 0).Category == Categories.Item;
public static bool IsCreature(Types type) =>
new ZElement(type, 0).Category == Categories.Creature;
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
namespace Orleans.Runtime
{
internal class AssemblyLoader
{
private readonly Dictionary<string, SearchOption> dirEnumArgs;
private readonly HashSet<AssemblyLoaderPathNameCriterion> pathNameCriteria;
private readonly HashSet<AssemblyLoaderReflectionCriterion> reflectionCriteria;
private readonly TraceLogger logger;
internal bool SimulateExcludeCriteriaFailure { get; set; }
internal bool SimulateLoadCriteriaFailure { get; set; }
internal bool SimulateReflectionOnlyLoadFailure { get; set; }
internal bool RethrowDiscoveryExceptions { get; set; }
private AssemblyLoader(
Dictionary<string, SearchOption> dirEnumArgs,
HashSet<AssemblyLoaderPathNameCriterion> pathNameCriteria,
HashSet<AssemblyLoaderReflectionCriterion> reflectionCriteria,
TraceLogger logger)
{
this.dirEnumArgs = dirEnumArgs;
this.pathNameCriteria = pathNameCriteria;
this.reflectionCriteria = reflectionCriteria;
this.logger = logger;
SimulateExcludeCriteriaFailure = false;
SimulateLoadCriteriaFailure = false;
SimulateReflectionOnlyLoadFailure = false;
RethrowDiscoveryExceptions = false;
// Ensure that each assembly which is loaded is processed.
AssemblyProcessor.Initialize();
}
/// <summary>
/// Loads assemblies according to caller-defined criteria.
/// </summary>
/// <param name="dirEnumArgs">A list of arguments that are passed to Directory.EnumerateFiles().
/// The sum of the DLLs found from these searches is used as a base set of assemblies for
/// criteria to evaluate.</param>
/// <param name="pathNameCriteria">A list of criteria that are used to disqualify
/// assemblies from being loaded based on path name alone (e.g.
/// AssemblyLoaderCriteria.ExcludeFileNames) </param>
/// <param name="reflectionCriteria">A list of criteria that are used to identify
/// assemblies to be loaded based on examination of their ReflectionOnly type
/// information (e.g. AssemblyLoaderCriteria.LoadTypesAssignableFrom).</param>
/// <param name="logger">A logger to provide feedback to.</param>
/// <returns>List of discovered assembly locations</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods", MessageId = "System.Reflection.Assembly.LoadFrom")]
public static List<string> LoadAssemblies(
Dictionary<string, SearchOption> dirEnumArgs,
IEnumerable<AssemblyLoaderPathNameCriterion> pathNameCriteria,
IEnumerable<AssemblyLoaderReflectionCriterion> reflectionCriteria,
TraceLogger logger)
{
var loader =
NewAssemblyLoader(
dirEnumArgs,
pathNameCriteria,
reflectionCriteria,
logger);
int count = 0;
List<string> discoveredAssemblyLocations = loader.DiscoverAssemblies();
foreach (var pathName in discoveredAssemblyLocations)
{
loader.logger.Info("Loading assembly {0}...", pathName);
// It is okay to use LoadFrom here because we are loading application assemblies deployed to the specific directory.
// Such application assemblies should not be deployed somewhere else, e.g. GAC, so this is safe.
Assembly.LoadFrom(pathName);
++count;
}
loader.logger.Info("{0} assemblies loaded.", count);
return discoveredAssemblyLocations;
}
public static T TryLoadAndCreateInstance<T>(string assemblyName, TraceLogger logger) where T : class
{
try
{
var assembly = Assembly.Load(new AssemblyName(assemblyName));
var foundType =
TypeUtils.GetTypes(
assembly,
type =>
typeof(T).GetTypeInfo().IsAssignableFrom(type) && !type.GetTypeInfo().IsInterface
&& type.GetTypeInfo().GetConstructor(Type.EmptyTypes) != null, logger).FirstOrDefault();
if (foundType == null)
{
return null;
}
return (T)Activator.CreateInstance(foundType, true);
}
catch (FileNotFoundException exception)
{
logger.Warn(ErrorCode.Loader_TryLoadAndCreateInstance_Failure, exception.Message, exception);
return null;
}
catch (Exception exc)
{
logger.Error(ErrorCode.Loader_TryLoadAndCreateInstance_Failure, exc.Message, exc);
throw;
}
}
public static T LoadAndCreateInstance<T>(string assemblyName, TraceLogger logger) where T : class
{
try
{
var assembly = Assembly.Load(new AssemblyName(assemblyName));
var foundType = TypeUtils.GetTypes(assembly, type => typeof(T).IsAssignableFrom(type), logger).First();
return (T)Activator.CreateInstance(foundType, true);
}
catch (Exception exc)
{
logger.Error(ErrorCode.Loader_LoadAndCreateInstance_Failure, exc.Message, exc);
throw;
}
}
// this method is internal so that it can be accessed from unit tests, which only test the discovery
// process-- not the actual loading of assemblies.
internal static AssemblyLoader NewAssemblyLoader(
Dictionary<string, SearchOption> dirEnumArgs,
IEnumerable<AssemblyLoaderPathNameCriterion> pathNameCriteria,
IEnumerable<AssemblyLoaderReflectionCriterion> reflectionCriteria,
TraceLogger logger)
{
if (null == dirEnumArgs)
throw new ArgumentNullException("dirEnumArgs");
if (dirEnumArgs.Count == 0)
throw new ArgumentException("At least one directory is necessary in order to search for assemblies.");
HashSet<AssemblyLoaderPathNameCriterion> pathNameCriteriaSet = null == pathNameCriteria
? new HashSet<AssemblyLoaderPathNameCriterion>()
: new HashSet<AssemblyLoaderPathNameCriterion>(pathNameCriteria.Distinct());
if (null == reflectionCriteria || !reflectionCriteria.Any())
throw new ArgumentException("No assemblies will be loaded unless reflection criteria are specified.");
var reflectionCriteriaSet = new HashSet<AssemblyLoaderReflectionCriterion>(reflectionCriteria.Distinct());
if (null == logger)
throw new ArgumentNullException("logger");
return new AssemblyLoader(
dirEnumArgs,
pathNameCriteriaSet,
reflectionCriteriaSet,
logger);
}
// this method is internal so that it can be accessed from unit tests, which only test the discovery
// process-- not the actual loading of assemblies.
internal List<string> DiscoverAssemblies()
{
try
{
if (dirEnumArgs.Count == 0)
throw new InvalidOperationException("Please specify a directory to search using the AddDirectory or AddRoot methods.");
AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += CachedReflectionOnlyTypeResolver.OnReflectionOnlyAssemblyResolve;
// the following explicit loop ensures that the finally clause is invoked
// after we're done enumerating.
return EnumerateApprovedAssemblies();
}
finally
{
AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve -= CachedReflectionOnlyTypeResolver.OnReflectionOnlyAssemblyResolve;
}
}
private List<string> EnumerateApprovedAssemblies()
{
var assemblies = new List<string>();
foreach (var i in dirEnumArgs)
{
var pathName = i.Key;
var searchOption = i.Value;
if (!Directory.Exists(pathName))
{
logger.Warn(ErrorCode.Loader_DirNotFound, "Unable to find directory {0}; skipping.", pathName);
continue;
}
logger.Info(
searchOption == SearchOption.TopDirectoryOnly ?
"Searching for assemblies in {0}..." :
"Recursively searching for assemblies in {0}...",
pathName);
var candidates =
Directory.EnumerateFiles(pathName, "*.dll", searchOption)
.Select(Path.GetFullPath)
.Distinct()
.ToArray();
// This is a workaround for the behavior of ReflectionOnlyLoad/ReflectionOnlyLoadFrom
// that appear not to automatically resolve dependencies.
// We are trying to pre-load all dlls we find in the folder, so that if one of these
// assemblies happens to be a dependency of an assembly we later on call
// Assembly.DefinedTypes on, the dependency will be already loaded and will get
// automatically resolved. Ugly, but seems to solve the problem.
foreach (var j in candidates)
{
try
{
if (logger.IsVerbose) logger.Verbose("Trying to pre-load {0} to reflection-only context.", j);
Assembly.ReflectionOnlyLoadFrom(j);
}
catch (Exception)
{
if (logger.IsVerbose) logger.Verbose("Failed to pre-load assembly {0} in reflection-only context.", j);
}
}
foreach (var j in candidates)
{
if (AssemblyPassesLoadCriteria(j))
assemblies.Add(j);
}
}
return assemblies;
}
private bool ShouldExcludeAssembly(string pathName)
{
foreach (var criterion in pathNameCriteria)
{
IEnumerable<string> complaints;
bool shouldExclude;
try
{
shouldExclude = !criterion.EvaluateCandidate(pathName, out complaints);
}
catch (Exception ex)
{
complaints = ReportUnexpectedException(ex);
if (RethrowDiscoveryExceptions)
throw;
shouldExclude = true;
}
if (shouldExclude)
{
LogComplaints(pathName, complaints);
return true;
}
}
return false;
}
private static Assembly MatchWithLoadedAssembly(AssemblyName searchFor, IEnumerable<Assembly> assemblies)
{
foreach (var assembly in assemblies)
{
var searchForFullName = searchFor.FullName;
var candidateFullName = assembly.FullName;
if (String.Equals(candidateFullName, searchForFullName, StringComparison.OrdinalIgnoreCase))
{
return assembly;
}
}
return null;
}
private static Assembly MatchWithLoadedAssembly(AssemblyName searchFor, AppDomain appDomain)
{
return
MatchWithLoadedAssembly(searchFor, appDomain.GetAssemblies()) ??
MatchWithLoadedAssembly(searchFor, appDomain.ReflectionOnlyGetAssemblies());
}
private static Assembly MatchWithLoadedAssembly(AssemblyName searchFor)
{
return MatchWithLoadedAssembly(searchFor, AppDomain.CurrentDomain);
}
private static bool InterpretFileLoadException(string asmPathName, out string[] complaints)
{
var matched = MatchWithLoadedAssembly(AssemblyName.GetAssemblyName(asmPathName));
if (null == matched)
{
// something unexpected has occurred. rethrow until we know what we're catching.
complaints = null;
return false;
}
if (matched.Location != asmPathName)
{
complaints = new string[] {String.Format("A conflicting assembly has already been loaded from {0}.", matched.Location)};
// exception was anticipated.
return true;
}
// we've been asked to not log this because it's not indicative of a problem.
complaints = null;
//complaints = new string[] {"Assembly has already been loaded into current application domain."};
// exception was anticipated.
return true;
}
private string[] ReportUnexpectedException(Exception exception)
{
const string msg = "An unexpected exception occurred while attempting to load an assembly.";
logger.Error(ErrorCode.Loader_UnexpectedException, msg, exception);
return new string[] {msg};
}
private bool ReflectionOnlyLoadAssembly(string pathName, out Assembly assembly, out string[] complaints)
{
try
{
if (SimulateReflectionOnlyLoadFailure)
throw NewTestUnexpectedException();
assembly = Assembly.ReflectionOnlyLoadFrom(pathName);
}
catch (FileLoadException e)
{
assembly = null;
if (!InterpretFileLoadException(pathName, out complaints))
complaints = ReportUnexpectedException(e);
if (RethrowDiscoveryExceptions)
throw;
return false;
}
catch (Exception e)
{
assembly = null;
complaints = ReportUnexpectedException(e);
if (RethrowDiscoveryExceptions)
throw;
return false;
}
complaints = null;
return true;
}
private void LogComplaint(string pathName, string complaint)
{
LogComplaints(pathName, new string[] { complaint });
}
private void LogComplaints(string pathName, IEnumerable<string> complaints)
{
var distinctComplaints = complaints.Distinct();
// generate feedback so that the operator can determine why her DLL didn't load.
var msg = new StringBuilder();
string bullet = Environment.NewLine + "\t* ";
msg.Append(String.Format("User assembly ignored: {0}", pathName));
int count = 0;
foreach (var i in distinctComplaints)
{
msg.Append(bullet);
msg.Append(i);
++count;
}
if (0 == count)
throw new InvalidOperationException("No complaint provided for assembly.");
// we can't use an error code here because we want each log message to be displayed.
logger.Info(msg.ToString());
}
private static AggregateException NewTestUnexpectedException()
{
var inner = new Exception[] { new OrleansException("Inner Exception #1"), new OrleansException("Inner Exception #2") };
return new AggregateException("Unexpected AssemblyLoader Exception Used for Unit Tests", inner);
}
private bool ShouldLoadAssembly(string pathName)
{
Assembly assembly;
string[] loadComplaints;
if (!ReflectionOnlyLoadAssembly(pathName, out assembly, out loadComplaints))
{
if (loadComplaints == null || loadComplaints.Length == 0)
return false;
LogComplaints(pathName, loadComplaints);
return false;
}
if (assembly.IsDynamic)
{
LogComplaint(pathName, "Assembly is dynamic (not supported).");
return false;
}
var criteriaComplaints = new List<string>();
foreach (var i in reflectionCriteria)
{
IEnumerable<string> complaints;
try
{
if (SimulateLoadCriteriaFailure)
throw NewTestUnexpectedException();
if (i.EvaluateCandidate(assembly, out complaints))
return true;
}
catch (Exception ex)
{
complaints = ReportUnexpectedException(ex);
if (RethrowDiscoveryExceptions)
throw;
}
criteriaComplaints.AddRange(complaints);
}
LogComplaints(pathName, criteriaComplaints);
return false;
}
private bool AssemblyPassesLoadCriteria(string pathName)
{
return !ShouldExcludeAssembly(pathName) && ShouldLoadAssembly(pathName);
}
}
}
| |
using System;
using System.Collections;
public class ArrayReverse2
{
private const int c_MIN_SIZE = 64;
private const int c_MAX_SIZE = 1024;
private const int c_MIN_STRLEN = 1;
private const int c_MAX_STRLEN = 1024;
public static int Main()
{
ArrayReverse2 ac = new ArrayReverse2();
TestLibrary.TestFramework.BeginTestCase("Array.Reverse(Array, int, int)");
if (ac.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
retVal = PosTest5() && retVal;
TestLibrary.TestFramework.LogInformation("");
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
retVal = NegTest4() && retVal;
return retVal;
}
public bool PosTest1()
{
bool retVal = true;
Array afterArray;
Array beforeArray;
int length;
TestLibrary.TestFramework.BeginScenario("PosTest1: Array.Reverse(Array, int, int)");
try
{
// creat the array
length = (TestLibrary.Generator.GetInt32(-55) % (c_MAX_SIZE-c_MIN_SIZE)) + c_MIN_SIZE;
beforeArray = Array.CreateInstance(typeof(Int32), length);
afterArray = Array.CreateInstance(typeof(Int32), length);
// fill the array
for (int i=0; i<beforeArray.Length; i++)
{
beforeArray.SetValue((object)TestLibrary.Generator.GetInt32(-55), i);
}
// copy the array
Array.Copy(beforeArray, afterArray, length);
Array.Reverse(afterArray, 0, length);
if (beforeArray.Length != afterArray.Length)
{
TestLibrary.TestFramework.LogError("000", "Unexpected length: Expected(" + beforeArray.Length + ") Actual(" + afterArray.Length + ")");
retVal = false;
}
for (int i=0; i<beforeArray.Length; i++)
{
if ((int)beforeArray.GetValue(length-i-1) != (int)afterArray.GetValue(i))
{
TestLibrary.TestFramework.LogError("001", "Unexpected value: Expected(" + beforeArray.GetValue(length-i-1) + ") Actual(" + afterArray.GetValue(i) + ")");
retVal = false;
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
Array afterArray;
Array beforeArray;
int length;
int startIndex;
TestLibrary.TestFramework.BeginScenario("PosTest2: Array.Reverse(Array, int, int) only reverse half of the array");
try
{
// creat the array
length = (TestLibrary.Generator.GetInt32(-55) % (c_MAX_SIZE-c_MIN_SIZE)) + c_MIN_SIZE;
beforeArray = Array.CreateInstance(typeof(Int32), length);
afterArray = Array.CreateInstance(typeof(Int32), length);
startIndex = length/2;
// fill the array
for (int i=0; i<beforeArray.Length; i++)
{
beforeArray.SetValue((object)TestLibrary.Generator.GetInt32(-55), i);
}
// copy the array
Array.Copy(beforeArray, afterArray, length);
Array.Reverse(afterArray, startIndex, length-startIndex);
if (beforeArray.Length != afterArray.Length)
{
TestLibrary.TestFramework.LogError("003", "Unexpected length: Expected(" + beforeArray.Length + ") Actual(" + afterArray.Length + ")");
retVal = false;
}
for (int i=0; i<beforeArray.Length; i++)
{
int beforeIndex;
if (i < startIndex)
{
beforeIndex = i;
}
else
{
beforeIndex = (length-(i-startIndex)-1);
}
if ((int)beforeArray.GetValue(beforeIndex) != (int)afterArray.GetValue(i))
{
TestLibrary.TestFramework.LogError("004", "Unexpected value: Expected(" + beforeArray.GetValue(beforeIndex) + ") Actual(" + afterArray.GetValue(i) + ")");
retVal = false;
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("005", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
Array afterArray;
Array beforeArray;
int length;
int endIndex;
TestLibrary.TestFramework.BeginScenario("PosTest3: Array.Reverse(Array, int, int) only reverse half of the array (begining)");
try
{
// creat the array
length = (TestLibrary.Generator.GetInt32(-55) % (c_MAX_SIZE-c_MIN_SIZE)) + c_MIN_SIZE;
beforeArray = Array.CreateInstance(typeof(Int32), length);
afterArray = Array.CreateInstance(typeof(Int32), length);
endIndex = length/2;
// fill the array
for (int i=0; i<beforeArray.Length; i++)
{
beforeArray.SetValue((object)TestLibrary.Generator.GetInt32(-55), i);
}
// copy the array
Array.Copy(beforeArray, afterArray, length);
Array.Reverse(afterArray, 0, endIndex);
if (beforeArray.Length != afterArray.Length)
{
TestLibrary.TestFramework.LogError("006", "Unexpected length: Expected(" + beforeArray.Length + ") Actual(" + afterArray.Length + ")");
retVal = false;
}
for (int i=0; i<beforeArray.Length; i++)
{
int beforeIndex;
if (i >= endIndex)
{
beforeIndex = i;
}
else
{
beforeIndex = endIndex-i-1;
}
if ((int)beforeArray.GetValue(beforeIndex) != (int)afterArray.GetValue(i))
{
TestLibrary.TestFramework.LogError("007", "Unexpected value: Expected(" + beforeArray.GetValue(beforeIndex) + ") Actual(" + afterArray.GetValue(i) + ")");
retVal = false;
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
Array afterArray;
Array beforeArray;
int length;
TestLibrary.TestFramework.BeginScenario("PosTest4: Array.Reverse(Array, int, int) array of strings");
try
{
// creat the array
length = (TestLibrary.Generator.GetInt32(-55) % (c_MAX_SIZE-c_MIN_SIZE)) + c_MIN_SIZE;
beforeArray = Array.CreateInstance(typeof(string), length);
afterArray = Array.CreateInstance(typeof(string), length);
// fill the array
for (int i=0; i<beforeArray.Length; i++)
{
beforeArray.SetValue(TestLibrary.Generator.GetString(-55, false, c_MIN_STRLEN, c_MAX_STRLEN), i);
}
// copy the array
Array.Copy(beforeArray, afterArray, length);
Array.Reverse(afterArray, 0, length);
if (beforeArray.Length != afterArray.Length)
{
TestLibrary.TestFramework.LogError("009", "Unexpected length: Expected(" + beforeArray.Length + ") Actual(" + afterArray.Length + ")");
retVal = false;
}
for (int i=0; i<beforeArray.Length; i++)
{
if (!beforeArray.GetValue(length-i-1).Equals(afterArray.GetValue(i)))
{
TestLibrary.TestFramework.LogError("010", "Unexpected value: Expected(" + beforeArray.GetValue(length-i-1) + ") Actual(" + afterArray.GetValue(i) + ")");
retVal = false;
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("011", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest5()
{
bool retVal = true;
Array afterArray;
Array beforeArray;
int length;
TestLibrary.TestFramework.BeginScenario("PosTest5: Array.Reverse(Array, int, int) array of MyStructs");
try
{
// creat the array
length = (TestLibrary.Generator.GetInt32(-55) % (c_MAX_SIZE-c_MIN_SIZE)) + c_MIN_SIZE;
beforeArray = Array.CreateInstance(typeof(MyStruct), length);
afterArray = Array.CreateInstance(typeof(MyStruct), length);
// fill the array
for (int i=0; i<beforeArray.Length; i++)
{
beforeArray.SetValue(new MyStruct(TestLibrary.Generator.GetSingle(-55)), i);
}
// copy the array
Array.Copy(beforeArray, afterArray, length);
Array.Reverse(afterArray, 0, length);
if (beforeArray.Length != afterArray.Length)
{
TestLibrary.TestFramework.LogError("012", "Unexpected length: Expected(" + beforeArray.Length + ") Actual(" + afterArray.Length + ")");
retVal = false;
}
for (int i=0; i<beforeArray.Length; i++)
{
if (((MyStruct)beforeArray.GetValue(length-i-1)).f != ((MyStruct)afterArray.GetValue(i)).f)
{
TestLibrary.TestFramework.LogError("013", "Unexpected value: Expected(" + ((MyStruct)beforeArray.GetValue(length-i-1)).f + ") Actual(" + ((MyStruct)afterArray.GetValue(i)).f + ")");
retVal = false;
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("014", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest1: Array.Reverse(Array, int, int) where array is null");
try
{
Array.Reverse(null, 0, 0);
TestLibrary.TestFramework.LogError("015", "Exception expected");
retVal = false;
}
catch (ArgumentNullException)
{
// expected
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("016", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
Array array;
int length;
TestLibrary.TestFramework.BeginScenario("NegTest1: Array.Reverse(Array, int, int) where index is negative");
try
{
length = (TestLibrary.Generator.GetInt32(-55) % (c_MAX_SIZE-c_MIN_SIZE)) + c_MIN_SIZE;
array = Array.CreateInstance(typeof(Int32), length);
Array.Reverse(array, -1, length);
TestLibrary.TestFramework.LogError("017", "Exception expected");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
// expected
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("018", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest3()
{
bool retVal = true;
Array array;
int length;
TestLibrary.TestFramework.BeginScenario("NegTest3: Array.Reverse(Array, int, int) where index is greater than length");
try
{
length = (TestLibrary.Generator.GetInt32(-55) % (c_MAX_SIZE-c_MIN_SIZE)) + c_MIN_SIZE;
array = Array.CreateInstance(typeof(Int32), length);
Array.Reverse(array, length, length);
TestLibrary.TestFramework.LogError("019", "Exception expected");
retVal = false;
}
catch (ArgumentException)
{
// expected
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("020", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest4()
{
bool retVal = true;
Array array;
int length;
TestLibrary.TestFramework.BeginScenario("NegTest4: Array.Reverse(Array, int, int) multi dimension array");
try
{
length = (TestLibrary.Generator.GetInt32(-55) % (c_MAX_SIZE-c_MIN_SIZE)) + c_MIN_SIZE;
array = Array.CreateInstance(typeof(Int32), new int[2] {length, length});
Array.Reverse(array, length, length);
TestLibrary.TestFramework.LogError("021", "Exception expected");
retVal = false;
}
catch (RankException)
{
// expected
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("022", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public struct MyStruct
{
public float f;
public MyStruct(float ff) { f = ff; }
}
}
| |
// Copyright (C) 2014 dot42
//
// Original filename: Org.Apache.Http.Conn.Routing.cs
//
// 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.
#pragma warning disable 1717
namespace Org.Apache.Http.Conn.Routing
{
/// <summary>
/// <para>Helps tracking the steps in establishing a route.</para><para><para></para><para></para><title>Revision:</title><para>620254 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/conn/routing/RouteTracker
/// </java-name>
[Dot42.DexImport("org/apache/http/conn/routing/RouteTracker", AccessFlags = 49)]
public sealed partial class RouteTracker : global::Org.Apache.Http.Conn.Routing.IRouteInfo, global::Java.Lang.ICloneable
/* scope: __dot42__ */
{
/// <summary>
/// <para>Creates a new route tracker. The target and origin need to be specified at creation time.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Lorg/apache/http/HttpHost;Ljava/net/InetAddress;)V", AccessFlags = 1)]
public RouteTracker(global::Org.Apache.Http.HttpHost target, global::Java.Net.InetAddress local) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Creates a new tracker for the given route. Only target and origin are taken from the route, everything else remains to be tracked.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Lorg/apache/http/conn/routing/HttpRoute;)V", AccessFlags = 1)]
public RouteTracker(global::Org.Apache.Http.Conn.Routing.HttpRoute route) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Tracks connecting to the target.</para><para></para>
/// </summary>
/// <java-name>
/// connectTarget
/// </java-name>
[Dot42.DexImport("connectTarget", "(Z)V", AccessFlags = 17)]
public void ConnectTarget(bool secure) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Tracks connecting to the first proxy.</para><para></para>
/// </summary>
/// <java-name>
/// connectProxy
/// </java-name>
[Dot42.DexImport("connectProxy", "(Lorg/apache/http/HttpHost;Z)V", AccessFlags = 17)]
public void ConnectProxy(global::Org.Apache.Http.HttpHost proxy, bool secure) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Tracks tunnelling to the target.</para><para></para>
/// </summary>
/// <java-name>
/// tunnelTarget
/// </java-name>
[Dot42.DexImport("tunnelTarget", "(Z)V", AccessFlags = 17)]
public void TunnelTarget(bool secure) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Tracks tunnelling to a proxy in a proxy chain. This will extend the tracked proxy chain, but it does not mark the route as tunnelled. Only end-to-end tunnels are considered there.</para><para></para>
/// </summary>
/// <java-name>
/// tunnelProxy
/// </java-name>
[Dot42.DexImport("tunnelProxy", "(Lorg/apache/http/HttpHost;Z)V", AccessFlags = 17)]
public void TunnelProxy(global::Org.Apache.Http.HttpHost proxy, bool secure) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Tracks layering a protocol.</para><para></para>
/// </summary>
/// <java-name>
/// layerProtocol
/// </java-name>
[Dot42.DexImport("layerProtocol", "(Z)V", AccessFlags = 17)]
public void LayerProtocol(bool secure) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Obtains the target host.</para><para></para>
/// </summary>
/// <returns>
/// <para>the target host </para>
/// </returns>
/// <java-name>
/// getTargetHost
/// </java-name>
[Dot42.DexImport("getTargetHost", "()Lorg/apache/http/HttpHost;", AccessFlags = 17)]
public global::Org.Apache.Http.HttpHost GetTargetHost() /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.HttpHost);
}
/// <summary>
/// <para>Obtains the local address to connect from.</para><para></para>
/// </summary>
/// <returns>
/// <para>the local address, or <code>null</code> </para>
/// </returns>
/// <java-name>
/// getLocalAddress
/// </java-name>
[Dot42.DexImport("getLocalAddress", "()Ljava/net/InetAddress;", AccessFlags = 17)]
public global::Java.Net.InetAddress GetLocalAddress() /* MethodBuilder.Create */
{
return default(global::Java.Net.InetAddress);
}
/// <summary>
/// <para>Obtains the number of hops in this route. A direct route has one hop. A route through a proxy has two hops. A route through a chain of <b>n</b> proxies has <b>n+1</b> hops.</para><para></para>
/// </summary>
/// <returns>
/// <para>the number of hops in this route </para>
/// </returns>
/// <java-name>
/// getHopCount
/// </java-name>
[Dot42.DexImport("getHopCount", "()I", AccessFlags = 17)]
public int GetHopCount() /* MethodBuilder.Create */
{
return default(int);
}
/// <summary>
/// <para>Obtains the target of a hop in this route. The target of the last hop is the target host, the target of previous hops is the respective proxy in the chain. For a route through exactly one proxy, target of hop 0 is the proxy and target of hop 1 is the target host.</para><para></para>
/// </summary>
/// <returns>
/// <para>the target of the given hop</para>
/// </returns>
/// <java-name>
/// getHopTarget
/// </java-name>
[Dot42.DexImport("getHopTarget", "(I)Lorg/apache/http/HttpHost;", AccessFlags = 17)]
public global::Org.Apache.Http.HttpHost GetHopTarget(int hop) /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.HttpHost);
}
/// <summary>
/// <para>Obtains the first proxy host.</para><para></para>
/// </summary>
/// <returns>
/// <para>the first proxy in the proxy chain, or <code>null</code> if this route is direct </para>
/// </returns>
/// <java-name>
/// getProxyHost
/// </java-name>
[Dot42.DexImport("getProxyHost", "()Lorg/apache/http/HttpHost;", AccessFlags = 17)]
public global::Org.Apache.Http.HttpHost GetProxyHost() /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.HttpHost);
}
/// <java-name>
/// isConnected
/// </java-name>
[Dot42.DexImport("isConnected", "()Z", AccessFlags = 17)]
public bool IsConnected() /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Obtains the tunnel type of this route. If there is a proxy chain, only end-to-end tunnels are considered.</para><para></para>
/// </summary>
/// <returns>
/// <para>the tunnelling type </para>
/// </returns>
/// <java-name>
/// getTunnelType
/// </java-name>
[Dot42.DexImport("getTunnelType", "()Lorg/apache/http/conn/routing/RouteInfo$TunnelType;", AccessFlags = 17)]
public global::Org.Apache.Http.Conn.Routing.IRouteInfo_TunnelType GetTunnelType() /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.Conn.Routing.IRouteInfo_TunnelType);
}
/// <summary>
/// <para>Checks whether this route is tunnelled through a proxy. If there is a proxy chain, only end-to-end tunnels are considered.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>true</code> if tunnelled end-to-end through at least one proxy, <code>false</code> otherwise </para>
/// </returns>
/// <java-name>
/// isTunnelled
/// </java-name>
[Dot42.DexImport("isTunnelled", "()Z", AccessFlags = 17)]
public bool IsTunnelled() /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Obtains the layering type of this route. In the presence of proxies, only layering over an end-to-end tunnel is considered.</para><para></para>
/// </summary>
/// <returns>
/// <para>the layering type </para>
/// </returns>
/// <java-name>
/// getLayerType
/// </java-name>
[Dot42.DexImport("getLayerType", "()Lorg/apache/http/conn/routing/RouteInfo$LayerType;", AccessFlags = 17)]
public global::Org.Apache.Http.Conn.Routing.IRouteInfo_LayerType GetLayerType() /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.Conn.Routing.IRouteInfo_LayerType);
}
/// <summary>
/// <para>Checks whether this route includes a layered protocol. In the presence of proxies, only layering over an end-to-end tunnel is considered.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>true</code> if layered, <code>false</code> otherwise </para>
/// </returns>
/// <java-name>
/// isLayered
/// </java-name>
[Dot42.DexImport("isLayered", "()Z", AccessFlags = 17)]
public bool IsLayered() /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Checks whether this route is secure.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>true</code> if secure, <code>false</code> otherwise </para>
/// </returns>
/// <java-name>
/// isSecure
/// </java-name>
[Dot42.DexImport("isSecure", "()Z", AccessFlags = 17)]
public bool IsSecure() /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Obtains the tracked route. If a route has been tracked, it is connected. If not connected, nothing has been tracked so far.</para><para></para>
/// </summary>
/// <returns>
/// <para>the tracked route, or <code>null</code> if nothing has been tracked so far </para>
/// </returns>
/// <java-name>
/// toRoute
/// </java-name>
[Dot42.DexImport("toRoute", "()Lorg/apache/http/conn/routing/HttpRoute;", AccessFlags = 17)]
public global::Org.Apache.Http.Conn.Routing.HttpRoute ToRoute() /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.Conn.Routing.HttpRoute);
}
/// <summary>
/// <para>Compares this tracked route to another.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>true</code> if the argument is the same tracked route, <code>false</code> </para>
/// </returns>
/// <java-name>
/// equals
/// </java-name>
[Dot42.DexImport("equals", "(Ljava/lang/Object;)Z", AccessFlags = 17)]
public override bool Equals(object o) /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Generates a hash code for this tracked route. Route trackers are modifiable and should therefore not be used as lookup keys. Use toRoute to obtain an unmodifiable representation of the tracked route.</para><para></para>
/// </summary>
/// <returns>
/// <para>the hash code </para>
/// </returns>
/// <java-name>
/// hashCode
/// </java-name>
[Dot42.DexImport("hashCode", "()I", AccessFlags = 17)]
public override int GetHashCode() /* MethodBuilder.Create */
{
return default(int);
}
/// <summary>
/// <para>Obtains a description of the tracked route.</para><para></para>
/// </summary>
/// <returns>
/// <para>a human-readable representation of the tracked route </para>
/// </returns>
/// <java-name>
/// toString
/// </java-name>
[Dot42.DexImport("toString", "()Ljava/lang/String;", AccessFlags = 17)]
public override string ToString() /* MethodBuilder.Create */
{
return default(string);
}
/// <java-name>
/// clone
/// </java-name>
[Dot42.DexImport("clone", "()Ljava/lang/Object;", AccessFlags = 1)]
public object Clone() /* MethodBuilder.Create */
{
return default(object);
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal RouteTracker() /* TypeBuilder.AddDefaultConstructor */
{
}
/// <summary>
/// <para>Obtains the target host.</para><para></para>
/// </summary>
/// <returns>
/// <para>the target host </para>
/// </returns>
/// <java-name>
/// getTargetHost
/// </java-name>
public global::Org.Apache.Http.HttpHost TargetHost
{
[Dot42.DexImport("getTargetHost", "()Lorg/apache/http/HttpHost;", AccessFlags = 17)]
get{ return GetTargetHost(); }
}
/// <summary>
/// <para>Obtains the local address to connect from.</para><para></para>
/// </summary>
/// <returns>
/// <para>the local address, or <code>null</code> </para>
/// </returns>
/// <java-name>
/// getLocalAddress
/// </java-name>
public global::Java.Net.InetAddress LocalAddress
{
[Dot42.DexImport("getLocalAddress", "()Ljava/net/InetAddress;", AccessFlags = 17)]
get{ return GetLocalAddress(); }
}
/// <summary>
/// <para>Obtains the number of hops in this route. A direct route has one hop. A route through a proxy has two hops. A route through a chain of <b>n</b> proxies has <b>n+1</b> hops.</para><para></para>
/// </summary>
/// <returns>
/// <para>the number of hops in this route </para>
/// </returns>
/// <java-name>
/// getHopCount
/// </java-name>
public int HopCount
{
[Dot42.DexImport("getHopCount", "()I", AccessFlags = 17)]
get{ return GetHopCount(); }
}
/// <summary>
/// <para>Obtains the first proxy host.</para><para></para>
/// </summary>
/// <returns>
/// <para>the first proxy in the proxy chain, or <code>null</code> if this route is direct </para>
/// </returns>
/// <java-name>
/// getProxyHost
/// </java-name>
public global::Org.Apache.Http.HttpHost ProxyHost
{
[Dot42.DexImport("getProxyHost", "()Lorg/apache/http/HttpHost;", AccessFlags = 17)]
get{ return GetProxyHost(); }
}
/// <summary>
/// <para>Obtains the tunnel type of this route. If there is a proxy chain, only end-to-end tunnels are considered.</para><para></para>
/// </summary>
/// <returns>
/// <para>the tunnelling type </para>
/// </returns>
/// <java-name>
/// getTunnelType
/// </java-name>
public global::Org.Apache.Http.Conn.Routing.IRouteInfo_TunnelType TunnelType
{
[Dot42.DexImport("getTunnelType", "()Lorg/apache/http/conn/routing/RouteInfo$TunnelType;", AccessFlags = 17)]
get{ return GetTunnelType(); }
}
/// <summary>
/// <para>Obtains the layering type of this route. In the presence of proxies, only layering over an end-to-end tunnel is considered.</para><para></para>
/// </summary>
/// <returns>
/// <para>the layering type </para>
/// </returns>
/// <java-name>
/// getLayerType
/// </java-name>
public global::Org.Apache.Http.Conn.Routing.IRouteInfo_LayerType LayerType
{
[Dot42.DexImport("getLayerType", "()Lorg/apache/http/conn/routing/RouteInfo$LayerType;", AccessFlags = 17)]
get{ return GetLayerType(); }
}
}
/// <summary>
/// <para>The route for a request. Instances of this class are unmodifiable and therefore suitable for use as lookup keys.</para><para><para></para><para></para><title>Revision:</title><para>653041 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/conn/routing/HttpRoute
/// </java-name>
[Dot42.DexImport("org/apache/http/conn/routing/HttpRoute", AccessFlags = 49)]
public sealed partial class HttpRoute : global::Org.Apache.Http.Conn.Routing.IRouteInfo, global::Java.Lang.ICloneable
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "(Lorg/apache/http/HttpHost;Ljava/net/InetAddress;[Lorg/apache/http/HttpHost;ZLorg" +
"/apache/http/conn/routing/RouteInfo$TunnelType;Lorg/apache/http/conn/routing/Rou" +
"teInfo$LayerType;)V", AccessFlags = 1)]
public HttpRoute(global::Org.Apache.Http.HttpHost httpHost, global::Java.Net.InetAddress inetAddress, global::Org.Apache.Http.HttpHost[] httpHost1, bool boolean, global::Org.Apache.Http.Conn.Routing.IRouteInfo_TunnelType iRouteInfo_TunnelType, global::Org.Apache.Http.Conn.Routing.IRouteInfo_LayerType iRouteInfo_LayerType) /* MethodBuilder.Create */
{
}
[Dot42.DexImport("<init>", "(Lorg/apache/http/HttpHost;Ljava/net/InetAddress;Lorg/apache/http/HttpHost;ZLorg/" +
"apache/http/conn/routing/RouteInfo$TunnelType;Lorg/apache/http/conn/routing/Rout" +
"eInfo$LayerType;)V", AccessFlags = 1)]
public HttpRoute(global::Org.Apache.Http.HttpHost httpHost, global::Java.Net.InetAddress inetAddress, global::Org.Apache.Http.HttpHost httpHost1, bool boolean, global::Org.Apache.Http.Conn.Routing.IRouteInfo_TunnelType iRouteInfo_TunnelType, global::Org.Apache.Http.Conn.Routing.IRouteInfo_LayerType iRouteInfo_LayerType) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Creates a new direct route. That is a route without a proxy.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Lorg/apache/http/HttpHost;Ljava/net/InetAddress;Z)V", AccessFlags = 1)]
public HttpRoute(global::Org.Apache.Http.HttpHost target, global::Java.Net.InetAddress local, bool secure) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Creates a new direct insecure route.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Lorg/apache/http/HttpHost;)V", AccessFlags = 1)]
public HttpRoute(global::Org.Apache.Http.HttpHost target) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Creates a new route through a proxy. When using this constructor, the <code>proxy</code> MUST be given. For convenience, it is assumed that a secure connection will be layered over a tunnel through the proxy.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Lorg/apache/http/HttpHost;Ljava/net/InetAddress;Lorg/apache/http/HttpHost;Z)V", AccessFlags = 1)]
public HttpRoute(global::Org.Apache.Http.HttpHost target, global::Java.Net.InetAddress local, global::Org.Apache.Http.HttpHost proxy, bool secure) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Obtains the target host.</para><para></para>
/// </summary>
/// <returns>
/// <para>the target host </para>
/// </returns>
/// <java-name>
/// getTargetHost
/// </java-name>
[Dot42.DexImport("getTargetHost", "()Lorg/apache/http/HttpHost;", AccessFlags = 17)]
public global::Org.Apache.Http.HttpHost GetTargetHost() /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.HttpHost);
}
/// <summary>
/// <para>Obtains the local address to connect from.</para><para></para>
/// </summary>
/// <returns>
/// <para>the local address, or <code>null</code> </para>
/// </returns>
/// <java-name>
/// getLocalAddress
/// </java-name>
[Dot42.DexImport("getLocalAddress", "()Ljava/net/InetAddress;", AccessFlags = 17)]
public global::Java.Net.InetAddress GetLocalAddress() /* MethodBuilder.Create */
{
return default(global::Java.Net.InetAddress);
}
/// <summary>
/// <para>Obtains the number of hops in this route. A direct route has one hop. A route through a proxy has two hops. A route through a chain of <b>n</b> proxies has <b>n+1</b> hops.</para><para></para>
/// </summary>
/// <returns>
/// <para>the number of hops in this route </para>
/// </returns>
/// <java-name>
/// getHopCount
/// </java-name>
[Dot42.DexImport("getHopCount", "()I", AccessFlags = 17)]
public int GetHopCount() /* MethodBuilder.Create */
{
return default(int);
}
/// <summary>
/// <para>Obtains the target of a hop in this route. The target of the last hop is the target host, the target of previous hops is the respective proxy in the chain. For a route through exactly one proxy, target of hop 0 is the proxy and target of hop 1 is the target host.</para><para></para>
/// </summary>
/// <returns>
/// <para>the target of the given hop</para>
/// </returns>
/// <java-name>
/// getHopTarget
/// </java-name>
[Dot42.DexImport("getHopTarget", "(I)Lorg/apache/http/HttpHost;", AccessFlags = 17)]
public global::Org.Apache.Http.HttpHost GetHopTarget(int hop) /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.HttpHost);
}
/// <summary>
/// <para>Obtains the first proxy host.</para><para></para>
/// </summary>
/// <returns>
/// <para>the first proxy in the proxy chain, or <code>null</code> if this route is direct </para>
/// </returns>
/// <java-name>
/// getProxyHost
/// </java-name>
[Dot42.DexImport("getProxyHost", "()Lorg/apache/http/HttpHost;", AccessFlags = 17)]
public global::Org.Apache.Http.HttpHost GetProxyHost() /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.HttpHost);
}
/// <summary>
/// <para>Obtains the tunnel type of this route. If there is a proxy chain, only end-to-end tunnels are considered.</para><para></para>
/// </summary>
/// <returns>
/// <para>the tunnelling type </para>
/// </returns>
/// <java-name>
/// getTunnelType
/// </java-name>
[Dot42.DexImport("getTunnelType", "()Lorg/apache/http/conn/routing/RouteInfo$TunnelType;", AccessFlags = 17)]
public global::Org.Apache.Http.Conn.Routing.IRouteInfo_TunnelType GetTunnelType() /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.Conn.Routing.IRouteInfo_TunnelType);
}
/// <summary>
/// <para>Checks whether this route is tunnelled through a proxy. If there is a proxy chain, only end-to-end tunnels are considered.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>true</code> if tunnelled end-to-end through at least one proxy, <code>false</code> otherwise </para>
/// </returns>
/// <java-name>
/// isTunnelled
/// </java-name>
[Dot42.DexImport("isTunnelled", "()Z", AccessFlags = 17)]
public bool IsTunnelled() /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Obtains the layering type of this route. In the presence of proxies, only layering over an end-to-end tunnel is considered.</para><para></para>
/// </summary>
/// <returns>
/// <para>the layering type </para>
/// </returns>
/// <java-name>
/// getLayerType
/// </java-name>
[Dot42.DexImport("getLayerType", "()Lorg/apache/http/conn/routing/RouteInfo$LayerType;", AccessFlags = 17)]
public global::Org.Apache.Http.Conn.Routing.IRouteInfo_LayerType GetLayerType() /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.Conn.Routing.IRouteInfo_LayerType);
}
/// <summary>
/// <para>Checks whether this route includes a layered protocol. In the presence of proxies, only layering over an end-to-end tunnel is considered.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>true</code> if layered, <code>false</code> otherwise </para>
/// </returns>
/// <java-name>
/// isLayered
/// </java-name>
[Dot42.DexImport("isLayered", "()Z", AccessFlags = 17)]
public bool IsLayered() /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Checks whether this route is secure.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>true</code> if secure, <code>false</code> otherwise </para>
/// </returns>
/// <java-name>
/// isSecure
/// </java-name>
[Dot42.DexImport("isSecure", "()Z", AccessFlags = 17)]
public bool IsSecure() /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Compares this route to another.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>true</code> if the argument is the same route, <code>false</code> </para>
/// </returns>
/// <java-name>
/// equals
/// </java-name>
[Dot42.DexImport("equals", "(Ljava/lang/Object;)Z", AccessFlags = 17)]
public override bool Equals(object o) /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Generates a hash code for this route.</para><para></para>
/// </summary>
/// <returns>
/// <para>the hash code </para>
/// </returns>
/// <java-name>
/// hashCode
/// </java-name>
[Dot42.DexImport("hashCode", "()I", AccessFlags = 17)]
public override int GetHashCode() /* MethodBuilder.Create */
{
return default(int);
}
/// <summary>
/// <para>Obtains a description of this route.</para><para></para>
/// </summary>
/// <returns>
/// <para>a human-readable representation of this route </para>
/// </returns>
/// <java-name>
/// toString
/// </java-name>
[Dot42.DexImport("toString", "()Ljava/lang/String;", AccessFlags = 17)]
public override string ToString() /* MethodBuilder.Create */
{
return default(string);
}
/// <java-name>
/// clone
/// </java-name>
[Dot42.DexImport("clone", "()Ljava/lang/Object;", AccessFlags = 1)]
public object Clone() /* MethodBuilder.Create */
{
return default(object);
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal HttpRoute() /* TypeBuilder.AddDefaultConstructor */
{
}
/// <summary>
/// <para>Obtains the target host.</para><para></para>
/// </summary>
/// <returns>
/// <para>the target host </para>
/// </returns>
/// <java-name>
/// getTargetHost
/// </java-name>
public global::Org.Apache.Http.HttpHost TargetHost
{
[Dot42.DexImport("getTargetHost", "()Lorg/apache/http/HttpHost;", AccessFlags = 17)]
get{ return GetTargetHost(); }
}
/// <summary>
/// <para>Obtains the local address to connect from.</para><para></para>
/// </summary>
/// <returns>
/// <para>the local address, or <code>null</code> </para>
/// </returns>
/// <java-name>
/// getLocalAddress
/// </java-name>
public global::Java.Net.InetAddress LocalAddress
{
[Dot42.DexImport("getLocalAddress", "()Ljava/net/InetAddress;", AccessFlags = 17)]
get{ return GetLocalAddress(); }
}
/// <summary>
/// <para>Obtains the number of hops in this route. A direct route has one hop. A route through a proxy has two hops. A route through a chain of <b>n</b> proxies has <b>n+1</b> hops.</para><para></para>
/// </summary>
/// <returns>
/// <para>the number of hops in this route </para>
/// </returns>
/// <java-name>
/// getHopCount
/// </java-name>
public int HopCount
{
[Dot42.DexImport("getHopCount", "()I", AccessFlags = 17)]
get{ return GetHopCount(); }
}
/// <summary>
/// <para>Obtains the first proxy host.</para><para></para>
/// </summary>
/// <returns>
/// <para>the first proxy in the proxy chain, or <code>null</code> if this route is direct </para>
/// </returns>
/// <java-name>
/// getProxyHost
/// </java-name>
public global::Org.Apache.Http.HttpHost ProxyHost
{
[Dot42.DexImport("getProxyHost", "()Lorg/apache/http/HttpHost;", AccessFlags = 17)]
get{ return GetProxyHost(); }
}
/// <summary>
/// <para>Obtains the tunnel type of this route. If there is a proxy chain, only end-to-end tunnels are considered.</para><para></para>
/// </summary>
/// <returns>
/// <para>the tunnelling type </para>
/// </returns>
/// <java-name>
/// getTunnelType
/// </java-name>
public global::Org.Apache.Http.Conn.Routing.IRouteInfo_TunnelType TunnelType
{
[Dot42.DexImport("getTunnelType", "()Lorg/apache/http/conn/routing/RouteInfo$TunnelType;", AccessFlags = 17)]
get{ return GetTunnelType(); }
}
/// <summary>
/// <para>Obtains the layering type of this route. In the presence of proxies, only layering over an end-to-end tunnel is considered.</para><para></para>
/// </summary>
/// <returns>
/// <para>the layering type </para>
/// </returns>
/// <java-name>
/// getLayerType
/// </java-name>
public global::Org.Apache.Http.Conn.Routing.IRouteInfo_LayerType LayerType
{
[Dot42.DexImport("getLayerType", "()Lorg/apache/http/conn/routing/RouteInfo$LayerType;", AccessFlags = 17)]
get{ return GetLayerType(); }
}
}
/// <summary>
/// <para>Encapsulates logic to compute a HttpRoute to a target host. Implementations may for example be based on parameters, or on the standard Java system properties. </para>
/// </summary>
/// <java-name>
/// org/apache/http/conn/routing/HttpRoutePlanner
/// </java-name>
[Dot42.DexImport("org/apache/http/conn/routing/HttpRoutePlanner", AccessFlags = 1537)]
public partial interface IHttpRoutePlanner
/* scope: __dot42__ */
{
/// <summary>
/// <para>Determines the route for a request.</para><para></para>
/// </summary>
/// <returns>
/// <para>the route that the request should take</para>
/// </returns>
/// <java-name>
/// determineRoute
/// </java-name>
[Dot42.DexImport("determineRoute", "(Lorg/apache/http/HttpHost;Lorg/apache/http/HttpRequest;Lorg/apache/http/protocol" +
"/HttpContext;)Lorg/apache/http/conn/routing/HttpRoute;", AccessFlags = 1025)]
global::Org.Apache.Http.Conn.Routing.HttpRoute DetermineRoute(global::Org.Apache.Http.HttpHost target, global::Org.Apache.Http.IHttpRequest request, global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>Basic implementation of an HttpRouteDirector. This implementation is stateless and therefore thread-safe.</para><para><para></para><para></para><title>Revision:</title><para>620255 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/conn/routing/BasicRouteDirector
/// </java-name>
[Dot42.DexImport("org/apache/http/conn/routing/BasicRouteDirector", AccessFlags = 33)]
public partial class BasicRouteDirector : global::Org.Apache.Http.Conn.Routing.IHttpRouteDirector
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public BasicRouteDirector() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Provides the next step.</para><para></para>
/// </summary>
/// <returns>
/// <para>one of the constants defined in this class, indicating either the next step to perform, or success, or failure. 0 is for success, a negative value for failure. </para>
/// </returns>
/// <java-name>
/// nextStep
/// </java-name>
[Dot42.DexImport("nextStep", "(Lorg/apache/http/conn/routing/RouteInfo;Lorg/apache/http/conn/routing/RouteInfo;" +
")I", AccessFlags = 1)]
public virtual int NextStep(global::Org.Apache.Http.Conn.Routing.IRouteInfo plan, global::Org.Apache.Http.Conn.Routing.IRouteInfo fact) /* MethodBuilder.Create */
{
return default(int);
}
/// <summary>
/// <para>Determines the first step to establish a route.</para><para></para>
/// </summary>
/// <returns>
/// <para>the first step </para>
/// </returns>
/// <java-name>
/// firstStep
/// </java-name>
[Dot42.DexImport("firstStep", "(Lorg/apache/http/conn/routing/RouteInfo;)I", AccessFlags = 4)]
protected internal virtual int FirstStep(global::Org.Apache.Http.Conn.Routing.IRouteInfo plan) /* MethodBuilder.Create */
{
return default(int);
}
/// <summary>
/// <para>Determines the next step to establish a direct connection.</para><para></para>
/// </summary>
/// <returns>
/// <para>one of the constants defined in this class, indicating either the next step to perform, or success, or failure </para>
/// </returns>
/// <java-name>
/// directStep
/// </java-name>
[Dot42.DexImport("directStep", "(Lorg/apache/http/conn/routing/RouteInfo;Lorg/apache/http/conn/routing/RouteInfo;" +
")I", AccessFlags = 4)]
protected internal virtual int DirectStep(global::Org.Apache.Http.Conn.Routing.IRouteInfo plan, global::Org.Apache.Http.Conn.Routing.IRouteInfo fact) /* MethodBuilder.Create */
{
return default(int);
}
/// <summary>
/// <para>Determines the next step to establish a connection via proxy.</para><para></para>
/// </summary>
/// <returns>
/// <para>one of the constants defined in this class, indicating either the next step to perform, or success, or failure </para>
/// </returns>
/// <java-name>
/// proxiedStep
/// </java-name>
[Dot42.DexImport("proxiedStep", "(Lorg/apache/http/conn/routing/RouteInfo;Lorg/apache/http/conn/routing/RouteInfo;" +
")I", AccessFlags = 4)]
protected internal virtual int ProxiedStep(global::Org.Apache.Http.Conn.Routing.IRouteInfo plan, global::Org.Apache.Http.Conn.Routing.IRouteInfo fact) /* MethodBuilder.Create */
{
return default(int);
}
}
/// <summary>
/// <para>Read-only interface for route information.</para><para><para></para><para></para><title>Revision:</title><para>652200 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/conn/routing/RouteInfo
/// </java-name>
[Dot42.DexImport("org/apache/http/conn/routing/RouteInfo", AccessFlags = 1537)]
public partial interface IRouteInfo
/* scope: __dot42__ */
{
/// <summary>
/// <para>Obtains the target host.</para><para></para>
/// </summary>
/// <returns>
/// <para>the target host </para>
/// </returns>
/// <java-name>
/// getTargetHost
/// </java-name>
[Dot42.DexImport("getTargetHost", "()Lorg/apache/http/HttpHost;", AccessFlags = 1025)]
global::Org.Apache.Http.HttpHost GetTargetHost() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Obtains the local address to connect from.</para><para></para>
/// </summary>
/// <returns>
/// <para>the local address, or <code>null</code> </para>
/// </returns>
/// <java-name>
/// getLocalAddress
/// </java-name>
[Dot42.DexImport("getLocalAddress", "()Ljava/net/InetAddress;", AccessFlags = 1025)]
global::Java.Net.InetAddress GetLocalAddress() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Obtains the number of hops in this route. A direct route has one hop. A route through a proxy has two hops. A route through a chain of <b>n</b> proxies has <b>n+1</b> hops.</para><para></para>
/// </summary>
/// <returns>
/// <para>the number of hops in this route </para>
/// </returns>
/// <java-name>
/// getHopCount
/// </java-name>
[Dot42.DexImport("getHopCount", "()I", AccessFlags = 1025)]
int GetHopCount() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Obtains the target of a hop in this route. The target of the last hop is the target host, the target of previous hops is the respective proxy in the chain. For a route through exactly one proxy, target of hop 0 is the proxy and target of hop 1 is the target host.</para><para></para>
/// </summary>
/// <returns>
/// <para>the target of the given hop</para>
/// </returns>
/// <java-name>
/// getHopTarget
/// </java-name>
[Dot42.DexImport("getHopTarget", "(I)Lorg/apache/http/HttpHost;", AccessFlags = 1025)]
global::Org.Apache.Http.HttpHost GetHopTarget(int hop) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Obtains the first proxy host.</para><para></para>
/// </summary>
/// <returns>
/// <para>the first proxy in the proxy chain, or <code>null</code> if this route is direct </para>
/// </returns>
/// <java-name>
/// getProxyHost
/// </java-name>
[Dot42.DexImport("getProxyHost", "()Lorg/apache/http/HttpHost;", AccessFlags = 1025)]
global::Org.Apache.Http.HttpHost GetProxyHost() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Obtains the tunnel type of this route. If there is a proxy chain, only end-to-end tunnels are considered.</para><para></para>
/// </summary>
/// <returns>
/// <para>the tunnelling type </para>
/// </returns>
/// <java-name>
/// getTunnelType
/// </java-name>
[Dot42.DexImport("getTunnelType", "()Lorg/apache/http/conn/routing/RouteInfo$TunnelType;", AccessFlags = 1025)]
global::Org.Apache.Http.Conn.Routing.IRouteInfo_TunnelType GetTunnelType() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Checks whether this route is tunnelled through a proxy. If there is a proxy chain, only end-to-end tunnels are considered.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>true</code> if tunnelled end-to-end through at least one proxy, <code>false</code> otherwise </para>
/// </returns>
/// <java-name>
/// isTunnelled
/// </java-name>
[Dot42.DexImport("isTunnelled", "()Z", AccessFlags = 1025)]
bool IsTunnelled() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Obtains the layering type of this route. In the presence of proxies, only layering over an end-to-end tunnel is considered.</para><para></para>
/// </summary>
/// <returns>
/// <para>the layering type </para>
/// </returns>
/// <java-name>
/// getLayerType
/// </java-name>
[Dot42.DexImport("getLayerType", "()Lorg/apache/http/conn/routing/RouteInfo$LayerType;", AccessFlags = 1025)]
global::Org.Apache.Http.Conn.Routing.IRouteInfo_LayerType GetLayerType() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Checks whether this route includes a layered protocol. In the presence of proxies, only layering over an end-to-end tunnel is considered.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>true</code> if layered, <code>false</code> otherwise </para>
/// </returns>
/// <java-name>
/// isLayered
/// </java-name>
[Dot42.DexImport("isLayered", "()Z", AccessFlags = 1025)]
bool IsLayered() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Checks whether this route is secure.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>true</code> if secure, <code>false</code> otherwise </para>
/// </returns>
/// <java-name>
/// isSecure
/// </java-name>
[Dot42.DexImport("isSecure", "()Z", AccessFlags = 1025)]
bool IsSecure() /* MethodBuilder.Create */ ;
}
/// <java-name>
/// org/apache/http/conn/routing/RouteInfo$LayerType
/// </java-name>
[Dot42.DexImport("org/apache/http/conn/routing/RouteInfo$LayerType", AccessFlags = 16409, Signature = "Ljava/lang/Enum<Lorg/apache/http/conn/routing/RouteInfo$LayerType;>;")]
public sealed class IRouteInfo_LayerType
/* scope: __dot42__ */
{
/// <java-name>
/// LAYERED
/// </java-name>
[Dot42.DexImport("LAYERED", "Lorg/apache/http/conn/routing/RouteInfo$LayerType;", AccessFlags = 16409)]
public static readonly global::Org.Apache.Http.Conn.Routing.IRouteInfo_LayerType LAYERED;
/// <java-name>
/// PLAIN
/// </java-name>
[Dot42.DexImport("PLAIN", "Lorg/apache/http/conn/routing/RouteInfo$LayerType;", AccessFlags = 16409)]
public static readonly global::Org.Apache.Http.Conn.Routing.IRouteInfo_LayerType PLAIN;
private IRouteInfo_LayerType() /* TypeBuilder.AddPrivateDefaultCtor */
{
}
}
/// <java-name>
/// org/apache/http/conn/routing/RouteInfo$TunnelType
/// </java-name>
[Dot42.DexImport("org/apache/http/conn/routing/RouteInfo$TunnelType", AccessFlags = 16409, Signature = "Ljava/lang/Enum<Lorg/apache/http/conn/routing/RouteInfo$TunnelType;>;")]
public sealed class IRouteInfo_TunnelType
/* scope: __dot42__ */
{
/// <java-name>
/// PLAIN
/// </java-name>
[Dot42.DexImport("PLAIN", "Lorg/apache/http/conn/routing/RouteInfo$TunnelType;", AccessFlags = 16409)]
public static readonly global::Org.Apache.Http.Conn.Routing.IRouteInfo_TunnelType PLAIN;
/// <java-name>
/// TUNNELLED
/// </java-name>
[Dot42.DexImport("TUNNELLED", "Lorg/apache/http/conn/routing/RouteInfo$TunnelType;", AccessFlags = 16409)]
public static readonly global::Org.Apache.Http.Conn.Routing.IRouteInfo_TunnelType TUNNELLED;
private IRouteInfo_TunnelType() /* TypeBuilder.AddPrivateDefaultCtor */
{
}
}
/// <summary>
/// <para>Provides directions on establishing a route. Implementations of this interface compare a planned route with a tracked route and indicate the next step required.</para><para><para></para><para></para><title>Revision:</title><para>620255 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/conn/routing/HttpRouteDirector
/// </java-name>
[Dot42.DexImport("org/apache/http/conn/routing/HttpRouteDirector", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)]
public static partial class IHttpRouteDirectorConstants
/* scope: __dot42__ */
{
/// <summary>
/// <para>Indicates that the route can not be established at all. </para>
/// </summary>
/// <java-name>
/// UNREACHABLE
/// </java-name>
[Dot42.DexImport("UNREACHABLE", "I", AccessFlags = 25)]
public const int UNREACHABLE = -1;
/// <summary>
/// <para>Indicates that the route is complete. </para>
/// </summary>
/// <java-name>
/// COMPLETE
/// </java-name>
[Dot42.DexImport("COMPLETE", "I", AccessFlags = 25)]
public const int COMPLETE = 0;
/// <summary>
/// <para>Step: open connection to target. </para>
/// </summary>
/// <java-name>
/// CONNECT_TARGET
/// </java-name>
[Dot42.DexImport("CONNECT_TARGET", "I", AccessFlags = 25)]
public const int CONNECT_TARGET = 1;
/// <summary>
/// <para>Step: open connection to proxy. </para>
/// </summary>
/// <java-name>
/// CONNECT_PROXY
/// </java-name>
[Dot42.DexImport("CONNECT_PROXY", "I", AccessFlags = 25)]
public const int CONNECT_PROXY = 2;
/// <summary>
/// <para>Step: tunnel through proxy to target. </para>
/// </summary>
/// <java-name>
/// TUNNEL_TARGET
/// </java-name>
[Dot42.DexImport("TUNNEL_TARGET", "I", AccessFlags = 25)]
public const int TUNNEL_TARGET = 3;
/// <summary>
/// <para>Step: tunnel through proxy to other proxy. </para>
/// </summary>
/// <java-name>
/// TUNNEL_PROXY
/// </java-name>
[Dot42.DexImport("TUNNEL_PROXY", "I", AccessFlags = 25)]
public const int TUNNEL_PROXY = 4;
/// <summary>
/// <para>Step: layer protocol (over tunnel). </para>
/// </summary>
/// <java-name>
/// LAYER_PROTOCOL
/// </java-name>
[Dot42.DexImport("LAYER_PROTOCOL", "I", AccessFlags = 25)]
public const int LAYER_PROTOCOL = 5;
}
/// <summary>
/// <para>Provides directions on establishing a route. Implementations of this interface compare a planned route with a tracked route and indicate the next step required.</para><para><para></para><para></para><title>Revision:</title><para>620255 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/conn/routing/HttpRouteDirector
/// </java-name>
[Dot42.DexImport("org/apache/http/conn/routing/HttpRouteDirector", AccessFlags = 1537)]
public partial interface IHttpRouteDirector
/* scope: __dot42__ */
{
/// <summary>
/// <para>Provides the next step.</para><para></para>
/// </summary>
/// <returns>
/// <para>one of the constants defined in this interface, indicating either the next step to perform, or success, or failure. 0 is for success, a negative value for failure. </para>
/// </returns>
/// <java-name>
/// nextStep
/// </java-name>
[Dot42.DexImport("nextStep", "(Lorg/apache/http/conn/routing/RouteInfo;Lorg/apache/http/conn/routing/RouteInfo;" +
")I", AccessFlags = 1025)]
int NextStep(global::Org.Apache.Http.Conn.Routing.IRouteInfo plan, global::Org.Apache.Http.Conn.Routing.IRouteInfo fact) /* MethodBuilder.Create */ ;
}
}
| |
#region Licence...
/*
The MIT License (MIT)
Copyright (c) 2015 Oleg Shilo
Permission is hereby granted,
free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion Licence...
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Text.RegularExpressions;
namespace WixSharp
{
internal static class RegFileImporter
{
public static bool SkipUnknownTypes = false;
static public RegValue[] ImportFrom(string regFile)
{
var result = new List<RegValue>();
string content = System.IO.File.ReadAllText(regFile);
content = Regex.Replace(content, @"\r\n|\n\r|\n|\r", "\r\n");
var parser = new RegParser();
char[] delimiter = { '\\' };
foreach (KeyValuePair<string, Dictionary<string, string>> entry in parser.Parse(content))
foreach (KeyValuePair<string, string> item in entry.Value)
{
string path = entry.Key;
var regval = new RegValue();
regval.Root = GetHive(path);
regval.Key = path.Split(delimiter, 2).Last();
regval.Name = item.Key;
regval.Value = Deserialize(item.Value, parser.Encoding);
if (regval.Value != null)
result.Add(regval);
}
return result.ToArray();
}
/*
hex: REG_BINARY
hex(0): REG_NONE
hex(1): REG_SZ (WiX string)
hex(2): REG_EXPAND_SZ (Wix expandable)
hex(3): REG_BINARY (WiX binary)
hex(4): REG_DWORD (WiX integer)
hex(5): REG_DWORD_BIG_ENDIAN ; invalid type ?
hex(6): REG_LINK
hex(7): REG_MULTI_SZ (WiX multiString)
hex(8): REG_RESOURCE_LIST
hex(9): REG_FULL_RESOURCE_DESCRIPTOR
hex(a): REG_RESOURCE_REQUIREMENTS_LIST
hex(b): REG_QWORD
*/
public static object Deserialize(string text, Encoding encoding)
{
//Note all string are encoded as Encoding.Unicode (UTF16LE)
//http://en.wikipedia.org/wiki/Windows_Registry
string rawValue = "";
Func<string, bool> isPreffix = preffix =>
{
if (text.StartsWith(preffix, StringComparison.OrdinalIgnoreCase))
{
rawValue = text.Substring(preffix.Length);
return true;
}
else
return false;
};
//WiX 'integer'
if (isPreffix("hex(4):") || isPreffix("dword:"))
return Convert.ToInt32(rawValue, 16);
//WiX 'multiString'
if (isPreffix("hex(7):"))
{
byte[] data = rawValue.Unescape().DecodeFromRegHex();
return encoding.GetString(data).TrimEnd('\0').Replace("\0", "\r\n");
}
//WiX 'expandable'
if (isPreffix("hex(2):"))
{
byte[] data = rawValue.Unescape().DecodeFromRegHex();
return encoding.GetString(data).TrimEnd('\0');
}
//WiX 'binary'
if (isPreffix("hex:"))
{
byte[] data = rawValue.Unescape().DecodeFromRegHex();
return data;
}
//WiX 'string'
if (isPreffix("hex(1):"))
return rawValue.Unescape();
if (isPreffix("\""))
{
var strValue = rawValue.Substring(0, rawValue.Length - 1); //trim a single " char
return Regex.Unescape(strValue).EscapeEnvars();
}
if (SkipUnknownTypes)
return null;
else
throw new Exception("Cannot deserialize RegFile value: '" + text + "'");
}
public static byte[] DecodeFromRegHex(this string obj)
{
var data = new List<byte>();
for (int i = 0; !string.IsNullOrEmpty(obj) && i < obj.Length;)
{
if (obj[i] == ',')
{
i++;
continue;
}
data.Add(byte.Parse(obj.Substring(i, 2), System.Globalization.NumberStyles.HexNumber));
i += 2;
}
return data.ToArray();
}
static string Unescape(this string text)
{
//Strip 'continue' char and merge string
return Regex.Replace(text, "\\\\\r\n[ ]*", string.Empty);
}
static RegistryHive GetHive(this string skey)
{
string tmpLine = skey.Trim();
if (tmpLine.StartsWith("HKEY_LOCAL_MACHINE\\"))
return RegistryHive.LocalMachine;
if (tmpLine.StartsWith("HKEY_CLASSES_ROOT\\"))
return RegistryHive.ClassesRoot;
if (tmpLine.StartsWith("HKEY_USERS\\"))
return RegistryHive.Users;
// if (tmpLine.StartsWith("HKEY_CURRENT_CONFIG\\"))
// return RegistryHive.CurrentConfig;
if (tmpLine.StartsWith("HKEY_CURRENT_USER\\"))
return RegistryHive.CurrentUser;
throw new Exception("Cannot extract hive from key path: " + skey);
}
}
/// <summary>
/// Based on Henryk Filipowicz work http://www.codeproject.com/Articles/125573/Registry-Export-File-reg-Parser
/// Licensed under The Code Project Open License (CPOL)
/// </summary>
internal class RegParser
{
public Encoding Encoding;
public Dictionary<string, Dictionary<string, string>> Entries;
/// <summary>
/// Parses the reg file for reg keys and reg values
/// </summary>
/// <returns>A Dictionary with reg keys as Dictionary keys and a Dictionary of (valuename, valuedata)</returns>
public Dictionary<string, Dictionary<string, string>> Parse(string content)
{
Encoding = this.GetEncoding(content);
var retValue = new Dictionary<string, Dictionary<string, string>>();
//Get registry keys and values content string
Dictionary<string, string> dictKeys = NormalizeDictionary("^[\t ]*\\[.+\\][\r\n]+", content, true);
//Get registry values for a given key
foreach (KeyValuePair<string, string> item in dictKeys)
{
Dictionary<string, string> dictValues = NormalizeDictionary("^[\t ]*(\".+\"|@)=", item.Value, false);
retValue.Add(item.Key, dictValues);
}
return Entries = retValue;
}
/// <summary>
/// Creates a flat Dictionary using given search pattern
/// </summary>
/// <param name="searchPattern">The search pattern</param>
/// <param name="content">The content string to be parsed</param>
/// <param name="stripeBraces">Flag for striping braces (true for reg keys, false for reg values)</param>
/// <returns>A Dictionary with retrieved keys and remaining content</returns>
Dictionary<string, string> NormalizeDictionary(string searchPattern, string content, bool stripeBraces)
{
MatchCollection matches = Regex.Matches(content, searchPattern, RegexOptions.Multiline);
Int32 startIndex = 0;
Int32 lengthIndex = 0;
var dictKeys = new Dictionary<string, string>();
foreach (Match match in matches)
{
try
{
//Retrieve key
string sKey = match.Value;
while (sKey.EndsWith("\r\n"))
sKey = sKey.Substring(0, sKey.Length - 2);
if (sKey.EndsWith("=")) sKey = sKey.Substring(0, sKey.Length - 1);
if (stripeBraces) sKey = StripeBraces(sKey);
if (sKey == "@")
sKey = "";
else
sKey = StripeLeadingChars(sKey, "\"");
//Retrieve value
startIndex = match.Index + match.Length;
Match nextMatch = match.NextMatch();
lengthIndex = ((nextMatch.Success) ? nextMatch.Index : content.Length) - startIndex;
string sValue = content.Substring(startIndex, lengthIndex);
//Removing the ending CR
while (sValue.EndsWith("\r\n"))
sValue = sValue.Substring(0, sValue.Length - 2);
dictKeys.Add(sKey, sValue);
}
catch (Exception ex)
{
throw new Exception(string.Format("Exception thrown on processing string {0}", match.Value), ex);
}
}
return dictKeys;
}
/// <summary>
/// Removes the leading and ending characters from the given string
/// </summary>
/// <param name="sLine">given string</param>
/// <param name="leadChar">The lead character.</param>
/// <returns>
/// edited string
/// </returns>
string StripeLeadingChars(string sLine, string leadChar)
{
string tmpvalue = sLine.Trim();
if (tmpvalue.StartsWith(leadChar) & tmpvalue.EndsWith(leadChar))
{
return tmpvalue.Substring(1, tmpvalue.Length - 2);
}
return tmpvalue;
}
/// <summary>
/// Removes the leading and ending parenthesis from the given string
/// </summary>
/// <param name="sLine">given string</param>
/// <returns>edited string</returns>
/// <remarks></remarks>
string StripeBraces(string sLine)
{
string tmpvalue = sLine.Trim();
if (tmpvalue.StartsWith("[") & tmpvalue.EndsWith("]"))
{
return tmpvalue.Substring(1, tmpvalue.Length - 2);
}
return tmpvalue;
}
/// <summary>
/// Retrieves the encoding of the reg file, checking the word "REGEDIT4"
/// </summary>
/// <returns></returns>
Encoding GetEncoding(string content)
{
if (Regex.IsMatch(content, "([ ]*(\r\n)*)REGEDIT4", RegexOptions.IgnoreCase | RegexOptions.Singleline))
return Encoding.Default;
else
return Encoding.Unicode; //The original code had a mistake. It is not UTF8 but UTF16LE (Encoding.Unicode)
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2014 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 NUnit.Framework;
using NUnit.Framework.Internal;
#if !SILVERLIGHT && !PORTABLE
using NUnitLite;
#endif
namespace NUnit.Tests
{
namespace Assemblies
{
/// <summary>
/// Constant definitions for the mock-assembly dll.
/// </summary>
public class MockAssembly
{
public const string FileName = "mock.nunit.assembly.exe";
public const int Classes = 9;
public const int NamespaceSuites = 6; // assembly, NUnit, Tests, Assemblies, Singletons, TestAssembly
public const int Tests = MockTestFixture.Tests
+ Singletons.OneTestCase.Tests
+ TestAssembly.MockTestFixture.Tests
+ IgnoredFixture.Tests
+ ExplicitFixture.Tests
+ BadFixture.Tests
+ FixtureWithTestCases.Tests
+ ParameterizedFixture.Tests
+ GenericFixtureConstants.Tests
+ CDataTestFixure.Tests
+ TestNameEscaping.Tests;
public const int Suites = MockTestFixture.Suites
+ Singletons.OneTestCase.Suites
+ TestAssembly.MockTestFixture.Suites
+ IgnoredFixture.Suites
+ ExplicitFixture.Suites
+ BadFixture.Suites
+ FixtureWithTestCases.Suites
+ ParameterizedFixture.Suites
+ GenericFixtureConstants.Suites
+ CDataTestFixure.Suites
+ TestNameEscaping.Suites
+ NamespaceSuites;
public const int Nodes = Tests + Suites;
public const int ExplicitFixtures = 1;
public const int SuitesRun = Suites - ExplicitFixtures;
public const int Ignored = MockTestFixture.Ignored + IgnoredFixture.Tests;
public const int Explicit = MockTestFixture.Explicit + ExplicitFixture.Tests;
public const int Skipped = Ignored + Explicit;
public const int NotRun = Ignored + Explicit + NotRunnable;
public const int TestsRun = Tests - NotRun;
public const int ResultCount = Tests - Explicit;
public const int Errors = MockTestFixture.Errors;
public const int Failures = MockTestFixture.Failures + CDataTestFixure.Failures;
public const int NotRunnable = MockTestFixture.NotRunnable + BadFixture.Tests;
public const int ErrorsAndFailures = Errors + Failures + NotRunnable;
public const int Inconclusive = MockTestFixture.Inconclusive;
public const int Success = TestsRun - Errors - Failures - Inconclusive;
#if !SILVERLIGHT && !PORTABLE
public static readonly string AssemblyPath = AssemblyHelper.GetAssemblyPath(typeof(MockAssembly).Assembly);
public static void Main(string[] args)
{
new AutoRun().Execute(args);
}
#endif
}
[TestFixture(Description="Fake Test Fixture")]
[Category("FixtureCategory")]
public class MockTestFixture
{
public const int Tests = 8;
public const int Suites = 1;
public const int Ignored = 1;
public const int Explicit = 1;
public const int NotRun = Ignored + Explicit;
public const int TestsRun = Tests - NotRun;
public const int ResultCount = Tests - Explicit;
public const int Failures = 1;
public const int Errors = 1;
public const int NotRunnable = 2;
public const int ErrorsAndFailures = Errors + Failures + NotRunnable;
public const int Inconclusive = 1;
[Test(Description="Mock Test #1")]
[Category("MockCategory")]
[Property("Severity", "Critical")]
public void TestWithDescription() { }
[Test]
protected static void NonPublicTest() { }
[Test]
public void FailingTest()
{
Assert.Fail("Intentional failure");
}
[Test, Ignore("Ignore Message")]
public void IgnoreTest() { }
[Test, Explicit]
public void ExplicitTest() { }
[Test]
public void NotRunnableTest( int a, int b) { }
[Test]
public void InconclusiveTest()
{
Assert.Inconclusive("No valid data");
}
[Test]
public void TestWithException()
{
MethodThrowsException();
}
private void MethodThrowsException()
{
throw new Exception("Intentional Exception");
}
}
}
namespace Singletons
{
[TestFixture]
public class OneTestCase
{
public const int Tests = 1;
public const int Suites = 1;
[Test]
public virtual void TestCase()
{}
}
}
namespace TestAssembly
{
[TestFixture]
public class MockTestFixture
{
public const int Tests = 1;
public const int Suites = 1;
[Test]
public void MyTest()
{
}
}
}
[TestFixture, Ignore("BECAUSE")]
public class IgnoredFixture
{
public const int Tests = 3;
public const int Suites = 1;
[Test]
public void Test1() { }
[Test]
public void Test2() { }
[Test]
public void Test3() { }
}
[TestFixture,Explicit]
public class ExplicitFixture
{
public const int Tests = 2;
public const int Suites = 1;
public const int Nodes = Tests + Suites;
[Test]
public void Test1() { }
[Test]
public void Test2() { }
}
[TestFixture]
public class BadFixture
{
public const int Tests = 1;
public const int Suites = 1;
public BadFixture(int val) { }
[Test]
public void SomeTest() { }
}
[TestFixture]
public class FixtureWithTestCases
{
public const int Tests = 4;
public const int Suites = 3;
[TestCase(2, 2, ExpectedResult=4)]
[TestCase(9, 11, ExpectedResult=20)]
public int MethodWithParameters(int x, int y)
{
return x+y;
}
[TestCase(2, 4)]
[TestCase(9.2, 11.7)]
public void GenericMethod<T>(T x, T y)
{
}
}
[TestFixture(5)]
[TestFixture(42)]
public class ParameterizedFixture
{
public const int Tests = 4;
public const int Suites = 3;
public ParameterizedFixture(int num) { }
[Test]
public void Test1() { }
[Test]
public void Test2() { }
}
public class GenericFixtureConstants
{
public const int Tests = 4;
public const int Suites = 3;
}
[TestFixture(5)]
[TestFixture(11.5)]
public class GenericFixture<T>
{
public GenericFixture(T num){ }
[Test]
public void Test1() { }
[Test]
public void Test2() { }
}
[TestFixture]
public class CDataTestFixure
{
public const int Tests = 4;
public const int Suites = 1;
public const int Failures = 2;
[Test]
public void DemonstrateIllegalSequenceInSuccessMessage()
{
Assert.Pass("Deliberate failure to illustrate ]]> in message ");
}
[Test]
public void DemonstrateIllegalSequenceAtEndOfSuccessMessage()
{
Assert.Pass("The CDATA was: <![CDATA[ My <xml> ]]>");
}
[Test]
public void DemonstrateIllegalSequenceInFailureMessage()
{
Assert.Fail("Deliberate failure to illustrate ]]> in message ");
}
[Test]
public void DemonstrateIllegalSequenceAtEndOfFailureMessage()
{
Assert.Fail("The CDATA was: <![CDATA[ My <xml> ]]>");
}
}
[TestFixture]
public class TestNameEscaping
{
public const int Tests = 10;
public const int Suites = 2;
[TestCase("< left bracket")]
[TestCase("> right bracket")]
[TestCase("'single quote'")]
[TestCase("\"double quote\"")]
[TestCase("&")]
public void MustBeEscaped(string str) { }
[TestCase("< left bracket", TestName = "<")]
[TestCase("> right bracket", TestName = ">")]
[TestCase("'single quote'", TestName = "'")]
[TestCase("double quote", TestName = "\"")]
[TestCase("amp", TestName = "&")]
public void MustBeEscaped_CustomName(string str) { }
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.