context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
using System;
using NSubstitute;
using Xunit;
namespace Extensions.Standard.Randomization.Test
{
public class UtilitiesTest
{
[Fact]
public void RandByteTest1()
{
const int repeats = 100;
var onesCounter = 0;
var zeroesCounter = 0;
var errorCounter = 0;
var rng = new Random();
for (var i = 0; i < repeats; ++i)
{
var x = rng.NextByte(2);
if (x == 0)
++zeroesCounter;
else if (x == 1)
++onesCounter;
else
++errorCounter;
}
Assert.Equal(0, errorCounter);
Assert.Equal(repeats, zeroesCounter + onesCounter);
}
[Fact]
public void RandByteTest2()
{
var repeats = 100;
var rng = new Random();
for (var i = 0; i < repeats; ++i)
{
var res = rng.NextByte();
}
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(2)]
[InlineData(3)]
[InlineData(4)]
[InlineData(999)]
public void NextBoolReturnsTrueOrFalse(int rand)
{
var randomSubstitute = Substitute.For<Random>();
randomSubstitute.Next().Returns(rand);
var expected = rand % 2 == 0;
Assert.Equal(expected, randomSubstitute.NextBool());
Assert.Equal(expected, randomSubstitute.NextBool());
Assert.Equal(expected, randomSubstitute.NextBool());
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(2)]
[InlineData(3)]
[InlineData(4)]
[InlineData(999)]
public void NextCharRetrunsValidResult(int low)
{
var high = low + 2;
var randomSubstitute = Substitute.For<Random>();
randomSubstitute.Next(Arg.Is(low), Arg.Is(high)).Returns(low);
var expected = (char)low;
Assert.Equal(expected, randomSubstitute.NextChar((char)low, (char)high));
}
[Theory]
[InlineData('a')]
[InlineData('b')]
[InlineData('z')]
public void NextLowercaseLetterRetrunsValidResult(int expected)
{
var randomSubstitute = Substitute.For<Random>();
randomSubstitute.Next(Arg.Any<int>(), Arg.Any<int>()).Returns(expected);
var received = randomSubstitute.NextLowercaseLetter();
randomSubstitute.DidNotReceive().Next(Arg.Is<int>(x => x < 'a'), Arg.Any<int>());
randomSubstitute.DidNotReceive().Next(Arg.Any<int>(), Arg.Is<int>(x => x > 123));
randomSubstitute.Received(1).Next(Arg.Is<int>(97), Arg.Is<int>(123));
}
[Theory]
[InlineData('A')]
[InlineData('B')]
[InlineData('Z')]
public void NextUppercaseLetterLetterRetrunsValidResult(int expected)
{
var randomSubstitute = Substitute.For<Random>();
randomSubstitute.Next(Arg.Any<int>(), Arg.Any<int>()).Returns(expected);
var received = randomSubstitute.NextUppercaseLetter();
randomSubstitute.DidNotReceive().Next(Arg.Is<int>(x => x < 'A'), Arg.Any<int>());
randomSubstitute.DidNotReceive().Next(Arg.Any<int>(), Arg.Is<int>(x => x > 91));
randomSubstitute.Received(1).Next(Arg.Is<int>(65), Arg.Is<int>(91));
}
[Fact]
public void NextLetterRetrunsValidResult()
{
var randomSubstitute = Substitute.For<Random>();
for (int i = 'A'; i < 'Z' + 1; ++i)
{
randomSubstitute.Next(Arg.Any<int>()).Returns(i - 'A');
Assert.Equal(i, randomSubstitute.NextLetter());
}
for (int i = 'a'; i < 123; ++i)
{
randomSubstitute.Next(Arg.Any<int>()).Returns(i - 'a' + 26);
Assert.Equal(i, randomSubstitute.NextLetter());
}
}
[Theory]
[InlineData("test")]
[InlineData(".NETStandard")]
public void NextAlphanumericRetrunsValidResult(string toChooseFrom)
{
var randomSubstitute = Substitute.For<Random>();
for (int i = '0'; i < '9' + 1; ++i)
{
randomSubstitute.Next(Arg.Any<int>()).Returns(i - '0');
Assert.Equal(i, randomSubstitute.NextAlphanumeric());
}
for (int i = 'A'; i < 'Z' + 1; ++i)
{
randomSubstitute.Next(Arg.Any<int>()).Returns(i - 'A' + 10);
Assert.Equal(i, randomSubstitute.NextAlphanumeric());
}
for (int i = 'a'; i < 123; ++i)
{
randomSubstitute.Next(Arg.Any<int>()).Returns(i - 'a' + 26 + 10);
Assert.Equal(i, randomSubstitute.NextAlphanumeric());
}
}
[Fact]
public void NextFloatRetrunsValidResult()
{
var randomSubstitute = Substitute.For<Random>();
randomSubstitute.NextDouble().Returns(.5);
Assert.Equal(.5, randomSubstitute.NextFloat());
Assert.IsType<float>(randomSubstitute.NextFloat());
}
[Theory]
[InlineData(1)]
[InlineData(10)]
[InlineData(100)]
[InlineData(1000000)]
public void NextFloatRangeRetrunsValidResult(float max)
{
var randomSubstitute = Substitute.For<Random>();
var almostOne = 0.9999999999999f;
randomSubstitute.NextDouble().Returns(almostOne);
var received = randomSubstitute.NextFloat(-max, max);
Assert.Equal(max, received);
}
[Fact]
public void NextFloatEdgeCase()
{
var randomSubstitute = Substitute.For<Random>();
var almostOne = 0.9999999999999f;
randomSubstitute.NextDouble().Returns(almostOne);
var received = randomSubstitute.NextFloat(float.MinValue, float.MaxValue);
Assert.Equal(float.MaxValue, received);
}
[Theory]
[InlineData(1.0)]
[InlineData(0.01)]
[InlineData(1111.0)]
[InlineData(15002900.0)]
public void NextDoubleReturnsMultiplied(double input)
{
var randomSubstitute = Substitute.For<Random>();
var almostOne = 0.9999999999999f;
randomSubstitute.NextDouble().Returns(almostOne);
var received = randomSubstitute.NextDouble(input);
Assert.Equal(almostOne * input, received);
}
[Theory]
[InlineData(1.0)]
[InlineData(0.01)]
[InlineData(1111.0)]
[InlineData(15002900.0)]
public void NextDoubleReturnsScaledForMinMax(double input)
{
var randomSubstitute = Substitute.For<Random>();
var almostOne = 0.9999999999999;
randomSubstitute.NextDouble().Returns(almostOne);
var received = randomSubstitute.NextDouble(-input, input);
Assert.Equal(Math.Round(almostOne * input, 5), Math.Round(received, 5));
}
[Fact]
public void NextDoubleThrowsWhenMinGreaterThanMax()
{
var randomSubstitute = Substitute.For<Random>();
Assert.Throws<ArgumentOutOfRangeException>(() => randomSubstitute.NextDouble(1000, -1100));
}
[Fact]
public void NextDoubleEdgeCaseDoesNotThrow()
{
var randomSubstitute = Substitute.For<Random>();
var almostOne = 0.9999999999999;
randomSubstitute.NextDouble().Returns(almostOne);
var expected = double.MinValue + almostOne * double.MaxValue - almostOne * double.MinValue;
var received = randomSubstitute.NextDouble(double.MinValue, double.MaxValue);
Assert.Equal(Math.Round(expected), Math.Round(received));
}
[Theory]
[InlineData(-1.120)]
[InlineData(-11.0)]
public void NextDoubleThrowsForMaxLessThanZero(double input)
{
var randomSubstitute = Substitute.For<Random>();
var almostOne = 0.9999999999999f;
randomSubstitute.NextDouble().Returns(almostOne);
Assert.Throws<ArgumentOutOfRangeException>(() => randomSubstitute.NextDouble(input));
}
}
}
| |
// 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.
// ------------------------------------------------------------------------------
// Changes to this file must follow the http://aka.ms/api-review process.
// ------------------------------------------------------------------------------
namespace Microsoft.Win32.SafeHandles
{
public sealed partial class SafeAccessTokenHandle : System.Runtime.InteropServices.SafeHandle
{
public SafeAccessTokenHandle(System.IntPtr handle) : base (default(System.IntPtr), default(bool)) { }
public static Microsoft.Win32.SafeHandles.SafeAccessTokenHandle InvalidHandle { get { throw null; } }
public override bool IsInvalid { get { throw null; } }
protected override bool ReleaseHandle() { throw null; }
}
}
namespace System.Security.Principal
{
public sealed partial class IdentityNotMappedException : System.SystemException
{
public IdentityNotMappedException() { }
public IdentityNotMappedException(string message) { }
public IdentityNotMappedException(string message, System.Exception inner) { }
public System.Security.Principal.IdentityReferenceCollection UnmappedIdentities { get { throw null; } }
public override void GetObjectData(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) { }
}
public abstract partial class IdentityReference
{
internal IdentityReference() { }
public abstract string Value { get; }
public abstract override bool Equals(object o);
public abstract override int GetHashCode();
public abstract bool IsValidTargetType(System.Type targetType);
public static bool operator ==(System.Security.Principal.IdentityReference left, System.Security.Principal.IdentityReference right) { throw null; }
public static bool operator !=(System.Security.Principal.IdentityReference left, System.Security.Principal.IdentityReference right) { throw null; }
public abstract override string ToString();
public abstract System.Security.Principal.IdentityReference Translate(System.Type targetType);
}
public partial class IdentityReferenceCollection : System.Collections.Generic.ICollection<System.Security.Principal.IdentityReference>, System.Collections.Generic.IEnumerable<System.Security.Principal.IdentityReference>, System.Collections.IEnumerable
{
public IdentityReferenceCollection() { }
public IdentityReferenceCollection(int capacity) { }
public int Count { get { throw null; } }
public System.Security.Principal.IdentityReference this[int index] { get { throw null; } set { } }
bool System.Collections.Generic.ICollection<System.Security.Principal.IdentityReference>.IsReadOnly { get { throw null; } }
public void Add(System.Security.Principal.IdentityReference identity) { }
public void Clear() { }
public bool Contains(System.Security.Principal.IdentityReference identity) { throw null; }
public void CopyTo(System.Security.Principal.IdentityReference[] array, int offset) { }
public System.Collections.Generic.IEnumerator<System.Security.Principal.IdentityReference> GetEnumerator() { throw null; }
public bool Remove(System.Security.Principal.IdentityReference identity) { throw null; }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; }
public System.Security.Principal.IdentityReferenceCollection Translate(System.Type targetType) { throw null; }
public System.Security.Principal.IdentityReferenceCollection Translate(System.Type targetType, bool forceSuccess) { throw null; }
}
public sealed partial class NTAccount : System.Security.Principal.IdentityReference
{
public NTAccount(string name) { }
public NTAccount(string domainName, string accountName) { }
public override string Value { get { throw null; } }
public override bool Equals(object o) { throw null; }
public override int GetHashCode() { throw null; }
public override bool IsValidTargetType(System.Type targetType) { throw null; }
public static bool operator ==(System.Security.Principal.NTAccount left, System.Security.Principal.NTAccount right) { throw null; }
public static bool operator !=(System.Security.Principal.NTAccount left, System.Security.Principal.NTAccount right) { throw null; }
public override string ToString() { throw null; }
public override System.Security.Principal.IdentityReference Translate(System.Type targetType) { throw null; }
}
public sealed partial class SecurityIdentifier : System.Security.Principal.IdentityReference, System.IComparable<System.Security.Principal.SecurityIdentifier>
{
public static readonly int MaxBinaryLength;
public static readonly int MinBinaryLength;
public SecurityIdentifier(byte[] binaryForm, int offset) { }
public SecurityIdentifier(System.IntPtr binaryForm) { }
public SecurityIdentifier(System.Security.Principal.WellKnownSidType sidType, System.Security.Principal.SecurityIdentifier domainSid) { }
public SecurityIdentifier(string sddlForm) { }
public System.Security.Principal.SecurityIdentifier AccountDomainSid { get { throw null; } }
public int BinaryLength { get { throw null; } }
public override string Value { get { throw null; } }
public int CompareTo(System.Security.Principal.SecurityIdentifier sid) { throw null; }
public override bool Equals(object o) { throw null; }
public bool Equals(System.Security.Principal.SecurityIdentifier sid) { throw null; }
public void GetBinaryForm(byte[] binaryForm, int offset) { }
public override int GetHashCode() { throw null; }
public bool IsAccountSid() { throw null; }
public bool IsEqualDomainSid(System.Security.Principal.SecurityIdentifier sid) { throw null; }
public override bool IsValidTargetType(System.Type targetType) { throw null; }
public bool IsWellKnown(System.Security.Principal.WellKnownSidType type) { throw null; }
public static bool operator ==(System.Security.Principal.SecurityIdentifier left, System.Security.Principal.SecurityIdentifier right) { throw null; }
public static bool operator !=(System.Security.Principal.SecurityIdentifier left, System.Security.Principal.SecurityIdentifier right) { throw null; }
public override string ToString() { throw null; }
public override System.Security.Principal.IdentityReference Translate(System.Type targetType) { throw null; }
}
[System.FlagsAttribute]
public enum TokenAccessLevels
{
AdjustDefault = 128,
AdjustGroups = 64,
AdjustPrivileges = 32,
AdjustSessionId = 256,
AllAccess = 983551,
AssignPrimary = 1,
Duplicate = 2,
Impersonate = 4,
MaximumAllowed = 33554432,
Query = 8,
QuerySource = 16,
Read = 131080,
Write = 131296,
}
public enum WellKnownSidType
{
AccountAdministratorSid = 38,
AccountCertAdminsSid = 46,
AccountComputersSid = 44,
AccountControllersSid = 45,
AccountDomainAdminsSid = 41,
AccountDomainGuestsSid = 43,
AccountDomainUsersSid = 42,
AccountEnterpriseAdminsSid = 48,
AccountGuestSid = 39,
AccountKrbtgtSid = 40,
AccountPolicyAdminsSid = 49,
AccountRasAndIasServersSid = 50,
AccountSchemaAdminsSid = 47,
AnonymousSid = 13,
AuthenticatedUserSid = 17,
BatchSid = 10,
BuiltinAccountOperatorsSid = 30,
BuiltinAdministratorsSid = 26,
BuiltinAuthorizationAccessSid = 59,
BuiltinBackupOperatorsSid = 33,
BuiltinDomainSid = 25,
BuiltinGuestsSid = 28,
BuiltinIncomingForestTrustBuildersSid = 56,
BuiltinNetworkConfigurationOperatorsSid = 37,
BuiltinPerformanceLoggingUsersSid = 58,
BuiltinPerformanceMonitoringUsersSid = 57,
BuiltinPowerUsersSid = 29,
BuiltinPreWindows2000CompatibleAccessSid = 35,
BuiltinPrintOperatorsSid = 32,
BuiltinRemoteDesktopUsersSid = 36,
BuiltinReplicatorSid = 34,
BuiltinSystemOperatorsSid = 31,
BuiltinUsersSid = 27,
CreatorGroupServerSid = 6,
CreatorGroupSid = 4,
CreatorOwnerServerSid = 5,
CreatorOwnerSid = 3,
DialupSid = 8,
DigestAuthenticationSid = 52,
EnterpriseControllersSid = 15,
InteractiveSid = 11,
LocalServiceSid = 23,
LocalSid = 2,
LocalSystemSid = 22,
LogonIdsSid = 21,
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
[System.ObsoleteAttribute("This member has been depcreated and is only maintained for backwards compatability. WellKnownSidType values greater than MaxDefined may be defined in future releases.")]
MaxDefined = 60,
NetworkServiceSid = 24,
NetworkSid = 9,
NTAuthoritySid = 7,
NtlmAuthenticationSid = 51,
NullSid = 0,
OtherOrganizationSid = 55,
ProxySid = 14,
RemoteLogonIdSid = 20,
RestrictedCodeSid = 18,
SChannelAuthenticationSid = 53,
SelfSid = 16,
ServiceSid = 12,
TerminalServerSid = 19,
ThisOrganizationSid = 54,
WinAccountReadonlyControllersSid = 75,
WinApplicationPackageAuthoritySid = 83,
WinBuiltinAnyPackageSid = 84,
WinBuiltinCertSvcDComAccessGroup = 78,
WinBuiltinCryptoOperatorsSid = 64,
WinBuiltinDCOMUsersSid = 61,
WinBuiltinEventLogReadersGroup = 76,
WinBuiltinIUsersSid = 62,
WinBuiltinTerminalServerLicenseServersSid = 60,
WinCacheablePrincipalsGroupSid = 72,
WinCapabilityDocumentsLibrarySid = 91,
WinCapabilityEnterpriseAuthenticationSid = 93,
WinCapabilityInternetClientServerSid = 86,
WinCapabilityInternetClientSid = 85,
WinCapabilityMusicLibrarySid = 90,
WinCapabilityPicturesLibrarySid = 88,
WinCapabilityPrivateNetworkClientServerSid = 87,
WinCapabilityRemovableStorageSid = 94,
WinCapabilitySharedUserCertificatesSid = 92,
WinCapabilityVideosLibrarySid = 89,
WinConsoleLogonSid = 81,
WinCreatorOwnerRightsSid = 71,
WinEnterpriseReadonlyControllersSid = 74,
WinHighLabelSid = 68,
WinIUserSid = 63,
WinLocalLogonSid = 80,
WinLowLabelSid = 66,
WinMediumLabelSid = 67,
WinMediumPlusLabelSid = 79,
WinNewEnterpriseReadonlyControllersSid = 77,
WinNonCacheablePrincipalsGroupSid = 73,
WinSystemLabelSid = 69,
WinThisOrganizationCertificateSid = 82,
WinUntrustedLabelSid = 65,
WinWriteRestrictedCodeSid = 70,
WorldSid = 1,
}
[System.Runtime.InteropServices.ComVisibleAttribute(true)]
public enum WindowsAccountType
{
Anonymous = 3,
Guest = 1,
Normal = 0,
System = 2,
}
public enum WindowsBuiltInRole
{
AccountOperator = 548,
Administrator = 544,
BackupOperator = 551,
Guest = 546,
PowerUser = 547,
PrintOperator = 550,
Replicator = 552,
SystemOperator = 549,
User = 545,
}
public partial class WindowsIdentity : System.Security.Claims.ClaimsIdentity, System.IDisposable, System.Runtime.Serialization.IDeserializationCallback, System.Runtime.Serialization.ISerializable
{
public new const string DefaultIssuer = "AD AUTHORITY";
public WindowsIdentity(System.IntPtr userToken) { }
public WindowsIdentity(System.IntPtr userToken, string type) { }
public WindowsIdentity(System.IntPtr userToken, string type, System.Security.Principal.WindowsAccountType acctType) { }
public WindowsIdentity(System.IntPtr userToken, string type, System.Security.Principal.WindowsAccountType acctType, bool isAuthenticated) { }
public WindowsIdentity(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
protected WindowsIdentity(System.Security.Principal.WindowsIdentity identity) { }
public WindowsIdentity(string sUserPrincipalName) { }
public Microsoft.Win32.SafeHandles.SafeAccessTokenHandle AccessToken { get { throw null; } }
public sealed override string AuthenticationType { get { throw null; } }
public override System.Collections.Generic.IEnumerable<System.Security.Claims.Claim> Claims { get { throw null; } }
public virtual System.Collections.Generic.IEnumerable<System.Security.Claims.Claim> DeviceClaims { get { throw null; } }
public System.Security.Principal.IdentityReferenceCollection Groups { get { throw null; } }
public System.Security.Principal.TokenImpersonationLevel ImpersonationLevel { get { throw null; } }
public virtual bool IsAnonymous { get { throw null; } }
public override bool IsAuthenticated { get { throw null; } }
public virtual bool IsGuest { get { throw null; } }
public virtual bool IsSystem { get { throw null; } }
public override string Name { get { throw null; } }
public System.Security.Principal.SecurityIdentifier Owner { get { throw null; } }
public virtual System.IntPtr Token { get { throw null; } }
public System.Security.Principal.SecurityIdentifier User { get { throw null; } }
public virtual System.Collections.Generic.IEnumerable<System.Security.Claims.Claim> UserClaims { get { throw null; } }
public override System.Security.Claims.ClaimsIdentity Clone() { throw null; }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
public static System.Security.Principal.WindowsIdentity GetAnonymous() { throw null; }
public static System.Security.Principal.WindowsIdentity GetCurrent() { throw null; }
public static System.Security.Principal.WindowsIdentity GetCurrent(bool ifImpersonating) { throw null; }
public static System.Security.Principal.WindowsIdentity GetCurrent(System.Security.Principal.TokenAccessLevels desiredAccess) { throw null; }
public static void RunImpersonated(Microsoft.Win32.SafeHandles.SafeAccessTokenHandle safeAccessTokenHandle, System.Action action) { }
public static T RunImpersonated<T>(Microsoft.Win32.SafeHandles.SafeAccessTokenHandle safeAccessTokenHandle, System.Func<T> func) { throw null; }
void System.Runtime.Serialization.IDeserializationCallback.OnDeserialization(object sender) { }
void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
}
public partial class WindowsPrincipal : System.Security.Claims.ClaimsPrincipal
{
public WindowsPrincipal(System.Security.Principal.WindowsIdentity ntIdentity) { }
public virtual System.Collections.Generic.IEnumerable<System.Security.Claims.Claim> DeviceClaims { get { throw null; } }
public override System.Security.Principal.IIdentity Identity { get { throw null; } }
public virtual System.Collections.Generic.IEnumerable<System.Security.Claims.Claim> UserClaims { get { throw null; } }
public virtual bool IsInRole(int rid) { throw null; }
public virtual bool IsInRole(System.Security.Principal.SecurityIdentifier sid) { throw null; }
public virtual bool IsInRole(System.Security.Principal.WindowsBuiltInRole role) { throw null; }
public override bool IsInRole(string role) { throw null; }
}
}
| |
//
// PhotoGridViewChild.cs
//
// Author:
// Mike Gemuende <mike@gemuende.de>
// Ruben Vermeersch <ruben@savanne.be>
//
// Copyright (c) 2010 Mike Gemuende
// Copyright (c) 2010 Ruben Vermeersch
//
// 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.Threading.Tasks;
using Tripod.Base;
using Tripod.Sources;
using Tripod.Tasks;
using Tripod.Graphics;
using Hyena;
using Hyena.Gui;
using Hyena.Data.Gui;
using Hyena.Gui.Theming;
using Hyena.Gui.Theatrics;
using Hyena.Gui.Canvas;
using Gtk;
using Cairo;
namespace Tripod.Model.Gui
{
public class PhotoGridViewChild : DataViewChild
{
static PhotoGridViewChild ()
{
}
#region Public Layout Properties
public int ThumbnailWidth { get { return (ParentLayout as PhotoGridViewLayout).ThumbnailWidth; } }
public int ThumbnailHeight { get { return (ParentLayout as PhotoGridViewLayout).ThumbnailHeight; } }
public double CaptionSpacing { get; set; }
#endregion
#region Private Layout Values
private bool valid;
private Rect inner_allocation;
private Rect thumbnail_allocation;
private Rect caption_allocation;
#endregion
#region Constructors
public PhotoGridViewChild ()
{
Padding = new Thickness (5);
CaptionSpacing = 10;
}
#endregion
#region Public Methods
public void InvalidateThumbnail ()
{
Invalidate (inner_allocation);
}
public IPhoto BoundPhoto {
get { return BoundObject as IPhoto; }
}
#endregion
public static void RenderThumbnail (Cairo.Context cr, ImageSurface image, bool dispose,
double x, double y, double width, double height, double radius,
bool fill, Cairo.Color fillColor, CairoCorners corners, double scale)
{
if (image == null || image.Handle == IntPtr.Zero) {
image = null;
}
double p_x = x;
double p_y = y;
if (image != null) {
double scaled_image_width = scale * image.Width;
double scaled_image_height = scale * image.Height;
p_x += (scaled_image_width < width ? (width - scaled_image_width) / 2 : 0) / scale;
p_y += (scaled_image_height < height ? (height - scaled_image_height) / 2 : 0) / scale;
}
cr.Antialias = Cairo.Antialias.Default;
if (image != null) {
if (fill) {
CairoExtensions.RoundedRectangle (cr, x, y, width, height, radius, corners);
cr.Color = fillColor;
cr.Fill ();
}
cr.Scale (scale, scale);
CairoExtensions.RoundedRectangle (cr, p_x, p_y, image.Width, image.Height, radius, corners);
cr.SetSource (image, p_x, p_y);
cr.Fill ();
cr.Scale (1.0/scale, 1.0/scale);
} else {
CairoExtensions.RoundedRectangle (cr, x, y, width, height, radius, corners);
if (fill) {
var grad = new LinearGradient (x, y, x, y + height);
grad.AddColorStop (0, fillColor);
grad.AddColorStop (1, CairoExtensions.ColorShade (fillColor, 1.3));
cr.Pattern = grad;
cr.Fill ();
grad.Destroy ();
}
}
cr.Stroke ();
if (dispose && image != null) {
((IDisposable)image).Dispose ();
}
}
#region DataViewChild Implementation
CancellableTask<Gdk.Pixbuf> last_loader_task = null;
IPhoto last_photo;
void Reload (IPhoto photo)
{
if (last_loader_task != null) {
// last_loader_task.Cancel (); // FIXME: Re-enable this!
if (last_loader_task.IsCompleted) {
last_loader_task.Result.Dispose ();
}
}
var loader = Core.PhotoLoaderCache.RequestLoader (photo);
last_loader_task = loader.FindBestPreview (ThumbnailWidth, ThumbnailHeight);
last_loader_task.ContinueWith ((t) => {
var new_surface = PixbufImageSurface.Create (last_loader_task.Result);
var cache = (ParentLayout as PhotoGridViewLayout).SurfaceCache;
ThreadAssist.ProxyToMain (() => {
ImageSurface old_surface = null;
if (cache.TryGetValue (photo, out old_surface)) {
if (old_surface != null)
old_surface.Dispose ();
}
cache[photo] = new_surface;
(ParentLayout.View as PhotoGridView).InvalidateThumbnail (photo);
});
}, TaskContinuationOptions.NotOnCanceled);
}
bool finding_larger = false;
void ReloadIfBetterSizeAvailable (IPhoto photo, int have_width, int have_height) {
if (finding_larger)
return;
finding_larger = true;
var loader = Core.PhotoLoaderCache.RequestLoader (photo);
var task = loader.IsBestPreview (have_width, have_height, ThumbnailWidth, ThumbnailHeight);
task.ContinueWith ((t) => {
if (!t.Result) {
Reload (photo);
}
finding_larger = false;
});
}
void ReloadIfSuboptimalSize (IPhoto photo) {
if (photo == null || finding_larger)
return;
ImageSurface image_surface = null;
if (!(ParentLayout as PhotoGridViewLayout).SurfaceCache.TryGetValue (photo, out image_surface))
return;
var surface_w = image_surface.Width;
var surface_h = image_surface.Height;
var alloc_w = thumbnail_allocation.Width;
var alloc_h = thumbnail_allocation.Height;
// Make sure we have the most optimal surface size.
bool too_small = surface_w < alloc_w && surface_h < alloc_h;
if (too_small) {
// Thumbnail never touches the edges.
ReloadIfBetterSizeAvailable (photo, surface_w, surface_h);
} else {
// Downscale if we're twice too large on the longest edge.
bool wider_than_high = surface_w > surface_h;
bool too_wide = surface_w > 2 * alloc_w;
bool too_high = surface_h > 2 * alloc_h;
if ((wider_than_high && too_wide) || too_high) {
ReloadIfBetterSizeAvailable (photo, surface_w, surface_h);
}
}
}
public override void Render (CellContext context)
{
if (inner_allocation.IsEmpty || ! valid)
return;
context.Context.Translate (inner_allocation.X, inner_allocation.Y);
var photo = BoundPhoto;
var view_layout = ParentLayout as PhotoGridViewLayout;
if (photo != last_photo) {
last_photo = photo;
Reload (photo);
}
view_layout.CaptionRender.Render (context, caption_allocation, photo);
ThreadAssist.BlockingProxyToMain (() => {
RenderThumbnail (photo, context);
ReloadIfSuboptimalSize (photo);
});
}
void RenderThumbnail (IPhoto photo, CellContext context)
{
ImageSurface image_surface = null;
if (!(ParentLayout as PhotoGridViewLayout).SurfaceCache.TryGetValue (photo, out image_surface))
return;
// Scale needed to fill the grid slot.
double scalex = image_surface.Width / thumbnail_allocation.Width;
double scaley = image_surface.Height / thumbnail_allocation.Height;
// Upscale if the photo is larger than the allocation.
bool upscale = photo.Width > thumbnail_allocation.Width || photo.Height > thumbnail_allocation.Height;
if (!upscale) {
scalex = Math.Max (1.0, scalex);
scaley = Math.Max (1.0, scaley);
}
double scale = 1 / Math.Max (scalex, scaley);
RenderThumbnail (context.Context,
image_surface,
false,
0.0,
0.0,
thumbnail_allocation.Width,
thumbnail_allocation.Height,
context.Theme.Context.Radius,
false,
new Color (0.8, 0.0, 0.0),
CairoCorners.All, scale);
}
public override void Arrange ()
{
if (BoundObject == null) {
valid = false;
return;
}
IPhoto photo = BoundObject as IPhoto;
if (photo == null)
throw new InvalidCastException ("PhotoGridViewChild can only bind IPhoto objects");
valid = true;
inner_allocation = new Rect () {
X = Padding.Left,
Y = Padding.Top,
Width = Allocation.Width - Padding.X,
Height = Allocation.Height - Padding.Y
};
thumbnail_allocation = new Rect () {
Width = ThumbnailWidth,
Height = ThumbnailHeight,
X = 0,
Y = 0
};
caption_allocation.Y = thumbnail_allocation.Height + CaptionSpacing;
caption_allocation.Width = inner_allocation.Width;
}
public override Size Measure (Size available)
{
var layout = ParentLayout as PhotoGridViewLayout;
caption_allocation.Height = layout.CaptionRender.MeasureHeight (ParentLayout.View);
double width = ThumbnailWidth + Padding.X;
double height = ThumbnailHeight + CaptionSpacing + caption_allocation.Height + Padding.Y;
return new Size (Math.Round (width), Math.Round (height));
}
#endregion
}
}
| |
// Copyright (c) 2015 Alachisoft
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Diagnostics;
using Alachisoft.NCache.Common;
using Alachisoft.NCache.Parser;
using Alachisoft.NCache.Caching.Queries.Filters;
using Alachisoft.NCache.Common.Util;
using Alachisoft.NCache.Common.Logger;
namespace Alachisoft.NCache.Caching.Queries
{
public class NCQLParserRule
{
ILogger _ncacheLog;
public ILogger NCacheLog
{
get { return _ncacheLog; }
}
public NCQLParserRule()
{
}
public NCQLParserRule(ILogger NCacheLog)
{
this._ncacheLog = NCacheLog;
}
/// Implements <Query> ::= SELECT <TypeIdentifier>
public Reduction CreateRULE_QUERY_SELECT(Reduction reduction)
{
object selectType = ((Reduction)((Token)reduction.GetToken(1)).Data).Tag;
Predicate selectTypePredicate = selectType as Predicate;
if (selectTypePredicate == null)
reduction.Tag = new IsOfTypePredicate(selectType.ToString());
else
reduction.Tag = selectTypePredicate;
if(NCacheLog.IsInfoEnabled) NCacheLog.Info("CreateRULE_QUERY_SELECT");
return null;
}
///Implements <Query> ::= SELECT <AggregateFunction>
public Reduction CreateRULE_QUERY_SELECT2(Reduction reduction)
{
return CreateRULE_QUERY_SELECT(reduction);
}
public Reduction CreateRULE_DELETEPARAMS_DOLLARTEXTDOLLAR(Reduction reduction)
{
reduction.Tag = "System.String";
if (NCacheLog.IsInfoEnabled) NCacheLog.Info("CreateRULE_OBJECTTYPE_DOLLARTEXTDOLLAR");
return null;
}
public Reduction CreateRULE_DELETEPARAMS(Reduction reduction)
{
return null;
}
/// Implements <Query> ::= SELECT <TypeIdentifier> WHERE <Expression>
public Reduction CreateRULE_QUERY_SELECT_WHERE(Reduction reduction)
{
//selectType can be one of the following depending on the query text: -
//1. A plain string that is the name of Type; we can build IsOfTypePredicate from this.
//2. AggregateFunctionPredicate that has IsOfTypePredicate set as its ChildPredicate // cant be this, grammer changed
//3. IsOfTypePredicate
object selectType = ((Reduction)reduction.GetToken(1).Data).Tag;
Predicate lhs = null;
Predicate rhs = (Predicate)((Reduction)reduction.GetToken(3).Data).Tag;
Predicate selectTypePredicate = selectType as Predicate;
Predicate result = null;
//1. selectType is string
if (selectTypePredicate == null)
{
lhs = new IsOfTypePredicate(selectType.ToString());
result = ExpressionBuilder.CreateLogicalAndPredicate(lhs, rhs);
}
////2. selectType is AggregateFunctionPredicate
//3. selectType is IsOfTypePredicate
else
{
lhs = selectTypePredicate;
result = ExpressionBuilder.CreateLogicalAndPredicate(lhs, rhs);
}
reduction.Tag = result;
if (NCacheLog.IsInfoEnabled) NCacheLog.Info("CreateRULE_QUERY_SELECT_WHERE");
return null;
}
public Reduction CreateRULE_QUERY_SELECT_WHERE2(Reduction reduction)
{
//selectType can be one of the following depending on the query text: -
// AggregateFunctionPredicate that has IsOfTypePredicate set as its ChildPredicate
object selectType = ((Reduction)reduction.GetToken(1).Data).Tag;
Predicate lhs = null;
Predicate rhs = (Predicate)((Reduction)reduction.GetToken(3).Data).Tag;
Predicate selectTypePredicate = selectType as Predicate;
Predicate result = null;
AggregateFunctionPredicate parentPredicate = selectTypePredicate as AggregateFunctionPredicate;
lhs = parentPredicate.ChildPredicate;
parentPredicate.ChildPredicate = ExpressionBuilder.CreateLogicalAndPredicate(lhs, rhs);
result = parentPredicate;
reduction.Tag = result;
if (NCacheLog.IsInfoEnabled) NCacheLog.Info("CreateRULE_QUERY_SELECT_WHERE2");
return null;
}
/// Implements <Expression> ::= <OrExpr>
public Reduction CreateRULE_EXPRESSION(Reduction reduction)
{
reduction.Tag = ((Reduction)((Token)reduction.GetToken(0)).Data).Tag;
if (NCacheLog.IsInfoEnabled) NCacheLog.Info("CreateRULE_EXPRESSION");
return null;
}
/// Implements <OrExpr> ::= <OrExpr> OR <AndExpr>
public Reduction CreateRULE_OREXPR_OR(Reduction reduction)
{
Predicate lhs = (Predicate)((Reduction)reduction.GetToken(0).Data).Tag;
Predicate rhs = (Predicate)((Reduction)reduction.GetToken(2).Data).Tag;
reduction.Tag = ExpressionBuilder.CreateLogicalOrPredicate(lhs, rhs);
if (NCacheLog.IsInfoEnabled) NCacheLog.Info("CreateRULE_OREXPR_OR");
return null;
}
/// Implements <OrExpr> ::= <AndExpr>
public Reduction CreateRULE_OREXPR(Reduction reduction)
{
reduction.Tag = ((Reduction)((Token)reduction.GetToken(0)).Data).Tag;
if (NCacheLog.IsInfoEnabled) NCacheLog.Info("CreateRULE_OREXPR");
return null;
}
/// Implements <AndExpr> ::= <AndExpr> AND <UnaryExpr>
public Reduction CreateRULE_ANDEXPR_AND(Reduction reduction)
{
Predicate lhs = (Predicate)((Reduction)reduction.GetToken(0).Data).Tag;
Predicate rhs = (Predicate)((Reduction)reduction.GetToken(2).Data).Tag;
reduction.Tag = ExpressionBuilder.CreateLogicalAndPredicate(lhs, rhs);
if (NCacheLog.IsInfoEnabled) NCacheLog.Info("CreateRULE_ANDEXPR_AND");
return null;
}
/// Implements <AndExpr> ::= <UnaryExpr>
public Reduction CreateRULE_ANDEXPR(Reduction reduction)
{
reduction.Tag = ((Reduction)((Token)reduction.GetToken(0)).Data).Tag;
if (NCacheLog.IsInfoEnabled) NCacheLog.Info("CreateRULE_ANDEXPR");
return null;
}
/// Implements <UnaryExpr> ::= NOT <CompareExpr>
public Reduction CreateRULE_UNARYEXPR_NOT(Reduction reduction)
{
Predicate pred = (Predicate)((Reduction)((Token)reduction.GetToken(1)).Data).Tag;
pred.Invert();
reduction.Tag = pred;
if (NCacheLog.IsInfoEnabled) NCacheLog.Info("CreateRULE_UNARYEXPR_NOT");
return null;
}
/// Implements <UnaryExpr> ::= <CompareExpr>
public Reduction CreateRULE_UNARYEXPR(Reduction reduction)
{
reduction.Tag = ((Reduction)((Token)reduction.GetToken(0)).Data).Tag;
if (NCacheLog.IsInfoEnabled) NCacheLog.Info("CreateRULE_UNARYEXPR");
return null;
}
/// Implements <CompareExpr> ::= <Value> '=' <Value>
public Reduction CreateRULE_COMPAREEXPR_EQ(Reduction reduction)
{
return CreateRULE_COMPAREEXPR_EQEQ(reduction);
}
/// Implements <CompareExpr> ::= <Value> '!=' <Value>
public Reduction CreateRULE_COMPAREEXPR_EXCLAMEQ(Reduction reduction)
{
return CreateRULE_COMPAREEXPR_LTGT(reduction);
}
/// Implements <CompareExpr> ::= <Value> '==' <Value>
public Reduction CreateRULE_COMPAREEXPR_EQEQ(Reduction reduction)
{
object lhs = ((Reduction)((Token)reduction.GetToken(0)).Data).Tag;
object rhs = ((Reduction)((Token)reduction.GetToken(2)).Data).Tag;
reduction.Tag = ExpressionBuilder.CreateEqualsPredicate(lhs, rhs);
if (NCacheLog.IsInfoEnabled) NCacheLog.Info("CreateRULE_COMPAREEXPR_EQEQ");
return null;
}
/// Implements <CompareExpr> ::= <Value> '<>' <Value>
public Reduction CreateRULE_COMPAREEXPR_LTGT(Reduction reduction)
{
object lhs = ((Reduction)((Token)reduction.GetToken(0)).Data).Tag;
object rhs = ((Reduction)((Token)reduction.GetToken(2)).Data).Tag;
reduction.Tag = ExpressionBuilder.CreateNotEqualsPredicate(lhs, rhs);
if(NCacheLog.IsInfoEnabled) NCacheLog.Info("CreateRULE_COMPAREEXPR_LTGT");
return null;
}
/// Implements <CompareExpr> ::= <Value> '<' <Value>
public Reduction CreateRULE_COMPAREEXPR_LT(Reduction reduction)
{
object lhs = ((Reduction)((Token)reduction.GetToken(0)).Data).Tag;
object rhs = ((Reduction)((Token)reduction.GetToken(2)).Data).Tag;
reduction.Tag = ExpressionBuilder.CreateLesserPredicate(lhs, rhs);
if(NCacheLog.IsInfoEnabled) NCacheLog.Info("CreateRULE_COMPAREEXPR_LT");
return null;
}
/// Implements <CompareExpr> ::= <Value> '>' <Value>
public Reduction CreateRULE_COMPAREEXPR_GT(Reduction reduction)
{
object lhs = ((Reduction)((Token)reduction.GetToken(0)).Data).Tag;
object rhs = ((Reduction)((Token)reduction.GetToken(2)).Data).Tag;
reduction.Tag = ExpressionBuilder.CreateGreaterPredicate(lhs, rhs);
if(NCacheLog.IsInfoEnabled) NCacheLog.Info("CreateRULE_COMPAREEXPR_GT");
return null;
}
/// Implements <CompareExpr> ::= <Value> '<=' <Value>
public Reduction CreateRULE_COMPAREEXPR_LTEQ(Reduction reduction)
{
object lhs = ((Reduction)((Token)reduction.GetToken(0)).Data).Tag;
object rhs = ((Reduction)((Token)reduction.GetToken(2)).Data).Tag;
reduction.Tag = ExpressionBuilder.CreateLesserEqualsPredicate(lhs, rhs);
if(NCacheLog.IsInfoEnabled) NCacheLog.Info("CreateRULE_COMPAREEXPR_LTEQ");
return null;
}
/// Implements <CompareExpr> ::= <Value> '>=' <Value>
public Reduction CreateRULE_COMPAREEXPR_GTEQ(Reduction reduction)
{
object lhs = ((Reduction)((Token)reduction.GetToken(0)).Data).Tag;
object rhs = ((Reduction)((Token)reduction.GetToken(2)).Data).Tag;
reduction.Tag = ExpressionBuilder.CreateGreaterEqualsPredicate(lhs, rhs);
if(NCacheLog.IsInfoEnabled) NCacheLog.Info("CreateRULE_COMPAREEXPR_GTEQ");
return null;
}
/// Implements <CompareExpr> ::= <Value> LIKE StringLiteral
public Reduction CreateRULE_COMPAREEXPR_LIKE_STRINGLITERAL(Reduction reduction)
{
object lhs = ((Reduction)((Token)reduction.GetToken(0)).Data).Tag;
RuntimeValue rhs = new RuntimeValue();
Predicate predicate = ExpressionBuilder.CreateLikePatternPredicate(lhs, rhs);
reduction.Tag = predicate;
if(NCacheLog.IsInfoEnabled) NCacheLog.Info("CreateRULE_COMPAREEXPR_LIKE_STRINGLITERAL");
return null;
}
/// Implements <CompareExpr> ::= <Value> NOT LIKE StringLiteral
public Reduction CreateRULE_COMPAREEXPR_NOT_LIKE_STRINGLITERAL(Reduction reduction)
{
object lhs = ((Reduction)((Token)reduction.GetToken(0)).Data).Tag;
RuntimeValue rhs = new RuntimeValue();
Predicate predicate = ExpressionBuilder.CreateLikePatternPredicate(lhs, rhs);
predicate.Invert();
reduction.Tag = predicate;
if(NCacheLog.IsInfoEnabled) NCacheLog.Info("CreateRULE_COMPAREEXPR_LIKE_STRINGLITERAL");
return null;
}
/// Implements <CompareExpr> ::= <Value> IN <InList>
public Reduction CreateRULE_COMPAREEXPR_IN(Reduction reduction)
{
object lhs = ((Reduction)((Token)reduction.GetToken(0)).Data).Tag;
IsInListPredicate pred = ((Reduction)((Token)reduction.GetToken(2)).Data).Tag as IsInListPredicate;
pred.Functor = lhs as IFunctor;
reduction.Tag = pred;
if(NCacheLog.IsInfoEnabled) NCacheLog.Info("CreateRULE_COMPAREEXPR_IN");
return null;
}
/// Implements <CompareExpr> ::= <Value> NOT IN <InList>
public Reduction CreateRULE_COMPAREEXPR_NOT_IN(Reduction reduction)
{
object lhs = ((Reduction)((Token)reduction.GetToken(0)).Data).Tag;
IsInListPredicate pred = (IsInListPredicate)
((Reduction)((Token)reduction.GetToken(3)).Data).Tag;
pred.Invert();
pred.Functor = lhs as IFunctor;
reduction.Tag = pred;
if(NCacheLog.IsInfoEnabled) NCacheLog.Info("CreateRULE_COMPAREEXPR_NOT_IN");
return null;
}
/// Implements <CompareExpr> ::= <Value> IS NUll
public Reduction CreateRULE_COMPAREEXPR_IS_NULL(Reduction reduction)
{
object lhs = ((Reduction)((Token)reduction.GetToken(0)).Data).Tag;
Predicate predicate = new IsNullPredicate(lhs as IFunctor);
reduction.Tag = predicate;
if(NCacheLog.IsInfoEnabled) NCacheLog.Info("RULE_COMPAREEXPR_IS_NULL");
return null;
}
/// Implements <CompareExpr> ::= <Value> IS NOT NUll
public Reduction CreateRULE_COMPAREEXPR_IS_NOT_NULL(Reduction reduction)
{
object lhs = ((Reduction)((Token)reduction.GetToken(0)).Data).Tag;
Predicate predicate = new IsNullPredicate(lhs as IFunctor);
predicate.Invert();
reduction.Tag = predicate;
if(NCacheLog.IsInfoEnabled) NCacheLog.Info("RULE_COMPAREEXPR_IS_NOT_NULL");
return null;
}
/// Implements <CompareExpr> ::= '(' <Expression> ')'
public Reduction CreateRULE_COMPAREEXPR_LPARAN_RPARAN(Reduction reduction)
{
if(NCacheLog.IsInfoEnabled) NCacheLog.Info("CreateRULE_COMPAREEXPR_LPARAN_RPARAN");
reduction.Tag = ((Reduction)((Token)reduction.GetToken(1)).Data).Tag;
return null;
}
/// Implements <Value> ::= <ObjectValue>
public Reduction CreateRULE_VALUE(Reduction reduction)
{
if(NCacheLog.IsInfoEnabled) NCacheLog.Info("CreateRULE_VALUE");
reduction.Tag = ((Reduction)((Token)reduction.GetToken(0)).Data).Tag;
return null;
}
/// Implements <Value> ::= '-' <NumLiteral>
public Reduction CreateRULE_VALUE_MINUS(Reduction reduction)
{
if(NCacheLog.IsInfoEnabled) NCacheLog.Info("RULE_VALUE_MINUS");
object functor = ((Reduction)((Token)reduction.GetToken(0)).Data).Tag;
if(functor is IntegerConstantValue)
reduction.Tag = new IntegerConstantValue("-" + reduction.GetToken(1).Data.ToString());
else
reduction.Tag = new DoubleConstantValue("-" + reduction.GetToken(1).Data.ToString());
return null;
}
/// Implements <Value> ::= <NumLiteral>
public Reduction CreateRULE_VALUE2(Reduction reduction)
{
if(NCacheLog.IsInfoEnabled) NCacheLog.Info("CreateRULE_VALUE2");
reduction.Tag = ((Reduction)((Token)reduction.GetToken(0)).Data).Tag;
return null;
}
/// Implements <Value> ::= <StrLiteral>
public Reduction CreateRULE_VALUE3(Reduction reduction)
{
if(NCacheLog.IsInfoEnabled) NCacheLog.Info("CreateRULE_VALUE3");
reduction.Tag = ((Reduction)((Token)reduction.GetToken(0)).Data).Tag;
return null;
}
/// Implements <Value> ::= true
public Reduction CreateRULE_VALUE_TRUE(Reduction reduction)
{
if(NCacheLog.IsInfoEnabled) NCacheLog.Info("CreateRULE_VALUE_TRUE");
reduction.Tag = new TrueValue();
return null;
}
/// Implements <Value> ::= false
public Reduction CreateRULE_VALUE_FALSE(Reduction reduction)
{
if(NCacheLog.IsInfoEnabled) NCacheLog.Info("CreateRULE_VALUE_FALSE");
reduction.Tag = new FalseValue();
return null;
}
/// Implements <Value> ::= <Date>
public Reduction CreateRULE_VALUE4(Reduction reduction)
{
if(NCacheLog.IsInfoEnabled) NCacheLog.Info("CreateRULE_VALUE4");
reduction.Tag = ((Reduction)((Token)reduction.GetToken(0)).Data).Tag;
return null;
}
/// Implements <Date> ::= DateTime '.' now
public Reduction CreateRULE_DATE_DATETIME_DOT_NOW(Reduction reduction)
{
if(NCacheLog.IsInfoEnabled) NCacheLog.Info("CreateRULE_DATE_DATETIME_DOT_NOW");
reduction.Tag = new DateTimeConstantValue();
return null;
}
/// Implements <Date> ::= DateTime '(' <StrLiteral> ')'
public Reduction CreateRULE_DATE_DATETIME_LPARAN_RPARAN(Reduction reduction)
{
if(NCacheLog.IsInfoEnabled) NCacheLog.Info("CreateRULE_DATE_DATETIME_LPARAN_RPARAN");
reduction.Tag = new DateTimeConstantValue(reduction.GetToken(2).Data.ToString());
return null;
}
/// Implements <StrLiteral> ::= StringLiteral
public Reduction CreateRULE_STRLITERAL_STRINGLITERAL(Reduction reduction)
{
if(NCacheLog.IsInfoEnabled) NCacheLog.Info("CreateRULE_STRLITERAL_STRINGLITERAL");
reduction.Tag = new StringConstantValue(reduction.GetToken(0).Data.ToString());
return null;
}
/// Implements <StrLiteral> ::= NUll
public Reduction CreateRULE_STRLITERAL_NULL(Reduction reduction)
{
if(NCacheLog.IsInfoEnabled) NCacheLog.Info("CreateRULE_STRLITERAL_NULL");
reduction.Tag = new NullValue();
return null;
}
/// Implements <StrLiteral> ::= ?
public Reduction CreateRULE_STRLITERAL_QUESTION(Reduction reduction)
{
if (NCacheLog.IsInfoEnabled) NCacheLog.Info("CreateRULE_STRLITERAL_QUESTION");
reduction.Tag = new RuntimeValue();
return null;
}
/// Implements <NumLiteral> ::= IntegerLiteral
public Reduction CreateRULE_NUMLITERAL_INTEGERLITERAL(Reduction reduction)
{
if(NCacheLog.IsInfoEnabled) NCacheLog.Info("CreateRULE_NUMLITERAL_INTEGERLITERAL");
reduction.Tag = new IntegerConstantValue(reduction.GetToken(0).Data.ToString());
return null;
}
/// Implements <NumLiteral> ::= RealLiteral
public Reduction CreateRULE_NUMLITERAL_REALLITERAL(Reduction reduction)
{
if(NCacheLog.IsInfoEnabled) NCacheLog.Info("CreateRULE_NUMLITERAL_REALLITERAL");
reduction.Tag = new DoubleConstantValue(reduction.GetToken(0).Data.ToString());
return null;
}
/// Implements <TypeIdentifier> ::= '*'
public Reduction CreateRULE_OBJECTTYPE_TIMES(Reduction reduction)
{
reduction.Tag = "*";
if(NCacheLog.IsInfoEnabled) NCacheLog.Info("CreateRULE_OBJECTTYPE_TIMES");
return null;
}
/// Implements <TypeIdentifier> ::= '$Text$'
public Reduction CreateRULE_OBJECTTYPE_DOLLARTEXTDOLLAR(Reduction reduction)
{
reduction.Tag = "System.String";
if (NCacheLog.IsInfoEnabled) NCacheLog.Info("CreateRULE_OBJECTTYPE_DOLLARTEXTDOLLAR");
return null;
}
/// Implements <TypeIdentifier> ::= <Identifier>
public Reduction CreateRULE_OBJECTTYPE_IDENTIFIER(Reduction reduction)
{
reduction.Tag = ((Token)reduction.GetToken(0)).Data;
if(NCacheLog.IsInfoEnabled) NCacheLog.Info("CreateRULE_TYPEIDENTIFIER_IDENTIFIER");
return null;
}
/// Implements <TypeIdentifier> ::= <TypeIdentifier> '.' <Identifier>
public Reduction CreateRULE_OBJECTTYPE_IDENTIFIER_DOT(Reduction reduction)
{
string lhs = ((Reduction)reduction.GetToken(0).Data).Tag.ToString();
string rhs = reduction.GetToken(2).Data.ToString();
reduction.Tag = lhs + "." + rhs;
if (NCacheLog.IsInfoEnabled) NCacheLog.Info("CreateRULE_OBJECTTYPE_IDENTIFIER_DOT");
return null;
}
/// Implements <ObjectType> ::= <AggregateFunction>
public Reduction CreateRULE_OBJECTTYPE2(Reduction reduction)
{
return null;
}
/// Implements <ObjectAttribute> ::= Identifier
public Reduction CreateRULE_OBJECTATTRIBUTE_IDENTIFIER(Reduction reduction)
{
string memberName = reduction.GetToken(0).Data.ToString();
reduction.Tag = memberName;
if (NCacheLog.IsInfoEnabled) NCacheLog.Info("CreateRULE_OBJECTATTRIBUTE_IDENTIFIER");
return null;
}
/// Implements <ObjectValue> ::= Keyword
public Reduction CreateRULE_OBJECTVALUE_KEYWORD(Reduction reduction)
{
if(NCacheLog.IsInfoEnabled) NCacheLog.Info("CreateRULE_OBJECTVALUE_KEYWORD");
reduction.Tag = new IdentityFunction();
return null;
}
/// Implements <ObjectValue> ::= Keyword '.' <Property>
public Reduction CreateRULE_OBJECTVALUE_KEYWORD_DOT(Reduction reduction)
{
object pred = ((Reduction)((Token)reduction.GetToken(2)).Data).Tag;
if(pred is IFunctor)
reduction.Tag = pred;
else
{
reduction.Tag = new MemberFunction(pred.ToString());
}
if(NCacheLog.IsInfoEnabled) NCacheLog.Info("CreateRULE_IDENTIFIER_KEYWORD");
return null;
}
/// Implements <Property> ::= <Property> '.' <Identifier>
public Reduction CreateRULE_PROPERTY_DOT(Reduction reduction)
{
IFunctor nested =
new MemberFunction(((Reduction)((Token)reduction.GetToken(2)).Data).Tag.ToString());
IFunctor func =
new MemberFunction(((Reduction)((Token)reduction.GetToken(0)).Data).Tag.ToString());
reduction.Tag = new CompositeFunction(func, nested);
if(NCacheLog.IsInfoEnabled) NCacheLog.Info("RULE_PROPERTY_DOT -> " + reduction.Tag);
return null;
}
/// Implements <Property> ::= <Identifier>
public Reduction CreateRULE_PROPERTY(Reduction reduction)
{
if(NCacheLog.IsInfoEnabled) NCacheLog.Info("CreateRULE_PROPERTY");
reduction.Tag = ((Token)reduction.GetToken(0)).Data;
return null;
}
/// Implements <Identifier> ::= Identifier
public Reduction CreateRULE_IDENTIFIER_IDENTIFIER(Reduction reduction)
{
reduction.Tag = ((Token)reduction.GetToken(0)).Data.ToString();
if(NCacheLog.IsInfoEnabled) NCacheLog.Info("RULE_IDENTIFIER_IDENTIFIER -> " + reduction.Tag);
return null;
}
/// Implements <Identifier> ::= Keyword
public Reduction CreateRULE_IDENTIFIER_KEYWORD(Reduction reduction)
{
reduction.Tag = ((Token)reduction.GetToken(0)).Data;
if(NCacheLog.IsInfoEnabled) NCacheLog.Info("RULE_IDENTIFIER_KEYWORD -> " + reduction.Tag);
return null;
}
/// Implements <InList> ::= '(' <ListType> ')'
public Reduction CreateRULE_INLIST_LPARAN_RPARAN(Reduction reduction)
{
if(NCacheLog.IsInfoEnabled) NCacheLog.Info("CreateRULE_INLIST_LPARAN_RPARAN");
object obj = ((Reduction)((Token)reduction.GetToken(1)).Data).Tag;
if (obj is ConstantValue || obj is RuntimeValue)
{
IsInListPredicate pred = new IsInListPredicate();
pred.Append(obj);
reduction.Tag = pred;
}
else
{
reduction.Tag = ((Reduction)((Token)reduction.GetToken(1)).Data).Tag;
}
return null;
}
/// Implements <ListType> ::= <NumLiteralList>
public Reduction CreateRULE_LISTTYPE(Reduction reduction)
{
if(NCacheLog.IsInfoEnabled) NCacheLog.Info("CreateRULE_LISTTYPE");
reduction.Tag = ((Reduction)((Token)reduction.GetToken(0)).Data).Tag;
return null;
}
/// Implements <ListType> ::= <StrLiteralList>
public Reduction CreateRULE_LISTTYPE2(Reduction reduction)
{
if(NCacheLog.IsInfoEnabled) NCacheLog.Info("CreateRULE_LISTTYPE2");
reduction.Tag = ((Reduction)((Token)reduction.GetToken(0)).Data).Tag;
return null;
}
/// Implements <ListType> ::= <DateList>
public Reduction CreateRULE_LISTTYPE3(Reduction reduction)
{
if(NCacheLog.IsInfoEnabled) NCacheLog.Info("CreateRULE_LISTTYPE3");
reduction.Tag = ((Reduction)((Token)reduction.GetToken(0)).Data).Tag;
return null;
}
/// Implements <NumLiteralList> ::= <NumLiteral> ',' <NumLiteralList>
public Reduction CreateRULE_NUMLITERALLIST_COMMA(Reduction reduction)
{
return CreateInclusionList(reduction);
}
/// Implements <NumLiteralList> ::= <NumLiteral>
public Reduction CreateRULE_NUMLITERALLIST(Reduction reduction)
{
if(NCacheLog.IsInfoEnabled) NCacheLog.Info("CreateRULE_NUMLITERALLIST");
IsInListPredicate pred = new IsInListPredicate();
pred.Append(((Reduction)reduction.GetToken(0).Data).Tag);
reduction.Tag = pred;
return null;
}
/// Implements <StrLiteralList> ::= <StrLiteral> ',' <StrLiteralList>
public Reduction CreateRULE_STRLITERALLIST_COMMA(Reduction reduction)
{
return CreateInclusionList(reduction);
}
/// Implements <StrLiteralList> ::= <StrLiteral>
public Reduction CreateRULE_STRLITERALLIST(Reduction reduction)
{
if(NCacheLog.IsInfoEnabled) NCacheLog.Info("CreateRULE_STRLITERALLIST");
reduction.Tag = ((Reduction)((Token)reduction.GetToken(0)).Data).Tag;
return null;
}
/// Implements <DateList> ::= <Date> ',' <DateList>
public Reduction CreateRULE_DATELIST_COMMA(Reduction reduction)
{
return CreateInclusionList(reduction);
}
/// Implements <DateList> ::= <Date>
public Reduction CreateRULE_DATELIST(Reduction reduction)
{
if(NCacheLog.IsInfoEnabled) NCacheLog.Info("CreateRULE_DATELIST");
reduction.Tag = ((Reduction)((Token)reduction.GetToken(0)).Data).Tag;
return null;
}
//self create
//=========================
public Reduction CreateRULE_ATRRIB(Reduction reduction)
{
if(NCacheLog.IsInfoEnabled) NCacheLog.Info("CreateRULE_ATRRIB");
reduction.Tag = ((Reduction)((Token)reduction.GetToken(0)).Data).Tag;
return null;
}
public Reduction CreateRULE_DATE_DATETIME_LPARAN_STRINGLITERAL_RPARAN(Reduction reduction)
{
if(NCacheLog.IsInfoEnabled) NCacheLog.Info("RULE_DATE_DATETIME_LPARAN_STRINGLITERAL_RPARAN");
string dateTime = reduction.GetToken(2).Data.ToString().Trim('\'');
reduction.Tag = new DateTimeConstantValue(dateTime);
return null;
}
public Reduction CreateRULE_OBJECTVALUE_KEYWORD_DOT_IDENTIFIER(Reduction reduction)
{
if(NCacheLog.IsInfoEnabled) NCacheLog.Info("RULE_OBJECTVALUE_KEYWORD_DOT_IDENTIFIER");
string memName = reduction.GetToken(2).Data.ToString();
reduction.Tag = new MemberFunction(memName);
return null;
}
/// Implements <SumFunction> ::= 'SUM(' <TypePlusAttribute> ')'
public Reduction CreateRULE_SUMFUNCTION_SUMLPARAN_RPARAN(Reduction reduction)
{
Reduction typePlusAttributeReduction = (Reduction)reduction.GetToken(1).Data;
string typeName = ((Reduction)typePlusAttributeReduction.GetToken(0).Data).Tag as string;
string memberName = ((Reduction)typePlusAttributeReduction.GetToken(2).Data).Tag as string;
Predicate childPredicate = new IsOfTypePredicate(typeName);
AggregateFunctionPredicate sumFunctionPredicate = ExpressionBuilder.CreateSumFunctionPredicate(memberName) as AggregateFunctionPredicate;
sumFunctionPredicate.ChildPredicate = childPredicate;
reduction.Tag = sumFunctionPredicate;
return null;
}
/// Implements <CountFunction> ::= 'COUNT(' <Property> ')'
public Reduction CreateRULE_COUNTFUNCTION_COUNTLPARAN_TIMES_RPARAN(Reduction reduction)
{
string typeName = ((Reduction)reduction.GetToken(1).Data).Tag as string;
Predicate childPredicate = new IsOfTypePredicate(typeName);
AggregateFunctionPredicate countFunctionPredicate = ExpressionBuilder.CreateCountFunctionPredicate() as AggregateFunctionPredicate;
countFunctionPredicate.ChildPredicate = childPredicate;
reduction.Tag = countFunctionPredicate;
return null;
}
/// Implements <MinFunction> ::= 'MIN(' <TypePlusAttribute> ')'
public Reduction CreateRULE_MINFUNCTION_MINLPARAN_RPARAN(Reduction reduction)
{
Reduction typePlusAttributeReduction = (Reduction)reduction.GetToken(1).Data;
string typeName = ((Reduction)typePlusAttributeReduction.GetToken(0).Data).Tag as string;
string memberName = ((Reduction)typePlusAttributeReduction.GetToken(2).Data).Tag as string;
Predicate childPredicate = new IsOfTypePredicate(typeName);
AggregateFunctionPredicate minFunctionPredicate = ExpressionBuilder.CreateMinFunctionPredicate(memberName) as AggregateFunctionPredicate;
minFunctionPredicate.ChildPredicate = childPredicate;
reduction.Tag = minFunctionPredicate;
return null;
}
/// Implements <MaxFunction> ::= 'MAX(' <TypePlusAttribute> ')'
public Reduction CreateRULE_MAXFUNCTION_MAXLPARAN_RPARAN(Reduction reduction)
{
Reduction typePlusAttributeReduction = (Reduction)reduction.GetToken(1).Data;
string typeName = ((Reduction)typePlusAttributeReduction.GetToken(0).Data).Tag as string;
string memberName = ((Reduction)typePlusAttributeReduction.GetToken(2).Data).Tag as string;
Predicate childPredicate = new IsOfTypePredicate(typeName);
AggregateFunctionPredicate maxFunctionPredicate = ExpressionBuilder.CreateMaxFunctionPredicate(memberName) as AggregateFunctionPredicate;
maxFunctionPredicate.ChildPredicate = childPredicate;
reduction.Tag = maxFunctionPredicate;
return null;
}
/// Implements <AverageFunction> ::= 'AVG(' <TypePlusAttribute> ')'
public Reduction CreateRULE_AVERAGEFUNCTION_AVGLPARAN_RPARAN(Reduction reduction)
{
Reduction typePlusAttributeReduction = (Reduction)reduction.GetToken(1).Data;
string typeName = ((Reduction)typePlusAttributeReduction.GetToken(0).Data).Tag as string;
string memberName = ((Reduction)typePlusAttributeReduction.GetToken(2).Data).Tag as string;
Predicate childPredicate = new IsOfTypePredicate(typeName);
AggregateFunctionPredicate avgFunctionPredicate = ExpressionBuilder.CreateAverageFunctionPredicate(memberName) as AggregateFunctionPredicate;
avgFunctionPredicate.ChildPredicate = childPredicate;
reduction.Tag = avgFunctionPredicate;
return null;
}
/// Implements <CompareExpr> ::= <Value> LIKE Question
public Reduction CreateRULE_COMPAREEXPR_LIKE_QUESTION(Reduction reduction)
{
return CreateRULE_COMPAREEXPR_LIKE_STRINGLITERAL(reduction);
}
/// Implements <CompareExpr> ::= <Value> NOT LIKE Question
public Reduction CreateRULE_COMPAREEXPR_NOT_LIKE_QUESTION(Reduction reduction)
{
return CreateRULE_COMPAREEXPR_NOT_LIKE_STRINGLITERAL(reduction);
}
/// Implements <CompareExpr> ::= <Value> ObjectType
public Reduction CreateRULE_OBJECTTYPE(Reduction reduction)
{
return null;
}
/// Implements <CompareExpr> ::= <Value> Property DOT Identifier
public Reduction CreateRULE_PROPERTY_DOT_IDENTIFIER(Reduction reduction)
{
return CreateRULE_OBJECTTYPE_IDENTIFIER_DOT(reduction);
}
/// Implements <CompareExpr> ::= <Value> Property Identifier
public Reduction CreateRULE_PROPERTY_IDENTIFIER(Reduction reduction)
{
return CreateRULE_OBJECTTYPE_IDENTIFIER(reduction);
}
/// Implements <CompareExpr> ::= <Value> Type Plus Attribute DOT
public Reduction CreateRULE_TYPEPLUSATTRIBUTE_DOT(Reduction reduction)
{
return null;
}
/// Implements <CompareExpr> ::= <Value> Aggregate Function
public Reduction CreateRULE_AGGREGATEFUNCTION(Reduction reduction)
{
return null;
}
/// Implements <CompareExpr> ::= <Value> Aggregate Function2
public Reduction CreateRULE_AGGREGATEFUNCTION2(Reduction reduction)
{
return null;
}
/// Implements <CompareExpr> ::= <Value> Aggregate Function3
public Reduction CreateRULE_AGGREGATEFUNCTION3(Reduction reduction)
{
return null;
}
/// Implements <CompareExpr> ::= <Value> Aggregate Function4
public Reduction CreateRULE_AGGREGATEFUNCTION4(Reduction reduction)
{
return null;
}
/// Implements <CompareExpr> ::= <Value> Aggregate Function5
public Reduction CreateRULE_AGGREGATEFUNCTION5(Reduction reduction)
{
return null;
}
/// Implements <CompareExpr> ::= <Value> COUNT Function COUNT LParan RParan
public Reduction CreateRULE_COUNTFUNCTION_COUNTLPARAN_RPARAN(Reduction reduction)
{
return CreateRULE_COUNTFUNCTION_COUNTLPARAN_TIMES_RPARAN(reduction);
}
//========================
public Reduction CreateInclusionList(Reduction reduction)
{
object tag = ((Reduction)reduction.GetToken(2).Data).Tag;
IsInListPredicate inc = null;
if(tag is IsInListPredicate)
inc = tag as IsInListPredicate;
else
{
inc = new IsInListPredicate();
inc.Append(tag);
}
inc.Append(((Reduction)reduction.GetToken(0).Data).Tag);
reduction.Tag = inc;
return null;
}
///Implements <ObjectAttribute> ::= Keyword '.' Identifier
public Reduction CreateRULE_OBJECTATTRIBUTE_KEYWORD_DOT_IDENTIFIER(Reduction reduction)
{
return CreateRULE_OBJECTVALUE_KEYWORD_DOT_IDENTIFIER(reduction);
}
}
}
| |
using System;
using OpenTK.Input;
using static FoxTrader.Constants;
namespace FoxTrader.UI.Control
{
/// <summary>Button control</summary>
internal class Button : Label
{
private bool m_centerImage;
private ImagePanel m_image;
private bool m_isDepressed;
private bool m_toggleStatus;
/// <summary>Control constructor</summary>
/// <param name="c_parentControl">Parent control</param>
internal Button(GameControl c_parentControl) : base(c_parentControl)
{
MouseInputEnabled = true;
Alignment = Pos.Center;
TextPadding = new Padding(3, 3, 3, 3);
UpdateTextColorState(false);
}
public override bool IsDisabled
{
get
{
return base.IsDisabled;
}
set
{
base.IsDisabled = value;
UpdateTextColorState(false);
}
}
/// <summary>Indicates whether the button is depressed</summary>
public bool IsDepressed
{
get
{
return m_isDepressed;
}
set
{
if (m_isDepressed == value)
{
return;
}
m_isDepressed = value;
Redraw();
}
}
/// <summary>Indicates whether the button is toggleable</summary>
public bool IsToggle
{
get;
set;
}
/// <summary>Determines the button's toggle state</summary>
public bool ToggleState
{
get
{
return m_toggleStatus;
}
set
{
if (!IsToggle)
{
return;
}
if (m_toggleStatus == value)
{
return;
}
m_toggleStatus = value;
Toggled?.Invoke(this, new MouseButtonEventArgs());
if (m_toggleStatus)
{
ToggledOn?.Invoke(this, new MouseButtonEventArgs());
}
else
{
ToggledOff?.Invoke(this, new MouseButtonEventArgs());
}
Redraw();
}
}
/// <summary>Invoked when the button's toggle state has changed</summary>
internal event MouseButtonEventHandler Toggled;
/// <summary>Invoked when the button's toggle state has changed to On</summary>
internal event MouseButtonEventHandler ToggledOn;
/// <summary>Invoked when the button's toggle state has changed to Off</summary>
internal event MouseButtonEventHandler ToggledOff;
/// <summary>Toggles the button</summary>
public virtual void Toggle()
{
ToggleState = !ToggleState;
}
/// <summary>Renders the control using specified skin</summary>
/// <param name="c_skin">Skin to use</param>
protected override void Render(Skin c_skin)
{
if (!ShouldDrawBackground)
{
return;
}
var a_drawDepressed = IsDepressed && IsHovered;
if (IsToggle)
{
a_drawDepressed = a_drawDepressed || ToggleState;
}
var a_bDrawHovered = IsHovered && ShouldDrawHover;
c_skin.DrawButton(this, a_drawDepressed, a_bDrawHovered, IsDisabled);
RenderText(c_skin.Renderer);
}
/// <summary>Internal OnPressed implementation</summary>
public override void OnClicked(MouseButtonEventArgs c_mouseButtonEventArgs)
{
if (IsToggle)
{
Toggle();
}
base.OnClicked(c_mouseButtonEventArgs);
}
/// <summary>Sets the button's image</summary>
/// <param name="c_textureName">Texture name. Null to remove</param>
/// <param name="c_center">Determines whether the image should be centered</param>
public void SetImage(string c_textureName, bool c_center = false)
{
if (string.IsNullOrEmpty(c_textureName))
{
m_image?.Dispose();
m_image = null;
return;
}
if (m_image == null)
{
m_image = new ImagePanel(this);
}
m_image.ImageName = c_textureName;
m_image.SizeToContents();
m_image.SetPosition(Math.Max(Padding.Left, 2), 2);
m_centerImage = c_center;
TextPadding = new Padding(m_image.Right + 2, TextPadding.Top, TextPadding.Right, TextPadding.Bottom);
}
/// <summary>Sizes to contents</summary>
public override void SizeToContents()
{
base.SizeToContents();
if (m_image != null)
{
var a_height = m_image.Height + 4;
if (Height < a_height)
{
Height = a_height;
}
}
}
/// <summary>Lays out the control's interior according to alignment, padding, dock etc</summary>
/// <param name="c_skin">Skin to use</param>
protected override void OnLayout(Skin c_skin)
{
base.OnLayout(c_skin);
if (m_image != null)
{
Align.CenterVertically(m_image);
if (m_centerImage)
{
Align.CenterHorizontally(m_image);
}
}
}
public override void OnMouseOver(MouseMoveEventArgs c_mouseEventArgs)
{
base.OnMouseOver(c_mouseEventArgs);
UpdateTextColorState(true);
}
public override void OnMouseOut(MouseMoveEventArgs c_mouseEventArgs)
{
base.OnMouseOut(c_mouseEventArgs);
UpdateTextColorState(false);
}
public override void OnMouseDown(MouseButtonEventArgs c_mouseButtonEventArgs)
{
base.OnMouseDown(c_mouseButtonEventArgs);
if (!IsDisabled)
{
m_isDepressed = true;
}
}
public override void OnMouseUp(MouseButtonEventArgs c_mouseButtonEventArgs)
{
base.OnMouseUp(c_mouseButtonEventArgs);
m_isDepressed = false;
}
private void UpdateTextColorState(bool c_isHovered)
{
if (IsDisabled)
{
TextColor = Skin.m_colors.m_button.m_disabled;
return;
}
if (IsDepressed || ToggleState)
{
TextColor = Skin.m_colors.m_button.m_down;
return;
}
if (c_isHovered)
{
TextColor = Skin.m_colors.m_button.m_hover;
return;
}
TextColor = Skin.m_colors.m_button.m_normal;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Threading;
#if DEBUG
using System.Collections.Concurrent;
#endif //DEBUG
namespace System.Runtime
{
internal abstract class InternalBufferManager
{
protected InternalBufferManager()
{
}
public abstract byte[] TakeBuffer(int bufferSize);
public abstract void ReturnBuffer(byte[] buffer);
public abstract void Clear();
public static InternalBufferManager Create(long maxBufferPoolSize, int maxBufferSize)
{
if (maxBufferPoolSize == 0)
{
return GCBufferManager.Value;
}
else
{
Fx.Assert(maxBufferPoolSize > 0 && maxBufferSize >= 0, "bad params, caller should verify");
return new PooledBufferManager(maxBufferPoolSize, maxBufferSize);
}
}
internal class PooledBufferManager : InternalBufferManager
{
private const int minBufferSize = 128;
private const int maxMissesBeforeTuning = 8;
private const int initialBufferCount = 1;
private readonly object _tuningLock;
private int[] _bufferSizes;
private BufferPool[] _bufferPools;
private long _memoryLimit;
private long _remainingMemory;
private bool _areQuotasBeingTuned;
private int _totalMisses;
#if DEBUG
private ConcurrentDictionary<int, string> _buffersPooled = new ConcurrentDictionary<int, string>();
#endif //DEBUG
public PooledBufferManager(long maxMemoryToPool, int maxBufferSize)
{
_tuningLock = new object();
_memoryLimit = maxMemoryToPool;
_remainingMemory = maxMemoryToPool;
List<BufferPool> bufferPoolList = new List<BufferPool>();
for (int bufferSize = minBufferSize; ;)
{
long bufferCountLong = _remainingMemory / bufferSize;
int bufferCount = bufferCountLong > int.MaxValue ? int.MaxValue : (int)bufferCountLong;
if (bufferCount > initialBufferCount)
{
bufferCount = initialBufferCount;
}
bufferPoolList.Add(BufferPool.CreatePool(bufferSize, bufferCount));
_remainingMemory -= (long)bufferCount * bufferSize;
if (bufferSize >= maxBufferSize)
{
break;
}
long newBufferSizeLong = (long)bufferSize * 2;
if (newBufferSizeLong > (long)maxBufferSize)
{
bufferSize = maxBufferSize;
}
else
{
bufferSize = (int)newBufferSizeLong;
}
}
_bufferPools = bufferPoolList.ToArray();
_bufferSizes = new int[_bufferPools.Length];
for (int i = 0; i < _bufferPools.Length; i++)
{
_bufferSizes[i] = _bufferPools[i].BufferSize;
}
}
public override void Clear()
{
#if DEBUG
_buffersPooled.Clear();
#endif //DEBUG
for (int i = 0; i < _bufferPools.Length; i++)
{
BufferPool bufferPool = _bufferPools[i];
bufferPool.Clear();
}
}
private void ChangeQuota(ref BufferPool bufferPool, int delta)
{
if (TraceCore.BufferPoolChangeQuotaIsEnabled(Fx.Trace))
{
TraceCore.BufferPoolChangeQuota(Fx.Trace, bufferPool.BufferSize, delta);
}
BufferPool oldBufferPool = bufferPool;
int newLimit = oldBufferPool.Limit + delta;
BufferPool newBufferPool = BufferPool.CreatePool(oldBufferPool.BufferSize, newLimit);
for (int i = 0; i < newLimit; i++)
{
byte[] buffer = oldBufferPool.Take();
if (buffer == null)
{
break;
}
newBufferPool.Return(buffer);
newBufferPool.IncrementCount();
}
_remainingMemory -= oldBufferPool.BufferSize * delta;
bufferPool = newBufferPool;
}
private void DecreaseQuota(ref BufferPool bufferPool)
{
ChangeQuota(ref bufferPool, -1);
}
private int FindMostExcessivePool()
{
long maxBytesInExcess = 0;
int index = -1;
for (int i = 0; i < _bufferPools.Length; i++)
{
BufferPool bufferPool = _bufferPools[i];
if (bufferPool.Peak < bufferPool.Limit)
{
long bytesInExcess = (bufferPool.Limit - bufferPool.Peak) * (long)bufferPool.BufferSize;
if (bytesInExcess > maxBytesInExcess)
{
index = i;
maxBytesInExcess = bytesInExcess;
}
}
}
return index;
}
private int FindMostStarvedPool()
{
long maxBytesMissed = 0;
int index = -1;
for (int i = 0; i < _bufferPools.Length; i++)
{
BufferPool bufferPool = _bufferPools[i];
if (bufferPool.Peak == bufferPool.Limit)
{
long bytesMissed = bufferPool.Misses * (long)bufferPool.BufferSize;
if (bytesMissed > maxBytesMissed)
{
index = i;
maxBytesMissed = bytesMissed;
}
}
}
return index;
}
private BufferPool FindPool(int desiredBufferSize)
{
for (int i = 0; i < _bufferSizes.Length; i++)
{
if (desiredBufferSize <= _bufferSizes[i])
{
return _bufferPools[i];
}
}
return null;
}
private void IncreaseQuota(ref BufferPool bufferPool)
{
ChangeQuota(ref bufferPool, 1);
}
public override void ReturnBuffer(byte[] buffer)
{
Fx.Assert(buffer != null, "caller must verify");
BufferPool bufferPool = FindPool(buffer.Length);
if (bufferPool != null)
{
if (buffer.Length != bufferPool.BufferSize)
{
throw Fx.Exception.Argument("buffer", InternalSR.BufferIsNotRightSizeForBufferManager);
}
if (bufferPool.Return(buffer))
{
bufferPool.IncrementCount();
}
}
}
public override byte[] TakeBuffer(int bufferSize)
{
Fx.Assert(bufferSize >= 0, "caller must ensure a non-negative argument");
BufferPool bufferPool = FindPool(bufferSize);
byte[] returnValue;
if (bufferPool != null)
{
byte[] buffer = bufferPool.Take();
if (buffer != null)
{
bufferPool.DecrementCount();
returnValue = buffer;
}
else
{
if (bufferPool.Peak == bufferPool.Limit)
{
bufferPool.Misses++;
if (++_totalMisses >= maxMissesBeforeTuning)
{
TuneQuotas();
}
}
if (TraceCore.BufferPoolAllocationIsEnabled(Fx.Trace))
{
TraceCore.BufferPoolAllocation(Fx.Trace, bufferPool.BufferSize);
}
returnValue = Fx.AllocateByteArray(bufferPool.BufferSize);
}
}
else
{
if (TraceCore.BufferPoolAllocationIsEnabled(Fx.Trace))
{
TraceCore.BufferPoolAllocation(Fx.Trace, bufferSize);
}
returnValue = Fx.AllocateByteArray(bufferSize);
}
#if DEBUG
string dummy;
_buffersPooled.TryRemove(returnValue.GetHashCode(), out dummy);
#endif //DEBUG
return returnValue;
}
private void TuneQuotas()
{
if (_areQuotasBeingTuned)
{
return;
}
bool lockHeld = false;
try
{
Monitor.TryEnter(_tuningLock, ref lockHeld);
// Don't bother if another thread already has the lock
if (!lockHeld || _areQuotasBeingTuned)
{
return;
}
_areQuotasBeingTuned = true;
}
finally
{
if (lockHeld)
{
Monitor.Exit(_tuningLock);
}
}
// find the "poorest" pool
int starvedIndex = FindMostStarvedPool();
if (starvedIndex >= 0)
{
BufferPool starvedBufferPool = _bufferPools[starvedIndex];
if (_remainingMemory < starvedBufferPool.BufferSize)
{
// find the "richest" pool
int excessiveIndex = FindMostExcessivePool();
if (excessiveIndex >= 0)
{
// steal from the richest
DecreaseQuota(ref _bufferPools[excessiveIndex]);
}
}
if (_remainingMemory >= starvedBufferPool.BufferSize)
{
// give to the poorest
IncreaseQuota(ref _bufferPools[starvedIndex]);
}
}
// reset statistics
for (int i = 0; i < _bufferPools.Length; i++)
{
BufferPool bufferPool = _bufferPools[i];
bufferPool.Misses = 0;
}
_totalMisses = 0;
_areQuotasBeingTuned = false;
}
internal abstract class BufferPool
{
private int _count;
private int _peak;
public BufferPool(int bufferSize, int limit)
{
BufferSize = bufferSize;
Limit = limit;
}
public int BufferSize { get; }
public int Limit { get; }
public int Misses { get; set; }
public int Peak
{
get { return _peak; }
}
public void Clear()
{
OnClear();
_count = 0;
}
public void DecrementCount()
{
int newValue = _count - 1;
if (newValue >= 0)
{
_count = newValue;
}
}
public void IncrementCount()
{
int newValue = _count + 1;
if (newValue <= Limit)
{
_count = newValue;
if (newValue > _peak)
{
_peak = newValue;
}
}
}
internal abstract byte[] Take();
internal abstract bool Return(byte[] buffer);
internal abstract void OnClear();
internal static BufferPool CreatePool(int bufferSize, int limit)
{
// To avoid many buffer drops during training of large objects which
// get allocated on the LOH, we use the LargeBufferPool and for
// bufferSize < 85000, the SynchronizedPool. However if bufferSize < 85000
// and (bufferSize + array-overhead) > 85000, this would still use
// the SynchronizedPool even though it is allocated on the LOH.
if (bufferSize < 85000)
{
return new SynchronizedBufferPool(bufferSize, limit);
}
else
{
return new LargeBufferPool(bufferSize, limit);
}
}
internal class SynchronizedBufferPool : BufferPool
{
private SynchronizedPool<byte[]> _innerPool;
internal SynchronizedBufferPool(int bufferSize, int limit)
: base(bufferSize, limit)
{
_innerPool = new SynchronizedPool<byte[]>(limit);
}
internal override void OnClear()
{
_innerPool.Clear();
}
internal override byte[] Take()
{
return _innerPool.Take();
}
internal override bool Return(byte[] buffer)
{
return _innerPool.Return(buffer);
}
}
internal class LargeBufferPool : BufferPool
{
private Stack<byte[]> _items;
internal LargeBufferPool(int bufferSize, int limit)
: base(bufferSize, limit)
{
_items = new Stack<byte[]>(limit);
}
private object ThisLock
{
get
{
return _items;
}
}
internal override void OnClear()
{
lock (ThisLock)
{
_items.Clear();
}
}
internal override byte[] Take()
{
lock (ThisLock)
{
if (_items.Count > 0)
{
return _items.Pop();
}
}
return null;
}
internal override bool Return(byte[] buffer)
{
lock (ThisLock)
{
if (_items.Count < Limit)
{
_items.Push(buffer);
return true;
}
}
return false;
}
}
}
}
internal class GCBufferManager : InternalBufferManager
{
private GCBufferManager()
{
}
public static GCBufferManager Value { get; } = new GCBufferManager();
public override void Clear()
{
}
public override byte[] TakeBuffer(int bufferSize)
{
return Fx.AllocateByteArray(bufferSize);
}
public override void ReturnBuffer(byte[] buffer)
{
// do nothing, GC will reclaim this buffer
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Runtime.InteropServices;
using IronPython.Runtime;
using IronPython.Runtime.Operations;
using IronPython.Runtime.Types;
using Microsoft.Scripting;
namespace NumpyDotNet {
/// <summary>
/// Implements array manipulation and construction functionality. This
/// class has functionality corresponding to functions in arrayobject.c,
/// ctors.c, and multiarraymodule.c
/// </summary>
internal static class NpyArray {
/// <summary>
/// Copies the source object into the destination array. src can be
/// any type so long as the number of elements matches dest. In the
/// case of strings, they will be padded with spaces if needed but
/// can not be longer than the number of elements in dest.
/// </summary>
/// <param name="dest">Destination array</param>
/// <param name="src">Source object</param>
internal static void CopyObject(ndarray dest, Object src) {
// For char arrays pad the input string.
if (dest.dtype.Type == NpyDefs.NPY_TYPECHAR.NPY_CHARLTR &&
dest.ndim > 0 && src is String) {
int ndimNew = (int)dest.Dims[dest.ndim - 1];
int ndimOld = ((String)src).Length;
if (ndimNew > ndimOld) {
src = ((String)src).PadRight(ndimNew, ' ');
}
}
ndarray srcArray;
if (src is ndarray) {
srcArray = (ndarray)src;
} else if (false) {
// TODO: Not handling scalars. See arrayobject.c:111
} else {
srcArray = FromAny(src, dest.dtype, 0, dest.ndim,
dest.dtype.Flags & NpyDefs.NPY_FORTRAN, null);
}
NpyCoreApi.MoveInto(dest, srcArray);
}
internal static void SetField(ndarray dest, IntPtr descr, int offset, object src)
{
// For char arrays pad the input string.
if (dest.dtype.Type == NpyDefs.NPY_TYPECHAR.NPY_CHARLTR &&
dest.ndim > 0 && src is String)
{
int ndimNew = (int)dest.Dims[dest.ndim - 1];
int ndimOld = ((String)src).Length;
if (ndimNew > ndimOld)
{
src = ((String)src).PadRight(ndimNew, ' ');
}
}
ndarray srcArray;
if (src is ndarray)
{
srcArray = (ndarray)src;
}
else if (false)
{
// TODO: Not handling scalars. See arrayobject.c:111
}
else
{
dtype src_dtype = NpyCoreApi.ToInterface<dtype>(descr);
srcArray = FromAny(src, src_dtype, 0, dest.ndim,
dest.dtype.Flags & NpyDefs.NPY_FORTRAN, null);
}
NpyCoreApi.Incref(descr);
if (NpyCoreApi.NpyArray_SetField(dest.Array, descr, offset, srcArray.Array) < 0)
{
NpyCoreApi.CheckError();
}
}
/// <summary>
/// Checks the strides against the shape of the array. This duplicates
/// NpyArray_CheckStrides and is only here because we don't currently support
/// buffers and can simplify this function plus it's much faster to do here
/// than to pass the arrays into the native world.
/// </summary>
/// <param name="elSize">Size of array element in bytes</param>
/// <param name="shape">Size of each dimension of the array</param>
/// <param name="strides">Stride of each dimension</param>
/// <returns>True if strides are ok, false if not</returns>
internal static bool CheckStrides(int elSize, long[] shape, long[] strides) {
// Product of all dimension sizes * element size in bytes.
long numbytes = shape.Aggregate(1L, (acc, x) => acc * x) * elSize;
long end = numbytes - elSize;
for (int i = 0; i < shape.Length; i++) {
if (strides[i] * (shape[i] - 1) > end) return false;
}
return true;
}
internal static ndarray CheckFromArray(Object src, dtype descr, int minDepth,
int maxDepth, int requires, Object context) {
if ((requires & NpyDefs.NPY_NOTSWAPPED) != 0) {
if (descr != null && src is ndarray &&
((ndarray)src).dtype.IsNativeByteOrder) {
descr = new dtype(((ndarray)src).dtype);
} else if (descr != null && !descr.IsNativeByteOrder) {
// Descr replace
}
if (descr != null) {
descr.ByteOrder = (byte)'=';
}
}
ndarray arr = FromAny(src, descr, minDepth, maxDepth, requires, context);
if (arr != null && (requires & NpyDefs.NPY_ELEMENTSTRIDES) != 0 &&
arr.ElementStrides == 0) {
arr = arr.NewCopy(NpyDefs.NPY_ORDER.NPY_ANYORDER);
}
return arr;
}
private static Exception UpdateIfCopyError() {
return new ArgumentException("UPDATEIFCOPY used for non-array input.");
}
private static ndarray FromAnyReturn(ndarray result, int minDepth, int maxDepth) {
if (minDepth != 0 && result.ndim < minDepth) {
throw new ArgumentException("object of too small depth for desired array");
}
if (maxDepth != 0 && result.ndim > maxDepth) {
throw new ArgumentException("object too deep for desired array");
}
return result;
}
internal static ndarray EnsureArray(object o) {
if (o == null) {
return null;
}
if (o.GetType() == typeof(ndarray)) {
return (ndarray)o;
}
if (o is ndarray) {
return FromArray((ndarray)o, null, NpyDefs.NPY_ENSUREARRAY);
}
return FromAny(o, flags: NpyDefs.NPY_ENSUREARRAY);
}
internal static ndarray EnsureAnyArray(object o) {
if (o == null) {
return null;
}
if (o is ndarray) {
return (ndarray)o;
}
return FromAny(o, flags: NpyDefs.NPY_ENSUREARRAY);
}
/// <summary>
/// Constructs a new array from multiple input types, like lists, arrays, etc.
/// </summary>
/// <param name="src"></param>
/// <param name="descr"></param>
/// <param name="minDepth"></param>
/// <param name="maxDepth"></param>
/// <param name="requires"></param>
/// <param name="context"></param>
/// <returns></returns>
internal static ndarray FromAny(Object src, dtype descr=null, int minDepth=0,
int maxDepth=0, int flags=0, Object context=null) {
ndarray result = null;
if (src == null) {
return Empty(new long[0], NpyCoreApi.DescrFromType(NpyDefs.NPY_TYPES.NPY_OBJECT));
}
Type t = src.GetType();
if (t != typeof(List) && t != typeof(PythonTuple)) {
if (src is ndarray) {
result = FromArray((ndarray)src, descr, flags);
return FromAnyReturn(result, minDepth, maxDepth);
}
if (src is ScalarGeneric) {
if ((flags & NpyDefs.NPY_UPDATEIFCOPY)!=0) {
throw UpdateIfCopyError();
}
result = FromScalar((ScalarGeneric)src, descr);
return FromAnyReturn(result, minDepth, maxDepth);
}
dtype newtype = (descr ?? FindScalarType(src));
if (descr == null && newtype != null) {
if ((flags & NpyDefs.NPY_UPDATEIFCOPY) != 0) {
throw UpdateIfCopyError();
}
result = FromPythonScalar(src, newtype);
return FromAnyReturn(result, minDepth, maxDepth);
}
// TODO: Handle buffer protocol
// TODO: Look at __array_struct__ and __array_interface__
result = FromArrayAttr(NpyUtil_Python.DefaultContext, src, descr, context);
if (result != null) {
if (descr != null && !NpyCoreApi.EquivTypes(descr, result.dtype) || flags != 0) {
result = FromArray(result, descr, flags);
return FromAnyReturn(result, minDepth, maxDepth);
}
}
}
bool is_object = false;
if ((flags&NpyDefs.NPY_UPDATEIFCOPY)!=0) {
throw UpdateIfCopyError();
}
if (descr == null) {
descr = FindArrayType(src, null);
} else if (descr.TypeNum == NpyDefs.NPY_TYPES.NPY_OBJECT) {
is_object = true;
}
bool seq = false;
if (src is IEnumerable<object>) {
try {
result = FromIEnumerable((IEnumerable<object>)src, descr, (flags & NpyDefs.NPY_FORTRAN) != 0, minDepth, maxDepth);
seq = true;
} catch (InsufficientMemoryException) {
throw;
} catch {
if (is_object) {
result = FromNestedList(src, descr, (flags & NpyDefs.NPY_FORTRAN) != 0);
seq = true;
}
}
}
if (!seq) {
result = FromPythonScalar(src, descr);
}
return FromAnyReturn(result, minDepth, maxDepth);
}
internal static ndarray FromNestedList(object src, dtype descr, bool fortran) {
long[] dims = new long[NpyDefs.NPY_MAXDIMS];
int nd = ObjectDepthAndDimension(src, dims, 0, NpyDefs.NPY_MAXDIMS);
if (nd == 0) {
return FromPythonScalar(src, descr);
}
ndarray result = NpyCoreApi.AllocArray(descr, nd, dims, fortran);
AssignToArray(src, result);
return result;
}
/// <summary>
/// Walks a set of nested lists (or tuples) to get the dimensions. The dimensionality must
/// be consistent for each nesting level. Thus, if one level is a mix of lsits and scalars,
/// it is truncated and all are assumed to be scalar objects.
///
/// That is, [[1, 2], 3, 4] is a 1-d array of 3 elements. It just happens that element 0 is
/// an object that is a list of [1, 2].
/// </summary>
/// <param name="src">Input object to talk</param>
/// <param name="dims">Array of dimensions of size 'max' filled in up to the return value</param>
/// <param name="idx">Current iteration depth, always start with 0</param>
/// <param name="max">Size of dims array at the start, then becomes depth so far when !firstElem</param>
/// <param name="firstElem">True if processing the first element of the list (populates dims), false for subsequent (checks dims)</param>
/// <returns>Number of dimensions (depth of nesting)</returns>
internal static int ObjectDepthAndDimension(object src, long[] dims, int idx, int max, bool firstElem=true)
{
int nd = -1;
// Recursively walk the tree and get the sizes of each dimension. When processing the
// first element in each sequence, firstElem is true and we populate dims[]. After that,
// we just verify that dims[] matches for subsequent elements.
IList<object> list = src as IList<object>; // List and PythonTuple both implement IList
if (max < 1 || list == null) {
nd = 0;
} else if (list.Count == 0) {
nd = 0;
} else if (max < 2) {
// On the first pass, populate the dimensions array. One subsequent passes verify
// that the size is the same or, if not,
if (firstElem) {
dims[idx] = list.Count;
nd = 1;
} else {
nd = (dims[idx] == list.Count) ? 1 : 0;
}
} else if (!firstElem && dims[idx] != list.Count) {
nd = 0;
} else {
// First element we traverse up to max depth and fill in the dims array.
nd = ObjectDepthAndDimension(list.First(), dims, idx + 1, max - 1, firstElem);
// Subsequent elements we just check that the size of each dimension is the
// same as clip the max depth to shallowest depth we have seen thus far.
nd = list.Skip(1).Aggregate(nd, (ndAcc, elem) =>
Math.Min(ndAcc, ObjectDepthAndDimension(elem, dims, idx + 1, ndAcc, false))
);
nd += 1;
dims[idx] = list.Count;
}
return nd;
}
internal static ndarray FromArrayAttr(CodeContext cntx, object src, dtype descr, object context) {
object f;
if (src is PythonType ||
!PythonOps.TryGetBoundAttr(cntx, src, "__array__", out f)) {
return null;
}
object result;
if (context == null) {
if (descr == null) {
result = PythonCalls.Call(cntx, f);
} else {
result = PythonCalls.Call(cntx, f, descr);
}
} else {
if (descr == null) {
try {
result = PythonCalls.Call(cntx, f, null, context);
} catch (ArgumentTypeException) {
result = PythonCalls.Call(cntx, f);
}
} else {
try {
result = PythonCalls.Call(cntx, f, descr, context);
} catch (ArgumentTypeException) {
result = PythonCalls.Call(cntx, f, context);
}
}
}
if (!(result is ndarray)) {
throw new ArgumentException("object __array__ method not producing an array");
}
return (ndarray)result;
}
internal static ndarray FromScalar(ScalarGeneric scalar, dtype descr = null) {
if (descr == null || NpyCoreApi.EquivTypes(scalar.dtype, descr)) {
return scalar.ToArray();
} else {
ndarray arr = scalar.ToArray();
// passing scalar.dtype instead of descr in because otherwise we loose information. Not
// sure if more processing is needed. Relevant CPython code is PyArray_DescrFromScalarUnwrap
return FromArray(arr, scalar.dtype, 0);
}
}
/// <summary>
/// Constructs a new array from an input array and descriptor type. The
/// Underlying array may or may not be copied depending on the requirements.
/// </summary>
/// <param name="src">Source array</param>
/// <param name="descr">Desired type</param>
/// <param name="flags">New array flags</param>
/// <returns>New array (may be source array)</returns>
internal static ndarray FromArray(ndarray src, dtype descr, int flags) {
if (descr == null && flags == 0) return src;
if (descr == null) descr = src.dtype;
if (descr != null) NpyCoreApi.Incref(descr.Descr);
return NpyCoreApi.DecrefToInterface<ndarray>(
NpyCoreApi.NpyArray_FromArray(src.Array, descr.Descr, flags));
}
internal static ndarray FromPythonScalar(object src, dtype descr) {
int itemsize = descr.ElementSize;
NpyDefs.NPY_TYPES type = descr.TypeNum;
if (itemsize == 0 && NpyDefs.IsExtended(type)) {
int n = PythonOps.Length(src);
if (type == NpyDefs.NPY_TYPES.NPY_UNICODE) {
n *= 4;
}
descr = new dtype(descr);
descr.ElementSize = n;
}
ndarray result = NpyCoreApi.AllocArray(descr, 0, null, false);
if (result.ndim > 0) {
throw new ArgumentException("shape-mismatch on array construction");
}
result.dtype.f.SetItem(src, 0, result);
return result;
}
/// <summary>
/// Builds an array from a sequence of objects. The elements of the sequence
/// can also be sequences in which case this function recursively walks the
/// nested sequences and builds an n dimentional array.
///
/// IronPython tuples and lists work as sequences.
/// </summary>
/// <param name="src">Input sequence</param>
/// <param name="descr">Desired array element type or null to determine automatically</param>
/// <param name="fortran">True if array should be Fortran layout, false for C</param>
/// <param name="minDepth"></param>
/// <param name="maxDepth"></param>
/// <returns>New array instance</returns>
internal static ndarray FromIEnumerable(IEnumerable<Object> src, dtype descr,
bool fortran, int minDepth, int maxDepth) {
ndarray result = null;
if (descr == null) {
descr = FindArrayType(src, null, NpyDefs.NPY_MAXDIMS);
}
int itemsize = descr.ElementSize;
NpyDefs.NPY_TYPES type = descr.TypeNum;
bool checkIt = (descr.Type != NpyDefs.NPY_TYPECHAR.NPY_CHARLTR);
bool stopAtString =
type != NpyDefs.NPY_TYPES.NPY_STRING ||
descr.Type == NpyDefs.NPY_TYPECHAR.NPY_STRINGLTR;
bool stopAtTuple =
type == NpyDefs.NPY_TYPES.NPY_VOID &&
(descr.HasNames || descr.HasSubarray);
int numDim = DiscoverDepth(src, NpyDefs.NPY_MAXDIMS + 1, stopAtString, stopAtTuple);
if (numDim == 0) {
return FromPythonScalar(src, descr);
} else {
if (maxDepth > 0 && type == NpyDefs.NPY_TYPES.NPY_OBJECT &&
numDim > maxDepth) {
numDim = maxDepth;
}
if (maxDepth > 0 && numDim > maxDepth ||
minDepth > 0 && numDim < minDepth) {
throw new ArgumentException("Invalid number of dimensions.");
}
long[] dims = new long[numDim];
DiscoverDimensions(src, numDim, dims, 0, checkIt);
if (descr.Type == NpyDefs.NPY_TYPECHAR.NPY_CHARLTR &&
numDim > 0 && dims[numDim - 1] == 1) {
numDim--;
}
if (itemsize == 0 && NpyDefs.IsExtended(descr.TypeNum)) {
itemsize = DiscoverItemsize(src, numDim, 0);
if (descr.TypeNum == NpyDefs.NPY_TYPES.NPY_UNICODE) {
itemsize *= 4;
}
descr = new dtype(descr);
descr.ElementSize = itemsize;
}
result = NpyCoreApi.AllocArray(descr, numDim, dims, fortran);
AssignToArray(src, result);
}
return result;
}
internal static ndarray PrependOnes(ndarray arr, int nd, int ndmin) {
IntPtr[] newdims = new IntPtr[ndmin];
IntPtr[] newstrides = new IntPtr[ndmin];
int num = ndmin - nd;
// Set the first num dims and strides for the 1's
for (int i=0; i<num; i++) {
newdims[i] = (IntPtr)1;
newstrides[i] = (IntPtr)arr.dtype.ElementSize;
}
// Copy in the rest of dims and strides
for (int i=num; i<ndmin; i++) {
int k = i-num;
newdims[i] = (IntPtr)arr.Dims[k];
newstrides[i] = (IntPtr)arr.Strides[k];
}
return NpyCoreApi.NewView(arr.dtype, ndmin, newdims, newstrides, arr, IntPtr.Zero, false);
}
private static dtype FindArrayReturn(dtype chktype, dtype minitype) {
dtype result = NpyCoreApi.SmallType(chktype, minitype);
if (result.TypeNum == NpyDefs.NPY_TYPES.NPY_VOID &&
minitype.TypeNum != NpyDefs.NPY_TYPES.NPY_VOID) {
result = NpyCoreApi.DescrFromType(NpyDefs.NPY_TYPES.NPY_OBJECT);
}
return result;
}
internal static dtype FindArrayType(Object src, dtype minitype, int max = NpyDefs.NPY_MAXDIMS) {
dtype chktype = null;
if (src is ndarray) {
chktype = ((ndarray)src).dtype;
if (minitype == null) {
return chktype;
} else {
return FindArrayReturn(chktype, minitype);
}
}
if (src is ScalarGeneric) {
chktype = ((ScalarGeneric)src).dtype;
if (minitype == null) {
return chktype;
} else {
return FindArrayReturn(chktype, minitype);
}
}
if (minitype == null) {
minitype = NpyCoreApi.DescrFromType(NpyDefs.NPY_TYPES.NPY_BOOL);
}
if (max < 0) {
chktype = UseDefaultType(src);
return FindArrayReturn(chktype, minitype);
}
chktype = FindScalarType(src);
if (chktype != null) {
return FindArrayReturn(chktype, minitype);
}
if (src is Bytes) {
Bytes b = (Bytes)src;
chktype = new dtype(NpyCoreApi.DescrFromType(NpyDefs.NPY_TYPES.NPY_STRING));
chktype.ElementSize = b.Count;
return FindArrayReturn(chktype, minitype);
}
if (src is String) {
String s = (String)src;
chktype = new dtype(NpyCoreApi.DescrFromType(NpyDefs.NPY_TYPES.NPY_UNICODE));
chktype.ElementSize = s.Length*4;
return FindArrayReturn(chktype, minitype);
}
// TODO: Handle buffer protocol
// TODO: __array_interface__
// TODO: __array_struct__
CodeContext cntx = NpyUtil_Python.DefaultContext;
object arrayAttr;
if (PythonOps.TryGetBoundAttr(cntx, src, "__array__", out arrayAttr)) {
try {
object ip = PythonCalls.Call(cntx, arrayAttr);
if (ip is ndarray) {
chktype = ((ndarray)ip).dtype;
return FindArrayReturn(chktype, minitype);
}
} catch {
// Ignore errors
}
}
// TODO: PyInstance_Check?
if (src is IEnumerable<object>) {
// TODO: This does not work for user-defined Python sequences
int l;
try {
l = PythonOps.Length(src);
} catch {
chktype = UseDefaultType(src);
return FindArrayReturn(chktype, minitype);
}
if (l == 0 && minitype.TypeNum == NpyDefs.NPY_TYPES.NPY_BOOL) {
minitype = NpyCoreApi.DescrFromType(NpyDefs.DefaultType);
}
while (--l >= 0) {
object item;
try {
item = PythonOps.GetIndex(cntx, src, l);
} catch {
chktype = UseDefaultType(src);
return FindArrayReturn(chktype, minitype);
}
chktype = FindArrayType(item, minitype, max-1);
minitype = NpyCoreApi.SmallType(chktype, minitype);
}
chktype = minitype;
return chktype;
}
chktype = UseDefaultType(src);
return FindArrayReturn(chktype, minitype);
}
private static dtype UseDefaultType(Object src) {
// TODO: User-defined types are not implemented yet.
return NpyCoreApi.DescrFromType(NpyDefs.NPY_TYPES.NPY_OBJECT);
}
/// <summary>
/// Returns the descriptor for a given native type or null if src is
/// not a scalar type
/// </summary>
/// <param name="src">Object to type</param>
/// <returns>Descriptor for type of 'src' or null if not scalar</returns>
internal static dtype FindScalarType(Object src) {
NpyDefs.NPY_TYPES type;
if (src is Double) type = NpyDefs.NPY_TYPES.NPY_DOUBLE;
else if (src is Single) type = NpyDefs.NPY_TYPES.NPY_FLOAT;
else if (src is Boolean) type = NpyDefs.NPY_TYPES.NPY_BOOL;
else if (src is Byte) type = NpyDefs.NPY_TYPES.NPY_BYTE;
else if (src is Int16) type = NpyDefs.NPY_TYPES.NPY_SHORT;
else if (src is Int32) type = NpyCoreApi.TypeOf_Int32;
else if (src is Int64) type = NpyCoreApi.TypeOf_Int64;
else if (src is UInt16) type = NpyDefs.NPY_TYPES.NPY_USHORT;
else if (src is UInt32) type = NpyCoreApi.TypeOf_UInt32;
else if (src is UInt64) type = NpyCoreApi.TypeOf_UInt64;
else if (src is BigInteger) {
BigInteger bi = (BigInteger)src;
if (Int64.MinValue <= bi && bi <= Int64.MaxValue) {
type = NpyCoreApi.TypeOf_Int64;
} else {
type = NpyDefs.NPY_TYPES.NPY_OBJECT;
}
}
else if (src is Complex) type = NpyDefs.NPY_TYPES.NPY_CDOUBLE;
else type = NpyDefs.NPY_TYPES.NPY_NOTYPE;
return (type != NpyDefs.NPY_TYPES.NPY_NOTYPE) ?
NpyCoreApi.DescrFromType(type) : null;
}
/// <summary>
/// Recursively discovers the nesting depth of a source object.
/// </summary>
/// <param name="src">Input object</param>
/// <param name="max">Max recursive depth</param>
/// <param name="stopAtString">Stop discovering if string is encounted</param>
/// <param name="stopAtTuple">Stop discovering if tuple is encounted</param>
/// <returns>Nesting depth or -1 on error</returns>
private static int DiscoverDepth(Object src, int max,
bool stopAtString, bool stopAtTuple) {
int d = 0;
if (max < 1) {
throw new ArgumentException("invalid input sequence");
}
if (stopAtTuple && src is PythonTuple) {
return 0;
}
if (src is string) {
return (stopAtString ? 0 : 1);
}
if (src is ndarray) {
return ((ndarray)src).ndim;
}
if (src is IList<object>) {
IList<object> list = (IList<object>)src;
if (list.Count == 0) {
return 1;
} else {
d = DiscoverDepth(list[0], max-1, stopAtString, stopAtTuple);
return d+1;
}
}
if (src is IEnumerable<object>) {
IEnumerable<object> seq = (IEnumerable<object>)src;
object first;
try {
first = seq.First();
} catch (InvalidOperationException) {
// Empty sequence
return 1;
}
d = DiscoverDepth(first, max-1, stopAtString, stopAtTuple);
return d+1;
}
// TODO: Not handling __array_struct__ attribute
// TODO: Not handling __array_interface__ attribute
return 0;
}
/// <summary>
/// Recursively discovers the size of each dimension given an input object.
/// </summary>
/// <param name="src">Input object</param>
/// <param name="numDim">Number of dimensions</param>
/// <param name="dims">Uninitialized array of dimension sizes to be filled in</param>
/// <param name="dimIdx">Current index into dims, incremented recursively</param>
/// <param name="checkIt">Verify that src is consistent</param>
private static void DiscoverDimensions(Object src, int numDim,
Int64[] dims, int dimIdx, bool checkIt) {
Int64 nLowest;
if (src is ndarray) {
ndarray arr = (ndarray)src;
if (arr.ndim == 0) dims[dimIdx] = 0;
else {
Int64[] d = arr.Dims;
for (int i = 0; i < numDim; i++) {
dims[i + dimIdx] = d[i];
}
}
} else if (src is IList<object>) {
IList<object> seq = (IList<object>)src;
nLowest = 0;
dims[dimIdx] = seq.Count();
if (numDim > 1) {
foreach (Object o in seq) {
DiscoverDimensions(o, numDim - 1, dims, dimIdx + 1, checkIt);
if (checkIt && nLowest != 0 && nLowest != dims[dimIdx + 1]) {
throw new ArgumentException("Inconsistent shape in sequence");
}
if (dims[dimIdx + 1] > nLowest) nLowest = dims[dimIdx + 1];
}
dims[dimIdx + 1] = nLowest;
}
}
else if (src is IEnumerable<Object>) {
IEnumerable<Object> seq = (IEnumerable<Object>)src;
nLowest = 0;
dims[dimIdx] = seq.Count();
if (numDim > 1) {
foreach (Object o in seq) {
DiscoverDimensions(o, numDim - 1, dims, dimIdx + 1, checkIt);
if (checkIt && nLowest != 0 && nLowest != dims[dimIdx + 1]) {
throw new ArgumentException("Inconsistent shape in sequence");
}
if (dims[dimIdx + 1] > nLowest) nLowest = dims[dimIdx + 1];
}
dims[dimIdx + 1] = nLowest;
}
} else {
// Scalar condition.
dims[dimIdx] = 1;
}
}
private static int DiscoverItemsize(object s, int nd, int min) {
if (s is ndarray) {
ndarray a = (ndarray)s;
return Math.Max(min, a.dtype.ElementSize);
}
int n = (int)NpyUtil_Python.CallBuiltin(null, "len", s);
if (nd == 0 || s is string || s is Bytes || s is MemoryView || s is PythonBuffer) {
return Math.Max(min, n);
} else {
int result = min;
for (int i = 0; i < n; i++) {
object item = PythonOps.GetIndex(NpyUtil_Python.DefaultContext, s, i);
result = DiscoverItemsize(item, nd - 1, result);
}
return result;
}
}
internal static ndarray Empty(long[] shape, dtype type = null, NpyDefs.NPY_ORDER order = NpyDefs.NPY_ORDER.NPY_CORDER) {
if (type == null) {
type = NpyCoreApi.DescrFromType(NpyDefs.DefaultType);
}
return NpyCoreApi.NewFromDescr(type, shape, null, (int)order, null);
}
internal static ndarray Zeros(long[] shape, dtype type = null, NpyDefs.NPY_ORDER order = NpyDefs.NPY_ORDER.NPY_CORDER) {
ndarray result = Empty(shape, type, order);
NpyCoreApi.NpyArrayAccess_ZeroFill(result.Array, IntPtr.Zero);
if (type.IsObject) {
// Object arrays are zero filled when created
FillObjects(result, 0);
} else {
NpyCoreApi.NpyArrayAccess_ZeroFill(result.Array, IntPtr.Zero);
}
return result;
}
internal static ndarray Arange(CodeContext cntx, object start, object stop = null, object step = null, dtype d = null) {
long[] dims;
if (d == null) {
d = NpyCoreApi.DescrFromType(NpyDefs.NPY_TYPES.NPY_LONG);
d = FindArrayType(start, d);
if (stop != null) {
d = FindArrayType(stop, d);
}
if (step != null) {
d = FindArrayType(step, d);
}
}
if (step == null) {
step = 1;
}
if (stop == null) {
stop = start;
start = 0;
}
object next;
IntPtr len = IntPtr.Zero;
try {
len = CalcLength(cntx, start, stop, step, out next, NpyDefs.IsComplex(d.TypeNum));
} catch (OverflowException) {
// Translate the error to make test_regression.py happy.
throw new ArgumentException("Maximum allowed size exceeded");
}
if (len.ToInt64() < 0) {
dims = new long[] { 0 };
return NpyCoreApi.NewFromDescr(d, dims, null, 0, null);
}
dtype native;
bool swap;
if (!d.IsNativeByteOrder) {
native = NpyCoreApi.DescrNewByteorder(d, '=');
swap = true;
} else {
native = d;
swap = false;
}
dims = new long[] { len.ToInt64() };
ndarray result = NpyCoreApi.NewFromDescr(native, dims, null, 0, null);
result.SetItem(start, 0);
if (len.ToInt64() > 1) {
result.SetItem(next, d.ElementSize);
}
if (len.ToInt64() > 2) {
NpyCoreApi.Fill(result);
}
if (swap) {
NpyCoreApi.Byteswap(result, true);
result.dtype = d;
}
return result;
}
internal static IntPtr CeilToIntPtr(double d) {
d = Math.Ceiling(d);
if (IntPtr.Size == 4) {
if (d > int.MaxValue || d < int.MinValue) {
throw new OverflowException();
}
return (IntPtr)(int)d;
} else {
if (d > long.MaxValue || d < long.MinValue) {
throw new OverflowException();
}
return (IntPtr)(long)d;
}
}
internal static IntPtr CalcLength(CodeContext cntx, object start, object stop, object step, out object next, bool complex) {
dynamic ops = PythonOps.ImportTop(cntx, "operator", 0);
object n = ops.sub(stop, start);
object val = ops.truediv(n, step);
IntPtr result;
if (complex && val is Complex) {
Complex c = (Complex)val;
result = CeilToIntPtr(Math.Min(c.Real, c.Imaginary));
} else {
double d = Convert.ToDouble(val);
result = CeilToIntPtr(d);
}
next = ops.add(start, step);
return result;
}
internal static void FillObjects(ndarray arr, object o) {
dtype d = arr.dtype;
if (d.IsObject) {
if (d.HasNames) {
foreach (string name in d.Names) {
using (ndarray view = NpyCoreApi.GetField(arr, name)) {
FillObjects(view, o);
}
}
} else {
NpyCoreApi.FillWithObject(arr, o);
}
}
}
internal static void AssignToArray(Object src, ndarray result) {
IEnumerable<object> seq = src as IEnumerable<object>;
if (seq == null) {
throw new ArgumentException("assignment from non-sequence");
}
if (result.ndim == 0) {
throw new ArgumentException("assignment to 0-d array");
}
AssignFromSeq(seq, result, 0, 0);
}
private static void AssignFromSeq(IEnumerable<Object> seq, ndarray result,
int dim, long offset) {
if (dim >= result.ndim) {
throw new IronPython.Runtime.Exceptions.RuntimeException(
String.Format("Source dimensions ({0}) exceeded target array dimensions ({1}).",
dim, result.ndim));
}
if (seq is ndarray && seq.GetType() != typeof(ndarray)) {
// Convert to an array to ensure the dimensionality reduction
// assumption works.
ndarray array = FromArray((ndarray)seq, null, NpyDefs.NPY_ENSUREARRAY);
seq = (IEnumerable<object>)array;
}
if (seq.Count() != result.Dims[dim]) {
throw new IronPython.Runtime.Exceptions.RuntimeException(
"AssignFromSeq: sequence/array shape mismatch.");
}
long stride = result.Stride(dim);
if (dim < result.ndim - 1) {
// Sequence elements should be additional sequences
seq.Iteri((o, i) =>
AssignFromSeq((IEnumerable<Object>)o, result, dim + 1, offset + stride * i));
} else {
seq.Iteri((o, i) => result.dtype.f.SetItem(o, offset + i*stride, result));
}
}
internal static ndarray Concatenate(IEnumerable<object> arrays, int axis) {
int i;
try {
arrays.First();
} catch (InvalidOperationException) {
throw new ArgumentException("concatenation of zero-length sequence is impossible");
}
ndarray[] mps = NpyUtil_ArgProcessing.ConvertToCommonType(arrays);
int n = mps.Length;
// TODO: Deal with subtypes
if (axis >= NpyDefs.NPY_MAXDIMS) {
// Flatten the arrays
for (i = 0; i < n; i++) {
mps[i] = mps[i].Ravel(NpyDefs.NPY_ORDER.NPY_CORDER);
}
} else if (axis != 0) {
// Swap to make the axis 0
for (i = 0; i < n; i++) {
mps[i] = NpyArray.FromArray(mps[i].SwapAxes(axis, 0), null, NpyDefs.NPY_C_CONTIGUOUS);
}
}
long[] dims = mps[0].Dims;
if (dims.Length == 0) {
throw new ArgumentException("0-d arrays can't be concatenated");
}
long new_dim = dims[0];
for (i = 1; i < n; i++) {
long[] dims2 = mps[i].Dims;
if (dims.Length != dims2.Length) {
throw new ArgumentException("arrays must have same number of dimensions");
}
bool eq = Enumerable.Zip(dims.Skip(1), dims2.Skip(1), (a, b) => (a == b)).All(x => x);
if (!eq) {
throw new ArgumentException("array dimensions do not agree");
}
new_dim += dims2[0];
}
dims[0] = new_dim;
ndarray result = NpyCoreApi.AllocArray(mps[0].dtype, dims.Length, dims, false);
if (!result.dtype.IsObject) {
// TODO: We really should be doing a memcpy here.
unsafe {
byte* dest = (byte*)result.UnsafeAddress.ToPointer();
foreach (ndarray a in mps) {
long s = a.Size*a.dtype.ElementSize;
byte* src = (byte*)a.UnsafeAddress;
while (s-- > 0) {
*dest++ = *src++;
}
}
}
} else {
// Do a high-level copy to get the references right.
long j = 0;
flatiter flat = result.Flat;
foreach (ndarray a in mps) {
long size = a.Size;
flat[new Slice(j, j+size)] = a.flat;
j += size;
}
}
if (0 < axis && axis < NpyDefs.NPY_MAXDIMS || axis < 0) {
return result.SwapAxes(axis, 0);
} else {
return result;
}
}
internal static ndarray InnerProduct(object o1, object o2) {
dtype d = FindArrayType(o1, null);
d = FindArrayType(o2, d);
ndarray a1 = FromAny(o1, d, flags: NpyDefs.NPY_ALIGNED);
ndarray a2 = FromAny(o2, d, flags: NpyDefs.NPY_ALIGNED);
return NpyCoreApi.DecrefToInterface<ndarray>(
NpyCoreApi.NpyArray_InnerProduct(a1.Array, a2.Array, (int)d.TypeNum));
}
internal static ndarray MatrixProduct(object o1, object o2) {
dtype d = FindArrayType(o1, null);
d = FindArrayType(o2, d);
ndarray a1 = FromAny(o1, d, flags: NpyDefs.NPY_ALIGNED);
ndarray a2 = FromAny(o2, d, flags: NpyDefs.NPY_ALIGNED);
if (a1.ndim == 0) {
return NpyArray.EnsureAnyArray(a1.item() * a2);
} else if (a2.ndim == 0) {
return NpyArray.EnsureAnyArray(a1 * a2.item());
} else {
return NpyCoreApi.DecrefToInterface<ndarray>(
NpyCoreApi.NpyArray_MatrixProduct(a1.Array, a2.Array, (int)d.TypeNum));
}
}
}
}
| |
//
// RssParser.cs
//
// Authors:
// Mike Urbanski <michael.c.urbanski@gmail.com>
// Gabriel Burt <gburt@novell.com>
//
// Copyright (C) 2007 Mike 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.Xml;
using System.Text;
using System.Collections.Generic;
using Hyena;
namespace Migo.Syndication
{
public class RssParser
{
private XmlDocument doc;
private XmlNamespaceManager mgr;
private string url;
public RssParser (string url, string xml)
{
this.url = url;
xml = xml.TrimStart ();
doc = new XmlDocument ();
// Don't resolve any external references, see bgo#601554
doc.XmlResolver = null;
try {
doc.LoadXml (xml);
} catch (XmlException e) {
bool have_stripped_control = false;
StringBuilder sb = new StringBuilder ();
foreach (char c in xml) {
if (Char.IsControl (c) && c != '\n') {
have_stripped_control = true;
} else {
sb.Append (c);
}
}
bool loaded = false;
if (have_stripped_control) {
try {
doc.LoadXml (sb.ToString ());
loaded = true;
} catch (Exception) {
}
}
if (!loaded) {
Log.Error (e);
throw new FormatException ("Invalid XML document.");
}
}
CheckRss ();
}
public RssParser (string url, XmlDocument doc)
{
this.url = url;
this.doc = doc;
CheckRss ();
}
public Feed CreateFeed ()
{
return UpdateFeed (new Feed ());
}
public Feed UpdateFeed (Feed feed)
{
try {
if (feed.Title == null || feed.Title.Trim () == "" || feed.Title == Mono.Unix.Catalog.GetString ("Unknown Podcast")) {
feed.Title = StringUtil.RemoveNewlines (GetXmlNodeText (doc, "/rss/channel/title"));
if (String.IsNullOrEmpty (feed.Title)) {
feed.Title = Mono.Unix.Catalog.GetString ("Unknown Podcast");
}
}
feed.Description = StringUtil.RemoveNewlines (GetXmlNodeText (doc, "/rss/channel/description"));
feed.Copyright = GetXmlNodeText (doc, "/rss/channel/copyright");
feed.ImageUrl = GetXmlNodeText (doc, "/rss/channel/itunes:image/@href");
if (String.IsNullOrEmpty (feed.ImageUrl)) {
feed.ImageUrl = GetXmlNodeText (doc, "/rss/channel/image/url");
}
feed.Language = GetXmlNodeText (doc, "/rss/channel/language");
feed.LastBuildDate = GetRfc822DateTime (doc, "/rss/channel/lastBuildDate");
feed.Link = GetXmlNodeText (doc, "/rss/channel/link");
feed.PubDate = GetRfc822DateTime (doc, "/rss/channel/pubDate");
feed.Keywords = GetXmlNodeText (doc, "/rss/channel/itunes:keywords");
feed.Category = GetXmlNodeText (doc, "/rss/channel/itunes:category/@text");
return feed;
} catch (Exception e) {
Log.Error ("Caught error parsing RSS channel", e);
}
return null;
}
public IEnumerable<FeedItem> GetFeedItems (Feed feed)
{
XmlNodeList nodes = null;
try {
nodes = doc.SelectNodes ("//item");
} catch (Exception e) {
Log.Error ("Unable to get any RSS items", e);
}
if (nodes != null) {
foreach (XmlNode node in nodes) {
FeedItem item = null;
try {
item = ParseItem (node);
if (item != null) {
item.Feed = feed;
}
} catch (Exception e) {
Log.Error (e);
}
if (item != null) {
yield return item;
}
}
}
}
private FeedItem ParseItem (XmlNode node)
{
try {
FeedItem item = new FeedItem ();
item.Description = StringUtil.RemoveNewlines (GetXmlNodeText (node, "description"));
item.UpdateStrippedDescription ();
item.Title = StringUtil.RemoveNewlines (GetXmlNodeText (node, "title"));
if (String.IsNullOrEmpty (item.Description) && String.IsNullOrEmpty (item.Title)) {
throw new FormatException ("node: Either 'title' or 'description' node must exist.");
}
item.Author = GetXmlNodeText (node, "author");
item.Comments = GetXmlNodeText (node, "comments");
// Removed, since we form our own Guid, since feeds don't seem to be consistent
// about including this element.
//item.Guid = GetXmlNodeText (node, "guid");
item.Link = GetXmlNodeText (node, "link");
item.PubDate = GetRfc822DateTime (node, "pubDate");
item.Modified = GetRfc822DateTime (node, "dcterms:modified");
item.LicenseUri = GetXmlNodeText (node, "creativeCommons:license");
// TODO prefer <media:content> nodes over <enclosure>?
item.Enclosure = ParseEnclosure (node) ?? ParseMediaContent (node);
return item;
} catch (Exception e) {
Log.Error ("Caught error parsing RSS item", e);
}
return null;
}
private FeedEnclosure ParseEnclosure (XmlNode node)
{
try {
FeedEnclosure enclosure = new FeedEnclosure ();
enclosure.Url = GetXmlNodeText (node, "enclosure/@url");
if (String.IsNullOrEmpty (enclosure.Url)) {
return null;
}
enclosure.FileSize = Math.Max (0, GetInt64 (node, "enclosure/@length"));
enclosure.MimeType = GetXmlNodeText (node, "enclosure/@type");
enclosure.Duration = GetITunesDuration (node);
enclosure.Keywords = GetXmlNodeText (node, "itunes:keywords");
return enclosure;
} catch (Exception e) {
Log.Error (String.Format ("Caught error parsing RSS enclosure in {0}", url), e);
}
return null;
}
// Parse one Media RSS media:content node
// http://search.yahoo.com/mrss/
private FeedEnclosure ParseMediaContent (XmlNode item_node)
{
try {
XmlNode node = null;
// Get the highest bitrate "full" content item
// TODO allow a user-preference for a feed to decide what quality to get, if there
// are options?
int max_bitrate = 0;
foreach (XmlNode test_node in item_node.SelectNodes ("media:content", mgr)) {
string expr = GetXmlNodeText (test_node, "@expression");
if (!(String.IsNullOrEmpty (expr) || expr == "full"))
continue;
int bitrate = GetInt32 (test_node, "@bitrate");
if (node == null || bitrate > max_bitrate) {
node = test_node;
max_bitrate = bitrate;
}
}
if (node == null)
return null;
FeedEnclosure enclosure = new FeedEnclosure ();
enclosure.Url = GetXmlNodeText (node, "@url");
if (String.IsNullOrEmpty (enclosure.Url)) {
return null;
}
enclosure.FileSize = Math.Max (0, GetInt64 (node, "@fileSize"));
enclosure.MimeType = GetXmlNodeText (node, "@type");
enclosure.Duration = TimeSpan.FromSeconds (GetInt64 (node, "@duration"));
enclosure.Keywords = GetXmlNodeText (item_node, "itunes:keywords");
// TODO get the thumbnail URL
return enclosure;
} catch (Exception e) {
Log.Error ("Caught error parsing RSS media:content", e);
}
return null;
}
private void CheckRss ()
{
if (doc.SelectSingleNode ("/rss") == null) {
throw new FormatException ("Invalid RSS document.");
}
if (doc.SelectSingleNode ("/rss/channel/title") == null) {
throw new FormatException ("Invalid RSS document. Node 'title' is required");
}
mgr = new XmlNamespaceManager (doc.NameTable);
mgr.AddNamespace ("itunes", "http://www.itunes.com/dtds/podcast-1.0.dtd");
mgr.AddNamespace ("creativeCommons", "http://backend.userland.com/creativeCommonsRssModule");
mgr.AddNamespace ("media", "http://search.yahoo.com/mrss/");
mgr.AddNamespace ("dcterms", "http://purl.org/dc/terms/");
}
public TimeSpan GetITunesDuration (XmlNode node)
{
return GetITunesDuration (GetXmlNodeText (node, "itunes:duration"));
}
public static TimeSpan GetITunesDuration (string duration)
{
if (String.IsNullOrEmpty (duration)) {
return TimeSpan.Zero;
}
try {
int hours = 0, minutes = 0, seconds = 0;
string [] parts = duration.Split (':');
if (parts.Length > 0)
seconds = Int32.Parse (parts[parts.Length - 1]);
if (parts.Length > 1)
minutes = Int32.Parse (parts[parts.Length - 2]);
if (parts.Length > 2)
hours = Int32.Parse (parts[parts.Length - 3]);
return TimeSpan.FromSeconds (hours * 3600 + minutes * 60 + seconds);
} catch {
return TimeSpan.Zero;
}
}
#region Xml Convienience Methods
public string GetXmlNodeText (XmlNode node, string tag)
{
XmlNode n = node.SelectSingleNode (tag, mgr);
return (n == null) ? null : n.InnerText.Trim ();
}
public DateTime GetRfc822DateTime (XmlNode node, string tag)
{
DateTime ret = DateTime.MinValue;
string result = GetXmlNodeText (node, tag);
if (!String.IsNullOrEmpty (result)) {
if (Rfc822DateTime.TryParse (result, out ret)) {
return ret;
}
if (DateTime.TryParse (result, out ret)) {
return ret;
}
}
return ret;
}
public long GetInt64 (XmlNode node, string tag)
{
long ret = 0;
string result = GetXmlNodeText (node, tag);
if (!String.IsNullOrEmpty (result)) {
Int64.TryParse (result, out ret);
}
return ret;
}
public int GetInt32 (XmlNode node, string tag)
{
int ret = 0;
string result = GetXmlNodeText (node, tag);
if (!String.IsNullOrEmpty (result)) {
Int32.TryParse (result, out ret);
}
return ret;
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
namespace Delver
{
[Serializable]
internal class EventInfoCollection
{
public static EventInfo LeaveZone(Card card, Zone from, Zone to)
{
switch (from)
{
case Zone.Battlefield:
return new LeaveTheBattlefield(card, to);
case Zone.Command:
return new LeaveCommandzone(card, to);
case Zone.Exile:
return new LeaveExile(card, to);
case Zone.Graveyard:
return new LeaveGraveyard(card, to);
case Zone.Hand:
return new LeaveHand(card, to);
case Zone.Library:
return new LeaveLibrary(card, to);
case Zone.Stack:
return new LeaveStack(card, to);
case Zone.None:
return new EventInfo();
default:
throw new NotImplementedException();
}
}
public static EventInfo EnterZone(Card card, Zone from, Zone to)
{
switch (to)
{
case Zone.Battlefield:
return new EnterTheBattlefield(card, from);
case Zone.Command:
return new EnterCommandzone(card, from);
case Zone.Exile:
return new EnterExile(card, from);
case Zone.Graveyard:
return new EnterGraveyard(card, from);
case Zone.Hand:
return new EnterHand(card, from);
case Zone.Library:
return new EnterLibrary(card, from);
case Zone.Stack:
return new EnterStack(card, from);
case Zone.None:
return new EventInfo();
default:
throw new NotImplementedException();
}
}
[Serializable]
public class DealsCombatDamageToPlayer : EventInfo
{
public int Damage;
public bool FirstStrikeDamage;
public Player target;
public DealsCombatDamageToPlayer(Zone zone = Zone.Battlefield) : base(zone)
{
}
public DealsCombatDamageToPlayer(Card source, Player target, int N, bool FirstStrikeDamage)
: this()
{
TriggerCard = source;
this.target = target;
Damage = N;
this.FirstStrikeDamage = FirstStrikeDamage;
}
}
[Serializable]
public class DealsCombatDamageToCreature : EventInfo
{
public int Damage;
public bool FirstStrikeDamage;
public Card target;
public DealsCombatDamageToCreature(Zone zone = Zone.Battlefield) : base(zone)
{
}
public DealsCombatDamageToCreature(Card source, Card target, int N, bool FirstStrikeDamage)
: this()
{
TriggerCard = source;
this.target = target;
Damage = N;
this.FirstStrikeDamage = FirstStrikeDamage;
}
}
[Serializable]
public class Dies : EventInfo
{
public Dies(Zone zone = Zone.Battlefield) : base(zone)
{
}
public Dies(Card card) : this()
{
TriggerPlayer = card.Controller;
TriggerCard = card;
}
}
[Serializable]
public class BeginningOfNextCleanupStep : EventInfo
{
public BeginningOfNextCleanupStep(Zone zone = Zone.Battlefield) : base(zone)
{
}
public BeginningOfNextCleanupStep(Player player) : this()
{
TriggerPlayer = player;
}
}
[Serializable]
public class BeginningOfPostMainStep : EventInfo
{
public BeginningOfPostMainStep(Zone zone = Zone.Battlefield) : base(zone)
{
}
public BeginningOfPostMainStep(Player player) : this()
{
TriggerPlayer = player;
}
}
[Serializable]
public class CreatureAttacks : EventInfo
{
public CreatureAttacks(Zone zone = Zone.Battlefield) : base(zone)
{
}
public CreatureAttacks(Player attacker, Player defender, Card card) : this()
{
TriggerPlayer = attacker;
TriggerCard = card;
}
}
[Serializable]
public class CreatuerBlocks : EventInfo
{
private List<Card> Blocked;
private Card Blocker;
public CreatuerBlocks(Zone zone = Zone.Battlefield) : base(zone)
{
}
public CreatuerBlocks(Player attacker, Player defender, Card Blocker, List<Card> Blocked)
: this()
{
TriggerPlayer = defender;
this.Blocker = Blocker;
this.Blocked = Blocked;
}
}
[Serializable]
public class AttackersDeclared : EventInfo
{
private List<Card> Cards;
public AttackersDeclared(Zone zone = Zone.Battlefield) : base(zone)
{
}
public AttackersDeclared(Player attacker, Player defender, List<Card> cards) : this()
{
TriggerPlayer = attacker;
Cards = cards;
}
}
[Serializable]
public class BlockersDeclared : EventInfo
{
private List<Card> Cards;
public BlockersDeclared(Zone zone = Zone.Battlefield) : base(zone)
{
}
public BlockersDeclared(Player attacker, Player defender, List<Card> cards) : this()
{
TriggerPlayer = defender;
Cards = cards;
}
}
[Serializable]
public class CombatDamageStep : EventInfo
{
public CombatDamageStep(Zone zone = Zone.Battlefield) : base(zone)
{
}
public CombatDamageStep(Player player) : this()
{
TriggerPlayer = player;
}
}
[Serializable]
public class EndOfCombatStep : EventInfo
{
public EndOfCombatStep(Zone zone = Zone.Battlefield) : base(zone)
{
}
public EndOfCombatStep(Player player) : this()
{
TriggerPlayer = player;
}
}
[Serializable]
public class BeginningOfEndStep : EventInfo
{
public BeginningOfEndStep(Zone zone = Zone.Battlefield) : base(zone)
{
}
public BeginningOfEndStep(Player player) : this()
{
TriggerPlayer = player;
}
}
[Serializable]
public class BeginningOfMainStep : EventInfo
{
public BeginningOfMainStep(Zone zone = Zone.Battlefield) : base(zone)
{
}
public BeginningOfMainStep(Player player) : this()
{
TriggerPlayer = player;
}
}
[Serializable]
public class BeginningOfDrawstep : EventInfo
{
public BeginningOfDrawstep(Zone zone = Zone.Battlefield) : base(zone)
{
}
public BeginningOfDrawstep(Player player) : this()
{
TriggerPlayer = player;
}
}
[Serializable]
public class BeginningOfCombatPhase : EventInfo
{
public BeginningOfCombatPhase(Zone zone = Zone.Battlefield) : base(zone)
{
}
public BeginningOfCombatPhase(Player player) : this()
{
TriggerPlayer = player;
}
}
[Serializable]
public class BeginningOfUpkeep : EventInfo
{
public BeginningOfUpkeep(Zone zone = Zone.Battlefield) : base(zone)
{
}
public BeginningOfUpkeep(Player activePlayer) : this()
{
TriggerPlayer = activePlayer;
}
}
[Serializable]
public class EnterTheBattlefield : EventInfo
{
public EnterTheBattlefield(Zone zone = Zone.Battlefield) : base(zone)
{
}
public EnterTheBattlefield(Card triggerCard, Zone from) : this()
{
this.TriggerCard = triggerCard;
this.TriggerPlayer = triggerCard.Controller;
this.FromZone = from;
this.ToZone = Zone.Battlefield;;
}
}
[Serializable]
public class EnterCommandzone : EventInfo
{
public EnterCommandzone(Zone zone = Zone.Battlefield) : base(zone)
{
}
public EnterCommandzone(Card triggerCard, Zone from) : this()
{
this.TriggerCard = triggerCard;
this.TriggerPlayer = triggerCard.Controller;
this.FromZone = from;
this.ToZone = Zone.Command;
}
}
[Serializable]
public class EnterExile : EventInfo
{
public EnterExile(Zone zone = Zone.Battlefield) : base(zone)
{
}
public EnterExile(Card triggerCard, Zone from) : this()
{
this.TriggerCard = triggerCard;
this.TriggerPlayer = triggerCard.Controller;
this.FromZone = from;
this.ToZone = Zone.Exile;
}
}
[Serializable]
public class EnterHand : EventInfo
{
public EnterHand(Zone zone = Zone.Battlefield) : base(zone)
{
}
public EnterHand(Card triggerCard, Zone from) : this()
{
this.TriggerCard = triggerCard;
this.TriggerPlayer = triggerCard.Controller;
this.FromZone = from;
this.ToZone = Zone.Hand;
}
}
[Serializable]
public class EnterLibrary : EventInfo
{
public EnterLibrary(Zone zone = Zone.Battlefield) : base(zone)
{
}
public EnterLibrary(Card triggerCard, Zone from) : this()
{
this.TriggerCard = triggerCard;
this.TriggerPlayer = triggerCard.Controller;
this.FromZone = from;
this.ToZone = Zone.Library;
}
}
[Serializable]
public class EnterGraveyard : EventInfo
{
public EnterGraveyard(Zone zone = Zone.Battlefield) : base(zone)
{
}
public EnterGraveyard(Card triggerCard, Zone from) : this()
{
this.TriggerCard = triggerCard;
this.TriggerPlayer = triggerCard.Controller;
this.FromZone = from;
this.ToZone = Zone.Graveyard;
}
}
[Serializable]
public class EnterStack : EventInfo
{
public EnterStack(Zone zone = Zone.Battlefield) : base(zone)
{
}
public EnterStack(Card triggerCard, Zone from) : this()
{
this.TriggerCard = triggerCard;
this.TriggerPlayer = triggerCard.Controller;
this.FromZone = from;
this.ToZone = Zone.Stack;
}
}
[Serializable]
public class LeaveTheBattlefield : EventInfo
{
public LeaveTheBattlefield(Zone zone = Zone.Battlefield) : base(zone)
{
}
public LeaveTheBattlefield(Card triggerCard, Zone to) : this()
{
this.TriggerCard = triggerCard;
this.TriggerPlayer = triggerCard.Controller;
this.FromZone = Zone.Battlefield;
this.ToZone = to;
}
}
[Serializable]
public class LeaveCommandzone : EventInfo
{
public LeaveCommandzone(Zone zone = Zone.Battlefield) : base(zone)
{
}
public LeaveCommandzone(Card triggerCard, Zone to) : this()
{
this.TriggerCard = triggerCard;
this.TriggerPlayer = triggerCard.Controller;
this.FromZone = Zone.Command;
this.ToZone = to;
}
}
[Serializable]
public class LeaveExile : EventInfo
{
public LeaveExile(Zone zone = Zone.Battlefield) : base(zone)
{
}
public LeaveExile(Card triggerCard, Zone to) : this()
{
this.TriggerCard = triggerCard;
this.TriggerPlayer = triggerCard.Controller;
this.FromZone = Zone.Exile;
this.ToZone = to;
}
}
[Serializable]
public class LeaveHand : EventInfo
{
public LeaveHand(Zone zone = Zone.Battlefield) : base(zone)
{
}
public LeaveHand(Card triggerCard, Zone to) : this()
{
this.TriggerCard = triggerCard;
this.TriggerPlayer = triggerCard.Controller;
this.FromZone = Zone.Hand;
this.ToZone = to;
}
}
[Serializable]
public class LeaveLibrary : EventInfo
{
public LeaveLibrary(Zone zone = Zone.Battlefield) : base(zone)
{
}
public LeaveLibrary(Card triggerCard, Zone to) : this()
{
this.TriggerCard = triggerCard;
this.TriggerPlayer = triggerCard.Controller;
this.FromZone = Zone.Library;
this.ToZone = to;
}
}
[Serializable]
public class LeaveGraveyard : EventInfo
{
public LeaveGraveyard(Zone zone = Zone.Battlefield) : base(zone)
{
}
public LeaveGraveyard(Card triggerCard, Zone to) : this()
{
this.TriggerCard = triggerCard;
this.TriggerPlayer = triggerCard.Controller;
this.FromZone = Zone.Graveyard;
this.ToZone = to;
}
}
[Serializable]
public class LeaveStack : EventInfo
{
public LeaveStack(Zone zone = Zone.Battlefield) : base(zone)
{
}
public LeaveStack(Card triggerCard, Zone to) : this()
{
this.TriggerCard = triggerCard;
this.TriggerPlayer = triggerCard.Controller;
this.FromZone = Zone.Stack;
this.ToZone = to;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime.Remoting;
using System.Runtime.Serialization;
using System.Reflection;
using System.Globalization;
using System.Runtime.Versioning;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
namespace System {
#if FEATURE_SERIALIZATION
[Serializable]
#endif
// Holds classes (Empty, Null, Missing) for which we guarantee that there is only ever one instance of.
internal class UnitySerializationHolder : ISerializable, IObjectReference
{
#region Internal Constants
internal const int EmptyUnity = 0x0001;
internal const int NullUnity = 0x0002;
internal const int MissingUnity = 0x0003;
internal const int RuntimeTypeUnity = 0x0004;
internal const int ModuleUnity = 0x0005;
internal const int AssemblyUnity = 0x0006;
internal const int GenericParameterTypeUnity = 0x0007;
internal const int PartialInstantiationTypeUnity = 0x0008;
internal const int Pointer = 0x0001;
internal const int Array = 0x0002;
internal const int SzArray = 0x0003;
internal const int ByRef = 0x0004;
#endregion
#region Internal Static Members
internal static void GetUnitySerializationInfo(SerializationInfo info, Missing missing)
{
info.SetType(typeof(UnitySerializationHolder));
info.AddValue("UnityType", MissingUnity);
}
internal static RuntimeType AddElementTypes(SerializationInfo info, RuntimeType type)
{
List<int> elementTypes = new List<int>();
while(type.HasElementType)
{
if (type.IsSzArray)
{
elementTypes.Add(SzArray);
}
else if (type.IsArray)
{
elementTypes.Add(type.GetArrayRank());
elementTypes.Add(Array);
}
else if (type.IsPointer)
{
elementTypes.Add(Pointer);
}
else if (type.IsByRef)
{
elementTypes.Add(ByRef);
}
type = (RuntimeType)type.GetElementType();
}
info.AddValue("ElementTypes", elementTypes.ToArray(), typeof(int[]));
return type;
}
internal Type MakeElementTypes(Type type)
{
for (int i = m_elementTypes.Length - 1; i >= 0; i --)
{
if (m_elementTypes[i] == SzArray)
{
type = type.MakeArrayType();
}
else if (m_elementTypes[i] == Array)
{
type = type.MakeArrayType(m_elementTypes[--i]);
}
else if ((m_elementTypes[i] == Pointer))
{
type = type.MakePointerType();
}
else if ((m_elementTypes[i] == ByRef))
{
type = type.MakeByRefType();
}
}
return type;
}
internal static void GetUnitySerializationInfo(SerializationInfo info, RuntimeType type)
{
if (type.GetRootElementType().IsGenericParameter)
{
type = AddElementTypes(info, type);
info.SetType(typeof(UnitySerializationHolder));
info.AddValue("UnityType", GenericParameterTypeUnity);
info.AddValue("GenericParameterPosition", type.GenericParameterPosition);
info.AddValue("DeclaringMethod", type.DeclaringMethod, typeof(MethodBase));
info.AddValue("DeclaringType", type.DeclaringType, typeof(Type));
return;
}
int unityType = RuntimeTypeUnity;
if (!type.IsGenericTypeDefinition && type.ContainsGenericParameters)
{
// Partial instantiation
unityType = PartialInstantiationTypeUnity;
type = AddElementTypes(info, type);
info.AddValue("GenericArguments", type.GetGenericArguments(), typeof(Type[]));
type = (RuntimeType)type.GetGenericTypeDefinition();
}
GetUnitySerializationInfo(info, unityType, type.FullName, type.GetRuntimeAssembly());
}
internal static void GetUnitySerializationInfo(
SerializationInfo info, int unityType, String data, RuntimeAssembly assembly)
{
// A helper method that returns the SerializationInfo that a class utilizing
// UnitySerializationHelper should return from a call to GetObjectData. It contains
// the unityType (defined above) and any optional data (used only for the reflection
// types.)
info.SetType(typeof(UnitySerializationHolder));
info.AddValue("Data", data, typeof(String));
info.AddValue("UnityType", unityType);
String assemName;
if (assembly == null)
{
assemName = String.Empty;
}
else
{
assemName = assembly.FullName;
}
info.AddValue("AssemblyName", assemName);
}
#endregion
#region Private Data Members
private Type[] m_instantiation;
private int[] m_elementTypes;
private int m_genericParameterPosition;
private Type m_declaringType;
private MethodBase m_declaringMethod;
private String m_data;
private String m_assemblyName;
private int m_unityType;
#endregion
#region Constructor
internal UnitySerializationHolder(SerializationInfo info, StreamingContext context)
{
if (info == null)
throw new ArgumentNullException("info");
Contract.EndContractBlock();
m_unityType = info.GetInt32("UnityType");
if (m_unityType == MissingUnity)
return;
if (m_unityType == GenericParameterTypeUnity)
{
m_declaringMethod = info.GetValue("DeclaringMethod", typeof(MethodBase)) as MethodBase;
m_declaringType = info.GetValue("DeclaringType", typeof(Type)) as Type;
m_genericParameterPosition = info.GetInt32("GenericParameterPosition");
m_elementTypes = info.GetValue("ElementTypes", typeof(int[])) as int[];
return;
}
if (m_unityType == PartialInstantiationTypeUnity)
{
m_instantiation = info.GetValue("GenericArguments", typeof(Type[])) as Type[];
m_elementTypes = info.GetValue("ElementTypes", typeof(int[])) as int[];
}
m_data = info.GetString("Data");
m_assemblyName = info.GetString("AssemblyName");
}
#endregion
#region Private Methods
private void ThrowInsufficientInformation(string field)
{
throw new SerializationException(
Environment.GetResourceString("Serialization_InsufficientDeserializationState", field));
}
#endregion
#region ISerializable
[System.Security.SecurityCritical] // auto-generated
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnitySerHolder"));
}
#endregion
#region IObjectReference
[System.Security.SecurityCritical] // auto-generated
public virtual Object GetRealObject(StreamingContext context)
{
// GetRealObject uses the data we have in m_data and m_unityType to do a lookup on the correct
// object to return. We have specific code here to handle the different types which we support.
// The reflection types (Assembly, Module, and Type) have to be looked up through their static
// accessors by name.
Assembly assembly;
switch (m_unityType)
{
case EmptyUnity:
{
return Empty.Value;
}
case NullUnity:
{
return DBNull.Value;
}
case MissingUnity:
{
return Missing.Value;
}
case PartialInstantiationTypeUnity:
{
m_unityType = RuntimeTypeUnity;
Type definition = GetRealObject(context) as Type;
m_unityType = PartialInstantiationTypeUnity;
if (m_instantiation[0] == null)
return null;
return MakeElementTypes(definition.MakeGenericType(m_instantiation));
}
case GenericParameterTypeUnity:
{
if (m_declaringMethod == null && m_declaringType == null)
ThrowInsufficientInformation("DeclaringMember");
if (m_declaringMethod != null)
return m_declaringMethod.GetGenericArguments()[m_genericParameterPosition];
return MakeElementTypes(m_declaringType.GetGenericArguments()[m_genericParameterPosition]);
}
case RuntimeTypeUnity:
{
if (m_data == null || m_data.Length == 0)
ThrowInsufficientInformation("Data");
if (m_assemblyName == null)
ThrowInsufficientInformation("AssemblyName");
if (m_assemblyName.Length == 0)
return Type.GetType(m_data, true, false);
assembly = Assembly.Load(m_assemblyName);
Type t = assembly.GetType(m_data, true, false);
return t;
}
case ModuleUnity:
{
if (m_data == null || m_data.Length == 0)
ThrowInsufficientInformation("Data");
if (m_assemblyName == null)
ThrowInsufficientInformation("AssemblyName");
assembly = Assembly.Load(m_assemblyName);
Module namedModule = assembly.GetModule(m_data);
if (namedModule == null)
throw new SerializationException(
Environment.GetResourceString("Serialization_UnableToFindModule", m_data, m_assemblyName));
return namedModule;
}
case AssemblyUnity:
{
if (m_data == null || m_data.Length == 0)
ThrowInsufficientInformation("Data");
if (m_assemblyName == null)
ThrowInsufficientInformation("AssemblyName");
assembly = Assembly.Load(m_assemblyName);
return assembly;
}
default:
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidUnity"));
}
}
#endregion
}
}
| |
/******************************************************************************
* Copyright (C) Leap Motion, Inc. 2011-2017. *
* Leap Motion proprietary and confidential. *
* *
* Use subject to the terms of the Leap Motion SDK Agreement available at *
* https://developer.leapmotion.com/sdk_agreement, or another agreement *
* between Leap Motion and you, your company or other organization. *
******************************************************************************/
using System.IO;
using System.Reflection;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Assertions;
using UnityEditor;
using UnityEditorInternal;
using Leap.Unity;
using Leap.Unity.Query;
namespace Leap.Unity.GraphicalRenderer {
public class LeapGuiGroupEditor {
public const int BUTTON_WIDTH = 30;
public const int REFRESH_WIDTH = 78;
private LeapGraphicRenderer _renderer;
private SerializedObject _serializedObject;
private SerializedProperty _supportInfo;
private SerializedProperty _groupProperty;
private SerializedProperty _multiFeatureList;
private SerializedProperty _multiRenderingMethod;
private SerializedProperty _featureTable;
private ReorderableList _featureList;
private MonoScript _renderingMethodMonoScript;
private List<SerializedProperty> _cachedPropertyList;
private List<float> _cachedPropertyHeights;
private SerializedProperty _renderingMethod;
private GenericMenu _addRenderingMethodMenu;
private GenericMenu _addFeatureMenu;
public LeapGuiGroupEditor(LeapGraphicRenderer renderer, SerializedObject serializedObject) {
_renderer = renderer;
_serializedObject = serializedObject;
var allTypes = Assembly.GetAssembly(typeof(LeapGraphicRenderer)).GetTypes();
var allRenderingMethods = allTypes.Query().
Where(t => !t.IsAbstract &&
!t.IsGenericType &&
t.IsSubclassOf(typeof(LeapRenderingMethod)));
_addRenderingMethodMenu = new GenericMenu();
foreach (var renderingMethod in allRenderingMethods) {
_addRenderingMethodMenu.AddItem(new GUIContent(LeapGraphicTagAttribute.GetTagName(renderingMethod)),
false,
() => {
serializedObject.ApplyModifiedProperties();
Undo.RecordObject(_renderer, "Changed rendering method");
EditorUtility.SetDirty(_renderer);
_renderer.editor.ChangeRenderingMethodOfSelectedGroup(renderingMethod, addFeatures: false);
serializedObject.Update();
_renderer.editor.ScheduleRebuild();
_serializedObject.SetIsDifferentCacheDirty();
});
}
var allFeatures = allTypes.Query().
Where(t => !t.IsAbstract &&
!t.IsGenericType &&
t.IsSubclassOf(typeof(LeapGraphicFeatureBase))).ToList();
allFeatures.Sort((a, b) => {
var tagA = LeapGraphicTagAttribute.GetTag(a);
var tagB = LeapGraphicTagAttribute.GetTag(b);
var orderA = tagA == null ? 0 : tagA.order;
var orderB = tagB == null ? 0 : tagB.order;
return orderA - orderB;
});
_addFeatureMenu = new GenericMenu();
foreach (var item in allFeatures.Query().WithPrevious(includeStart: true)) {
var tag = LeapGraphicTagAttribute.GetTag(item.value);
var order = tag == null ? 0 : tag.order;
if (item.hasPrev) {
var prevTag = LeapGraphicTagAttribute.GetTag(item.prev);
var prevOrder = prevTag == null ? 0 : prevTag.order;
if ((prevOrder / 100) != (order / 100)) {
_addFeatureMenu.AddSeparator("");
}
}
_addFeatureMenu.AddItem(new GUIContent(tag.name),
false,
() => {
if (item.value.ImplementsInterface(typeof(ICustomChannelFeature)) && LeapGraphicPreferences.promptWhenAddCustomChannel) {
int result = EditorUtility.DisplayDialogComplex("Adding Custom Channel", "Custom channels can only be utilized by writing custom shaders, are you sure you want to continue?", "Add it", "Cancel", "Add it from now on");
switch (result) {
case 0:
break;
case 1:
return;
case 2:
LeapGraphicPreferences.promptWhenAddCustomChannel = false;
break;
}
}
serializedObject.ApplyModifiedProperties();
Undo.RecordObject(_renderer, "Added feature");
EditorUtility.SetDirty(_renderer);
_renderer.editor.AddFeatureToSelectedGroup(item.value);
_serializedObject.Update();
_serializedObject.SetIsDifferentCacheDirty();
});
}
}
public void Invalidate() {
_featureList = null;
_renderingMethodMonoScript = null;
}
public void DoGuiLayout(SerializedProperty groupProperty) {
using (new ProfilerSample("Draw Graphic Group")) {
init(groupProperty);
drawRendererHeader();
drawGroupName();
drawMonoScript();
drawStatsArea();
drawSpriteWarning();
EditorGUILayout.PropertyField(_renderingMethod, includeChildren: true);
EditorGUILayout.Space();
drawFeatureHeader();
_featureList.DoLayoutList();
drawWarningDialogs();
}
}
private void init(SerializedProperty groupProperty) {
Assert.IsNotNull(groupProperty);
_groupProperty = groupProperty;
_multiFeatureList = _groupProperty.FindPropertyRelative("_features");
_multiRenderingMethod = _groupProperty.FindPropertyRelative("_renderingMethod");
_featureTable = MultiTypedListUtil.GetTableProperty(_multiFeatureList);
Assert.IsNotNull(_featureTable);
if (_featureList == null || !SerializedProperty.EqualContents(_featureList.serializedProperty, _featureTable)) {
_featureList = new ReorderableList(_serializedObject,
_featureTable,
draggable: true,
displayHeader: false,
displayAddButton: false,
displayRemoveButton: false);
_featureList.showDefaultBackground = false;
_featureList.headerHeight = 0;
_featureList.elementHeight = EditorGUIUtility.singleLineHeight;
_featureList.elementHeightCallback = featureHeightCallback;
_featureList.drawElementCallback = drawFeatureCallback;
_featureList.onReorderCallback = onReorderFeaturesCallback;
}
_renderingMethod = MultiTypedReferenceUtil.GetReferenceProperty(_multiRenderingMethod);
_supportInfo = _groupProperty.FindPropertyRelative("_supportInfo");
_cachedPropertyList = new List<SerializedProperty>();
_cachedPropertyHeights = new List<float>();
for (int i = 0; i < _featureTable.arraySize; i++) {
var idIndex = _featureTable.GetArrayElementAtIndex(i);
var referenceProp = MultiTypedListUtil.GetReferenceProperty(_multiFeatureList, idIndex);
_cachedPropertyList.Add(referenceProp);
//Make sure to add one line for the label
_cachedPropertyHeights.Add(EditorGUI.GetPropertyHeight(referenceProp) + EditorGUIUtility.singleLineHeight);
}
_renderingMethod = MultiTypedReferenceUtil.GetReferenceProperty(_multiRenderingMethod);
if (_renderingMethodMonoScript == null) {
_renderingMethodMonoScript = AssetDatabase.FindAssets(_renderingMethod.type).
Query().
Where(guid => !string.IsNullOrEmpty(guid)).
Select(guid => AssetDatabase.GUIDToAssetPath(guid)).
Where(path => Path.GetFileNameWithoutExtension(path) == _renderingMethod.type).
Select(path => AssetDatabase.LoadAssetAtPath<MonoScript>(path)).
FirstOrDefault();
}
}
private void drawGroupName() {
var nameProperty = _groupProperty.FindPropertyRelative("_groupName");
EditorGUILayout.PropertyField(nameProperty);
nameProperty.stringValue = nameProperty.stringValue.Trim();
if (string.IsNullOrEmpty(nameProperty.stringValue)) {
nameProperty.stringValue = "MyGroupName";
}
}
private void drawRendererHeader() {
Rect rect = EditorGUILayout.GetControlRect(GUILayout.MaxHeight(EditorGUIUtility.singleLineHeight));
Rect left, right;
rect.SplitHorizontallyWithRight(out left, out right, BUTTON_WIDTH * 2);
if (!EditorApplication.isPlaying && PrefabUtility.GetPrefabType(_renderer) != PrefabType.Prefab) {
var mesher = _renderer.editor.GetSelectedRenderingMethod() as LeapMesherBase;
if (mesher != null) {
Color prevColor = GUI.color;
if (mesher.IsAtlasDirty) {
GUI.color = Color.yellow;
}
Rect middle;
left.SplitHorizontallyWithRight(out left, out middle, REFRESH_WIDTH);
if (GUI.Button(middle, "Refresh Atlas", EditorStyles.miniButtonMid)) {
_serializedObject.ApplyModifiedProperties();
Undo.RecordObject(_renderer, "Refreshed atlas");
EditorUtility.SetDirty(_renderer);
mesher.RebuildAtlas(new ProgressBar());
_renderer.editor.ScheduleRebuild();
_serializedObject.Update();
}
GUI.color = prevColor;
}
}
EditorGUI.LabelField(left, "Renderer", EditorStyles.miniButtonLeft);
using (new EditorGUI.DisabledGroupScope(EditorApplication.isPlaying)) {
if (GUI.Button(right, "v", EditorStyles.miniButtonRight)) {
_addRenderingMethodMenu.ShowAsContext();
}
}
}
private void drawStatsArea() {
using (new EditorGUI.DisabledGroupScope(true)) {
var graphicList = _groupProperty.FindPropertyRelative("_graphics");
int count = graphicList.arraySize;
EditorGUILayout.IntField("Attached Graphic Count", count);
}
}
private void drawSpriteWarning() {
var list = Pool<List<LeapGraphicFeatureBase>>.Spawn();
try {
foreach (var group in _renderer.groups) {
list.AddRange(group.features);
}
SpriteAtlasUtil.ShowInvalidSpriteWarning(list);
} finally {
list.Clear();
Pool<List<LeapGraphicFeatureBase>>.Recycle(list);
}
}
private void drawMonoScript() {
using (new EditorGUI.DisabledGroupScope(true)) {
EditorGUILayout.ObjectField("Rendering Method",
_renderingMethodMonoScript,
typeof(MonoScript),
allowSceneObjects: false);
}
}
private void drawWarningDialogs() {
HashSet<string> shownMessages = Pool<HashSet<string>>.Spawn();
try {
for (int i = 0; i < _cachedPropertyList.Count; i++) {
if (!EditorApplication.isPlaying) {
var supportInfo = _supportInfo.GetArrayElementAtIndex(i);
var supportProperty = supportInfo.FindPropertyRelative("support");
var messageProperty = supportInfo.FindPropertyRelative("message");
if (shownMessages.Contains(messageProperty.stringValue)) {
continue;
}
shownMessages.Add(messageProperty.stringValue);
switch ((SupportType)supportProperty.intValue) {
case SupportType.Warning:
EditorGUILayout.HelpBox(messageProperty.stringValue, MessageType.Warning);
break;
case SupportType.Error:
EditorGUILayout.HelpBox(messageProperty.stringValue, MessageType.Error);
break;
}
}
}
} finally {
shownMessages.Clear();
Pool<HashSet<string>>.Recycle(shownMessages);
}
}
private void drawFeatureHeader() {
Rect rect = EditorGUILayout.GetControlRect(GUILayout.MaxHeight(EditorGUIUtility.singleLineHeight));
Rect left, middle, right;
rect.SplitHorizontallyWithRight(out middle, out right, BUTTON_WIDTH);
middle.SplitHorizontallyWithRight(out left, out middle, BUTTON_WIDTH);
EditorGUI.LabelField(left, "Graphic Features", EditorStyles.miniButtonLeft);
using (new EditorGUI.DisabledGroupScope(EditorApplication.isPlaying)) {
EditorGUI.BeginDisabledGroup(_featureTable.arraySize == 0);
if (GUI.Button(middle, "-", EditorStyles.miniButtonMid) && _featureList.index >= 0) {
_serializedObject.ApplyModifiedProperties();
Undo.RecordObject(_renderer, "Removed Feature");
EditorUtility.SetDirty(_renderer);
_renderer.editor.RemoveFeatureFromSelectedGroup(_featureList.index);
_serializedObject.Update();
init(_groupProperty);
}
EditorGUI.EndDisabledGroup();
if (GUI.Button(right, "+", EditorStyles.miniButtonRight)) {
_addFeatureMenu.ShowAsContext();
}
}
}
// Feature list callbacks
private void drawFeatureHeaderCallback(Rect rect) {
Rect left, right;
rect.SplitHorizontallyWithRight(out left, out right, BUTTON_WIDTH);
EditorGUI.LabelField(left, "Graphic Features", EditorStyles.miniButtonLeft);
if (GUI.Button(right, "+", EditorStyles.miniButtonRight)) {
_addFeatureMenu.ShowAsContext();
}
}
private float featureHeightCallback(int index) {
return _cachedPropertyHeights[index];
}
delegate void Action<T1, T2, T3, T4, T5>(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5);
private void drawFeatureCallback(Rect rect, int index, bool isActive, bool isFocused) {
var featureProperty = _cachedPropertyList[index];
rect = rect.SingleLine();
string featureName = LeapGraphicTagAttribute.GetTagName(featureProperty.type);
int lastIndexOf = featureName.LastIndexOf('/');
if (lastIndexOf >= 0) {
featureName = featureName.Substring(lastIndexOf + 1);
}
GUIContent featureLabel = new GUIContent(featureName);
Color originalColor = GUI.color;
if (!EditorApplication.isPlaying &&
index < _supportInfo.arraySize) {
var supportInfo = _supportInfo.GetArrayElementAtIndex(index);
var supportProperty = supportInfo.FindPropertyRelative("support");
var messageProperty = supportInfo.FindPropertyRelative("message");
switch ((SupportType)supportProperty.intValue) {
case SupportType.Warning:
GUI.color = Color.yellow;
featureLabel.tooltip = messageProperty.stringValue;
break;
case SupportType.Error:
GUI.color = Color.red;
featureLabel.tooltip = messageProperty.stringValue;
break;
}
}
Vector2 size = EditorStyles.label.CalcSize(featureLabel);
Rect labelRect = rect;
labelRect.width = size.x;
GUI.Box(labelRect, "");
EditorGUI.LabelField(labelRect, featureLabel);
GUI.color = originalColor;
rect = rect.NextLine().Indent();
EditorGUI.PropertyField(rect, featureProperty, includeChildren: true);
}
private void onReorderFeaturesCallback(ReorderableList list) {
_renderer.editor.ScheduleRebuild();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using BTCPayServer.Client.Models;
using BTCPayServer.Data;
using BTCPayServer.HostedServices;
using BTCPayServer.Logging;
using BTCPayServer.Models;
using BTCPayServer.Models.InvoicingModels;
using BTCPayServer.Services;
using BTCPayServer.Services.Invoices;
using NBitcoin;
using NBitcoin.DataEncoders;
using NBXplorer.Models;
using StoreData = BTCPayServer.Data.StoreData;
namespace BTCPayServer.Payments.Bitcoin
{
public class BitcoinLikePaymentHandler : PaymentMethodHandlerBase<DerivationSchemeSettings, BTCPayNetwork>
{
readonly ExplorerClientProvider _ExplorerProvider;
private readonly BTCPayNetworkProvider _networkProvider;
private readonly IFeeProviderFactory _FeeRateProviderFactory;
private readonly NBXplorerDashboard _dashboard;
private readonly Services.Wallets.BTCPayWalletProvider _WalletProvider;
private readonly Dictionary<string, string> _bech32Prefix;
public BitcoinLikePaymentHandler(ExplorerClientProvider provider,
BTCPayNetworkProvider networkProvider,
IFeeProviderFactory feeRateProviderFactory,
NBXplorerDashboard dashboard,
Services.Wallets.BTCPayWalletProvider walletProvider)
{
_ExplorerProvider = provider;
_networkProvider = networkProvider;
_FeeRateProviderFactory = feeRateProviderFactory;
_dashboard = dashboard;
_WalletProvider = walletProvider;
_bech32Prefix = networkProvider.GetAll().OfType<BTCPayNetwork>()
.Where(network => network.NBitcoinNetwork?.Consensus?.SupportSegwit is true).ToDictionary(network => network.CryptoCode,
network => Encoders.ASCII.EncodeData(
network.NBitcoinNetwork.GetBech32Encoder(Bech32Type.WITNESS_PUBKEY_ADDRESS, false)
.HumanReadablePart));
}
class Prepare
{
public Task<FeeRate> GetFeeRate;
public Task<FeeRate> GetNetworkFeeRate;
public Task<KeyPathInformation> ReserveAddress;
}
public override void PreparePaymentModel(PaymentModel model, InvoiceResponse invoiceResponse,
StoreBlob storeBlob, IPaymentMethod paymentMethod)
{
var paymentMethodId = paymentMethod.GetId();
var cryptoInfo = invoiceResponse.CryptoInfo.First(o => o.GetpaymentMethodId() == paymentMethodId);
var network = _networkProvider.GetNetwork<BTCPayNetwork>(model.CryptoCode);
model.ShowRecommendedFee = storeBlob.ShowRecommendedFee;
model.FeeRate = ((BitcoinLikeOnChainPaymentMethod)paymentMethod.GetPaymentMethodDetails()).GetFeeRate();
model.PaymentMethodName = GetPaymentMethodName(network);
var lightningFallback = "";
if (model.Activated && network.SupportLightning && storeBlob.OnChainWithLnInvoiceFallback)
{
var lightningInfo = invoiceResponse.CryptoInfo.FirstOrDefault(a =>
a.GetpaymentMethodId() == new PaymentMethodId(model.CryptoCode, PaymentTypes.LightningLike));
if (!string.IsNullOrEmpty(lightningInfo?.PaymentUrls?.BOLT11))
lightningFallback = "&" + lightningInfo.PaymentUrls.BOLT11
.Replace("lightning:", "lightning=", StringComparison.OrdinalIgnoreCase)
.ToUpperInvariant();
}
if (model.Activated)
{
model.InvoiceBitcoinUrl = (cryptoInfo.PaymentUrls?.BIP21 ?? "") + lightningFallback;
model.InvoiceBitcoinUrlQR = (cryptoInfo.PaymentUrls?.BIP21 ?? "") + lightningFallback
.Replace("LIGHTNING=", "lightning=", StringComparison.OrdinalIgnoreCase);
}
else
{
model.InvoiceBitcoinUrl = "";
model.InvoiceBitcoinUrlQR = "";
}
// Most wallets still don't support BITCOIN: schema, so we're leaving this for better days
// Ref: https://github.com/btcpayserver/btcpayserver/pull/2060#issuecomment-723828348
//model.InvoiceBitcoinUrlQR = cryptoInfo.PaymentUrls.BIP21
// .Replace("bitcoin:", "BITCOIN:", StringComparison.OrdinalIgnoreCase)
// We're leading the way in Bitcoin community with adding UPPERCASE Bech32 addresses in QR Code
if (network.CryptoCode.Equals("BTC", StringComparison.InvariantCultureIgnoreCase) && _bech32Prefix.TryGetValue(model.CryptoCode, out var prefix) && model.BtcAddress.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
{
model.InvoiceBitcoinUrlQR = model.InvoiceBitcoinUrlQR.Replace(
$"{network.NBitcoinNetwork.UriScheme}:{model.BtcAddress}", $"{network.NBitcoinNetwork.UriScheme}:{model.BtcAddress.ToUpperInvariant()}",
StringComparison.OrdinalIgnoreCase
);
}
}
public override string GetCryptoImage(PaymentMethodId paymentMethodId)
{
var network = _networkProvider.GetNetwork<BTCPayNetwork>(paymentMethodId.CryptoCode);
return GetCryptoImage(network);
}
private string GetCryptoImage(BTCPayNetworkBase network)
{
return network.CryptoImagePath;
}
public override string GetPaymentMethodName(PaymentMethodId paymentMethodId)
{
var network = _networkProvider.GetNetwork<BTCPayNetwork>(paymentMethodId.CryptoCode);
return GetPaymentMethodName(network);
}
public override IEnumerable<PaymentMethodId> GetSupportedPaymentMethods()
{
return _networkProvider
.GetAll()
.OfType<BTCPayNetwork>()
.Select(network => new PaymentMethodId(network.CryptoCode, PaymentTypes.BTCLike));
}
private string GetPaymentMethodName(BTCPayNetworkBase network)
{
return network.DisplayName;
}
public override object PreparePayment(DerivationSchemeSettings supportedPaymentMethod, StoreData store,
BTCPayNetworkBase network)
{
var storeBlob = store.GetStoreBlob();
return new Prepare()
{
GetFeeRate =
_FeeRateProviderFactory.CreateFeeProvider(network)
.GetFeeRateAsync(storeBlob.RecommendedFeeBlockTarget),
GetNetworkFeeRate = storeBlob.NetworkFeeMode == NetworkFeeMode.Never
? null
: _FeeRateProviderFactory.CreateFeeProvider(network).GetFeeRateAsync(),
ReserveAddress = _WalletProvider.GetWallet(network)
.ReserveAddressAsync(supportedPaymentMethod.AccountDerivation)
};
}
public override PaymentType PaymentType => PaymentTypes.BTCLike;
public override async Task<IPaymentMethodDetails> CreatePaymentMethodDetails(
InvoiceLogs logs,
DerivationSchemeSettings supportedPaymentMethod, PaymentMethod paymentMethod, StoreData store,
BTCPayNetwork network, object preparePaymentObject)
{
if (preparePaymentObject is null)
{
return new BitcoinLikeOnChainPaymentMethod()
{
Activated = false
};
}
if (!_ExplorerProvider.IsAvailable(network))
throw new PaymentMethodUnavailableException($"Full node not available");
var prepare = (Prepare)preparePaymentObject;
var onchainMethod = new BitcoinLikeOnChainPaymentMethod();
var blob = store.GetStoreBlob();
onchainMethod.Activated = true;
// TODO: this needs to be refactored to move this logic into BitcoinLikeOnChainPaymentMethod
// This is likely a constructor code
onchainMethod.NetworkFeeMode = blob.NetworkFeeMode;
onchainMethod.FeeRate = await prepare.GetFeeRate;
switch (onchainMethod.NetworkFeeMode)
{
case NetworkFeeMode.Always:
onchainMethod.NetworkFeeRate = (await prepare.GetNetworkFeeRate);
onchainMethod.NextNetworkFee =
onchainMethod.NetworkFeeRate.GetFee(100); // assume price for 100 bytes
break;
case NetworkFeeMode.Never:
onchainMethod.NetworkFeeRate = FeeRate.Zero;
onchainMethod.NextNetworkFee = Money.Zero;
break;
case NetworkFeeMode.MultiplePaymentsOnly:
onchainMethod.NetworkFeeRate = (await prepare.GetNetworkFeeRate);
onchainMethod.NextNetworkFee = Money.Zero;
break;
}
var reserved = await prepare.ReserveAddress;
if (paymentMethod.ParentEntity.Type != InvoiceType.TopUp)
{
var txOut = network.NBitcoinNetwork.Consensus.ConsensusFactory.CreateTxOut();
txOut.ScriptPubKey = reserved.Address.ScriptPubKey;
var dust = txOut.GetDustThreshold();
var amount = paymentMethod.Calculate().Due;
if (amount < dust)
throw new PaymentMethodUnavailableException("Amount below the dust threshold. For amounts of this size, it is recommended to enable an off-chain (Lightning) payment method");
}
onchainMethod.DepositAddress = reserved.Address.ToString();
onchainMethod.KeyPath = reserved.KeyPath;
onchainMethod.PayjoinEnabled = blob.PayJoinEnabled &&
supportedPaymentMethod
.AccountDerivation.ScriptPubKeyType() != ScriptPubKeyType.Legacy &&
network.SupportPayJoin;
if (onchainMethod.PayjoinEnabled)
{
var prefix = $"{supportedPaymentMethod.PaymentId.ToPrettyString()}:";
var nodeSupport = _dashboard?.Get(network.CryptoCode)?.Status?.BitcoinStatus?.Capabilities
?.CanSupportTransactionCheck is true;
onchainMethod.PayjoinEnabled &= supportedPaymentMethod.IsHotWallet && nodeSupport;
if (!supportedPaymentMethod.IsHotWallet)
logs.Write($"{prefix} Payjoin should have been enabled, but your store is not a hotwallet", InvoiceEventData.EventSeverity.Warning);
if (!nodeSupport)
logs.Write($"{prefix} Payjoin should have been enabled, but your version of NBXplorer or full node does not support it.", InvoiceEventData.EventSeverity.Warning);
if (onchainMethod.PayjoinEnabled)
logs.Write($"{prefix} Payjoin is enabled for this invoice.", InvoiceEventData.EventSeverity.Info);
}
return onchainMethod;
}
}
}
| |
using System;
using System.Globalization;
using System.Text;
using IL2CPU.API;
namespace Cosmos.IL2CPU.IL.CustomImplementations.System
{
[Plug(Target = typeof(sbyte))]
public static class Int8Impl
{
public static string ToString(ref sbyte aThis)
{
bool bNegative = false;
sbyte aValue = aThis;
if (aValue < 0)
{
bNegative = true;
aValue *= -1;
}
return GeneralIntegerImplByUInt64.ToString((UInt64)aValue, bNegative);
}
public static bool TryParse(string s, NumberStyles style, IFormatProvider provider, out sbyte result)
{
// Todo, consider how to implemente style and provider
throw new NotImplementedException();
//return TryParse(s, out result);
}
public static bool TryParse(string s, out sbyte result)
{
bool bCanParse = false;
result = 0;
try
{
result = Parse(s);
bCanParse = true;
}
catch(Exception)
{
// Something wrong
}
return bCanParse;
}
public static sbyte Parse(string s)
{
Int64 result = GeneralIntegerImplByUInt64.ParseSignedInteger(s);
if (result > sbyte.MaxValue || result < sbyte.MinValue)
{
throw new OverflowException();
}
return (sbyte)result;
}
}
[Plug(Target = typeof(byte))]
public static class UInt8Impl
{
public static string ToString(ref byte aThis)
{
byte aValue = aThis;
return GeneralIntegerImplByUInt64.ToString((UInt64)aValue, false);
}
public static bool TryParse(string s, NumberStyles style, IFormatProvider provider, out byte result)
{
// Todo, consider how to implemente style and provider
// Exponent, "1E0", "1e3"...
// Decimal point "1.0", "3.5"
throw new NotImplementedException();
//return TryParse(s, out result);
}
public static bool TryParse(string s, out byte result)
{
bool bCanParse = false;
result = 0;
try
{
result = Parse(s);
bCanParse = true;
}
catch (Exception)
{
// Something wrong
}
return bCanParse;
}
public static byte Parse(string s)
{
UInt64 result = GeneralIntegerImplByUInt64.ParseUnsignedInteger(s);
if (result > byte.MaxValue)
{
throw new OverflowException();
}
return (byte)result;
}
}
[Plug(Target = typeof(short))]
public static class Int16Impl
{
public static string ToString(ref short aThis)
{
bool bNegative = false;
short aValue = aThis;
if (aValue < 0)
{
bNegative = true;
aValue *= -1;
}
return GeneralIntegerImplByUInt64.ToString((UInt64)aValue, bNegative);
}
public static bool TryParse(string s, NumberStyles style, IFormatProvider provider, out short result)
{
// Todo, consider how to implemente style and provider
throw new NotImplementedException();
//return TryParse(s, out result);
}
public static bool TryParse(string s, out short result)
{
bool bCanParse = false;
result = 0;
try
{
result = Parse(s);
bCanParse = true;
}
catch (Exception)
{
// Something wrong
}
return bCanParse;
}
public static short Parse(string s)
{
Int64 result = GeneralIntegerImplByUInt64.ParseSignedInteger(s);
if (result > short.MaxValue || result < short.MinValue)
{
throw new OverflowException();
}
return (short)result;
}
}
[Plug(Target = typeof(ushort))]
public static class UInt16Impl
{
public static string ToString(ref ushort aThis)
{
ushort aValue = aThis;
return GeneralIntegerImplByUInt64.ToString((UInt64)aValue, false);
}
public static bool TryParse(string s, NumberStyles style, IFormatProvider provider, out ushort result)
{
// Todo, consider how to implemente style and provider
throw new NotImplementedException();
//return TryParse(s, out result);
}
public static bool TryParse(string s, out ushort result)
{
bool bCanParse = false;
result = 0;
try
{
result = Parse(s);
bCanParse = true;
}
catch (Exception)
{
// Something wrong
}
return bCanParse;
}
public static ushort Parse(string s)
{
UInt64 result = GeneralIntegerImplByUInt64.ParseUnsignedInteger(s);
if (result > ushort.MaxValue)
{
throw new OverflowException();
}
return (ushort)result;
}
}
[Plug(Target = typeof(int))]
public static class Int32Impl
{
public static string ToString(ref int aThis)
{
bool bNegative = false;
int aValue = aThis;
if (aValue < 0)
{
bNegative = true;
aValue *= -1;
}
return GeneralIntegerImplByUInt64.ToString((UInt64)aValue, bNegative);
}
public static bool TryParse(string s, NumberStyles style, IFormatProvider provider, out short result)
{
// Todo, consider how to implemente style and provider
throw new NotImplementedException();
//return TryParse(s, out result);
}
public static bool TryParse(string s, out int result)
{
bool bCanParse = false;
result = 0;
try
{
result = Parse(s);
bCanParse = true;
}
catch (Exception)
{
// Something wrong
}
return bCanParse;
}
public static int Parse(string s)
{
Int64 result = GeneralIntegerImplByUInt64.ParseSignedInteger(s);
if (result > int.MaxValue || result < int.MinValue)
{
throw new OverflowException();
}
return (int)result;
}
}
[Plug(Target = typeof(uint))]
public static class UInt32Impl
{
public static string ToString(ref uint aThis)
{
uint aValue = aThis;
return GeneralIntegerImplByUInt64.ToString((UInt64)aValue, false);
}
public static bool TryParse(string s, NumberStyles style, IFormatProvider provider, out uint result)
{
// Todo, consider how to implemente style and provider
throw new NotImplementedException();
//return TryParse(s, out result);
}
public static bool TryParse(string s, out uint result)
{
bool bCanParse = false;
result = 0;
try
{
result = Parse(s);
bCanParse = true;
}
catch (Exception)
{
// Something wrong
}
return bCanParse;
}
public static uint Parse(string s)
{
UInt64 result = GeneralIntegerImplByUInt64.ParseUnsignedInteger(s);
if (result > uint.MaxValue)
{
throw new OverflowException();
}
return (uint)result;
}
}
internal static class GeneralIntegerImplByUInt64
{
internal static Int64 ParseSignedInteger(string s)
{
bool bNegative;
Int64 result = (Int64)ParseInteger(s, out bNegative);
if (bNegative)
result *= -1;
return result;
}
internal static UInt64 ParseUnsignedInteger(string s)
{
bool bNegative;
UInt64 result = ParseInteger(s, out bNegative);
if (bNegative && result != 0)
{
throw new OverflowException();
}
return result;
}
/// <summary>
/// ParseInteger
/// Sole algorithm implementation of "integer Parse(string)"
/// </summary>
/// <param name="s"></param>
/// <param name="bNegative"></param>
/// <returns></returns>
private static UInt64 ParseInteger(string s, out bool bNegative)
{
UInt64 result = 0;
int nParseStartPos = 0;
bNegative = false;
if (s.Length >= 1)
{
if (s[0] == '+')
{
nParseStartPos = 1;
}
else if (s[0] == '-')
{
nParseStartPos = 1;
bNegative = true;
}
}
for (int i = nParseStartPos; i < s.Length; i++)
{
sbyte ind = (sbyte)(s[i] - '0');
if (ind < 0 || ind > 9)
{
throw new FormatException("Digit " + s[i] + " not found");
}
result = (result * 10) + (UInt64)ind;
}
return result;
}
/// <summary>
/// ToString
/// Sole algorithm implementation of "string ToString(integer)"
/// </summary>
/// <param name="aValue"></param>
/// <param name="bIsNegative"></param>
/// <returns></returns>
internal static string ToString(UInt64 aValue, bool bIsNegative)
{
char[] xResultChars = new char[21]; // 64 bit UInteger convert to string, with sign symble, max length is 21.
int xCurrentPos = xResultChars.Length - 1;
while (aValue > 0)
{
byte xPos = (byte)(aValue % 10);
aValue /= 10;
xResultChars[xCurrentPos] = (char)('0' + xPos);
xCurrentPos -= 1;
}
if (bIsNegative)
{
xResultChars[xCurrentPos] = '-';
xCurrentPos -= 1;
}
return new String(xResultChars, xCurrentPos + 1, xResultChars.Length - xCurrentPos - 1);
}
}
}
| |
//#define DEBUGREADERS
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using System.Xml;
using System.Globalization;
using ExcelDataReader.Portable.Async;
using ExcelDataReader.Portable.Core;
using ExcelDataReader.Portable.Core.OpenXmlFormat;
using ExcelDataReader.Portable.Data;
using ExcelDataReader.Portable.IO;
using PCLStorage;
namespace ExcelDataReader.Portable
{
public class ExcelOpenXmlReader : IExcelDataReader
{
private readonly IFileSystem fileSystem;
private readonly IFileHelper fileHelper;
private readonly IDataHelper dataHelper;
#region Members
private XlsxWorkbook _workbook;
private bool _isValid;
private bool _isClosed;
private bool _isFirstRead;
private string _exceptionMessage;
private int _depth;
private int _resultIndex;
private int _emptyRowCount;
private ZipWorker _zipWorker;
private XmlReader _xmlReader;
private Stream _sheetStream;
private object[] _cellsValues;
private object[] _savedCellsValues;
private bool disposed;
private bool _isFirstRowAsColumnNames;
private const string COLUMN = "Column";
private string instanceId = Guid.NewGuid().ToString();
private List<int> _defaultDateTimeStyles;
private string _namespaceUri;
#endregion
public ExcelOpenXmlReader(IFileSystem fileSystem, IFileHelper fileHelper, IDataHelper dataHelper)
{
this.fileSystem = fileSystem;
this.fileHelper = fileHelper;
this.dataHelper = dataHelper;
_isValid = true;
_isFirstRead = true;
_defaultDateTimeStyles = new List<int>(new int[]
{
14, 15, 16, 17, 18, 19, 20, 21, 22, 45, 46, 47
});
}
private async void ReadGlobals()
{
_workbook = new XlsxWorkbook(
await _zipWorker.GetWorkbookStream(),
await _zipWorker.GetWorkbookRelsStream(),
await _zipWorker.GetSharedStringsStream(),
await _zipWorker.GetStylesStream());
CheckDateTimeNumFmts(_workbook.Styles.NumFmts);
}
private void CheckDateTimeNumFmts(List<XlsxNumFmt> list)
{
if (list.Count == 0) return;
foreach (XlsxNumFmt numFmt in list)
{
if (string.IsNullOrEmpty(numFmt.FormatCode)) continue;
string fc = numFmt.FormatCode.ToLower();
int pos;
while ((pos = fc.IndexOf('"')) > 0)
{
int endPos = fc.IndexOf('"', pos + 1);
if (endPos > 0) fc = fc.Remove(pos, endPos - pos + 1);
}
//it should only detect it as a date if it contains
//dd mm mmm yy yyyy
//h hh ss
//AM PM
//and only if these appear as "words" so either contained in [ ]
//or delimted in someway
//updated to not detect as date if format contains a #
var formatReader = new FormatReader() {FormatString = fc};
if (formatReader.IsDateFormatString())
{
_defaultDateTimeStyles.Add(numFmt.Id);
}
}
}
private async void ReadSheetGlobals(XlsxWorksheet sheet)
{
if (_xmlReader != null) _xmlReader.Dispose();
if (_sheetStream != null) _sheetStream.Dispose();
_sheetStream = await _zipWorker.GetWorksheetStream(sheet.Path);
if (null == _sheetStream) return;
_xmlReader = XmlReader.Create(_sheetStream);
//count rows and cols in case there is no dimension elements
int rows = 0;
int cols = 0;
_namespaceUri = null;
int biggestColumn = 0; //used when no col elements and no dimension
while (_xmlReader.Read())
{
if (_xmlReader.NodeType == XmlNodeType.Element && _xmlReader.LocalName == XlsxWorksheet.N_worksheet)
{
//grab the namespaceuri from the worksheet element
_namespaceUri = _xmlReader.NamespaceURI;
}
if (_xmlReader.NodeType == XmlNodeType.Element && _xmlReader.LocalName == XlsxWorksheet.N_dimension)
{
string dimValue = _xmlReader.GetAttribute(XlsxWorksheet.A_ref);
sheet.Dimension = new XlsxDimension(dimValue);
break;
}
//removed: Do not use col to work out number of columns as this is really for defining formatting, so may not contain all columns
//if (_xmlReader.NodeType == XmlNodeType.Element && _xmlReader.LocalName == XlsxWorksheet.N_col)
// cols++;
if (_xmlReader.NodeType == XmlNodeType.Element && _xmlReader.LocalName == XlsxWorksheet.N_row)
rows++;
//check cells so we can find size of sheet if can't work it out from dimension or col elements (dimension should have been set before the cells if it was available)
//ditto for cols
if (sheet.Dimension == null && cols == 0 && _xmlReader.NodeType == XmlNodeType.Element && _xmlReader.LocalName == XlsxWorksheet.N_c)
{
var refAttribute = _xmlReader.GetAttribute(XlsxWorksheet.A_r);
if (refAttribute != null)
{
var thisRef = ReferenceHelper.ReferenceToColumnAndRow(refAttribute);
if (thisRef[1] > biggestColumn)
biggestColumn = thisRef[1];
}
}
}
//if we didn't get a dimension element then use the calculated rows/cols to create it
if (sheet.Dimension == null)
{
if (cols == 0)
cols = biggestColumn;
if (rows == 0 || cols == 0)
{
sheet.IsEmpty = true;
return;
}
sheet.Dimension = new XlsxDimension(rows, cols);
//we need to reset our position to sheet data
_xmlReader.Dispose();
_sheetStream.Dispose();
_sheetStream = await _zipWorker.GetWorksheetStream(sheet.Path);
_xmlReader = XmlReader.Create(_sheetStream);
}
//read up to the sheetData element. if this element is empty then there aren't any rows and we need to null out dimension
_xmlReader.ReadToFollowing(XlsxWorksheet.N_sheetData, _namespaceUri);
if (_xmlReader.IsEmptyElement)
{
sheet.IsEmpty = true;
}
}
private bool ReadSheetRow(XlsxWorksheet sheet)
{
if (null == _xmlReader) return false;
if (_emptyRowCount != 0)
{
_cellsValues = new object[sheet.ColumnsCount];
_emptyRowCount--;
_depth++;
return true;
}
if (_savedCellsValues != null)
{
_cellsValues = _savedCellsValues;
_savedCellsValues = null;
_depth++;
return true;
}
if ((_xmlReader.NodeType == XmlNodeType.Element && _xmlReader.LocalName == XlsxWorksheet.N_row) ||
_xmlReader.ReadToFollowing(XlsxWorksheet.N_row, _namespaceUri))
{
_cellsValues = new object[sheet.ColumnsCount];
int rowIndex = int.Parse(_xmlReader.GetAttribute(XlsxWorksheet.A_r));
if (rowIndex != (_depth + 1))
if (rowIndex != (_depth + 1))
{
_emptyRowCount = rowIndex - _depth - 1;
}
bool hasValue = false;
string a_s = String.Empty;
string a_t = String.Empty;
string a_r = String.Empty;
int col = 0;
int row = 0;
while (_xmlReader.Read())
{
if (_xmlReader.Depth == 2) break;
if (_xmlReader.NodeType == XmlNodeType.Element)
{
hasValue = false;
if (_xmlReader.LocalName == XlsxWorksheet.N_c)
{
a_s = _xmlReader.GetAttribute(XlsxWorksheet.A_s);
a_t = _xmlReader.GetAttribute(XlsxWorksheet.A_t);
a_r = _xmlReader.GetAttribute(XlsxWorksheet.A_r);
XlsxDimension.XlsxDim(a_r, out col, out row);
}
else if (_xmlReader.LocalName == XlsxWorksheet.N_v || _xmlReader.LocalName == XlsxWorksheet.N_t)
{
hasValue = true;
}
}
if (_xmlReader.NodeType == XmlNodeType.Text && hasValue)
{
double number;
object o = _xmlReader.Value;
var style = NumberStyles.Any;
var culture = CultureInfo.InvariantCulture;
if (double.TryParse(o.ToString(), style, culture, out number))
o = number;
if (null != a_t && a_t == XlsxWorksheet.A_s) //if string
{
o = Helpers.ConvertEscapeChars(_workbook.SST[int.Parse(o.ToString())]);
} // Requested change 4: missing (it appears that if should be else if)
else if (null != a_t && a_t == XlsxWorksheet.N_inlineStr) //if string inline
{
o = Helpers.ConvertEscapeChars(o.ToString());
}
else if (a_t == "b") //boolean
{
o = _xmlReader.Value == "1";
}
else if (null != a_s) //if something else
{
XlsxXf xf = _workbook.Styles.CellXfs[int.Parse(a_s)];
if (o != null && o.ToString() != string.Empty && IsDateTimeStyle(xf.NumFmtId))
o = Helpers.ConvertFromOATime(number);
else if (xf.NumFmtId == 49)
o = o.ToString();
}
if (col - 1 < _cellsValues.Length)
_cellsValues[col - 1] = o;
}
}
if (_emptyRowCount > 0)
{
_savedCellsValues = _cellsValues;
return ReadSheetRow(sheet);
}
_depth++;
return true;
}
_xmlReader.Dispose();
if (_sheetStream != null) _sheetStream.Dispose();
return false;
}
private bool InitializeSheetRead()
{
if (ResultsCount <= 0) return false;
ReadSheetGlobals(_workbook.Sheets[_resultIndex]);
if (_workbook.Sheets[_resultIndex].Dimension == null) return false;
_isFirstRead = false;
_depth = 0;
_emptyRowCount = 0;
return true;
}
private bool IsDateTimeStyle(int styleId)
{
return _defaultDateTimeStyles.Contains(styleId);
}
#region IExcelDataReader Members
public void Initialize(System.IO.Stream fileStream)
{
_zipWorker = new ZipWorker(fileSystem, fileHelper);
AsyncHelper.RunSync(() => _zipWorker.Extract(fileStream));
if (!_zipWorker.IsValid)
{
_isValid = false;
_exceptionMessage = _zipWorker.ExceptionMessage;
Close();
return;
}
ReadGlobals();
}
public void LoadDataSet(IDatasetHelper datasetHelper)
{
LoadDataSet(datasetHelper, true);
}
public void LoadDataSet(IDatasetHelper datasetHelper, bool convertOADateTime)
{
if (!_isValid)
{
datasetHelper.IsValid = false;
}
datasetHelper.IsValid = true;
datasetHelper.CreateNew();
for (int ind = 0; ind < _workbook.Sheets.Count; ind++)
{
datasetHelper.CreateNewTable(_workbook.Sheets[ind].Name);
datasetHelper.AddExtendedPropertyToTable("visiblestate", _workbook.Sheets[ind].VisibleState);
ReadSheetGlobals(_workbook.Sheets[ind]);
if (_workbook.Sheets[ind].Dimension == null) continue;
_depth = 0;
_emptyRowCount = 0;
//DataTable columns
//todo: all very similar to sheet load in binary reader
if (!_isFirstRowAsColumnNames)
{
for (int i = 0; i < _workbook.Sheets[ind].ColumnsCount; i++)
{
datasetHelper.AddColumn(null);
}
}
else if (ReadSheetRow(_workbook.Sheets[ind]))
{
for (int index = 0; index < _cellsValues.Length; index++)
{
if (_cellsValues[index] != null && _cellsValues[index].ToString().Length > 0)
datasetHelper.AddColumn(_cellsValues[index].ToString());
else
datasetHelper.AddColumn(string.Concat(COLUMN, index));
}
}
else continue;
datasetHelper.BeginLoadData();
var hasRows = false;
while (ReadSheetRow(_workbook.Sheets[ind]))
{
hasRows = true;
datasetHelper.AddRow(_cellsValues);
}
if (hasRows)
datasetHelper.EndLoadTable();
}
datasetHelper.DatasetLoadComplete();
}
public bool IsFirstRowAsColumnNames
{
get
{
return _isFirstRowAsColumnNames;
}
set
{
_isFirstRowAsColumnNames = value;
}
}
public bool ConvertOaDate { get; set; }
public ReadOption ReadOption { get; set; }
public bool IsValid
{
get { return _isValid; }
}
public string ExceptionMessage
{
get { return _exceptionMessage; }
}
public string Name
{
get
{
return (_resultIndex >= 0 && _resultIndex < ResultsCount) ? _workbook.Sheets[_resultIndex].Name : null;
}
}
public string VisibleState
{
get
{
return (_resultIndex >= 0 && _resultIndex < ResultsCount) ? _workbook.Sheets[_resultIndex].VisibleState : null;
}
}
public void Close()
{
_isClosed = true;
if (_xmlReader != null) _xmlReader.Dispose();
if (_sheetStream != null) _sheetStream.Dispose();
if (_zipWorker != null) _zipWorker.Dispose();
}
public int Depth
{
get { return _depth; }
}
public int ResultsCount
{
get { return _workbook == null ? -1 : _workbook.Sheets.Count; }
}
public bool IsClosed
{
get { return _isClosed; }
}
public bool NextResult()
{
if (_resultIndex >= (this.ResultsCount - 1)) return false;
_resultIndex++;
_isFirstRead = true;
_savedCellsValues = null;
return true;
}
public bool Read()
{
if (!_isValid) return false;
if (_isFirstRead && !InitializeSheetRead())
{
return false;
}
return ReadSheetRow(_workbook.Sheets[_resultIndex]);
}
public int FieldCount
{
get { return (_resultIndex >= 0 && _resultIndex < ResultsCount) ? _workbook.Sheets[_resultIndex].ColumnsCount : -1; }
}
public bool GetBoolean(int i)
{
if (IsDBNull(i)) return false;
return Boolean.Parse(_cellsValues[i].ToString());
}
public DateTime GetDateTime(int i)
{
if (IsDBNull(i)) return DateTime.MinValue;
try
{
return (DateTime)_cellsValues[i];
}
catch (InvalidCastException)
{
return DateTime.MinValue;
}
}
public decimal GetDecimal(int i)
{
if (IsDBNull(i)) return decimal.MinValue;
return decimal.Parse(_cellsValues[i].ToString());
}
public double GetDouble(int i)
{
if (IsDBNull(i)) return double.MinValue;
return double.Parse(_cellsValues[i].ToString());
}
public float GetFloat(int i)
{
if (IsDBNull(i)) return float.MinValue;
return float.Parse(_cellsValues[i].ToString());
}
public short GetInt16(int i)
{
if (IsDBNull(i)) return short.MinValue;
return short.Parse(_cellsValues[i].ToString());
}
public int GetInt32(int i)
{
if (IsDBNull(i)) return int.MinValue;
return int.Parse(_cellsValues[i].ToString());
}
public long GetInt64(int i)
{
if (IsDBNull(i)) return long.MinValue;
return long.Parse(_cellsValues[i].ToString());
}
public string GetString(int i)
{
if (IsDBNull(i)) return null;
return _cellsValues[i].ToString();
}
public object GetValue(int i)
{
return _cellsValues[i];
}
public bool IsDBNull(int i)
{
return (null == _cellsValues[i]) || (dataHelper.IsDBNull(_cellsValues[i]));
}
public object this[int i]
{
get { return _cellsValues[i]; }
}
#endregion
#region IDisposable Members
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
// Check to see if Dispose has already been called.
if (!this.disposed)
{
if (disposing)
{
if (_xmlReader != null) ((IDisposable) _xmlReader).Dispose();
if (_sheetStream != null) _sheetStream.Dispose();
if (_zipWorker != null) _zipWorker.Dispose();
}
_zipWorker = null;
_xmlReader = null;
_sheetStream = null;
_workbook = null;
_cellsValues = null;
_savedCellsValues = null;
disposed = true;
}
}
~ExcelOpenXmlReader()
{
Dispose(false);
}
#endregion
#region Not Supported IDataReader Members
public int RecordsAffected
{
get { throw new NotSupportedException(); }
}
#endregion
#region Not Supported IDataRecord Members
public byte GetByte(int i)
{
throw new NotSupportedException();
}
public long GetBytes(int i, long fieldOffset, byte[] buffer, int bufferoffset, int length)
{
throw new NotSupportedException();
}
public char GetChar(int i)
{
throw new NotSupportedException();
}
public long GetChars(int i, long fieldoffset, char[] buffer, int bufferoffset, int length)
{
throw new NotSupportedException();
}
public IDataReader GetData(int i)
{
throw new NotSupportedException();
}
public string GetDataTypeName(int i)
{
throw new NotSupportedException();
}
public Type GetFieldType(int i)
{
throw new NotSupportedException();
}
public Guid GetGuid(int i)
{
throw new NotSupportedException();
}
public string GetName(int i)
{
throw new NotSupportedException();
}
public int GetOrdinal(string name)
{
throw new NotSupportedException();
}
public int GetValues(object[] values)
{
throw new NotSupportedException();
}
public object this[string name]
{
get { throw new NotSupportedException(); }
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
namespace System.Drawing.Html
{
public class HtmlTag
{
#region Fields
private string _tagName;
private bool _isClosing;
private Dictionary<string, string> _attributes;
#endregion
#region Ctor
private HtmlTag()
{
_attributes = new Dictionary<string, string>();
}
public HtmlTag(string tag)
: this()
{
tag = tag.Substring(1, tag.Length - 2);
int spaceIndex = tag.IndexOf(" ");
//Extract tag name
if (spaceIndex < 0)
{
_tagName = tag;
}
else
{
_tagName = tag.Substring(0, spaceIndex);
}
//Check if is end tag
if (_tagName.StartsWith("/"))
{
_isClosing = true;
_tagName = _tagName.Substring(1);
}
_tagName = _tagName.ToLower();
//Extract attributes
MatchCollection atts = Parser.Match(Parser.HmlTagAttributes, tag);
foreach (Match att in atts)
{
//Extract attribute and value
string[] chunks = att.Value.Split('=');
if (chunks.Length == 1)
{
if(!Attributes.ContainsKey(chunks[0]))
Attributes.Add(chunks[0].ToLower(), string.Empty);
}
else if (chunks.Length == 2)
{
string attname = chunks[0].Trim();
string attvalue = chunks[1].Trim();
if (attvalue.StartsWith("\"") && attvalue.EndsWith("\"") && attvalue.Length > 2)
{
attvalue = attvalue.Substring(1, attvalue.Length - 2);
}
if (!Attributes.ContainsKey(attname))
Attributes.Add(attname, attvalue);
}
}
}
#endregion
#region Props
/// <summary>
/// Gets the dictionary of attributes in the tag
/// </summary>
public Dictionary<string, string> Attributes
{
get { return _attributes; }
}
/// <summary>
/// Gets the name of this tag
/// </summary>
public string TagName
{
get { return _tagName; }
}
/// <summary>
/// Gets if the tag is actually a closing tag
/// </summary>
public bool IsClosing
{
get { return _isClosing; }
}
/// <summary>
/// Gets if the tag is single placed; in other words it doesn't need a closing tag;
/// e.g. <br>
/// </summary>
public bool IsSingle
{
get
{
return TagName.StartsWith("!")
|| (new List<string>(
new string[]{
"area", "base", "basefont", "br", "col",
"frame", "hr", "img", "input", "isindex",
"link", "meta", "param"
}
)).Contains(TagName)
;
}
}
internal void TranslateAttributes(CssBox box)
{
string t = TagName.ToUpper();
foreach (string att in Attributes.Keys)
{
string value = Attributes[att];
switch (att)
{
case HtmlConstants.align:
if (value == HtmlConstants.left || value == HtmlConstants.center || value == HtmlConstants.right || value == HtmlConstants.justify)
box.TextAlign = value;
else
box.VerticalAlign = value;
break;
case HtmlConstants.background:
box.BackgroundImage = value;
break;
case HtmlConstants.bgcolor:
box.BackgroundColor = value;
break;
case HtmlConstants.border:
box.BorderWidth = TranslateLength(value);
if (t == HtmlConstants.TABLE)
{
ApplyTableBorder(box, value);
}
else
{
box.BorderStyle = CssConstants.Solid;
}
break;
case HtmlConstants.bordercolor:
box.BorderColor = value;
break;
case HtmlConstants.cellspacing:
box.BorderSpacing = TranslateLength(value);
break;
case HtmlConstants.cellpadding:
ApplyTablePadding(box, value);
break;
case HtmlConstants.color:
box.Color = value;
break;
case HtmlConstants.dir:
box.Direction = value;
break;
case HtmlConstants.face:
box.FontFamily = value;
break;
case HtmlConstants.height:
box.Height = TranslateLength(value);
break;
case HtmlConstants.hspace:
box.MarginRight = box.MarginLeft = TranslateLength(value);
break;
case HtmlConstants.nowrap:
box.WhiteSpace = CssConstants.Nowrap;
break;
case HtmlConstants.size:
if (t == HtmlConstants.HR)
box.Height = TranslateLength(value);
break;
case HtmlConstants.valign:
box.VerticalAlign = value;
break;
case HtmlConstants.vspace:
box.MarginTop = box.MarginBottom = TranslateLength(value);
break;
case HtmlConstants.width:
box.Width = TranslateLength(value);
break;
}
}
}
#endregion
#region Methods
/// <summary>
/// Converts an HTML length into a Css length
/// </summary>
/// <param name="htmlLength"></param>
/// <returns></returns>
private string TranslateLength(string htmlLength)
{
CssLength len = new CssLength(htmlLength);
if (len.HasError)
{
return htmlLength + "px";
}
return htmlLength;
}
/// <summary>
/// Cascades to the TD's the border spacified in the TABLE tag.
/// </summary>
/// <param name="table"></param>
/// <param name="border"></param>
private void ApplyTableBorder(CssBox table, string border)
{
foreach (CssBox box in table.Boxes)
{
foreach (CssBox cell in box.Boxes)
{
cell.BorderWidth = TranslateLength(border);
}
}
}
/// <summary>
/// Cascades to the TD's the border spacified in the TABLE tag.
/// </summary>
/// <param name="table"></param>
/// <param name="border"></param>
private void ApplyTablePadding(CssBox table, string padding)
{
foreach (CssBox box in table.Boxes)
{
foreach (CssBox cell in box.Boxes)
{
cell.Padding = TranslateLength(padding);
}
}
}
/// <summary>
/// Gets a boolean indicating if the attribute list has the specified attribute
/// </summary>
/// <param name="attribute"></param>
/// <returns></returns>
public bool HasAttribute(string attribute)
{
return Attributes.ContainsKey(attribute);
}
public override string ToString()
{
return string.Format("<{1}{0}>", TagName, IsClosing ? "/" : string.Empty);
}
#endregion
}
}
| |
// **********************************************************************
//
// Copyright (c) 2003-2013 ZeroC, Inc. All rights reserved.
//
// This copy of Ice is licensed to you under the terms described in the
// ICE_LICENSE file included in this distribution.
//
// **********************************************************************
//
// Ice version 3.5.1
//
// <auto-generated>
//
// Generated from file `Example.ice'
//
// Warning: do not edit this file.
//
// </auto-generated>
//
using _System = global::System;
using _Microsoft = global::Microsoft;
#pragma warning disable 1591
namespace IceCompactId
{
}
namespace Example
{
[_System.Runtime.InteropServices.ComVisible(false)]
[_System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704")]
[_System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707")]
[_System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709")]
[_System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710")]
[_System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1711")]
[_System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1715")]
[_System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1716")]
[_System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1720")]
[_System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1722")]
[_System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1724")]
public partial interface Converter : Ice.Object, ConverterOperations_, ConverterOperationsNC_
{
}
}
namespace Example
{
[_System.CodeDom.Compiler.GeneratedCodeAttribute("slice2cs", "3.5.1")]
public delegate void Callback_Converter_toUpper(string ret__);
}
namespace Example
{
[_System.CodeDom.Compiler.GeneratedCodeAttribute("slice2cs", "3.5.1")]
public interface ConverterPrx : Ice.ObjectPrx
{
string toUpper(string s);
string toUpper(string s, _System.Collections.Generic.Dictionary<string, string> context__);
Ice.AsyncResult<Example.Callback_Converter_toUpper> begin_toUpper(string s);
Ice.AsyncResult<Example.Callback_Converter_toUpper> begin_toUpper(string s, _System.Collections.Generic.Dictionary<string, string> ctx__);
Ice.AsyncResult begin_toUpper(string s, Ice.AsyncCallback cb__, object cookie__);
Ice.AsyncResult begin_toUpper(string s, _System.Collections.Generic.Dictionary<string, string> ctx__, Ice.AsyncCallback cb__, object cookie__);
string end_toUpper(Ice.AsyncResult r__);
}
}
namespace Example
{
[_System.CodeDom.Compiler.GeneratedCodeAttribute("slice2cs", "3.5.1")]
public interface ConverterOperations_
{
string toUpper(string s, Ice.Current current__);
}
[_System.CodeDom.Compiler.GeneratedCodeAttribute("slice2cs", "3.5.1")]
public interface ConverterOperationsNC_
{
string toUpper(string s);
}
}
namespace Example
{
[_System.Runtime.InteropServices.ComVisible(false)]
[_System.CodeDom.Compiler.GeneratedCodeAttribute("slice2cs", "3.5.1")]
public sealed class ConverterPrxHelper : Ice.ObjectPrxHelperBase, ConverterPrx
{
#region Synchronous operations
public string toUpper(string s)
{
return toUpper(s, null, false);
}
public string toUpper(string s, _System.Collections.Generic.Dictionary<string, string> context__)
{
return toUpper(s, context__, true);
}
private string toUpper(string s, _System.Collections.Generic.Dictionary<string, string> context__, bool explicitContext__)
{
if(explicitContext__ && context__ == null)
{
context__ = emptyContext_;
}
Ice.Instrumentation.InvocationObserver observer__ = IceInternal.ObserverHelper.get(this, __toUpper_name, context__);
int cnt__ = 0;
try
{
while(true)
{
Ice.ObjectDel_ delBase__ = null;
try
{
checkTwowayOnly__(__toUpper_name);
delBase__ = getDelegate__(false);
ConverterDel_ del__ = (ConverterDel_)delBase__;
return del__.toUpper(s, context__, observer__);
}
catch(IceInternal.LocalExceptionWrapper ex__)
{
handleExceptionWrapper__(delBase__, ex__, observer__);
}
catch(Ice.LocalException ex__)
{
handleException__(delBase__, ex__, true, ref cnt__, observer__);
}
}
}
finally
{
if(observer__ != null)
{
observer__.detach();
}
}
}
#endregion
#region Asynchronous operations
public Ice.AsyncResult<Example.Callback_Converter_toUpper> begin_toUpper(string s)
{
return begin_toUpper(s, null, false, null, null);
}
public Ice.AsyncResult<Example.Callback_Converter_toUpper> begin_toUpper(string s, _System.Collections.Generic.Dictionary<string, string> ctx__)
{
return begin_toUpper(s, ctx__, true, null, null);
}
public Ice.AsyncResult begin_toUpper(string s, Ice.AsyncCallback cb__, object cookie__)
{
return begin_toUpper(s, null, false, cb__, cookie__);
}
public Ice.AsyncResult begin_toUpper(string s, _System.Collections.Generic.Dictionary<string, string> ctx__, Ice.AsyncCallback cb__, object cookie__)
{
return begin_toUpper(s, ctx__, true, cb__, cookie__);
}
private const string __toUpper_name = "toUpper";
public string end_toUpper(Ice.AsyncResult r__)
{
IceInternal.OutgoingAsync outAsync__ = (IceInternal.OutgoingAsync)r__;
IceInternal.OutgoingAsync.check__(outAsync__, this, __toUpper_name);
bool ok__ = outAsync__.wait__();
try
{
if(!ok__)
{
try
{
outAsync__.throwUserException__();
}
catch(Ice.UserException ex__)
{
throw new Ice.UnknownUserException(ex__.ice_name(), ex__);
}
}
string ret__;
IceInternal.BasicStream is__ = outAsync__.startReadParams__();
ret__ = is__.readString();
outAsync__.endReadParams__();
return ret__;
}
catch(Ice.LocalException ex)
{
Ice.Instrumentation.InvocationObserver obsv__ = outAsync__.getObserver__();
if(obsv__ != null)
{
obsv__.failed(ex.ice_name());
}
throw ex;
}
}
private Ice.AsyncResult<Example.Callback_Converter_toUpper> begin_toUpper(string s, _System.Collections.Generic.Dictionary<string, string> ctx__, bool explicitContext__, Ice.AsyncCallback cb__, object cookie__)
{
checkAsyncTwowayOnly__(__toUpper_name);
IceInternal.TwowayOutgoingAsync<Example.Callback_Converter_toUpper> result__ = new IceInternal.TwowayOutgoingAsync<Example.Callback_Converter_toUpper>(this, __toUpper_name, toUpper_completed__, cookie__);
if(cb__ != null)
{
result__.whenCompletedWithAsyncCallback(cb__);
}
try
{
result__.prepare__(__toUpper_name, Ice.OperationMode.Normal, ctx__, explicitContext__);
IceInternal.BasicStream os__ = result__.startWriteParams__(Ice.FormatType.DefaultFormat);
os__.writeString(s);
result__.endWriteParams__();
result__.send__(true);
}
catch(Ice.LocalException ex__)
{
result__.exceptionAsync__(ex__);
}
return result__;
}
private void toUpper_completed__(Ice.AsyncResult r__, Example.Callback_Converter_toUpper cb__, Ice.ExceptionCallback excb__)
{
string ret__;
try
{
ret__ = end_toUpper(r__);
}
catch(Ice.Exception ex__)
{
if(excb__ != null)
{
excb__(ex__);
}
return;
}
if(cb__ != null)
{
cb__(ret__);
}
}
#endregion
#region Checked and unchecked cast operations
public static ConverterPrx checkedCast(Ice.ObjectPrx b)
{
if(b == null)
{
return null;
}
ConverterPrx r = b as ConverterPrx;
if((r == null) && b.ice_isA(ice_staticId()))
{
ConverterPrxHelper h = new ConverterPrxHelper();
h.copyFrom__(b);
r = h;
}
return r;
}
public static ConverterPrx checkedCast(Ice.ObjectPrx b, _System.Collections.Generic.Dictionary<string, string> ctx)
{
if(b == null)
{
return null;
}
ConverterPrx r = b as ConverterPrx;
if((r == null) && b.ice_isA(ice_staticId(), ctx))
{
ConverterPrxHelper h = new ConverterPrxHelper();
h.copyFrom__(b);
r = h;
}
return r;
}
public static ConverterPrx checkedCast(Ice.ObjectPrx b, string f)
{
if(b == null)
{
return null;
}
Ice.ObjectPrx bb = b.ice_facet(f);
try
{
if(bb.ice_isA(ice_staticId()))
{
ConverterPrxHelper h = new ConverterPrxHelper();
h.copyFrom__(bb);
return h;
}
}
catch(Ice.FacetNotExistException)
{
}
return null;
}
public static ConverterPrx checkedCast(Ice.ObjectPrx b, string f, _System.Collections.Generic.Dictionary<string, string> ctx)
{
if(b == null)
{
return null;
}
Ice.ObjectPrx bb = b.ice_facet(f);
try
{
if(bb.ice_isA(ice_staticId(), ctx))
{
ConverterPrxHelper h = new ConverterPrxHelper();
h.copyFrom__(bb);
return h;
}
}
catch(Ice.FacetNotExistException)
{
}
return null;
}
public static ConverterPrx uncheckedCast(Ice.ObjectPrx b)
{
if(b == null)
{
return null;
}
ConverterPrx r = b as ConverterPrx;
if(r == null)
{
ConverterPrxHelper h = new ConverterPrxHelper();
h.copyFrom__(b);
r = h;
}
return r;
}
public static ConverterPrx uncheckedCast(Ice.ObjectPrx b, string f)
{
if(b == null)
{
return null;
}
Ice.ObjectPrx bb = b.ice_facet(f);
ConverterPrxHelper h = new ConverterPrxHelper();
h.copyFrom__(bb);
return h;
}
public static readonly string[] ids__ =
{
"::Example::Converter",
"::Ice::Object"
};
public static string ice_staticId()
{
return ids__[0];
}
#endregion
#region Marshaling support
protected override Ice.ObjectDelM_ createDelegateM__()
{
return new ConverterDelM_();
}
protected override Ice.ObjectDelD_ createDelegateD__()
{
return new ConverterDelD_();
}
public static void write__(IceInternal.BasicStream os__, ConverterPrx v__)
{
os__.writeProxy(v__);
}
public static ConverterPrx read__(IceInternal.BasicStream is__)
{
Ice.ObjectPrx proxy = is__.readProxy();
if(proxy != null)
{
ConverterPrxHelper result = new ConverterPrxHelper();
result.copyFrom__(proxy);
return result;
}
return null;
}
#endregion
}
}
namespace Example
{
[_System.CodeDom.Compiler.GeneratedCodeAttribute("slice2cs", "3.5.1")]
public interface ConverterDel_ : Ice.ObjectDel_
{
string toUpper(string s, _System.Collections.Generic.Dictionary<string, string> context__, Ice.Instrumentation.InvocationObserver observer__);
}
}
namespace Example
{
[_System.Runtime.InteropServices.ComVisible(false)]
[_System.CodeDom.Compiler.GeneratedCodeAttribute("slice2cs", "3.5.1")]
public sealed class ConverterDelM_ : Ice.ObjectDelM_, ConverterDel_
{
public string toUpper(string s, _System.Collections.Generic.Dictionary<string, string> context__, Ice.Instrumentation.InvocationObserver observer__)
{
IceInternal.Outgoing og__ = handler__.getOutgoing("toUpper", Ice.OperationMode.Normal, context__, observer__);
try
{
try
{
IceInternal.BasicStream os__ = og__.startWriteParams(Ice.FormatType.DefaultFormat);
os__.writeString(s);
og__.endWriteParams();
}
catch(Ice.LocalException ex__)
{
og__.abort(ex__);
}
bool ok__ = og__.invoke();
try
{
if(!ok__)
{
try
{
og__.throwUserException();
}
catch(Ice.UserException ex__)
{
throw new Ice.UnknownUserException(ex__.ice_name(), ex__);
}
}
IceInternal.BasicStream is__ = og__.startReadParams();
string ret__;
ret__ = is__.readString();
og__.endReadParams();
return ret__;
}
catch(Ice.LocalException ex__)
{
throw new IceInternal.LocalExceptionWrapper(ex__, false);
}
}
finally
{
handler__.reclaimOutgoing(og__);
}
}
}
}
namespace Example
{
[_System.Runtime.InteropServices.ComVisible(false)]
[_System.CodeDom.Compiler.GeneratedCodeAttribute("slice2cs", "3.5.1")]
public sealed class ConverterDelD_ : Ice.ObjectDelD_, ConverterDel_
{
[_System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031")]
public string toUpper(string s, _System.Collections.Generic.Dictionary<string, string> context__, Ice.Instrumentation.InvocationObserver observer__)
{
Ice.Current current__ = new Ice.Current();
initCurrent__(ref current__, "toUpper", Ice.OperationMode.Normal, context__);
string result__ = null;
IceInternal.Direct.RunDelegate run__ = delegate(Ice.Object obj__)
{
Converter servant__ = null;
try
{
servant__ = (Converter)obj__;
}
catch(_System.InvalidCastException)
{
throw new Ice.OperationNotExistException(current__.id, current__.facet, current__.operation);
}
result__ = servant__.toUpper(s, current__);
return Ice.DispatchStatus.DispatchOK;
};
IceInternal.Direct direct__ = null;
try
{
direct__ = new IceInternal.Direct(current__, run__);
try
{
Ice.DispatchStatus status__ = direct__.getServant().collocDispatch__(direct__);
_System.Diagnostics.Debug.Assert(status__ == Ice.DispatchStatus.DispatchOK);
}
finally
{
direct__.destroy();
}
}
catch(Ice.SystemException)
{
throw;
}
catch(_System.Exception ex__)
{
IceInternal.LocalExceptionWrapper.throwWrapper(ex__);
}
return result__;
}
}
}
namespace Example
{
[_System.Runtime.InteropServices.ComVisible(false)]
[_System.CodeDom.Compiler.GeneratedCodeAttribute("slice2cs", "3.5.1")]
public abstract class ConverterDisp_ : Ice.ObjectImpl, Converter
{
#region Slice operations
public string toUpper(string s)
{
return toUpper(s, Ice.ObjectImpl.defaultCurrent);
}
public abstract string toUpper(string s, Ice.Current current__);
#endregion
#region Slice type-related members
public static new readonly string[] ids__ =
{
"::Example::Converter",
"::Ice::Object"
};
public override bool ice_isA(string s)
{
return _System.Array.BinarySearch(ids__, s, IceUtilInternal.StringUtil.OrdinalStringComparer) >= 0;
}
public override bool ice_isA(string s, Ice.Current current__)
{
return _System.Array.BinarySearch(ids__, s, IceUtilInternal.StringUtil.OrdinalStringComparer) >= 0;
}
public override string[] ice_ids()
{
return ids__;
}
public override string[] ice_ids(Ice.Current current__)
{
return ids__;
}
public override string ice_id()
{
return ids__[0];
}
public override string ice_id(Ice.Current current__)
{
return ids__[0];
}
public static new string ice_staticId()
{
return ids__[0];
}
#endregion
#region Operation dispatch
[_System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1011")]
public static Ice.DispatchStatus toUpper___(Converter obj__, IceInternal.Incoming inS__, Ice.Current current__)
{
checkMode__(Ice.OperationMode.Normal, current__.mode);
IceInternal.BasicStream is__ = inS__.startReadParams();
string s;
s = is__.readString();
inS__.endReadParams();
string ret__ = obj__.toUpper(s, current__);
IceInternal.BasicStream os__ = inS__.startWriteParams__(Ice.FormatType.DefaultFormat);
os__.writeString(ret__);
inS__.endWriteParams__(true);
return Ice.DispatchStatus.DispatchOK;
}
private static string[] all__ =
{
"ice_id",
"ice_ids",
"ice_isA",
"ice_ping",
"toUpper"
};
public override Ice.DispatchStatus dispatch__(IceInternal.Incoming inS__, Ice.Current current__)
{
int pos = _System.Array.BinarySearch(all__, current__.operation, IceUtilInternal.StringUtil.OrdinalStringComparer);
if(pos < 0)
{
throw new Ice.OperationNotExistException(current__.id, current__.facet, current__.operation);
}
switch(pos)
{
case 0:
{
return ice_id___(this, inS__, current__);
}
case 1:
{
return ice_ids___(this, inS__, current__);
}
case 2:
{
return ice_isA___(this, inS__, current__);
}
case 3:
{
return ice_ping___(this, inS__, current__);
}
case 4:
{
return toUpper___(this, inS__, current__);
}
}
_System.Diagnostics.Debug.Assert(false);
throw new Ice.OperationNotExistException(current__.id, current__.facet, current__.operation);
}
#endregion
#region Marshaling support
protected override void writeImpl__(IceInternal.BasicStream os__)
{
os__.startWriteSlice(ice_staticId(), -1, true);
os__.endWriteSlice();
}
protected override void readImpl__(IceInternal.BasicStream is__)
{
is__.startReadSlice();
is__.endReadSlice();
}
#endregion
}
}
| |
using Microsoft.IdentityModel;
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.S2S.Tokens;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.EventReceivers;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
using System.ServiceModel;
using System.Text;
using System.Web;
using System.Web.Configuration;
using System.Web.Script.Serialization;
using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction;
using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException;
using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration;
using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials;
namespace OfficeDevPnP.PartnerPack.Setup
{
public static class TokenHelper
{
#region public fields
/// <summary>
/// SharePoint principal.
/// </summary>
public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000";
/// <summary>
/// Lifetime of HighTrust access token, 12 hours.
/// </summary>
public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0);
#endregion public fields
#region public methods
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequest request)
{
return GetContextTokenFromRequest(new HttpRequestWrapper(request));
}
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequestBase request)
{
string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" };
foreach (string paramName in paramNames)
{
if (!string.IsNullOrEmpty(request.Form[paramName]))
{
return request.Form[paramName];
}
if (!string.IsNullOrEmpty(request.QueryString[paramName]))
{
return request.QueryString[paramName];
}
}
return null;
}
/// <summary>
/// Validate that a specified context token string is intended for this application based on the parameters
/// specified in web.config. Parameters used from web.config used for validation include ClientId,
/// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present,
/// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not
/// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an
/// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents
/// and a JsonWebSecurityToken based on the context token is returned.
/// </summary>
/// <param name="contextTokenString">The context token to validate</param>
/// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation.
/// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used
/// for validation instead of <paramref name="appHostName"/> .</param>
/// <returns>A JsonWebSecurityToken based on the context token.</returns>
public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null)
{
JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler();
SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString);
JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken;
SharePointContextToken token = SharePointContextToken.Create(jsonToken);
string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority;
int firstDot = stsAuthority.IndexOf('.');
GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot);
AcsHostUrl = stsAuthority.Substring(firstDot + 1);
tokenHandler.ValidateToken(jsonToken);
string[] acceptableAudiences;
if (!String.IsNullOrEmpty(HostedAppHostNameOverride))
{
acceptableAudiences = HostedAppHostNameOverride.Split(';');
}
else if (appHostName == null)
{
acceptableAudiences = new[] { HostedAppHostName };
}
else
{
acceptableAudiences = new[] { appHostName };
}
bool validationSuccessful = false;
string realm = Realm ?? token.Realm;
foreach (var audience in acceptableAudiences)
{
string principal = GetFormattedPrincipal(ClientId, audience, realm);
if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal))
{
validationSuccessful = true;
break;
}
}
if (!validationSuccessful)
{
throw new AudienceUriValidationFailedException(
String.Format(CultureInfo.CurrentCulture,
"\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience));
}
return token;
}
/// <summary>
/// Retrieves an access token from ACS to call the source of the specified context token at the specified
/// targetHost. The targetHost must be registered for the principal that sent the context token.
/// </summary>
/// <param name="contextToken">Context token issued by the intended access token audience</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <returns>An access token with an audience matching the context token's source</returns>
public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost)
{
string targetPrincipalName = contextToken.TargetPrincipalName;
// Extract the refreshToken from the context token
string refreshToken = contextToken.RefreshToken;
if (String.IsNullOrEmpty(refreshToken))
{
return null;
}
string targetRealm = Realm ?? contextToken.Realm;
return GetAccessToken(refreshToken,
targetPrincipalName,
targetHost,
targetRealm);
}
/// <summary>
/// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="authorizationCode">Authorization code to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string authorizationCode,
string targetPrincipalName,
string targetHost,
string targetRealm,
Uri redirectUri)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
// Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered
OAuth2AccessTokenRequest oauth2Request =
OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode(
clientId,
ClientSecret,
authorizationCode,
redirectUri,
resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="refreshToken">Refresh token to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string refreshToken,
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Retrieves an app-only access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAppOnlyAccessToken(
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource);
oauth2Request.Resource = resource;
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Creates a client context based on the properties of a remote event receiver
/// </summary>
/// <param name="properties">Properties of a remote event receiver</param>
/// <returns>A ClientContext ready to call the web where the event originated</returns>
public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties)
{
Uri sharepointUrl;
if (properties.ListEventProperties != null)
{
sharepointUrl = new Uri(properties.ListEventProperties.WebUrl);
}
else if (properties.ItemEventProperties != null)
{
sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl);
}
else if (properties.WebEventProperties != null)
{
sharepointUrl = new Uri(properties.WebEventProperties.FullUrl);
}
else
{
return null;
}
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Creates a client context based on the properties of an app event
/// </summary>
/// <param name="properties">Properties of an app event</param>
/// <param name="useAppWeb">True to target the app web, false to target the host web</param>
/// <returns>A ClientContext ready to call the app web or the parent web</returns>
public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb)
{
if (properties.AppEventProperties == null)
{
return null;
}
Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl;
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string authorizationCode,
Uri redirectUri)
{
return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="targetPrincipalName">Name of the target SharePoint principal</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string targetPrincipalName,
string authorizationCode,
string targetRealm,
Uri redirectUri)
{
Uri targetUri = new Uri(targetUrl);
string accessToken =
GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Uses the specified access token to create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="accessToken">Access token to be used when calling the specified targetUrl</param>
/// <returns>A ClientContext ready to call targetUrl with the specified access token</returns>
public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken)
{
ClientContext clientContext = new ClientContext(targetUrl);
clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous;
clientContext.FormDigestHandlingEnabled = false;
clientContext.ExecutingWebRequest +=
delegate(object oSender, WebRequestEventArgs webRequestEventArgs)
{
webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] =
"Bearer " + accessToken;
};
return clientContext;
}
/// <summary>
/// Retrieves an access token from ACS using the specified context token, and uses that access token to create
/// a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="contextTokenString">Context token received from the target SharePoint site</param>
/// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName
/// of web.config will be used instead</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithContextToken(
string targetUrl,
string contextTokenString,
string appHostUrl)
{
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl);
Uri targetUri = new Uri(targetUrl);
string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is
/// granted</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope,
redirectUri);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request a new context token.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param>
/// <returns>Url of the SharePoint site's context token redirect page</returns>
public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri)
{
return string.Format(
"{0}{1}?client_id={2}&redirect_uri={3}",
EnsureTrailingSlash(contextUrl),
RedirectPage,
ClientId,
redirectUri);
}
/// <summary>
/// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified
/// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in
/// web.config, an auth challenge will be issued to the targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>An access token with an audience of the target principal</returns>
public static string GetS2SAccessTokenWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
}
/// <summary>
/// Retrieves an S2S client context with an access token signed by the application's private certificate on
/// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the
/// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the
/// targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>A ClientContext using an access token with an audience of the target application</returns>
public static ClientContext GetS2SClientContextWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken);
}
/// <summary>
/// Get authentication realm from SharePoint
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <returns>String representation of the realm GUID</returns>
public static string GetRealmFromTargetUrl(Uri targetApplicationUri)
{
WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc");
request.Headers.Add("Authorization: Bearer ");
try
{
using (request.GetResponse())
{
}
}
catch (WebException e)
{
if (e.Response == null)
{
return null;
}
string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"];
if (string.IsNullOrEmpty(bearerResponseHeader))
{
return null;
}
const string bearer = "Bearer realm=\"";
int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal);
if (bearerIndex < 0)
{
return null;
}
int realmIndex = bearerIndex + bearer.Length;
if (bearerResponseHeader.Length >= realmIndex + 36)
{
string targetRealm = bearerResponseHeader.Substring(realmIndex, 36);
Guid realmGuid;
if (Guid.TryParse(targetRealm, out realmGuid))
{
return targetRealm;
}
}
}
return null;
}
/// <summary>
/// Determines if this is a high trust app.
/// </summary>
/// <returns>True if this is a high trust app.</returns>
public static bool IsHighTrustApp()
{
return SigningCredentials != null;
}
/// <summary>
/// Ensures that the specified URL ends with '/' if it is not null or empty.
/// </summary>
/// <param name="url">The url.</param>
/// <returns>The url ending with '/' if it is not null or empty.</returns>
public static string EnsureTrailingSlash(string url)
{
if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/')
{
return url + "/";
}
return url;
}
#endregion
#region private fields
//
// Configuration Constants
//
private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx";
private const string RedirectPage = "_layouts/15/AppRedirect.aspx";
private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000";
private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1";
private const string S2SProtocol = "OAuth2";
private const string DelegationIssuance = "DelegationIssuance1.0";
private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier;
private const string TrustedForImpersonationClaimType = "trustedfordelegation";
private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken;
//
// Environment Constants
//
private static string GlobalEndPointPrefix = "accounts";
private static string AcsHostUrl = "accesscontrol.windows.net";
//
// Hosted app configuration
//
private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId");
private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId");
private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride");
private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName");
private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret");
private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret");
private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath");
private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword");
private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword);
private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest);
#endregion
#region private methods
private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl)
{
string contextTokenString = properties.ContextToken;
if (String.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host);
string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken;
return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken);
}
private static string GetAcsMetadataEndpointUrl()
{
return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl);
}
private static string GetFormattedPrincipal(string principalName, string hostName, string realm)
{
if (!String.IsNullOrEmpty(hostName))
{
return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm);
}
return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm);
}
private static string GetAcsPrincipalName(string realm)
{
return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm);
}
private static string GetAcsGlobalEndpointUrl()
{
return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl);
}
private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler()
{
JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler();
handler.Configuration = new SecurityTokenHandlerConfiguration();
handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never);
handler.Configuration.CertificateValidator = X509CertificateValidator.None;
List<byte[]> securityKeys = new List<byte[]>();
securityKeys.Add(Convert.FromBase64String(ClientSecret));
if (!string.IsNullOrEmpty(SecondaryClientSecret))
{
securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret));
}
List<SecurityToken> securityTokens = new List<SecurityToken>();
securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys));
handler.Configuration.IssuerTokenResolver =
SecurityTokenResolver.CreateDefaultSecurityTokenResolver(
new ReadOnlyCollection<SecurityToken>(securityTokens),
false);
SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry();
foreach (byte[] securitykey in securityKeys)
{
issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace));
}
handler.Configuration.IssuerNameRegistry = issuerNameRegistry;
return handler;
}
private static string GetS2SAccessTokenWithClaims(
string targetApplicationHostName,
string targetRealm,
IEnumerable<JsonWebTokenClaim> claims)
{
return IssueToken(
ClientId,
IssuerId,
targetRealm,
SharePointPrincipal,
targetRealm,
targetApplicationHostName,
true,
claims,
claims == null);
}
private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity)
{
JsonWebTokenClaim[] claims = new JsonWebTokenClaim[]
{
new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()),
new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory")
};
return claims;
}
private static string IssueToken(
string sourceApplication,
string issuerApplication,
string sourceRealm,
string targetApplication,
string targetRealm,
string targetApplicationHostName,
bool trustedForDelegation,
IEnumerable<JsonWebTokenClaim> claims,
bool appOnly = false)
{
if (null == SigningCredentials)
{
throw new InvalidOperationException("SigningCredentials was not initialized");
}
#region Actor token
string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm);
string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm);
string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm);
List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>();
actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid));
if (trustedForDelegation && !appOnly)
{
actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true"));
}
// Create token
JsonWebSecurityToken actorToken = new JsonWebSecurityToken(
issuer: issuer,
audience: audience,
validFrom: DateTime.UtcNow,
validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
signingCredentials: SigningCredentials,
claims: actorClaims);
string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken);
if (appOnly)
{
// App-only token is the same as actor token for delegated case
return actorTokenString;
}
#endregion Actor token
#region Outer token
List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims);
outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString));
JsonWebSecurityToken jsonToken = new JsonWebSecurityToken(
nameid, // outer token issuer should match actor token nameid
audience,
DateTime.UtcNow,
DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
outerClaims);
string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken);
#endregion Outer token
return accessToken;
}
#endregion
#region AcsMetadataParser
// This class is used to get MetaData document from the global STS endpoint. It contains
// methods to parse the MetaData document and get endpoints and STS certificate.
public static class AcsMetadataParser
{
public static X509Certificate2 GetAcsSigningCert(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
if (null != document.keys && document.keys.Count > 0)
{
JsonKey signingKey = document.keys[0];
if (null != signingKey && null != signingKey.keyValue)
{
return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value));
}
}
throw new Exception("Metadata document does not contain ACS signing certificate.");
}
public static string GetDelegationServiceUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance);
if (null != delegationEndpoint)
{
return delegationEndpoint.location;
}
throw new Exception("Metadata document does not contain Delegation Service endpoint Url");
}
private static JsonMetadataDocument GetMetadataDocument(string realm)
{
string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}",
GetAcsMetadataEndpointUrl(),
realm);
byte[] acsMetadata;
using (WebClient webClient = new WebClient())
{
acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm);
}
string jsonResponseString = Encoding.UTF8.GetString(acsMetadata);
JavaScriptSerializer serializer = new JavaScriptSerializer();
JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString);
if (null == document)
{
throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm);
}
return document;
}
public static string GetStsUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol);
if (null != s2sEndpoint)
{
return s2sEndpoint.location;
}
throw new Exception("Metadata document does not contain STS endpoint url");
}
private class JsonMetadataDocument
{
public string serviceName { get; set; }
public List<JsonEndpoint> endpoints { get; set; }
public List<JsonKey> keys { get; set; }
}
private class JsonEndpoint
{
public string location { get; set; }
public string protocol { get; set; }
public string usage { get; set; }
}
private class JsonKeyValue
{
public string type { get; set; }
public string value { get; set; }
}
private class JsonKey
{
public string usage { get; set; }
public JsonKeyValue keyValue { get; set; }
}
}
#endregion
}
/// <summary>
/// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token
/// </summary>
public class SharePointContextToken : JsonWebSecurityToken
{
public static SharePointContextToken Create(JsonWebSecurityToken contextToken)
{
return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims);
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims)
: base(issuer, audience, validFrom, validTo, claims)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken)
: base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials)
: base(issuer, audience, validFrom, validTo, claims, signingCredentials)
{
}
public string NameId
{
get
{
return GetClaimValue(this, "nameid");
}
}
/// <summary>
/// The principal name portion of the context token's "appctxsender" claim
/// </summary>
public string TargetPrincipalName
{
get
{
string appctxsender = GetClaimValue(this, "appctxsender");
if (appctxsender == null)
{
return null;
}
return appctxsender.Split('@')[0];
}
}
/// <summary>
/// The context token's "refreshtoken" claim
/// </summary>
public string RefreshToken
{
get
{
return GetClaimValue(this, "refreshtoken");
}
}
/// <summary>
/// The context token's "CacheKey" claim
/// </summary>
public string CacheKey
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string cacheKey = (string)dict["CacheKey"];
return cacheKey;
}
}
/// <summary>
/// The context token's "SecurityTokenServiceUri" claim
/// </summary>
public string SecurityTokenServiceUri
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"];
return securityTokenServiceUri;
}
}
/// <summary>
/// The realm portion of the context token's "audience" claim
/// </summary>
public string Realm
{
get
{
string aud = Audience;
if (aud == null)
{
return null;
}
string tokenRealm = aud.Substring(aud.IndexOf('@') + 1);
return tokenRealm;
}
}
private static string GetClaimValue(JsonWebSecurityToken token, string claimType)
{
if (token == null)
{
throw new ArgumentNullException("token");
}
foreach (JsonWebTokenClaim claim in token.Claims)
{
if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType))
{
return claim.Value;
}
}
return null;
}
}
/// <summary>
/// Represents a security token which contains multiple security keys that are generated using symmetric algorithms.
/// </summary>
public class MultipleSymmetricKeySecurityToken : SecurityToken
{
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys)
: this(UniqueId.CreateUniqueId(), keys)
{
}
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="tokenId">The unique identifier of the security token.</param>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys)
{
if (keys == null)
{
throw new ArgumentNullException("keys");
}
if (String.IsNullOrEmpty(tokenId))
{
throw new ArgumentException("Value cannot be a null or empty string.", "tokenId");
}
foreach (byte[] key in keys)
{
if (key.Length <= 0)
{
throw new ArgumentException("The key length must be greater then zero.", "keys");
}
}
id = tokenId;
effectiveTime = DateTime.UtcNow;
securityKeys = CreateSymmetricSecurityKeys(keys);
}
/// <summary>
/// Gets the unique identifier of the security token.
/// </summary>
public override string Id
{
get
{
return id;
}
}
/// <summary>
/// Gets the cryptographic keys associated with the security token.
/// </summary>
public override ReadOnlyCollection<SecurityKey> SecurityKeys
{
get
{
return securityKeys.AsReadOnly();
}
}
/// <summary>
/// Gets the first instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidFrom
{
get
{
return effectiveTime;
}
}
/// <summary>
/// Gets the last instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidTo
{
get
{
// Never expire
return DateTime.MaxValue;
}
}
/// <summary>
/// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier.
/// </summary>
/// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param>
/// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns>
public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause)
{
if (keyIdentifierClause == null)
{
throw new ArgumentNullException("keyIdentifierClause");
}
// Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the
// presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later
// when the key is matched to the issuer.
if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause)
{
return true;
}
return base.MatchesKeyIdentifierClause(keyIdentifierClause);
}
#region private members
private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys)
{
List<SecurityKey> symmetricKeys = new List<SecurityKey>();
foreach (byte[] key in keys)
{
symmetricKeys.Add(new InMemorySymmetricSecurityKey(key));
}
return symmetricKeys;
}
private string id;
private DateTime effectiveTime;
private List<SecurityKey> securityKeys;
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Runtime.Serialization
{
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Threading;
using System.Xml;
using DataContractDictionary = System.Collections.Generic.Dictionary<System.Xml.XmlQualifiedName, DataContract>;
using System.Xml.Serialization;
using System.Xml.Schema;
using System.Security;
using System.Linq;
using XmlSchemaType = System.Object;
#if NET_NATIVE
public delegate IXmlSerializable CreateXmlSerializableDelegate();
public sealed class XmlDataContract : DataContract
#else
internal delegate IXmlSerializable CreateXmlSerializableDelegate();
internal sealed class XmlDataContract : DataContract
#endif
{
[SecurityCritical]
/// <SecurityNote>
/// Critical - holds instance of CriticalHelper which keeps state that is cached statically for serialization.
/// Static fields are marked SecurityCritical or readonly to prevent
/// data from being modified or leaked to other components in appdomain.
/// </SecurityNote>
private XmlDataContractCriticalHelper _helper;
/// <SecurityNote>
/// Critical - initializes SecurityCritical field 'helper'
/// Safe - doesn't leak anything
/// </SecurityNote>
[SecuritySafeCritical]
public XmlDataContract() : base(new XmlDataContractCriticalHelper())
{
_helper = base.Helper as XmlDataContractCriticalHelper;
}
/// <SecurityNote>
/// Critical - initializes SecurityCritical field 'helper'
/// Safe - doesn't leak anything
/// </SecurityNote>
[SecuritySafeCritical]
internal XmlDataContract(Type type) : base(new XmlDataContractCriticalHelper(type))
{
_helper = base.Helper as XmlDataContractCriticalHelper;
}
public override DataContractDictionary KnownDataContracts
{
/// <SecurityNote>
/// Critical - fetches the critical KnownDataContracts property
/// Safe - KnownDataContracts only needs to be protected for write
/// </SecurityNote>
[SecuritySafeCritical]
get
{ return _helper.KnownDataContracts; }
/// <SecurityNote>
/// Critical - sets the critical KnownDataContracts property
/// </SecurityNote>
[SecurityCritical]
set
{ _helper.KnownDataContracts = value; }
}
internal bool IsAnonymous
{
/// <SecurityNote>
/// Critical - fetches the critical IsAnonymous property
/// Safe - IsAnonymous only needs to be protected for write
/// </SecurityNote>
[SecuritySafeCritical]
get
{ return _helper.IsAnonymous; }
}
public override bool HasRoot
{
/// <SecurityNote>
/// Critical - fetches the critical HasRoot property
/// Safe - HasRoot only needs to be protected for write
/// </SecurityNote>
[SecuritySafeCritical]
get
{ return _helper.HasRoot; }
/// <SecurityNote>
/// Critical - sets the critical HasRoot property
/// </SecurityNote>
[SecurityCritical]
set
{ _helper.HasRoot = value; }
}
public override XmlDictionaryString TopLevelElementName
{
/// <SecurityNote>
/// Critical - fetches the critical TopLevelElementName property
/// Safe - TopLevelElementName only needs to be protected for write
/// </SecurityNote>
[SecuritySafeCritical]
get
{ return _helper.TopLevelElementName; }
/// <SecurityNote>
/// Critical - sets the critical TopLevelElementName property
/// </SecurityNote>
[SecurityCritical]
set
{ _helper.TopLevelElementName = value; }
}
public override XmlDictionaryString TopLevelElementNamespace
{
/// <SecurityNote>
/// Critical - fetches the critical TopLevelElementNamespace property
/// Safe - TopLevelElementNamespace only needs to be protected for write
/// </SecurityNote>
[SecuritySafeCritical]
get
{ return _helper.TopLevelElementNamespace; }
/// <SecurityNote>
/// Critical - sets the critical TopLevelElementNamespace property
/// </SecurityNote>
[SecurityCritical]
set
{ _helper.TopLevelElementNamespace = value; }
}
#if !NET_NATIVE
internal CreateXmlSerializableDelegate CreateXmlSerializableDelegate
{
/// <SecurityNote>
/// Critical - fetches the critical CreateXmlSerializableDelegate property
/// Safe - CreateXmlSerializableDelegate only needs to be protected for write; initialized in getter if null
/// </SecurityNote>
[SecuritySafeCritical]
get
{
if (_helper.CreateXmlSerializableDelegate == null)
{
lock (this)
{
if (_helper.CreateXmlSerializableDelegate == null)
{
CreateXmlSerializableDelegate tempCreateXmlSerializable = GenerateCreateXmlSerializableDelegate();
Interlocked.MemoryBarrier();
_helper.CreateXmlSerializableDelegate = tempCreateXmlSerializable;
}
}
}
return _helper.CreateXmlSerializableDelegate;
}
}
#else
public CreateXmlSerializableDelegate CreateXmlSerializableDelegate { get; set; }
#endif
internal override bool CanContainReferences
{
get { return false; }
}
public override bool IsBuiltInDataContract
{
get
{
return UnderlyingType == Globals.TypeOfXmlElement || UnderlyingType == Globals.TypeOfXmlNodeArray;
}
}
[SecurityCritical]
/// <SecurityNote>
/// Critical - holds all state used for (de)serializing XML types.
/// since the data is cached statically, we lock down access to it.
/// </SecurityNote>
private class XmlDataContractCriticalHelper : DataContract.DataContractCriticalHelper
{
private DataContractDictionary _knownDataContracts;
private bool _isKnownTypeAttributeChecked;
private XmlDictionaryString _topLevelElementName;
private XmlDictionaryString _topLevelElementNamespace;
private bool _hasRoot;
private CreateXmlSerializableDelegate _createXmlSerializable;
internal XmlDataContractCriticalHelper()
{
}
internal XmlDataContractCriticalHelper(Type type) : base(type)
{
if (type.GetTypeInfo().IsDefined(Globals.TypeOfDataContractAttribute, false))
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.IXmlSerializableCannotHaveDataContract, DataContract.GetClrTypeFullName(type))));
if (type.GetTypeInfo().IsDefined(Globals.TypeOfCollectionDataContractAttribute, false))
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.IXmlSerializableCannotHaveCollectionDataContract, DataContract.GetClrTypeFullName(type))));
XmlSchemaType xsdType;
bool hasRoot;
XmlQualifiedName stableName;
SchemaExporter.GetXmlTypeInfo(type, out stableName, out xsdType, out hasRoot);
this.StableName = stableName;
this.HasRoot = hasRoot;
XmlDictionary dictionary = new XmlDictionary();
this.Name = dictionary.Add(StableName.Name);
this.Namespace = dictionary.Add(StableName.Namespace);
object[] xmlRootAttributes = (UnderlyingType == null) ? null : UnderlyingType.GetTypeInfo().GetCustomAttributes(Globals.TypeOfXmlRootAttribute, false).ToArray();
if (xmlRootAttributes == null || xmlRootAttributes.Length == 0)
{
if (hasRoot)
{
_topLevelElementName = Name;
_topLevelElementNamespace = (this.StableName.Namespace == Globals.SchemaNamespace) ? DictionaryGlobals.EmptyString : Namespace;
}
}
else
{
if (hasRoot)
{
XmlRootAttribute xmlRootAttribute = (XmlRootAttribute)xmlRootAttributes[0];
string elementName = xmlRootAttribute.ElementName;
_topLevelElementName = (elementName == null || elementName.Length == 0) ? Name : dictionary.Add(DataContract.EncodeLocalName(elementName));
string elementNs = xmlRootAttribute.Namespace;
_topLevelElementNamespace = (elementNs == null || elementNs.Length == 0) ? DictionaryGlobals.EmptyString : dictionary.Add(elementNs);
}
else
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.IsAnyCannotHaveXmlRoot, DataContract.GetClrTypeFullName(UnderlyingType))));
}
}
}
internal override DataContractDictionary KnownDataContracts
{
[SecurityCritical]
get
{
if (!_isKnownTypeAttributeChecked && UnderlyingType != null)
{
lock (this)
{
if (!_isKnownTypeAttributeChecked)
{
_knownDataContracts = DataContract.ImportKnownTypeAttributes(this.UnderlyingType);
Interlocked.MemoryBarrier();
_isKnownTypeAttributeChecked = true;
}
}
}
return _knownDataContracts;
}
[SecurityCritical]
set
{ _knownDataContracts = value; }
}
internal bool IsAnonymous
{
get { return false; }
}
internal override bool HasRoot
{
[SecurityCritical]
get
{ return _hasRoot; }
[SecurityCritical]
set
{ _hasRoot = value; }
}
internal override XmlDictionaryString TopLevelElementName
{
[SecurityCritical]
get
{ return _topLevelElementName; }
[SecurityCritical]
set
{ _topLevelElementName = value; }
}
internal override XmlDictionaryString TopLevelElementNamespace
{
[SecurityCritical]
get
{ return _topLevelElementNamespace; }
[SecurityCritical]
set
{ _topLevelElementNamespace = value; }
}
internal CreateXmlSerializableDelegate CreateXmlSerializableDelegate
{
get { return _createXmlSerializable; }
set { _createXmlSerializable = value; }
}
}
private ConstructorInfo GetConstructor()
{
Type type = UnderlyingType;
if (type.GetTypeInfo().IsValueType)
return null;
ConstructorInfo ctor = type.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public, Array.Empty<Type>());
if (ctor == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.IXmlSerializableMustHaveDefaultConstructor, DataContract.GetClrTypeFullName(type))));
return ctor;
}
#if !NET_NATIVE
/// <SecurityNote>
/// Critical - calls CodeGenerator.BeginMethod which is SecurityCritical
/// Safe - self-contained: returns the delegate to the generated IL but otherwise all IL generation is self-contained here
/// </SecurityNote>
[SecuritySafeCritical]
internal CreateXmlSerializableDelegate GenerateCreateXmlSerializableDelegate()
{
Type type = this.UnderlyingType;
CodeGenerator ilg = new CodeGenerator();
bool memberAccessFlag = RequiresMemberAccessForCreate(null) && !(type.FullName == "System.Xml.Linq.XElement");
try
{
ilg.BeginMethod("Create" + DataContract.GetClrTypeFullName(type), typeof(CreateXmlSerializableDelegate), memberAccessFlag);
}
catch (SecurityException securityException)
{
if (memberAccessFlag)
{
RequiresMemberAccessForCreate(securityException);
}
else
{
throw;
}
}
if (type.GetTypeInfo().IsValueType)
{
System.Reflection.Emit.LocalBuilder local = ilg.DeclareLocal(type, type.Name + "Value");
ilg.Ldloca(local);
ilg.InitObj(type);
ilg.Ldloc(local);
}
else
{
// Special case XElement
// codegen the same as 'internal XElement : this("default") { }'
ConstructorInfo ctor = GetConstructor();
if (!ctor.IsPublic && type.FullName == "System.Xml.Linq.XElement")
{
Type xName = type.GetTypeInfo().Assembly.GetType("System.Xml.Linq.XName");
if (xName != null)
{
MethodInfo XName_op_Implicit = xName.GetMethod(
"op_Implicit",
BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public,
new Type[] { typeof(String) }
);
ConstructorInfo XElement_ctor = type.GetConstructor(
BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public,
new Type[] { xName }
);
if (XName_op_Implicit != null && XElement_ctor != null)
{
ilg.Ldstr("default");
ilg.Call(XName_op_Implicit);
ctor = XElement_ctor;
}
}
}
ilg.New(ctor);
}
ilg.ConvertValue(this.UnderlyingType, Globals.TypeOfIXmlSerializable);
ilg.Ret();
return (CreateXmlSerializableDelegate)ilg.EndMethod();
}
/// <SecurityNote>
/// Review - calculates whether this Xml type requires MemberAccessPermission for deserialization.
/// since this information is used to determine whether to give the generated code access
/// permissions to private members, any changes to the logic should be reviewed.
/// </SecurityNote>
private bool RequiresMemberAccessForCreate(SecurityException securityException)
{
if (!IsTypeVisible(UnderlyingType))
{
if (securityException != null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new SecurityException(SR.Format(SR.PartialTrustIXmlSerializableTypeNotPublic, DataContract.GetClrTypeFullName(UnderlyingType)),
securityException));
}
return true;
}
if (ConstructorRequiresMemberAccess(GetConstructor()))
{
if (securityException != null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new SecurityException(SR.Format(SR.PartialTrustIXmlSerialzableNoPublicConstructor, DataContract.GetClrTypeFullName(UnderlyingType)),
securityException));
}
return true;
}
return false;
}
#endif
public override void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context)
{
if (context == null)
XmlObjectSerializerWriteContext.WriteRootIXmlSerializable(xmlWriter, obj);
else
context.WriteIXmlSerializable(xmlWriter, obj);
}
public override object ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context)
{
object o;
if (context == null)
{
o = XmlObjectSerializerReadContext.ReadRootIXmlSerializable(xmlReader, this, true /*isMemberType*/);
}
else
{
o = context.ReadIXmlSerializable(xmlReader, this, true /*isMemberType*/);
context.AddNewObject(o);
}
xmlReader.ReadEndElement();
return o;
}
}
}
| |
//
// TaskStatusIcon.cs
//
// Author:
// Gabriel Burt <gburt@novell.com>
//
// 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.Text;
using System.Collections.Generic;
using Mono.Unix;
using Gtk;
using Hyena;
using Hyena.Jobs;
using Hyena.Widgets;
using Banshee.Base;
using Banshee.ServiceStack;
namespace Banshee.Gui.Widgets
{
public class TaskStatusIcon : AnimatedImage
{
private List<Job> jobs = new List<Job> ();
public bool ShowOnlyBackgroundTasks { get; set; }
public bool IntermittentVisibility { get; set; }
public uint IntermittentVisibleTime { get; set; }
public uint IntermittentHiddenTime { get; set; }
private uint turn_off_id;
private uint turn_on_id;
public TaskStatusIcon ()
{
ShowOnlyBackgroundTasks = true;
IntermittentVisibility = false;
IntermittentVisibleTime = 2500;
IntermittentHiddenTime = 2 * IntermittentVisibleTime;
// Setup widgetry
try {
Pixbuf = Gtk.IconTheme.Default.LoadIcon ("process-working", 22, IconLookupFlags.NoSvg);
FrameHeight = 22;
FrameWidth = 22;
Load ();
TaskActive = false;
} catch (Exception e) {
Hyena.Log.Exception (e);
}
// Listen for jobs
JobScheduler job_manager = ServiceManager.Get<JobScheduler> ();
job_manager.JobAdded += OnJobAdded;
job_manager.JobRemoved += OnJobRemoved;
Update ();
}
protected TaskStatusIcon (IntPtr raw) : base (raw)
{
}
private void Update ()
{
lock (jobs) {
if (jobs.Count > 0) {
var sb = new StringBuilder ();
sb.Append ("<b>");
sb.Append (GLib.Markup.EscapeText (Catalog.GetPluralString (
"Active Task Running", "Active Tasks Running", jobs.Count)));
sb.Append ("</b>");
foreach (Job job in jobs) {
sb.AppendLine ();
sb.AppendFormat ("<small> \u2022 {0}</small>",
GLib.Markup.EscapeText (job.Title));
}
TooltipMarkup = sb.ToString ();
TaskActive = true;
} else {
TooltipText = null;
TaskActive = false;
}
}
}
private bool first = true;
private bool task_active = false;
private bool TaskActive {
set {
if (!first && task_active == value) {
return;
}
first = false;
task_active = value;
if (task_active) {
if (IntermittentVisibility) {
TurnOn ();
} else {
Active = true;
Sensitive = true;
}
} else {
if (IntermittentVisibility) {
TurnOff ();
} else {
Active = false;
Sensitive = false;
}
}
}
}
private bool TurnOn ()
{
if (task_active) {
Active = true;
Sensitive = true;
if (turn_off_id == 0) {
turn_off_id = Banshee.ServiceStack.Application.RunTimeout (IntermittentHiddenTime, TurnOff);
}
}
turn_on_id = 0;
return false;
}
private bool TurnOff ()
{
Active = false;
Sensitive = task_active;
if (task_active && turn_on_id == 0) {
turn_on_id = Banshee.ServiceStack.Application.RunTimeout (IntermittentVisibleTime, TurnOn);
}
turn_off_id = 0;
return false;
}
private void OnJobUpdated (object o, EventArgs args)
{
ThreadAssist.ProxyToMain (Update);
}
private void AddJob (Job job)
{
lock (jobs) {
if (job == null || (ShowOnlyBackgroundTasks && !job.IsBackground) || job.IsFinished) {
return;
}
jobs.Add (job);
job.Updated += OnJobUpdated;
}
ThreadAssist.ProxyToMain (Update);
}
private void OnJobAdded (Job job)
{
AddJob (job);
}
private void RemoveJob (Job job)
{
lock (jobs) {
if (jobs.Contains (job)) {
job.Updated -= OnJobUpdated;
jobs.Remove (job);
}
}
ThreadAssist.ProxyToMain (Update);
}
private void OnJobRemoved (Job job)
{
RemoveJob (job);
}
}
}
| |
//
// 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.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Microsoft.Azure;
using Microsoft.Azure.Management.DataFactories.Common.Models;
using Microsoft.Azure.Management.DataFactories.Core;
using Microsoft.Azure.Management.DataFactories.Core.Registration.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.DataFactories.Core
{
/// <summary>
/// Operations for managing data factory ActivityTypes.
/// </summary>
internal partial class ActivityTypeOperations : IServiceOperations<DataFactoryManagementClient>, IActivityTypeOperations
{
/// <summary>
/// Initializes a new instance of the ActivityTypeOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal ActivityTypeOperations(DataFactoryManagementClient client)
{
this._client = client;
}
private DataFactoryManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.DataFactories.Core.DataFactoryManagementClient.
/// </summary>
public DataFactoryManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Delete an ActivityType instance.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. The name of the data factory.
/// </param>
/// <param name='activityTypeName'>
/// Required. The name of the activityType.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public async Task<LongRunningOperationResponse> BeginDeleteAsync(string resourceGroupName, string dataFactoryName, string activityTypeName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (resourceGroupName != null && resourceGroupName.Length > 1000)
{
throw new ArgumentOutOfRangeException("resourceGroupName");
}
if (Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+$") == false)
{
throw new ArgumentOutOfRangeException("resourceGroupName");
}
if (dataFactoryName == null)
{
throw new ArgumentNullException("dataFactoryName");
}
if (dataFactoryName != null && dataFactoryName.Length > 63)
{
throw new ArgumentOutOfRangeException("dataFactoryName");
}
if (Regex.IsMatch(dataFactoryName, "^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$") == false)
{
throw new ArgumentOutOfRangeException("dataFactoryName");
}
if (activityTypeName == null)
{
throw new ArgumentNullException("activityTypeName");
}
if (activityTypeName != null && activityTypeName.Length > 260)
{
throw new ArgumentOutOfRangeException("activityTypeName");
}
if (Regex.IsMatch(activityTypeName, "^[A-Za-z0-9_][^<>*#.%&:\\\\+?/]*$") == false)
{
throw new ArgumentOutOfRangeException("activityTypeName");
}
// 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("dataFactoryName", dataFactoryName);
tracingParameters.Add("activityTypeName", activityTypeName);
TracingAdapter.Enter(invocationId, this, "BeginDeleteAsync", 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/Microsoft.DataFactory/datafactories/";
url = url + Uri.EscapeDataString(dataFactoryName);
url = url + "/activityTypes/";
url = url + Uri.EscapeDataString(activityTypeName);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-08-01");
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-client-request-id", Guid.NewGuid().ToString());
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Accepted && statusCode != HttpStatusCode.NoContent)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
LongRunningOperationResponse result = null;
// Deserialize Response
result = new LongRunningOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("Location"))
{
result.OperationStatusLink = httpResponse.Headers.GetValues("Location").FirstOrDefault();
}
if (httpResponse.Headers.Contains("Retry-After"))
{
result.RetryAfter = int.Parse(httpResponse.Headers.GetValues("Retry-After").FirstOrDefault(), CultureInfo.InvariantCulture);
}
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (statusCode == HttpStatusCode.Conflict)
{
result.Status = OperationStatus.Failed;
}
if (statusCode == HttpStatusCode.OK)
{
result.Status = OperationStatus.Succeeded;
}
if (statusCode == HttpStatusCode.NoContent)
{
result.Status = OperationStatus.Succeeded;
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Create or update an ActivityType.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. The name of the data factory.
/// </param>
/// <param name='parameters'>
/// Required. The parameters required to create or update an
/// ActivityType definition.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The create or update ActivityType operation response.
/// </returns>
public async Task<ActivityTypeCreateOrUpdateResponse> CreateOrUpdateAsync(string resourceGroupName, string dataFactoryName, ActivityTypeCreateOrUpdateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (resourceGroupName != null && resourceGroupName.Length > 1000)
{
throw new ArgumentOutOfRangeException("resourceGroupName");
}
if (Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+$") == false)
{
throw new ArgumentOutOfRangeException("resourceGroupName");
}
if (dataFactoryName == null)
{
throw new ArgumentNullException("dataFactoryName");
}
if (dataFactoryName != null && dataFactoryName.Length > 63)
{
throw new ArgumentOutOfRangeException("dataFactoryName");
}
if (Regex.IsMatch(dataFactoryName, "^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$") == false)
{
throw new ArgumentOutOfRangeException("dataFactoryName");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.ActivityType == null)
{
throw new ArgumentNullException("parameters.ActivityType");
}
if (parameters.ActivityType.Name == null)
{
throw new ArgumentNullException("parameters.ActivityType.Name");
}
if (parameters.ActivityType.Name != null && parameters.ActivityType.Name.Length > 260)
{
throw new ArgumentOutOfRangeException("parameters.ActivityType.Name");
}
if (Regex.IsMatch(parameters.ActivityType.Name, "^[A-Za-z0-9_][^<>*#.%&:\\\\+?/]*$") == false)
{
throw new ArgumentOutOfRangeException("parameters.ActivityType.Name");
}
if (parameters.ActivityType.Properties == null)
{
throw new ArgumentNullException("parameters.ActivityType.Properties");
}
if (parameters.ActivityType.Properties.Schema == null)
{
throw new ArgumentNullException("parameters.ActivityType.Properties.Schema");
}
if (parameters.ActivityType.Properties.Scope == null)
{
throw new ArgumentNullException("parameters.ActivityType.Properties.Scope");
}
// 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("dataFactoryName", dataFactoryName);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "CreateOrUpdateAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourcegroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/Microsoft.DataFactory/datafactories/";
url = url + Uri.EscapeDataString(dataFactoryName);
url = url + "/activityTypes/";
url = url + Uri.EscapeDataString(parameters.ActivityType.Name);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-08-01");
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-client-request-id", Guid.NewGuid().ToString());
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject activityTypeCreateOrUpdateParametersValue = new JObject();
requestDoc = activityTypeCreateOrUpdateParametersValue;
activityTypeCreateOrUpdateParametersValue["name"] = parameters.ActivityType.Name;
JObject propertiesValue = new JObject();
activityTypeCreateOrUpdateParametersValue["properties"] = propertiesValue;
propertiesValue["scope"] = parameters.ActivityType.Properties.Scope;
if (parameters.ActivityType.Properties.BaseType != null)
{
propertiesValue["baseType"] = parameters.ActivityType.Properties.BaseType;
}
propertiesValue["schema"] = JObject.Parse(parameters.ActivityType.Properties.Schema);
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 && statusCode != HttpStatusCode.Created)
{
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
ActivityTypeCreateOrUpdateResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ActivityTypeCreateOrUpdateResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
ActivityType activityTypeInstance = new ActivityType();
result.ActivityType = activityTypeInstance;
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
activityTypeInstance.Name = nameInstance;
}
JToken propertiesValue2 = responseDoc["properties"];
if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null)
{
ActivityTypeProperties propertiesInstance = new ActivityTypeProperties();
activityTypeInstance.Properties = propertiesInstance;
JToken scopeValue = propertiesValue2["scope"];
if (scopeValue != null && scopeValue.Type != JTokenType.Null)
{
string scopeInstance = ((string)scopeValue);
propertiesInstance.Scope = scopeInstance;
}
JToken baseTypeValue = propertiesValue2["baseType"];
if (baseTypeValue != null && baseTypeValue.Type != JTokenType.Null)
{
string baseTypeInstance = ((string)baseTypeValue);
propertiesInstance.BaseType = baseTypeInstance;
}
JToken schemaValue = propertiesValue2["schema"];
if (schemaValue != null && schemaValue.Type != JTokenType.Null)
{
string schemaInstance = schemaValue.ToString(Newtonsoft.Json.Formatting.Indented);
propertiesInstance.Schema = schemaInstance;
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Create or update an ActivityType.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. The name of the data factory.
/// </param>
/// <param name='activityTypeName'>
/// Required. An ActivityType name.
/// </param>
/// <param name='parameters'>
/// Required. The parameters required to create or update an
/// ActivityType definition.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The create or update ActivityType operation response.
/// </returns>
public async Task<ActivityTypeCreateOrUpdateResponse> CreateOrUpdateWithRawJsonContentAsync(string resourceGroupName, string dataFactoryName, string activityTypeName, ActivityTypeCreateOrUpdateWithRawJsonContentParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (resourceGroupName != null && resourceGroupName.Length > 1000)
{
throw new ArgumentOutOfRangeException("resourceGroupName");
}
if (Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+$") == false)
{
throw new ArgumentOutOfRangeException("resourceGroupName");
}
if (dataFactoryName == null)
{
throw new ArgumentNullException("dataFactoryName");
}
if (dataFactoryName != null && dataFactoryName.Length > 63)
{
throw new ArgumentOutOfRangeException("dataFactoryName");
}
if (Regex.IsMatch(dataFactoryName, "^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$") == false)
{
throw new ArgumentOutOfRangeException("dataFactoryName");
}
if (activityTypeName == null)
{
throw new ArgumentNullException("activityTypeName");
}
if (activityTypeName != null && activityTypeName.Length > 260)
{
throw new ArgumentOutOfRangeException("activityTypeName");
}
if (Regex.IsMatch(activityTypeName, "^[A-Za-z0-9_][^<>*#.%&:\\\\+?/]*$") == false)
{
throw new ArgumentOutOfRangeException("activityTypeName");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Content == null)
{
throw new ArgumentNullException("parameters.Content");
}
// 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("dataFactoryName", dataFactoryName);
tracingParameters.Add("activityTypeName", activityTypeName);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "CreateOrUpdateWithRawJsonContentAsync", 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/Microsoft.DataFactory/datafactories/";
url = url + Uri.EscapeDataString(dataFactoryName);
url = url + "/activityTypes/";
url = url + Uri.EscapeDataString(activityTypeName);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-08-01");
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-client-request-id", Guid.NewGuid().ToString());
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = parameters.Content;
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 && statusCode != HttpStatusCode.Created)
{
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
ActivityTypeCreateOrUpdateResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ActivityTypeCreateOrUpdateResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
ActivityType activityTypeInstance = new ActivityType();
result.ActivityType = activityTypeInstance;
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
activityTypeInstance.Name = nameInstance;
}
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
ActivityTypeProperties propertiesInstance = new ActivityTypeProperties();
activityTypeInstance.Properties = propertiesInstance;
JToken scopeValue = propertiesValue["scope"];
if (scopeValue != null && scopeValue.Type != JTokenType.Null)
{
string scopeInstance = ((string)scopeValue);
propertiesInstance.Scope = scopeInstance;
}
JToken baseTypeValue = propertiesValue["baseType"];
if (baseTypeValue != null && baseTypeValue.Type != JTokenType.Null)
{
string baseTypeInstance = ((string)baseTypeValue);
propertiesInstance.BaseType = baseTypeInstance;
}
JToken schemaValue = propertiesValue["schema"];
if (schemaValue != null && schemaValue.Type != JTokenType.Null)
{
string schemaInstance = schemaValue.ToString(Newtonsoft.Json.Formatting.Indented);
propertiesInstance.Schema = schemaInstance;
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Delete an ActivityType instance.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. The name of the data factory.
/// </param>
/// <param name='activityTypeName'>
/// Required. The name of the activityType.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public async Task<LongRunningOperationResponse> DeleteAsync(string resourceGroupName, string dataFactoryName, string activityTypeName, CancellationToken cancellationToken)
{
DataFactoryManagementClient 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("resourceGroupName", resourceGroupName);
tracingParameters.Add("dataFactoryName", dataFactoryName);
tracingParameters.Add("activityTypeName", activityTypeName);
TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters);
}
cancellationToken.ThrowIfCancellationRequested();
LongRunningOperationResponse response = await client.ActivityTypes.BeginDeleteAsync(resourceGroupName, dataFactoryName, activityTypeName, cancellationToken).ConfigureAwait(false);
if (response.Status == OperationStatus.Succeeded)
{
return response;
}
cancellationToken.ThrowIfCancellationRequested();
LongRunningOperationResponse result = await client.GetLongRunningOperationStatusAsync(response.OperationStatusLink, cancellationToken).ConfigureAwait(false);
int delayInSeconds = response.RetryAfter;
if (delayInSeconds == 0)
{
delayInSeconds = 30;
}
if (client.LongRunningOperationInitialTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationInitialTimeout;
}
while ((result.Status != OperationStatus.InProgress) == false)
{
cancellationToken.ThrowIfCancellationRequested();
await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
result = await client.GetLongRunningOperationStatusAsync(response.OperationStatusLink, cancellationToken).ConfigureAwait(false);
delayInSeconds = result.RetryAfter;
if (delayInSeconds == 0)
{
delayInSeconds = 15;
}
if (client.LongRunningOperationRetryTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationRetryTimeout;
}
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Gets an ActivityType instance.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. The name of the data factory.
/// </param>
/// <param name='parameters'>
/// Required. Parameters specifying how to get an ActivityType
/// definition.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The Get ActivityType operation response.
/// </returns>
public async Task<ActivityTypeGetResponse> GetAsync(string resourceGroupName, string dataFactoryName, ActivityTypeGetParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (resourceGroupName != null && resourceGroupName.Length > 1000)
{
throw new ArgumentOutOfRangeException("resourceGroupName");
}
if (Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+$") == false)
{
throw new ArgumentOutOfRangeException("resourceGroupName");
}
if (dataFactoryName == null)
{
throw new ArgumentNullException("dataFactoryName");
}
if (dataFactoryName != null && dataFactoryName.Length > 63)
{
throw new ArgumentOutOfRangeException("dataFactoryName");
}
if (Regex.IsMatch(dataFactoryName, "^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$") == false)
{
throw new ArgumentOutOfRangeException("dataFactoryName");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.ActivityTypeName == null)
{
throw new ArgumentNullException("parameters.ActivityTypeName");
}
if (parameters.ActivityTypeName != null && parameters.ActivityTypeName.Length > 260)
{
throw new ArgumentOutOfRangeException("parameters.ActivityTypeName");
}
if (Regex.IsMatch(parameters.ActivityTypeName, "^[A-Za-z0-9_][^<>*#.%&:\\\\+?/]*$") == false)
{
throw new ArgumentOutOfRangeException("parameters.ActivityTypeName");
}
if (parameters.RegistrationScope == null)
{
throw new ArgumentNullException("parameters.RegistrationScope");
}
// 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("dataFactoryName", dataFactoryName);
tracingParameters.Add("parameters", parameters);
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/Microsoft.DataFactory/datafactories/";
url = url + Uri.EscapeDataString(dataFactoryName);
url = url + "/activityTypes/";
url = url + Uri.EscapeDataString(parameters.ActivityTypeName);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-08-01");
queryParameters.Add("scope=" + Uri.EscapeDataString(parameters.RegistrationScope));
queryParameters.Add("resolved=" + Uri.EscapeDataString(parameters.Resolved.ToString().ToLower()));
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("x-ms-client-request-id", Guid.NewGuid().ToString());
// 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
ActivityTypeGetResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ActivityTypeGetResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
ActivityType activityTypeInstance = new ActivityType();
result.ActivityType = activityTypeInstance;
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
activityTypeInstance.Name = nameInstance;
}
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
ActivityTypeProperties propertiesInstance = new ActivityTypeProperties();
activityTypeInstance.Properties = propertiesInstance;
JToken scopeValue = propertiesValue["scope"];
if (scopeValue != null && scopeValue.Type != JTokenType.Null)
{
string scopeInstance = ((string)scopeValue);
propertiesInstance.Scope = scopeInstance;
}
JToken baseTypeValue = propertiesValue["baseType"];
if (baseTypeValue != null && baseTypeValue.Type != JTokenType.Null)
{
string baseTypeInstance = ((string)baseTypeValue);
propertiesInstance.BaseType = baseTypeInstance;
}
JToken schemaValue = propertiesValue["schema"];
if (schemaValue != null && schemaValue.Type != JTokenType.Null)
{
string schemaInstance = schemaValue.ToString(Newtonsoft.Json.Formatting.Indented);
propertiesInstance.Schema = schemaInstance;
}
}
}
}
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>
/// Gets the first page of ActivityType instances with the link to the
/// next page.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. The name of the data factory.
/// </param>
/// <param name='parameters'>
/// Required. Parameters specifying how to return a list of
/// ActivityType definitions.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The List ActivityType operation response.
/// </returns>
public async Task<ActivityTypeListResponse> ListAsync(string resourceGroupName, string dataFactoryName, ActivityTypeListParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (resourceGroupName != null && resourceGroupName.Length > 1000)
{
throw new ArgumentOutOfRangeException("resourceGroupName");
}
if (Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+$") == false)
{
throw new ArgumentOutOfRangeException("resourceGroupName");
}
if (dataFactoryName == null)
{
throw new ArgumentNullException("dataFactoryName");
}
if (dataFactoryName != null && dataFactoryName.Length > 63)
{
throw new ArgumentOutOfRangeException("dataFactoryName");
}
if (Regex.IsMatch(dataFactoryName, "^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$") == false)
{
throw new ArgumentOutOfRangeException("dataFactoryName");
}
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("dataFactoryName", dataFactoryName);
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/Microsoft.DataFactory/datafactories/";
url = url + Uri.EscapeDataString(dataFactoryName);
url = url + "/activityTypes";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-08-01");
if (parameters.ActivityTypeName != null)
{
queryParameters.Add("name=" + Uri.EscapeDataString(parameters.ActivityTypeName));
}
if (parameters.RegistrationScope != null)
{
queryParameters.Add("scope=" + Uri.EscapeDataString(parameters.RegistrationScope));
}
queryParameters.Add("resolved=" + Uri.EscapeDataString(parameters.Resolved.ToString().ToLower()));
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("x-ms-client-request-id", Guid.NewGuid().ToString());
// 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
ActivityTypeListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ActivityTypeListResponse();
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))
{
ActivityType activityTypeInstance = new ActivityType();
result.ActivityTypes.Add(activityTypeInstance);
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
activityTypeInstance.Name = nameInstance;
}
JToken propertiesValue = valueValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
ActivityTypeProperties propertiesInstance = new ActivityTypeProperties();
activityTypeInstance.Properties = propertiesInstance;
JToken scopeValue = propertiesValue["scope"];
if (scopeValue != null && scopeValue.Type != JTokenType.Null)
{
string scopeInstance = ((string)scopeValue);
propertiesInstance.Scope = scopeInstance;
}
JToken baseTypeValue = propertiesValue["baseType"];
if (baseTypeValue != null && baseTypeValue.Type != JTokenType.Null)
{
string baseTypeInstance = ((string)baseTypeValue);
propertiesInstance.BaseType = baseTypeInstance;
}
JToken schemaValue = propertiesValue["schema"];
if (schemaValue != null && schemaValue.Type != JTokenType.Null)
{
string schemaInstance = schemaValue.ToString(Newtonsoft.Json.Formatting.Indented);
propertiesInstance.Schema = schemaInstance;
}
}
}
}
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>
/// Gets the next page of ActivityType instances with the link to the
/// next page.
/// </summary>
/// <param name='nextLink'>
/// Required. The url to the next ActivityTypes page.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The List ActivityType operation response.
/// </returns>
public async Task<ActivityTypeListResponse> 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("x-ms-client-request-id", Guid.NewGuid().ToString());
// 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
ActivityTypeListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ActivityTypeListResponse();
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))
{
ActivityType activityTypeInstance = new ActivityType();
result.ActivityTypes.Add(activityTypeInstance);
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
activityTypeInstance.Name = nameInstance;
}
JToken propertiesValue = valueValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
ActivityTypeProperties propertiesInstance = new ActivityTypeProperties();
activityTypeInstance.Properties = propertiesInstance;
JToken scopeValue = propertiesValue["scope"];
if (scopeValue != null && scopeValue.Type != JTokenType.Null)
{
string scopeInstance = ((string)scopeValue);
propertiesInstance.Scope = scopeInstance;
}
JToken baseTypeValue = propertiesValue["baseType"];
if (baseTypeValue != null && baseTypeValue.Type != JTokenType.Null)
{
string baseTypeInstance = ((string)baseTypeValue);
propertiesInstance.BaseType = baseTypeInstance;
}
JToken schemaValue = propertiesValue["schema"];
if (schemaValue != null && schemaValue.Type != JTokenType.Null)
{
string schemaInstance = schemaValue.ToString(Newtonsoft.Json.Formatting.Indented);
propertiesInstance.Schema = schemaInstance;
}
}
}
}
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();
}
}
}
}
}
| |
// UrlRewriter - A .NET URL Rewriter module
// Version 2.0
//
// Copyright 2007 Intelligencia
// Copyright 2007 Seth Yates
//
namespace Intelligencia.UrlRewriter
{
using System;
using System.Collections;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using Intelligencia.UrlRewriter.Configuration;
using Intelligencia.UrlRewriter.Utilities;
/// <summary>
/// The core RewriterEngine class.
/// </summary>
public class RewriterEngine
{
/// <summary>
/// Constructor.
/// </summary>
/// <param name="contextFacade">The context facade to use.</param>
/// <param name="configuration">The configuration to use.</param>
public RewriterEngine(IContextFacade contextFacade, RewriterConfiguration configuration)
{
if (contextFacade == null)
{
throw new ArgumentNullException("contextFacade");
}
if (configuration == null)
{
throw new ArgumentNullException("configuration");
}
ContextFacade = contextFacade;
_configuration = configuration;
}
/// <summary>
/// Resolves an Application-path relative location
/// </summary>
/// <param name="location">The location</param>
/// <returns>The absolute location.</returns>
public string ResolveLocation(string location)
{
if (location == null)
{
throw new ArgumentNullException("location");
}
string appPath = ContextFacade.GetApplicationPath();
if (appPath.Length > 1)
{
appPath += "/";
}
return location.Replace("~/", appPath);
}
/// <summary>
/// Performs the rewriting.
/// </summary>
public void Rewrite()
{
string originalUrl = ContextFacade.GetRawUrl().Replace("+", " ");
RawUrl = originalUrl;
// Create the context
RewriteContext context = new RewriteContext(
this,
originalUrl,
ContextFacade.GetHttpMethod(),
ContextFacade.MapPath,
ContextFacade.GetServerVariables(),
ContextFacade.GetHeaders(),
ContextFacade.GetCookies());
// Process each rule.
ProcessRules(context);
// Append any headers defined.
AppendHeaders(context);
// Append any cookies defined.
AppendCookies(context);
// Rewrite the path if the location has changed.
ContextFacade.SetStatusCode((int)context.StatusCode);
if ((context.Location != originalUrl) && ((int)context.StatusCode < 400))
{
if ((int)context.StatusCode < 300)
{
// Successful status if less than 300
_configuration.Logger.Info(
MessageProvider.FormatString(Message.RewritingXtoY, ContextFacade.GetRawUrl(), context.Location));
// Verify that the url exists on this server.
HandleDefaultDocument(context); // VerifyResultExists(context);
if (context.Location.Contains(@"&"))
{
var queryStringCollection = HttpUtility.ParseQueryString(new Uri(this.ContextFacade.GetRequestUrl(), context.Location).Query);
StringBuilder builder = new StringBuilder();
foreach (var value in queryStringCollection.AllKeys.Distinct())
{
var argument = queryStringCollection.GetValues(value).FirstOrDefault();
if (value == "g")
{
if (context.Location != argument)
{
builder.AppendFormat(
"{0}={1}&",
value,
argument);
}
}
else
{
builder.AppendFormat(
"{0}={1}&",
value,
argument);
}
}
context.Location = context.Location.Remove(context.Location.IndexOf("?") + 1);
context.Location = context.Location + builder;
if (context.Location.EndsWith(@"&"))
{
context.Location = context.Location.Remove(context.Location.Length - 1);
}
}
ContextFacade.RewritePath(context.Location);
}
else
{
// Redirection
_configuration.Logger.Info(
MessageProvider.FormatString(
Message.RedirectingXtoY, ContextFacade.GetRawUrl(), context.Location));
ContextFacade.SetRedirectLocation(context.Location);
}
}
else if ((int)context.StatusCode >= 400)
{
HandleError(context);
}
else if (HandleDefaultDocument(context))
{
ContextFacade.RewritePath(context.Location);
}
// Sets the context items.
SetContextItems(context);
}
/// <summary>
/// Expands the given input based on the current context.
/// </summary>
/// <param name="context">The current context</param>
/// <param name="input">The input to expand.</param>
/// <returns>The expanded input</returns>
public string Expand(RewriteContext context, string input)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
if (input == null)
{
throw new ArgumentNullException("input");
}
/* replacement :- $n
* | ${[a-zA-Z0-9\-]+}
* | ${fn( <replacement> )}
* | ${<replacement-or-id>:<replacement-or-value>:<replacement-or-value>}
*
* replacement-or-id :- <replacement> | <id>
* replacement-or-value :- <replacement> | <value>
*/
/* $1 - regex replacement
* ${propertyname}
* ${map-name:value} map-name is replacement, value is replacement
* ${map-name:value|default-value} map-name is replacement, value is replacement, default-value is replacement
* ${fn(value)} value is replacement
*/
using (StringReader reader = new StringReader(input))
{
using (StringWriter writer = new StringWriter())
{
char ch = (char)reader.Read();
while (ch != (char)65535)
{
if ((char)ch == '$')
{
writer.Write(Reduce(context, reader));
}
else
{
writer.Write((char)ch);
}
ch = (char)reader.Read();
}
return writer.GetStringBuilder().ToString();
}
}
}
private void ProcessRules(RewriteContext context)
{
const int MaxRestart = 10; // Controls the number of restarts so we don't get into an infinite loop
IList rewriteRules = _configuration.Rules;
int restarts = 0;
for (int i = 0; i < rewriteRules.Count; i++)
{
// If the rule is conditional, ensure the conditions are met.
IRewriteCondition condition = rewriteRules[i] as IRewriteCondition;
if (condition == null || condition.IsMatch(context))
{
// Execute the action.
IRewriteAction action = rewriteRules[i] as IRewriteAction;
RewriteProcessing processing = action.Execute(context);
// If the action is Stop, then break out of the processing loop
if (processing == RewriteProcessing.StopProcessing)
{
_configuration.Logger.Debug(MessageProvider.FormatString(Message.StoppingBecauseOfRule));
break;
}
else if (processing == RewriteProcessing.RestartProcessing)
{
_configuration.Logger.Debug(MessageProvider.FormatString(Message.RestartingBecauseOfRule));
// Restart from the first rule.
i = 0;
if (++restarts > MaxRestart)
{
throw new InvalidOperationException(MessageProvider.FormatString(Message.TooManyRestarts));
}
}
}
}
}
/// <summary>
/// Handles the default document.
/// </summary>
/// <param name="context">The context.</param>
/// <returns></returns>
private bool HandleDefaultDocument(RewriteContext context)
{
Uri uri = new Uri(this.ContextFacade.GetRequestUrl(), context.Location);
UriBuilder b = new UriBuilder(uri);
b.Path += "/";
uri = b.Uri;
if (uri.Host == this.ContextFacade.GetRequestUrl().Host)
{
try
{
string filename = this.ContextFacade.MapPath(uri.AbsolutePath);
if (Directory.Exists(filename))
{
foreach (
string document in from string document in RewriterConfiguration.Current.DefaultDocuments
let pathName = Path.Combine(filename, document)
where File.Exists(pathName)
select document)
{
context.Location = new Uri(uri, document).AbsolutePath;
return true;
}
}
}
catch (PathTooLongException)
{
// ignore if path to long
return false;
}
}
return false;
}
private void VerifyResultExists(RewriteContext context)
{
if ((String.Compare(context.Location, ContextFacade.GetRawUrl()) != 0) && ((int)context.StatusCode < 300))
{
Uri uri = new Uri(ContextFacade.GetRequestUrl(), context.Location);
if (uri.Host == ContextFacade.GetRequestUrl().Host)
{
string filename = ContextFacade.MapPath(uri.AbsolutePath);
if (!File.Exists(filename))
{
_configuration.Logger.Debug(MessageProvider.FormatString(Message.ResultNotFound, filename));
context.StatusCode = HttpStatusCode.NotFound;
}
else
{
HandleDefaultDocument(context);
}
}
}
}
private void HandleError(RewriteContext context)
{
// Return the status code.
ContextFacade.SetStatusCode((int)context.StatusCode);
// Get the error handler if there is one.
IRewriteErrorHandler handler = _configuration.ErrorHandlers[(int)context.StatusCode] as IRewriteErrorHandler;
if (handler != null)
{
try
{
_configuration.Logger.Debug(MessageProvider.FormatString(Message.CallingErrorHandler));
// Execute the error handler.
ContextFacade.HandleError(handler);
}
catch (HttpException)
{
throw;
}
catch (Exception exc)
{
_configuration.Logger.Fatal(exc.Message, exc);
throw new HttpException(
(int)HttpStatusCode.InternalServerError, HttpStatusCode.InternalServerError.ToString());
}
}
else
{
throw new HttpException((int)context.StatusCode, context.StatusCode.ToString());
}
}
private void AppendHeaders(RewriteContext context)
{
foreach (string headerKey in context.Headers)
{
ContextFacade.AppendHeader(headerKey, context.Headers[headerKey]);
}
}
private void AppendCookies(RewriteContext context)
{
for (int i = 0; i < context.Cookies.Count; i++)
{
HttpCookie cookie = context.Cookies[i];
ContextFacade.AppendCookie(cookie);
}
}
private void SetContextItems(RewriteContext context)
{
this.OriginalQueryString =
new Uri(this.ContextFacade.GetRequestUrl(), this.ContextFacade.GetRawUrl()).Query.Replace("?", string.Empty);
this.QueryString = new Uri(this.ContextFacade.GetRequestUrl(), context.Location).Query.Replace("?", string.Empty);
// Add in the properties as context items, so these will be accessible to the handler
foreach (string key in context.Properties.Keys)
{
ContextFacade.SetItem(string.Format("Rewriter.{0}", key), context.Properties[key]);
}
}
/// <summary>
/// The raw url.
/// </summary>
public string RawUrl
{
get
{
return (string)ContextFacade.GetItem(ContextRawUrl);
}
set
{
ContextFacade.SetItem(ContextRawUrl, value);
}
}
/// <summary>
/// The original query string.
/// </summary>
public string OriginalQueryString
{
get
{
return (string)ContextFacade.GetItem(ContextOriginalQueryString);
}
set
{
ContextFacade.SetItem(ContextOriginalQueryString, value);
}
}
/// <summary>
/// The final querystring, after rewriting.
/// </summary>
public string QueryString
{
get
{
return (string)ContextFacade.GetItem(ContextQueryString);
}
set
{
ContextFacade.SetItem(ContextQueryString, value);
}
}
private string Reduce(RewriteContext context, StringReader reader)
{
string result;
char ch = (char)reader.Read();
if (char.IsDigit(ch))
{
string num = ch.ToString();
if (char.IsDigit((char)reader.Peek()))
{
ch = (char)reader.Read();
num += ch.ToString();
}
if (context.LastMatch != null)
{
Group group = context.LastMatch.Groups[Convert.ToInt32(num)];
result = @group != null ? @group.Value : string.Empty;
}
else
{
result = string.Empty;
}
}
else
switch (ch)
{
case '<':
{
string expr;
using (StringWriter writer = new StringWriter())
{
ch = (char)reader.Read();
while (ch != '>' && ch != (char)65535)
{
if (ch == '$')
{
writer.Write(this.Reduce(context, reader));
}
else
{
writer.Write(ch);
}
ch = (char)reader.Read();
}
expr = writer.GetStringBuilder().ToString();
}
if (context.LastMatch != null)
{
Group group = context.LastMatch.Groups[expr];
if (@group != null)
{
result = @group.Value;
}
else
{
result = string.Empty;
}
}
else
{
result = string.Empty;
}
}
break;
case '{':
{
string expr;
bool isMap = false;
bool isFunction = false;
using (StringWriter writer = new StringWriter())
{
ch = (char)reader.Read();
while (ch != '}' && ch != (char)65535)
{
if (ch == '$')
{
writer.Write(this.Reduce(context, reader));
}
else
{
if (ch == ':') isMap = true;
else if (ch == '(') isFunction = true;
writer.Write(ch);
}
ch = (char)reader.Read();
}
expr = writer.GetStringBuilder().ToString();
}
if (isMap)
{
Match match = Regex.Match(expr, @"^([^\:]+)\:([^\|]+)(\|(.+))?$");
string mapName = match.Groups[1].Value;
string mapArgument = match.Groups[2].Value;
string mapDefault = match.Groups[4].Value;
result =
this._configuration.TransformFactory.GetTransform(mapName).ApplyTransform(
mapArgument) ?? mapDefault;
}
else if (isFunction)
{
Match match = Regex.Match(expr, @"^([^\(]+)\((.+)\)$");
string functionName = match.Groups[1].Value;
string functionArgument = match.Groups[2].Value;
IRewriteTransform tx = this._configuration.TransformFactory.GetTransform(functionName);
result = tx != null ? tx.ApplyTransform(functionArgument) : expr;
}
else
{
result = context.Properties[expr];
}
}
break;
default:
result = ch.ToString();
break;
}
return result;
}
private const string ContextQueryString = "UrlRewriter.NET.QueryString";
private const string ContextOriginalQueryString = "UrlRewriter.NET.OriginalQueryString";
private const string ContextRawUrl = "UrlRewriter.NET.RawUrl";
private RewriterConfiguration _configuration;
private IContextFacade ContextFacade;
}
}
| |
/*
* Copyright 2021 Google LLC All Rights Reserved.
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file or at
* https://developers.google.com/open-source/licenses/bsd
*/
// <auto-generated>
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/api/auth.proto
// </auto-generated>
#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/auth.proto</summary>
public static partial class AuthReflection {
#region Descriptor
/// <summary>File descriptor for google/api/auth.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static AuthReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"ChVnb29nbGUvYXBpL2F1dGgucHJvdG8SCmdvb2dsZS5hcGkibAoOQXV0aGVu",
"dGljYXRpb24SLQoFcnVsZXMYAyADKAsyHi5nb29nbGUuYXBpLkF1dGhlbnRp",
"Y2F0aW9uUnVsZRIrCglwcm92aWRlcnMYBCADKAsyGC5nb29nbGUuYXBpLkF1",
"dGhQcm92aWRlciKpAQoSQXV0aGVudGljYXRpb25SdWxlEhAKCHNlbGVjdG9y",
"GAEgASgJEiwKBW9hdXRoGAIgASgLMh0uZ29vZ2xlLmFwaS5PQXV0aFJlcXVp",
"cmVtZW50cxIgChhhbGxvd193aXRob3V0X2NyZWRlbnRpYWwYBSABKAgSMQoM",
"cmVxdWlyZW1lbnRzGAcgAygLMhsuZ29vZ2xlLmFwaS5BdXRoUmVxdWlyZW1l",
"bnQiTAoLSnd0TG9jYXRpb24SEAoGaGVhZGVyGAEgASgJSAASDwoFcXVlcnkY",
"AiABKAlIABIUCgx2YWx1ZV9wcmVmaXgYAyABKAlCBAoCaW4imgEKDEF1dGhQ",
"cm92aWRlchIKCgJpZBgBIAEoCRIOCgZpc3N1ZXIYAiABKAkSEAoIandrc191",
"cmkYAyABKAkSEQoJYXVkaWVuY2VzGAQgASgJEhkKEWF1dGhvcml6YXRpb25f",
"dXJsGAUgASgJEi4KDWp3dF9sb2NhdGlvbnMYBiADKAsyFy5nb29nbGUuYXBp",
"Lkp3dExvY2F0aW9uIi0KEU9BdXRoUmVxdWlyZW1lbnRzEhgKEGNhbm9uaWNh",
"bF9zY29wZXMYASABKAkiOQoPQXV0aFJlcXVpcmVtZW50EhMKC3Byb3ZpZGVy",
"X2lkGAEgASgJEhEKCWF1ZGllbmNlcxgCIAEoCUJrCg5jb20uZ29vZ2xlLmFw",
"aUIJQXV0aFByb3RvUAFaRWdvb2dsZS5nb2xhbmcub3JnL2dlbnByb3RvL2dv",
"b2dsZWFwaXMvYXBpL3NlcnZpY2Vjb25maWc7c2VydmljZWNvbmZpZ6ICBEdB",
"UEliBnByb3RvMw=="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Api.Authentication), global::Google.Api.Authentication.Parser, new[]{ "Rules", "Providers" }, null, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Api.AuthenticationRule), global::Google.Api.AuthenticationRule.Parser, new[]{ "Selector", "Oauth", "AllowWithoutCredential", "Requirements" }, null, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Api.JwtLocation), global::Google.Api.JwtLocation.Parser, new[]{ "Header", "Query", "ValuePrefix" }, new[]{ "In" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Api.AuthProvider), global::Google.Api.AuthProvider.Parser, new[]{ "Id", "Issuer", "JwksUri", "Audiences", "AuthorizationUrl", "JwtLocations" }, null, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Api.OAuthRequirements), global::Google.Api.OAuthRequirements.Parser, new[]{ "CanonicalScopes" }, null, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Api.AuthRequirement), global::Google.Api.AuthRequirement.Parser, new[]{ "ProviderId", "Audiences" }, null, null, null, null)
}));
}
#endregion
}
#region Messages
/// <summary>
/// `Authentication` defines the authentication configuration for an API.
///
/// Example for an API targeted for external use:
///
/// name: calendar.googleapis.com
/// authentication:
/// providers:
/// - id: google_calendar_auth
/// jwks_uri: https://www.googleapis.com/oauth2/v1/certs
/// issuer: https://securetoken.google.com
/// rules:
/// - selector: "*"
/// requirements:
/// provider_id: google_calendar_auth
/// </summary>
public sealed partial class Authentication : pb::IMessage<Authentication>
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
, pb::IBufferMessage
#endif
{
private static readonly pb::MessageParser<Authentication> _parser = new pb::MessageParser<Authentication>(() => new Authentication());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<Authentication> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Api.AuthReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Authentication() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Authentication(Authentication other) : this() {
rules_ = other.rules_.Clone();
providers_ = other.providers_.Clone();
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Authentication Clone() {
return new Authentication(this);
}
/// <summary>Field number for the "rules" field.</summary>
public const int RulesFieldNumber = 3;
private static readonly pb::FieldCodec<global::Google.Api.AuthenticationRule> _repeated_rules_codec
= pb::FieldCodec.ForMessage(26, global::Google.Api.AuthenticationRule.Parser);
private readonly pbc::RepeatedField<global::Google.Api.AuthenticationRule> rules_ = new pbc::RepeatedField<global::Google.Api.AuthenticationRule>();
/// <summary>
/// A list of authentication rules that apply to individual API methods.
///
/// **NOTE:** All service configuration rules follow "last one wins" order.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::Google.Api.AuthenticationRule> Rules {
get { return rules_; }
}
/// <summary>Field number for the "providers" field.</summary>
public const int ProvidersFieldNumber = 4;
private static readonly pb::FieldCodec<global::Google.Api.AuthProvider> _repeated_providers_codec
= pb::FieldCodec.ForMessage(34, global::Google.Api.AuthProvider.Parser);
private readonly pbc::RepeatedField<global::Google.Api.AuthProvider> providers_ = new pbc::RepeatedField<global::Google.Api.AuthProvider>();
/// <summary>
/// Defines a set of authentication providers that a service supports.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::Google.Api.AuthProvider> Providers {
get { return providers_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as Authentication);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(Authentication other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if(!rules_.Equals(other.rules_)) return false;
if(!providers_.Equals(other.providers_)) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
hash ^= rules_.GetHashCode();
hash ^= providers_.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.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 !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
output.WriteRawMessage(this);
#else
rules_.WriteTo(output, _repeated_rules_codec);
providers_.WriteTo(output, _repeated_providers_codec);
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
rules_.WriteTo(ref output, _repeated_rules_codec);
providers_.WriteTo(ref output, _repeated_providers_codec);
if (_unknownFields != null) {
_unknownFields.WriteTo(ref output);
}
}
#endif
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
size += rules_.CalculateSize(_repeated_rules_codec);
size += providers_.CalculateSize(_repeated_providers_codec);
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(Authentication other) {
if (other == null) {
return;
}
rules_.Add(other.rules_);
providers_.Add(other.providers_);
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
input.ReadRawMessage(this);
#else
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 26: {
rules_.AddEntriesFrom(input, _repeated_rules_codec);
break;
}
case 34: {
providers_.AddEntriesFrom(input, _repeated_providers_codec);
break;
}
}
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 26: {
rules_.AddEntriesFrom(ref input, _repeated_rules_codec);
break;
}
case 34: {
providers_.AddEntriesFrom(ref input, _repeated_providers_codec);
break;
}
}
}
}
#endif
}
/// <summary>
/// Authentication rules for the service.
///
/// By default, if a method has any authentication requirements, every request
/// must include a valid credential matching one of the requirements.
/// It's an error to include more than one kind of credential in a single
/// request.
///
/// If a method doesn't have any auth requirements, request credentials will be
/// ignored.
/// </summary>
public sealed partial class AuthenticationRule : pb::IMessage<AuthenticationRule>
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
, pb::IBufferMessage
#endif
{
private static readonly pb::MessageParser<AuthenticationRule> _parser = new pb::MessageParser<AuthenticationRule>(() => new AuthenticationRule());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<AuthenticationRule> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Api.AuthReflection.Descriptor.MessageTypes[1]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public AuthenticationRule() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public AuthenticationRule(AuthenticationRule other) : this() {
selector_ = other.selector_;
oauth_ = other.oauth_ != null ? other.oauth_.Clone() : null;
allowWithoutCredential_ = other.allowWithoutCredential_;
requirements_ = other.requirements_.Clone();
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public AuthenticationRule Clone() {
return new AuthenticationRule(this);
}
/// <summary>Field number for the "selector" field.</summary>
public const int SelectorFieldNumber = 1;
private string selector_ = "";
/// <summary>
/// Selects the methods to which this rule applies.
///
/// Refer to [selector][google.api.DocumentationRule.selector] for syntax details.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Selector {
get { return selector_; }
set {
selector_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "oauth" field.</summary>
public const int OauthFieldNumber = 2;
private global::Google.Api.OAuthRequirements oauth_;
/// <summary>
/// The requirements for OAuth credentials.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Api.OAuthRequirements Oauth {
get { return oauth_; }
set {
oauth_ = value;
}
}
/// <summary>Field number for the "allow_without_credential" field.</summary>
public const int AllowWithoutCredentialFieldNumber = 5;
private bool allowWithoutCredential_;
/// <summary>
/// If true, the service accepts API keys without any other credential.
/// This flag only applies to HTTP and gRPC requests.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool AllowWithoutCredential {
get { return allowWithoutCredential_; }
set {
allowWithoutCredential_ = value;
}
}
/// <summary>Field number for the "requirements" field.</summary>
public const int RequirementsFieldNumber = 7;
private static readonly pb::FieldCodec<global::Google.Api.AuthRequirement> _repeated_requirements_codec
= pb::FieldCodec.ForMessage(58, global::Google.Api.AuthRequirement.Parser);
private readonly pbc::RepeatedField<global::Google.Api.AuthRequirement> requirements_ = new pbc::RepeatedField<global::Google.Api.AuthRequirement>();
/// <summary>
/// Requirements for additional authentication providers.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::Google.Api.AuthRequirement> Requirements {
get { return requirements_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as AuthenticationRule);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(AuthenticationRule other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Selector != other.Selector) return false;
if (!object.Equals(Oauth, other.Oauth)) return false;
if (AllowWithoutCredential != other.AllowWithoutCredential) return false;
if(!requirements_.Equals(other.requirements_)) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Selector.Length != 0) hash ^= Selector.GetHashCode();
if (oauth_ != null) hash ^= Oauth.GetHashCode();
if (AllowWithoutCredential != false) hash ^= AllowWithoutCredential.GetHashCode();
hash ^= requirements_.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.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 !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
output.WriteRawMessage(this);
#else
if (Selector.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Selector);
}
if (oauth_ != null) {
output.WriteRawTag(18);
output.WriteMessage(Oauth);
}
if (AllowWithoutCredential != false) {
output.WriteRawTag(40);
output.WriteBool(AllowWithoutCredential);
}
requirements_.WriteTo(output, _repeated_requirements_codec);
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
if (Selector.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Selector);
}
if (oauth_ != null) {
output.WriteRawTag(18);
output.WriteMessage(Oauth);
}
if (AllowWithoutCredential != false) {
output.WriteRawTag(40);
output.WriteBool(AllowWithoutCredential);
}
requirements_.WriteTo(ref output, _repeated_requirements_codec);
if (_unknownFields != null) {
_unknownFields.WriteTo(ref output);
}
}
#endif
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Selector.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Selector);
}
if (oauth_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Oauth);
}
if (AllowWithoutCredential != false) {
size += 1 + 1;
}
size += requirements_.CalculateSize(_repeated_requirements_codec);
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(AuthenticationRule other) {
if (other == null) {
return;
}
if (other.Selector.Length != 0) {
Selector = other.Selector;
}
if (other.oauth_ != null) {
if (oauth_ == null) {
Oauth = new global::Google.Api.OAuthRequirements();
}
Oauth.MergeFrom(other.Oauth);
}
if (other.AllowWithoutCredential != false) {
AllowWithoutCredential = other.AllowWithoutCredential;
}
requirements_.Add(other.requirements_);
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
input.ReadRawMessage(this);
#else
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
Selector = input.ReadString();
break;
}
case 18: {
if (oauth_ == null) {
Oauth = new global::Google.Api.OAuthRequirements();
}
input.ReadMessage(Oauth);
break;
}
case 40: {
AllowWithoutCredential = input.ReadBool();
break;
}
case 58: {
requirements_.AddEntriesFrom(input, _repeated_requirements_codec);
break;
}
}
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
Selector = input.ReadString();
break;
}
case 18: {
if (oauth_ == null) {
Oauth = new global::Google.Api.OAuthRequirements();
}
input.ReadMessage(Oauth);
break;
}
case 40: {
AllowWithoutCredential = input.ReadBool();
break;
}
case 58: {
requirements_.AddEntriesFrom(ref input, _repeated_requirements_codec);
break;
}
}
}
}
#endif
}
/// <summary>
/// Specifies a location to extract JWT from an API request.
/// </summary>
public sealed partial class JwtLocation : pb::IMessage<JwtLocation>
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
, pb::IBufferMessage
#endif
{
private static readonly pb::MessageParser<JwtLocation> _parser = new pb::MessageParser<JwtLocation>(() => new JwtLocation());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<JwtLocation> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Api.AuthReflection.Descriptor.MessageTypes[2]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public JwtLocation() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public JwtLocation(JwtLocation other) : this() {
valuePrefix_ = other.valuePrefix_;
switch (other.InCase) {
case InOneofCase.Header:
Header = other.Header;
break;
case InOneofCase.Query:
Query = other.Query;
break;
}
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public JwtLocation Clone() {
return new JwtLocation(this);
}
/// <summary>Field number for the "header" field.</summary>
public const int HeaderFieldNumber = 1;
/// <summary>
/// Specifies HTTP header name to extract JWT token.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Header {
get { return inCase_ == InOneofCase.Header ? (string) in_ : ""; }
set {
in_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
inCase_ = InOneofCase.Header;
}
}
/// <summary>Field number for the "query" field.</summary>
public const int QueryFieldNumber = 2;
/// <summary>
/// Specifies URL query parameter name to extract JWT token.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Query {
get { return inCase_ == InOneofCase.Query ? (string) in_ : ""; }
set {
in_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
inCase_ = InOneofCase.Query;
}
}
/// <summary>Field number for the "value_prefix" field.</summary>
public const int ValuePrefixFieldNumber = 3;
private string valuePrefix_ = "";
/// <summary>
/// The value prefix. The value format is "value_prefix{token}"
/// Only applies to "in" header type. Must be empty for "in" query type.
/// If not empty, the header value has to match (case sensitive) this prefix.
/// If not matched, JWT will not be extracted. If matched, JWT will be
/// extracted after the prefix is removed.
///
/// For example, for "Authorization: Bearer {JWT}",
/// value_prefix="Bearer " with a space at the end.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string ValuePrefix {
get { return valuePrefix_; }
set {
valuePrefix_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
private object in_;
/// <summary>Enum of possible cases for the "in" oneof.</summary>
public enum InOneofCase {
None = 0,
Header = 1,
Query = 2,
}
private InOneofCase inCase_ = InOneofCase.None;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public InOneofCase InCase {
get { return inCase_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void ClearIn() {
inCase_ = InOneofCase.None;
in_ = null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as JwtLocation);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(JwtLocation other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Header != other.Header) return false;
if (Query != other.Query) return false;
if (ValuePrefix != other.ValuePrefix) return false;
if (InCase != other.InCase) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (inCase_ == InOneofCase.Header) hash ^= Header.GetHashCode();
if (inCase_ == InOneofCase.Query) hash ^= Query.GetHashCode();
if (ValuePrefix.Length != 0) hash ^= ValuePrefix.GetHashCode();
hash ^= (int) inCase_;
if (_unknownFields != null) {
hash ^= _unknownFields.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 !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
output.WriteRawMessage(this);
#else
if (inCase_ == InOneofCase.Header) {
output.WriteRawTag(10);
output.WriteString(Header);
}
if (inCase_ == InOneofCase.Query) {
output.WriteRawTag(18);
output.WriteString(Query);
}
if (ValuePrefix.Length != 0) {
output.WriteRawTag(26);
output.WriteString(ValuePrefix);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
if (inCase_ == InOneofCase.Header) {
output.WriteRawTag(10);
output.WriteString(Header);
}
if (inCase_ == InOneofCase.Query) {
output.WriteRawTag(18);
output.WriteString(Query);
}
if (ValuePrefix.Length != 0) {
output.WriteRawTag(26);
output.WriteString(ValuePrefix);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(ref output);
}
}
#endif
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (inCase_ == InOneofCase.Header) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Header);
}
if (inCase_ == InOneofCase.Query) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Query);
}
if (ValuePrefix.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(ValuePrefix);
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(JwtLocation other) {
if (other == null) {
return;
}
if (other.ValuePrefix.Length != 0) {
ValuePrefix = other.ValuePrefix;
}
switch (other.InCase) {
case InOneofCase.Header:
Header = other.Header;
break;
case InOneofCase.Query:
Query = other.Query;
break;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
input.ReadRawMessage(this);
#else
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
Header = input.ReadString();
break;
}
case 18: {
Query = input.ReadString();
break;
}
case 26: {
ValuePrefix = input.ReadString();
break;
}
}
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
Header = input.ReadString();
break;
}
case 18: {
Query = input.ReadString();
break;
}
case 26: {
ValuePrefix = input.ReadString();
break;
}
}
}
}
#endif
}
/// <summary>
/// Configuration for an authentication provider, including support for
/// [JSON Web Token
/// (JWT)](https://tools.ietf.org/html/draft-ietf-oauth-json-web-token-32).
/// </summary>
public sealed partial class AuthProvider : pb::IMessage<AuthProvider>
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
, pb::IBufferMessage
#endif
{
private static readonly pb::MessageParser<AuthProvider> _parser = new pb::MessageParser<AuthProvider>(() => new AuthProvider());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<AuthProvider> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Api.AuthReflection.Descriptor.MessageTypes[3]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public AuthProvider() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public AuthProvider(AuthProvider other) : this() {
id_ = other.id_;
issuer_ = other.issuer_;
jwksUri_ = other.jwksUri_;
audiences_ = other.audiences_;
authorizationUrl_ = other.authorizationUrl_;
jwtLocations_ = other.jwtLocations_.Clone();
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public AuthProvider Clone() {
return new AuthProvider(this);
}
/// <summary>Field number for the "id" field.</summary>
public const int IdFieldNumber = 1;
private string id_ = "";
/// <summary>
/// The unique identifier of the auth provider. It will be referred to by
/// `AuthRequirement.provider_id`.
///
/// Example: "bookstore_auth".
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Id {
get { return id_; }
set {
id_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "issuer" field.</summary>
public const int IssuerFieldNumber = 2;
private string issuer_ = "";
/// <summary>
/// Identifies the principal that issued the JWT. See
/// https://tools.ietf.org/html/draft-ietf-oauth-json-web-token-32#section-4.1.1
/// Usually a URL or an email address.
///
/// Example: https://securetoken.google.com
/// Example: 1234567-compute@developer.gserviceaccount.com
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Issuer {
get { return issuer_; }
set {
issuer_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "jwks_uri" field.</summary>
public const int JwksUriFieldNumber = 3;
private string jwksUri_ = "";
/// <summary>
/// URL of the provider's public key set to validate signature of the JWT. See
/// [OpenID
/// Discovery](https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata).
/// Optional if the key set document:
/// - can be retrieved from
/// [OpenID
/// Discovery](https://openid.net/specs/openid-connect-discovery-1_0.html)
/// of the issuer.
/// - can be inferred from the email domain of the issuer (e.g. a Google
/// service account).
///
/// Example: https://www.googleapis.com/oauth2/v1/certs
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string JwksUri {
get { return jwksUri_; }
set {
jwksUri_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "audiences" field.</summary>
public const int AudiencesFieldNumber = 4;
private string audiences_ = "";
/// <summary>
/// The list of JWT
/// [audiences](https://tools.ietf.org/html/draft-ietf-oauth-json-web-token-32#section-4.1.3).
/// that are allowed to access. A JWT containing any of these audiences will
/// be accepted. When this setting is absent, JWTs with audiences:
/// - "https://[service.name]/[google.protobuf.Api.name]"
/// - "https://[service.name]/"
/// will be accepted.
/// For example, if no audiences are in the setting, LibraryService API will
/// accept JWTs with the following audiences:
/// -
/// https://library-example.googleapis.com/google.example.library.v1.LibraryService
/// - https://library-example.googleapis.com/
///
/// Example:
///
/// audiences: bookstore_android.apps.googleusercontent.com,
/// bookstore_web.apps.googleusercontent.com
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Audiences {
get { return audiences_; }
set {
audiences_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "authorization_url" field.</summary>
public const int AuthorizationUrlFieldNumber = 5;
private string authorizationUrl_ = "";
/// <summary>
/// Redirect URL if JWT token is required but not present or is expired.
/// Implement authorizationUrl of securityDefinitions in OpenAPI spec.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string AuthorizationUrl {
get { return authorizationUrl_; }
set {
authorizationUrl_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "jwt_locations" field.</summary>
public const int JwtLocationsFieldNumber = 6;
private static readonly pb::FieldCodec<global::Google.Api.JwtLocation> _repeated_jwtLocations_codec
= pb::FieldCodec.ForMessage(50, global::Google.Api.JwtLocation.Parser);
private readonly pbc::RepeatedField<global::Google.Api.JwtLocation> jwtLocations_ = new pbc::RepeatedField<global::Google.Api.JwtLocation>();
/// <summary>
/// Defines the locations to extract the JWT.
///
/// JWT locations can be either from HTTP headers or URL query parameters.
/// The rule is that the first match wins. The checking order is: checking
/// all headers first, then URL query parameters.
///
/// If not specified, default to use following 3 locations:
/// 1) Authorization: Bearer
/// 2) x-goog-iap-jwt-assertion
/// 3) access_token query parameter
///
/// Default locations can be specified as followings:
/// jwt_locations:
/// - header: Authorization
/// value_prefix: "Bearer "
/// - header: x-goog-iap-jwt-assertion
/// - query: access_token
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::Google.Api.JwtLocation> JwtLocations {
get { return jwtLocations_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as AuthProvider);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(AuthProvider other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Id != other.Id) return false;
if (Issuer != other.Issuer) return false;
if (JwksUri != other.JwksUri) return false;
if (Audiences != other.Audiences) return false;
if (AuthorizationUrl != other.AuthorizationUrl) return false;
if(!jwtLocations_.Equals(other.jwtLocations_)) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Id.Length != 0) hash ^= Id.GetHashCode();
if (Issuer.Length != 0) hash ^= Issuer.GetHashCode();
if (JwksUri.Length != 0) hash ^= JwksUri.GetHashCode();
if (Audiences.Length != 0) hash ^= Audiences.GetHashCode();
if (AuthorizationUrl.Length != 0) hash ^= AuthorizationUrl.GetHashCode();
hash ^= jwtLocations_.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.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 !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
output.WriteRawMessage(this);
#else
if (Id.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Id);
}
if (Issuer.Length != 0) {
output.WriteRawTag(18);
output.WriteString(Issuer);
}
if (JwksUri.Length != 0) {
output.WriteRawTag(26);
output.WriteString(JwksUri);
}
if (Audiences.Length != 0) {
output.WriteRawTag(34);
output.WriteString(Audiences);
}
if (AuthorizationUrl.Length != 0) {
output.WriteRawTag(42);
output.WriteString(AuthorizationUrl);
}
jwtLocations_.WriteTo(output, _repeated_jwtLocations_codec);
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
if (Id.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Id);
}
if (Issuer.Length != 0) {
output.WriteRawTag(18);
output.WriteString(Issuer);
}
if (JwksUri.Length != 0) {
output.WriteRawTag(26);
output.WriteString(JwksUri);
}
if (Audiences.Length != 0) {
output.WriteRawTag(34);
output.WriteString(Audiences);
}
if (AuthorizationUrl.Length != 0) {
output.WriteRawTag(42);
output.WriteString(AuthorizationUrl);
}
jwtLocations_.WriteTo(ref output, _repeated_jwtLocations_codec);
if (_unknownFields != null) {
_unknownFields.WriteTo(ref output);
}
}
#endif
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Id.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Id);
}
if (Issuer.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Issuer);
}
if (JwksUri.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(JwksUri);
}
if (Audiences.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Audiences);
}
if (AuthorizationUrl.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(AuthorizationUrl);
}
size += jwtLocations_.CalculateSize(_repeated_jwtLocations_codec);
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(AuthProvider other) {
if (other == null) {
return;
}
if (other.Id.Length != 0) {
Id = other.Id;
}
if (other.Issuer.Length != 0) {
Issuer = other.Issuer;
}
if (other.JwksUri.Length != 0) {
JwksUri = other.JwksUri;
}
if (other.Audiences.Length != 0) {
Audiences = other.Audiences;
}
if (other.AuthorizationUrl.Length != 0) {
AuthorizationUrl = other.AuthorizationUrl;
}
jwtLocations_.Add(other.jwtLocations_);
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
input.ReadRawMessage(this);
#else
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
Id = input.ReadString();
break;
}
case 18: {
Issuer = input.ReadString();
break;
}
case 26: {
JwksUri = input.ReadString();
break;
}
case 34: {
Audiences = input.ReadString();
break;
}
case 42: {
AuthorizationUrl = input.ReadString();
break;
}
case 50: {
jwtLocations_.AddEntriesFrom(input, _repeated_jwtLocations_codec);
break;
}
}
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
Id = input.ReadString();
break;
}
case 18: {
Issuer = input.ReadString();
break;
}
case 26: {
JwksUri = input.ReadString();
break;
}
case 34: {
Audiences = input.ReadString();
break;
}
case 42: {
AuthorizationUrl = input.ReadString();
break;
}
case 50: {
jwtLocations_.AddEntriesFrom(ref input, _repeated_jwtLocations_codec);
break;
}
}
}
}
#endif
}
/// <summary>
/// OAuth scopes are a way to define data and permissions on data. For example,
/// there are scopes defined for "Read-only access to Google Calendar" and
/// "Access to Cloud Platform". Users can consent to a scope for an application,
/// giving it permission to access that data on their behalf.
///
/// OAuth scope specifications should be fairly coarse grained; a user will need
/// to see and understand the text description of what your scope means.
///
/// In most cases: use one or at most two OAuth scopes for an entire family of
/// products. If your product has multiple APIs, you should probably be sharing
/// the OAuth scope across all of those APIs.
///
/// When you need finer grained OAuth consent screens: talk with your product
/// management about how developers will use them in practice.
///
/// Please note that even though each of the canonical scopes is enough for a
/// request to be accepted and passed to the backend, a request can still fail
/// due to the backend requiring additional scopes or permissions.
/// </summary>
public sealed partial class OAuthRequirements : pb::IMessage<OAuthRequirements>
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
, pb::IBufferMessage
#endif
{
private static readonly pb::MessageParser<OAuthRequirements> _parser = new pb::MessageParser<OAuthRequirements>(() => new OAuthRequirements());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<OAuthRequirements> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Api.AuthReflection.Descriptor.MessageTypes[4]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public OAuthRequirements() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public OAuthRequirements(OAuthRequirements other) : this() {
canonicalScopes_ = other.canonicalScopes_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public OAuthRequirements Clone() {
return new OAuthRequirements(this);
}
/// <summary>Field number for the "canonical_scopes" field.</summary>
public const int CanonicalScopesFieldNumber = 1;
private string canonicalScopes_ = "";
/// <summary>
/// The list of publicly documented OAuth scopes that are allowed access. An
/// OAuth token containing any of these scopes will be accepted.
///
/// Example:
///
/// canonical_scopes: https://www.googleapis.com/auth/calendar,
/// https://www.googleapis.com/auth/calendar.read
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string CanonicalScopes {
get { return canonicalScopes_; }
set {
canonicalScopes_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as OAuthRequirements);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(OAuthRequirements other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (CanonicalScopes != other.CanonicalScopes) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (CanonicalScopes.Length != 0) hash ^= CanonicalScopes.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.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 !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
output.WriteRawMessage(this);
#else
if (CanonicalScopes.Length != 0) {
output.WriteRawTag(10);
output.WriteString(CanonicalScopes);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
if (CanonicalScopes.Length != 0) {
output.WriteRawTag(10);
output.WriteString(CanonicalScopes);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(ref output);
}
}
#endif
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (CanonicalScopes.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(CanonicalScopes);
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(OAuthRequirements other) {
if (other == null) {
return;
}
if (other.CanonicalScopes.Length != 0) {
CanonicalScopes = other.CanonicalScopes;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
input.ReadRawMessage(this);
#else
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
CanonicalScopes = input.ReadString();
break;
}
}
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
CanonicalScopes = input.ReadString();
break;
}
}
}
}
#endif
}
/// <summary>
/// User-defined authentication requirements, including support for
/// [JSON Web Token
/// (JWT)](https://tools.ietf.org/html/draft-ietf-oauth-json-web-token-32).
/// </summary>
public sealed partial class AuthRequirement : pb::IMessage<AuthRequirement>
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
, pb::IBufferMessage
#endif
{
private static readonly pb::MessageParser<AuthRequirement> _parser = new pb::MessageParser<AuthRequirement>(() => new AuthRequirement());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<AuthRequirement> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Api.AuthReflection.Descriptor.MessageTypes[5]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public AuthRequirement() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public AuthRequirement(AuthRequirement other) : this() {
providerId_ = other.providerId_;
audiences_ = other.audiences_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public AuthRequirement Clone() {
return new AuthRequirement(this);
}
/// <summary>Field number for the "provider_id" field.</summary>
public const int ProviderIdFieldNumber = 1;
private string providerId_ = "";
/// <summary>
/// [id][google.api.AuthProvider.id] from authentication provider.
///
/// Example:
///
/// provider_id: bookstore_auth
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string ProviderId {
get { return providerId_; }
set {
providerId_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "audiences" field.</summary>
public const int AudiencesFieldNumber = 2;
private string audiences_ = "";
/// <summary>
/// NOTE: This will be deprecated soon, once AuthProvider.audiences is
/// implemented and accepted in all the runtime components.
///
/// The list of JWT
/// [audiences](https://tools.ietf.org/html/draft-ietf-oauth-json-web-token-32#section-4.1.3).
/// that are allowed to access. A JWT containing any of these audiences will
/// be accepted. When this setting is absent, only JWTs with audience
/// "https://[Service_name][google.api.Service.name]/[API_name][google.protobuf.Api.name]"
/// will be accepted. For example, if no audiences are in the setting,
/// LibraryService API will only accept JWTs with the following audience
/// "https://library-example.googleapis.com/google.example.library.v1.LibraryService".
///
/// Example:
///
/// audiences: bookstore_android.apps.googleusercontent.com,
/// bookstore_web.apps.googleusercontent.com
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Audiences {
get { return audiences_; }
set {
audiences_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as AuthRequirement);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(AuthRequirement other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (ProviderId != other.ProviderId) return false;
if (Audiences != other.Audiences) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (ProviderId.Length != 0) hash ^= ProviderId.GetHashCode();
if (Audiences.Length != 0) hash ^= Audiences.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.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 !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
output.WriteRawMessage(this);
#else
if (ProviderId.Length != 0) {
output.WriteRawTag(10);
output.WriteString(ProviderId);
}
if (Audiences.Length != 0) {
output.WriteRawTag(18);
output.WriteString(Audiences);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
if (ProviderId.Length != 0) {
output.WriteRawTag(10);
output.WriteString(ProviderId);
}
if (Audiences.Length != 0) {
output.WriteRawTag(18);
output.WriteString(Audiences);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(ref output);
}
}
#endif
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (ProviderId.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(ProviderId);
}
if (Audiences.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Audiences);
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(AuthRequirement other) {
if (other == null) {
return;
}
if (other.ProviderId.Length != 0) {
ProviderId = other.ProviderId;
}
if (other.Audiences.Length != 0) {
Audiences = other.Audiences;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
input.ReadRawMessage(this);
#else
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
ProviderId = input.ReadString();
break;
}
case 18: {
Audiences = input.ReadString();
break;
}
}
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
ProviderId = input.ReadString();
break;
}
case 18: {
Audiences = input.ReadString();
break;
}
}
}
}
#endif
}
#endregion
}
#endregion Designer generated code
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using Microsoft.MixedReality.Toolkit.Core.Definitions.Devices;
using Microsoft.MixedReality.Toolkit.Core.Definitions.InputSystem;
using Microsoft.MixedReality.Toolkit.Core.Definitions.Utilities;
using Microsoft.MixedReality.Toolkit.Core.EventDatum.Input;
using Microsoft.MixedReality.Toolkit.Core.Extensions;
using Microsoft.MixedReality.Toolkit.Core.Interfaces.DataProviders.Controllers;
using Microsoft.MixedReality.Toolkit.Core.Interfaces.InputSystem;
using Microsoft.MixedReality.Toolkit.Core.Interfaces.InputSystem.Handlers;
using Microsoft.MixedReality.Toolkit.Core.Services.InputSystem.Sources;
using Microsoft.MixedReality.Toolkit.Core.Utilities;
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
namespace Microsoft.MixedReality.Toolkit.Core.Services.InputSystem
{
/// <summary>
/// The Mixed Reality Toolkit's specific implementation of the <see cref="IMixedRealityInputSystem"/>
/// </summary>
public class MixedRealityInputSystem : BaseEventSystem, IMixedRealityInputSystem
{
/// <summary>
/// Constructor.
/// </summary>
/// <param name="profile"></param>
public MixedRealityInputSystem(MixedRealityInputSystemProfile profile) : base(profile)
{
if (MixedRealityToolkit.Instance.ActiveProfile.InputSystemProfile.InputActionRulesProfile == null)
{
throw new Exception("The Input system is missing the required Input Action Rules Profile!");
}
if (MixedRealityToolkit.Instance.ActiveProfile.InputSystemProfile.PointerProfile == null)
{
throw new Exception("The Input system is missing the required Pointer Profile!");
}
if (MixedRealityToolkit.Instance.ActiveProfile.InputSystemProfile.PointerProfile.GazeProviderType?.Type == null)
{
throw new Exception("The Input system is missing the required GazeProviderType!");
}
}
/// <inheritdoc />
public event Action InputEnabled;
/// <inheritdoc />
public event Action InputDisabled;
/// <inheritdoc />
public HashSet<IMixedRealityInputSource> DetectedInputSources { get; } = new HashSet<IMixedRealityInputSource>();
/// <inheritdoc />
public HashSet<IMixedRealityController> DetectedControllers { get; } = new HashSet<IMixedRealityController>();
private IMixedRealityFocusProvider focusProvider = null;
/// <inheritdoc />
public IMixedRealityFocusProvider FocusProvider => focusProvider ?? (focusProvider = MixedRealityToolkit.GetService<IMixedRealityFocusProvider>());
/// <inheritdoc />
public IMixedRealityGazeProvider GazeProvider { get; private set; }
private readonly Stack<GameObject> modalInputStack = new Stack<GameObject>();
private readonly Stack<GameObject> fallbackInputStack = new Stack<GameObject>();
/// <inheritdoc />
public bool IsInputEnabled => disabledRefCount <= 0;
private int disabledRefCount;
private SourceStateEventData sourceStateEventData;
private SourcePoseEventData<TrackingState> sourceTrackingEventData;
private SourcePoseEventData<Vector2> sourceVector2EventData;
private SourcePoseEventData<Vector3> sourcePositionEventData;
private SourcePoseEventData<Quaternion> sourceRotationEventData;
private SourcePoseEventData<MixedRealityPose> sourcePoseEventData;
private FocusEventData focusEventData;
private InputEventData inputEventData;
private MixedRealityPointerEventData pointerEventData;
private InputEventData<float> floatInputEventData;
private InputEventData<Vector2> vector2InputEventData;
private InputEventData<Vector3> positionInputEventData;
private InputEventData<Quaternion> rotationInputEventData;
private InputEventData<MixedRealityPose> poseInputEventData;
private SpeechEventData speechEventData;
private DictationEventData dictationEventData;
private MixedRealityInputActionRulesProfile CurrentInputActionRulesProfile { get; } = MixedRealityToolkit.Instance.ActiveProfile.InputSystemProfile.InputActionRulesProfile;
#region IMixedRealityManager Implementation
/// <inheritdoc />
/// <remarks>
/// Input system is critical, so should be processed before all other managers
/// </remarks>
public override uint Priority => 1;
/// <inheritdoc />
public override void Initialize()
{
base.Initialize();
bool addedComponents = false;
if (!Application.isPlaying)
{
var standaloneInputModules = UnityEngine.Object.FindObjectsOfType<StandaloneInputModule>();
CameraCache.Main.transform.position = Vector3.zero;
CameraCache.Main.transform.rotation = Quaternion.identity;
if (standaloneInputModules.Length == 0)
{
CameraCache.Main.gameObject.EnsureComponent<StandaloneInputModule>();
addedComponents = true;
}
else
{
bool raiseWarning;
if (standaloneInputModules.Length == 1)
{
raiseWarning = standaloneInputModules[0].gameObject != CameraCache.Main.gameObject;
}
else
{
raiseWarning = true;
}
if (raiseWarning)
{
Debug.LogWarning("Found an existing Standalone Input Module in your scene. The Mixed Reality Input System requires only one, and must be found on the main camera.");
}
}
}
else
{
sourceStateEventData = new SourceStateEventData(EventSystem.current);
sourceTrackingEventData = new SourcePoseEventData<TrackingState>(EventSystem.current);
sourceVector2EventData = new SourcePoseEventData<Vector2>(EventSystem.current);
sourcePositionEventData = new SourcePoseEventData<Vector3>(EventSystem.current);
sourceRotationEventData = new SourcePoseEventData<Quaternion>(EventSystem.current);
sourcePoseEventData = new SourcePoseEventData<MixedRealityPose>(EventSystem.current);
focusEventData = new FocusEventData(EventSystem.current);
inputEventData = new InputEventData(EventSystem.current);
pointerEventData = new MixedRealityPointerEventData(EventSystem.current);
floatInputEventData = new InputEventData<float>(EventSystem.current);
vector2InputEventData = new InputEventData<Vector2>(EventSystem.current);
positionInputEventData = new InputEventData<Vector3>(EventSystem.current);
rotationInputEventData = new InputEventData<Quaternion>(EventSystem.current);
poseInputEventData = new InputEventData<MixedRealityPose>(EventSystem.current);
speechEventData = new SpeechEventData(EventSystem.current);
dictationEventData = new DictationEventData(EventSystem.current);
}
if (!addedComponents)
{
CameraCache.Main.gameObject.EnsureComponent<StandaloneInputModule>();
}
GazeProvider = CameraCache.Main.gameObject.EnsureComponent(MixedRealityToolkit.Instance.ActiveProfile.InputSystemProfile.PointerProfile.GazeProviderType.Type) as IMixedRealityGazeProvider;
}
/// <inheritdoc />
public override void Enable()
{
InputEnabled?.Invoke();
}
/// <inheritdoc />
public override void Disable()
{
GazeProvider = null;
if (!Application.isPlaying)
{
var component = CameraCache.Main.GetComponent<IMixedRealityGazeProvider>() as Component;
if (component != null)
{
UnityEngine.Object.DestroyImmediate(component);
}
var inputModule = CameraCache.Main.GetComponent<StandaloneInputModule>();
if (inputModule != null)
{
UnityEngine.Object.DestroyImmediate(inputModule);
}
}
InputDisabled?.Invoke();
}
#endregion IMixedRealityManager Implementation
#region IEventSystemManager Implementation
/// <inheritdoc />
public override void HandleEvent<T>(BaseEventData eventData, ExecuteEvents.EventFunction<T> eventHandler)
{
if (disabledRefCount > 0)
{
return;
}
Debug.Assert(eventData != null);
var baseInputEventData = ExecuteEvents.ValidateEventData<BaseInputEventData>(eventData);
Debug.Assert(baseInputEventData != null);
Debug.Assert(!baseInputEventData.used);
if (baseInputEventData.InputSource == null)
{
Debug.LogError($"Failed to find an input source for {baseInputEventData}");
return;
}
// Send the event to global listeners
base.HandleEvent(eventData, eventHandler);
if (baseInputEventData.used)
{
// All global listeners get a chance to see the event,
// but if any of them marked it used,
// we stop the event from going any further.
return;
}
if (baseInputEventData.InputSource.Pointers == null)
{
Debug.LogError($"InputSource {baseInputEventData.InputSource.SourceName} doesn't have any registered pointers! Input Sources without pointers should use the GazeProvider's pointer as a default fallback.");
return;
}
var modalEventHandled = false;
// Get the focused object for each pointer of the event source
for (int i = 0; i < baseInputEventData.InputSource.Pointers.Length; i++)
{
GameObject focusedObject = FocusProvider?.GetFocusedObject(baseInputEventData.InputSource.Pointers[i]);
// Handle modal input if one exists
if (modalInputStack.Count > 0 && !modalEventHandled)
{
GameObject modalInput = modalInputStack.Peek();
if (modalInput != null)
{
modalEventHandled = true;
// If there is a focused object in the hierarchy of the modal handler, start the event bubble there
if (focusedObject != null && focusedObject.transform.IsChildOf(modalInput.transform))
{
if (ExecuteEvents.ExecuteHierarchy(focusedObject, baseInputEventData, eventHandler) && baseInputEventData.used)
{
return;
}
}
// Otherwise, just invoke the event on the modal handler itself
else
{
if (ExecuteEvents.ExecuteHierarchy(modalInput, baseInputEventData, eventHandler) && baseInputEventData.used)
{
return;
}
}
}
else
{
Debug.LogError("ModalInput GameObject reference was null!\nDid this GameObject get destroyed?");
}
}
// If event was not handled by modal, pass it on to the current focused object
if (focusedObject != null)
{
if (ExecuteEvents.ExecuteHierarchy(focusedObject, baseInputEventData, eventHandler) && baseInputEventData.used)
{
return;
}
}
}
// If event was not handled by the focused object, pass it on to any fallback handlers
if (fallbackInputStack.Count > 0)
{
GameObject fallbackInput = fallbackInputStack.Peek();
if (ExecuteEvents.ExecuteHierarchy(fallbackInput, baseInputEventData, eventHandler) && baseInputEventData.used)
{
// return;
}
}
}
/// <summary>
/// Register a <see cref="GameObject"/> to listen to events that will receive all input events, regardless
/// of which other <see cref="GameObject"/>s might have handled the event beforehand.
/// <remarks>Useful for listening to events when the <see cref="GameObject"/> is currently not being raycasted against by the <see cref="FocusProvider"/>.</remarks>
/// </summary>
/// <param name="listener">Listener to add.</param>
public override void Register(GameObject listener)
{
base.Register(listener);
}
/// <summary>
/// Unregister a <see cref="GameObject"/> from listening to input events.
/// </summary>
/// <param name="listener"></param>
public override void Unregister(GameObject listener)
{
base.Unregister(listener);
}
#endregion IEventSystemManager Implementation
#region Input Disabled Options
/// <summary>
/// Push a disabled input state onto the input manager.
/// While input is disabled no events will be sent out and the cursor displays
/// a waiting animation.
/// </summary>
public void PushInputDisable()
{
++disabledRefCount;
if (disabledRefCount == 1)
{
InputDisabled?.Invoke();
if (GazeProvider != null)
{
GazeProvider.Enabled = false;
}
}
}
/// <summary>
/// Pop disabled input state. When the last disabled state is
/// popped off the stack input will be re-enabled.
/// </summary>
public void PopInputDisable()
{
--disabledRefCount;
Debug.Assert(disabledRefCount >= 0, "Tried to pop more input disable than the amount pushed.");
if (disabledRefCount == 0)
{
InputEnabled?.Invoke();
if (GazeProvider != null)
{
GazeProvider.Enabled = true;
}
}
}
/// <summary>
/// Clear the input disable stack, which will immediately re-enable input.
/// </summary>
public void ClearInputDisableStack()
{
bool wasInputDisabled = disabledRefCount > 0;
disabledRefCount = 0;
if (wasInputDisabled)
{
InputEnabled?.Invoke();
if (GazeProvider != null)
{
GazeProvider.Enabled = true;
}
}
}
#endregion Input Disabled Options
#region Modal Input Options
/// <summary>
/// Push a game object into the modal input stack. Any input handlers
/// on the game object are given priority to input events before any focused objects.
/// </summary>
/// <param name="inputHandler">The input handler to push</param>
public void PushModalInputHandler(GameObject inputHandler)
{
modalInputStack.Push(inputHandler);
}
/// <summary>
/// Remove the last game object from the modal input stack.
/// </summary>
public void PopModalInputHandler()
{
if (modalInputStack.Count > 0)
{
modalInputStack.Pop();
}
}
/// <summary>
/// Clear all modal input handlers off the stack.
/// </summary>
public void ClearModalInputStack()
{
modalInputStack.Clear();
}
#endregion Modal Input Options
#region Fallback Input Handler Options
/// <summary>
/// Push a game object into the fallback input stack. Any input handlers on
/// the game object are given input events when no modal or focused objects consume the event.
/// </summary>
/// <param name="inputHandler">The input handler to push</param>
public void PushFallbackInputHandler(GameObject inputHandler)
{
fallbackInputStack.Push(inputHandler);
}
/// <summary>
/// Remove the last game object from the fallback input stack.
/// </summary>
public void PopFallbackInputHandler()
{
fallbackInputStack.Pop();
}
/// <summary>
/// Clear all fallback input handlers off the stack.
/// </summary>
public void ClearFallbackInputStack()
{
fallbackInputStack.Clear();
}
#endregion Fallback Input Handler Options
#region IMixedRealityController Utilities
/// <inheritdoc />
public bool TryGetController(IMixedRealityInputSource inputSource, out IMixedRealityController controller)
{
foreach (IMixedRealityController mixedRealityController in DetectedControllers)
{
if (inputSource.SourceId == mixedRealityController.InputSource.SourceId)
{
controller = mixedRealityController;
return true;
}
}
controller = null;
return false;
}
#endregion IMixedRealityController Utilities
#region Input Events
#region Input Source Events
/// <inheritdoc />
public uint GenerateNewSourceId()
{
var newId = (uint)UnityEngine.Random.Range(1, int.MaxValue);
foreach (var inputSource in DetectedInputSources)
{
if (inputSource.SourceId == newId)
{
return GenerateNewSourceId();
}
}
return newId;
}
/// <inheritdoc />
public IMixedRealityInputSource RequestNewGenericInputSource(string name, IMixedRealityPointer[] pointers = null) => new BaseGenericInputSource(name, pointers);
#region Input Source State Events
/// <inheritdoc />
public void RaiseSourceDetected(IMixedRealityInputSource source, IMixedRealityController controller = null)
{
// Create input event
sourceStateEventData.Initialize(source, controller);
Debug.Assert(!DetectedInputSources.Contains(source), $"{source.SourceName} has already been registered with the Input Manager!");
DetectedInputSources.Add(source);
if (controller != null)
{
DetectedControllers.Add(controller);
}
FocusProvider?.OnSourceDetected(sourceStateEventData);
// Pass handler through HandleEvent to perform modal/fallback logic
HandleEvent(sourceStateEventData, OnSourceDetectedEventHandler);
}
private static readonly ExecuteEvents.EventFunction<IMixedRealitySourceStateHandler> OnSourceDetectedEventHandler =
delegate (IMixedRealitySourceStateHandler handler, BaseEventData eventData)
{
var casted = ExecuteEvents.ValidateEventData<SourceStateEventData>(eventData);
handler.OnSourceDetected(casted);
};
/// <inheritdoc />
public void RaiseSourceLost(IMixedRealityInputSource source, IMixedRealityController controller = null)
{
// Create input event
sourceStateEventData.Initialize(source, controller);
Debug.Assert(DetectedInputSources.Contains(source), $"{source.SourceName} was never registered with the Input Manager!");
DetectedInputSources.Remove(source);
if (controller != null)
{
DetectedControllers.Remove(controller);
}
FocusProvider?.OnSourceLost(sourceStateEventData);
// Pass handler through HandleEvent to perform modal/fallback logic
HandleEvent(sourceStateEventData, OnSourceLostEventHandler);
}
private static readonly ExecuteEvents.EventFunction<IMixedRealitySourceStateHandler> OnSourceLostEventHandler =
delegate (IMixedRealitySourceStateHandler handler, BaseEventData eventData)
{
var casted = ExecuteEvents.ValidateEventData<SourceStateEventData>(eventData);
handler.OnSourceLost(casted);
};
#endregion Input Source State Events
#region Input Source Pose Events
/// <inheritdoc />
public void RaiseSourceTrackingStateChanged(IMixedRealityInputSource source, IMixedRealityController controller, TrackingState state)
{
// Create input event
sourceTrackingEventData.Initialize(source, controller, state);
// Pass handler through HandleEvent to perform modal/fallback logic
HandleEvent(sourceTrackingEventData, OnSourceTrackingChangedEventHandler);
}
private static readonly ExecuteEvents.EventFunction<IMixedRealitySourcePoseHandler> OnSourceTrackingChangedEventHandler =
delegate (IMixedRealitySourcePoseHandler handler, BaseEventData eventData)
{
var casted = ExecuteEvents.ValidateEventData<SourcePoseEventData<TrackingState>>(eventData);
handler.OnSourcePoseChanged(casted);
};
/// <inheritdoc />
public void RaiseSourcePositionChanged(IMixedRealityInputSource source, IMixedRealityController controller, Vector2 position)
{
// Create input event
sourceVector2EventData.Initialize(source, controller, position);
// Pass handler through HandleEvent to perform modal/fallback logic
HandleEvent(sourceVector2EventData, OnSourcePoseVector2ChangedEventHandler);
}
private static readonly ExecuteEvents.EventFunction<IMixedRealitySourcePoseHandler> OnSourcePoseVector2ChangedEventHandler =
delegate (IMixedRealitySourcePoseHandler handler, BaseEventData eventData)
{
var casted = ExecuteEvents.ValidateEventData<SourcePoseEventData<Vector2>>(eventData);
handler.OnSourcePoseChanged(casted);
};
/// <inheritdoc />
public void RaiseSourcePositionChanged(IMixedRealityInputSource source, IMixedRealityController controller, Vector3 position)
{
// Create input event
sourcePositionEventData.Initialize(source, controller, position);
// Pass handler through HandleEvent to perform modal/fallback logic
HandleEvent(sourcePositionEventData, OnSourcePositionChangedEventHandler);
}
private static readonly ExecuteEvents.EventFunction<IMixedRealitySourcePoseHandler> OnSourcePositionChangedEventHandler =
delegate (IMixedRealitySourcePoseHandler handler, BaseEventData eventData)
{
var casted = ExecuteEvents.ValidateEventData<SourcePoseEventData<Vector3>>(eventData);
handler.OnSourcePoseChanged(casted);
};
/// <inheritdoc />
public void RaiseSourceRotationChanged(IMixedRealityInputSource source, IMixedRealityController controller, Quaternion rotation)
{
// Create input event
sourceRotationEventData.Initialize(source, controller, rotation);
// Pass handler through HandleEvent to perform modal/fallback logic
HandleEvent(sourceRotationEventData, OnSourceRotationChangedEventHandler);
}
private static readonly ExecuteEvents.EventFunction<IMixedRealitySourcePoseHandler> OnSourceRotationChangedEventHandler =
delegate (IMixedRealitySourcePoseHandler handler, BaseEventData eventData)
{
var casted = ExecuteEvents.ValidateEventData<SourcePoseEventData<Quaternion>>(eventData);
handler.OnSourcePoseChanged(casted);
};
/// <inheritdoc />
public void RaiseSourcePoseChanged(IMixedRealityInputSource source, IMixedRealityController controller, MixedRealityPose position)
{
// Create input event
sourcePoseEventData.Initialize(source, controller, position);
// Pass handler through HandleEvent to perform modal/fallback logic
HandleEvent(sourcePoseEventData, OnSourcePoseChangedEventHandler);
}
private static readonly ExecuteEvents.EventFunction<IMixedRealitySourcePoseHandler> OnSourcePoseChangedEventHandler =
delegate (IMixedRealitySourcePoseHandler handler, BaseEventData eventData)
{
var casted = ExecuteEvents.ValidateEventData<SourcePoseEventData<MixedRealityPose>>(eventData);
handler.OnSourcePoseChanged(casted);
};
#endregion Input Source Pose Events
#endregion Input Source Events
#region Focus Events
/// <inheritdoc />
public void RaisePreFocusChanged(IMixedRealityPointer pointer, GameObject oldFocusedObject, GameObject newFocusedObject)
{
focusEventData.Initialize(pointer, oldFocusedObject, newFocusedObject);
// Raise Focus Events on the old and new focused objects.
if (oldFocusedObject != null)
{
ExecuteEvents.ExecuteHierarchy(oldFocusedObject, focusEventData, OnPreFocusChangedHandler);
}
if (newFocusedObject != null)
{
ExecuteEvents.ExecuteHierarchy(newFocusedObject, focusEventData, OnPreFocusChangedHandler);
}
// Raise Focus Events on the pointers cursor if it has one.
if (pointer.BaseCursor != null)
{
try
{
// When shutting down a game, we can sometime get old references to game objects that have been cleaned up.
// We'll ignore when this happens.
ExecuteEvents.ExecuteHierarchy(pointer.BaseCursor.GameObjectReference, focusEventData, OnPreFocusChangedHandler);
}
catch (Exception)
{
// ignored.
}
}
}
private static readonly ExecuteEvents.EventFunction<IMixedRealityFocusChangedHandler> OnPreFocusChangedHandler =
delegate (IMixedRealityFocusChangedHandler handler, BaseEventData eventData)
{
var casted = ExecuteEvents.ValidateEventData<FocusEventData>(eventData);
handler.OnBeforeFocusChange(casted);
};
/// <inheritdoc />
public void RaiseFocusChanged(IMixedRealityPointer pointer, GameObject oldFocusedObject, GameObject newFocusedObject)
{
focusEventData.Initialize(pointer, oldFocusedObject, newFocusedObject);
// Raise Focus Events on the old and new focused objects.
if (oldFocusedObject != null)
{
ExecuteEvents.ExecuteHierarchy(oldFocusedObject, focusEventData, OnFocusChangedHandler);
}
if (newFocusedObject != null)
{
ExecuteEvents.ExecuteHierarchy(newFocusedObject, focusEventData, OnFocusChangedHandler);
}
// Raise Focus Events on the pointers cursor if it has one.
if (pointer.BaseCursor != null)
{
try
{
// When shutting down a game, we can sometime get old references to game objects that have been cleaned up.
// We'll ignore when this happens.
ExecuteEvents.ExecuteHierarchy(pointer.BaseCursor.GameObjectReference, focusEventData, OnFocusChangedHandler);
}
catch (Exception)
{
// ignored.
}
}
}
private static readonly ExecuteEvents.EventFunction<IMixedRealityFocusChangedHandler> OnFocusChangedHandler =
delegate (IMixedRealityFocusChangedHandler handler, BaseEventData eventData)
{
var casted = ExecuteEvents.ValidateEventData<FocusEventData>(eventData);
handler.OnFocusChanged(casted);
};
/// <inheritdoc />
public void RaiseFocusEnter(IMixedRealityPointer pointer, GameObject focusedObject)
{
focusEventData.Initialize(pointer);
ExecuteEvents.ExecuteHierarchy(focusedObject, focusEventData, OnFocusEnterEventHandler);
if (FocusProvider.TryGetSpecificPointerGraphicEventData(pointer, out GraphicInputEventData graphicEventData))
{
ExecuteEvents.ExecuteHierarchy(focusedObject, graphicEventData, ExecuteEvents.pointerEnterHandler);
}
}
private static readonly ExecuteEvents.EventFunction<IMixedRealityFocusHandler> OnFocusEnterEventHandler =
delegate (IMixedRealityFocusHandler handler, BaseEventData eventData)
{
var casted = ExecuteEvents.ValidateEventData<FocusEventData>(eventData);
handler.OnFocusEnter(casted);
};
/// <inheritdoc />
public void RaiseFocusExit(IMixedRealityPointer pointer, GameObject unfocusedObject)
{
focusEventData.Initialize(pointer);
ExecuteEvents.ExecuteHierarchy(unfocusedObject, focusEventData, OnFocusExitEventHandler);
if (FocusProvider.TryGetSpecificPointerGraphicEventData(pointer, out GraphicInputEventData graphicEventData))
{
ExecuteEvents.ExecuteHierarchy(unfocusedObject, graphicEventData, ExecuteEvents.pointerExitHandler);
}
}
private static readonly ExecuteEvents.EventFunction<IMixedRealityFocusHandler> OnFocusExitEventHandler =
delegate (IMixedRealityFocusHandler handler, BaseEventData eventData)
{
var casted = ExecuteEvents.ValidateEventData<FocusEventData>(eventData);
handler.OnFocusExit(casted);
};
#endregion Focus Events
#region Pointers
#region Pointer Down
private static readonly ExecuteEvents.EventFunction<IMixedRealityPointerHandler> OnPointerDownEventHandler =
delegate (IMixedRealityPointerHandler handler, BaseEventData eventData)
{
var casted = ExecuteEvents.ValidateEventData<MixedRealityPointerEventData>(eventData);
handler.OnPointerDown(casted);
};
/// <inheritdoc />
public void RaisePointerDown(IMixedRealityPointer pointer, MixedRealityInputAction inputAction, IMixedRealityInputSource inputSource = null)
{
// Create input event
pointerEventData.Initialize(pointer, inputAction, inputSource);
// Pass handler through HandleEvent to perform modal/fallback logic
HandleEvent(pointerEventData, OnPointerDownEventHandler);
FocusProvider.TryGetSpecificPointerGraphicEventData(pointer, out GraphicInputEventData graphicInputEventData);
if (graphicInputEventData != null && graphicInputEventData.selectedObject != null)
{
ExecuteEvents.ExecuteHierarchy(graphicInputEventData.selectedObject, graphicInputEventData, ExecuteEvents.pointerDownHandler);
}
}
#endregion Pointer Down
#region Pointer Click
private static readonly ExecuteEvents.EventFunction<IMixedRealityPointerHandler> OnInputClickedEventHandler =
delegate (IMixedRealityPointerHandler handler, BaseEventData eventData)
{
var casted = ExecuteEvents.ValidateEventData<MixedRealityPointerEventData>(eventData);
handler.OnPointerClicked(casted);
};
/// <inheritdoc />
public void RaisePointerClicked(IMixedRealityPointer pointer, MixedRealityInputAction inputAction, int count, IMixedRealityInputSource inputSource = null)
{
// Create input event
pointerEventData.Initialize(pointer, inputAction, inputSource, count);
// Pass handler through HandleEvent to perform modal/fallback logic
HandleEvent(pointerEventData, OnInputClickedEventHandler);
// NOTE: In Unity UI, a "click" happens on every pointer up, so we have RaisePointerUp call the pointerClickHandler.
}
#endregion Pointer Click
#region Pointer Up
private static readonly ExecuteEvents.EventFunction<IMixedRealityPointerHandler> OnPointerUpEventHandler =
delegate (IMixedRealityPointerHandler handler, BaseEventData eventData)
{
var casted = ExecuteEvents.ValidateEventData<MixedRealityPointerEventData>(eventData);
handler.OnPointerUp(casted);
};
/// <inheritdoc />
public void RaisePointerUp(IMixedRealityPointer pointer, MixedRealityInputAction inputAction, IMixedRealityInputSource inputSource = null)
{
// Create input event
pointerEventData.Initialize(pointer, inputAction);
// Pass handler through HandleEvent to perform modal/fallback logic
HandleEvent(pointerEventData, OnPointerUpEventHandler);
FocusProvider.TryGetSpecificPointerGraphicEventData(pointer, out GraphicInputEventData graphicInputEventData);
if (graphicInputEventData != null)
{
if (graphicInputEventData.selectedObject != null)
{
ExecuteEvents.ExecuteHierarchy(graphicInputEventData.selectedObject, graphicInputEventData, ExecuteEvents.pointerUpHandler);
ExecuteEvents.ExecuteHierarchy(graphicInputEventData.selectedObject, graphicInputEventData, ExecuteEvents.pointerClickHandler);
}
graphicInputEventData.Clear();
}
}
#endregion Pointer Up
#endregion Pointers
#region Generic Input Events
#region Input Down
private static readonly ExecuteEvents.EventFunction<IMixedRealityInputHandler> OnInputDownEventHandler =
delegate (IMixedRealityInputHandler handler, BaseEventData eventData)
{
var casted = ExecuteEvents.ValidateEventData<InputEventData>(eventData);
handler.OnInputDown(casted);
};
/// <inheritdoc />
public void RaiseOnInputDown(IMixedRealityInputSource source, MixedRealityInputAction inputAction)
{
RaiseOnInputDown(source, Handedness.None, inputAction);
}
/// <inheritdoc />
public void RaiseOnInputDown(IMixedRealityInputSource source, Handedness handedness, MixedRealityInputAction inputAction)
{
Debug.Assert(DetectedInputSources.Contains(source));
inputAction = ProcessRules(inputAction, true);
// Create input event
inputEventData.Initialize(source, handedness, inputAction);
// Pass handler through HandleEvent to perform modal/fallback logic
HandleEvent(inputEventData, OnInputDownEventHandler);
}
#endregion Input Down
#region Input Pressed
/// <inheritdoc />
public void RaiseOnInputPressed(IMixedRealityInputSource source, MixedRealityInputAction inputAction)
{
RaiseOnInputPressed(source, Handedness.None, inputAction);
}
/// <inheritdoc />
public void RaiseOnInputPressed(IMixedRealityInputSource source, Handedness handedness, MixedRealityInputAction inputAction)
{
Debug.Assert(DetectedInputSources.Contains(source));
inputAction = ProcessRules(inputAction, true);
// Create input event
floatInputEventData.Initialize(source, handedness, inputAction);
// Pass handler through HandleEvent to perform modal/fallback logic
HandleEvent(floatInputEventData, SingleAxisInputEventHandler);
}
/// <inheritdoc />
public void RaiseOnInputPressed(IMixedRealityInputSource source, MixedRealityInputAction inputAction, float pressAmount)
{
RaiseOnInputPressed(source, Handedness.None, inputAction, pressAmount);
}
/// <inheritdoc />
public void RaiseOnInputPressed(IMixedRealityInputSource source, Handedness handedness, MixedRealityInputAction inputAction, float pressAmount)
{
Debug.Assert(DetectedInputSources.Contains(source));
inputAction = ProcessRules(inputAction, pressAmount);
// Create input event
floatInputEventData.Initialize(source, handedness, inputAction, pressAmount);
// Pass handler through HandleEvent to perform modal/fallback logic
HandleEvent(floatInputEventData, SingleAxisInputEventHandler);
}
#endregion Input Pressed
#region Input Up
private static readonly ExecuteEvents.EventFunction<IMixedRealityInputHandler> OnInputUpEventHandler =
delegate (IMixedRealityInputHandler handler, BaseEventData eventData)
{
var casted = ExecuteEvents.ValidateEventData<InputEventData>(eventData);
handler.OnInputUp(casted);
};
/// <inheritdoc />
public void RaiseOnInputUp(IMixedRealityInputSource source, MixedRealityInputAction inputAction)
{
RaiseOnInputUp(source, Handedness.None, inputAction);
}
/// <inheritdoc />
public void RaiseOnInputUp(IMixedRealityInputSource source, Handedness handedness, MixedRealityInputAction inputAction)
{
Debug.Assert(DetectedInputSources.Contains(source));
inputAction = ProcessRules(inputAction, false);
// Create input event
inputEventData.Initialize(source, handedness, inputAction);
// Pass handler through HandleEvent to perform modal/fallback logic
HandleEvent(inputEventData, OnInputUpEventHandler);
}
#endregion Input Up
#region Input Position Changed
private static readonly ExecuteEvents.EventFunction<IMixedRealityInputHandler<float>> SingleAxisInputEventHandler =
delegate (IMixedRealityInputHandler<float> handler, BaseEventData eventData)
{
var casted = ExecuteEvents.ValidateEventData<InputEventData<float>>(eventData);
handler.OnInputChanged(casted);
};
/// <inheritdoc />
public void RaisePositionInputChanged(IMixedRealityInputSource source, MixedRealityInputAction inputAction, float inputPosition)
{
RaisePositionInputChanged(source, Handedness.None, inputAction, inputPosition);
}
/// <inheritdoc />
public void RaisePositionInputChanged(IMixedRealityInputSource source, Handedness handedness, MixedRealityInputAction inputAction, float inputPosition)
{
Debug.Assert(DetectedInputSources.Contains(source));
inputAction = ProcessRules(inputAction, inputPosition);
// Create input event
floatInputEventData.Initialize(source, handedness, inputAction, inputPosition);
// Pass handler through HandleEvent to perform modal/fallback logic
HandleEvent(floatInputEventData, SingleAxisInputEventHandler);
}
private static readonly ExecuteEvents.EventFunction<IMixedRealityInputHandler<Vector2>> OnTwoDoFInputChanged =
delegate (IMixedRealityInputHandler<Vector2> handler, BaseEventData eventData)
{
var casted = ExecuteEvents.ValidateEventData<InputEventData<Vector2>>(eventData);
handler.OnInputChanged(casted);
};
/// <inheritdoc />
public void RaisePositionInputChanged(IMixedRealityInputSource source, MixedRealityInputAction inputAction, Vector2 inputPosition)
{
RaisePositionInputChanged(source, Handedness.None, inputAction, inputPosition);
}
/// <inheritdoc />
public void RaisePositionInputChanged(IMixedRealityInputSource source, Handedness handedness, MixedRealityInputAction inputAction, Vector2 inputPosition)
{
Debug.Assert(DetectedInputSources.Contains(source));
inputAction = ProcessRules(inputAction, inputPosition);
// Create input event
vector2InputEventData.Initialize(source, handedness, inputAction, inputPosition);
// Pass handler through HandleEvent to perform modal/fallback logic
HandleEvent(vector2InputEventData, OnTwoDoFInputChanged);
}
private static readonly ExecuteEvents.EventFunction<IMixedRealityInputHandler<Vector3>> OnPositionInputChanged =
delegate (IMixedRealityInputHandler<Vector3> handler, BaseEventData eventData)
{
var casted = ExecuteEvents.ValidateEventData<InputEventData<Vector3>>(eventData);
handler.OnInputChanged(casted);
};
/// <inheritdoc />
public void RaisePositionInputChanged(IMixedRealityInputSource source, MixedRealityInputAction inputAction, Vector3 position)
{
RaisePositionInputChanged(source, Handedness.None, inputAction, position);
}
/// <inheritdoc />
public void RaisePositionInputChanged(IMixedRealityInputSource source, Handedness handedness, MixedRealityInputAction inputAction, Vector3 position)
{
Debug.Assert(DetectedInputSources.Contains(source));
inputAction = ProcessRules(inputAction, position);
// Create input event
positionInputEventData.Initialize(source, handedness, inputAction, position);
// Pass handler through HandleEvent to perform modal/fallback logic
HandleEvent(positionInputEventData, OnPositionInputChanged);
}
#endregion Input Position Changed
#region Input Rotation Changed
private static readonly ExecuteEvents.EventFunction<IMixedRealityInputHandler<Quaternion>> OnRotationInputChanged =
delegate (IMixedRealityInputHandler<Quaternion> handler, BaseEventData eventData)
{
var casted = ExecuteEvents.ValidateEventData<InputEventData<Quaternion>>(eventData);
handler.OnInputChanged(casted);
};
/// <inheritdoc />
public void RaiseRotationInputChanged(IMixedRealityInputSource source, MixedRealityInputAction inputAction, Quaternion rotation)
{
RaiseRotationInputChanged(source, Handedness.None, inputAction, rotation);
}
/// <inheritdoc />
public void RaiseRotationInputChanged(IMixedRealityInputSource source, Handedness handedness, MixedRealityInputAction inputAction, Quaternion rotation)
{
Debug.Assert(DetectedInputSources.Contains(source));
inputAction = ProcessRules(inputAction, rotation);
// Create input event
rotationInputEventData.Initialize(source, handedness, inputAction, rotation);
// Pass handler through HandleEvent to perform modal/fallback logic
HandleEvent(positionInputEventData, OnRotationInputChanged);
}
#endregion Input Rotation Changed
#region Input Pose Changed
private static readonly ExecuteEvents.EventFunction<IMixedRealityInputHandler<MixedRealityPose>> OnPoseInputChanged =
delegate (IMixedRealityInputHandler<MixedRealityPose> handler, BaseEventData eventData)
{
var casted = ExecuteEvents.ValidateEventData<InputEventData<MixedRealityPose>>(eventData);
handler.OnInputChanged(casted);
};
/// <inheritdoc />
public void RaisePoseInputChanged(IMixedRealityInputSource source, MixedRealityInputAction inputAction, MixedRealityPose inputData)
{
RaisePoseInputChanged(source, Handedness.None, inputAction, inputData);
}
/// <inheritdoc />
public void RaisePoseInputChanged(IMixedRealityInputSource source, Handedness handedness, MixedRealityInputAction inputAction, MixedRealityPose inputData)
{
Debug.Assert(DetectedInputSources.Contains(source));
inputAction = ProcessRules(inputAction, inputData);
// Create input event
poseInputEventData.Initialize(source, handedness, inputAction, inputData);
// Pass handler through HandleEvent to perform modal/fallback logic
HandleEvent(poseInputEventData, OnPoseInputChanged);
}
#endregion Input Pose Changed
#endregion Generic Input Events
#region Gesture Events
private static readonly ExecuteEvents.EventFunction<IMixedRealityGestureHandler> OnGestureStarted =
delegate (IMixedRealityGestureHandler handler, BaseEventData eventData)
{
var casted = ExecuteEvents.ValidateEventData<InputEventData>(eventData);
handler.OnGestureStarted(casted);
};
/// <inheritdoc />
public void RaiseGestureStarted(IMixedRealityController controller, MixedRealityInputAction action)
{
Debug.Assert(DetectedInputSources.Contains(controller.InputSource));
action = ProcessRules(action, true);
inputEventData.Initialize(controller.InputSource, controller.ControllerHandedness, action);
HandleEvent(inputEventData, OnGestureStarted);
}
private static readonly ExecuteEvents.EventFunction<IMixedRealityGestureHandler> OnGestureUpdated =
delegate (IMixedRealityGestureHandler handler, BaseEventData eventData)
{
var casted = ExecuteEvents.ValidateEventData<InputEventData>(eventData);
handler.OnGestureUpdated(casted);
};
/// <inheritdoc />
public void RaiseGestureUpdated(IMixedRealityController controller, MixedRealityInputAction action)
{
Debug.Assert(DetectedInputSources.Contains(controller.InputSource));
action = ProcessRules(action, true);
inputEventData.Initialize(controller.InputSource, controller.ControllerHandedness, action);
HandleEvent(inputEventData, OnGestureUpdated);
}
private static readonly ExecuteEvents.EventFunction<IMixedRealityGestureHandler<Vector2>> OnGestureVector2PositionUpdated =
delegate (IMixedRealityGestureHandler<Vector2> handler, BaseEventData eventData)
{
var casted = ExecuteEvents.ValidateEventData<InputEventData<Vector2>>(eventData);
handler.OnGestureUpdated(casted);
};
/// <inheritdoc />
public void RaiseGestureUpdated(IMixedRealityController controller, MixedRealityInputAction action, Vector2 inputData)
{
Debug.Assert(DetectedInputSources.Contains(controller.InputSource));
action = ProcessRules(action, inputData);
vector2InputEventData.Initialize(controller.InputSource, controller.ControllerHandedness, action, inputData);
HandleEvent(vector2InputEventData, OnGestureVector2PositionUpdated);
}
private static readonly ExecuteEvents.EventFunction<IMixedRealityGestureHandler<Vector3>> OnGesturePositionUpdated =
delegate (IMixedRealityGestureHandler<Vector3> handler, BaseEventData eventData)
{
var casted = ExecuteEvents.ValidateEventData<InputEventData<Vector3>>(eventData);
handler.OnGestureUpdated(casted);
};
/// <inheritdoc />
public void RaiseGestureUpdated(IMixedRealityController controller, MixedRealityInputAction action, Vector3 inputData)
{
Debug.Assert(DetectedInputSources.Contains(controller.InputSource));
action = ProcessRules(action, inputData);
positionInputEventData.Initialize(controller.InputSource, controller.ControllerHandedness, action, inputData);
HandleEvent(positionInputEventData, OnGesturePositionUpdated);
}
private static readonly ExecuteEvents.EventFunction<IMixedRealityGestureHandler<Quaternion>> OnGestureRotationUpdated =
delegate (IMixedRealityGestureHandler<Quaternion> handler, BaseEventData eventData)
{
var casted = ExecuteEvents.ValidateEventData<InputEventData<Quaternion>>(eventData);
handler.OnGestureUpdated(casted);
};
/// <inheritdoc />
public void RaiseGestureUpdated(IMixedRealityController controller, MixedRealityInputAction action, Quaternion inputData)
{
Debug.Assert(DetectedInputSources.Contains(controller.InputSource));
action = ProcessRules(action, inputData);
rotationInputEventData.Initialize(controller.InputSource, controller.ControllerHandedness, action, inputData);
HandleEvent(rotationInputEventData, OnGestureRotationUpdated);
}
private static readonly ExecuteEvents.EventFunction<IMixedRealityGestureHandler<MixedRealityPose>> OnGesturePoseUpdated =
delegate (IMixedRealityGestureHandler<MixedRealityPose> handler, BaseEventData eventData)
{
var casted = ExecuteEvents.ValidateEventData<InputEventData<MixedRealityPose>>(eventData);
handler.OnGestureUpdated(casted);
};
/// <inheritdoc />
public void RaiseGestureUpdated(IMixedRealityController controller, MixedRealityInputAction action, MixedRealityPose inputData)
{
Debug.Assert(DetectedInputSources.Contains(controller.InputSource));
action = ProcessRules(action, inputData);
poseInputEventData.Initialize(controller.InputSource, controller.ControllerHandedness, action, inputData);
HandleEvent(poseInputEventData, OnGesturePoseUpdated);
}
private static readonly ExecuteEvents.EventFunction<IMixedRealityGestureHandler> OnGestureCompleted =
delegate (IMixedRealityGestureHandler handler, BaseEventData eventData)
{
var casted = ExecuteEvents.ValidateEventData<InputEventData>(eventData);
handler.OnGestureCompleted(casted);
};
/// <inheritdoc />
public void RaiseGestureCompleted(IMixedRealityController controller, MixedRealityInputAction action)
{
Debug.Assert(DetectedInputSources.Contains(controller.InputSource));
action = ProcessRules(action, false);
inputEventData.Initialize(controller.InputSource, controller.ControllerHandedness, action);
HandleEvent(inputEventData, OnGestureCompleted);
}
private static readonly ExecuteEvents.EventFunction<IMixedRealityGestureHandler<Vector2>> OnGestureVector2PositionCompleted =
delegate (IMixedRealityGestureHandler<Vector2> handler, BaseEventData eventData)
{
var casted = ExecuteEvents.ValidateEventData<InputEventData<Vector2>>(eventData);
handler.OnGestureCompleted(casted);
};
/// <inheritdoc />
public void RaiseGestureCompleted(IMixedRealityController controller, MixedRealityInputAction action, Vector2 inputData)
{
Debug.Assert(DetectedInputSources.Contains(controller.InputSource));
action = ProcessRules(action, inputData);
vector2InputEventData.Initialize(controller.InputSource, controller.ControllerHandedness, action, inputData);
HandleEvent(vector2InputEventData, OnGestureVector2PositionCompleted);
}
private static readonly ExecuteEvents.EventFunction<IMixedRealityGestureHandler<Vector3>> OnGesturePositionCompleted =
delegate (IMixedRealityGestureHandler<Vector3> handler, BaseEventData eventData)
{
var casted = ExecuteEvents.ValidateEventData<InputEventData<Vector3>>(eventData);
handler.OnGestureCompleted(casted);
};
/// <inheritdoc />
public void RaiseGestureCompleted(IMixedRealityController controller, MixedRealityInputAction action, Vector3 inputData)
{
Debug.Assert(DetectedInputSources.Contains(controller.InputSource));
action = ProcessRules(action, inputData);
positionInputEventData.Initialize(controller.InputSource, controller.ControllerHandedness, action, inputData);
HandleEvent(positionInputEventData, OnGesturePositionCompleted);
}
private static readonly ExecuteEvents.EventFunction<IMixedRealityGestureHandler<Quaternion>> OnGestureRotationCompleted =
delegate (IMixedRealityGestureHandler<Quaternion> handler, BaseEventData eventData)
{
var casted = ExecuteEvents.ValidateEventData<InputEventData<Quaternion>>(eventData);
handler.OnGestureCompleted(casted);
};
/// <inheritdoc />
public void RaiseGestureCompleted(IMixedRealityController controller, MixedRealityInputAction action, Quaternion inputData)
{
Debug.Assert(DetectedInputSources.Contains(controller.InputSource));
action = ProcessRules(action, inputData);
rotationInputEventData.Initialize(controller.InputSource, controller.ControllerHandedness, action, inputData);
HandleEvent(rotationInputEventData, OnGestureRotationCompleted);
}
private static readonly ExecuteEvents.EventFunction<IMixedRealityGestureHandler<MixedRealityPose>> OnGesturePoseCompleted =
delegate (IMixedRealityGestureHandler<MixedRealityPose> handler, BaseEventData eventData)
{
var casted = ExecuteEvents.ValidateEventData<InputEventData<MixedRealityPose>>(eventData);
handler.OnGestureCompleted(casted);
};
/// <inheritdoc />
public void RaiseGestureCompleted(IMixedRealityController controller, MixedRealityInputAction action, MixedRealityPose inputData)
{
Debug.Assert(DetectedInputSources.Contains(controller.InputSource));
action = ProcessRules(action, inputData);
poseInputEventData.Initialize(controller.InputSource, controller.ControllerHandedness, action, inputData);
HandleEvent(poseInputEventData, OnGesturePoseCompleted);
}
private static readonly ExecuteEvents.EventFunction<IMixedRealityGestureHandler> OnGestureCanceled =
delegate (IMixedRealityGestureHandler handler, BaseEventData eventData)
{
var casted = ExecuteEvents.ValidateEventData<InputEventData>(eventData);
handler.OnGestureCanceled(casted);
};
/// <inheritdoc />
public void RaiseGestureCanceled(IMixedRealityController controller, MixedRealityInputAction action)
{
Debug.Assert(DetectedInputSources.Contains(controller.InputSource));
action = ProcessRules(action, false);
inputEventData.Initialize(controller.InputSource, controller.ControllerHandedness, action);
HandleEvent(inputEventData, OnGestureCanceled);
}
#endregion Gesture Events
#region Speech Keyword Events
private static readonly ExecuteEvents.EventFunction<IMixedRealitySpeechHandler> OnSpeechKeywordRecognizedEventHandler =
delegate (IMixedRealitySpeechHandler handler, BaseEventData eventData)
{
var casted = ExecuteEvents.ValidateEventData<SpeechEventData>(eventData);
handler.OnSpeechKeywordRecognized(casted);
};
/// <inheritdoc />
public void RaiseSpeechCommandRecognized(IMixedRealityInputSource source, MixedRealityInputAction inputAction, RecognitionConfidenceLevel confidence, TimeSpan phraseDuration, DateTime phraseStartTime, string text)
{
Debug.Assert(DetectedInputSources.Contains(source));
// Create input event
speechEventData.Initialize(source, inputAction, confidence, phraseDuration, phraseStartTime, text);
// Pass handler through HandleEvent to perform modal/fallback logic
HandleEvent(speechEventData, OnSpeechKeywordRecognizedEventHandler);
}
#endregion Speech Keyword Events
#region Dictation Events
private static readonly ExecuteEvents.EventFunction<IMixedRealityDictationHandler> OnDictationHypothesisEventHandler =
delegate (IMixedRealityDictationHandler handler, BaseEventData eventData)
{
var casted = ExecuteEvents.ValidateEventData<DictationEventData>(eventData);
handler.OnDictationHypothesis(casted);
};
/// <inheritdoc />
public void RaiseDictationHypothesis(IMixedRealityInputSource source, string dictationHypothesis, AudioClip dictationAudioClip = null)
{
Debug.Assert(DetectedInputSources.Contains(source));
// Create input event
dictationEventData.Initialize(source, dictationHypothesis, dictationAudioClip);
// Pass handler through HandleEvent to perform modal/fallback logic
HandleEvent(dictationEventData, OnDictationHypothesisEventHandler);
}
private static readonly ExecuteEvents.EventFunction<IMixedRealityDictationHandler> OnDictationResultEventHandler =
delegate (IMixedRealityDictationHandler handler, BaseEventData eventData)
{
var casted = ExecuteEvents.ValidateEventData<DictationEventData>(eventData);
handler.OnDictationResult(casted);
};
/// <inheritdoc />
public void RaiseDictationResult(IMixedRealityInputSource source, string dictationResult, AudioClip dictationAudioClip = null)
{
Debug.Assert(DetectedInputSources.Contains(source));
// Create input event
dictationEventData.Initialize(source, dictationResult, dictationAudioClip);
// Pass handler through HandleEvent to perform modal/fallback logic
HandleEvent(dictationEventData, OnDictationResultEventHandler);
}
private static readonly ExecuteEvents.EventFunction<IMixedRealityDictationHandler> OnDictationCompleteEventHandler =
delegate (IMixedRealityDictationHandler handler, BaseEventData eventData)
{
var casted = ExecuteEvents.ValidateEventData<DictationEventData>(eventData);
handler.OnDictationComplete(casted);
};
/// <inheritdoc />
public void RaiseDictationComplete(IMixedRealityInputSource source, string dictationResult, AudioClip dictationAudioClip)
{
Debug.Assert(DetectedInputSources.Contains(source));
// Create input event
dictationEventData.Initialize(source, dictationResult, dictationAudioClip);
// Pass handler through HandleEvent to perform modal/fallback logic
HandleEvent(dictationEventData, OnDictationCompleteEventHandler);
}
private static readonly ExecuteEvents.EventFunction<IMixedRealityDictationHandler> OnDictationErrorEventHandler =
delegate (IMixedRealityDictationHandler handler, BaseEventData eventData)
{
var casted = ExecuteEvents.ValidateEventData<DictationEventData>(eventData);
handler.OnDictationError(casted);
};
/// <inheritdoc />
public void RaiseDictationError(IMixedRealityInputSource source, string dictationResult, AudioClip dictationAudioClip = null)
{
Debug.Assert(DetectedInputSources.Contains(source));
// Create input event
dictationEventData.Initialize(source, dictationResult, dictationAudioClip);
// Pass handler through HandleEvent to perform modal/fallback logic
HandleEvent(dictationEventData, OnDictationErrorEventHandler);
}
#endregion Dictation Events
#endregion Input Events
#region Rules
private static MixedRealityInputAction ProcessRules_Internal<T1, T2>(MixedRealityInputAction inputAction, T1[] inputActionRules, T2 criteria) where T1 : struct, IInputActionRule<T2>
{
for (int i = 0; i < inputActionRules.Length; i++)
{
if (inputActionRules[i].BaseAction == inputAction && inputActionRules[i].Criteria.Equals(criteria))
{
if (inputActionRules[i].RuleAction == inputAction)
{
Debug.LogError("Input Action Rule cannot be the same as the rule's Base Action!");
return inputAction;
}
if (inputActionRules[i].BaseAction.AxisConstraint != inputActionRules[i].RuleAction.AxisConstraint)
{
Debug.LogError("Input Action Rule doesn't have the same Axis Constraint as the Base Action!");
return inputAction;
}
return inputActionRules[i].RuleAction;
}
}
return inputAction;
}
private MixedRealityInputAction ProcessRules(MixedRealityInputAction inputAction, bool criteria)
{
if (CurrentInputActionRulesProfile != null && CurrentInputActionRulesProfile.InputActionRulesDigital?.Length > 0)
{
return ProcessRules_Internal(inputAction, CurrentInputActionRulesProfile.InputActionRulesDigital, criteria);
}
return inputAction;
}
private MixedRealityInputAction ProcessRules(MixedRealityInputAction inputAction, float criteria)
{
if (CurrentInputActionRulesProfile != null && CurrentInputActionRulesProfile.InputActionRulesSingleAxis?.Length > 0)
{
return ProcessRules_Internal(inputAction, CurrentInputActionRulesProfile.InputActionRulesSingleAxis, criteria);
}
return inputAction;
}
private MixedRealityInputAction ProcessRules(MixedRealityInputAction inputAction, Vector2 criteria)
{
if (CurrentInputActionRulesProfile != null && CurrentInputActionRulesProfile.InputActionRulesDualAxis?.Length > 0)
{
return ProcessRules_Internal(inputAction, CurrentInputActionRulesProfile.InputActionRulesDualAxis, criteria);
}
return inputAction;
}
private MixedRealityInputAction ProcessRules(MixedRealityInputAction inputAction, Vector3 criteria)
{
if (CurrentInputActionRulesProfile != null && CurrentInputActionRulesProfile.InputActionRulesVectorAxis?.Length > 0)
{
return ProcessRules_Internal(inputAction, CurrentInputActionRulesProfile.InputActionRulesVectorAxis, criteria);
}
return inputAction;
}
private MixedRealityInputAction ProcessRules(MixedRealityInputAction inputAction, Quaternion criteria)
{
if (CurrentInputActionRulesProfile != null && CurrentInputActionRulesProfile.InputActionRulesQuaternionAxis?.Length > 0)
{
return ProcessRules_Internal(inputAction, CurrentInputActionRulesProfile.InputActionRulesQuaternionAxis, criteria);
}
return inputAction;
}
private MixedRealityInputAction ProcessRules(MixedRealityInputAction inputAction, MixedRealityPose criteria)
{
if (CurrentInputActionRulesProfile != null && CurrentInputActionRulesProfile.InputActionRulesPoseAxis?.Length > 0)
{
return ProcessRules_Internal(inputAction, CurrentInputActionRulesProfile.InputActionRulesPoseAxis, criteria);
}
return inputAction;
}
#endregion Rules
}
}
| |
#region License
/*
* Copyright (C) 2002-2008 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
#region Imports
using System;
using System.Collections.Generic;
#endregion
namespace Spring.Collections.Generic
{
/// <summary>
/// A bounded <see cref="IQueue{T}"/> backed by an array. This queue orders
/// elements FIFO (first-in-first-out). The <i>head</i> of the queue is
/// that element that has been on the queue the longest time. The <i>tail</i>
/// of the queue is that element that has been on the queue the shortest time.
/// New elements are inserted at the tail of the queue, and the queue retrieval
/// operations obtain elements at the head of the queue.
/// </summary>
/// <remarks>
/// <para>
/// This is a classic "bounded buffer", in which a fixed-sized array
/// holds elements inserted by producers and extracted by consumers. Once
/// created, the capacity cannot be increased.
/// </para>
/// </remarks>
/// <author>Doug Lea</author>
/// <author>Griffin Caprio (.NET)</author>
/// <author>Kenneth Xu</author>
[Serializable]
public class ArrayQueue<T> : AbstractQueue<T>
{
/// <summary>
/// The intial capacity of this queue.
/// </summary>
private int _capacity;
/// <summary>Number of items in the queue </summary>
private int _count;
/// <summary>The queued items </summary>
private T[] _items;
/// <summary>items index for next take, poll or remove </summary>
[NonSerialized] private int _takeIndex;
/// <summary>items index for next put, offer, or add. </summary>
[NonSerialized] private int _putIndex;
#region Private Methods
/// <summary>
/// Utility for remove and iterator.remove: Delete item at position <paramref name="index"/>.
/// Call only when holding lock.
/// </summary>
internal virtual void removeAt(int index)
{
T[] items = _items;
if (index == _takeIndex)
{
items[_takeIndex] = default(T);
_takeIndex = increment(_takeIndex);
}
else
{
for (;; )
{
int nextIndex = increment(index);
if (nextIndex != _putIndex)
{
items[index] = items[nextIndex];
index = nextIndex;
}
else
{
items[index] = default(T);
_putIndex = index;
break;
}
}
}
--_count;
}
/// <summary> Circularly increment i.</summary>
private int increment(int index)
{
return (++index == _items.Length) ? 0 : index;
}
/// <summary>
/// Inserts element at current put position, advances, and signals.
/// Call only when holding lock.
/// </summary>
private void insert(T x)
{
_items[_putIndex] = x;
_putIndex = increment(_putIndex);
++_count;
}
/// <summary>
/// Extracts element at current take position, advances, and signals.
/// Call only when holding lock.
/// </summary>
private T extract()
{
T[] items = _items;
T x = items[_takeIndex];
items[_takeIndex] = default(T);
_takeIndex = increment(_takeIndex);
--_count;
return x;
}
#endregion
#region Constructors
/// <summary>
/// Creates an <see cref="ArrayQueue{T}"/> with the given (fixed)
/// <paramref name="capacity"/> and initially containing the elements
/// of the given collection, added in traversal order of the
/// collection's iterator.
/// </summary>
/// <param name="capacity">
/// The capacity of this queue.
/// </param>
/// <param name="collection">
/// The collection of elements to initially contain.
/// </param>
/// <exception cref="ArgumentOutOfRangeException">
/// If <paramref name="capacity"/> is less than 1 or is less than the
/// size of <pararef name="collection"/>.
/// </exception>
/// <exception cref="ArgumentNullException">
/// If <paramref name="collection"/> is <see langword="null"/>.
/// </exception>
public ArrayQueue(int capacity, IEnumerable<T> collection) : this(capacity)
{
if (collection == null)
throw new ArgumentNullException("collection");
foreach (T currentObject in collection)
{
if(_count >= capacity)
{
throw new ArgumentOutOfRangeException(
"collection", collection, "Collection size greater than queue capacity");
}
insert(currentObject);
}
}
/// <summary>
/// Creates an <see cref="ArrayQueue{T}"/> with the given (fixed)
/// <paramref name="capacity"/> and default fairness access policy.
/// </summary>
/// <param name="capacity">
/// The capacity of this queue.
/// </param>
/// <exception cref="ArgumentOutOfRangeException">
/// If <paramref name="capacity"/> is less than 1.
/// </exception>
public ArrayQueue(int capacity)
{
if (capacity <= 0)
throw new ArgumentOutOfRangeException(
"capacity", capacity, "Must not be negative");
_capacity = capacity;
_items = new T[capacity];
}
#endregion
/// <summary>
/// Clear the queue without locking, this is for subclass to provide
/// the clear implementation without worrying about concurrency.
/// </summary>
public override void Clear()
{
T[] items = _items;
int i = _takeIndex;
int k = _count;
while (k-- > 0)
{
items[i] = default(T);
i = increment(i);
}
_count = 0;
_putIndex = 0;
_takeIndex = 0;
}
/// <summary>
///
/// </summary>
public override int Capacity
{
get { return _capacity; }
}
/// <summary>
/// Returns <see langword="true"/> if this queue contains the specified element.
/// </summary>
/// <remarks>
/// More formally, returns <see langword="true"/> if and only if this queue contains
/// at least one element <i>element</i> such that <i>elementToSearchFor.equals(element)</i>.
/// </remarks>
/// <param name="elementToSearchFor">object to be checked for containment in this queue</param>
/// <returns> <see langword="true"/> if this queue contains the specified element</returns>
public override bool Contains(T elementToSearchFor)
{
T[] items = _items;
int i = _takeIndex;
int k = 0;
while (k++ < _count)
{
if (elementToSearchFor.Equals(items[i]))
return true;
i = increment(i);
}
return false;
}
/// <summary>
/// Removes a single instance of the specified element from this queue,
/// if it is present. More formally, removes an <i>element</i> such
/// that <i>elementToRemove.Equals(element)</i>, if this queue contains one or more such
/// elements.
/// </summary>
/// <param name="elementToRemove">element to be removed from this queue, if present
/// </param>
/// <returns> <see langword="true"/> if this queue contained the specified element or
/// if this queue changed as a result of the call, <see langword="false"/> otherwise
/// </returns>
public override bool Remove(T elementToRemove)
{
T[] items = _items;
int currentIndex = _takeIndex;
int currentStep = 0;
for (;;)
{
if (currentStep++ >= _count)
return false;
if (elementToRemove.Equals(items[currentIndex]))
{
removeAt(currentIndex);
return true;
}
currentIndex = increment(currentIndex);
}
}
/// <summary>
/// Gets the capacity of the queue.
/// </summary>
public override int RemainingCapacity
{
get { return _capacity - _count; }
}
/// <summary>
/// Returns the number of elements in this queue.
/// </summary>
/// <returns> the number of elements in this queue</returns>
public override int Count
{
get { return _count; }
}
/// <summary>
/// Inserts the specified element into this queue if it is possible to do
/// so immediately without violating capacity restrictions.
/// </summary>
/// <remarks>
/// <p/>
/// When using a capacity-restricted queue, this method is generally
/// preferable to <see cref="ArgumentException"/>,
/// which can fail to insert an element only by throwing an exception.
/// </remarks>
/// <param name="element">
/// The element to add.
/// </param>
/// <returns>
/// <see langword="true"/> if the element was added to this queue.
/// </returns>
/// <exception cref="object">
/// If the element cannot be added at this time due to capacity restrictions.
/// </exception>
/// <exception cref="ArgumentNullException">
/// If the supplied <paramref name="element"/> is <see langword="null"/>
/// and this queue does not permit <see langword="null"/> elements.
/// </exception>
/// <exception cref="InvalidOperationException">
/// If some property of the supplied <paramref name="element"/> prevents
/// it from being added to this queue.
/// </exception>
public override bool Offer(T element)
{
if (_count == _items.Length)
return false;
else
{
insert(element);
return true;
}
}
/// <summary>
/// Retrieves and removes the head of this queue.
/// </summary>
/// <remarks>
/// <p/>
/// This method differs from <see cref="IQueue{T}.Poll"/>
/// only in that it throws an exception if this queue is empty.
/// </remarks>
/// <returns>
/// The head of this queue
/// </returns>
/// <exception cref="Spring.Collections.NoElementsException">if this queue is empty</exception>
public override T Remove()
{
if (_count == 0)
throw new NoElementsException("Queue is empty.");
T x = extract();
return x;
}
/// <summary>
/// Retrieves and removes the head of this queue,
/// or returns <see langword="null"/> if this queue is empty.
/// </summary>
/// <returns>
/// The head of this queue, or <see langword="null"/> if this queue is empty.
/// </returns>
public override bool Poll(out T element)
{
bool notEmpty = _count > 0;
element = notEmpty ? extract() : default(T);
return notEmpty;
}
/// <summary>
/// Retrieves, but does not remove, the head of this queue,
/// or returns <see langword="null"/> if this queue is empty.
/// </summary>
/// <returns>
/// The head of this queue, or <see langword="null"/> if this queue is empty.
/// </returns>
public override bool Peek(out T element)
{
bool notEmpty = (_count > 0);
element = notEmpty ? _items[_takeIndex] : default(T);
return notEmpty;
}
/// <summary>
/// Returns an array of <typeparamref name="T"/> containing all of the
/// elements in this queue, in proper sequence.
/// </summary>
/// <remarks>
/// The returned array will be "safe" in that no references to it are
/// maintained by this queue. (In other words, this method must allocate
/// a new array). The caller is thus free to modify the returned array.
/// </remarks>
/// <returns> an <c>T[]</c> containing all of the elements in this queue</returns>
public T[] ToArray()
{
T[] items = _items;
T[] a = new T[_count];
int k = 0;
int i = _takeIndex;
while (k < _count)
{
a[k++] = items[i];
i = increment(i);
}
return a;
}
/// <summary>
/// Returns an array containing all of the elements in this queue, in
/// proper sequence; the runtime type of the returned array is that of
/// the specified array.
/// </summary>
/// <remarks>
/// If the queue fits in the specified array, it
/// is returned therein. Otherwise, a new array is allocated with the
/// runtime type of the specified array and the size of this queue.
///
/// <p/>
/// If this queue fits in the specified array with room to spare
/// (i.e., the array has more elements than this queue), the element in
/// the array immediately following the end of the queue is set to
/// <see langword="null"/>.
///
/// <p/>
/// Like the <see cref="ToArray()"/> method,
/// this method acts as bridge between
/// array-based and collection-based APIs. Further, this method allows
/// precise control over the runtime type of the output array, and may,
/// under certain circumstances, be used to save allocation costs.
///
/// <p/>
/// Suppose <i>x</i> is a queue known to contain only strings.
/// The following code can be used to dump the queue into a newly
/// allocated array of <see cref="System.String"/> objects:
///
/// <code>
/// string[] y = x.ToArray(new string[0]);
/// </code>
///
/// Note that <see cref="ToArray(T[])"/> with an empty
/// arry is identical in function to
/// <see cref="ToArray()"/>.
/// </remarks>
/// <param name="targetArray">
/// the array into which the elements of the queue are to
/// be stored, if it is big enough; otherwise, a new array of the
/// same runtime type is allocated for this purpose
/// </param>
/// <returns> an array containing all of the elements in this queue</returns>
/// <exception cref="ArrayTypeMismatchException">if the runtime type of the <pararef name="targetArray"/>
/// is not a super tyoe of the runtime tye of every element in this queue.
/// </exception>
/// <exception cref="System.ArgumentNullException">If the <paramref name="targetArray"/> is <see langword="null"/>
/// </exception>
public T[] ToArray(T[] targetArray)
{
if (targetArray == null)
throw new ArgumentNullException("targetArray");
T[] items = _items;
if (targetArray.Length < _count)
targetArray = (T[]) Array.CreateInstance(targetArray.GetType().GetElementType(), _count);
int k = 0;
int i = _takeIndex;
while (k < _count)
{
targetArray[k++] = items[i];
i = increment(i);
}
if (targetArray.Length > _count)
targetArray[_count] = default(T);
return targetArray;
}
/// <summary>
/// Returns an <see cref="IEnumerator{T}"/> over the elements in this
/// queue in proper sequence.
/// </summary>
/// <remarks>
/// The returned <see cref="IEnumerator{T}"/> is a "weakly consistent"
/// iterator guarantees to traverse elements as they existed upon
/// construction of the iterator, and may (but is not guaranteed to)
/// reflect any modifications subsequent to construction.
/// </remarks>
/// <returns>
/// An iterator over the elements in this queue in proper sequence.
/// </returns>
public override IEnumerator<T> GetEnumerator()
{
return new ArrayQueueEnumerator(this);
}
/// <summary>
/// Gets a value indicating whether the <see cref="ICollection{T}"/> is read-only.
/// This implementation always return true;
/// </summary>
///
/// <returns>
/// true if the <see cref="ICollection{T}"/> is read-only; otherwise, false.
/// This implementation always return true;
/// </returns>
///
public override bool IsReadOnly
{
get
{
return false;
}
}
private class ArrayQueueEnumerator : AbstractEnumerator<T>
{
/// <summary>
/// Index of element to be returned by next,
/// or a negative number if no such element.
/// </summary>
private int _nextIndex;
/// <summary>
/// Parent <see cref="ArrayQueue{T}"/>
/// for this <see cref="IEnumerator{T}"/>
/// </summary>
private readonly ArrayQueue<T> _enclosingInstance;
/// <summary>
/// nextItem holds on to item fields because once we claim
/// that an element exists in hasNext(), we must return it in
/// the following next() call even if it was in the process of
/// being removed when hasNext() was called.
/// </summary>
private T _nextItem;
protected override T FetchCurrent()
{
T x = _nextItem;
_nextIndex = _enclosingInstance.increment(_nextIndex);
CheckNext();
return x;
}
internal ArrayQueueEnumerator(ArrayQueue<T> enclosingInstance)
{
_enclosingInstance = enclosingInstance;
SetInitialState();
}
protected override bool GoNext()
{
return _nextIndex >= 0;
}
public override void Reset()
{
SetInitialState();
}
private void SetInitialState()
{
if (_enclosingInstance.Count == 0)
_nextIndex = - 1;
else
{
_nextIndex = _enclosingInstance._takeIndex;
_nextItem = _enclosingInstance._items[_enclosingInstance._takeIndex];
}
}
/// <summary>
/// Checks whether nextIndex is valid; if so setting nextItem.
/// Stops iterator when either hits putIndex or sees null item.
/// </summary>
private void CheckNext()
{
if (_nextIndex == _enclosingInstance._putIndex)
{
_nextIndex = - 1;
_nextItem = default(T);
}
else
{
_nextItem = _enclosingInstance._items[_nextIndex];
}
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.DirectoryServices;
namespace VersionOne.IIS {
public abstract class IISObject {
private static IDictionary<string, IISObject> _map = new Dictionary<string, IISObject>();
private string _path;
protected string Path {
get { return _path; }
}
public string Name {
get {
string[] parts = _path.Split('/');
return parts[parts.Length - 1];
}
}
private IDictionary _properties = new Hashtable();
private IDictionary Properties {
get { return _properties; }
}
private bool _haschanged;
public bool HasChanged {
get { return _haschanged; }
}
public IISObject(string path) {
_path = path;
_map[path] = this;
}
public void AcceptChanges() {
if (HasChanged) {
using (DirectoryEntry entry = new DirectoryEntry(_path)) {
foreach (DictionaryEntry propentry in Properties)
entry.InvokeSet((string) propentry.Key, propentry.Value);
entry.CommitChanges();
}
}
}
public void RejectChanges() {
Properties.Clear();
_haschanged = false;
}
protected T Create<T>(string name, string type) where T : IISObject {
using (DirectoryEntry entry = new DirectoryEntry(_path))
using (DirectoryEntry e = entry.Children.Add(name, type))
e.CommitChanges();
return GetChild<T>(name);
}
protected T GetProperty<T>(string name) {
object value = Properties[name];
if (value == null) {
using (DirectoryEntry entry = new DirectoryEntry(_path))
value = Properties[name] = entry.InvokeGet(name);
}
return (T) value;
}
protected void SetProperty<T>(string name, T value) {
T v = GetProperty<T>(name);
if (!v.Equals(value)) {
Properties[name] = value;
_haschanged = true;
}
}
protected void Execute(string method) {
using (DirectoryEntry entry = new DirectoryEntry(_path))
entry.Invoke(method, null);
}
protected object Execute(string method, params object[] args) {
using (DirectoryEntry entry = new DirectoryEntry(_path))
return entry.Invoke(method, args);
}
protected T GetChild<T>(string name) where T : IISObject {
string fullpath = Path + "/" + name;
if (DirectoryEntry.Exists(fullpath))
return GetNode<T>(fullpath);
return null;
}
protected T GetParent<T>() where T : IISObject {
string[] parts = _path.Split('/');
string path = string.Join("/", parts, 0, parts.Length - 1);
return GetNode<T>(path);
}
private static T GetNode<T>(string fullpath) where T : IISObject {
IISObject v;
if (!_map.TryGetValue(fullpath, out v))
v = (T) Activator.CreateInstance(typeof (T), new object[] {fullpath});
return (T) v;
}
protected IDictionary<string, T> GetChildren<T>(string type) where T : IISObject {
IDictionary<string, T> results = new Dictionary<string, T>();
using (DirectoryEntry entry = new DirectoryEntry(_path)) {
foreach (DirectoryEntry child in entry.Children)
using (child)
if (child.SchemaClassName == type)
results.Add(child.Name, GetChild<T>(child.Name));
}
return results;
}
}
public class IISComputer : IISObject {
private IISWebService _webservice;
public IISWebService WebService {
get {
if (_webservice == null)
_webservice = GetChild<IISWebService>("W3SVC");
return _webservice;
}
}
public IISComputer() : this("localhost") {}
public IISComputer(string servername) : base("IIS://" + servername) {}
}
public class IISWebService : IISObject {
public IISWebService(string path) : base(path) {}
public IISComputer Computer {
get { return GetParent<IISComputer>(); }
}
private IDictionary<string, IISWebServer> _webservers;
private IDictionary<string, IISWebServer> WebServersDict {
get {
if (_webservers == null)
_webservers = GetChildren<IISWebServer>("IIsWebServer");
return _webservers;
}
}
public ICollection<IISWebServer> WebServers {
get { return WebServersDict.Values; }
}
private IISApplicationPools _apppools;
public IISApplicationPools AppPools {
get {
if (_apppools == null)
_apppools = GetChild<IISApplicationPools>("AppPools");
return _apppools;
}
}
}
public class IISApplicationPools : IISObject {
public IISApplicationPools(string path) : base(path) {}
public IISWebService WebService {
get { return GetParent<IISWebService>(); }
}
private IDictionary<string, IISApplicationPool> _apppools;
private IDictionary<string, IISApplicationPool> AppPoolsDict {
get {
if (_apppools == null)
_apppools = GetChildren<IISApplicationPool>("IIsApplicationPool");
return _apppools;
}
}
public ICollection<IISApplicationPool> AppPools {
get { return AppPoolsDict.Values; }
}
public IISApplicationPool GetApplicationPool(string name) {
IISApplicationPool pool;
AppPoolsDict.TryGetValue(name, out pool);
return pool;
}
public IISApplicationPool AddApplicationPool(string name) {
IISApplicationPool apppool = GetApplicationPool(name);
if (apppool == null) {
apppool = Create<IISApplicationPool>(name, "IIsApplicationPool");
AppPoolsDict.Add(name, apppool);
}
return apppool;
}
}
public class IISApplicationPool : IISObject {
public IISApplicationPool(string path) : base(path) {}
public IISApplicationPools AppPools {
get { return GetParent<IISApplicationPools>(); }
}
public int PeriodicRestartMemory {
get { return GetProperty<int>("PeriodicRestartMemory"); }
set { SetProperty("PeriodicRestartMemory", value); }
}
public int PeriodicRestartPrivateMemory {
get { return GetProperty<int>("PeriodicRestartPrivateMemory"); }
set { SetProperty("PeriodicRestartPrivateMemory", value); }
}
public void Start() {
Execute("Start");
}
public void Stop() {
Execute("Stop");
}
public void Recycle() {
Execute("Recycle");
}
}
public class IISWebServer : IISObject {
public IISWebServer(string path) : base(path) {}
public IISWebService WebService {
get { return GetParent<IISWebService>(); }
}
private IDictionary<string, IISRootWebVirtualDir> _virtualdirs;
private IDictionary<string, IISRootWebVirtualDir> VirtualDirsDict {
get {
if (_virtualdirs == null)
_virtualdirs = GetChildren<IISRootWebVirtualDir>("IIsWebVirtualDir");
return _virtualdirs;
}
}
public string ServerBindings {
get { return GetProperty<string>("ServerBindings"); }
}
public string HostName {
get {
string[] parts = ServerBindings.Split(':');
string host = "localhost";
if (parts[2] != string.Empty)
host = parts[2];
return host;
}
}
public int Port {
get {
string[] parts = ServerBindings.Split(':');
string port = "80";
if (parts[1] != string.Empty)
port = parts[1];
return int.Parse(port);
}
}
public string Url {
get {
string url = "http://" + HostName;
if (Port != 80)
url += ":" + Port;
return url;
}
}
public ICollection<IISRootWebVirtualDir> VirtualDirs {
get { return VirtualDirsDict.Values; }
}
}
public class IISWebVirtualDir : IISObject {
public IISWebVirtualDir(string path) : base(path) {}
public IISWebVirtualDir ParentDir {
get { return GetParent<IISWebVirtualDir>(); }
}
public virtual bool IsRoot {
get { return false; }
}
private IDictionary<string, IISWebVirtualDir> _virtualdirs;
private IDictionary<string, IISWebVirtualDir> VirtualDirsDict {
get {
if (_virtualdirs == null)
_virtualdirs = GetChildren<IISWebVirtualDir>("IIsWebVirtualDir");
return _virtualdirs;
}
}
public ICollection<IISWebVirtualDir> VirtualDirs {
get { return VirtualDirsDict.Values; }
}
public string AppPoolID {
get { return GetProperty<string>("AppPoolID"); }
set { SetProperty("AppPoolID", value); }
}
public IISWebVirtualDir GetVirtualDir(string instancename) {
IISWebVirtualDir instance;
if (VirtualDirsDict.TryGetValue(instancename, out instance))
return instance;
return null;
}
}
public class IISRootWebVirtualDir : IISWebVirtualDir {
public override bool IsRoot {
get { return true; }
}
public IISWebServer WebServer {
get { return GetParent<IISWebServer>(); }
}
public IISRootWebVirtualDir(string path) : base(path) {}
}
}
| |
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;
using Faithlife.Parsing;
namespace Facility.Definition.Fsd
{
internal static class FsdParsers
{
public static ServiceInfo ParseDefinition(NamedText source, IReadOnlyDictionary<string, FsdRemarksSection> remarksSections)
{
return DefinitionParser(new Context(source, remarksSections)).Parse(source.Text);
}
static readonly IParser<string> CommentParser =
Parser.Regex(@"//([^\r\n]*)(\r\n?|\n|$)").Select(x => x.Groups[1].ToString());
static readonly IParser<string> CommentOrWhiteSpaceParser =
CommentParser.Or(Parser.WhiteSpace.AtLeastOnce().Success(""));
static IParser<T> CommentedToken<T>(this IParser<T> parser) =>
parser.PrecededBy(CommentOrWhiteSpaceParser.Many()).TrimEnd();
static IParser<string> PunctuationParser(string token) =>
Parser.String(token).CommentedToken().Named("'" + token + "'");
static readonly IParser<string> NameParser =
Parser.Regex(@"[a-zA-Z_][0-9a-zA-Z_]*").Select(x => x.ToString()).CommentedToken();
static IParser<string> KeywordParser(params string[] keywords) =>
NameParser.Where(keywords.Contains).Named(string.Join(" or ", keywords.Select(x => "'" + x + "'")));
static IParser<IReadOnlyList<T>> Delimited<T>(this IParser<T> parser, string delimiter) =>
parser.Delimited(PunctuationParser(delimiter));
static IParser<IReadOnlyList<T>> DelimitedAllowTrailing<T>(this IParser<T> parser, string delimiter) =>
parser.DelimitedAllowTrailing(PunctuationParser(delimiter));
static IParser<T> Bracketed<T>(this IParser<T> parser, string openBracket, string closeBracket) =>
parser.Bracketed(PunctuationParser(openBracket), PunctuationParser(closeBracket));
static readonly IParser<Match> AttributeParameterValueParser =
Parser.Regex(@"""(([^""\\]+|\\[""\\/bfnrt]|\\u[0-9a-fA-f]{4})*)""|([0-9a-zA-Z.+_-]+)");
static IParser<ServiceAttributeParameterInfo> AttributeParameterParser(Context context) =>
from name in NameParser.Named("parameter name").Positioned()
from colon in PunctuationParser(":")
from value in AttributeParameterValueParser.Named("parameter value")
select new ServiceAttributeParameterInfo(name.Value, TryParseAttributeParameterValue(value), context.GetPosition(name.Position));
static IParser<ServiceAttributeInfo> AttributeParser(Context context) =>
from name in NameParser.Named("attribute name").Positioned()
from parameters in AttributeParameterParser(context).Delimited(",").Bracketed("(", ")").OrDefault()
select new ServiceAttributeInfo(name.Value, parameters, context.GetPosition(name.Position));
static IParser<ServiceEnumValueInfo> EnumValueParser(Context context) =>
from comments1 in CommentOrWhiteSpaceParser.Many()
from attributes in AttributeParser(context).Delimited(",").Bracketed("[", "]").Many()
from comments2 in CommentOrWhiteSpaceParser.Many()
from name in NameParser.Named("value name").Positioned()
select new ServiceEnumValueInfo(name.Value, attributes.SelectMany(x => x), BuildSummary(comments1, comments2), context.GetPosition(name.Position));
static IParser<ServiceEnumInfo> EnumParser(Context context) =>
from comments1 in CommentOrWhiteSpaceParser.Many()
from attributes in AttributeParser(context).Delimited(",").Bracketed("[", "]").Many()
from comments2 in CommentOrWhiteSpaceParser.Many()
from keyword in KeywordParser("enum").Positioned()
from name in NameParser.Named("enum name")
from values in EnumValueParser(context).DelimitedAllowTrailing(",").Bracketed("{", "}")
select new ServiceEnumInfo(name, values,
attributes.SelectMany(x => x), BuildSummary(comments1, comments2),
context.GetRemarksSection(name)?.Lines, context.GetPosition(keyword.Position));
static IParser<ServiceErrorInfo> ErrorParser(Context context) =>
from comments1 in CommentOrWhiteSpaceParser.Many()
from attributes in AttributeParser(context).Delimited(",").Bracketed("[", "]").Many()
from comments2 in CommentOrWhiteSpaceParser.Many()
from name in NameParser.Named("error name").Positioned()
select new ServiceErrorInfo(name.Value, attributes.SelectMany(x => x), BuildSummary(comments1, comments2), context.GetPosition(name.Position));
static IParser<ServiceErrorSetInfo> ErrorSetParser(Context context) =>
from comments1 in CommentOrWhiteSpaceParser.Many()
from attributes in AttributeParser(context).Delimited(",").Bracketed("[", "]").Many()
from comments2 in CommentOrWhiteSpaceParser.Many()
from keyword in KeywordParser("errors").Positioned()
from name in NameParser.Named("errors name")
from errors in ErrorParser(context).DelimitedAllowTrailing(",").Bracketed("{", "}")
select new ServiceErrorSetInfo(name, errors,
attributes.SelectMany(x => x), BuildSummary(comments1, comments2),
context.GetRemarksSection(name)?.Lines, context.GetPosition(keyword.Position));
static readonly IParser<string> TypeParser = Parser.Regex(@"[0-9a-zA-Z<>[\]]+").Select(x => x.ToString()).CommentedToken();
static IParser<ServiceFieldInfo> FieldParser(Context context) =>
from comments1 in CommentOrWhiteSpaceParser.Many()
from attributes in AttributeParser(context).Delimited(",").Bracketed("[", "]").Many()
from comments2 in CommentOrWhiteSpaceParser.Many()
from name in NameParser.Named("field name").Positioned()
from colon in PunctuationParser(":")
from typeName in TypeParser.Named("field type name").Positioned()
from semicolon in PunctuationParser(";")
select new ServiceFieldInfo(name.Value, typeName.Value, attributes.SelectMany(x => x), BuildSummary(comments1, comments2), context.GetPosition(name.Position));
static IParser<ServiceDtoInfo> DtoParser(Context context) =>
from comments1 in CommentOrWhiteSpaceParser.Many()
from attributes in AttributeParser(context).Delimited(",").Bracketed("[", "]").Many()
from comments2 in CommentOrWhiteSpaceParser.Many()
from keyword in KeywordParser("data").Positioned()
from name in NameParser.Named("data name")
from fields in FieldParser(context).Many().Bracketed("{", "}")
select new ServiceDtoInfo(name, fields,
attributes.SelectMany(x => x), BuildSummary(comments1, comments2),
context.GetRemarksSection(name)?.Lines, context.GetPosition(keyword.Position));
static IParser<ServiceMethodInfo> MethodParser(Context context) =>
from comments1 in CommentOrWhiteSpaceParser.Many()
from attributes in AttributeParser(context).Delimited(",").Bracketed("[", "]").Many()
from comments2 in CommentOrWhiteSpaceParser.Many()
from keyword in KeywordParser("method").Positioned()
from name in NameParser.Named("method name")
from requestFields in FieldParser(context).Many().Bracketed("{", "}")
from colon in PunctuationParser(":")
from responseFields in FieldParser(context).Many().Bracketed("{", "}")
select new ServiceMethodInfo(name, requestFields, responseFields,
attributes.SelectMany(x => x), BuildSummary(comments1, comments2),
context.GetRemarksSection(name)?.Lines, context.GetPosition(keyword.Position));
static IParser<IServiceMemberInfo> ServiceItemParser(Context context) =>
Parser.Or<IServiceMemberInfo>(EnumParser(context), DtoParser(context), MethodParser(context), ErrorSetParser(context));
static IParser<ServiceInfo> ServiceParser(Context context) =>
from comments1 in CommentOrWhiteSpaceParser.Many()
from attributes in AttributeParser(context).Delimited(",").Bracketed("[", "]").Many()
from comments2 in CommentOrWhiteSpaceParser.Many()
from keyword in KeywordParser("service").Positioned()
from name in NameParser.Named("service name")
from items in ServiceItemParser(context).Many().Bracketed("{", "}")
select new ServiceInfo(name, items,
attributes.SelectMany(x => x), BuildSummary(comments1, comments2),
context.GetRemarksSection(name)?.Lines, context.GetPosition(keyword.Position));
static IParser<ServiceInfo> DefinitionParser(Context context) =>
from service in ServiceParser(context).FollowedBy(CommentOrWhiteSpaceParser.Many())
from end in Parser.Success(true).End().Named("end")
select service;
static string TryParseAttributeParameterValue(Match match)
{
return match.Groups[1].Success ?
string.Concat(match.Groups[2].Captures.OfType<Capture>().Select(x => x.ToString()).Select(x => x[0] == '\\' ? DecodeBackslash(x) : x)) :
match.Groups[3].ToString();
}
static string DecodeBackslash(string text)
{
switch (text[1])
{
case 'b':
return "\b";
case 'f':
return "\f";
case 'n':
return "\n";
case 'r':
return "\r";
case 't':
return "\t";
case 'u':
return new string((char) ushort.Parse(text.Substring(2), NumberStyles.HexNumber, CultureInfo.InvariantCulture), 1);
default:
return text.Substring(1);
}
}
static string BuildSummary(IEnumerable<string> comments1, IEnumerable<string> comments2)
{
return string.Join(" ", comments1.Concat(comments2).Where(x => x.Trim().Length != 0).Reverse().TakeWhile(x => x.Length > 2 && x[0] == '/' && x[1] == ' ').Reverse().Select(x => x.Substring(2).Trim()));
}
sealed class Context
{
public Context(NamedText source, IReadOnlyDictionary<string, FsdRemarksSection> remarksSections)
{
m_source = source;
m_remarksSections = remarksSections;
}
public NamedTextPosition GetPosition(TextPosition position)
{
var lineColumn = position.GetLineColumn();
return new NamedTextPosition(m_source.Name, lineColumn.LineNumber, lineColumn.ColumnNumber);
}
public FsdRemarksSection GetRemarksSection(string name)
{
FsdRemarksSection section;
m_remarksSections.TryGetValue(name, out section);
return section;
}
readonly NamedText m_source;
readonly IReadOnlyDictionary<string, FsdRemarksSection> m_remarksSections;
}
}
}
| |
using UnityEngine;
using UnityEditor;
using System.IO;
using System;
using System.Collections.Generic;
using System.Reflection;
//using System.Net;
public class WooglieEditor : EditorWindow
{
const int API_VERSION = 1;
const string URL_LOSTPW = "http://www.wooglie.com/user.php?sub=lostpw";
const string URL_REGISTER = "http://www.wooglie.com/user.php?sub=register&developer=1";
const string URL_ACCOUNT = "http://www.wooglie.com/gamedevelopers.php";
const string URL_HELP = "http://www.wooglie.com/gamedevelopers.php?subPage=apiHelp";
static bool isUnityPRO = false;
static bool checkedPRO = false;
static WTextSettings settings;
//static WebClient wcUploader;
static WooglieEditor()
{
settings = new WTextSettings("Assets/WooglieAPI/Settings/settings.txt");
}
[MenuItem("Window/Wooglie.com API")]
static void Init()
{
EditorWindow.GetWindow(typeof(WooglieEditor), false, "Wooglie API");
}
void Awake()
{
ResetData();
WWWForm form = new WWWForm();
form.AddField("action", "checkLogin");
Contact(form);
wooglieLogo = (Texture2D)Resources.Load("WooglieLogo", typeof(Texture2D));
SetupData();
}
bool startPublish = false;
string uploadIndieGame = "";
void WooglieUpdate()
{
// ACTIONS
if (startPublish)
{
startPublish = false;
Publish();
}
if (uploadIndieGame != "")
{
UploadWebplayer(uploadIndieGame);
uploadIndieGame = "";
}
}
void SetupData()
{
//SETUP
EditorApplication.update += WooglieUpdate;
/*if (wcUploader == null)
{
wcUploader = new WebClient();
wcUploader.UploadFileCompleted += UploadFileCompletedCallback;
wcUploader.UploadProgressChanged += UploadProgressCallback;
} */
//Test unity pro
Assembly a = System.Reflection.Assembly.Load("UnityEditor");
if (a == null) return;
Type type = a.GetType("UnityEditorInternal.InternalEditorUtility");
if (type == null) return;
MethodInfo inf2 = type.GetMethod("HasPro");
if (inf2 == null) return;
isUnityPRO = (bool)inf2.Invoke(null, null);
checkedPRO = true;
}
Texture2D wooglieLogo;
Vector2 scrollPos = Vector2.zero;
void OnGUI()
{
if (!checkedPRO)
SetupData();
scrollPos = EditorGUILayout.BeginScrollView(scrollPos);
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
if (GUILayout.Button(wooglieLogo, new GUIStyle()))
Application.OpenURL("http://www.Wooglie.com");
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
bool hasLoginData = (EditorPrefs.GetString("WooglieAPIKey", "") != "");
if (!hasLoginData)
{
NeedLoginGUI();
}
else
{
LoggedInGUI();
}
EditorGUILayout.EndScrollView();
}
public enum WooglieCategories { Action, Arcade, Adventure, Puzzle, Racing, Shooters, Sports, Strategy }
public enum WooglieGameState { Completed, InDevelopment, Cancelled }
class GameInfo
{
//LOADED VIA MAIN GAME LIST
public int ID;
public bool inDev;
public string status = "";
public bool requireEditor;
public string title = "";
public WooglieCategories gameCategory;
public WooglieGameState gameState;
public bool streamWebplayer;
public bool isLive
{
get { return status.Contains("is live"); }
}
//LOADED WHEN EDITING ONLY
public string changeNotes = "";
public string gameControls = "";
public string gameWords = "";
public string gameLong = "";
public string gameShort = "";
public string gameTags = "";
public int gameHeight;
public int gameWidth;
public bool uploadedAllImages = false;
public GameInfo()
{ }
//CLONE: USED FOR EDITING ONLY
protected GameInfo(GameInfo other)
{
ID = other.ID;
inDev = other.inDev;
title = other.title;
gameCategory = other.gameCategory;
gameState = other.gameState;
streamWebplayer = other.streamWebplayer;
gameControls = other.gameControls;
gameWords = other.gameWords;
gameTags = other.gameTags;
gameLong = other.gameLong;
gameShort = other.gameShort;
gameHeight = other.gameHeight;
gameWidth = other.gameWidth;
uploadedAllImages = other.uploadedAllImages;
changeNotes = other.changeNotes;
}
public GameInfo Clone()
{
return new GameInfo(this);
}
}
List<GameInfo> gameList = new List<GameInfo>();
bool loadedGameList = false;
int loadedGames = 0;
void ResetData()
{
loadedGameList = false;
gameList = new List<GameInfo>();
editGameID = 0;
}
WooglieGameState StringToGameState(string state)
{
foreach (WooglieGameState suit in Enum.GetValues(typeof(WooglieGameState)))
{
if (suit + "" == state)
return suit;
}
return WooglieGameState.InDevelopment;
}
WooglieCategories StringToCategory(string cat)
{
foreach (WooglieCategories suit in Enum.GetValues(typeof(WooglieCategories)))
{
if (suit + "" == cat)
return suit;
}
return WooglieCategories.Action;
}
void LoadAccountData()
{
if (wooglieLogo == null) wooglieLogo = (Texture2D)Resources.Load("WooglieLogo", typeof(Texture2D));
loadedGameList = true;
WWWForm form = new WWWForm();
form.AddField("action", "gameList");
string output = Contact(form);
string result = output;
int statusCode = 0;
if (result.Length >= 1)
{
statusCode = int.Parse(output.Substring(0, 1) + "");
result = output.Substring(1);
}
if (statusCode != 1)
{ //ERROR
EditorUtility.DisplayDialog("Error", "Couldn't fetch game list, please relogin. Details:" + result, "OK");
}
else
{
string[] lines = result.Split('\n');
gameList = new List<GameInfo>();
foreach (string line in lines)
{
string[] items = line.Split('#');
if (items.Length < 5) { continue; }
GameInfo gi = new GameInfo();
gi.ID = int.Parse(items[0]);
gi.gameCategory = StringToCategory(items[1]);
gi.status = items[2];
gi.requireEditor = (items[3] == "1");
gi.streamWebplayer = (items[4] == "1");
gi.title = items[5];
gi.gameState = StringToGameState(items[6]);
gameList.Add(gi);
}
loadedGames = gameList.Count;
}
}
#region LoginArea
string loginUsername = "";
string loginPassword = "";
void NeedLoginGUI()
{
GUILayout.Space(10); loginUsername = EditorGUILayout.TextField("Username", loginUsername);
loginPassword = EditorGUILayout.PasswordField("Password", loginPassword);
GUILayout.Space(10);
if (GUILayout.Button("Login"))
{
DoLogin();
}
GUILayout.BeginHorizontal();
if (GUILayout.Button("Register [URL]"))
{
Application.OpenURL(URL_REGISTER);
}
if (GUILayout.Button("Forgot your details? [URL]"))
{
Application.OpenURL(URL_LOSTPW);
}
GUILayout.EndHorizontal();
}
void DoLogin()
{
ResetData();
WWWForm form = new WWWForm();
form.AddField("action", "login");
form.AddField("loginUser", loginUsername);
form.AddField("loginPW", loginPassword);
string result = Contact(form);
int statusCode = 0;
if (result.Length >= 1)
{
statusCode = int.Parse(result.Substring(0, 1) + "");
result = result.Substring(1);
}
if (statusCode != 1)
{ //ERROR
bool status = EditorUtility.DisplayDialog("Error", "Login error: " + result, "OK", "Forgot PW?");
if (!status)
Application.OpenURL(URL_LOSTPW);
}
else
{
string[] output = result.Split('#');
EditorPrefs.SetString("WooglieAPIKey", output[0]);
EditorPrefs.SetString("WooglieDevID", output[1]);
}
}
private enum MenuState { selectgame, editgame }
MenuState menuState = MenuState.selectgame;
void LoggedInGUI()
{
if (!loadedGameList || loadedGames != gameList.Count)
LoadAccountData();
switch (menuState)
{
case MenuState.selectgame:
SelectGameGUI();
break;
case MenuState.editgame:
EditGameGUI();
break;
}
}
#endregion
void SelectGameGUI()
{
if (GUILayout.Button("Documentation [URL]"))
Application.OpenURL(URL_HELP);
if (GUILayout.Button("Open account page [URL]"))
Application.OpenURL(URL_ACCOUNT);
if (GUILayout.Button("Logout"))
{
EditorPrefs.SetString("WooglieAPIKey", "");
}
EditorGUILayout.Separator();
if (gameList.Count > 0)
{
GUILayout.BeginHorizontal();
GUILayout.Label("You have " + gameList.Count + " games on Wooglie.");
GUILayout.FlexibleSpace();
AddGameButton();
GUILayout.EndHorizontal();
foreach (GameInfo game in gameList)
{
GUILayout.BeginHorizontal();
if (GUILayout.Button("Edit", GUILayout.Width(50)))
{
editGameID = game.ID; menuState = MenuState.editgame;
}
GUILayout.Label(game.title, GUILayout.Width(120));
GUILayout.Label("| " + game.gameCategory, GUILayout.Width(100));
GUILayout.Label("| ", GUILayout.Width(20));
string thisStatus = "";
if (game.isLive)
{
GUI.color = Color.green;
thisStatus = "LIVE";
}
else if (game.inDev)
{
GUI.color = Color.yellow;
thisStatus = "DEV";
}
else
{
if (game.requireEditor || game.status.Contains("Awaiting staff"))
{
GUI.color = Color.yellow;
thisStatus = "Awaiting staff review";
}
else
{
GUI.color = Color.red;
thisStatus = "Please upload!";
}
}
GUILayout.Label(thisStatus, GUILayout.Width(150));
GUI.color = Color.white;
GUILayout.EndHorizontal();
}
}
else
{
GUILayout.BeginHorizontal();
GUILayout.Label("You have not yet added any games to Wooglie.");
GUILayout.FlexibleSpace();
AddGameButton();
GUILayout.EndHorizontal();
}
EditorGUILayout.Separator();
}
void AddGameButton()
{
if (GUILayout.Button("Add a new game"))
{
WWWForm form = new WWWForm();
form.AddField("action", "addGame");
string output = Contact(form);
string result = output;
int statusCode = 0;
if (result.Length >= 1)
{
statusCode = int.Parse(output.Substring(0, 1) + "");
result = output.Substring(1);
}
if (statusCode != 1)
{ //ERROR
EditorUtility.DisplayDialog("Error", "Couldn't add game. Details:" + result, "OK");
}
else
{
editGameID = int.Parse(result); menuState = MenuState.editgame;
//Reload game list
LoadAccountData();
}
}
}
private int editGameID = 0;
private GameInfo editGameInfo = null;
private int lastMetaDownload = 0;
private bool metaIsUploaded = false;
string IsMetaDataOK(GameInfo info)
{
if (info.title.Length <= 2) return "Please correct the title.";
if (info.gameControls.Length <= 2) return "Please enter a controls description.";
//if (info.gameWords.Length <= 2) return "Please enter a 5 word description.";
if (info.gameShort.Length <= 2) return "Please enter a short description.";
if (info.gameLong.Length <= 2) return "Please enter a long description.";
return "";
}
bool showStepOne = true;
bool showStepTwo = true;
bool showStepThree = true;
string CapString(string input, int len)
{
if (input.Length > len)
return input.Substring(0, len);
return input;
}
void EditGameGUI()
{
if (GUILayout.Button("Back"))
{
menuState = MenuState.selectgame;
editGameInfo = null;
}
if (editGameInfo == null || editGameID != editGameInfo.ID)
{
editGameInfo = null; lastMetaDownload = 0; metaIsUploaded = false;
foreach (GameInfo info in gameList)
{
if (info.ID == editGameID)
{
editGameInfo = info.Clone();
break;
}
}
}
if (editGameInfo == null) return;
if (lastMetaDownload == 0 || lastMetaDownload != editGameInfo.ID)
{
lastMetaDownload = editGameInfo.ID;
DownloadEditMetaData();
metaIsUploaded = IsMetaDataOK(editGameInfo) == "";
}
EditorGUILayout.Separator();
GUILayout.Label("How to upload your game?", "boldLabel");
GUILayout.Label("1) Submit the required metadata.", "miniLabel");
GUILayout.Label("2) Select and upload the required promotional images.", "miniLabel");
GUILayout.Label("3) Press publish!", "miniLabel");
EditorGUILayout.Separator();
EditorGUILayout.Separator();
GUILayout.Label("Add your game:", "boldLabel");
showStepOne = EditorGUILayout.Foldout(showStepOne, "1) Meta data:");
if (showStepOne)
{
GUILayout.BeginHorizontal();
GUILayout.Space(40);
GUILayout.BeginVertical();
GUILayout.Label("The game description etc. After completing this information you'll be able to upload your game.", "miniLabel");
EditorGUILayout.Separator();
editGameInfo.title = EditorGUILayout.TextField("Title:", editGameInfo.title);
editGameInfo.gameCategory = (WooglieCategories)EditorGUILayout.EnumPopup("Category:", editGameInfo.gameCategory);
editGameInfo.gameState = (WooglieGameState)EditorGUILayout.EnumPopup("State:", editGameInfo.gameState);
editGameInfo.streamWebplayer = EditorGUILayout.Toggle("Stream webplayer:", editGameInfo.streamWebplayer);
editGameInfo.gameWidth = EditorGUILayout.IntField("Width", editGameInfo.gameWidth);
editGameInfo.gameHeight = EditorGUILayout.IntField("Height", editGameInfo.gameHeight);
editGameInfo.gameTags = EditorGUILayout.TextField("Tags:", editGameInfo.gameTags);
//editGameInfo.gameWords = EditorGUILayout.TextField("+-5 words description:", editGameInfo.gameWords);
editGameInfo.gameShort = EditorGUILayout.TextField("Short description:", editGameInfo.gameShort);
GUILayout.Label("Controls:");
editGameInfo.gameControls = EditorGUILayout.TextArea(editGameInfo.gameControls, GUILayout.Height(60));
GUILayout.Label("Long description:");
editGameInfo.gameLong = EditorGUILayout.TextArea(editGameInfo.gameLong, GUILayout.Height(100));
//LIMIT
editGameInfo.gameWidth = Mathf.Clamp(editGameInfo.gameWidth, 100, 925);
editGameInfo.gameHeight = Mathf.Clamp(editGameInfo.gameHeight, 100, 600);
editGameInfo.title = CapString(editGameInfo.title, 100);
editGameInfo.gameWords = CapString(editGameInfo.gameWords, 35);
string err = IsMetaDataOK(editGameInfo);
if (err != "")
{
GUI.color = Color.red;
GUILayout.Label("Missing information: " + IsMetaDataOK(editGameInfo), "miniLabel");
GUI.color = Color.white;
}
else
{
if (GUILayout.Button("Update metadata"))
{
//SAVE META
SaveMetaData(editGameInfo);
metaIsUploaded = IsMetaDataOK(editGameInfo) == "";
if (metaIsUploaded)
{
showStepOne = false;
showStepTwo = true;
}
}
}
GUILayout.EndVertical();
GUILayout.EndHorizontal();
}
showStepTwo = EditorGUILayout.Foldout(showStepTwo, "2) Upload images");
if (showStepTwo)
{
GUILayout.BeginHorizontal();
GUILayout.Space(40);
GUILayout.BeginVertical();
if (!metaIsUploaded)
{
GUI.color = Color.red;
GUILayout.Label("You can not yet upload the webplayer and images:\n- Upload your metadata first.", "miniLabel");
GUI.color = Color.white;
}
else
{
GUILayout.Label("When you press publish, the game will be build and the images and game will be uploaded to Wooglie.com.", "miniLabel");
if (textureIcon == null && settings.GetString("promoImagesIcon", "") != "")
textureIcon = (Texture2D)AssetDatabase.LoadAssetAtPath(settings.GetString("promoImagesIcon", ""), typeof(Texture2D));
if (textureFeature == null && settings.GetString("promoImagesFeatured", "") != "")
textureFeature = (Texture2D)AssetDatabase.LoadAssetAtPath(settings.GetString("promoImagesFeatured", ""), typeof(Texture2D));
GUILayout.BeginHorizontal();
textureIcon = (Texture2D)EditorGUILayout.ObjectField("Icon:", textureIcon, typeof(Texture2D), false, GUILayout.Width(200));
GUILayout.Label("Main icon\n100x100 ", "miniLabel");
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
textureFeature = (Texture2D)EditorGUILayout.ObjectField("*Feature:", textureFeature, typeof(Texture2D), false, GUILayout.Width(200));
GUILayout.Label("Used when featured\n600x280\n*This image is optional", "miniLabel");
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
if (GUI.changed)
{
if (textureIcon != null){
string imgPath = AssetDatabase.GetAssetPath(textureIcon);
if(imgPath==""){
//string str = "(width:" + textureIcon.width + " height:" + textureIcon.height + ")";
textureIcon = null;
//EditorUtility.DisplayDialog("Error", "The image you selected does not match the required size (width: 100 height: 100), you select an image with the following sizes: "+str, "OK");
}else{
settings.SetString("promoImagesIcon", imgPath);
}
}
if (textureFeature != null)
{
string imgPath = AssetDatabase.GetAssetPath(textureFeature);
if (imgPath == "") textureIcon = null;
else settings.SetString("promoImagesFeatured", imgPath);
}
}
if (GUILayout.Button("Upload promo images"))
{
//SAVE META
if (UploadFiles())
{
if (editGameInfo.uploadedAllImages)
{
showStepTwo = false;
showStepThree = true;
}
}
}
}
GUILayout.EndVertical();
GUILayout.EndHorizontal();
}
showStepThree = EditorGUILayout.Foldout(showStepThree, "3) Upload game");
if (showStepThree)
{
GUILayout.BeginHorizontal();
GUILayout.Space(40);
GUILayout.BeginVertical();
if (editGameInfo.uploadedAllImages)
{
if (isUnityPRO)
{
GUILayout.Label("Because you are using Unity PRO, you can simply use the button below to complete\n" +
"your Wooglie submission. The tool will automatically build the game using your current\n" +
"build scenes. Furthermore a script will be added to your first screen to ensure no\n" +
"other websites can copy your game.", "miniLabel");
GUILayout.BeginHorizontal();
GUILayout.Space(20);
if (GUILayout.Button("Upload game!", GUILayout.Width(100)))
{
startPublish = true;
}
GUILayout.EndHorizontal();
}
else
{
GUILayout.Label("Because you're using Unity FREE(Indie), you cant upload in one click;\nYou'll need to manually build a .unity3d webplayer and upload it using the form below.\nNote that the build NEEDS to include the WoogliePiracyProtection script, use the button below to add it to your project(or to test if it is in).", "miniLabel");
GUILayout.Space(10);
GUILayout.BeginHorizontal();
GUILayout.Space(20);
if (GUILayout.Button("Add/Test Wooglie script", GUILayout.Width(200)))
{
testedScriptPresence = AddWooglieScript(true);
}
GUILayout.EndHorizontal();
if (testedScriptPresence)
{
GUILayout.Label("Upload webplayer:", "boldLabel");
if (!File.Exists(uploadFilePath)) uploadFilePath = "";
GUILayout.BeginHorizontal();
GUILayout.Space(20);
GUILayout.Label("Path: " + uploadFilePath, GUILayout.Width(200));
if (GUILayout.Button("Select a .unity3d webplayer", GUILayout.Width(200)))
{
uploadFilePath = EditorUtility.OpenFilePanel("Select a unity3d webplayer", "", "unity3d");
}
GUILayout.EndHorizontal();
if (uploadFilePath != "")
{
GUILayout.BeginHorizontal();
GUILayout.Space(20);
if (GUILayout.Button("Upload game!", GUILayout.Width(100)))
{
uploadIndieGame = "file://" + uploadFilePath;
}
GUILayout.EndHorizontal();
}
}
}
GUILayout.Space(10);
GUILayout.Label("Privacy notice: Please note that with uploading your game you will also submit your\nUnity version and the build size log of the webplayer (if present).", "miniLabel");
}
else
{
GUI.color = Color.red;
GUILayout.Label("You can not yet upload the webplayer:\n- Upload your images first.", "miniLabel");
GUI.color = Color.white;
}
GUILayout.EndVertical();
GUILayout.EndHorizontal();
}
EditorGUILayout.Space();
}
string uploadFilePath = "";
bool testedScriptPresence = false;
Texture2D textureIcon = null;
Texture2D textureFeature = null;
/*bool VerifyImage(Texture2D text, int width, int height)
{
if (text.width != width || text.height != height)
{
return false;
}
return true;
}*/
byte[] GetImageBytes(Texture2D text)
{
string path = AssetDatabase.GetAssetPath(text);
byte[] bits = System.IO.File.ReadAllBytes(path);
/*
TextureImporter tI = (TextureImporter)TextureImporter.GetAtPath(path);
tI.isReadable = true;
AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate);
byte[] bits = textureIcon.EncodeToPNG();
tI.isReadable = false;
*/
return bits;
}
bool UploadFiles()
{
WWWForm form = new WWWForm();
form.AddField("action", "uploadGame");
form.AddField("gameID", editGameInfo.ID);
if (textureIcon != null) form.AddBinaryData("uploadFileIcon", GetImageBytes(textureIcon));
if (textureFeature != null) form.AddBinaryData("uploadFileFeatured", GetImageBytes(textureFeature));
string result = Contact(form);
int statusCode = 0;
if (result.Length >= 1)
{
statusCode = int.Parse(result.Substring(0, 1) + "");
result = result.Substring(1);
}
if (statusCode != 1)
{ //ERROR
EditorUtility.DisplayDialog("Error", "Couldn't upload images. Details:" + result, "OK");
}
else
{
EditorUtility.DisplayDialog("Succes", "Your image(s) have been uploaded!", "OK");
LoadAccountData();
editGameInfo.uploadedAllImages = true;
return true;
}
return false;
}
void DownloadEditMetaData()
{
WWWForm form = new WWWForm();
form.AddField("action", "gameInfo");
form.AddField("gameID", editGameInfo.ID);
string result = Contact(form);
int statusCode = 0;
if (result.Length >= 1)
{
statusCode = int.Parse(result.Substring(0, 1) + "");
result = result.Substring(1);
}
if (statusCode != 1)
{ //ERROR
EditorUtility.DisplayDialog("Error", "Couldn't download game metadata. Details:" + result, "OK");
}
else
{
string[] items = result.Split('\n');
editGameInfo.title = items[0];
editGameInfo.gameWidth = int.Parse(items[1]);
editGameInfo.gameHeight = int.Parse(items[2]);
editGameInfo.gameControls = BRtoN(items[3]);
editGameInfo.gameWords = items[4];
editGameInfo.gameShort = BRtoN(items[5]);
editGameInfo.gameLong = BRtoN(items[6]);
editGameInfo.changeNotes = BRtoN(items[7]);
editGameInfo.uploadedAllImages = items[8] == "1";
editGameInfo.gameTags = items[9];
}
}
string BRtoN(string input)
{
return input.Replace("<br />", "\n");
}
void SaveMetaData(GameInfo gI)
{
WWWForm form = new WWWForm();
form.AddField("action", "uploadMeta");
form.AddField("gameID", gI.ID);
form.AddField("gameName", gI.title);
form.AddField("gameControls", gI.gameControls);
form.AddField("gameCategory", "" + gI.gameCategory);
form.AddField("gameState", "" + gI.gameState);
form.AddField("gameTags", gI.gameTags);
form.AddField("gameWords", gI.gameWords);
form.AddField("gameShort", gI.gameShort);
form.AddField("gameLong", gI.gameLong);
form.AddField("gameName", gI.title);
form.AddField("streamWebplayer", gI.streamWebplayer ? "1" : "0");
form.AddField("gameWidth", gI.gameWidth);
form.AddField("gameHeight", gI.gameHeight);
string result = Contact(form);
int statusCode = 0;
if (result.Length >= 1)
{
statusCode = int.Parse(result.Substring(0, 1) + "");
result = result.Substring(1);
}
if (statusCode != 1)
{ //ERROR
EditorUtility.DisplayDialog("Error", "Couldn't save game: " + result, "OK");
}
else
{
EditorUtility.DisplayDialog("Saved!", "Saved metadata!", "OK");
LoadAccountData();
}
}
#region BUILD
public static string TMPFolder()
{
// string pat = Path.GetTempPath() + "WooglieUpload/";
string pat = Application.dataPath.Replace("/Assets", "/") + "Builds/WooglieUpload/";
EnsureFolders(pat);
return pat;
}
public static void EnsureFolders(string path)
{
path = path.Replace('\\', '/');
string[] folders = path.Split('/');
for (int i = 0; i < folders.Length - 1; i++)
{
string currentpath = folders[i];
if (i > 0)
{
for (int j = i - 1; j >= 0; j--)
currentpath = folders[j] + '/' + currentpath;
}
if (currentpath == "") continue;
if (!Directory.Exists(currentpath))
{
Directory.CreateDirectory(currentpath);
}
}
}
static string[] GetBuildScenes()
{
List<string> scenes = new List<string>();
foreach (EditorBuildSettingsScene scene in EditorBuildSettings.scenes)
{
if (scene.enabled)
scenes.Add(scene.path);
}
return scenes.ToArray();
}
bool AddWooglieScript(bool warn)
{
//Add Wooglie security
EditorApplication.SaveCurrentSceneIfUserWantsTo();
string[] scenes =GetBuildScenes();
if (scenes.Length <= 0)
{
EditorUtility.DisplayDialog("Wooglie security", "The script could not be added to your first scene as this project doesnt have any buildsettings. Please open the correct project.", "OK");
return false;
}
if(EditorApplication.currentScene != scenes[0]){
EditorApplication.OpenScene(scenes[0]);
}
UnityEngine.Object obj = GameObject.FindObjectOfType(typeof(WoogliePiracyProtection));
if (obj == null)
{
if (warn) EditorUtility.DisplayDialog("Wooglie security", "Added script to the first scene. You can now make a build.", "OK");
new GameObject("Wooglie", typeof(WoogliePiracyProtection));
}
else
{
if (warn) EditorUtility.DisplayDialog("Wooglie security", "The script has already been added to the first scene. You can now make a build.", "OK");
}
EditorApplication.SaveScene(scenes[0]);
return true;
}
void Publish()
{
AddWooglieScript(false);
string buildResult = StartBuild();
if (buildResult != "")
{
if (buildResult.Contains("requires Unity PRO"))
{
isUnityPRO = false;
}
return;
}
UploadWebplayer("");
//Remove wooglie protection
WoogliePiracyProtection obj2 = (WoogliePiracyProtection)GameObject.FindObjectOfType(typeof(WoogliePiracyProtection));
if (obj2 != null)
{
DestroyImmediate(obj2.gameObject);
}
try
{
Directory.Delete(TMPFolder(), true);
}
catch (Exception ex) { Debug.Log(ex); }
}
string StartBuild()
{
string outputFolder = TMPFolder();
BuildTarget target = BuildTarget.WebPlayerStreamed;
if (!editGameInfo.streamWebplayer)
target = BuildTarget.WebPlayer;
if (GetBuildScenes().Length <= 0)
{
string err = "Couldn't attempt an automatic build: No scenes are active in this project.";
EditorUtility.DisplayDialog("Build error", err, "OK");
return err;
}
string errorR = BuildPipeline.BuildPlayer(GetBuildScenes(), outputFolder, target, BuildOptions.None);
if (errorR.Contains("requires Unity PRO"))
{
return errorR;
}
else if (errorR != "")
{
EditorUtility.DisplayDialog("Build error", errorR, "OK");
return errorR;
}
return "";
}
void UploadWebplayer(string file)
{
if (file == "")
{
file = ("file://" + TMPFolder() + ".unity3d").Replace("\\", "/");
}
WWW localFile = new WWW(file);
int mb = localFile.bytes.Length / (1024 * 1024);
if (mb >= 23)
{
EditorUtility.DisplayDialog("Error", "The game is " + mb + "Mb. THe max. upload size is 20MB. Please optimize your game. ", "OK");
return;
}else if(localFile.bytes.Length/1024 <= 1 ){
EditorUtility.DisplayDialog("Error", "The API tried to upload a file with filesize <=1kb (" + (localFile.bytes.Length/1024) + " kb). Please contact hello@Wooglie.com so that we can help you upload your game.", "OK");
return;
}
//new System.Threading.Thread(() => wcUploader.UploadFileAsync(new Uri("http://devs.wooglie.com/editorAPI.php"), "POST", file)).Start();
// Create a Web Form
WWWForm form = new WWWForm();
form.AddField("action", "uploadGame");
form.AddField("gameID", editGameID);
form.AddBinaryData("newUnityFile", localFile.bytes, "gameData");
form.AddField("buildReport", GetBuildSizeReport());
form.AddField("unityEditorVersion", Application.unityVersion);
string wwwData = Contact(form);
EditorUtility.ClearProgressBar();
string result = wwwData;
int statusCode = 0;
if (result.Length >= 1)
{
statusCode = int.Parse(wwwData.Substring(0, 1) + "");
result = wwwData.Substring(1);
}
if (statusCode != 1)
{ //ERROR
EditorUtility.DisplayDialog("Error", "Upload error: " + result, "OK");
}
else
{
EditorUtility.DisplayDialog("Succes!", "Your game has been submitted to Wooglie!\nYou will receive an email once we review the game, usually within 3 business days." + result, "OK");
LoadAccountData();
}
}
/// <summary>
/// Gets the editor log. But -only- grab the last Player size statistics
/// </summary>
/// <returns></returns>
static string GetBuildSizeReport()
{
string path = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "/Unity/Editor/Editor.log";
string editorLogContents = "";
try
{
using (FileStream fileStream = new FileStream(
path,
FileMode.Open,
FileAccess.Read,
FileShare.ReadWrite))
{
using (StreamReader streamReader = new StreamReader(fileStream))
{
editorLogContents = streamReader.ReadToEnd();
}
}
}
catch (Exception ex)
{
Debug.Log("Could not open editor log: " + ex);
}
if (editorLogContents != "")
{
int lastIndex = editorLogContents.LastIndexOf("***Player size statistics***");
if (lastIndex <= 0) return ""; // No log
int indexComplete = editorLogContents.LastIndexOf("*** Completed");
int len = indexComplete - lastIndex;
if (len < 0) len = editorLogContents.Length - lastIndex - 1;
string buildSize = editorLogContents.Substring(lastIndex, len);
indexComplete = buildSize.IndexOf("Unloading ");
if (indexComplete > 0)
buildSize = buildSize.Substring(0, indexComplete);
return buildSize;
}
return "";
}
#endregion
string Contact(WWWForm form)
{
form.AddField("editorAPIVersion", API_VERSION);
string apiKey = EditorPrefs.GetString("WooglieAPIKey", "");
string devID = EditorPrefs.GetString("WooglieDevID", "");
if (apiKey != "")
{
form.AddField("apiKey", apiKey);
form.AddField("devID", devID);
}
WWW www = new WWW("http://devs.wooglie.com/editorAPI.php", form);
while (!www.isDone)
{
EditorUtility.DisplayProgressBar("Uploading", "Progress: " + ((int)(www.uploadProgress*100))+"%", www.uploadProgress);
//HANG
}
EditorUtility.ClearProgressBar();
if (www.error != null)
{
EditorUtility.DisplayDialog("Wooglie.com connection error", "Details: " + www.error, "OK");
return "";
}
if (www.text.Length >= 1)
{
if (www.text[0] == '0')
{
if (www.text.Contains("Invalid login"))
{//Clear the invalid login data
EditorUtility.DisplayDialog("Invalid Wooglie API login", "Please relogin.", "OK");
EditorPrefs.SetString("WooglieAPIKey", "");
EditorPrefs.SetString("WooglieDevID", "");
ResetData();
}
else if (www.text.Contains("Outdated editor") || www.text.Contains("update the Wooglie API"))
{
EditorUtility.DisplayDialog("Oudated Wooglie API", www.text, "OK");
}
}
}
//All good..but calls need to check for 1 or 0
return www.text;
}
/*
private void UploadProgressCallback(object sender, UploadProgressChangedEventArgs e)
{
Debug.Log((string)e.UserState + "\n\n"
+ "Uploaded " + e.BytesSent + "/" + e.TotalBytesToSend
+ "b (" + e.ProgressPercentage + "%)");
}
private void UploadFileCompletedCallback(object sender, UploadFileCompletedEventArgs e)
{
Debug.Log("Upload complete my liege!");
}*/
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using Microsoft.Build.BuildEngine.Shared;
using Microsoft.Win32;
using System.IO;
namespace Microsoft.Build.BuildEngine
{
/// <summary>
/// The Intrinsic class provides static methods that can be accessed from MSBuild's
/// property functions using $([MSBuild]::Function(x,y))
/// </summary>
internal static class IntrinsicFunctions
{
/// <summary>
/// Add two doubles
/// </summary>
internal static double Add(double a, double b)
{
return a + b;
}
/// <summary>
/// Add two longs
/// </summary>
internal static long Add(long a, long b)
{
return a + b;
}
/// <summary>
/// Subtract two doubles
/// </summary>
internal static double Subtract(double a, double b)
{
return a - b;
}
/// <summary>
/// Subtract two longs
/// </summary>
internal static long Subtract(long a, long b)
{
return a - b;
}
/// <summary>
/// Multiply two doubles
/// </summary>
internal static double Multiply(double a, double b)
{
return a * b;
}
/// <summary>
/// Multiply two longs
/// </summary>
internal static long Multiply(long a, long b)
{
return a * b;
}
/// <summary>
/// Divide two doubles
/// </summary>
internal static double Divide(double a, double b)
{
return a / b;
}
/// <summary>
/// Divide two longs
/// </summary>
internal static long Divide(long a, long b)
{
return a / b;
}
/// <summary>
/// Modulo two doubles
/// </summary>
internal static double Modulo(double a, double b)
{
return a % b;
}
/// <summary>
/// Modulo two longs
/// </summary>
internal static long Modulo(long a, long b)
{
return a % b;
}
/// <summary>
/// Escape the string according to MSBuild's escaping rules
/// </summary>
internal static string Escape(string unescaped)
{
return EscapingUtilities.Escape(unescaped);
}
/// <summary>
/// Unescape the string according to MSBuild's escaping rules
/// </summary>
internal static string Unescape(string escaped)
{
return EscapingUtilities.UnescapeAll(escaped);
}
/// <summary>
/// Perform a bitwise OR on the first and second (first | second)
/// </summary>
internal static int BitwiseOr(int first, int second)
{
return first | second;
}
/// <summary>
/// Perform a bitwise AND on the first and second (first & second)
/// </summary>
internal static int BitwiseAnd(int first, int second)
{
return first & second;
}
/// <summary>
/// Perform a bitwise XOR on the first and second (first ^ second)
/// </summary>
internal static int BitwiseXor(int first, int second)
{
return first ^ second;
}
/// <summary>
/// Perform a bitwise NOT on the first and second (~first)
/// </summary>
internal static int BitwiseNot(int first)
{
return ~first;
}
/// <summary>
/// Get the value of the registry key and value, default value is null
/// </summary>
internal static object GetRegistryValue(string keyName, string valueName)
{
return Registry.GetValue(keyName, valueName, null /* null to match the $(Regsitry:XYZ@ZBC) behaviour */);
}
/// <summary>
/// Get the value of the registry key and value
/// </summary>
internal static object GetRegistryValue(string keyName, string valueName, object defaultValue)
{
return Registry.GetValue(keyName, valueName, defaultValue);
}
/// <summary>
/// Get the value of the registry key from one of the RegistryView's specified
/// </summary>
internal static object GetRegistryValueFromView(string keyName, string valueName, object defaultValue, params object[] views)
{
string subKeyName;
// We will take on handing of default value
// A we need to act on the null return from the GetValue call below
// so we can keep searching other registry views
object result = defaultValue;
// If we haven't been passed any views, then we'll just use the default view
if (views == null || views.Length == 0)
{
views = new object[] { RegistryView.Default };
}
foreach (object viewObject in views)
{
string viewAsString = viewObject as string;
if (viewAsString != null)
{
string typeLeafName = typeof(RegistryView).Name + ".";
string typeFullName = typeof(RegistryView).FullName + ".";
// We'll allow the user to specify the leaf or full type name on the RegistryView enum
viewAsString = viewAsString.Replace(typeFullName, "").Replace(typeLeafName, "");
// This may throw - and that's fine as the user will receive a controlled version
// of that error.
RegistryView view = (RegistryView)Enum.Parse(typeof(RegistryView), viewAsString, true);
using (RegistryKey key = GetBaseKeyFromKeyName(keyName, view, out subKeyName))
{
if (key != null)
{
using (RegistryKey subKey = key.OpenSubKey(subKeyName, false))
{
// If we managed to retrieve the subkey, then move onto locating the value
if (subKey != null)
{
result = subKey.GetValue(valueName);
}
// We've found a value, so stop looking
if (result != null)
{
break;
}
}
}
}
}
}
// We will have either found a result or defaultValue if one wasn't found at this point
return result;
}
/// <summary>
/// Given the absolute location of a file, and a disc location, returns relative file path to that disk location.
/// Throws UriFormatException.
/// </summary>
/// <param name="basePath">
/// The base path we want to relativize to. Must be absolute.
/// Should <i>not</i> include a filename as the last segment will be interpreted as a directory.
/// </param>
/// <param name="path">
/// The path we need to make relative to basePath. The path can be either absolute path or a relative path in which case it is relative to the base path.
/// If the path cannot be made relative to the base path (for example, it is on another drive), it is returned verbatim.
/// </param>
/// <returns>relative path (can be the full path)</returns>
internal static string MakeRelative(string basePath, string path)
{
string result = FileUtilities.MakeRelative(basePath, path);
return result;
}
/// <summary>
/// Locate a file in either the directory specified or a location in the
/// direcorty structure above that directory.
/// </summary>
internal static string GetDirectoryNameOfFileAbove(string startingDirectory, string fileName)
{
// Canonicalize our starting location
string lookInDirectory = Path.GetFullPath(startingDirectory);
do
{
// Construct the path that we will use to test against
string possibleFileDirectory = Path.Combine(lookInDirectory, fileName);
// If we successfully locate the file in the directory that we're
// looking in, simply return that location. Otherwise we'll
// keep moving up the tree.
if (File.Exists(possibleFileDirectory))
{
// We've found the file, return the directory we found it in
return lookInDirectory;
}
else
{
// GetDirectoryName will return null when we reach the root
// terminating our search
lookInDirectory = Path.GetDirectoryName(lookInDirectory);
}
}
while (lookInDirectory != null);
// When we didn't find the location, then return an empty string
return String.Empty;
}
/// <summary>
/// Return the string in parameter 'defaultValue' only if parameter 'conditionValue' is empty
/// else, return the value conditionValue
/// </summary>
internal static string ValueOrDefault(string conditionValue, string defaultValue)
{
if (String.IsNullOrEmpty(conditionValue))
{
return defaultValue;
}
else
{
return conditionValue;
}
}
/// <summary>
/// Returns true if a task host exists that can service the requested runtime and architecture
/// values, and false otherwise.
/// </summary>
/// <comments>
/// The old engine ignores the concept of the task host entirely, so it shouldn't really
/// matter what we return. So we return "true" because regardless of the task host parameters,
/// the task will be successfully run (in-proc).
/// </comments>
internal static bool DoesTaskHostExist(string runtime, string architecture)
{
return true;
}
#region Debug only intrinsics
/// <summary>
/// returns if the string contains escaped wildcards
/// </summary>
internal static List<string> __GetListTest()
{
return new List<string> { "A", "B", "C", "D" };
}
#endregion
/// <summary>
/// Following function will parse a keyName and returns the basekey for it.
/// It will also store the subkey name in the out parameter.
/// If the keyName is not valid, we will throw ArgumentException.
/// The return value shouldn't be null.
/// Taken from: \ndp\clr\src\BCL\Microsoft\Win32\Registry.cs
/// </summary>
private static RegistryKey GetBaseKeyFromKeyName(string keyName, RegistryView view, out string subKeyName)
{
if (keyName == null)
{
throw new ArgumentNullException(nameof(keyName));
}
string basekeyName;
int i = keyName.IndexOf('\\');
if (i != -1)
{
basekeyName = keyName.Substring(0, i).ToUpper(System.Globalization.CultureInfo.InvariantCulture);
}
else
{
basekeyName = keyName.ToUpper(System.Globalization.CultureInfo.InvariantCulture);
}
RegistryKey basekey = null;
switch (basekeyName)
{
case "HKEY_CURRENT_USER":
basekey = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, view);
break;
case "HKEY_LOCAL_MACHINE":
basekey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, view);
break;
case "HKEY_CLASSES_ROOT":
basekey = RegistryKey.OpenBaseKey(RegistryHive.ClassesRoot, view);
break;
case "HKEY_USERS":
basekey = RegistryKey.OpenBaseKey(RegistryHive.Users, view);
break;
case "HKEY_PERFORMANCE_DATA":
basekey = RegistryKey.OpenBaseKey(RegistryHive.PerformanceData, view);
break;
case "HKEY_CURRENT_CONFIG":
basekey = RegistryKey.OpenBaseKey(RegistryHive.CurrentConfig, view);
break;
case "HKEY_DYN_DATA":
basekey = RegistryKey.OpenBaseKey(RegistryHive.DynData, view);
break;
default:
ErrorUtilities.ThrowArgument(keyName);
break;
}
if (i == -1 || i == keyName.Length)
{
subKeyName = string.Empty;
}
else
{
subKeyName = keyName.Substring(i + 1, keyName.Length - i - 1);
}
return basekey;
}
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.Runtime.Serialization
{
using System;
using System.Xml;
using System.Xml.Schema;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using DataContractDictionary = System.Collections.Generic.Dictionary<System.Xml.XmlQualifiedName, DataContract>;
using System.Text;
internal class DataContractSet
{
Dictionary<XmlQualifiedName, DataContract> contracts;
Dictionary<DataContract, object> processedContracts;
IDataContractSurrogate dataContractSurrogate;
Hashtable surrogateDataTable;
DataContractDictionary knownTypesForObject;
ICollection<Type> referencedTypes;
ICollection<Type> referencedCollectionTypes;
Dictionary<XmlQualifiedName, object> referencedTypesDictionary;
Dictionary<XmlQualifiedName, object> referencedCollectionTypesDictionary;
internal DataContractSet(IDataContractSurrogate dataContractSurrogate) : this(dataContractSurrogate, null, null) { }
internal DataContractSet(IDataContractSurrogate dataContractSurrogate, ICollection<Type> referencedTypes, ICollection<Type> referencedCollectionTypes)
{
this.dataContractSurrogate = dataContractSurrogate;
this.referencedTypes = referencedTypes;
this.referencedCollectionTypes = referencedCollectionTypes;
}
internal DataContractSet(DataContractSet dataContractSet)
{
if (dataContractSet == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("dataContractSet"));
this.dataContractSurrogate = dataContractSet.dataContractSurrogate;
this.referencedTypes = dataContractSet.referencedTypes;
this.referencedCollectionTypes = dataContractSet.referencedCollectionTypes;
foreach (KeyValuePair<XmlQualifiedName, DataContract> pair in dataContractSet)
{
Add(pair.Key, pair.Value);
}
if (dataContractSet.processedContracts != null)
{
foreach (KeyValuePair<DataContract, object> pair in dataContractSet.processedContracts)
{
ProcessedContracts.Add(pair.Key, pair.Value);
}
}
}
Dictionary<XmlQualifiedName, DataContract> Contracts
{
get
{
if (contracts == null)
{
contracts = new Dictionary<XmlQualifiedName, DataContract>();
}
return contracts;
}
}
Dictionary<DataContract, object> ProcessedContracts
{
get
{
if (processedContracts == null)
{
processedContracts = new Dictionary<DataContract, object>();
}
return processedContracts;
}
}
Hashtable SurrogateDataTable
{
get
{
if (surrogateDataTable == null)
surrogateDataTable = new Hashtable();
return surrogateDataTable;
}
}
internal DataContractDictionary KnownTypesForObject
{
get { return knownTypesForObject; }
set { knownTypesForObject = value; }
}
internal void Add(Type type)
{
DataContract dataContract = GetDataContract(type);
EnsureTypeNotGeneric(dataContract.UnderlyingType);
Add(dataContract);
}
internal static void EnsureTypeNotGeneric(Type type)
{
if (type.ContainsGenericParameters)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.GenericTypeNotExportable, type)));
}
void Add(DataContract dataContract)
{
Add(dataContract.StableName, dataContract);
}
public void Add(XmlQualifiedName name, DataContract dataContract)
{
if (dataContract.IsBuiltInDataContract)
return;
InternalAdd(name, dataContract);
}
internal void InternalAdd(XmlQualifiedName name, DataContract dataContract)
{
DataContract dataContractInSet = null;
if (Contracts.TryGetValue(name, out dataContractInSet))
{
if (!dataContractInSet.Equals(dataContract))
{
if (dataContract.UnderlyingType == null || dataContractInSet.UnderlyingType == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.DupContractInDataContractSet, dataContract.StableName.Name, dataContract.StableName.Namespace)));
else
{
bool typeNamesEqual = (DataContract.GetClrTypeFullName(dataContract.UnderlyingType) == DataContract.GetClrTypeFullName(dataContractInSet.UnderlyingType));
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.DupTypeContractInDataContractSet, (typeNamesEqual ? dataContract.UnderlyingType.AssemblyQualifiedName : DataContract.GetClrTypeFullName(dataContract.UnderlyingType)), (typeNamesEqual ? dataContractInSet.UnderlyingType.AssemblyQualifiedName : DataContract.GetClrTypeFullName(dataContractInSet.UnderlyingType)), dataContract.StableName.Name, dataContract.StableName.Namespace)));
}
}
}
else
{
Contracts.Add(name, dataContract);
if (dataContract is ClassDataContract)
{
AddClassDataContract((ClassDataContract)dataContract);
}
else if (dataContract is CollectionDataContract)
{
AddCollectionDataContract((CollectionDataContract)dataContract);
}
else if (dataContract is XmlDataContract)
{
AddXmlDataContract((XmlDataContract)dataContract);
}
}
}
void AddClassDataContract(ClassDataContract classDataContract)
{
if (classDataContract.BaseContract != null)
{
Add(classDataContract.BaseContract.StableName, classDataContract.BaseContract);
}
if (!classDataContract.IsISerializable)
{
if (classDataContract.Members != null)
{
for (int i = 0; i < classDataContract.Members.Count; i++)
{
DataMember dataMember = classDataContract.Members[i];
DataContract memberDataContract = GetMemberTypeDataContract(dataMember);
if (dataContractSurrogate != null && dataMember.MemberInfo != null)
{
object customData = DataContractSurrogateCaller.GetCustomDataToExport(
dataContractSurrogate,
dataMember.MemberInfo,
memberDataContract.UnderlyingType);
if (customData != null)
SurrogateDataTable.Add(dataMember, customData);
}
Add(memberDataContract.StableName, memberDataContract);
}
}
}
AddKnownDataContracts(classDataContract.KnownDataContracts);
}
void AddCollectionDataContract(CollectionDataContract collectionDataContract)
{
if (collectionDataContract.IsDictionary)
{
ClassDataContract keyValueContract = collectionDataContract.ItemContract as ClassDataContract;
AddClassDataContract(keyValueContract);
}
else
{
DataContract itemContract = GetItemTypeDataContract(collectionDataContract);
if (itemContract != null)
Add(itemContract.StableName, itemContract);
}
AddKnownDataContracts(collectionDataContract.KnownDataContracts);
}
void AddXmlDataContract(XmlDataContract xmlDataContract)
{
AddKnownDataContracts(xmlDataContract.KnownDataContracts);
}
void AddKnownDataContracts(DataContractDictionary knownDataContracts)
{
if (knownDataContracts != null)
{
foreach (DataContract knownDataContract in knownDataContracts.Values)
{
Add(knownDataContract);
}
}
}
internal XmlQualifiedName GetStableName(Type clrType)
{
if (dataContractSurrogate != null)
{
Type dcType = DataContractSurrogateCaller.GetDataContractType(dataContractSurrogate, clrType);
//if (clrType.IsValueType != dcType.IsValueType)
// throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.ValueTypeMismatchInSurrogatedType, dcType, clrType)));
return DataContract.GetStableName(dcType);
}
return DataContract.GetStableName(clrType);
}
internal DataContract GetDataContract(Type clrType)
{
if (dataContractSurrogate == null)
return DataContract.GetDataContract(clrType);
DataContract dataContract = DataContract.GetBuiltInDataContract(clrType);
if (dataContract != null)
return dataContract;
Type dcType = DataContractSurrogateCaller.GetDataContractType(dataContractSurrogate, clrType);
//if (clrType.IsValueType != dcType.IsValueType)
// throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.ValueTypeMismatchInSurrogatedType, dcType, clrType)));
dataContract = DataContract.GetDataContract(dcType);
if (!SurrogateDataTable.Contains(dataContract))
{
object customData = DataContractSurrogateCaller.GetCustomDataToExport(
dataContractSurrogate, clrType, dcType);
if (customData != null)
SurrogateDataTable.Add(dataContract, customData);
}
return dataContract;
}
internal DataContract GetMemberTypeDataContract(DataMember dataMember)
{
if (dataMember.MemberInfo != null)
{
Type dataMemberType = dataMember.MemberType;
if (dataMember.IsGetOnlyCollection)
{
if (dataContractSurrogate != null)
{
Type dcType = DataContractSurrogateCaller.GetDataContractType(dataContractSurrogate, dataMemberType);
if (dcType != dataMemberType)
{
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.SurrogatesWithGetOnlyCollectionsNotSupported,
DataContract.GetClrTypeFullName(dataMemberType), DataContract.GetClrTypeFullName(dataMember.MemberInfo.DeclaringType), dataMember.MemberInfo.Name)));
}
}
return DataContract.GetGetOnlyCollectionDataContract(DataContract.GetId(dataMemberType.TypeHandle), dataMemberType.TypeHandle, dataMemberType, SerializationMode.SharedContract);
}
else
{
return GetDataContract(dataMemberType);
}
}
return dataMember.MemberTypeContract;
}
internal DataContract GetItemTypeDataContract(CollectionDataContract collectionContract)
{
if (collectionContract.ItemType != null)
return GetDataContract(collectionContract.ItemType);
return collectionContract.ItemContract;
}
internal object GetSurrogateData(object key)
{
return SurrogateDataTable[key];
}
internal void SetSurrogateData(object key, object surrogateData)
{
SurrogateDataTable[key] = surrogateData;
}
public DataContract this[XmlQualifiedName key]
{
get
{
DataContract dataContract = DataContract.GetBuiltInDataContract(key.Name, key.Namespace);
if (dataContract == null)
{
Contracts.TryGetValue(key, out dataContract);
}
return dataContract;
}
}
public IDataContractSurrogate DataContractSurrogate
{
get { return dataContractSurrogate; }
}
public bool Remove(XmlQualifiedName key)
{
if (DataContract.GetBuiltInDataContract(key.Name, key.Namespace) != null)
return false;
return Contracts.Remove(key);
}
public IEnumerator<KeyValuePair<XmlQualifiedName, DataContract>> GetEnumerator()
{
return Contracts.GetEnumerator();
}
internal bool IsContractProcessed(DataContract dataContract)
{
return ProcessedContracts.ContainsKey(dataContract);
}
internal void SetContractProcessed(DataContract dataContract)
{
ProcessedContracts.Add(dataContract, dataContract);
}
internal ContractCodeDomInfo GetContractCodeDomInfo(DataContract dataContract)
{
object info;
if (ProcessedContracts.TryGetValue(dataContract, out info))
return (ContractCodeDomInfo)info;
return null;
}
internal void SetContractCodeDomInfo(DataContract dataContract, ContractCodeDomInfo info)
{
ProcessedContracts.Add(dataContract, info);
}
Dictionary<XmlQualifiedName, object> GetReferencedTypes()
{
if (referencedTypesDictionary == null)
{
referencedTypesDictionary = new Dictionary<XmlQualifiedName, object>();
//Always include Nullable as referenced type
//Do not allow surrogating Nullable<T>
referencedTypesDictionary.Add(DataContract.GetStableName(Globals.TypeOfNullable), Globals.TypeOfNullable);
if (this.referencedTypes != null)
{
foreach (Type type in this.referencedTypes)
{
if (type == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ReferencedTypesCannotContainNull)));
AddReferencedType(referencedTypesDictionary, type);
}
}
}
return referencedTypesDictionary;
}
Dictionary<XmlQualifiedName, object> GetReferencedCollectionTypes()
{
if (referencedCollectionTypesDictionary == null)
{
referencedCollectionTypesDictionary = new Dictionary<XmlQualifiedName, object>();
if (this.referencedCollectionTypes != null)
{
foreach (Type type in this.referencedCollectionTypes)
{
if (type == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ReferencedCollectionTypesCannotContainNull)));
AddReferencedType(referencedCollectionTypesDictionary, type);
}
}
XmlQualifiedName genericDictionaryName = DataContract.GetStableName(Globals.TypeOfDictionaryGeneric);
if (!referencedCollectionTypesDictionary.ContainsKey(genericDictionaryName) && GetReferencedTypes().ContainsKey(genericDictionaryName))
AddReferencedType(referencedCollectionTypesDictionary, Globals.TypeOfDictionaryGeneric);
}
return referencedCollectionTypesDictionary;
}
void AddReferencedType(Dictionary<XmlQualifiedName, object> referencedTypes, Type type)
{
if (IsTypeReferenceable(type))
{
XmlQualifiedName stableName;
try
{
stableName = this.GetStableName(type);
}
catch (InvalidDataContractException)
{
// Type not referenceable if we can't get a stable name.
return;
}
catch (InvalidOperationException)
{
// Type not referenceable if we can't get a stable name.
return;
}
object value;
if (referencedTypes.TryGetValue(stableName, out value))
{
Type referencedType = value as Type;
if (referencedType != null)
{
if (referencedType != type)
{
referencedTypes.Remove(stableName);
List<Type> types = new List<Type>();
types.Add(referencedType);
types.Add(type);
referencedTypes.Add(stableName, types);
}
}
else
{
List<Type> types = (List<Type>)value;
if (!types.Contains(type))
types.Add(type);
}
}
else
referencedTypes.Add(stableName, type);
}
}
internal bool TryGetReferencedType(XmlQualifiedName stableName, DataContract dataContract, out Type type)
{
return TryGetReferencedType(stableName, dataContract, false/*useReferencedCollectionTypes*/, out type);
}
internal bool TryGetReferencedCollectionType(XmlQualifiedName stableName, DataContract dataContract, out Type type)
{
return TryGetReferencedType(stableName, dataContract, true/*useReferencedCollectionTypes*/, out type);
}
bool TryGetReferencedType(XmlQualifiedName stableName, DataContract dataContract, bool useReferencedCollectionTypes, out Type type)
{
object value;
Dictionary<XmlQualifiedName, object> referencedTypes = useReferencedCollectionTypes ? GetReferencedCollectionTypes() : GetReferencedTypes();
if (referencedTypes.TryGetValue(stableName, out value))
{
type = value as Type;
if (type != null)
return true;
else
{
// Throw ambiguous type match exception
List<Type> types = (List<Type>)value;
StringBuilder errorMessage = new StringBuilder();
bool containsGenericType = false;
for (int i = 0; i < types.Count; i++)
{
Type conflictingType = types[i];
if (!containsGenericType)
containsGenericType = conflictingType.IsGenericTypeDefinition;
errorMessage.AppendFormat("{0}\"{1}\" ", Environment.NewLine, conflictingType.AssemblyQualifiedName);
if (dataContract != null)
{
DataContract other = this.GetDataContract(conflictingType);
errorMessage.Append(SR.GetString(((other != null && other.Equals(dataContract)) ? SR.ReferencedTypeMatchingMessage : SR.ReferencedTypeNotMatchingMessage)));
}
}
if (containsGenericType)
{
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(
(useReferencedCollectionTypes ? SR.AmbiguousReferencedCollectionTypes1 : SR.AmbiguousReferencedTypes1),
errorMessage.ToString())));
}
else
{
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(
(useReferencedCollectionTypes ? SR.AmbiguousReferencedCollectionTypes3 : SR.AmbiguousReferencedTypes3),
XmlConvert.DecodeName(stableName.Name),
stableName.Namespace,
errorMessage.ToString())));
}
}
}
type = null;
return false;
}
static bool IsTypeReferenceable(Type type)
{
Type itemType;
try
{
return (type.IsSerializable ||
type.IsDefined(Globals.TypeOfDataContractAttribute, false) ||
(Globals.TypeOfIXmlSerializable.IsAssignableFrom(type) && !type.IsGenericTypeDefinition) ||
CollectionDataContract.IsCollection(type, out itemType) ||
ClassDataContract.IsNonAttributedTypeValidForSerialization(type));
}
catch (System.IO.FileLoadException)
{ // this can happen in Type.IsDefined when trying to load a referenced library that is not available at design time.
}
return false;
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2011 Charlie Poole, Rob Prouse
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Security;
using System.Threading;
namespace NUnit.Framework.Internal
{
/// <summary>
/// ThreadUtility provides a set of static methods convenient
/// for working with threads.
/// </summary>
public static class ThreadUtility
{
internal static void BlockingDelay(int milliseconds)
{
#if NETSTANDARD1_6
System.Threading.Tasks.Task.Delay(milliseconds).GetAwaiter().GetResult();
#else
Thread.Sleep(milliseconds);
#endif
}
#if THREAD_ABORT
private const int ThreadAbortedCheckDelay = 100;
/// <summary>
/// Pre-Task compatibility
/// </summary>
public static void Delay(int milliseconds, WaitCallback threadPoolWork, object state = null)
{
new DelayClosure(milliseconds, threadPoolWork, state);
}
private sealed class DelayClosure
{
private readonly Timer _timer;
private readonly WaitCallback _threadPoolWork;
private readonly object _state;
public DelayClosure(int milliseconds, WaitCallback threadPoolWork, object state)
{
_threadPoolWork = threadPoolWork;
_state = state;
_timer = new Timer(Callback, null, Timeout.Infinite, Timeout.Infinite);
// Make sure _timer is set before starting the timer so that it is disposed.
_timer.Change(milliseconds, Timeout.Infinite);
}
private void Callback(object _)
{
_timer.Dispose();
_threadPoolWork.Invoke(_state);
}
}
/// <summary>
/// Abort a thread, helping to dislodging it if it is blocked in native code
/// </summary>
/// <param name="thread">The thread to abort</param>
/// <param name="nativeId">The native thread id (if known), otherwise 0.
/// If provided, allows the thread to be killed if it's in a message pump native blocking wait.
/// This must have previously been captured by calling <see cref="GetCurrentThreadNativeId"/> from the running thread itself.</param>
public static void Abort(Thread thread, int nativeId = 0)
{
if (nativeId != 0)
DislodgeThreadInNativeMessageWait(thread, nativeId);
thread.Abort();
}
/// <summary>
/// Do our best to kill a thread
/// </summary>
/// <param name="thread">The thread to kill</param>
/// <param name="nativeId">The native thread id (if known), otherwise 0.
/// If provided, allows the thread to be killed if it's in a message pump native blocking wait.
/// This must have previously been captured by calling <see cref="GetCurrentThreadNativeId"/> from the running thread itself.</param>
public static void Kill(Thread thread, int nativeId = 0)
{
Kill(thread, null, nativeId);
}
/// <summary>
/// Do our best to kill a thread, passing state info
/// </summary>
/// <param name="thread">The thread to kill</param>
/// <param name="stateInfo">Info for the ThreadAbortException handler</param>
/// <param name="nativeId">The native thread id (if known), otherwise 0.
/// If provided, allows the thread to be killed if it's in a message pump native blocking wait.
/// This must have previously been captured by calling <see cref="GetCurrentThreadNativeId"/> from the running thread itself.</param>
public static void Kill(Thread thread, object stateInfo, int nativeId = 0)
{
if (nativeId != 0)
DislodgeThreadInNativeMessageWait(thread, nativeId);
try
{
if (stateInfo == null)
thread.Abort();
else
thread.Abort(stateInfo);
}
catch (ThreadStateException)
{
// Although obsolete, this use of Resume() takes care of
// the odd case where a ThreadStateException is received.
#pragma warning disable 0618,0612 // Thread.Resume has been deprecated
thread.Resume();
#pragma warning restore 0618,0612 // Thread.Resume has been deprecated
}
if ( (thread.ThreadState & ThreadState.WaitSleepJoin) != 0 )
thread.Interrupt();
}
/// <summary>
/// Schedule a threadpool thread to check on the aborting thread in case it's in a message pump native blocking wait
/// </summary>
private static void DislodgeThreadInNativeMessageWait(Thread thread, int nativeId)
{
if (nativeId == 0) throw new ArgumentOutOfRangeException(nameof(nativeId), "Native thread ID must not be zero.");
// Schedule a threadpool thread to check on the aborting thread in case it's in a message pump native blocking wait
Delay(ThreadAbortedCheckDelay, CheckOnAbortingThread, new CheckOnAbortingThreadState(thread, nativeId));
}
private static void CheckOnAbortingThread(object state)
{
var context = (CheckOnAbortingThreadState)state;
switch (context.Thread.ThreadState)
{
case ThreadState.Aborted:
return;
case ThreadState.AbortRequested:
PostThreadCloseMessage(context.NativeId);
break;
}
Delay(ThreadAbortedCheckDelay, CheckOnAbortingThread, state);
}
private sealed class CheckOnAbortingThreadState
{
public Thread Thread { get; }
public int NativeId { get; }
public CheckOnAbortingThreadState(Thread thread, int nativeId)
{
Thread = thread;
NativeId = nativeId;
}
}
private static bool isNotOnWindows;
/// <summary>
/// Captures the current thread's native id. If provided to <see cref="Kill(Thread,int)"/> later, allows the thread to be killed if it's in a message pump native blocking wait.
/// </summary>
[SecuritySafeCritical]
public static int GetCurrentThreadNativeId()
{
if (isNotOnWindows) return 0;
try
{
return GetCurrentThreadId();
}
catch (EntryPointNotFoundException)
{
isNotOnWindows = true;
return 0;
}
}
/// <summary>
/// Sends a message to the thread to dislodge it from native code and allow a return to managed code, where a ThreadAbortException can be generated.
/// The message is meaningless (WM_CLOSE without a window handle) but it will end any blocking message wait.
/// </summary>
[SecuritySafeCritical]
private static void PostThreadCloseMessage(int nativeId)
{
if (!PostThreadMessage(nativeId, WM.CLOSE, IntPtr.Zero, IntPtr.Zero))
{
const int ERROR_INVALID_THREAD_ID = 0x5A4;
var errorCode = Marshal.GetLastWin32Error();
if (errorCode != ERROR_INVALID_THREAD_ID)
throw new Win32Exception(errorCode);
}
}
[DllImport("kernel32.dll")]
private static extern int GetCurrentThreadId();
[DllImport("user32.dll", SetLastError = true)]
private static extern bool PostThreadMessage(int id, WM msg, IntPtr wParam, IntPtr lParam);
private enum WM : uint
{
CLOSE = 0x0010
}
#endif
}
}
| |
/*
* MindTouch Core - open source enterprise collaborative networking
* Copyright (c) 2006-2010 MindTouch Inc.
* www.mindtouch.com oss@mindtouch.com
*
* For community documentation and downloads visit www.opengarden.org;
* please review the licensing section.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
* http://www.gnu.org/copyleft/gpl.html
*/
using System;
using MindTouch.Tasking;
using NUnit.Framework;
using MindTouch.Dream;
using MindTouch.Xml;
using MindTouch.Dream.Test;
namespace MindTouch.Deki.Tests.UserTests
{
[TestFixture]
public class DekiWiki_UsersTest
{
/// <summary>
/// Create a user
/// </summary>
/// <feature>
/// <name>POST:users</name>
/// <uri>http://developer.mindtouch.com/en/ref/MindTouch_API/POST%3ausers</uri>
/// </feature>
/// <expected>User creation successful and POST response metadata matches sent information</expected>
[Test]
public void CreateUser()
{
// Build ADMIN plug
Plug p = Utils.BuildPlugForAdmin();
try
{
// Define user information and generate user XML document
string name = Utils.GenerateUniqueName();
string email = "newuser1@mindtouch.com";
string fullName = "newuser1's full name";
string role = "Contributor";
XDoc usersDoc = new XDoc("user")
.Elem("username", name)
.Elem("email", email)
.Elem("fullname", fullName)
.Start("permissions.user")
.Elem("role", role)
.End();
// Create the User
DreamMessage msg = p.At("users").Post(usersDoc);
Assert.AreEqual(DreamStatus.Ok, msg.Status, "User creation failed");
// Assert all the information in the returned document is consistent
Assert.IsTrue(msg.ToDocument()["username"].AsText == name, "Name does not match that in return document");
Assert.IsTrue(msg.ToDocument()["email"].AsText == email, "Email does not match that in return document");
Assert.IsTrue(msg.ToDocument()["fullname"].AsText == fullName, "Full name does not match that in return document");
Assert.IsTrue(msg.ToDocument()["permissions.user/role"].AsText == role, "User permissions does not match that in return document");
}
// In the case the username already exists
catch (MindTouch.Dream.DreamResponseException ex)
{
Assert.IsTrue(ex.Response.Status == DreamStatus.Conflict, "Username already exists, but did not return Conflict?!");
}
}
/// <summary>
/// Set a new user password
/// </summary>
/// <feature>
/// <name>PUT:users/{userid}/password</name>
/// <uri>http://developer.mindtouch.com/en/ref/MindTouch_API/PUT%3ausers%2f%2f%7Buserid%7D%2f%2fpassword</uri>
/// </feature>
/// <expected>Successful authentication through new username/password credentials</expected>
[Test]
public void SetUserPassword()
{
// Build ADMIN plug
Plug p = Utils.BuildPlugForAdmin();
// Create a random contributor
string id = null;
string name = null;
DreamMessage msg = UserUtils.CreateRandomContributor(p, out id, out name);
// Set a new password "newpassword" for the user
msg = DreamMessage.Ok(MimeType.TEXT, "newpassword");
msg = p.At("users", "=" + name, "password").Put(msg);
Assert.AreEqual(DreamStatus.Ok, msg.Status, "Setting password failed");
// "Log out" of ADMIN
p = Utils.BuildPlugForAnonymous();
// Build a plug for username/newpassword and assert authentication is successful
msg = p.WithCredentials(name, "newpassword").At("users", "authenticate").Get();
Assert.AreEqual(DreamStatus.Ok, msg.Status, "User authentication failed");
}
/// <summary>
/// Set an alternative user password
/// </summary>
/// <feature>
/// <name>PUT:users/{userid}/password</name>
/// <uri>http://developer.mindtouch.com/en/ref/MindTouch_API/PUT%3ausers%2f%2f%7Buserid%7D%2f%2fpassword</uri>
/// <parameter>altpassword</parameter>
/// </feature>
/// <expected>Successful authentication through alternative username/password credentials</expected>
[Test]
public void SetUserAltPassword()
{
// Build ADMIN plug
Plug p = Utils.BuildPlugForAdmin();
// Create a random contributor
string id = null;
string name = null;
DreamMessage msg = UserUtils.CreateRandomContributor(p, out id, out name);
// Set a new password "newpassword" for the user
msg = DreamMessage.Ok(MimeType.TEXT, "newpassword");
msg = p.At("users", "=" + name, "password").Put(msg);
Assert.AreEqual(DreamStatus.Ok, msg.Status, "Password set failed");
// Set an alternative password "altpassword" for the user
msg = DreamMessage.Ok(MimeType.TEXT, "newaltpassword");
msg = p.At("users", "=" + name, "password").With("altpassword", true).Put(msg);
Assert.AreEqual(DreamStatus.Ok, msg.Status, "Alternative password set failed");
// "Log out" of ADMIN and build plug for the user using the alternative password
p = Utils.BuildPlugForAnonymous();
msg = p.WithCredentials(name, "newaltpassword").At("users", "authenticate").Get();
Assert.AreEqual(DreamStatus.Ok, msg.Status, "Authentication with new alternative password failed");
// "Log out" again and build plug using the new password
p = Utils.BuildPlugForAnonymous();
msg = p.WithCredentials(name, "newpassword").At("users", "authenticate").Get();
Assert.AreEqual(DreamStatus.Ok, msg.Status, "Authentication with new password failed");
}
/// <summary>
/// Retrieve user list
/// </summary>
/// <feature>
/// <name>GET:users</name>
/// <uri>http://developer.mindtouch.com/en/ref/MindTouch_API/GET%3ausers</uri>
/// </feature>
/// <expected>200 OK HTTP response</expected>
[Test]
public void GetUsers()
{
// Build ADMIN plug
Plug p = Utils.BuildPlugForAdmin();
// Retrieve user list
DreamMessage msg = p.At("users").Get();
Assert.AreEqual(DreamStatus.Ok, msg.Status, "User list retrieval failed");
}
/// <summary>
/// Retrieve user data by name/ID
/// </summary>
/// <feature>
/// <name>GET:users/{userid}</name>
/// <uri>http://developer.mindtouch.com/en/ref/MindTouch_API/GET%3ausers%2f%2f%7buserid%7d</uri>
/// </feature>
/// <expected>Generated user information matches subsequent retrieved user metadata</expected>
[Test]
public void GetUser()
{
// Build ADMIN plug
Plug p = Utils.BuildPlugForAdmin();
// Create a random contributor
string id = null;
string name = null;
DreamMessage msg = UserUtils.CreateRandomContributor(p, out id, out name);
// Retrieve the user by name and assert that the retrieved document name element matches generated name
msg = p.At("users", "=" + name).Get();
Assert.AreEqual(DreamStatus.Ok, msg.Status, "User retrieval by name failed");
Assert.IsTrue(msg.ToDocument()["username"].AsText == name, "Name in retrieved user (by name) document does not match generated name!");
// Retrieve the user by ID and perform the same check
msg = p.At("users", id).Get();
Assert.AreEqual(DreamStatus.Ok, msg.Status, "User retrieval by ID failed");
Assert.IsTrue(msg.ToDocument()["username"].AsText == name, "Name in retrieved user (by ID) document does not match generated name!");
// Retrieve the current user (ADMIN) and assert the retrieved document shows the correct name and role
msg = p.At("users", "current").Get();
Assert.AreEqual(DreamStatus.Ok, msg.Status, "Retrieval of current user failed! " + msg.ToText());
Assert.AreEqual(Utils.Settings.UserName.ToLower(), msg.ToDocument()["username"].AsText.ToLower(), "Current user is not 'Admin'?!");
Assert.AreEqual("Admin", msg.ToDocument()["permissions.user/role"].AsText, "Current user does not have ADMIN permissions?!");
}
/// <summary>
/// Update user information through POST request
/// </summary>
/// <feature>
/// <name>POST:users</name>
/// <uri>http://developer.mindtouch.com/en/ref/MindTouch_API/POST%3ausers</uri>
/// </feature>
/// <expected>Updated user information matches POST method response metadata</expected>
[Test]
public void ChangeUserThroughPost()
{
// Build ADMIN plug
Plug p = Utils.BuildPlugForAdmin();
// Create a random contributor
string id = null;
string name = null;
DreamMessage msg = UserUtils.CreateRandomContributor(p, out id, out name);
// Define user information and generate user XML document
string newemail = "newpostusermail@mindtouch.com";
string newfullName = "new post full name";
string newrole = "Viewer";
string newTimezone = "-08:00";
XDoc usersDoc = new XDoc("user").Attr("id", id)
.Elem("email", newemail)
.Elem("fullname", newfullName)
.Elem("timezone", newTimezone)
.Start("permissions.user")
.Elem("role", newrole)
.End();
// Replace random contributor's information with new information
msg = p.At("users").Post(usersDoc);
Assert.AreEqual(DreamStatus.Ok, msg.Status, "User update failed");
// Assert returned POST method document metadata is consistent with the XML request information
Assert.IsTrue(msg.ToDocument()["username"].AsText == name, "Name does not match that in return document");
Assert.IsTrue(msg.ToDocument()["email"].AsText == newemail, "Email does not match that in return document");
Assert.IsTrue(msg.ToDocument()["fullname"].AsText == newfullName, "Full name does not match that in return document");
Assert.IsTrue(msg.ToDocument()["permissions.user/role"].AsText == newrole, "User permissions does not match that in return document");
Assert.AreEqual(newTimezone, msg.ToDocument()["timezone"].AsText, "Timezone does not match that in return document");
}
/// <summary>
/// Update user information through PUT request
/// </summary>
/// <feature>
/// <name>PUT:users/{userid}</name>
/// <uri>http://developer.mindtouch.com/en/ref/MindTouch_API/PUT%3ausers%2f%2f%7Buserid%7D</uri>
/// </feature>
/// <expected>Updated user information matches PUT method response metadata</expected>
[Test]
public void ChangeUserThroughPUT()
{
// Build ADMIN plug
Plug p = Utils.BuildPlugForAdmin();
// Create a random contributor
string id = null;
string name = null;
DreamMessage msg = UserUtils.CreateRandomContributor(p, out id, out name);
// Define user information and generate user XML document
string newemail = "newusermail@mindtouch.com";
string newfullName = "new full name";
string newrole = "Viewer";
XDoc usersDoc = new XDoc("user")
.Elem("email", newemail)
.Elem("fullname", newfullName)
.Start("permissions.user")
.Elem("role", newrole)
.End();
// Replace random contributor's information with new information (by name)
msg = p.At("users", "=" + name).Put(usersDoc);
Assert.AreEqual(DreamStatus.Ok, msg.Status, "User update failed (by name)");
// Assert returned PUT method document metadata is consistent with the XML request information
Assert.IsTrue(msg.ToDocument()["username"].AsText == name, "Name does not match that in return document");
Assert.IsTrue(msg.ToDocument()["email"].AsText == newemail, "Email does not match that in return document");
Assert.IsTrue(msg.ToDocument()["fullname"].AsText == newfullName, "Full name does not match that in return document");
Assert.IsTrue(msg.ToDocument()["permissions.user/role"].AsText == newrole, "User permissions does not match that in return document");
// Same replacement operation, but by ID
msg = p.At("users", id).Put(usersDoc);
Assert.AreEqual(DreamStatus.Ok, msg.Status, "User update failed (by ID)");
// Same consistency check as above
Assert.IsTrue(msg.ToDocument()["username"].AsText == name, "Name does not match that in return document");
Assert.IsTrue(msg.ToDocument()["email"].AsText == newemail, "Email does not match that in return document");
Assert.IsTrue(msg.ToDocument()["fullname"].AsText == newfullName, "Full name does not match that in return document");
Assert.IsTrue(msg.ToDocument()["permissions.user/role"].AsText == newrole, "User permissions does not match that in return document");
}
/// <summary>
/// Authenticate a user via username:password credentials
/// </summary>
/// <feature>
/// <name>POST:users/authenticate</name>
/// <uri>http://developer.mindtouch.com/en/ref/MindTouch_API/POST%3ausers%2f%2fauthenticate</uri>
/// </feature>
/// <expected>200 OK HTTP response</expected>
[Test]
public void PostUsersAuthenticate()
{
// Build plug and authenticate user with username:password credentials
Plug p = Utils.BuildPlugForAnonymous().WithCredentials(Utils.Settings.UserName, Utils.Settings.Password);
// Assert succesful authentication and retrieve authtoken for user
DreamMessage msg = p.At("users", "authenticate").PostAsync().Wait();
Assert.AreEqual(DreamStatus.Ok, msg.Status, "Failed to authenticate user");
}
/// <summary>
/// Authenticate a user by providing API key
/// </summary>
/// <feature>
/// <name>GET:users/authenticate</name>
/// <uri>http://developer.mindtouch.com/en/ref/MindTouch_API/GET%3ausers%2f%2fauthenticate</uri>
/// </feature>
/// <expected>Impersonated user matches one authenticated</expected>
[Test]
public void Can_impersonate_user() {
// Retrieve authtoken for a given user by only providing the API key
var msg = Utils.Settings.Server
.At("users", "authenticate")
.WithCredentials(Utils.Settings.UserName, null)
.With("apikey", Utils.Settings.ApiKey)
.Get(new Result<DreamMessage>()).Wait();
// Retrieve current logged user metadata
msg = Utils.Settings.Server.At("users", "current").Get(new Result<DreamMessage>()).Wait();
Assert.AreEqual(DreamStatus.Ok, msg.Status, "Failed to retrieve current user data");
// Assert name of user impersonated matches name returned in current user metadata
Assert.AreEqual(Utils.Settings.UserName.ToLower(), msg.ToDocument()["username"].AsText.ToLower(), "Current user does not match impersonated user!");
}
/// <summary>
/// Attempt to authenticate without a password or API key
/// </summary>
/// <feature>
/// <name>GET:users/authenticate</name>
/// <uri>http://developer.mindtouch.com/en/ref/MindTouch_API/GET%3ausers%2f%2fauthenticate</uri>
/// </feature>
/// <expected>401 Unauthorized HTTP response</expected>
[Test]
public void Cannot_authenticate_without_password() {
// Attempt to authenticate a user without a password or API key
var msg = Utils.Settings.Server
.At("users", "authenticate")
.WithCredentials(Utils.Settings.UserName, null)
.Get(new Result<DreamMessage>()).Wait();
// Assert Unauthorized response returned
Assert.AreEqual(DreamStatus.Unauthorized, msg.Status, "Returned unexpected HTTP response!");
}
/// <summary>
/// Check allowed contributor READ, LOGIN permissions against a list of pages
/// </summary>
/// <feature>
/// <name>POST:users/{userid}/allowed</name>
/// <uri>http://developer.mindtouch.com/en/ref/MindTouch_API/POST%3apages%2f%2f%7Bpageid%7D%2f%2fallowed</uri>
/// </feature>
/// <expected>200 OK HTTP response</expected>
[Test]
public void PostAllowed()
{
// Build ADMIN plug
Plug p = Utils.BuildPlugForAdmin();
// Create a random contributor
string id = null;
string name = null;
DreamMessage msg = UserUtils.CreateRandomContributor(p, out id, out name);
// Create a random page
string pageid = null;
msg = PageUtils.CreateRandomPage(p, out pageid);
// XML document with a list of pages to run against the 'allowed' feature
XDoc pagesDoc = new XDoc("pages")
.Start("page")
.Attr("id", pageid)
.End();
// Check to see if user has LOGIN, READ permissions for the pages on the list
msg = p.At("users", id, "allowed").With("operations", "LOGIN,READ").Post(pagesDoc);
Assert.AreEqual(DreamStatus.Ok, msg.Status, "Allowed retrieval failed");
}
/// <summary>
/// Retrieve a user's feed
/// </summary>
/// <feature>
/// <name>GET:users/{userid}/feed</name>
/// <uri>http://developer.mindtouch.com/en/ref/MindTouch_API/GET%3ausers%2f%2f%7Buserid%7D%2f%2ffeed</uri>
/// </feature>
/// <expected>200 OK HTTP response</expected>
[Test]
public void GetFeed()
{
// Build ADMIN plug
Plug p = Utils.BuildPlugForAdmin();
// Create a random contributor
string id = null;
string name = null;
DreamMessage msg = UserUtils.CreateRandomContributor(p, out id, out name);
// Retrieve the user's feed
msg = p.At("users", id, "feed").Get();
Assert.AreEqual(DreamStatus.Ok, msg.Status, "User's feed retrieval failed");
}
/// <summary>
/// Retrieve a user's favories feed
/// </summary>
/// <feature>
/// <name>GET:users/{userid}/favorites/feed</name>
/// <uri>http://developer.mindtouch.com/en/ref/MindTouch_API/GET%3ausers%2f%2f%7buserid%7d%2f%2ffavorites%2f%2ffeed</uri>
/// </feature>
/// <expected>200 OK HTTP response</expected>
[Test]
public void GetFavoritesFeed()
{
// Build ADMIN plug
Plug p = Utils.BuildPlugForAdmin();
// Create random contributor
string id = null;
string name = null;
DreamMessage msg = UserUtils.CreateRandomContributor(p, out id, out name);
// Retrieve the user's favorites feed
msg = p.At("users", id, "favorites", "feed").Get();
Assert.AreEqual(DreamStatus.Ok, msg.Status, "User's favorites feed retrieval failed");
}
/// <summary>
/// Retrieve a user's favorite pages
/// </summary>
/// <feature>
/// <name>GET:users/{userid}/favorites</name>
/// <uri>http://developer.mindtouch.com/en/ref/MindTouch_API/GET%3ausers%2f%2f%7buserid%7d%2f%2ffavorites</uri>
/// </feature>
/// <expected>200 OK HTTP response</expected>
[Test]
public void GetFavoritesPages()
{
// Build ADMIN plug
Plug p = Utils.BuildPlugForAdmin();
// Create random contributor
string id = null;
string name = null;
DreamMessage msg = UserUtils.CreateRandomContributor(p, out id, out name);
// Retrieve user's favorite pages (should be 0 for a new user)
msg = p.At("users", id, "favorites").Get();
Assert.AreEqual(DreamStatus.Ok, msg.Status, "User's favorites retrieval failed");
Assert.AreEqual(0, msg.ToDocument()["@count"].AsInt, "New user has favorite pages?!");
}
/// <summary>
/// Update user information through Contributor (non-admin) account
/// </summary>
/// <feature>
/// <name>POST:users</name>
/// <uri>http://developer.mindtouch.com/en/ref/MindTouch_API/POST%3ausers</uri>
/// </feature>
/// <expected>403 Forbidden HTTP response</expected>
[Test]
public void RenameUser()
{
// Build ADMIN plug
Plug p = Utils.BuildPlugForAdmin();
// Create a random contributor
string username = null;
string userid = null;
DreamMessage msg = UserUtils.CreateRandomContributor(p, out userid, out username);
// Define user information and generate user XML document
string name = Utils.GenerateUniqueName();
string email = "newuser1@mindtouch.com";
string fullName = "newuser1's full name";
string role = "Contributor";
XDoc usersDoc = new XDoc("user").Attr("id", userid)
.Elem("username", name)
.Elem("email", email)
.Elem("fullname", fullName)
.Start("permissions.user")
.Elem("role", role)
.End();
// Update the user information and assert response document returns correct name
msg = p.At("users").Post(usersDoc);
Assert.AreEqual(DreamStatus.Ok, msg.Status, "User update failed");
Assert.IsTrue(msg.ToDocument()["username"].AsText == name, "Response document name does not match generated name");
// Retrieve user XML document by ID and assert document returns correct name
msg = p.At("users", userid).Get();
Assert.AreEqual(DreamStatus.Ok, msg.Status, "User retrieval failed");
Assert.IsTrue(msg.ToDocument()["username"].AsText == name, "Name of retrieved user does not match generated name");
// Build plug for user
p = Utils.BuildPlugForUser(name, "password");
try
{
// Create user XML document and attempt to update user
usersDoc = new XDoc("user").Attr("id", userid)
.Elem("username", Utils.GenerateUniqueName())
.Elem("email", email)
.Elem("fullname", fullName)
.Start("permissions.user")
.Elem("role", role)
.End();
msg = p.At("users").Post(usersDoc);
// Should not get here
Assert.IsTrue(false, "User succeeded in updating self?!");
}
catch (MindTouch.Dream.DreamResponseException ex)
{
// Assert 'Forbidden' response returned
Assert.IsTrue(ex.Response.Status == DreamStatus.Forbidden, "HTTP response other than 'Forbidden' returned!");
}
}
/// <summary>
/// Update user with homepage
/// </summary>
/// <feature>
/// <name>POST:users</name>
/// <uri>http://developer.mindtouch.com/en/ref/MindTouch_API/POST%3ausers</uri>
/// </feature>
/// <expected>User homepage moves to new user name. Old user homepage redirects to new one.</expected>
[Test]
public void RenameUserWithHomePage()
{
//Actions:
// Create User
// Create a home page for the user
// Rename user
//Expected result:
// Homepage must change path
// Build ADMIN plug
Plug p = Utils.BuildPlugForAdmin();
// Create a random contributor
string username = null;
string userid = null;
DreamMessage msg = UserUtils.CreateRandomUser(p, "Contributor", "password", out userid, out username);
// Create homepage by logging in.
p.At("users", "authenticate").WithCredentials(username, "password").Get();
string homepageContent = "This is a homepage for " + username;
PageUtils.SavePage(p, "User:" + username, homepageContent);
// Retrieve userpage content
msg = p.At("pages", "=" + XUri.DoubleEncode("User:" + username), "contents").Get();
Assert.AreEqual(DreamStatus.Ok, msg.Status, "Userpage retrieval failed");
Assert.IsTrue(msg.ToDocument()["body"].AsText == homepageContent, "Retrieved content does not match generated content!");
// Define user information and generate user XML document
string newname = Utils.GenerateUniqueName();
string email = "newuser1@mindtouch.com";
string fullName = "newuser1's full name";
string role = "Contributor";
XDoc usersDoc = new XDoc("user").Attr("id", userid)
.Elem("username", newname)
.Elem("email", email)
.Elem("fullname", fullName)
.Start("permissions.user")
.Elem("role", role)
.End();
// Build ADMIN plug
p = Utils.BuildPlugForAdmin();
// Update (rename) user
msg = p.At("users").PostAsync(usersDoc).Wait();
Assert.AreEqual(DreamStatus.Ok, msg.Status, "Rename user failed");
// Validate new page
msg = p.At("pages", "=" + XUri.DoubleEncode("User:" + newname), "contents").Get();
Assert.AreEqual(DreamStatus.Ok, msg.Status, "Userpage (new) content retrieval failed!");
Assert.IsTrue(msg.ToDocument()["body"].AsText == homepageContent, "Retrieved userpage (new) content does not match generated content!");
// Wait for redirect to complete
Assert.IsTrue(Wait.For(() =>
{
msg = PageUtils.GetPage(Utils.BuildPlugForAdmin(), "User:" + username);
return (msg.IsSuccessful);
},
TimeSpan.FromSeconds(10)),
"unable to find redirect");
// Validate old page contents
msg = p.At("pages", "=" + XUri.DoubleEncode("User:" + username), "contents").Get();
Assert.AreEqual(DreamStatus.Ok, msg.Status, "Userpage (old) content retrieval failed!");
Assert.IsTrue(msg.ToDocument()["body"].AsText == homepageContent, "Retrieved userpage (old) content does not match generated content!");
// Validate old redirected info
msg = p.At("pages", "=" + XUri.DoubleEncode("User:" + username)).Get();
string redirectedfrom = msg.ToDocument()["page.redirectedfrom/page/path"].AsText;
Assert.IsTrue(redirectedfrom.EndsWith(username), "Old redirected page is invalid");
}
/// <summary>
/// Rename user to a new name in which User:newname page already exists (despite no user with name newname existing)
/// </summary>
/// <feature>
/// <name>POST:users</name>
/// <uri>http://developer.mindtouch.com/en/ref/MindTouch_API/POST%3ausers</uri>
/// </feature>
/// <expected>409 Conflict HTTP response</expected>
[Test]
public void RenameUserWithHomePageConflict()
{
//Actions:
// Create User
// Generate new name for user
// Create a page with same name as a new name for the user
// Try to rename user
//Expected result:
// Conflict
// Build ADMIN plug
Plug p = Utils.BuildPlugForAdmin();
// Create a random contributor
string username = null;
string userid = null;
DreamMessage msg = UserUtils.CreateRandomContributor(p, out userid, out username);
// Create a new name and a userpage for the new name and contributor
string name = Utils.GenerateUniqueName();
PageUtils.SavePage(p, "User:" + name, "This is a page");
PageUtils.SavePage(p, "User:" + username, "This is a homepage");
// Define user information and generate user XML document
string email = "newuser1@mindtouch.com";
string fullName = "newuser1's full name";
string role = "Contributor";
XDoc usersDoc = new XDoc("user").Attr("id", userid)
.Elem("username", name)
.Elem("email", email)
.Elem("fullname", fullName)
.Start("permissions.user")
.Elem("role", role)
.End();
try
{
// Attempt to update user to name with existing userpage
msg = p.At("users").Post(usersDoc);
// Should not get here
Assert.IsTrue(false, "User update to name with existing userpage succeeded?!");
}
catch (MindTouch.Dream.DreamResponseException ex)
{
Assert.IsTrue(ex.Response.Status == DreamStatus.Conflict, "HTTP response other than 'Conflict' returned");
}
}
/// <summary>
/// Create a user, create a userpage, rename user, create a new user with same name as original user, create a userpage for new user
/// </summary>
/// <feature>
/// <name>POST:users</name>
/// <uri>http://developer.mindtouch.com/en/ref/MindTouch_API/POST%3ausers</uri>
/// </feature>
/// <expected>New user userpage successfully created with correct content</expected>
[Test]
public void RenameUserWithHomePageAndCreateNewUserWithSameName()
{
//Actions:
// Create User
// Create a home page for the user
// Rename user
// Create a new user with name same as an old user
// Create a home page for the new user
//Expected result:
// Homepage for new user must have correct content
// Build ADMIN plug
Plug p = Utils.BuildPlugForAdmin();
// Create random contributor
string oldname = null;
string userid = null;
DreamMessage msg = UserUtils.CreateRandomUser(p, "Contributor", "password", out userid, out oldname);
// Create homepage by logging in.
p = Utils.BuildPlugForUser(oldname, "password");
// Create content for userpage
string homepageContent = "This is a homepage for " + oldname;
PageUtils.SavePage(p, "User:" + oldname, homepageContent);
// Retrieve userpage contents
msg = p.At("pages", "=" + XUri.DoubleEncode("User:" + oldname), "contents").Get();
Assert.AreEqual(DreamStatus.Ok, msg.Status, "Userpage retrieval failed!");
Assert.IsTrue(msg.ToDocument()["body"].AsText == homepageContent, "Retrieved content does not match generated content!");
// Define new user information and generate user XML document
string newname = Utils.GenerateUniqueName();
string email = "newuser1@mindtouch.com";
string fullName = "newuser1's full name";
string role = "Contributor";
XDoc usersDoc = new XDoc("user").Attr("id", userid)
.Elem("username", newname)
.Elem("email", email)
.Elem("fullname", fullName)
.Start("permissions.user")
.Elem("role", role)
.End();
// Log in as ADMIN again
p = Utils.BuildPlugForAdmin();
// Update the user
msg = p.At("users").Post(usersDoc);
Assert.AreEqual(DreamStatus.Ok, msg.Status, "User update failed!");
// Create a user with same name as old user before update
msg = UserUtils.CreateUser(p, "Contributor", "password", out userid, oldname);
// Log in as newly created user
p = Utils.BuildPlugForUser(oldname, "password");
// Create content for userpage
homepageContent = "This is a homepage for new user with name " + oldname;
PageUtils.SavePage(p, "User:" + oldname, homepageContent);
// Retrieve userpage content
msg = p.At("pages", "=" + XUri.DoubleEncode("User:" + oldname), "contents").Get();
Assert.AreEqual(DreamStatus.Ok, msg.Status, "Userpage content retrieval failed!");
Assert.IsTrue(msg.ToDocument()["body"].AsText == homepageContent, "Retrieved userpage content does not match generated content!");
}
/// <summary>
/// Test user sorting
/// </summary>
/// <feature>
/// <name>GET:users</name>
/// <uri>http://developer.mindtouch.com/en/ref/MindTouch_API/GET%3ausers</uri>
/// <parameter>usernamefilter</parameter>
/// </feature>
/// <expected>Users correctly sorted ascending/descending by name, role, email, nick, fullname, last login</expected>
[Test]
public void TestGetUsersSorting() {
// Build ADMIN plug
Plug p = Utils.BuildPlugForAdmin();
// Create 2 users with Contributor role
string id = null;
string usernameFilter = Utils.GenerateUniqueName();
UserUtils.CreateUser(p, "Contributor", "password", out id, "+0" + usernameFilter + Utils.GenerateUniqueName());
UserUtils.CreateUser(p, "Contributor", "password", out id, "-0" + usernameFilter + Utils.GenerateUniqueName());
// Create 4 more users, each with a unique role
string uniqueRoleName = null;
UserUtils.CreateRandomRole(p, out uniqueRoleName);
UserUtils.CreateUser(p, uniqueRoleName, "password", out id, Utils.GenerateUniqueName() + usernameFilter);
UserUtils.CreateRandomRole(p, out uniqueRoleName);
UserUtils.CreateUser(p, uniqueRoleName, "password", out id, Utils.GenerateUniqueName() + usernameFilter);
UserUtils.CreateRandomRole(p, out uniqueRoleName);
UserUtils.CreateUser(p, uniqueRoleName, "password", out id, Utils.GenerateUniqueName() + usernameFilter);
UserUtils.CreateRandomRole(p, out uniqueRoleName);
UserUtils.CreateUser(p, uniqueRoleName, "password", out id, Utils.GenerateUniqueName() + usernameFilter);
// Filter the above users from existing users and check for correct ascending/descending sorting
// as defined by the "TestSortingOfDocByField" method
Utils.TestSortingOfDocByField(p.At("users").With("usernamefilter", usernameFilter)
.With("sortby", "username").Get().ToDocument(), "user", "username", true);
Utils.TestSortingOfDocByField(p.At("users").With("usernamefilter", usernameFilter)
.With("sortby", "-username").Get().ToDocument(), "user", "username", false);
Utils.TestSortingOfDocByField(p.At("users").With("usernamefilter", usernameFilter)
.With("sortby", "role").Get().ToDocument(), "user", "permissions.user/role", true);
Utils.TestSortingOfDocByField(p.At("users").With("usernamefilter", usernameFilter)
.With("sortby", "-role").Get().ToDocument(), "user", "permissions.user/role", false);
Utils.TestSortingOfDocByField(p.At("users").With("usernamefilter", usernameFilter)
.With("sortby", "nick").Get().ToDocument(), "user", "nick", true);
Utils.TestSortingOfDocByField(p.At("users").With("usernamefilter", usernameFilter)
.With("sortby", "-nick").Get().ToDocument(), "user", "nick", false);
Utils.TestSortingOfDocByField(p.At("users").With("usernamefilter", usernameFilter)
.With("sortby", "email").Get().ToDocument(), "user", "email", true);
Utils.TestSortingOfDocByField(p.At("users").With("usernamefilter", usernameFilter)
.With("sortby", "-email").Get().ToDocument(), "user", "email", false);
Utils.TestSortingOfDocByField(p.At("users").With("usernamefilter", usernameFilter)
.With("sortby", "fullname").Get().ToDocument(), "user", "fullname", true);
Utils.TestSortingOfDocByField(p.At("users").With("usernamefilter", usernameFilter)
.With("sortby", "-fullname").Get().ToDocument(), "user", "fullname", false);
Utils.TestSortingOfDocByField(p.At("users").With("usernamefilter", usernameFilter)
.With("sortby", "date.lastlogin").Get().ToDocument(), "user", "date.lastlogin", true);
Utils.TestSortingOfDocByField(p.At("users").With("usernamefilter", usernameFilter)
.With("sortby", "-date.lastlogin").Get().ToDocument(), "user", "date.lastlogin", false);
// Sorting by service test moved to XmlAuthTests class
// Inactivate the last created user
XDoc usersDoc = new XDoc("user").Attr("id", id)
.Elem("status", "inactive");
DreamMessage msg = p.At("users").PostAsync(usersDoc).Wait();
Assert.AreEqual(msg.Status, DreamStatus.Ok);
// Perform the sort check once more
Utils.TestSortingOfDocByField(p.At("users").With("usernamefilter", usernameFilter)
.With("sortby", "status").Get().ToDocument(), "user", "status", false);
Utils.TestSortingOfDocByField(p.At("users").With("usernamefilter", usernameFilter)
.With("sortby", "-status").Get().ToDocument(), "user", "status", true);
}
/// <summary>
/// Retrieve users through filters
/// </summary>
/// <feature>
/// <name>GET:users</name>
/// <uri>http://developer.mindtouch.com/en/ref/MindTouch_API/GET%3ausers</uri>
/// <parameter>usernamefilter</parameter>
/// <parameter>usernameemailfilter</parameter>
/// <parameter>rolefilter</parameter>
/// </feature>
/// <expected>Users filtered correctly</expected>
[Test]
public void GetUsersWithFilters()
{
//Actions:
// Create User1 with unique name and email and role
// Try to get user through username filter
// Try to get user through usernameemail filter
// Try to get user through role filter
//Expected result:
// All operations are correct
// Build ADMIN plug
Plug p = Utils.BuildPlugForAdmin();
// Create a unique role
string uniqueRoleName = null;
DreamMessage msg = UserUtils.CreateRandomRole(p, out uniqueRoleName);
Assert.AreEqual(DreamStatus.Ok, msg.Status, "Role creation failed!");
// Create a user with the role
string id = null;
string uniqueUserName = Utils.GenerateUniqueName();
string uniqueUserMail = "mail" + Utils.GenerateUniqueName() + "@mindtouch.com";
UserUtils.CreateUser(p, uniqueRoleName, "password", out id, uniqueUserName, uniqueUserMail);
// Filter in user by username
msg = p.At("users").With("usernamefilter", uniqueUserName).Get();
Assert.AreEqual(msg.ToDocument()["user/username"].AsText, uniqueUserName, "User name filtered does not match generated username!");
Assert.AreEqual(msg.ToDocument()["user/email"].AsText, uniqueUserMail, "User email filtered does not match generated email!");
// Filter in user by username through different query
msg = p.At("users").With("usernameemailfilter", uniqueUserName).Get();
Assert.AreEqual(msg.ToDocument()["user/username"].AsText, uniqueUserName, "User name filtered does not match generated username!");
Assert.AreEqual(msg.ToDocument()["user/email"].AsText, uniqueUserMail, "User email filtered does not match generated email!");
// Filter in user by email
msg = p.At("users").With("usernameemailfilter", uniqueUserMail).Get();
Assert.AreEqual(msg.ToDocument()["user/username"].AsText, uniqueUserName, "User name filtered does not match generated username!");
Assert.AreEqual(msg.ToDocument()["user/email"].AsText, uniqueUserMail, "User email filtered does not match generated email!");
// Filter in user by role
msg = p.At("users").With("rolefilter", uniqueRoleName).Get();
Assert.AreEqual(msg.ToDocument()["user/username"].AsText, uniqueUserName, "User name filtered does not match generated username!");
Assert.AreEqual(msg.ToDocument()["user/email"].AsText, uniqueUserMail, "User email filtered does not match generated email!");
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace NPSSMSVoting.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);
}
}
}
}
| |
// Copyright (c) 1995-2009 held by the author(s). All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the names of the Naval Postgraduate School (NPS)
// Modeling Virtual Environments and Simulation (MOVES) Institute
// (http://www.nps.edu and http://www.MovesInstitute.org)
// nor the names of its contributors may be used to endorse or
// promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008, MOVES Institute, Naval Postgraduate School. All
// rights reserved. This work is licensed under the BSD open source license,
// available at https://www.movesinstitute.org/licenses/bsd.html
//
// Author: DMcG
// Modified for use with C#:
// - Peter Smith (Naval Air Warfare Center - Training Systems Division)
// - Zvonko Bostjancic (Blubit d.o.o. - zvonko.bostjancic@blubit.si)
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Text;
using System.Xml.Serialization;
using OpenDis.Core;
namespace OpenDis.Dis1998
{
/// <summary>
/// Section 5.3.9.3 Information initiating the dyanic allocation and control of simulation entities between two simulation applications. Requires manual cleanup. The padding between record sets is variable. UNFINISHED
/// </summary>
[Serializable]
[XmlRoot]
[XmlInclude(typeof(EntityID))]
[XmlInclude(typeof(RecordSet))]
public partial class TransferControlRequestPdu : EntityManagementFamilyPdu, IEquatable<TransferControlRequestPdu>
{
/// <summary>
/// ID of entity originating request
/// </summary>
private EntityID _orginatingEntityID = new EntityID();
/// <summary>
/// ID of entity receiving request
/// </summary>
private EntityID _recevingEntityID = new EntityID();
/// <summary>
/// ID ofrequest
/// </summary>
private uint _requestID;
/// <summary>
/// required level of reliabliity service.
/// </summary>
private byte _requiredReliabilityService;
/// <summary>
/// type of transfer desired
/// </summary>
private byte _tranferType;
/// <summary>
/// The entity for which control is being requested to transfer
/// </summary>
private EntityID _transferEntityID = new EntityID();
/// <summary>
/// number of record sets to transfer
/// </summary>
private byte _numberOfRecordSets;
/// <summary>
/// ^^^This is wrong--the RecordSet class needs more work
/// </summary>
private List<RecordSet> _recordSets = new List<RecordSet>();
/// <summary>
/// Initializes a new instance of the <see cref="TransferControlRequestPdu"/> class.
/// </summary>
public TransferControlRequestPdu()
{
PduType = (byte)35;
}
/// <summary>
/// Implements the operator !=.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>
/// <c>true</c> if operands are not equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator !=(TransferControlRequestPdu left, TransferControlRequestPdu right)
{
return !(left == right);
}
/// <summary>
/// Implements the operator ==.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>
/// <c>true</c> if both operands are equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator ==(TransferControlRequestPdu left, TransferControlRequestPdu right)
{
if (object.ReferenceEquals(left, right))
{
return true;
}
if (((object)left == null) || ((object)right == null))
{
return false;
}
return left.Equals(right);
}
public override int GetMarshalledSize()
{
int marshalSize = 0;
marshalSize = base.GetMarshalledSize();
marshalSize += this._orginatingEntityID.GetMarshalledSize(); // this._orginatingEntityID
marshalSize += this._recevingEntityID.GetMarshalledSize(); // this._recevingEntityID
marshalSize += 4; // this._requestID
marshalSize += 1; // this._requiredReliabilityService
marshalSize += 1; // this._tranferType
marshalSize += this._transferEntityID.GetMarshalledSize(); // this._transferEntityID
marshalSize += 1; // this._numberOfRecordSets
for (int idx = 0; idx < this._recordSets.Count; idx++)
{
RecordSet listElement = (RecordSet)this._recordSets[idx];
marshalSize += listElement.GetMarshalledSize();
}
return marshalSize;
}
/// <summary>
/// Gets or sets the ID of entity originating request
/// </summary>
[XmlElement(Type = typeof(EntityID), ElementName = "orginatingEntityID")]
public EntityID OrginatingEntityID
{
get
{
return this._orginatingEntityID;
}
set
{
this._orginatingEntityID = value;
}
}
/// <summary>
/// Gets or sets the ID of entity receiving request
/// </summary>
[XmlElement(Type = typeof(EntityID), ElementName = "recevingEntityID")]
public EntityID RecevingEntityID
{
get
{
return this._recevingEntityID;
}
set
{
this._recevingEntityID = value;
}
}
/// <summary>
/// Gets or sets the ID ofrequest
/// </summary>
[XmlElement(Type = typeof(uint), ElementName = "requestID")]
public uint RequestID
{
get
{
return this._requestID;
}
set
{
this._requestID = value;
}
}
/// <summary>
/// Gets or sets the required level of reliabliity service.
/// </summary>
[XmlElement(Type = typeof(byte), ElementName = "requiredReliabilityService")]
public byte RequiredReliabilityService
{
get
{
return this._requiredReliabilityService;
}
set
{
this._requiredReliabilityService = value;
}
}
/// <summary>
/// Gets or sets the type of transfer desired
/// </summary>
[XmlElement(Type = typeof(byte), ElementName = "tranferType")]
public byte TranferType
{
get
{
return this._tranferType;
}
set
{
this._tranferType = value;
}
}
/// <summary>
/// Gets or sets the The entity for which control is being requested to transfer
/// </summary>
[XmlElement(Type = typeof(EntityID), ElementName = "transferEntityID")]
public EntityID TransferEntityID
{
get
{
return this._transferEntityID;
}
set
{
this._transferEntityID = value;
}
}
/// <summary>
/// Gets or sets the number of record sets to transfer
/// </summary>
/// <remarks>
/// Note that setting this value will not change the marshalled value. The list whose length this describes is used for that purpose.
/// The getnumberOfRecordSets method will also be based on the actual list length rather than this value.
/// The method is simply here for completeness and should not be used for any computations.
/// </remarks>
[XmlElement(Type = typeof(byte), ElementName = "numberOfRecordSets")]
public byte NumberOfRecordSets
{
get
{
return this._numberOfRecordSets;
}
set
{
this._numberOfRecordSets = value;
}
}
/// <summary>
/// Gets the ^^^This is wrong--the RecordSet class needs more work
/// </summary>
[XmlElement(ElementName = "recordSetsList", Type = typeof(List<RecordSet>))]
public List<RecordSet> RecordSets
{
get
{
return this._recordSets;
}
}
/// <summary>
/// Automatically sets the length of the marshalled data, then calls the marshal method.
/// </summary>
/// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param>
public override void MarshalAutoLengthSet(DataOutputStream dos)
{
// Set the length prior to marshalling data
this.Length = (ushort)this.GetMarshalledSize();
this.Marshal(dos);
}
/// <summary>
/// Marshal the data to the DataOutputStream. Note: Length needs to be set before calling this method
/// </summary>
/// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public override void Marshal(DataOutputStream dos)
{
base.Marshal(dos);
if (dos != null)
{
try
{
this._orginatingEntityID.Marshal(dos);
this._recevingEntityID.Marshal(dos);
dos.WriteUnsignedInt((uint)this._requestID);
dos.WriteUnsignedByte((byte)this._requiredReliabilityService);
dos.WriteUnsignedByte((byte)this._tranferType);
this._transferEntityID.Marshal(dos);
dos.WriteUnsignedByte((byte)this._recordSets.Count);
for (int idx = 0; idx < this._recordSets.Count; idx++)
{
RecordSet aRecordSet = (RecordSet)this._recordSets[idx];
aRecordSet.Marshal(dos);
}
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public override void Unmarshal(DataInputStream dis)
{
base.Unmarshal(dis);
if (dis != null)
{
try
{
this._orginatingEntityID.Unmarshal(dis);
this._recevingEntityID.Unmarshal(dis);
this._requestID = dis.ReadUnsignedInt();
this._requiredReliabilityService = dis.ReadUnsignedByte();
this._tranferType = dis.ReadUnsignedByte();
this._transferEntityID.Unmarshal(dis);
this._numberOfRecordSets = dis.ReadUnsignedByte();
for (int idx = 0; idx < this.NumberOfRecordSets; idx++)
{
RecordSet anX = new RecordSet();
anX.Unmarshal(dis);
this._recordSets.Add(anX);
}
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
}
/// <summary>
/// This allows for a quick display of PDU data. The current format is unacceptable and only used for debugging.
/// This will be modified in the future to provide a better display. Usage:
/// pdu.GetType().InvokeMember("Reflection", System.Reflection.BindingFlags.InvokeMethod, null, pdu, new object[] { sb });
/// where pdu is an object representing a single pdu and sb is a StringBuilder.
/// Note: The supplied Utilities folder contains a method called 'DecodePDU' in the PDUProcessor Class that provides this functionality
/// </summary>
/// <param name="sb">The StringBuilder instance to which the PDU is written to.</param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public override void Reflection(StringBuilder sb)
{
sb.AppendLine("<TransferControlRequestPdu>");
base.Reflection(sb);
try
{
sb.AppendLine("<orginatingEntityID>");
this._orginatingEntityID.Reflection(sb);
sb.AppendLine("</orginatingEntityID>");
sb.AppendLine("<recevingEntityID>");
this._recevingEntityID.Reflection(sb);
sb.AppendLine("</recevingEntityID>");
sb.AppendLine("<requestID type=\"uint\">" + this._requestID.ToString(CultureInfo.InvariantCulture) + "</requestID>");
sb.AppendLine("<requiredReliabilityService type=\"byte\">" + this._requiredReliabilityService.ToString(CultureInfo.InvariantCulture) + "</requiredReliabilityService>");
sb.AppendLine("<tranferType type=\"byte\">" + this._tranferType.ToString(CultureInfo.InvariantCulture) + "</tranferType>");
sb.AppendLine("<transferEntityID>");
this._transferEntityID.Reflection(sb);
sb.AppendLine("</transferEntityID>");
sb.AppendLine("<recordSets type=\"byte\">" + this._recordSets.Count.ToString(CultureInfo.InvariantCulture) + "</recordSets>");
for (int idx = 0; idx < this._recordSets.Count; idx++)
{
sb.AppendLine("<recordSets" + idx.ToString(CultureInfo.InvariantCulture) + " type=\"RecordSet\">");
RecordSet aRecordSet = (RecordSet)this._recordSets[idx];
aRecordSet.Reflection(sb);
sb.AppendLine("</recordSets" + idx.ToString(CultureInfo.InvariantCulture) + ">");
}
sb.AppendLine("</TransferControlRequestPdu>");
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
/// <summary>
/// Determines whether the specified <see cref="System.Object"/> is equal to this instance.
/// </summary>
/// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object obj)
{
return this == obj as TransferControlRequestPdu;
}
/// <summary>
/// Compares for reference AND value equality.
/// </summary>
/// <param name="obj">The object to compare with this instance.</param>
/// <returns>
/// <c>true</c> if both operands are equal; otherwise, <c>false</c>.
/// </returns>
public bool Equals(TransferControlRequestPdu obj)
{
bool ivarsEqual = true;
if (obj.GetType() != this.GetType())
{
return false;
}
ivarsEqual = base.Equals(obj);
if (!this._orginatingEntityID.Equals(obj._orginatingEntityID))
{
ivarsEqual = false;
}
if (!this._recevingEntityID.Equals(obj._recevingEntityID))
{
ivarsEqual = false;
}
if (this._requestID != obj._requestID)
{
ivarsEqual = false;
}
if (this._requiredReliabilityService != obj._requiredReliabilityService)
{
ivarsEqual = false;
}
if (this._tranferType != obj._tranferType)
{
ivarsEqual = false;
}
if (!this._transferEntityID.Equals(obj._transferEntityID))
{
ivarsEqual = false;
}
if (this._numberOfRecordSets != obj._numberOfRecordSets)
{
ivarsEqual = false;
}
if (this._recordSets.Count != obj._recordSets.Count)
{
ivarsEqual = false;
}
if (ivarsEqual)
{
for (int idx = 0; idx < this._recordSets.Count; idx++)
{
if (!this._recordSets[idx].Equals(obj._recordSets[idx]))
{
ivarsEqual = false;
}
}
}
return ivarsEqual;
}
/// <summary>
/// HashCode Helper
/// </summary>
/// <param name="hash">The hash value.</param>
/// <returns>The new hash value.</returns>
private static int GenerateHash(int hash)
{
hash = hash << (5 + hash);
return hash;
}
/// <summary>
/// Gets the hash code.
/// </summary>
/// <returns>The hash code.</returns>
public override int GetHashCode()
{
int result = 0;
result = GenerateHash(result) ^ base.GetHashCode();
result = GenerateHash(result) ^ this._orginatingEntityID.GetHashCode();
result = GenerateHash(result) ^ this._recevingEntityID.GetHashCode();
result = GenerateHash(result) ^ this._requestID.GetHashCode();
result = GenerateHash(result) ^ this._requiredReliabilityService.GetHashCode();
result = GenerateHash(result) ^ this._tranferType.GetHashCode();
result = GenerateHash(result) ^ this._transferEntityID.GetHashCode();
result = GenerateHash(result) ^ this._numberOfRecordSets.GetHashCode();
if (this._recordSets.Count > 0)
{
for (int idx = 0; idx < this._recordSets.Count; idx++)
{
result = GenerateHash(result) ^ this._recordSets[idx].GetHashCode();
}
}
return result;
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
extern alias Scripting;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Ipc;
using System.Runtime.Remoting.Messaging;
using System.Runtime.Serialization.Formatters;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.CodeAnalysis.Scripting;
using Microsoft.CodeAnalysis.Scripting.Hosting;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Interactive
{
using RelativePathResolver = Scripting::Microsoft.CodeAnalysis.RelativePathResolver;
internal partial class InteractiveHost
{
/// <summary>
/// A remote singleton server-activated object that lives in the interactive host process and controls it.
/// </summary>
internal sealed class Service : MarshalByRefObject, IDisposable
{
private static readonly ManualResetEventSlim s_clientExited = new ManualResetEventSlim(false);
private static Control s_control;
private InteractiveAssemblyLoader _assemblyLoader;
private MetadataShadowCopyProvider _metadataFileProvider;
private ReplServiceProvider _replServiceProvider;
private InteractiveScriptGlobals _globals;
// Session is not thread-safe by itself, and the compilation
// and execution of scripts are asynchronous operations.
// However since the operations are executed serially, it
// is sufficient to lock when creating the async tasks.
private readonly object _lastTaskGuard = new object();
private Task<EvaluationState> _lastTask;
private struct EvaluationState
{
internal ImmutableArray<string> SourceSearchPaths;
internal ImmutableArray<string> ReferenceSearchPaths;
internal string WorkingDirectory;
internal readonly ScriptState<object> ScriptStateOpt;
internal readonly ScriptOptions ScriptOptions;
internal EvaluationState(
ScriptState<object> scriptStateOpt,
ScriptOptions scriptOptions,
ImmutableArray<string> sourceSearchPaths,
ImmutableArray<string> referenceSearchPaths,
string workingDirectory)
{
Debug.Assert(scriptOptions != null);
Debug.Assert(!sourceSearchPaths.IsDefault);
Debug.Assert(!referenceSearchPaths.IsDefault);
Debug.Assert(workingDirectory != null);
ScriptStateOpt = scriptStateOpt;
ScriptOptions = scriptOptions;
SourceSearchPaths = sourceSearchPaths;
ReferenceSearchPaths = referenceSearchPaths;
WorkingDirectory = workingDirectory;
}
internal EvaluationState WithScriptState(ScriptState<object> state)
{
Debug.Assert(state != null);
return new EvaluationState(
state,
ScriptOptions,
SourceSearchPaths,
ReferenceSearchPaths,
WorkingDirectory);
}
internal EvaluationState WithOptions(ScriptOptions options)
{
Debug.Assert(options != null);
return new EvaluationState(
ScriptStateOpt,
options,
SourceSearchPaths,
ReferenceSearchPaths,
WorkingDirectory);
}
}
private static readonly ImmutableArray<string> s_systemNoShadowCopyDirectories = ImmutableArray.Create(
FileUtilities.NormalizeDirectoryPath(Environment.GetFolderPath(Environment.SpecialFolder.Windows)),
FileUtilities.NormalizeDirectoryPath(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles)),
FileUtilities.NormalizeDirectoryPath(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86)),
FileUtilities.NormalizeDirectoryPath(RuntimeEnvironment.GetRuntimeDirectory()));
#region Setup
public Service()
{
var initialState = new EvaluationState(
scriptStateOpt: null,
scriptOptions: ScriptOptions.Default,
sourceSearchPaths: ImmutableArray<string>.Empty,
referenceSearchPaths: ImmutableArray<string>.Empty,
workingDirectory: Directory.GetCurrentDirectory());
_lastTask = Task.FromResult(initialState);
Console.OutputEncoding = Encoding.UTF8;
// We want to be sure to delete the shadow-copied files when the process goes away. Frankly
// there's nothing we can do if the process is forcefully quit or goes down in a completely
// uncontrolled manner (like a stack overflow). When the process goes down in a controlled
// manned, we should generally expect this event to be called.
AppDomain.CurrentDomain.ProcessExit += HandleProcessExit;
}
private void HandleProcessExit(object sender, EventArgs e)
{
Dispose();
AppDomain.CurrentDomain.ProcessExit -= HandleProcessExit;
}
public void Dispose()
{
_metadataFileProvider.Dispose();
}
public override object InitializeLifetimeService()
{
return null;
}
public void Initialize(Type replServiceProviderType, string cultureName)
{
Debug.Assert(replServiceProviderType != null);
Debug.Assert(cultureName != null);
Debug.Assert(_metadataFileProvider == null);
Debug.Assert(_assemblyLoader == null);
Debug.Assert(_replServiceProvider == null);
// TODO (tomat): we should share the copied files with the host
_metadataFileProvider = new MetadataShadowCopyProvider(
Path.Combine(Path.GetTempPath(), "InteractiveHostShadow"),
noShadowCopyDirectories: s_systemNoShadowCopyDirectories,
documentationCommentsCulture: new CultureInfo(cultureName));
_assemblyLoader = new InteractiveAssemblyLoader(_metadataFileProvider);
_replServiceProvider = (ReplServiceProvider)Activator.CreateInstance(replServiceProviderType);
_globals = new InteractiveScriptGlobals(Console.Out, _replServiceProvider.ObjectFormatter);
}
private MetadataReferenceResolver CreateMetadataReferenceResolver(ImmutableArray<string> searchPaths, string baseDirectory)
{
return new RuntimeMetadataReferenceResolver(
new RelativePathResolver(searchPaths, baseDirectory),
null,
GacFileResolver.IsAvailable ? new GacFileResolver(preferredCulture: CultureInfo.CurrentCulture) : null,
(path, properties) => new ShadowCopyReference(_metadataFileProvider, path, properties));
}
private SourceReferenceResolver CreateSourceReferenceResolver(ImmutableArray<string> searchPaths, string baseDirectory)
{
return new SourceFileResolver(searchPaths, baseDirectory);
}
private static bool AttachToClientProcess(int clientProcessId)
{
Process clientProcess;
try
{
clientProcess = Process.GetProcessById(clientProcessId);
}
catch (ArgumentException)
{
return false;
}
clientProcess.EnableRaisingEvents = true;
clientProcess.Exited += new EventHandler((_, __) =>
{
s_clientExited.Set();
});
return clientProcess.IsAlive();
}
// for testing purposes
public void EmulateClientExit()
{
s_clientExited.Set();
}
internal static void RunServer(string[] args)
{
if (args.Length != 3)
{
throw new ArgumentException("Expecting arguments: <server port> <semaphore name> <client process id>");
}
RunServer(args[0], args[1], int.Parse(args[2], CultureInfo.InvariantCulture));
}
/// <summary>
/// Implements remote server.
/// </summary>
private static void RunServer(string serverPort, string semaphoreName, int clientProcessId)
{
if (!AttachToClientProcess(clientProcessId))
{
return;
}
// Disables Windows Error Reporting for the process, so that the process fails fast.
// Unfortunately, this doesn't work on Windows Server 2008 (OS v6.0), Vista (OS v6.0) and XP (OS v5.1)
// Note that GetErrorMode is not available on XP at all.
if (Environment.OSVersion.Version >= new Version(6, 1, 0, 0))
{
SetErrorMode(GetErrorMode() | ErrorMode.SEM_FAILCRITICALERRORS | ErrorMode.SEM_NOOPENFILEERRORBOX | ErrorMode.SEM_NOGPFAULTERRORBOX);
}
IpcServerChannel serverChannel = null;
IpcClientChannel clientChannel = null;
try
{
using (var semaphore = Semaphore.OpenExisting(semaphoreName))
{
// DEBUG: semaphore.WaitOne();
var serverProvider = new BinaryServerFormatterSinkProvider();
serverProvider.TypeFilterLevel = TypeFilterLevel.Full;
var clientProvider = new BinaryClientFormatterSinkProvider();
clientChannel = new IpcClientChannel(GenerateUniqueChannelLocalName(), clientProvider);
ChannelServices.RegisterChannel(clientChannel, ensureSecurity: false);
serverChannel = new IpcServerChannel(GenerateUniqueChannelLocalName(), serverPort, serverProvider);
ChannelServices.RegisterChannel(serverChannel, ensureSecurity: false);
RemotingConfiguration.RegisterWellKnownServiceType(
typeof(Service),
ServiceName,
WellKnownObjectMode.Singleton);
using (var resetEvent = new ManualResetEventSlim(false))
{
var uiThread = new Thread(() =>
{
s_control = new Control();
s_control.CreateControl();
resetEvent.Set();
Application.Run();
});
uiThread.SetApartmentState(ApartmentState.STA);
uiThread.IsBackground = true;
uiThread.Start();
resetEvent.Wait();
}
// the client can instantiate interactive host now:
semaphore.Release();
}
s_clientExited.Wait();
}
finally
{
if (serverChannel != null)
{
ChannelServices.UnregisterChannel(serverChannel);
}
if (clientChannel != null)
{
ChannelServices.UnregisterChannel(clientChannel);
}
}
// force exit even if there are foreground threads running:
Environment.Exit(0);
}
internal static string ServiceName
{
get { return typeof(Service).Name; }
}
private static string GenerateUniqueChannelLocalName()
{
return typeof(Service).FullName + Guid.NewGuid();
}
#endregion
#region Remote Async Entry Points
// Used by ResetInteractive - consider improving (we should remember the parameters for auto-reset, e.g.)
[OneWay]
public void SetPathsAsync(
RemoteAsyncOperation<RemoteExecutionResult> operation,
string[] referenceSearchPaths,
string[] sourceSearchPaths,
string baseDirectory)
{
Debug.Assert(operation != null);
Debug.Assert(referenceSearchPaths != null);
Debug.Assert(sourceSearchPaths != null);
Debug.Assert(baseDirectory != null);
lock (_lastTaskGuard)
{
_lastTask = SetPathsAsync(_lastTask, operation, referenceSearchPaths, sourceSearchPaths, baseDirectory);
}
}
private async Task<EvaluationState> SetPathsAsync(
Task<EvaluationState> lastTask,
RemoteAsyncOperation<RemoteExecutionResult> operation,
string[] referenceSearchPaths,
string[] sourceSearchPaths,
string baseDirectory)
{
var state = await ReportUnhandledExceptionIfAny(lastTask).ConfigureAwait(false);
try
{
Directory.SetCurrentDirectory(baseDirectory);
_globals.ReferencePaths.Clear();
_globals.ReferencePaths.AddRange(referenceSearchPaths);
_globals.SourcePaths.Clear();
_globals.SourcePaths.AddRange(sourceSearchPaths);
}
finally
{
state = CompleteExecution(state, operation, success: true);
}
return state;
}
/// <summary>
/// Reads given initialization file (.rsp) and loads and executes all assembly references and files, respectively specified in it.
/// Execution is performed on the UI thread.
/// </summary>
[OneWay]
public void InitializeContextAsync(RemoteAsyncOperation<RemoteExecutionResult> operation, string initializationFile, bool isRestarting)
{
Debug.Assert(operation != null);
lock (_lastTaskGuard)
{
_lastTask = InitializeContextAsync(_lastTask, operation, initializationFile, isRestarting);
}
}
/// <summary>
/// Adds an assembly reference to the current session.
/// </summary>
[OneWay]
public void AddReferenceAsync(RemoteAsyncOperation<bool> operation, string reference)
{
Debug.Assert(operation != null);
Debug.Assert(reference != null);
lock (_lastTaskGuard)
{
_lastTask = AddReferenceAsync(_lastTask, operation, reference);
}
}
private async Task<EvaluationState> AddReferenceAsync(Task<EvaluationState> lastTask, RemoteAsyncOperation<bool> operation, string reference)
{
var state = await ReportUnhandledExceptionIfAny(lastTask).ConfigureAwait(false);
bool success = false;
try
{
var resolvedReferences = state.ScriptOptions.MetadataResolver.ResolveReference(reference, baseFilePath: null, properties: MetadataReferenceProperties.Assembly);
if (!resolvedReferences.IsDefaultOrEmpty)
{
state = state.WithOptions(state.ScriptOptions.AddReferences(resolvedReferences));
success = true;
}
else
{
Console.Error.WriteLine(string.Format(FeaturesResources.CannotResolveReference, reference));
}
}
catch (Exception e)
{
ReportUnhandledException(e);
}
finally
{
operation.Completed(success);
}
return state;
}
/// <summary>
/// Executes given script snippet on the UI thread in the context of the current session.
/// </summary>
[OneWay]
public void ExecuteAsync(RemoteAsyncOperation<RemoteExecutionResult> operation, string text)
{
Debug.Assert(operation != null);
Debug.Assert(text != null);
lock (_lastTaskGuard)
{
_lastTask = ExecuteAsync(_lastTask, operation, text);
}
}
private async Task<EvaluationState> ExecuteAsync(Task<EvaluationState> lastTask, RemoteAsyncOperation<RemoteExecutionResult> operation, string text)
{
var state = await ReportUnhandledExceptionIfAny(lastTask).ConfigureAwait(false);
bool success = false;
try
{
Script<object> script = TryCompile(state.ScriptStateOpt?.Script, text, null, state.ScriptOptions);
if (script != null)
{
// successful if compiled
success = true;
// remove references and imports from the options, they have been applied and will be inherited from now on:
state = state.WithOptions(state.ScriptOptions.RemoveImportsAndReferences());
var newScriptState = await ExecuteOnUIThread(script, state.ScriptStateOpt, displayResult: true).ConfigureAwait(false);
state = state.WithScriptState(newScriptState);
}
}
catch (Exception e)
{
ReportUnhandledException(e);
}
finally
{
state = CompleteExecution(state, operation, success);
}
return state;
}
private void DisplayException(Exception e)
{
if (e is FileLoadException && e.InnerException is InteractiveAssemblyLoaderException)
{
Console.Error.WriteLine(e.InnerException.Message);
}
else
{
Console.Error.Write(_replServiceProvider.ObjectFormatter.FormatException(e));
}
}
/// <summary>
/// Executes given script file on the UI thread in the context of the current session.
/// </summary>
[OneWay]
public void ExecuteFileAsync(RemoteAsyncOperation<RemoteExecutionResult> operation, string path)
{
Debug.Assert(operation != null);
Debug.Assert(path != null);
lock (_lastTaskGuard)
{
_lastTask = ExecuteFileAsync(operation, _lastTask, path);
}
}
private EvaluationState CompleteExecution(EvaluationState state, RemoteAsyncOperation<RemoteExecutionResult> operation, bool success)
{
// send any updates to the host object and current directory back to the client:
var currentSourcePaths = _globals.SourcePaths.ToArray();
var currentReferencePaths = _globals.ReferencePaths.ToArray();
var currentWorkingDirectory = Directory.GetCurrentDirectory();
var changedSourcePaths = currentSourcePaths.SequenceEqual(state.SourceSearchPaths) ? null : currentSourcePaths;
var changedReferencePaths = currentReferencePaths.SequenceEqual(state.ReferenceSearchPaths) ? null : currentReferencePaths;
var changedWorkingDirectory = currentWorkingDirectory == state.WorkingDirectory ? null : currentWorkingDirectory;
operation.Completed(new RemoteExecutionResult(success, changedSourcePaths, changedReferencePaths, changedWorkingDirectory));
// no changes in resolvers:
if (changedReferencePaths == null && changedSourcePaths == null && changedWorkingDirectory == null)
{
return state;
}
var newSourcePaths = ImmutableArray.CreateRange(currentSourcePaths);
var newReferencePaths = ImmutableArray.CreateRange(currentReferencePaths);
var newWorkingDirectory = currentWorkingDirectory;
ScriptOptions newOptions = state.ScriptOptions;
if (changedReferencePaths != null || changedWorkingDirectory != null)
{
newOptions = newOptions.WithMetadataResolver(CreateMetadataReferenceResolver(newReferencePaths, newWorkingDirectory));
}
if (changedSourcePaths != null || changedWorkingDirectory != null)
{
newOptions = newOptions.WithSourceResolver(CreateSourceReferenceResolver(newSourcePaths, newWorkingDirectory));
}
return new EvaluationState(
state.ScriptStateOpt,
newOptions,
newSourcePaths,
newReferencePaths,
workingDirectory: newWorkingDirectory);
}
private static async Task<EvaluationState> ReportUnhandledExceptionIfAny(Task<EvaluationState> lastTask)
{
try
{
return await lastTask.ConfigureAwait(false);
}
catch (Exception e)
{
ReportUnhandledException(e);
return lastTask.Result;
}
}
private static void ReportUnhandledException(Exception e)
{
Console.Error.WriteLine("Unexpected error:");
Console.Error.WriteLine(e);
Debug.Fail("Unexpected error");
Debug.WriteLine(e);
}
#endregion
#region Operations
/// <summary>
/// Loads references, set options and execute files specified in the initialization file.
/// Also prints logo unless <paramref name="isRestarting"/> is true.
/// </summary>
private async Task<EvaluationState> InitializeContextAsync(
Task<EvaluationState> lastTask,
RemoteAsyncOperation<RemoteExecutionResult> operation,
string initializationFileOpt,
bool isRestarting)
{
Debug.Assert(initializationFileOpt == null || PathUtilities.IsAbsolute(initializationFileOpt));
var state = await ReportUnhandledExceptionIfAny(lastTask).ConfigureAwait(false);
try
{
// TODO (tomat): this is also done in CommonInteractiveEngine, perhaps we can pass the parsed command lines to here?
if (!isRestarting)
{
Console.Out.WriteLine(_replServiceProvider.Logo);
}
if (File.Exists(initializationFileOpt))
{
Console.Out.WriteLine(string.Format(FeaturesResources.LoadingContextFrom, Path.GetFileName(initializationFileOpt)));
var parser = _replServiceProvider.CommandLineParser;
// The base directory for relative paths is the directory that contains the .rsp file.
// Note that .rsp files included by this .rsp file will share the base directory (Dev10 behavior of csc/vbc).
var rspDirectory = Path.GetDirectoryName(initializationFileOpt);
var args = parser.Parse(new[] { "@" + initializationFileOpt }, rspDirectory, RuntimeEnvironment.GetRuntimeDirectory(), null);
foreach (var error in args.Errors)
{
var writer = (error.Severity == DiagnosticSeverity.Error) ? Console.Error : Console.Out;
writer.WriteLine(error.GetMessage(CultureInfo.CurrentCulture));
}
if (args.Errors.Length == 0)
{
var metadataResolver = CreateMetadataReferenceResolver(args.ReferencePaths, rspDirectory);
var sourceResolver = CreateSourceReferenceResolver(args.SourcePaths, rspDirectory);
var metadataReferences = new List<PortableExecutableReference>();
foreach (CommandLineReference cmdLineReference in args.MetadataReferences)
{
// interactive command line parser doesn't accept modules or linked assemblies
Debug.Assert(cmdLineReference.Properties.Kind == MetadataImageKind.Assembly && !cmdLineReference.Properties.EmbedInteropTypes);
var resolvedReferences = metadataResolver.ResolveReference(cmdLineReference.Reference, baseFilePath: null, properties: MetadataReferenceProperties.Assembly);
if (!resolvedReferences.IsDefaultOrEmpty)
{
metadataReferences.AddRange(resolvedReferences);
}
}
var scriptPathOpt = args.SourceFiles.IsEmpty ? null : args.SourceFiles[0].Path;
var rspState = new EvaluationState(
state.ScriptStateOpt,
state.ScriptOptions.
WithFilePath(scriptPathOpt).
WithReferences(metadataReferences).
WithImports(CommandLineHelpers.GetImports(args)).
WithMetadataResolver(metadataResolver).
WithSourceResolver(sourceResolver),
args.SourcePaths,
args.ReferencePaths,
rspDirectory);
_globals.ReferencePaths.Clear();
_globals.ReferencePaths.AddRange(args.ReferencePaths);
_globals.SourcePaths.Clear();
_globals.SourcePaths.AddRange(args.SourcePaths);
_globals.Args.AddRange(args.ScriptArguments);
if (scriptPathOpt != null)
{
var newScriptState = await TryExecuteFileAsync(rspState, scriptPathOpt).ConfigureAwait(false);
if (newScriptState != null)
{
// remove references and imports from the options, they have been applied and will be inherited from now on:
rspState = rspState.
WithScriptState(newScriptState).
WithOptions(rspState.ScriptOptions.RemoveImportsAndReferences());
}
}
state = rspState;
}
}
if (!isRestarting)
{
Console.Out.WriteLine(FeaturesResources.TypeHelpForMoreInformation);
}
}
catch (Exception e)
{
ReportUnhandledException(e);
}
finally
{
state = CompleteExecution(state, operation, success: true);
}
return state;
}
private string ResolveRelativePath(string path, string baseDirectory, ImmutableArray<string> searchPaths, bool displayPath)
{
List<string> attempts = new List<string>();
Func<string, bool> fileExists = file =>
{
attempts.Add(file);
return File.Exists(file);
};
string fullPath = FileUtilities.ResolveRelativePath(path, null, baseDirectory, searchPaths, fileExists);
if (fullPath == null)
{
if (displayPath)
{
Console.Error.WriteLine(FeaturesResources.SpecifiedFileNotFoundFormat, path);
}
else
{
Console.Error.WriteLine(FeaturesResources.SpecifiedFileNotFound);
}
if (attempts.Count > 0)
{
DisplaySearchPaths(Console.Error, attempts);
}
}
return fullPath;
}
private Script<object> TryCompile(Script previousScript, string code, string path, ScriptOptions options)
{
Script script;
var scriptOptions = options.WithFilePath(path);
if (previousScript != null)
{
script = previousScript.ContinueWith(code, scriptOptions);
}
else
{
script = _replServiceProvider.CreateScript<object>(code, scriptOptions, _globals.GetType(), _assemblyLoader);
}
var diagnostics = script.Compile();
if (diagnostics.HasAnyErrors())
{
DisplayInteractiveErrors(diagnostics, Console.Error);
return null;
}
return (Script<object>)script;
}
private async Task<EvaluationState> ExecuteFileAsync(
RemoteAsyncOperation<RemoteExecutionResult> operation,
Task<EvaluationState> lastTask,
string path)
{
var state = await ReportUnhandledExceptionIfAny(lastTask).ConfigureAwait(false);
string fullPath = ResolveRelativePath(path, state.WorkingDirectory, state.SourceSearchPaths, displayPath: false);
if (fullPath != null)
{
var newScriptState = await TryExecuteFileAsync(state, fullPath).ConfigureAwait(false);
if (newScriptState != null)
{
return CompleteExecution(state.WithScriptState(newScriptState), operation, success: newScriptState.Exception == null);
}
}
return CompleteExecution(state, operation, success: false);
}
/// <summary>
/// Executes specified script file as a submission.
/// </summary>
/// <remarks>
/// All errors are written to the error output stream.
/// Uses source search paths to resolve unrooted paths.
/// </remarks>
private async Task<ScriptState<object>> TryExecuteFileAsync(EvaluationState state, string fullPath)
{
Debug.Assert(PathUtilities.IsAbsolute(fullPath));
string content = null;
try
{
using (var reader = File.OpenText(fullPath))
{
content = await reader.ReadToEndAsync().ConfigureAwait(false);
}
}
catch (Exception e)
{
// file read errors:
Console.Error.WriteLine(e.Message);
return null;
}
Script<object> script = TryCompile(state.ScriptStateOpt?.Script, content, fullPath, state.ScriptOptions);
if (script == null)
{
// compilation errors:
return null;
}
return await ExecuteOnUIThread(script, state.ScriptStateOpt, displayResult: false).ConfigureAwait(false);
}
private static void DisplaySearchPaths(TextWriter writer, List<string> attemptedFilePaths)
{
var directories = attemptedFilePaths.Select(path => Path.GetDirectoryName(path)).ToArray();
var uniqueDirectories = new HashSet<string>(directories);
writer.WriteLine(uniqueDirectories.Count == 1 ?
FeaturesResources.SearchedInDirectory :
FeaturesResources.SearchedInDirectories);
foreach (string directory in directories)
{
if (uniqueDirectories.Remove(directory))
{
writer.Write(" ");
writer.WriteLine(directory);
}
}
}
private async Task<ScriptState<object>> ExecuteOnUIThread(Script<object> script, ScriptState<object> stateOpt, bool displayResult)
{
return await ((Task<ScriptState<object>>)s_control.Invoke(
(Func<Task<ScriptState<object>>>)(async () =>
{
var task = (stateOpt == null) ?
script.RunAsync(_globals, catchException: e => true, cancellationToken: CancellationToken.None) :
script.RunFromAsync(stateOpt, catchException: e => true, cancellationToken: CancellationToken.None);
var newState = await task.ConfigureAwait(false);
if (newState.Exception != null)
{
DisplayException(newState.Exception);
}
else if (displayResult && newState.Script.HasReturnValue())
{
_globals.Print(newState.ReturnValue);
}
return newState;
}))).ConfigureAwait(false);
}
private void DisplayInteractiveErrors(ImmutableArray<Diagnostic> diagnostics, TextWriter output)
{
var displayedDiagnostics = new List<Diagnostic>();
const int MaxErrorCount = 5;
for (int i = 0, n = Math.Min(diagnostics.Length, MaxErrorCount); i < n; i++)
{
displayedDiagnostics.Add(diagnostics[i]);
}
displayedDiagnostics.Sort((d1, d2) => d1.Location.SourceSpan.Start - d2.Location.SourceSpan.Start);
var formatter = _replServiceProvider.DiagnosticFormatter;
foreach (var diagnostic in displayedDiagnostics)
{
output.WriteLine(formatter.Format(diagnostic, output.FormatProvider as CultureInfo));
}
if (diagnostics.Length > MaxErrorCount)
{
int notShown = diagnostics.Length - MaxErrorCount;
output.WriteLine(string.Format(output.FormatProvider, FeaturesResources.PlusAdditional, notShown, (notShown == 1) ? "error" : "errors"));
}
}
#endregion
#region Win32 API
[DllImport("kernel32", PreserveSig = true)]
internal static extern ErrorMode SetErrorMode(ErrorMode mode);
[DllImport("kernel32", PreserveSig = true)]
internal static extern ErrorMode GetErrorMode();
[Flags]
internal enum ErrorMode : int
{
/// <summary>
/// Use the system default, which is to display all error dialog boxes.
/// </summary>
SEM_FAILCRITICALERRORS = 0x0001,
/// <summary>
/// The system does not display the critical-error-handler message box. Instead, the system sends the error to the calling process.
/// Best practice is that all applications call the process-wide SetErrorMode function with a parameter of SEM_FAILCRITICALERRORS at startup.
/// This is to prevent error mode dialogs from hanging the application.
/// </summary>
SEM_NOGPFAULTERRORBOX = 0x0002,
/// <summary>
/// The system automatically fixes memory alignment faults and makes them invisible to the application.
/// It does this for the calling process and any descendant processes. This feature is only supported by
/// certain processor architectures. For more information, see the Remarks section.
/// After this value is set for a process, subsequent attempts to clear the value are ignored.
/// </summary>
SEM_NOALIGNMENTFAULTEXCEPT = 0x0004,
/// <summary>
/// The system does not display a message box when it fails to find a file. Instead, the error is returned to the calling process.
/// </summary>
SEM_NOOPENFILEERRORBOX = 0x8000,
}
#endregion
#region Testing
// TODO(tomat): remove when the compiler supports events
// For testing purposes only!
public void HookMaliciousAssemblyResolve()
{
AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler((_, __) =>
{
int i = 0;
while (true)
{
if (i < 10)
{
i = i + 1;
}
else if (i == 10)
{
Console.Error.WriteLine("in the loop");
i = i + 1;
}
}
});
}
public void RemoteConsoleWrite(byte[] data, bool isError)
{
using (var stream = isError ? Console.OpenStandardError() : Console.OpenStandardOutput())
{
stream.Write(data, 0, data.Length);
stream.Flush();
}
}
public bool IsShadowCopy(string path)
{
return _metadataFileProvider.IsShadowCopy(path);
}
#endregion
}
}
}
| |
// $ANTLR 3.1.2 E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g 2012-09-26 21:27:43
using System;
using Antlr.Runtime;
using IList = System.Collections.IList;
using ArrayList = System.Collections.ArrayList;
using Stack = Antlr.Runtime.Collections.StackList;
public class fbxLexer : Lexer {
public const int COLON = 5;
public const int WS = 11;
public const int COMENT = 18;
public const int COMMA = 4;
public const int LETTER = 14;
public const int RCURLY = 7;
public const int NUMBER = 13;
public const int LCURLY = 6;
public const int NL = 10;
public const int DIGIT = 12;
public const int MINUS = 9;
public const int DOT = 8;
public const int ID = 15;
public const int EOF = -1;
public const int OctalEscape = 16;
public const int STRING = 17;
// delegates
// delegators
public fbxLexer()
{
InitializeCyclicDFAs();
}
public fbxLexer(ICharStream input)
: this(input, null) {
}
public fbxLexer(ICharStream input, RecognizerSharedState state)
: base(input, state) {
InitializeCyclicDFAs();
}
override public string GrammarFileName
{
get { return "E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g";}
}
// $ANTLR start "COMMA"
public void mCOMMA() // throws RecognitionException [2]
{
try
{
int _type = COMMA;
int _channel = DEFAULT_TOKEN_CHANNEL;
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:7:7: ( ',' )
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:7:9: ','
{
Match(',');
}
state.type = _type;
state.channel = _channel;
}
finally
{
}
}
// $ANTLR end "COMMA"
// $ANTLR start "COLON"
public void mCOLON() // throws RecognitionException [2]
{
try
{
int _type = COLON;
int _channel = DEFAULT_TOKEN_CHANNEL;
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:8:7: ( ':' )
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:8:9: ':'
{
Match(':');
}
state.type = _type;
state.channel = _channel;
}
finally
{
}
}
// $ANTLR end "COLON"
// $ANTLR start "LCURLY"
public void mLCURLY() // throws RecognitionException [2]
{
try
{
int _type = LCURLY;
int _channel = DEFAULT_TOKEN_CHANNEL;
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:9:8: ( '{' )
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:9:10: '{'
{
Match('{');
}
state.type = _type;
state.channel = _channel;
}
finally
{
}
}
// $ANTLR end "LCURLY"
// $ANTLR start "RCURLY"
public void mRCURLY() // throws RecognitionException [2]
{
try
{
int _type = RCURLY;
int _channel = DEFAULT_TOKEN_CHANNEL;
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:10:8: ( '}' )
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:10:10: '}'
{
Match('}');
}
state.type = _type;
state.channel = _channel;
}
finally
{
}
}
// $ANTLR end "RCURLY"
// $ANTLR start "DOT"
public void mDOT() // throws RecognitionException [2]
{
try
{
int _type = DOT;
int _channel = DEFAULT_TOKEN_CHANNEL;
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:11:5: ( '.' )
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:11:7: '.'
{
Match('.');
}
state.type = _type;
state.channel = _channel;
}
finally
{
}
}
// $ANTLR end "DOT"
// $ANTLR start "MINUS"
public void mMINUS() // throws RecognitionException [2]
{
try
{
int _type = MINUS;
int _channel = DEFAULT_TOKEN_CHANNEL;
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:12:7: ( '-' )
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:12:9: '-'
{
Match('-');
}
state.type = _type;
state.channel = _channel;
}
finally
{
}
}
// $ANTLR end "MINUS"
// $ANTLR start "NL"
public void mNL() // throws RecognitionException [2]
{
try
{
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:21:4: ( '\\r\\n' | '\\n' | '\\r' )
int alt1 = 3;
int LA1_0 = input.LA(1);
if ( (LA1_0 == '\r') )
{
int LA1_1 = input.LA(2);
if ( (LA1_1 == '\n') )
{
alt1 = 1;
}
else
{
alt1 = 3;}
}
else if ( (LA1_0 == '\n') )
{
alt1 = 2;
}
else
{
NoViableAltException nvae_d1s0 =
new NoViableAltException("", 1, 0, input);
throw nvae_d1s0;
}
switch (alt1)
{
case 1 :
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:21:5: '\\r\\n'
{
Match("\r\n");
}
break;
case 2 :
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:22:3: '\\n'
{
Match('\n');
}
break;
case 3 :
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:23:3: '\\r'
{
Match('\r');
}
break;
}
}
finally
{
}
}
// $ANTLR end "NL"
// $ANTLR start "WS"
public void mWS() // throws RecognitionException [2]
{
try
{
int _type = WS;
int _channel = DEFAULT_TOKEN_CHANNEL;
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:26:4: ( ( ' ' | '\\t' | NL ) )
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:26:5: ( ' ' | '\\t' | NL )
{
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:26:5: ( ' ' | '\\t' | NL )
int alt2 = 3;
switch ( input.LA(1) )
{
case ' ':
{
alt2 = 1;
}
break;
case '\t':
{
alt2 = 2;
}
break;
case '\n':
case '\r':
{
alt2 = 3;
}
break;
default:
NoViableAltException nvae_d2s0 =
new NoViableAltException("", 2, 0, input);
throw nvae_d2s0;
}
switch (alt2)
{
case 1 :
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:26:6: ' '
{
Match(' ');
}
break;
case 2 :
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:26:10: '\\t'
{
Match('\t');
}
break;
case 3 :
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:26:16: NL
{
mNL();
}
break;
}
_channel=HIDDEN;
}
state.type = _type;
state.channel = _channel;
}
finally
{
}
}
// $ANTLR end "WS"
// $ANTLR start "DIGIT"
public void mDIGIT() // throws RecognitionException [2]
{
try
{
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:30:7: ( ( '0' .. '9' ) )
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:30:8: ( '0' .. '9' )
{
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:30:8: ( '0' .. '9' )
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:30:9: '0' .. '9'
{
MatchRange('0','9');
}
}
}
finally
{
}
}
// $ANTLR end "DIGIT"
// $ANTLR start "NUMBER"
public void mNUMBER() // throws RecognitionException [2]
{
try
{
int _type = NUMBER;
int _channel = DEFAULT_TOKEN_CHANNEL;
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:33:8: ( ( MINUS )? ( DIGIT )+ ( DOT ( DIGIT )+ )? ( 'e' ( MINUS )? ( DIGIT )+ )? )
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:33:11: ( MINUS )? ( DIGIT )+ ( DOT ( DIGIT )+ )? ( 'e' ( MINUS )? ( DIGIT )+ )?
{
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:33:11: ( MINUS )?
int alt3 = 2;
int LA3_0 = input.LA(1);
if ( (LA3_0 == '-') )
{
alt3 = 1;
}
switch (alt3)
{
case 1 :
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:33:11: MINUS
{
mMINUS();
}
break;
}
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:33:18: ( DIGIT )+
int cnt4 = 0;
do
{
int alt4 = 2;
int LA4_0 = input.LA(1);
if ( ((LA4_0 >= '0' && LA4_0 <= '9')) )
{
alt4 = 1;
}
switch (alt4)
{
case 1 :
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:33:18: DIGIT
{
mDIGIT();
}
break;
default:
if ( cnt4 >= 1 ) goto loop4;
EarlyExitException eee4 =
new EarlyExitException(4, input);
throw eee4;
}
cnt4++;
} while (true);
loop4:
; // Stops C# compiler whinging that label 'loop4' has no statements
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:33:25: ( DOT ( DIGIT )+ )?
int alt6 = 2;
int LA6_0 = input.LA(1);
if ( (LA6_0 == '.') )
{
alt6 = 1;
}
switch (alt6)
{
case 1 :
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:33:26: DOT ( DIGIT )+
{
mDOT();
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:33:30: ( DIGIT )+
int cnt5 = 0;
do
{
int alt5 = 2;
int LA5_0 = input.LA(1);
if ( ((LA5_0 >= '0' && LA5_0 <= '9')) )
{
alt5 = 1;
}
switch (alt5)
{
case 1 :
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:33:30: DIGIT
{
mDIGIT();
}
break;
default:
if ( cnt5 >= 1 ) goto loop5;
EarlyExitException eee5 =
new EarlyExitException(5, input);
throw eee5;
}
cnt5++;
} while (true);
loop5:
; // Stops C# compiler whinging that label 'loop5' has no statements
}
break;
}
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:33:39: ( 'e' ( MINUS )? ( DIGIT )+ )?
int alt9 = 2;
int LA9_0 = input.LA(1);
if ( (LA9_0 == 'e') )
{
alt9 = 1;
}
switch (alt9)
{
case 1 :
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:33:40: 'e' ( MINUS )? ( DIGIT )+
{
Match('e');
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:33:45: ( MINUS )?
int alt7 = 2;
int LA7_0 = input.LA(1);
if ( (LA7_0 == '-') )
{
alt7 = 1;
}
switch (alt7)
{
case 1 :
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:33:45: MINUS
{
mMINUS();
}
break;
}
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:33:52: ( DIGIT )+
int cnt8 = 0;
do
{
int alt8 = 2;
int LA8_0 = input.LA(1);
if ( ((LA8_0 >= '0' && LA8_0 <= '9')) )
{
alt8 = 1;
}
switch (alt8)
{
case 1 :
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:33:52: DIGIT
{
mDIGIT();
}
break;
default:
if ( cnt8 >= 1 ) goto loop8;
EarlyExitException eee8 =
new EarlyExitException(8, input);
throw eee8;
}
cnt8++;
} while (true);
loop8:
; // Stops C# compiler whinging that label 'loop8' has no statements
}
break;
}
}
state.type = _type;
state.channel = _channel;
}
finally
{
}
}
// $ANTLR end "NUMBER"
// $ANTLR start "LETTER"
public void mLETTER() // throws RecognitionException [2]
{
try
{
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:37:8: ( ( 'a' .. 'z' ) | ( 'A' .. 'Z' ) )
int alt10 = 2;
int LA10_0 = input.LA(1);
if ( ((LA10_0 >= 'a' && LA10_0 <= 'z')) )
{
alt10 = 1;
}
else if ( ((LA10_0 >= 'A' && LA10_0 <= 'Z')) )
{
alt10 = 2;
}
else
{
NoViableAltException nvae_d10s0 =
new NoViableAltException("", 10, 0, input);
throw nvae_d10s0;
}
switch (alt10)
{
case 1 :
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:37:9: ( 'a' .. 'z' )
{
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:37:9: ( 'a' .. 'z' )
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:37:10: 'a' .. 'z'
{
MatchRange('a','z');
}
}
break;
case 2 :
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:37:20: ( 'A' .. 'Z' )
{
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:37:20: ( 'A' .. 'Z' )
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:37:21: 'A' .. 'Z'
{
MatchRange('A','Z');
}
}
break;
}
}
finally
{
}
}
// $ANTLR end "LETTER"
// $ANTLR start "ID"
public void mID() // throws RecognitionException [2]
{
try
{
int _type = ID;
int _channel = DEFAULT_TOKEN_CHANNEL;
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:40:4: ( LETTER ( DIGIT | LETTER | '_' )* )
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:40:6: LETTER ( DIGIT | LETTER | '_' )*
{
mLETTER();
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:40:13: ( DIGIT | LETTER | '_' )*
do
{
int alt11 = 4;
switch ( input.LA(1) )
{
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
{
alt11 = 1;
}
break;
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
case 'G':
case 'H':
case 'I':
case 'J':
case 'K':
case 'L':
case 'M':
case 'N':
case 'O':
case 'P':
case 'Q':
case 'R':
case 'S':
case 'T':
case 'U':
case 'V':
case 'W':
case 'X':
case 'Y':
case 'Z':
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'g':
case 'h':
case 'i':
case 'j':
case 'k':
case 'l':
case 'm':
case 'n':
case 'o':
case 'p':
case 'q':
case 'r':
case 's':
case 't':
case 'u':
case 'v':
case 'w':
case 'x':
case 'y':
case 'z':
{
alt11 = 2;
}
break;
case '_':
{
alt11 = 3;
}
break;
}
switch (alt11)
{
case 1 :
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:40:14: DIGIT
{
mDIGIT();
}
break;
case 2 :
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:40:20: LETTER
{
mLETTER();
}
break;
case 3 :
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:40:27: '_'
{
Match('_');
}
break;
default:
goto loop11;
}
} while (true);
loop11:
; // Stops C# compiler whining that label 'loop11' has no statements
}
state.type = _type;
state.channel = _channel;
}
finally
{
}
}
// $ANTLR end "ID"
// $ANTLR start "OctalEscape"
public void mOctalEscape() // throws RecognitionException [2]
{
try
{
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:45:5: ( ( '0' .. '3' ) ( '0' .. '7' ) ( '0' .. '7' ) | ( '0' .. '7' ) ( '0' .. '7' ) | ( '0' .. '7' ) )
int alt12 = 3;
int LA12_0 = input.LA(1);
if ( ((LA12_0 >= '0' && LA12_0 <= '3')) )
{
int LA12_1 = input.LA(2);
if ( ((LA12_1 >= '0' && LA12_1 <= '7')) )
{
int LA12_3 = input.LA(3);
if ( ((LA12_3 >= '0' && LA12_3 <= '7')) )
{
alt12 = 1;
}
else
{
alt12 = 2;}
}
else
{
alt12 = 3;}
}
else if ( ((LA12_0 >= '4' && LA12_0 <= '7')) )
{
int LA12_2 = input.LA(2);
if ( ((LA12_2 >= '0' && LA12_2 <= '7')) )
{
alt12 = 2;
}
else
{
alt12 = 3;}
}
else
{
NoViableAltException nvae_d12s0 =
new NoViableAltException("", 12, 0, input);
throw nvae_d12s0;
}
switch (alt12)
{
case 1 :
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:45:10: ( '0' .. '3' ) ( '0' .. '7' ) ( '0' .. '7' )
{
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:45:10: ( '0' .. '3' )
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:45:11: '0' .. '3'
{
MatchRange('0','3');
}
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:45:21: ( '0' .. '7' )
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:45:22: '0' .. '7'
{
MatchRange('0','7');
}
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:45:32: ( '0' .. '7' )
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:45:33: '0' .. '7'
{
MatchRange('0','7');
}
}
break;
case 2 :
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:46:10: ( '0' .. '7' ) ( '0' .. '7' )
{
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:46:10: ( '0' .. '7' )
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:46:11: '0' .. '7'
{
MatchRange('0','7');
}
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:46:21: ( '0' .. '7' )
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:46:22: '0' .. '7'
{
MatchRange('0','7');
}
}
break;
case 3 :
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:47:10: ( '0' .. '7' )
{
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:47:10: ( '0' .. '7' )
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:47:11: '0' .. '7'
{
MatchRange('0','7');
}
}
break;
}
}
finally
{
}
}
// $ANTLR end "OctalEscape"
// $ANTLR start "STRING"
public void mSTRING() // throws RecognitionException [2]
{
try
{
int _type = STRING;
int _channel = DEFAULT_TOKEN_CHANNEL;
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:49:8: ( '\"' (~ ( '\"' ) )* '\"' )
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:49:10: '\"' (~ ( '\"' ) )* '\"'
{
Match('\"');
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:49:14: (~ ( '\"' ) )*
do
{
int alt13 = 2;
int LA13_0 = input.LA(1);
if ( ((LA13_0 >= '\u0000' && LA13_0 <= '!') || (LA13_0 >= '#' && LA13_0 <= '\uFFFF')) )
{
alt13 = 1;
}
switch (alt13)
{
case 1 :
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:49:16: ~ ( '\"' )
{
if ( (input.LA(1) >= '\u0000' && input.LA(1) <= '!') || (input.LA(1) >= '#' && input.LA(1) <= '\uFFFF') )
{
input.Consume();
}
else
{
MismatchedSetException mse = new MismatchedSetException(null,input);
Recover(mse);
throw mse;}
}
break;
default:
goto loop13;
}
} while (true);
loop13:
; // Stops C# compiler whining that label 'loop13' has no statements
Match('\"');
}
state.type = _type;
state.channel = _channel;
}
finally
{
}
}
// $ANTLR end "STRING"
// $ANTLR start "COMENT"
public void mCOMENT() // throws RecognitionException [2]
{
try
{
int _type = COMENT;
int _channel = DEFAULT_TOKEN_CHANNEL;
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:52:8: ( ';' (~ ( '\\n' | '\\r' ) )* ( '\\r' )? '\\n' )
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:52:10: ';' (~ ( '\\n' | '\\r' ) )* ( '\\r' )? '\\n'
{
Match(';');
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:52:14: (~ ( '\\n' | '\\r' ) )*
do
{
int alt14 = 2;
int LA14_0 = input.LA(1);
if ( ((LA14_0 >= '\u0000' && LA14_0 <= '\t') || (LA14_0 >= '\u000B' && LA14_0 <= '\f') || (LA14_0 >= '\u000E' && LA14_0 <= '\uFFFF')) )
{
alt14 = 1;
}
switch (alt14)
{
case 1 :
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:52:14: ~ ( '\\n' | '\\r' )
{
if ( (input.LA(1) >= '\u0000' && input.LA(1) <= '\t') || (input.LA(1) >= '\u000B' && input.LA(1) <= '\f') || (input.LA(1) >= '\u000E' && input.LA(1) <= '\uFFFF') )
{
input.Consume();
}
else
{
MismatchedSetException mse = new MismatchedSetException(null,input);
Recover(mse);
throw mse;}
}
break;
default:
goto loop14;
}
} while (true);
loop14:
; // Stops C# compiler whining that label 'loop14' has no statements
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:52:28: ( '\\r' )?
int alt15 = 2;
int LA15_0 = input.LA(1);
if ( (LA15_0 == '\r') )
{
alt15 = 1;
}
switch (alt15)
{
case 1 :
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:52:28: '\\r'
{
Match('\r');
}
break;
}
Match('\n');
_channel=HIDDEN;
}
state.type = _type;
state.channel = _channel;
}
finally
{
}
}
// $ANTLR end "COMENT"
override public void mTokens() // throws RecognitionException
{
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:1:8: ( COMMA | COLON | LCURLY | RCURLY | DOT | MINUS | WS | NUMBER | ID | STRING | COMENT )
int alt16 = 11;
alt16 = dfa16.Predict(input);
switch (alt16)
{
case 1 :
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:1:10: COMMA
{
mCOMMA();
}
break;
case 2 :
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:1:16: COLON
{
mCOLON();
}
break;
case 3 :
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:1:22: LCURLY
{
mLCURLY();
}
break;
case 4 :
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:1:29: RCURLY
{
mRCURLY();
}
break;
case 5 :
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:1:36: DOT
{
mDOT();
}
break;
case 6 :
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:1:40: MINUS
{
mMINUS();
}
break;
case 7 :
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:1:46: WS
{
mWS();
}
break;
case 8 :
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:1:49: NUMBER
{
mNUMBER();
}
break;
case 9 :
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:1:56: ID
{
mID();
}
break;
case 10 :
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:1:59: STRING
{
mSTRING();
}
break;
case 11 :
// E:\\DEVELOP\\Visual Studio Projects\\Vsual Studio 2010\\GameEngineSlimDX\\GEngine\\ResourcesManagers\\FBXParser\\fbx.g:1:66: COMENT
{
mCOMENT();
}
break;
}
}
protected DFA16 dfa16;
private void InitializeCyclicDFAs()
{
this.dfa16 = new DFA16(this);
}
const string DFA16_eotS =
"\x06\uffff\x01\x0c\x06\uffff";
const string DFA16_eofS =
"\x0d\uffff";
const string DFA16_minS =
"\x01\x09\x05\uffff\x01\x30\x06\uffff";
const string DFA16_maxS =
"\x01\x7d\x05\uffff\x01\x39\x06\uffff";
const string DFA16_acceptS =
"\x01\uffff\x01\x01\x01\x02\x01\x03\x01\x04\x01\x05\x01\uffff\x01"+
"\x07\x01\x08\x01\x09\x01\x0a\x01\x0b\x01\x06";
const string DFA16_specialS =
"\x0d\uffff}>";
static readonly string[] DFA16_transitionS = {
"\x02\x07\x02\uffff\x01\x07\x12\uffff\x01\x07\x01\uffff\x01"+
"\x0a\x09\uffff\x01\x01\x01\x06\x01\x05\x01\uffff\x0a\x08\x01"+
"\x02\x01\x0b\x05\uffff\x1a\x09\x06\uffff\x1a\x09\x01\x03\x01"+
"\uffff\x01\x04",
"",
"",
"",
"",
"",
"\x0a\x08",
"",
"",
"",
"",
"",
""
};
static readonly short[] DFA16_eot = DFA.UnpackEncodedString(DFA16_eotS);
static readonly short[] DFA16_eof = DFA.UnpackEncodedString(DFA16_eofS);
static readonly char[] DFA16_min = DFA.UnpackEncodedStringToUnsignedChars(DFA16_minS);
static readonly char[] DFA16_max = DFA.UnpackEncodedStringToUnsignedChars(DFA16_maxS);
static readonly short[] DFA16_accept = DFA.UnpackEncodedString(DFA16_acceptS);
static readonly short[] DFA16_special = DFA.UnpackEncodedString(DFA16_specialS);
static readonly short[][] DFA16_transition = DFA.UnpackEncodedStringArray(DFA16_transitionS);
protected class DFA16 : DFA
{
public DFA16(BaseRecognizer recognizer)
{
this.recognizer = recognizer;
this.decisionNumber = 16;
this.eot = DFA16_eot;
this.eof = DFA16_eof;
this.min = DFA16_min;
this.max = DFA16_max;
this.accept = DFA16_accept;
this.special = DFA16_special;
this.transition = DFA16_transition;
}
override public string Description
{
get { return "1:1: Tokens : ( COMMA | COLON | LCURLY | RCURLY | DOT | MINUS | WS | NUMBER | ID | STRING | COMENT );"; }
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace System.Net.Primitives.Functional.Tests
{
public class IPAddressParsing
{
#region IPv4
[Theory]
[InlineData("192.168.0.1", "192.168.0.1")]
[InlineData("0.0.0.0", "0.0.0.0")]
[InlineData("0", "0.0.0.0")]
[InlineData("255.255.255.255", "255.255.255.255")]
[InlineData("4294967294", "255.255.255.254")]
[InlineData("4294967295", "255.255.255.255")]
[InlineData("157.3873051", "157.59.25.27")]
[InlineData("157.6427", "157.0.25.27")]
[InlineData("2637895963", "157.59.25.27")]
public void ParseIPv4_Decimal_Success(string address, string expected)
{
Assert.Equal(expected, IPAddress.Parse(address).ToString());
}
[Theory]
[InlineData("0xFF.0xFF.0xFF.0xFF", "255.255.255.255")]
[InlineData("0x0", "0.0.0.0")]
[InlineData("0xFFFFFFFE", "255.255.255.254")]
[InlineData("0xFFFFFFFF", "255.255.255.255")]
[InlineData("0x9D3B191B", "157.59.25.27")]
[InlineData("0X9D.0x3B.0X19.0x1B", "157.59.25.27")]
[InlineData("0x89.0xab.0xcd.0xef", "137.171.205.239")]
public void ParseIPv4_Hex_Success(string address, string expected)
{
Assert.Equal(expected, IPAddress.Parse(address).ToString());
}
[Theory]
[InlineData("0377.0377.0377.0377", "255.255.255.255")]
[InlineData("037777777776", "255.255.255.254")]
[InlineData("037777777777", "255.255.255.255")]
[InlineData("023516614433", "157.59.25.27")]
[InlineData("00000023516614433", "157.59.25.27")]
public void ParseIPv4_Octal_Success(string address, string expected)
{
Assert.Equal(expected, IPAddress.Parse(address).ToString());
}
[Theory]
[ActiveIssue(8362, PlatformID.OSX)]
[InlineData("000235.000073.0000031.00000033", "157.59.25.27")] // Octal
[InlineData("0235.073.031.033", "157.59.25.27")] // Octal
[InlineData("157.59.25.033", "157.59.25.27")] // Partial octal
public void ParseIPv4_Octal_Success_NonOSX(string address, string expected)
{
Assert.Equal(expected, IPAddress.Parse(address).ToString());
}
[Theory]
[InlineData("157.59.25.0x1B", "157.59.25.27")]
[InlineData("157.59.0x001B", "157.59.0.27")]
[InlineData("157.0x00001B", "157.0.0.27")]
[InlineData("157.59.0x25.033", "157.59.37.27")]
public void ParseIPv4_MixedBase_Success(string address, string expected)
{
Assert.Equal(expected, IPAddress.Parse(address).ToString());
}
[Fact]
public void ParseIPv4_WithSubnet_Failure()
{
Assert.Throws<FormatException>(() => { IPAddress.Parse("192.168.0.0/16"); });
}
[Fact]
public void ParseIPv4_WithPort_Failure()
{
Assert.Throws<FormatException>(() => { IPAddress.Parse("192.168.0.1:80"); });
}
[Fact]
public void ParseIPv4_Empty_Failure()
{
Assert.Throws<FormatException>(() => { IPAddress.Parse(""); });
}
[Theory]
[InlineData(" ")]
[InlineData(" 127.0.0.1")]
public void ParseIPv4_Whitespace_Failure(string address)
{
Assert.Throws<FormatException>(() => { IPAddress.Parse(address); });
}
[Theory]
[InlineData("157.3B191B")] // Hex without 0x
[InlineData("1.1.1.0x")] // Empty trailing hex segment
[InlineData("0000X9D.0x3B.0X19.0x1B")] // Leading zeros on hex
public void ParseIPv4_InvalidHex_Failure(string address)
{
Assert.Throws<FormatException>(() => { IPAddress.Parse(address); });
}
[Theory]
[PlatformSpecific(~PlatformID.OSX)] // There doesn't appear to be an OSX API that will fail for these
[InlineData("0x.1.1.1")] // Empty leading hex segment
public void ParseIPv4_InvalidHex_Failure_NonOSX(string address)
{
Assert.Throws<FormatException>(() => { IPAddress.Parse(address); });
}
[Theory]
[ActiveIssue(8362, PlatformID.OSX)]
[InlineData("0.0.0.089")] // Octal (leading zero) but with 8 or 9
public void ParseIPv4_InvalidOctal_Failure(string address)
{
Assert.Throws<FormatException>(() => { IPAddress.Parse(address); });
}
[Theory]
[InlineData("260.156")] // Left dotted segments can't be more than 255
[InlineData("255.260.156")] // Left dotted segments can't be more than 255
[InlineData("0xFF.0xFFFFFF.0xFF")] // Middle segment too large
[InlineData("0xFFFFFF.0xFF.0xFFFFFF")] // Leading segment too large
public void ParseIPv4_InvalidValue_Failure(string address)
{
Assert.Throws<FormatException>(() => { IPAddress.Parse(address); });
}
[Theory]
[PlatformSpecific(~PlatformID.OSX)] // There does't appear to be an OSX API that will fail for these
[InlineData("4294967296")] // Decimal overflow by 1
[InlineData("040000000000")] // Octal overflow by 1
[InlineData("01011101001110110001100100011011")] // Binary? Read as octal, overflows
[InlineData("10011101001110110001100100011011")] // Binary? Read as decimal, overflows
[InlineData("0x100000000")] // Hex overflow by 1
public void ParseIPv4_InvalidValue_Failure_NonOSX(string address)
{
Assert.Throws<FormatException>(() => { IPAddress.Parse(address); });
}
[Theory]
[InlineData("1.1\u67081.1.1")] // Unicode, Crashes .NET 4.0 IPAddress.TryParse
public void ParseIPv4_InvalidChar_Failure(string address)
{
Assert.Throws<FormatException>(() => { IPAddress.Parse(address); });
}
[Theory]
[InlineData("...")] // Empty sections
[InlineData("1.1.1.")] // Empty trailing section
[InlineData("1..1.1")] // Empty internal section
[InlineData(".1.1.1")] // Empty leading section
[InlineData("..11.1")] // Empty sections
public void ParseIPv4_EmptySection_Failure(string address)
{
Assert.Throws<FormatException>(() => { IPAddress.Parse(address); });
}
#endregion
#region IPv6
[Theory]
[InlineData("Fe08::1", "fe08::1")]
[InlineData("0000:0000:0000:0000:0000:0000:0000:0000", "::")]
[InlineData("FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF", "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff")]
[InlineData("0:0:0:0:0:0:0:0", "::")]
[InlineData("1:0:0:0:0:0:0:0", "1::")]
[InlineData("0:1:0:0:0:0:0:0", "0:1::")]
[InlineData("0:0:1:0:0:0:0:0", "0:0:1::")]
[InlineData("0:0:0:1:0:0:0:0", "0:0:0:1::")]
[InlineData("0:0:0:0:1:0:0:0", "::1:0:0:0")]
[InlineData("0:0:0:0:0:1:0:0", "::1:0:0")]
[InlineData("0:0:0:0:0:0:1:0", "::0.1.0.0")]
[InlineData("0:0:0:0:0:0:0:1", "::1")]
[InlineData("1:0:0:0:0:0:0:1", "1::1")]
[InlineData("1:1:0:0:0:0:0:1", "1:1::1")]
[InlineData("1:0:1:0:0:0:0:1", "1:0:1::1")]
[InlineData("1:0:0:1:0:0:0:1", "1:0:0:1::1")]
[InlineData("1:0:0:0:1:0:0:1", "1::1:0:0:1")]
[InlineData("1:0:0:0:0:1:0:1", "1::1:0:1")]
[InlineData("1:0:0:0:0:0:1:1", "1::1:1")]
[InlineData("1:1:0:0:1:0:0:1", "1:1::1:0:0:1")]
[InlineData("1:0:1:0:0:1:0:1", "1:0:1::1:0:1")]
[InlineData("1:0:0:1:0:0:1:1", "1::1:0:0:1:1")]
[InlineData("1:1:0:0:0:1:0:1", "1:1::1:0:1")]
[InlineData("1:0:0:0:1:0:1:1", "1::1:0:1:1")]
[InlineData("::", "::")]
public void ParseIPv6_NoBrackets_Success(string address, string expected)
{
Assert.Equal(expected, IPAddress.Parse(address).ToString());
}
[Fact]
public void ParseIPv6_Brackets_SuccessBracketsDropped()
{
Assert.Equal("fe08::1", IPAddress.Parse("[Fe08::1]").ToString());
}
[Fact]
public void ParseIPv6_LeadingBracket_Failure()
{
Assert.Throws<FormatException>(() => { IPAddress.Parse("[Fe08::1"); });
}
[Fact]
public void ParseIPv6_TrailingBracket_Failure()
{
Assert.Throws<FormatException>(() => { IPAddress.Parse("Fe08::1]"); });
}
[Fact]
public void ParseIPv6_BracketsAndPort_SuccessBracketsAndPortDropped()
{
Assert.Equal("fe08::1", IPAddress.Parse("[Fe08::1]:80").ToString());
}
[Fact]
public void ParseIPv6_BracketsAndInvalidPort_Failure()
{
Assert.Throws<FormatException>(() => { IPAddress.Parse("[Fe08::1]:80Z"); });
}
[Fact]
public void ParseIPv6_BracketsAndHexPort_SuccessBracketsAndPortDropped()
{
Assert.Equal("fe08::1", IPAddress.Parse("[Fe08::1]:0xFA").ToString());
}
[Fact]
public void ParseIPv6_WithSubnet_Failure()
{
Assert.Throws<FormatException>(() => { IPAddress.Parse("Fe08::/64"); });
}
[Theory]
[InlineData("Fe08::1%13542", "fe08::1%13542")]
[InlineData("1::%1", "1::%1")]
[InlineData("::1%12", "::1%12")]
[InlineData("::%123", "::%123")]
public void ParseIPv6_ScopeID_Success(string address, string expected)
{
Assert.Equal(expected, IPAddress.Parse(address).ToString());
}
[Theory]
[InlineData("FE08::192.168.0.1", "fe08::c0a8:1")] // Output is not IPv4 mapped
[InlineData("::192.168.0.1", "::192.168.0.1")]
[InlineData("::FFFF:192.168.0.1", "::ffff:192.168.0.1")] // SIIT
public void ParseIPv6_v4_Success(string address, string expected)
{
Assert.Equal(expected, IPAddress.Parse(address).ToString());
}
[Theory]
[PlatformSpecific(~PlatformID.AnyUnix)]
// Linux/OSX don't do the IPv6->IPv4 formatting for these addresses
[InlineData("::FFFF:0:192.168.0.1", "::ffff:0:192.168.0.1")] // SIIT
[InlineData("::5EFE:192.168.0.1", "::5efe:192.168.0.1")] // ISATAP
[InlineData("1::5EFE:192.168.0.1", "1::5efe:192.168.0.1")] // ISATAP
public void ParseIPv6_v4_Success_NonUnix(string address, string expected)
{
Assert.Equal(expected, IPAddress.Parse(address).ToString());
}
[Theory]
[PlatformSpecific(PlatformID.AnyUnix)]
// Linux/OSX don't do the IPv6->IPv4 formatting for these addresses
[InlineData("::FFFF:0:192.168.0.1", "::ffff:0:c0a8:1")] // SIIT
[InlineData("::5EFE:192.168.0.1", "::5efe:c0a8:1")] // ISATAP
[InlineData("1::5EFE:192.168.0.1", "1::5efe:c0a8:1")] // ISATAP
public void ParseIPv6_v4_Success_Unix(string address, string expected)
{
Assert.Equal(expected, IPAddress.Parse(address).ToString());
}
[Theory]
[PlatformSpecific(~PlatformID.Linux)] // Linux does not appear to recognize this as a valid address
[InlineData("::192.168.0.010", "::192.168.0.10")] // Embedded IPv4 octal, read as decimal
public void ParseIPv6_v4_Success_NonLinux(string address, string expected)
{
Assert.Equal(expected, IPAddress.Parse(address).ToString());
}
[Fact]
public void ParseIPv6_Incomplete_Failure()
{
Assert.Throws<FormatException>(() => { IPAddress.Parse("[1]"); });
}
[Fact]
public void ParseIPv6_LeadingSingleColon_Failure()
{
Assert.Throws<FormatException>(() => { IPAddress.Parse(":1"); });
}
[Fact]
public void ParseIPv6_TrailingSingleColon_Failure()
{
Assert.Throws<FormatException>(() => { IPAddress.Parse("1:"); });
}
[Fact]
public void ParseIPv6_LeadingWhitespace_Failure()
{
Assert.Throws<FormatException>(() => { IPAddress.Parse(" ::1"); });
}
[Fact]
public void ParseIPv6_TrailingWhitespace_Failure()
{
Assert.Throws<FormatException>(() => { IPAddress.Parse("::1 "); });
}
[Fact]
public void ParseIPv6_Ambiguous_Failure()
{
Assert.Throws<FormatException>(() => { IPAddress.Parse("1::1::1"); });
}
[Fact]
public void ParseIPv6_InvalidChar_Failure()
{
Assert.Throws<FormatException>(() => { IPAddress.Parse("1:1\u67081:1:1"); });
}
[Fact]
public void ParseIPv6_v4_OutOfRange_Failure()
{
Assert.Throws<FormatException>(() => { IPAddress.Parse("FE08::260.168.0.1"); });
}
[Fact]
public void ParseIPv6_v4_Hex_Failure()
{
Assert.Throws<FormatException>(() => { IPAddress.Parse("::192.168.0.0x0"); });
}
[Fact]
public void ParseIPv6_Rawv4_Failure()
{
Assert.Throws<FormatException>(() => { IPAddress.Parse("[192.168.0.1]"); });
}
[Fact]
public void ParseIPv6_InvalidHex_Failure()
{
Assert.Throws<FormatException>(() => { IPAddress.Parse("G::"); });
}
[Fact]
public void ParseIPv6_InvalidValue_Failure()
{
Assert.Throws<FormatException>(() => { IPAddress.Parse("FFFFF::"); });
}
[Fact]
public void ParseIPv6_ColonScope_Failure()
{
Assert.Throws<FormatException>(() => { IPAddress.Parse(":%12"); });
}
[Fact]
public void ParseIPv6_JustScope_Failure()
{
Assert.Throws<FormatException>(() => { IPAddress.Parse("%12"); });
}
[Fact]
[PlatformSpecific(~PlatformID.OSX)]
public void ParseIPv6_AlphaNumericScope_Failure()
{
Assert.Throws<FormatException>(() => { IPAddress.Parse("::%1a"); });
}
#endregion
[Fact]
public void Parse_Null_Throws()
{
Assert.Throws<ArgumentNullException>(() => { IPAddress.Parse(null); });
}
[Fact]
public void TryParse_Null_False()
{
IPAddress ipAddress;
Assert.False(IPAddress.TryParse(null, out ipAddress));
}
[Fact]
public void Parse_Empty_Throws()
{
Assert.Throws<FormatException>(() => { IPAddress.Parse(String.Empty); });
}
[Fact]
public void TryParse_Empty_False()
{
IPAddress ipAddress;
Assert.False(IPAddress.TryParse(String.Empty, out ipAddress));
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
// <OWNER>[....]</OWNER>
//
//
// SHA512Managed.cs
//
// C# implementation of the proposed SHA-512 hash algorithm
//
namespace System.Security.Cryptography {
using System;
using System.Diagnostics.Contracts;
[System.Runtime.InteropServices.ComVisible(true)]
public class SHA512Managed : SHA512
{
private byte[] _buffer;
private ulong _count; // Number of bytes in the hashed message
private UInt64[] _stateSHA512;
private UInt64[] _W;
//
// public constructors
//
public SHA512Managed()
{
if (CryptoConfig.AllowOnlyFipsAlgorithms)
throw new InvalidOperationException(Environment.GetResourceString("Cryptography_NonCompliantFIPSAlgorithm"));
Contract.EndContractBlock();
_stateSHA512 = new UInt64[8];
_buffer = new byte[128];
_W = new UInt64[80];
InitializeState();
}
//
// public methods
//
public override void Initialize() {
InitializeState();
// Zeroize potentially sensitive information.
Array.Clear(_buffer, 0, _buffer.Length);
Array.Clear(_W, 0, _W.Length);
}
[System.Security.SecuritySafeCritical] // auto-generated
protected override void HashCore(byte[] rgb, int ibStart, int cbSize) {
_HashData(rgb, ibStart, cbSize);
}
[System.Security.SecuritySafeCritical] // auto-generated
protected override byte[] HashFinal() {
return _EndHash();
}
//
// private methods
//
private void InitializeState() {
_count = 0;
_stateSHA512[0] = 0x6a09e667f3bcc908;
_stateSHA512[1] = 0xbb67ae8584caa73b;
_stateSHA512[2] = 0x3c6ef372fe94f82b;
_stateSHA512[3] = 0xa54ff53a5f1d36f1;
_stateSHA512[4] = 0x510e527fade682d1;
_stateSHA512[5] = 0x9b05688c2b3e6c1f;
_stateSHA512[6] = 0x1f83d9abfb41bd6b;
_stateSHA512[7] = 0x5be0cd19137e2179;
}
/* SHA512 block update operation. Continues an SHA message-digest
operation, processing another message block, and updating the
context.
*/
[System.Security.SecurityCritical] // auto-generated
private unsafe void _HashData(byte[] partIn, int ibStart, int cbSize)
{
int bufferLen;
int partInLen = cbSize;
int partInBase = ibStart;
/* Compute length of buffer */
bufferLen = (int) (_count & 0x7f);
/* Update number of bytes */
_count += (ulong) partInLen;
fixed (UInt64* stateSHA512 = _stateSHA512) {
fixed (byte* buffer = _buffer) {
fixed (UInt64* expandedBuffer = _W) {
if ((bufferLen > 0) && (bufferLen + partInLen >= 128)) {
Buffer.InternalBlockCopy(partIn, partInBase, _buffer, bufferLen, 128 - bufferLen);
partInBase += (128 - bufferLen);
partInLen -= (128 - bufferLen);
SHATransform(expandedBuffer, stateSHA512, buffer);
bufferLen = 0;
}
/* Copy input to temporary buffer and hash */
while (partInLen >= 128) {
Buffer.InternalBlockCopy(partIn, partInBase, _buffer, 0, 128);
partInBase += 128;
partInLen -= 128;
SHATransform(expandedBuffer, stateSHA512, buffer);
}
if (partInLen > 0) {
Buffer.InternalBlockCopy(partIn, partInBase, _buffer, bufferLen, partInLen);
}
}
}
}
}
/* SHA512 finalization. Ends an SHA512 message-digest operation, writing
the message digest.
*/
[System.Security.SecurityCritical] // auto-generated
private byte[] _EndHash()
{
byte[] pad;
int padLen;
ulong bitCount;
byte[] hash = new byte[64]; // HashSizeValue = 512
/* Compute padding: 80 00 00 ... 00 00 <bit count>
*/
padLen = 128 - (int)(_count & 0x7f);
if (padLen <= 16)
padLen += 128;
pad = new byte[padLen];
pad[0] = 0x80;
// Convert count to bit count
bitCount = _count * 8;
// If we ever have UInt128 for bitCount, then these need to be uncommented.
// Note that C# only looks at the low 6 bits of the shift value for ulongs,
// so >>0 and >>64 are equal!
//pad[padLen-16] = (byte) ((bitCount >> 120) & 0xff);
//pad[padLen-15] = (byte) ((bitCount >> 112) & 0xff);
//pad[padLen-14] = (byte) ((bitCount >> 104) & 0xff);
//pad[padLen-13] = (byte) ((bitCount >> 96) & 0xff);
//pad[padLen-12] = (byte) ((bitCount >> 88) & 0xff);
//pad[padLen-11] = (byte) ((bitCount >> 80) & 0xff);
//pad[padLen-10] = (byte) ((bitCount >> 72) & 0xff);
//pad[padLen-9] = (byte) ((bitCount >> 64) & 0xff);
pad[padLen-8] = (byte) ((bitCount >> 56) & 0xff);
pad[padLen-7] = (byte) ((bitCount >> 48) & 0xff);
pad[padLen-6] = (byte) ((bitCount >> 40) & 0xff);
pad[padLen-5] = (byte) ((bitCount >> 32) & 0xff);
pad[padLen-4] = (byte) ((bitCount >> 24) & 0xff);
pad[padLen-3] = (byte) ((bitCount >> 16) & 0xff);
pad[padLen-2] = (byte) ((bitCount >> 8) & 0xff);
pad[padLen-1] = (byte) ((bitCount >> 0) & 0xff);
/* Digest padding */
_HashData(pad, 0, pad.Length);
/* Store digest */
Utils.QuadWordToBigEndian (hash, _stateSHA512, 8);
HashValue = hash;
return hash;
}
private readonly static UInt64[] _K = {
0x428a2f98d728ae22, 0x7137449123ef65cd, 0xb5c0fbcfec4d3b2f, 0xe9b5dba58189dbbc,
0x3956c25bf348b538, 0x59f111f1b605d019, 0x923f82a4af194f9b, 0xab1c5ed5da6d8118,
0xd807aa98a3030242, 0x12835b0145706fbe, 0x243185be4ee4b28c, 0x550c7dc3d5ffb4e2,
0x72be5d74f27b896f, 0x80deb1fe3b1696b1, 0x9bdc06a725c71235, 0xc19bf174cf692694,
0xe49b69c19ef14ad2, 0xefbe4786384f25e3, 0x0fc19dc68b8cd5b5, 0x240ca1cc77ac9c65,
0x2de92c6f592b0275, 0x4a7484aa6ea6e483, 0x5cb0a9dcbd41fbd4, 0x76f988da831153b5,
0x983e5152ee66dfab, 0xa831c66d2db43210, 0xb00327c898fb213f, 0xbf597fc7beef0ee4,
0xc6e00bf33da88fc2, 0xd5a79147930aa725, 0x06ca6351e003826f, 0x142929670a0e6e70,
0x27b70a8546d22ffc, 0x2e1b21385c26c926, 0x4d2c6dfc5ac42aed, 0x53380d139d95b3df,
0x650a73548baf63de, 0x766a0abb3c77b2a8, 0x81c2c92e47edaee6, 0x92722c851482353b,
0xa2bfe8a14cf10364, 0xa81a664bbc423001, 0xc24b8b70d0f89791, 0xc76c51a30654be30,
0xd192e819d6ef5218, 0xd69906245565a910, 0xf40e35855771202a, 0x106aa07032bbd1b8,
0x19a4c116b8d2d0c8, 0x1e376c085141ab53, 0x2748774cdf8eeb99, 0x34b0bcb5e19b48a8,
0x391c0cb3c5c95a63, 0x4ed8aa4ae3418acb, 0x5b9cca4f7763e373, 0x682e6ff3d6b2b8a3,
0x748f82ee5defb2fc, 0x78a5636f43172f60, 0x84c87814a1f0ab72, 0x8cc702081a6439ec,
0x90befffa23631e28, 0xa4506cebde82bde9, 0xbef9a3f7b2c67915, 0xc67178f2e372532b,
0xca273eceea26619c, 0xd186b8c721c0c207, 0xeada7dd6cde0eb1e, 0xf57d4f7fee6ed178,
0x06f067aa72176fba, 0x0a637dc5a2c898a6, 0x113f9804bef90dae, 0x1b710b35131c471b,
0x28db77f523047d84, 0x32caab7b40c72493, 0x3c9ebe0a15c9bebc, 0x431d67c49c100d4c,
0x4cc5d4becb3e42b6, 0x597f299cfc657e2a, 0x5fcb6fab3ad6faec, 0x6c44198c4a475817,
};
[System.Security.SecurityCritical] // auto-generated
private static unsafe void SHATransform (UInt64* expandedBuffer, UInt64* state, byte* block)
{
UInt64 a, b, c, d, e, f, g, h;
UInt64 aa, bb, cc, dd, ee, ff, hh, gg;
UInt64 T1;
a = state[0];
b = state[1];
c = state[2];
d = state[3];
e = state[4];
f = state[5];
g = state[6];
h = state[7];
// fill in the first 16 blocks of W.
Utils.QuadWordFromBigEndian (expandedBuffer, 16, block);
SHA512Expand (expandedBuffer);
/* Apply the SHA512 compression function */
// We are trying to be smart here and avoid as many copies as we can
// The perf gain with this method over the straightforward modify and shift
// forward is >= 20%, so it's worth the pain
for (int j=0; j<80; ) {
T1 = h + Sigma_1(e) + Ch(e,f,g) + _K[j] + expandedBuffer[j];
ee = d + T1;
aa = T1 + Sigma_0(a) + Maj(a,b,c);
j++;
T1 = g + Sigma_1(ee) + Ch(ee,e,f) + _K[j] + expandedBuffer[j];
ff = c + T1;
bb = T1 + Sigma_0(aa) + Maj(aa,a,b);
j++;
T1 = f + Sigma_1(ff) + Ch(ff,ee,e) + _K[j] + expandedBuffer[j];
gg = b + T1;
cc = T1 + Sigma_0(bb) + Maj(bb,aa,a);
j++;
T1 = e + Sigma_1(gg) + Ch(gg,ff,ee) + _K[j] + expandedBuffer[j];
hh = a + T1;
dd = T1 + Sigma_0(cc) + Maj(cc,bb,aa);
j++;
T1 = ee + Sigma_1(hh) + Ch(hh,gg,ff) + _K[j] + expandedBuffer[j];
h = aa + T1;
d = T1 + Sigma_0(dd) + Maj(dd,cc,bb);
j++;
T1 = ff + Sigma_1(h) + Ch(h,hh,gg) + _K[j] + expandedBuffer[j];
g = bb + T1;
c = T1 + Sigma_0(d) + Maj(d,dd,cc);
j++;
T1 = gg + Sigma_1(g) + Ch(g,h,hh) + _K[j] + expandedBuffer[j];
f = cc + T1;
b = T1 + Sigma_0(c) + Maj(c,d,dd);
j++;
T1 = hh + Sigma_1(f) + Ch(f,g,h) + _K[j] + expandedBuffer[j];
e = dd + T1;
a = T1 + Sigma_0(b) + Maj(b,c,d);
j++;
}
state[0] += a;
state[1] += b;
state[2] += c;
state[3] += d;
state[4] += e;
state[5] += f;
state[6] += g;
state[7] += h;
}
private static UInt64 RotateRight(UInt64 x, int n) {
return (((x) >> (n)) | ((x) << (64-(n))));
}
private static UInt64 Ch(UInt64 x, UInt64 y, UInt64 z) {
return ((x & y) ^ ((x ^ 0xffffffffffffffff) & z));
}
private static UInt64 Maj(UInt64 x, UInt64 y, UInt64 z) {
return ((x & y) ^ (x & z) ^ (y & z));
}
private static UInt64 Sigma_0(UInt64 x) {
return (RotateRight(x,28) ^ RotateRight(x,34) ^ RotateRight(x,39));
}
private static UInt64 Sigma_1(UInt64 x) {
return (RotateRight(x,14) ^ RotateRight(x,18) ^ RotateRight(x,41));
}
private static UInt64 sigma_0(UInt64 x) {
return (RotateRight(x,1) ^ RotateRight(x,8) ^ (x >> 7));
}
private static UInt64 sigma_1(UInt64 x) {
return (RotateRight(x,19) ^ RotateRight(x,61) ^ (x >> 6));
}
/* This function creates W_16,...,W_79 according to the formula
W_j <- sigma_1(W_{j-2}) + W_{j-7} + sigma_0(W_{j-15}) + W_{j-16};
*/
[System.Security.SecurityCritical] // auto-generated
private static unsafe void SHA512Expand (UInt64* x)
{
for (int i = 16; i < 80; i++) {
x[i] = sigma_1(x[i-2]) + x[i-7] + sigma_0(x[i-15]) + x[i-16];
}
}
}
}
| |
// 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.
// ------------------------------------------------------------------------------
// Changes to this file must follow the http://aka.ms/api-review process.
// ------------------------------------------------------------------------------
namespace System
{
public readonly partial struct Char8 : System.IComparable<System.Char8>, System.IEquatable<System.Char8>
{
private readonly int _dummyPrimitive;
public int CompareTo(System.Char8 other) { throw null; }
public bool Equals(System.Char8 other) { throw null; }
public override bool Equals(object? obj) { throw null; }
public override int GetHashCode() { throw null; }
public static bool operator ==(System.Char8 left, System.Char8 right) { throw null; }
public static explicit operator System.Char8(char value) { throw null; }
public static explicit operator char(System.Char8 value) { throw null; }
[System.CLSCompliantAttribute(false)]
public static explicit operator sbyte(System.Char8 value) { throw null; }
public static explicit operator System.Char8(short value) { throw null; }
public static explicit operator System.Char8(int value) { throw null; }
public static explicit operator System.Char8(long value) { throw null; }
[System.CLSCompliantAttribute(false)]
public static explicit operator System.Char8(sbyte value) { throw null; }
[System.CLSCompliantAttribute(false)]
public static explicit operator System.Char8(ushort value) { throw null; }
[System.CLSCompliantAttribute(false)]
public static explicit operator System.Char8(uint value) { throw null; }
[System.CLSCompliantAttribute(false)]
public static explicit operator System.Char8(ulong value) { throw null; }
public static bool operator >(System.Char8 left, System.Char8 right) { throw null; }
public static bool operator >=(System.Char8 left, System.Char8 right) { throw null; }
public static implicit operator System.Char8(byte value) { throw null; }
public static implicit operator byte(System.Char8 value) { throw null; }
public static implicit operator short(System.Char8 value) { throw null; }
public static implicit operator int(System.Char8 value) { throw null; }
public static implicit operator long(System.Char8 value) { throw null; }
[System.CLSCompliantAttribute(false)]
public static implicit operator ushort(System.Char8 value) { throw null; }
[System.CLSCompliantAttribute(false)]
public static implicit operator uint(System.Char8 value) { throw null; }
[System.CLSCompliantAttribute(false)]
public static implicit operator ulong(System.Char8 value) { throw null; }
public static bool operator !=(System.Char8 left, System.Char8 right) { throw null; }
public static bool operator <(System.Char8 left, System.Char8 right) { throw null; }
public static bool operator <=(System.Char8 left, System.Char8 right) { throw null; }
public override string ToString() { throw null; }
}
public static partial class Utf8Extensions
{
public static System.ReadOnlySpan<byte> AsBytes(this System.ReadOnlySpan<System.Char8> text) { throw null; }
public static System.ReadOnlySpan<byte> AsBytes(this System.Utf8String? text) { throw null; }
public static System.ReadOnlySpan<byte> AsBytes(this System.Utf8String? text, int start) { throw null; }
public static System.ReadOnlySpan<byte> AsBytes(this System.Utf8String? text, int start, int length) { throw null; }
public static System.ReadOnlyMemory<System.Char8> AsMemory(this System.Utf8String? text) { throw null; }
public static System.ReadOnlyMemory<System.Char8> AsMemory(this System.Utf8String? text, System.Index startIndex) { throw null; }
public static System.ReadOnlyMemory<System.Char8> AsMemory(this System.Utf8String? text, int start) { throw null; }
public static System.ReadOnlyMemory<System.Char8> AsMemory(this System.Utf8String? text, int start, int length) { throw null; }
public static System.ReadOnlyMemory<System.Char8> AsMemory(this System.Utf8String? text, System.Range range) { throw null; }
public static System.ReadOnlyMemory<byte> AsMemoryBytes(this System.Utf8String? text) { throw null; }
public static System.ReadOnlyMemory<byte> AsMemoryBytes(this System.Utf8String? text, System.Index startIndex) { throw null; }
public static System.ReadOnlyMemory<byte> AsMemoryBytes(this System.Utf8String? text, int start) { throw null; }
public static System.ReadOnlyMemory<byte> AsMemoryBytes(this System.Utf8String? text, int start, int length) { throw null; }
public static System.ReadOnlyMemory<byte> AsMemoryBytes(this System.Utf8String? text, System.Range range) { throw null; }
public static System.Text.Utf8Span AsSpan(this System.Utf8String? text) { throw null; }
public static System.Text.Utf8Span AsSpan(this System.Utf8String? text, int start) { throw null; }
public static System.Text.Utf8Span AsSpan(this System.Utf8String? text, int start, int length) { throw null; }
public static System.Utf8String ToUtf8String(this System.Text.Rune rune) { throw null; }
}
public sealed partial class Utf8String : System.IComparable<System.Utf8String?>,
#nullable disable
System.IEquatable<System.Utf8String>
#nullable restore
{
public static readonly System.Utf8String Empty;
[System.CLSCompliantAttribute(false)]
public unsafe Utf8String(byte* value) { }
public Utf8String(byte[] value, int startIndex, int length) { }
[System.CLSCompliantAttribute(false)]
public unsafe Utf8String(char* value) { }
public Utf8String(char[] value, int startIndex, int length) { }
public Utf8String(System.ReadOnlySpan<byte> value) { }
public Utf8String(System.ReadOnlySpan<char> value) { }
public Utf8String(string value) { }
public ByteEnumerable Bytes { get { throw null; } }
public CharEnumerable Chars { get { throw null; } }
public int Length { get { throw null; } }
public RuneEnumerable Runes { get { throw null; } }
public static bool AreEquivalent(System.Utf8String? utf8Text, string? utf16Text) { throw null; }
public static bool AreEquivalent(System.Text.Utf8Span utf8Text, System.ReadOnlySpan<char> utf16Text) { throw null; }
public static bool AreEquivalent(System.ReadOnlySpan<byte> utf8Text, System.ReadOnlySpan<char> utf16Text) { throw null; }
public int CompareTo(System.Utf8String? other) { throw null; }
public int CompareTo(System.Utf8String? other, System.StringComparison comparison) { throw null; }
public bool Contains(char value) { throw null; }
public bool Contains(char value, System.StringComparison comparison) { throw null; }
public bool Contains(System.Text.Rune value) { throw null; }
public bool Contains(System.Text.Rune value, System.StringComparison comparison) { throw null; }
public bool Contains(System.Utf8String value) { throw null; }
public bool Contains(System.Utf8String value, System.StringComparison comparison) { throw null; }
public static System.Utf8String Create<TState>(int length, TState state, System.Buffers.SpanAction<byte, TState> action) { throw null; }
public static System.Utf8String CreateFromRelaxed(System.ReadOnlySpan<byte> buffer) { throw null; }
public static System.Utf8String CreateFromRelaxed(System.ReadOnlySpan<char> buffer) { throw null; }
public static System.Utf8String CreateRelaxed<TState>(int length, TState state, System.Buffers.SpanAction<byte, TState> action) { throw null; }
public bool EndsWith(char value) { throw null; }
public bool EndsWith(char value, System.StringComparison comparison) { throw null; }
public bool EndsWith(System.Text.Rune value) { throw null; }
public bool EndsWith(System.Text.Rune value, System.StringComparison comparison) { throw null; }
public bool EndsWith(System.Utf8String value) { throw null; }
public bool EndsWith(System.Utf8String value, System.StringComparison comparison) { throw null; }
public override bool Equals(object? obj) { throw null; }
public static bool Equals(System.Utf8String? a, System.Utf8String? b, System.StringComparison comparison) { throw null; }
public static bool Equals(System.Utf8String? left, System.Utf8String? right) { throw null; }
public bool Equals(System.Utf8String? value) { throw null; }
public bool Equals(System.Utf8String? value, System.StringComparison comparison) { throw null; }
public override int GetHashCode() { throw null; }
public int GetHashCode(System.StringComparison comparison) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public ref readonly byte GetPinnableReference() { throw null; }
public static implicit operator System.Text.Utf8Span(System.Utf8String? value) { throw null; }
public bool IsAscii() { throw null; }
public bool IsNormalized(System.Text.NormalizationForm normalizationForm = System.Text.NormalizationForm.FormC) { throw null; }
public static bool IsNullOrEmpty([System.Diagnostics.CodeAnalysis.NotNullWhenAttribute(false)] System.Utf8String? value) { throw null; }
public static bool IsNullOrWhiteSpace([System.Diagnostics.CodeAnalysis.NotNullWhenAttribute(false)] System.Utf8String? value) { throw null; }
public System.Utf8String Normalize(System.Text.NormalizationForm normalizationForm = System.Text.NormalizationForm.FormC) { throw null; }
public static bool operator !=(System.Utf8String? left, System.Utf8String? right) { throw null; }
public static bool operator ==(System.Utf8String? left, System.Utf8String? right) { throw null; }
public SplitResult Split(char separator, System.Utf8StringSplitOptions options = System.Utf8StringSplitOptions.None) { throw null; }
public SplitResult Split(System.Text.Rune separator, System.Utf8StringSplitOptions options = System.Utf8StringSplitOptions.None) { throw null; }
public SplitResult Split(System.Utf8String separator, System.Utf8StringSplitOptions options = System.Utf8StringSplitOptions.None) { throw null; }
public SplitOnResult SplitOn(char separator) { throw null; }
public SplitOnResult SplitOn(char separator, System.StringComparison comparisonType) { throw null; }
public SplitOnResult SplitOn(System.Text.Rune separator) { throw null; }
public SplitOnResult SplitOn(System.Text.Rune separator, System.StringComparison comparisonType) { throw null; }
public SplitOnResult SplitOn(System.Utf8String separator) { throw null; }
public SplitOnResult SplitOn(System.Utf8String separator, System.StringComparison comparisonType) { throw null; }
public SplitOnResult SplitOnLast(char separator) { throw null; }
public SplitOnResult SplitOnLast(char separator, System.StringComparison comparisonType) { throw null; }
public SplitOnResult SplitOnLast(System.Text.Rune separator) { throw null; }
public SplitOnResult SplitOnLast(System.Text.Rune separator, System.StringComparison comparisonType) { throw null; }
public SplitOnResult SplitOnLast(System.Utf8String separator) { throw null; }
public SplitOnResult SplitOnLast(System.Utf8String separator, System.StringComparison comparisonType) { throw null; }
public bool StartsWith(char value) { throw null; }
public bool StartsWith(char value, System.StringComparison comparison) { throw null; }
public bool StartsWith(System.Text.Rune value) { throw null; }
public bool StartsWith(System.Text.Rune value, System.StringComparison comparison) { throw null; }
public bool StartsWith(System.Utf8String value) { throw null; }
public bool StartsWith(System.Utf8String value, System.StringComparison comparison) { throw null; }
public System.Utf8String this[System.Range range] { get { throw null; } }
public byte[] ToByteArray() { throw null; }
public char[] ToCharArray() { throw null; }
public System.Utf8String ToLower(System.Globalization.CultureInfo culture) { throw null; }
public System.Utf8String ToLowerInvariant() { throw null; }
public override string ToString() { throw null; }
public System.Utf8String ToUpper(System.Globalization.CultureInfo culture) { throw null; }
public System.Utf8String ToUpperInvariant() { throw null; }
public System.Utf8String Trim() { throw null; }
public System.Utf8String TrimEnd() { throw null; }
public System.Utf8String TrimStart() { throw null; }
public static bool TryCreateFrom(System.ReadOnlySpan<byte> buffer, [System.Diagnostics.CodeAnalysis.NotNullWhenAttribute(true)] out System.Utf8String? value) { throw null; }
public static bool TryCreateFrom(System.ReadOnlySpan<char> buffer, [System.Diagnostics.CodeAnalysis.NotNullWhenAttribute(true)] out System.Utf8String? value) { throw null; }
public bool TryFind(char value, out System.Range range) { throw null; }
public bool TryFind(char value, System.StringComparison comparisonType, out System.Range range) { throw null; }
public bool TryFind(System.Text.Rune value, out System.Range range) { throw null; }
public bool TryFind(System.Text.Rune value, System.StringComparison comparisonType, out System.Range range) { throw null; }
public bool TryFind(System.Utf8String value, out System.Range range) { throw null; }
public bool TryFind(System.Utf8String value, System.StringComparison comparisonType, out System.Range range) { throw null; }
public bool TryFindLast(char value, out System.Range range) { throw null; }
public bool TryFindLast(char value, System.StringComparison comparisonType, out System.Range range) { throw null; }
public bool TryFindLast(System.Text.Rune value, out System.Range range) { throw null; }
public bool TryFindLast(System.Text.Rune value, System.StringComparison comparisonType, out System.Range range) { throw null; }
public bool TryFindLast(System.Utf8String value, out System.Range range) { throw null; }
public bool TryFindLast(System.Utf8String value, System.StringComparison comparisonType, out System.Range range) { throw null; }
public static System.Utf8String UnsafeCreateWithoutValidation(System.ReadOnlySpan<byte> utf8Contents) { throw null; }
public static System.Utf8String UnsafeCreateWithoutValidation<TState>(int length, TState state, System.Buffers.SpanAction<byte, TState> action) { throw null; }
public readonly partial struct ByteEnumerable : System.Collections.Generic.IEnumerable<byte>
{
private readonly object _dummy;
public Enumerator GetEnumerator() { throw null; }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; }
System.Collections.Generic.IEnumerator<byte> System.Collections.Generic.IEnumerable<byte>.GetEnumerator() { throw null; }
public struct Enumerator : System.Collections.Generic.IEnumerator<byte>
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
public byte Current { get { throw null; } }
public bool MoveNext() { throw null; }
void System.IDisposable.Dispose() { }
object System.Collections.IEnumerator.Current { get { throw null; } }
void System.Collections.IEnumerator.Reset() { }
}
}
public readonly partial struct CharEnumerable : System.Collections.Generic.IEnumerable<char>
{
private readonly object _dummy;
public Enumerator GetEnumerator() { throw null; }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; }
System.Collections.Generic.IEnumerator<char> System.Collections.Generic.IEnumerable<char>.GetEnumerator() { throw null; }
public struct Enumerator : System.Collections.Generic.IEnumerator<char>
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
public char Current { get { throw null; } }
public bool MoveNext() { throw null; }
void System.IDisposable.Dispose() { }
object System.Collections.IEnumerator.Current { get { throw null; } }
void System.Collections.IEnumerator.Reset() { }
}
}
public readonly partial struct RuneEnumerable : System.Collections.Generic.IEnumerable<System.Text.Rune>
{
private readonly object _dummy;
public Enumerator GetEnumerator() { throw null; }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; }
System.Collections.Generic.IEnumerator<System.Text.Rune> System.Collections.Generic.IEnumerable<System.Text.Rune>.GetEnumerator() { throw null; }
public struct Enumerator : System.Collections.Generic.IEnumerator<System.Text.Rune>
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
public System.Text.Rune Current { get { throw null; } }
public bool MoveNext() { throw null; }
void System.IDisposable.Dispose() { }
object System.Collections.IEnumerator.Current { get { throw null; } }
void System.Collections.IEnumerator.Reset() { }
}
}
public readonly struct SplitResult : System.Collections.Generic.IEnumerable<Utf8String?>
{
private readonly object _dummy;
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Deconstruct(out System.Utf8String? item1, out System.Utf8String? item2) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Deconstruct(out System.Utf8String? item1, out System.Utf8String? item2, out System.Utf8String? item3) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Deconstruct(out System.Utf8String? item1, out System.Utf8String? item2, out System.Utf8String? item3, out System.Utf8String? item4) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Deconstruct(out System.Utf8String? item1, out System.Utf8String? item2, out System.Utf8String? item3, out System.Utf8String? item4, out System.Utf8String? item5) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Deconstruct(out System.Utf8String? item1, out System.Utf8String? item2, out System.Utf8String? item3, out System.Utf8String? item4, out System.Utf8String? item5, out System.Utf8String? item6) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Deconstruct(out System.Utf8String? item1, out System.Utf8String? item2, out System.Utf8String? item3, out System.Utf8String? item4, out System.Utf8String? item5, out System.Utf8String? item6, out System.Utf8String? item7) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Deconstruct(out System.Utf8String? item1, out System.Utf8String? item2, out System.Utf8String? item3, out System.Utf8String? item4, out System.Utf8String? item5, out System.Utf8String? item6, out System.Utf8String? item7, out System.Utf8String? item8) { throw null; }
public Enumerator GetEnumerator() { throw null; }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; }
System.Collections.Generic.IEnumerator<System.Utf8String?> System.Collections.Generic.IEnumerable<System.Utf8String?>.GetEnumerator() { throw null; }
public struct Enumerator : System.Collections.Generic.IEnumerator<System.Utf8String?>
{
private readonly object _dummy;
public System.Utf8String? Current { get { throw null; } }
public bool MoveNext() { throw null; }
void System.IDisposable.Dispose() { }
object? System.Collections.IEnumerator.Current { get { throw null; } }
void System.Collections.IEnumerator.Reset() { throw null; }
}
}
public readonly struct SplitOnResult
{
private readonly object _dummy;
public System.Utf8String? After { get { throw null; } }
public System.Utf8String Before { get { throw null; } }
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public void Deconstruct(out System.Utf8String before, out System.Utf8String? after) { throw null; }
}
}
[System.FlagsAttribute]
public enum Utf8StringSplitOptions
{
None = 0,
RemoveEmptyEntries = 1,
TrimEntries = 2
}
}
namespace System.Net.Http
{
public sealed partial class Utf8StringContent : System.Net.Http.HttpContent
{
public Utf8StringContent(System.Utf8String content) { }
public Utf8StringContent(System.Utf8String content, string? mediaType) { }
protected override System.Threading.Tasks.Task<System.IO.Stream> CreateContentReadStreamAsync() { throw null; }
protected override System.Threading.Tasks.Task SerializeToStreamAsync(System.IO.Stream stream, System.Net.TransportContext? context) { throw null; }
protected override bool TryComputeLength(out long length) { throw null; }
}
}
namespace System.Text
{
public readonly ref partial struct Utf8Span
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
public Utf8Span(System.Utf8String? value) { throw null; }
public System.ReadOnlySpan<byte> Bytes { get { throw null; } }
public CharEnumerable Chars { get { throw null; } }
public static System.Text.Utf8Span Empty { get { throw null; } }
public bool IsEmpty { get { throw null; } }
public int Length { get { throw null; } }
public RuneEnumerable Runes { get { throw null; } }
public int CompareTo(System.Text.Utf8Span other) { throw null; }
public int CompareTo(System.Text.Utf8Span other, System.StringComparison comparison) { throw null; }
public bool Contains(char value) { throw null; }
public bool Contains(char value, System.StringComparison comparison) { throw null; }
public bool Contains(System.Text.Rune value) { throw null; }
public bool Contains(System.Text.Rune value, System.StringComparison comparison) { throw null; }
public bool Contains(System.Text.Utf8Span value) { throw null; }
public bool Contains(System.Text.Utf8Span value, System.StringComparison comparison) { throw null; }
public bool EndsWith(char value) { throw null; }
public bool EndsWith(char value, System.StringComparison comparison) { throw null; }
public bool EndsWith(System.Text.Rune value) { throw null; }
public bool EndsWith(System.Text.Rune value, System.StringComparison comparison) { throw null; }
public bool EndsWith(System.Text.Utf8Span value) { throw null; }
public bool EndsWith(System.Text.Utf8Span value, System.StringComparison comparison) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
[System.ObsoleteAttribute("Equals(object) on Utf8Span will always throw an exception. Use Equals(Utf8Span) or == instead.")]
public override bool Equals(object? obj) { throw null; }
public bool Equals(System.Text.Utf8Span other) { throw null; }
public bool Equals(System.Text.Utf8Span other, System.StringComparison comparison) { throw null; }
public static bool Equals(System.Text.Utf8Span left, System.Text.Utf8Span right) { throw null; }
public static bool Equals(System.Text.Utf8Span left, System.Text.Utf8Span right, System.StringComparison comparison) { throw null; }
public override int GetHashCode() { throw null; }
public int GetHashCode(System.StringComparison comparison) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public ref readonly byte GetPinnableReference() { throw null; }
public bool IsAscii() { throw null; }
public bool IsEmptyOrWhiteSpace() { throw null; }
public bool IsNormalized(System.Text.NormalizationForm normalizationForm = System.Text.NormalizationForm.FormC) { throw null; }
public System.Utf8String Normalize(System.Text.NormalizationForm normalizationForm = System.Text.NormalizationForm.FormC) { throw null; }
public int Normalize(System.Span<byte> destination, System.Text.NormalizationForm normalizationForm = System.Text.NormalizationForm.FormC) { throw null; }
public static bool operator !=(System.Text.Utf8Span left, System.Text.Utf8Span right) { throw null; }
public static bool operator ==(System.Text.Utf8Span left, System.Text.Utf8Span right) { throw null; }
public System.Text.Utf8Span this[System.Range range] { get { throw null; } }
public SplitResult Split(char separator, System.Utf8StringSplitOptions options = System.Utf8StringSplitOptions.None) { throw null; }
public SplitResult Split(System.Text.Rune separator, System.Utf8StringSplitOptions options = System.Utf8StringSplitOptions.None) { throw null; }
public SplitResult Split(System.Text.Utf8Span separator, System.Utf8StringSplitOptions options = System.Utf8StringSplitOptions.None) { throw null; }
public SplitOnResult SplitOn(char separator) { throw null; }
public SplitOnResult SplitOn(char separator, System.StringComparison comparisonType) { throw null; }
public SplitOnResult SplitOn(System.Text.Rune separator) { throw null; }
public SplitOnResult SplitOn(System.Text.Rune separator, System.StringComparison comparisonType) { throw null; }
public SplitOnResult SplitOn(System.Text.Utf8Span separator) { throw null; }
public SplitOnResult SplitOn(System.Text.Utf8Span separator, System.StringComparison comparisonType) { throw null; }
public SplitOnResult SplitOnLast(char separator) { throw null; }
public SplitOnResult SplitOnLast(char separator, System.StringComparison comparisonType) { throw null; }
public SplitOnResult SplitOnLast(System.Text.Rune separator) { throw null; }
public SplitOnResult SplitOnLast(System.Text.Rune separator, System.StringComparison comparisonType) { throw null; }
public SplitOnResult SplitOnLast(System.Text.Utf8Span separator) { throw null; }
public SplitOnResult SplitOnLast(System.Text.Utf8Span separator, System.StringComparison comparisonType) { throw null; }
public bool StartsWith(char value) { throw null; }
public bool StartsWith(char value, System.StringComparison comparison) { throw null; }
public bool StartsWith(System.Text.Rune value) { throw null; }
public bool StartsWith(System.Text.Rune value, System.StringComparison comparison) { throw null; }
public bool StartsWith(System.Text.Utf8Span value) { throw null; }
public bool StartsWith(System.Text.Utf8Span value, System.StringComparison comparison) { throw null; }
public System.Text.Utf8Span Trim() { throw null; }
public System.Text.Utf8Span TrimEnd() { throw null; }
public System.Text.Utf8Span TrimStart() { throw null; }
public byte[] ToByteArray() { throw null; }
public char[] ToCharArray() { throw null; }
public int ToChars(System.Span<char> destination) { throw null; }
public System.Utf8String ToLower(System.Globalization.CultureInfo culture) { throw null; }
public int ToLower(System.Span<byte> destination, System.Globalization.CultureInfo culture) { throw null; }
public System.Utf8String ToLowerInvariant() { throw null; }
public int ToLowerInvariant(System.Span<byte> destination) { throw null; }
public override string ToString() { throw null; }
public System.Utf8String ToUpper(System.Globalization.CultureInfo culture) { throw null; }
public int ToUpper(System.Span<byte> destination, System.Globalization.CultureInfo culture) { throw null; }
public System.Utf8String ToUpperInvariant() { throw null; }
public int ToUpperInvariant(System.Span<byte> destination) { throw null; }
public System.Utf8String ToUtf8String() { throw null; }
public bool TryFind(char value, out System.Range range) { throw null; }
public bool TryFind(char value, System.StringComparison comparisonType, out System.Range range) { throw null; }
public bool TryFind(System.Text.Rune value, out System.Range range) { throw null; }
public bool TryFind(System.Text.Rune value, System.StringComparison comparisonType, out System.Range range) { throw null; }
public bool TryFind(System.Text.Utf8Span value, out System.Range range) { throw null; }
public bool TryFind(System.Text.Utf8Span value, System.StringComparison comparisonType, out System.Range range) { throw null; }
public bool TryFindLast(char value, out System.Range range) { throw null; }
public bool TryFindLast(char value, System.StringComparison comparisonType, out System.Range range) { throw null; }
public bool TryFindLast(System.Text.Rune value, out System.Range range) { throw null; }
public bool TryFindLast(System.Text.Rune value, System.StringComparison comparisonType, out System.Range range) { throw null; }
public bool TryFindLast(System.Text.Utf8Span value, out System.Range range) { throw null; }
public bool TryFindLast(System.Text.Utf8Span value, System.StringComparison comparisonType, out System.Range range) { throw null; }
public static System.Text.Utf8Span UnsafeCreateWithoutValidation(System.ReadOnlySpan<byte> buffer) { throw null; }
public readonly ref struct CharEnumerable
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
public Enumerator GetEnumerator() { throw null; }
public ref struct Enumerator
{
private object _dummy;
private int _dummyPrimitive;
public char Current { get { throw null; } }
public bool MoveNext() { throw null; }
}
}
public readonly ref struct RuneEnumerable
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
public Enumerator GetEnumerator() { throw null; }
public ref struct Enumerator
{
private object _dummy;
private int _dummyPrimitive;
public System.Text.Rune Current { get { throw null; } }
public bool MoveNext() { throw null; }
}
}
public readonly ref struct SplitResult
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Deconstruct(out System.Text.Utf8Span item1, out System.Text.Utf8Span item2) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Deconstruct(out System.Text.Utf8Span item1, out System.Text.Utf8Span item2, out System.Text.Utf8Span item3) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Deconstruct(out System.Text.Utf8Span item1, out System.Text.Utf8Span item2, out System.Text.Utf8Span item3, out System.Text.Utf8Span item4) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Deconstruct(out System.Text.Utf8Span item1, out System.Text.Utf8Span item2, out System.Text.Utf8Span item3, out System.Text.Utf8Span item4, out System.Text.Utf8Span item5) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Deconstruct(out System.Text.Utf8Span item1, out System.Text.Utf8Span item2, out System.Text.Utf8Span item3, out System.Text.Utf8Span item4, out System.Text.Utf8Span item5, out System.Text.Utf8Span item6) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Deconstruct(out System.Text.Utf8Span item1, out System.Text.Utf8Span item2, out System.Text.Utf8Span item3, out System.Text.Utf8Span item4, out System.Text.Utf8Span item5, out System.Text.Utf8Span item6, out System.Text.Utf8Span item7) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Deconstruct(out System.Text.Utf8Span item1, out System.Text.Utf8Span item2, out System.Text.Utf8Span item3, out System.Text.Utf8Span item4, out System.Text.Utf8Span item5, out System.Text.Utf8Span item6, out System.Text.Utf8Span item7, out System.Text.Utf8Span item8) { throw null; }
public Enumerator GetEnumerator() { throw null; }
public ref struct Enumerator
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
public System.Text.Utf8Span Current { get { throw null; } }
public bool MoveNext() { throw null; }
}
}
public readonly ref struct SplitOnResult
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
public Utf8Span After { get { throw null; } }
public Utf8Span Before { get { throw null; } }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Deconstruct(out System.Text.Utf8Span before, out System.Text.Utf8Span after) { throw null; }
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using NUnit.Framework;
using LoreSoft.MathExpressions;
namespace LoreSoft.MathExpressions.Tests
{
[TestFixture]
public class MathEvaluatorTest
{
private MathEvaluator eval;
[SetUp]
public void Setup()
{
eval = new MathEvaluator();
}
[TearDown]
public void TearDown()
{
//TODO: NUnit TearDown
}
[Test]
public void EvaluateNegative()
{
double expected = 2d + -1d;
double result = eval.Evaluate("2 + -1");
Assert.AreEqual(expected, result);
expected = -2d + 1d;
result = eval.Evaluate("-2 + 1");
Assert.AreEqual(expected, result);
expected = (2d + -1d) * (-1d + 2d);
result = eval.Evaluate("(2 + -1) * (-1 + 2)");
Assert.AreEqual(expected, result);
// this failed due to a bug in parsing whereby the minus sign was erroneously mistaken for a negative sign.
// which left the -4 on the calculationStack at the end of evaluation.
expected = (-4 - 3) * 5;
result = eval.Evaluate("(-4-3) *5");
Assert.AreEqual(expected, result);
}
[Test]
public void EvaluateLog10()
{
double result = eval.Evaluate("log10(10)");
Assert.AreEqual(1d, result);
}
[Test]
public void EvaluateSimple()
{
double expected = (2d + 1d) * (1d + 2d);
double result = eval.Evaluate("(2 + 1) * (1 + 2)");
Assert.AreEqual(expected, result);
expected = 2d + 1d * 1d + 2d;
result = eval.Evaluate("2 + 1 * 1 + 2");
Assert.AreEqual(expected, result);
expected = 1d / 2d;
result = eval.Evaluate("1/2");
Assert.AreEqual(expected, result);
}
[Test]
public void EvaluateComplex()
{
double expected = ((1d + 2d) + 3d) * 2d - 8d / 4d;
double result = eval.Evaluate("((1 + 2) + 3) * 2 - 8 / 4");
Assert.AreEqual(expected, result);
expected = 3d + 4d / 5d - 8d;
result = eval.Evaluate("3+4/5-8");
Assert.AreEqual(expected, result);
expected = Math.Pow(1, 2) + 5 * 1 + 14;
result = eval.Evaluate("1 ^ 2 + 5 * 1 + 14");
Assert.AreEqual(expected, result);
}
[Test]
public void EvaluateComplexPower()
{
double expected = Math.Pow(1, 2) + 5 * 1 + 14;
double result = eval.Evaluate("pow(1,2) + 5 * 1 + 14");
Assert.AreEqual(expected, result);
}
[Test]
public void EvaluateFunctionSin()
{
double expected = Math.Sin(45);
double result = eval.Evaluate("sin(45)");
Assert.AreEqual(expected, result);
}
[Test]
public void EvaluateFunctionSinMath()
{
double expected = Math.Sin(45) + 45;
double result = eval.Evaluate("sin(45) + 45");
Assert.AreEqual(expected, result);
}
[Test]
public void EvaluateFunctionPow()
{
double expected = Math.Pow(45, 2);
double result = eval.Evaluate("pow(45, 2)");
Assert.AreEqual(expected, result);
}
[Test]
public void EvaluateFunctionMin()
{
double expected = Math.Min(45, 50);
double result = eval.Evaluate("min(45, 50)");
Assert.AreEqual(expected, result);
}
[Test]
public void EvaluateFunctionRound()
{
double expected = Math.Round(1.23456789, 4);
double result = eval.Evaluate("round(1.23456789, 4)");
Assert.AreEqual(expected, result);
}
[Test]
public void EvaluateFunctionMinMath()
{
double expected = Math.Min(45, 50) + 45;
double result = eval.Evaluate("min(45, 50) + 45");
Assert.AreEqual(expected, result);
}
[Test]
public void EvaluateFunctionMinNested()
{
double expected = Math.Min(3, Math.Min(45, 50));
double result = eval.Evaluate("min(3, min(45,50))");
Assert.AreEqual(expected, result);
}
[Test]
public void EvaluateFunctionMinWithEmbeddedParenthesis()
{
double expected = Math.Min(3, (45 + 50));
double result = eval.Evaluate("min(3, (45+50))");
Assert.AreEqual(expected, result);
}
[Test, Ignore]
public void EvaluateFunctionMinWithinParenthesis()
{
// this should work... but doesnt.
double expected = (3 * Math.Min(45, 50));
double result = eval.Evaluate("(3 * Min(45,50))");
Assert.AreEqual(expected, result);
}
[Test]
public void EvaluateFunctionMax()
{
double expected = Math.Max(45, 50);
double result = eval.Evaluate("max(45, 50)");
Assert.AreEqual(expected, result);
}
[Test]
public void EvaluateFunctionMaxNested()
{
double expected = Math.Max(3, Math.Max(45, 50));
double result = eval.Evaluate("max(3, max(45,50))");
Assert.AreEqual(expected, result);
}
[TestCase("2*45,")]
[TestCase("min(,2,3)")]
[TestCase("sin(3,)")]
[TestCase("min(min(3,4),,4)")]
[TestCase("min((1,2))")]
[ExpectedException(typeof(ParseException))]
public void EvaluateMisplacedComma(string expr)
{
eval.Evaluate(expr);
}
[Test, ExpectedException(typeof(ParseException))]
public void EvaluateFunctionHasTooManyArguments()
{
// This will result in 4 things being added to expression queue, when only 2 are expected by max function
eval.Evaluate("max(1,2,3,4)");
}
[Test]
public void EvaluateFunctionMaxMath()
{
double expected = Math.Max(45, 50) + 45;
double result = eval.Evaluate("max(45, 50) + 45");
Assert.AreEqual(expected, result);
}
[Test]
public void EvaluateFunctionSinComplex()
{
double expected = 10 * Math.Sin(35 + 10) + 10;
double result = eval.Evaluate("10 * sin(35 + 10) + 10");
Assert.AreEqual(expected, result);
expected = 10 * Math.Sin(35 + 10) / Math.Sin(2); ;
result = eval.Evaluate("10 * sin(35 + 10) / sin(2)");
Assert.AreEqual(expected, result);
}
[Test]
public void EvaluateVariableComplex()
{
int i = 10;
eval.Variables.Add("i", i);
double expected = Math.Pow(i, 2) + 5 * i + 14;
double result = eval.Evaluate("i^2+5*i+14");
Assert.AreEqual(expected, result);
}
[Test]
public void EvaluateVariableLoop()
{
eval.Variables.Add("i", 0);
double expected = 0;
double result = 0;
for (int i = 1; i < 100000; i++)
{
eval.Variables["i"] = i;
expected += Math.Pow(i, 2) + 5 * i + 14;
result += eval.Evaluate("i^2+5*i+14");
}
Assert.AreEqual(expected, result);
}
[Test]
public void EvaluateConvert()
{
double expected = 12;
double result = eval.Evaluate("1 [ft->in]");
Assert.AreEqual(expected, result);
expected = 12;
result = eval.Evaluate("1 [ft -> in]");
Assert.AreEqual(expected, result);
}
[Test]
[Ignore]
public void EvaluateFunctionOverFunction()
{
double expected = Math.Sin(5) / Math.Sin(2);
double result;
result = eval.Evaluate("(sin(5)) / (sin(2))");
Assert.AreEqual(expected, result);
result = eval.Evaluate("sin(5) / sin(2)");
Assert.AreEqual(expected, result);
}
class MultiplyBy10Expr : IExpression
{
public int ArgumentCount
{
get
{
return 1;
}
}
private double Test(double[] numbers)
{
return 10*numbers[0];
}
public MathEvaluate Evaluate
{
get { return Test; }
set
{
throw new NotImplementedException();
}
}
}
[TestCase("MB10(5)", 50d)]
[TestCase("(MB10(5))", 50d)]
[TestCase("MB10(5) + 10", 60d)]
[TestCase("MB10(MB10(5))", 500d)]
public void EvaluateCustomUnaryFunction(string expr, double expected)
{
eval.RegisterFunction("MB10", new MultiplyBy10Expr());
double result = eval.Evaluate(expr);
Assert.AreEqual(expected, result);
}
class AddThreeNumbers : IExpression
{
public int ArgumentCount
{
get
{
return 3;
}
}
private double AddThem(double[] numbers)
{
return numbers[0] + numbers[1] + numbers[2];
}
public MathEvaluate Evaluate
{
get { return AddThem; }
set
{
throw new NotImplementedException();
}
}
}
[Test]
public void EvaluateCustomTernaryFunction()
{
eval.RegisterFunction("A3", new AddThreeNumbers());
double result = eval.Evaluate("A3(1,2,3)");
Assert.AreEqual(6d, 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.Diagnostics;
using System.Globalization;
using System.IO;
namespace System.Net.NetworkInformation
{
internal static partial class StringParsingHelpers
{
private static readonly string[] s_newLineSeparator = new string[] { Environment.NewLine }; // Used for string splitting
internal static int ParseNumSocketConnections(string filePath, string protocolName)
{
if (!File.Exists(filePath))
{
throw new PlatformNotSupportedException(SR.net_InformationUnavailableOnPlatform);
}
// Parse the number of active connections out of /proc/net/sockstat
string sockstatFile = File.ReadAllText(filePath);
int indexOfTcp = sockstatFile.IndexOf(protocolName, StringComparison.Ordinal);
int endOfTcpLine = sockstatFile.IndexOf(Environment.NewLine, indexOfTcp + 1, StringComparison.Ordinal);
string tcpLineData = sockstatFile.Substring(indexOfTcp, endOfTcpLine - indexOfTcp);
StringParser sockstatParser = new StringParser(tcpLineData, ' ');
sockstatParser.MoveNextOrFail(); // Skip "<name>:"
sockstatParser.MoveNextOrFail(); // Skip: "inuse"
return sockstatParser.ParseNextInt32();
}
internal static TcpConnectionInformation[] ParseActiveTcpConnectionsFromFiles(string tcp4ConnectionsFile, string tcp6ConnectionsFile)
{
if (!File.Exists(tcp4ConnectionsFile) || !File.Exists(tcp6ConnectionsFile))
{
throw new PlatformNotSupportedException(SR.net_InformationUnavailableOnPlatform);
}
string tcp4FileContents = File.ReadAllText(tcp4ConnectionsFile);
string[] v4connections = tcp4FileContents.Split(s_newLineSeparator, StringSplitOptions.RemoveEmptyEntries);
string tcp6FileContents = File.ReadAllText(tcp6ConnectionsFile);
string[] v6connections = tcp6FileContents.Split(s_newLineSeparator, StringSplitOptions.RemoveEmptyEntries);
// First line is header in each file.
TcpConnectionInformation[] connections = new TcpConnectionInformation[v4connections.Length + v6connections.Length - 2];
int index = 0;
// TCP Connections
for (int i = 1; i < v4connections.Length; i++) // Skip first line header.
{
string line = v4connections[i];
connections[index++] = ParseTcpConnectionInformationFromLine(line);
}
// TCP6 Connections
for (int i = 1; i < v6connections.Length; i++) // Skip first line header.
{
string line = v6connections[i];
connections[index++] = ParseTcpConnectionInformationFromLine(line);
}
return connections;
}
internal static IPEndPoint[] ParseActiveTcpListenersFromFiles(string tcp4ConnectionsFile, string tcp6ConnectionsFile)
{
if (!File.Exists(tcp4ConnectionsFile) || !File.Exists(tcp6ConnectionsFile))
{
throw new PlatformNotSupportedException(SR.net_InformationUnavailableOnPlatform);
}
string tcp4FileContents = File.ReadAllText(tcp4ConnectionsFile);
string[] v4connections = tcp4FileContents.Split(s_newLineSeparator, StringSplitOptions.RemoveEmptyEntries);
string tcp6FileContents = File.ReadAllText(tcp6ConnectionsFile);
string[] v6connections = tcp6FileContents.Split(s_newLineSeparator, StringSplitOptions.RemoveEmptyEntries);
/// First line is header in each file.
IPEndPoint[] endPoints = new IPEndPoint[v4connections.Length + v6connections.Length - 2];
int index = 0;
// TCP Connections
for (int i = 1; i < v4connections.Length; i++) // Skip first line header.
{
string line = v4connections[i];
IPEndPoint endPoint = ParseLocalConnectionInformation(line);
endPoints[index++] = endPoint;
}
// TCP6 Connections
for (int i = 1; i < v6connections.Length; i++) // Skip first line header.
{
string line = v6connections[i];
IPEndPoint endPoint = ParseLocalConnectionInformation(line);
endPoints[index++] = endPoint;
}
return endPoints;
}
public static IPEndPoint[] ParseActiveUdpListenersFromFiles(string udp4File, string udp6File)
{
if (!File.Exists(udp4File) || !File.Exists(udp6File))
{
throw new PlatformNotSupportedException(SR.net_InformationUnavailableOnPlatform);
}
string udp4FileContents = File.ReadAllText(udp4File);
string[] v4connections = udp4FileContents.Split(s_newLineSeparator, StringSplitOptions.RemoveEmptyEntries);
string udp6FileContents = File.ReadAllText(udp6File);
string[] v6connections = udp6FileContents.Split(s_newLineSeparator, StringSplitOptions.RemoveEmptyEntries);
// First line is header in each file.
IPEndPoint[] endPoints = new IPEndPoint[v4connections.Length + v6connections.Length - 2];
int index = 0;
// UDP Connections
for (int i = 1; i < v4connections.Length; i++) // Skip first line header.
{
string line = v4connections[i];
IPEndPoint endPoint = ParseLocalConnectionInformation(line);
endPoints[index++] = endPoint;
}
// UDP6 Connections
for (int i = 1; i < v6connections.Length; i++) // Skip first line header.
{
string line = v6connections[i];
IPEndPoint endPoint = ParseLocalConnectionInformation(line);
endPoints[index++] = endPoint;
}
return endPoints;
}
// Parsing logic for local and remote addresses and ports, as well as socket state.
internal static TcpConnectionInformation ParseTcpConnectionInformationFromLine(string line)
{
StringParser parser = new StringParser(line, ' ', true);
parser.MoveNextOrFail(); // skip Index
string localAddressAndPort = parser.MoveAndExtractNext(); // local_address
IPEndPoint localEndPoint = ParseAddressAndPort(localAddressAndPort);
string remoteAddressAndPort = parser.MoveAndExtractNext(); // rem_address
IPEndPoint remoteEndPoint = ParseAddressAndPort(remoteAddressAndPort);
string socketStateHex = parser.MoveAndExtractNext();
int nativeTcpState;
if (!int.TryParse(socketStateHex, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out nativeTcpState))
{
throw ExceptionHelper.CreateForParseFailure();
}
TcpState tcpState = MapTcpState(nativeTcpState);
return new SimpleTcpConnectionInformation(localEndPoint, remoteEndPoint, tcpState);
}
// Common parsing logic for the local connection information.
private static IPEndPoint ParseLocalConnectionInformation(string line)
{
StringParser parser = new StringParser(line, ' ', true);
parser.MoveNextOrFail(); // skip Index
string localAddressAndPort = parser.MoveAndExtractNext();
int indexOfColon = localAddressAndPort.IndexOf(':');
if (indexOfColon == -1)
{
throw ExceptionHelper.CreateForParseFailure();
}
string remoteAddressString = localAddressAndPort.Substring(0, indexOfColon);
IPAddress localIPAddress = ParseHexIPAddress(remoteAddressString);
string portString = localAddressAndPort.Substring(indexOfColon + 1, localAddressAndPort.Length - (indexOfColon + 1));
int localPort;
if (!int.TryParse(portString, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out localPort))
{
throw ExceptionHelper.CreateForParseFailure();
}
return new IPEndPoint(localIPAddress, localPort);
}
private static IPEndPoint ParseAddressAndPort(string colonSeparatedAddress)
{
int indexOfColon = colonSeparatedAddress.IndexOf(':');
if (indexOfColon == -1)
{
throw ExceptionHelper.CreateForParseFailure();
}
string remoteAddressString = colonSeparatedAddress.Substring(0, indexOfColon);
IPAddress ipAddress = ParseHexIPAddress(remoteAddressString);
string portString = colonSeparatedAddress.Substring(indexOfColon + 1, colonSeparatedAddress.Length - (indexOfColon + 1));
int port;
if (!int.TryParse(portString, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out port))
{
throw ExceptionHelper.CreateForParseFailure();
}
return new IPEndPoint(ipAddress, port);
}
// Maps from Linux TCP states to .NET TcpStates.
private static TcpState MapTcpState(int state)
{
return Interop.Sys.MapTcpState((int)state);
}
internal static IPAddress ParseHexIPAddress(string remoteAddressString)
{
if (remoteAddressString.Length <= 8) // IPv4 Address
{
return ParseIPv4HexString(remoteAddressString);
}
else if (remoteAddressString.Length == 32) // IPv6 Address
{
return ParseIPv6HexString(remoteAddressString);
}
else
{
throw ExceptionHelper.CreateForParseFailure();
}
}
// Simply converst the hex string into a long and uses the IPAddress(long) constructor.
// Strings passed to this method must be 8 or less characters in length (32-bit address).
private static IPAddress ParseIPv4HexString(string hexAddress)
{
IPAddress ipAddress;
long addressValue;
if (!long.TryParse(hexAddress, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out addressValue))
{
throw ExceptionHelper.CreateForParseFailure();
}
ipAddress = new IPAddress(addressValue);
return ipAddress;
}
// Parses a 128-bit IPv6 Address stored as a 32-character hex number.
// Strings passed to this must be 32 characters in length.
private static IPAddress ParseIPv6HexString(string hexAddress)
{
Debug.Assert(hexAddress.Length == 32);
byte[] addressBytes = new byte[16];
for (int i = 0; i < 16; i++)
{
addressBytes[i] = (byte)(HexToByte(hexAddress[(i * 2)])
+ HexToByte(hexAddress[(i * 2) + 1]));
}
IPAddress ipAddress = new IPAddress(addressBytes);
return ipAddress;
}
private static byte HexToByte(char val)
{
if (val <= '9' && val >= '0')
{
return (byte)(val - '0');
}
else if (val >= 'a' && val <= 'f')
{
return (byte)((val - 'a') + 10);
}
else if (val >= 'A' && val <= 'F')
{
return (byte)((val - 'A') + 10);
}
else
{
throw ExceptionHelper.CreateForParseFailure();
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
namespace System.Data.SqlClient.SNI
{
/// <summary>
/// SNI MARS connection. Multiple MARS streams will be overlaid on this connection.
/// </summary>
internal class SNIMarsConnection
{
private readonly Guid _connectionId = Guid.NewGuid();
private readonly Dictionary<int, SNIMarsHandle> _sessions = new Dictionary<int, SNIMarsHandle>();
private readonly byte[] _headerBytes = new byte[SNISMUXHeader.HEADER_LENGTH];
private readonly SNISMUXHeader _currentHeader = new SNISMUXHeader();
private SNIHandle _lowerHandle;
private ushort _nextSessionId = 0;
private int _currentHeaderByteCount = 0;
private int _dataBytesLeft = 0;
private SNIPacket _currentPacket;
/// <summary>
/// Connection ID
/// </summary>
public Guid ConnectionId
{
get
{
return _connectionId;
}
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="lowerHandle">Lower handle</param>
public SNIMarsConnection(SNIHandle lowerHandle)
{
_lowerHandle = lowerHandle;
_lowerHandle.SetAsyncCallbacks(HandleReceiveComplete, HandleSendComplete);
}
public SNIMarsHandle CreateMarsSession(object callbackObject, bool async)
{
lock (this)
{
ushort sessionId = _nextSessionId++;
SNIMarsHandle handle = new SNIMarsHandle(this, sessionId, callbackObject, async);
_sessions.Add(sessionId, handle);
return handle;
}
}
/// <summary>
/// Start receiving
/// </summary>
/// <returns></returns>
public uint StartReceive()
{
SNIPacket packet = null;
if (ReceiveAsync(ref packet) == TdsEnums.SNI_SUCCESS_IO_PENDING)
{
return TdsEnums.SNI_SUCCESS_IO_PENDING;
}
return SNICommon.ReportSNIError(SNIProviders.SMUX_PROV, 0, SNICommon.ConnNotUsableError, string.Empty);
}
/// <summary>
/// Send a packet synchronously
/// </summary>
/// <param name="packet">SNI packet</param>
/// <returns>SNI error code</returns>
public uint Send(SNIPacket packet)
{
lock (this)
{
return _lowerHandle.Send(packet);
}
}
/// <summary>
/// Send a packet asynchronously
/// </summary>
/// <param name="packet">SNI packet</param>
/// <param name="callback">Completion callback</param>
/// <returns>SNI error code</returns>
public uint SendAsync(SNIPacket packet, SNIAsyncCallback callback)
{
lock (this)
{
return _lowerHandle.SendAsync(packet, false, callback);
}
}
/// <summary>
/// Receive a packet asynchronously
/// </summary>
/// <param name="packet">SNI packet</param>
/// <returns>SNI error code</returns>
public uint ReceiveAsync(ref SNIPacket packet)
{
if (packet != null)
{
packet.Release();
packet = null;
}
lock (this)
{
return _lowerHandle.ReceiveAsync(ref packet);
}
}
/// <summary>
/// Check SNI handle connection
/// </summary>
/// <returns>SNI error status</returns>
public uint CheckConnection()
{
lock (this)
{
return _lowerHandle.CheckConnection();
}
}
/// <summary>
/// Process a receive error
/// </summary>
public void HandleReceiveError(SNIPacket packet)
{
Debug.Assert(Monitor.IsEntered(this), "HandleReceiveError was called without being locked.");
foreach (SNIMarsHandle handle in _sessions.Values)
{
if (packet.HasCompletionCallback)
{
handle.HandleReceiveError(packet);
}
}
packet?.Release();
}
/// <summary>
/// Process a send completion
/// </summary>
/// <param name="packet">SNI packet</param>
/// <param name="sniErrorCode">SNI error code</param>
public void HandleSendComplete(SNIPacket packet, uint sniErrorCode)
{
packet.InvokeCompletionCallback(sniErrorCode);
}
/// <summary>
/// Process a receive completion
/// </summary>
/// <param name="packet">SNI packet</param>
/// <param name="sniErrorCode">SNI error code</param>
public void HandleReceiveComplete(SNIPacket packet, uint sniErrorCode)
{
SNISMUXHeader currentHeader = null;
SNIPacket currentPacket = null;
SNIMarsHandle currentSession = null;
if (sniErrorCode != TdsEnums.SNI_SUCCESS)
{
lock (this)
{
HandleReceiveError(packet);
return;
}
}
while (true)
{
lock (this)
{
if (_currentHeaderByteCount != SNISMUXHeader.HEADER_LENGTH)
{
currentHeader = null;
currentPacket = null;
currentSession = null;
while (_currentHeaderByteCount != SNISMUXHeader.HEADER_LENGTH)
{
int bytesTaken = packet.TakeData(_headerBytes, _currentHeaderByteCount, SNISMUXHeader.HEADER_LENGTH - _currentHeaderByteCount);
_currentHeaderByteCount += bytesTaken;
if (bytesTaken == 0)
{
sniErrorCode = ReceiveAsync(ref packet);
if (sniErrorCode == TdsEnums.SNI_SUCCESS_IO_PENDING)
{
return;
}
HandleReceiveError(packet);
return;
}
}
_currentHeader.Read(_headerBytes);
_dataBytesLeft = (int)_currentHeader.length;
_currentPacket = new SNIPacket(headerSize: 0, dataSize: (int)_currentHeader.length);
}
currentHeader = _currentHeader;
currentPacket = _currentPacket;
if (_currentHeader.flags == (byte)SNISMUXFlags.SMUX_DATA)
{
if (_dataBytesLeft > 0)
{
int length = packet.TakeData(_currentPacket, _dataBytesLeft);
_dataBytesLeft -= length;
if (_dataBytesLeft > 0)
{
sniErrorCode = ReceiveAsync(ref packet);
if (sniErrorCode == TdsEnums.SNI_SUCCESS_IO_PENDING)
{
return;
}
HandleReceiveError(packet);
return;
}
}
}
_currentHeaderByteCount = 0;
if (!_sessions.ContainsKey(_currentHeader.sessionId))
{
SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.SMUX_PROV, 0, SNICommon.InvalidParameterError, string.Empty);
HandleReceiveError(packet);
_lowerHandle.Dispose();
_lowerHandle = null;
return;
}
if (_currentHeader.flags == (byte)SNISMUXFlags.SMUX_FIN)
{
_sessions.Remove(_currentHeader.sessionId);
}
else
{
currentSession = _sessions[_currentHeader.sessionId];
}
}
if (currentHeader.flags == (byte)SNISMUXFlags.SMUX_DATA)
{
currentSession.HandleReceiveComplete(currentPacket, currentHeader);
}
if (_currentHeader.flags == (byte)SNISMUXFlags.SMUX_ACK)
{
try
{
currentSession.HandleAck(currentHeader.highwater);
}
catch (Exception e)
{
SNICommon.ReportSNIError(SNIProviders.SMUX_PROV, SNICommon.InternalExceptionError, e);
}
}
lock (this)
{
if (packet.DataLeft == 0)
{
sniErrorCode = ReceiveAsync(ref packet);
if (sniErrorCode == TdsEnums.SNI_SUCCESS_IO_PENDING)
{
return;
}
HandleReceiveError(packet);
return;
}
}
}
}
/// <summary>
/// Enable SSL
/// </summary>
public uint EnableSsl(uint options)
{
return _lowerHandle.EnableSsl(options);
}
/// <summary>
/// Disable SSL
/// </summary>
public void DisableSsl()
{
_lowerHandle.DisableSsl();
}
#if DEBUG
/// <summary>
/// Test handle for killing underlying connection
/// </summary>
public void KillConnection()
{
_lowerHandle.KillConnection();
}
#endif
}
}
| |
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Windows.Forms;
using DpSdkEngLib;
using DPSDKOPSLib;
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
using System.Linq;
using System.Xml.Linq;
// ERROR: Not supported in C#: OptionDeclaration
namespace _4PosBackOffice.NET
{
internal partial class frmFilterOrderList : System.Windows.Forms.Form
{
string gField;
string[,] gArray;
bool loading;
string gFieldID;
string gFieldName;
string gHeading;
List<Button> cmdClick = new List<Button>();
private void loadLanguage()
{
//frmFilterOrderList = No caption / No Code / NA?
//TOOLBAR CODE NOT DONE!
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1080;
//Search|Checked
if (modRecordSet.rsLang.RecordCount){_lbl_2.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lbl_2.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsHelp.filter = "Help_Section=0 AND Help_Form='" + this.Name + "'";
//UPGRADE_ISSUE: Form property frmFilterOrderList.ToolTip1 was not upgraded. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="CC4C7EC0-C903-48FC-ACCC-81861D12DA4A"'
if (modRecordSet.rsHelp.RecordCount)
this.ToolTip1 = modRecordSet.rsHelp.Fields("Help_ContextID").Value;
}
private void setup()
{
short x = 0;
loading = true;
lstFilter.Visible = false;
this.lstFilter.Items.Clear();
int m = 0;
switch (this.tbStockItem.Tag) {
case Convert.ToString(1):
for (x = 0; x <= Information.UBound(gArray); x++) {
if (Convert.ToBoolean(gArray[x, 2])) {
if (Strings.InStr(Strings.UCase(gArray[x, 1]), Strings.UCase(this.txtSearch.Text))) {
m = lstFilter.Items.Add(new LBI(gArray[x, 1], x));
lstFilter.SetItemChecked(m, gArray[x, 2]);
}
}
}
break;
case Convert.ToString(2):
for (x = 0; x <= Information.UBound(gArray); x++) {
if (Convert.ToBoolean(gArray[x, 2])) {
} else {
if (Strings.InStr(Strings.UCase(gArray[x, 1]), Strings.UCase(this.txtSearch.Text))) {
m = lstFilter.Items.Add(new LBI(gArray[x, 1], x));
lstFilter.SetItemChecked(m, gArray[x, 2]);
}
}
}
break;
default:
for (x = 0; x <= Information.UBound(gArray); x++) {
if (Strings.InStr(Strings.UCase(gArray[x, 1]), Strings.UCase(this.txtSearch.Text))) {
m = lstFilter.Items.Add(new LBI(gArray[x, 1], x));
lstFilter.SetItemChecked(m, gArray[x, 2]);
}
}
break;
}
if (lstFilter.SelectedIndex)
lstFilter.SelectedIndex = 0;
lstFilter.Visible = true;
loading = false;
}
public bool loadData(ref string lName)
{
bool functionReturnValue = false;
ADODB.Recordset rs = default(ADODB.Recordset);
string lSQL = null;
int x = 0;
string lID = null;
gField = lName;
rs = modRecordSet.getRS(ref "SELECT * From ftConstruct WHERE (ftConstruct_Name = '" + Strings.Replace(lName, "'", "''") + "')");
gFieldID = rs.Fields("ftConstruct_FieldID").Value;
gFieldName = rs.Fields("ftConstruct_FieldName").Value;
gHeading = rs.Fields("ftConstruct_DisplayName").Value;
lSQL = rs.Fields("ftConstruct_SQL").Value;
rs.Close();
rs = modRecordSet.getRS(ref lSQL);
//Display the list of Titles in the DataCombo
loading = true;
functionReturnValue = false;
x = -1;
gArray = new string[rs.RecordCount, 3];
while (!(rs.EOF)) {
x = x + 1;
gArray[x, 0] = rs.Fields(gFieldID).Value;
gArray[x, 1] = rs.Fields(gFieldName).Value + "";
gArray[x, 2] = Convert.ToString(0);
rs.MoveNext();
}
rs.Close();
rs = modRecordSet.getRS(ref "SELECT ftDataItem_ID From ftOrderItem WHERE (ftDataItem_PersonID = " + modRecordSet.gPersonID + ") AND (ftDataItem_FieldName = '" + Strings.Replace(gField, "'", "''") + "')");
while (!(rs.EOF)) {
lID = rs.Fields("ftDataItem_ID").Value;
for (x = 0; x <= Information.UBound(gArray); x++) {
if (lID == gArray[x, 0]) {
gArray[x, 2] = Convert.ToString(1);
}
}
rs.MoveNext();
}
rs.Close();
setup();
functionReturnValue = true;
loadLanguage();
ShowDialog();
loading = false;
return functionReturnValue;
}
private void save()
{
short x = 0;
string lSQL = null;
string lHeading = null;
ADODB.Recordset rs = new ADODB.Recordset();
rs = modRecordSet.cnnDB.Execute("DELETE FROM ftOrderItem WHERE (ftDataItem_PersonID = " + modRecordSet.gPersonID + ") AND (ftDataItem_FieldName = '" + Strings.Replace(gField, "'", "''") + "')");
modRecordSet.cnnDB.Execute("DELETE FROM ftOrder WHERE (ftData_PersonID = " + modRecordSet.gPersonID + ") AND (ftData_FieldName = '" + Strings.Replace(gField, "'", "''") + "')");
for (x = 0; x <= lstFilter.Items.Count - 1; x++) {
if (lstFilter.GetItemChecked(x)) {
lHeading = lHeading + " OR ''" + gArray[GID.GetItemData(ref lstFilter, ref x), 1] + "''";
lSQL = lSQL + " OR [field] = " + gArray[GID.GetItemData(ref lstFilter, ref x), 0];
modRecordSet.cnnDB.Execute("INSERT INTO ftOrderItem (ftDataItem_PersonID, ftDataItem_FieldName, ftDataItem_ID) VALUES (" + modRecordSet.gPersonID + ", '" + Strings.Replace(gField, "'", "''") + "', " + gArray[GID.GetItemData(ref lstFilter, ref x), 0] + ")");
}
}
if (!string.IsNullOrEmpty(lSQL)) {
lSQL = "(" + Strings.Mid(lSQL, 4) + ")";
lHeading = "(" + gHeading + " = " + Strings.Mid(lHeading, 4) + ")";
modRecordSet.cnnDB.Execute("INSERT INTO ftOrder (ftData_PersonID, ftData_FieldName, ftData_SQL, ftData_Heading) VALUES (" + modRecordSet.gPersonID + ", '" + Strings.Replace(gField, "'", "''") + "', '" + Strings.Replace(lSQL, "'", "''") + "', '" + Strings.Replace(lHeading, "'", "''") + "')");
}
}
//Handles cmdClick.Click
private void cmdClick_Click(System.Object eventSender, System.EventArgs eventArgs)
{
Button btn = new Button();
btn = (Button)eventSender;
int Index = GetIndex.GetIndexer(ref btn, ref cmdClick);
tbStockItem_ButtonClick(this.tbStockItem.Items[Index], new System.EventArgs());
lstFilter.Focus();
}
private void frmFilterOrderList_FormClosed(System.Object eventSender, System.Windows.Forms.FormClosedEventArgs eventArgs)
{
save();
}
private void lstFilter_ItemCheck(System.Object eventSender, System.Windows.Forms.ItemCheckEventArgs eventArgs)
{
if (loading)
return;
short x = 0;
x = GID.GetItemData(ref lstFilter, ref lstFilter.SelectedIndex);
if (Convert.ToBoolean(gArray[x, 2]) != lstFilter.GetItemChecked(eventArgs.Index)) {
gArray[x, 2] = Convert.ToString(lstFilter.GetItemChecked(lstFilter.SelectedIndex));
}
}
private void lstFilter_KeyDown(System.Object eventSender, System.Windows.Forms.KeyEventArgs eventArgs)
{
short KeyCode = eventArgs.KeyCode;
short Shift = eventArgs.KeyData / 0x10000;
if (Shift == 4 & KeyCode == 88) {
this.Close();
KeyCode = 0;
}
}
private void lstFilter_KeyPress(System.Object eventSender, System.Windows.Forms.KeyPressEventArgs eventArgs)
{
short KeyAscii = Strings.Asc(eventArgs.KeyChar);
if (KeyAscii == 27) {
this.Close();
KeyAscii = 0;
}
eventArgs.KeyChar = Strings.Chr(KeyAscii);
if (KeyAscii == 0) {
eventArgs.Handled = true;
}
}
private void tbStockItem_ButtonClick(System.Object eventSender, System.EventArgs eventArgs)
{
System.Windows.Forms.ToolStripItem Button = (System.Windows.Forms.ToolStripItem)eventSender;
short x = 0;
if (Button.Name == "clear") {
for (x = 0; x <= lstFilter.Items.Count - 1; x++) {
gArray[x, 2] = Convert.ToString(0);
lstFilter.SetItemChecked(x, gArray[x, 2]);
}
setup();
} else {
for (x = 1; x <= tbStockItem.Items.Count; x++) {
((ToolStripButton)tbStockItem.Items[x]).Checked = false;
}
tbStockItem.Tag = Button.Owner.Items.IndexOf(Button) - 1;
//Button.Checked = True
setup();
}
}
private void txtSearch_Enter(System.Object eventSender, System.EventArgs eventArgs)
{
txtSearch.SelectionStart = 0;
txtSearch.SelectionLength = 9999;
}
private void txtSearch_KeyDown(System.Object eventSender, System.Windows.Forms.KeyEventArgs eventArgs)
{
short KeyCode = eventArgs.KeyCode;
short Shift = eventArgs.KeyData / 0x10000;
if (KeyCode == 40) {
if (lstFilter.Items.Count) {
lstFilter.Focus();
if (lstFilter.SelectedIndex == -1) {
lstFilter.SelectedIndex = 0;
}
}
KeyCode = 0;
}
if (Shift == 4 & KeyCode == 88) {
this.Close();
KeyCode = 0;
}
}
private void txtSearch_KeyPress(System.Object eventSender, System.Windows.Forms.KeyPressEventArgs eventArgs)
{
short KeyAscii = Strings.Asc(eventArgs.KeyChar);
if (KeyAscii == 13) {
setup();
KeyAscii = 0;
}
if (KeyAscii == 27) {
this.Close();
KeyAscii = 0;
}
eventArgs.KeyChar = Strings.Chr(KeyAscii);
if (KeyAscii == 0) {
eventArgs.Handled = true;
}
}
private void frmFilterOrderList_Load(object sender, System.EventArgs e)
{
cmdClick.AddRange(new Button[] {
_cmdClick_1,
_cmdClick_2,
_cmdClick_3,
_cmdClick_4
});
Button bt = new Button();
foreach (Button bt_loopVariable in cmdClick) {
bt = bt_loopVariable;
bt.Click += cmdClick_Click;
}
}
}
}
| |
//
// 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.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.WindowsAzure.Management.SiteRecovery;
using Microsoft.WindowsAzure.Management.SiteRecovery.Models;
namespace Microsoft.WindowsAzure
{
public static partial class RecoveryPlanOperationsExtensions
{
/// <summary>
/// Commit the recovery plan.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.SiteRecovery.IRecoveryPlanOperations.
/// </param>
/// <param name='recoveryPlanId'>
/// Required. RecoveryPlan ID.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// The response model for the Job details object.
/// </returns>
public static JobResponse Commit(this IRecoveryPlanOperations operations, string recoveryPlanId, CustomRequestHeaders customRequestHeaders)
{
return Task.Factory.StartNew((object s) =>
{
return ((IRecoveryPlanOperations)s).CommitAsync(recoveryPlanId, customRequestHeaders);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Commit the recovery plan.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.SiteRecovery.IRecoveryPlanOperations.
/// </param>
/// <param name='recoveryPlanId'>
/// Required. RecoveryPlan ID.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// The response model for the Job details object.
/// </returns>
public static Task<JobResponse> CommitAsync(this IRecoveryPlanOperations operations, string recoveryPlanId, CustomRequestHeaders customRequestHeaders)
{
return operations.CommitAsync(recoveryPlanId, customRequestHeaders, CancellationToken.None);
}
/// <summary>
/// Create the recovery plan.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.SiteRecovery.IRecoveryPlanOperations.
/// </param>
/// <param name='parameters'>
/// Required. Create recovery plan input parameters.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// The response model for the Job details object.
/// </returns>
public static JobResponse CreateRecoveryPlan(this IRecoveryPlanOperations operations, RecoveryPlanXmlData parameters, CustomRequestHeaders customRequestHeaders)
{
return Task.Factory.StartNew((object s) =>
{
return ((IRecoveryPlanOperations)s).CreateRecoveryPlanAsync(parameters, customRequestHeaders);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Create the recovery plan.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.SiteRecovery.IRecoveryPlanOperations.
/// </param>
/// <param name='parameters'>
/// Required. Create recovery plan input parameters.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// The response model for the Job details object.
/// </returns>
public static Task<JobResponse> CreateRecoveryPlanAsync(this IRecoveryPlanOperations operations, RecoveryPlanXmlData parameters, CustomRequestHeaders customRequestHeaders)
{
return operations.CreateRecoveryPlanAsync(parameters, customRequestHeaders, CancellationToken.None);
}
/// <summary>
/// Remove a Recovery Plan from the current Azure Site Recovery Vault.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.SiteRecovery.IRecoveryPlanOperations.
/// </param>
/// <param name='recoveryPlanId'>
/// Required. RecoveryPlan ID.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// The response model for the Job details object.
/// </returns>
public static JobResponse Delete(this IRecoveryPlanOperations operations, string recoveryPlanId, CustomRequestHeaders customRequestHeaders)
{
return Task.Factory.StartNew((object s) =>
{
return ((IRecoveryPlanOperations)s).DeleteAsync(recoveryPlanId, customRequestHeaders);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Remove a Recovery Plan from the current Azure Site Recovery Vault.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.SiteRecovery.IRecoveryPlanOperations.
/// </param>
/// <param name='recoveryPlanId'>
/// Required. RecoveryPlan ID.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// The response model for the Job details object.
/// </returns>
public static Task<JobResponse> DeleteAsync(this IRecoveryPlanOperations operations, string recoveryPlanId, CustomRequestHeaders customRequestHeaders)
{
return operations.DeleteAsync(recoveryPlanId, customRequestHeaders, CancellationToken.None);
}
/// <summary>
/// Get the recovery plan by the ID.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.SiteRecovery.IRecoveryPlanOperations.
/// </param>
/// <param name='recoveryPlanId'>
/// Required. RecoveryPlan ID.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// The response model for the recoveryplan object.
/// </returns>
public static RecoveryPlanResponse Get(this IRecoveryPlanOperations operations, string recoveryPlanId, CustomRequestHeaders customRequestHeaders)
{
return Task.Factory.StartNew((object s) =>
{
return ((IRecoveryPlanOperations)s).GetAsync(recoveryPlanId, customRequestHeaders);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get the recovery plan by the ID.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.SiteRecovery.IRecoveryPlanOperations.
/// </param>
/// <param name='recoveryPlanId'>
/// Required. RecoveryPlan ID.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// The response model for the recoveryplan object.
/// </returns>
public static Task<RecoveryPlanResponse> GetAsync(this IRecoveryPlanOperations operations, string recoveryPlanId, CustomRequestHeaders customRequestHeaders)
{
return operations.GetAsync(recoveryPlanId, customRequestHeaders, CancellationToken.None);
}
/// <summary>
/// Get the recovery plan xml by the ID.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.SiteRecovery.IRecoveryPlanOperations.
/// </param>
/// <param name='recoveryPlanId'>
/// Required. RecoveryPlan ID.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// The xml output for the recoveryplan object.
/// </returns>
public static RecoveryPlanXmlOuput GetRecoveryPlanXml(this IRecoveryPlanOperations operations, string recoveryPlanId, CustomRequestHeaders customRequestHeaders)
{
return Task.Factory.StartNew((object s) =>
{
return ((IRecoveryPlanOperations)s).GetRecoveryPlanXmlAsync(recoveryPlanId, customRequestHeaders);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get the recovery plan xml by the ID.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.SiteRecovery.IRecoveryPlanOperations.
/// </param>
/// <param name='recoveryPlanId'>
/// Required. RecoveryPlan ID.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// The xml output for the recoveryplan object.
/// </returns>
public static Task<RecoveryPlanXmlOuput> GetRecoveryPlanXmlAsync(this IRecoveryPlanOperations operations, string recoveryPlanId, CustomRequestHeaders customRequestHeaders)
{
return operations.GetRecoveryPlanXmlAsync(recoveryPlanId, customRequestHeaders, CancellationToken.None);
}
/// <summary>
/// Get the list of all recoveryplans under the resource.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.SiteRecovery.IRecoveryPlanOperations.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// The response model for the list recoveryplans operation.
/// </returns>
public static RecoveryPlanListResponse List(this IRecoveryPlanOperations operations, CustomRequestHeaders customRequestHeaders)
{
return Task.Factory.StartNew((object s) =>
{
return ((IRecoveryPlanOperations)s).ListAsync(customRequestHeaders);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get the list of all recoveryplans under the resource.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.SiteRecovery.IRecoveryPlanOperations.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// The response model for the list recoveryplans operation.
/// </returns>
public static Task<RecoveryPlanListResponse> ListAsync(this IRecoveryPlanOperations operations, CustomRequestHeaders customRequestHeaders)
{
return operations.ListAsync(customRequestHeaders, CancellationToken.None);
}
/// <summary>
/// PlannedFailover for the recovery plan.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.SiteRecovery.IRecoveryPlanOperations.
/// </param>
/// <param name='recoveryPlanId'>
/// Required. RecoveryPlan ID.
/// </param>
/// <param name='parameters'>
/// Optional.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// The response model for the Job details object.
/// </returns>
public static JobResponse RecoveryPlanPlannedFailover(this IRecoveryPlanOperations operations, string recoveryPlanId, RpPlannedFailoverRequest parameters, CustomRequestHeaders customRequestHeaders)
{
return Task.Factory.StartNew((object s) =>
{
return ((IRecoveryPlanOperations)s).RecoveryPlanPlannedFailoverAsync(recoveryPlanId, parameters, customRequestHeaders);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// PlannedFailover for the recovery plan.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.SiteRecovery.IRecoveryPlanOperations.
/// </param>
/// <param name='recoveryPlanId'>
/// Required. RecoveryPlan ID.
/// </param>
/// <param name='parameters'>
/// Optional.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// The response model for the Job details object.
/// </returns>
public static Task<JobResponse> RecoveryPlanPlannedFailoverAsync(this IRecoveryPlanOperations operations, string recoveryPlanId, RpPlannedFailoverRequest parameters, CustomRequestHeaders customRequestHeaders)
{
return operations.RecoveryPlanPlannedFailoverAsync(recoveryPlanId, parameters, customRequestHeaders, CancellationToken.None);
}
/// <summary>
/// TestFailover for the recovery plan.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.SiteRecovery.IRecoveryPlanOperations.
/// </param>
/// <param name='recoveryPlanId'>
/// Required. RecoveryPlan ID.
/// </param>
/// <param name='parameters'>
/// Optional.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// The response model for the Job details object.
/// </returns>
public static JobResponse RecoveryPlanTestFailover(this IRecoveryPlanOperations operations, string recoveryPlanId, RpTestFailoverRequest parameters, CustomRequestHeaders customRequestHeaders)
{
return Task.Factory.StartNew((object s) =>
{
return ((IRecoveryPlanOperations)s).RecoveryPlanTestFailoverAsync(recoveryPlanId, parameters, customRequestHeaders);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// TestFailover for the recovery plan.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.SiteRecovery.IRecoveryPlanOperations.
/// </param>
/// <param name='recoveryPlanId'>
/// Required. RecoveryPlan ID.
/// </param>
/// <param name='parameters'>
/// Optional.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// The response model for the Job details object.
/// </returns>
public static Task<JobResponse> RecoveryPlanTestFailoverAsync(this IRecoveryPlanOperations operations, string recoveryPlanId, RpTestFailoverRequest parameters, CustomRequestHeaders customRequestHeaders)
{
return operations.RecoveryPlanTestFailoverAsync(recoveryPlanId, parameters, customRequestHeaders, CancellationToken.None);
}
/// <summary>
/// UnplannedFailover for the recovery plan.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.SiteRecovery.IRecoveryPlanOperations.
/// </param>
/// <param name='recoveryPlanId'>
/// Required. RecoveryPlan ID.
/// </param>
/// <param name='parameters'>
/// Optional.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// The response model for the Job details object.
/// </returns>
public static JobResponse RecoveryPlanUnplannedFailover(this IRecoveryPlanOperations operations, string recoveryPlanId, RpUnplannedFailoverRequest parameters, CustomRequestHeaders customRequestHeaders)
{
return Task.Factory.StartNew((object s) =>
{
return ((IRecoveryPlanOperations)s).RecoveryPlanUnplannedFailoverAsync(recoveryPlanId, parameters, customRequestHeaders);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// UnplannedFailover for the recovery plan.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.SiteRecovery.IRecoveryPlanOperations.
/// </param>
/// <param name='recoveryPlanId'>
/// Required. RecoveryPlan ID.
/// </param>
/// <param name='parameters'>
/// Optional.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// The response model for the Job details object.
/// </returns>
public static Task<JobResponse> RecoveryPlanUnplannedFailoverAsync(this IRecoveryPlanOperations operations, string recoveryPlanId, RpUnplannedFailoverRequest parameters, CustomRequestHeaders customRequestHeaders)
{
return operations.RecoveryPlanUnplannedFailoverAsync(recoveryPlanId, parameters, customRequestHeaders, CancellationToken.None);
}
/// <summary>
/// Reprotect the recovery plan.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.SiteRecovery.IRecoveryPlanOperations.
/// </param>
/// <param name='recoveryPlanId'>
/// Required. RecoveryPlan ID.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// The response model for the Job details object.
/// </returns>
public static JobResponse Reprotect(this IRecoveryPlanOperations operations, string recoveryPlanId, CustomRequestHeaders customRequestHeaders)
{
return Task.Factory.StartNew((object s) =>
{
return ((IRecoveryPlanOperations)s).ReprotectAsync(recoveryPlanId, customRequestHeaders);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Reprotect the recovery plan.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.SiteRecovery.IRecoveryPlanOperations.
/// </param>
/// <param name='recoveryPlanId'>
/// Required. RecoveryPlan ID.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// The response model for the Job details object.
/// </returns>
public static Task<JobResponse> ReprotectAsync(this IRecoveryPlanOperations operations, string recoveryPlanId, CustomRequestHeaders customRequestHeaders)
{
return operations.ReprotectAsync(recoveryPlanId, customRequestHeaders, CancellationToken.None);
}
/// <summary>
/// Update the recovery plan.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.SiteRecovery.IRecoveryPlanOperations.
/// </param>
/// <param name='parameters'>
/// Required. Update recovery plan input parameters.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// The response model for the Job details object.
/// </returns>
public static JobResponse UpdateRecoveryPlan(this IRecoveryPlanOperations operations, RecoveryPlanXmlData parameters, CustomRequestHeaders customRequestHeaders)
{
return Task.Factory.StartNew((object s) =>
{
return ((IRecoveryPlanOperations)s).UpdateRecoveryPlanAsync(parameters, customRequestHeaders);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Update the recovery plan.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.SiteRecovery.IRecoveryPlanOperations.
/// </param>
/// <param name='parameters'>
/// Required. Update recovery plan input parameters.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// The response model for the Job details object.
/// </returns>
public static Task<JobResponse> UpdateRecoveryPlanAsync(this IRecoveryPlanOperations operations, RecoveryPlanXmlData parameters, CustomRequestHeaders customRequestHeaders)
{
return operations.UpdateRecoveryPlanAsync(parameters, customRequestHeaders, CancellationToken.None);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Text;
using System.Xml;
using DataContractDictionary = System.Collections.Generic.Dictionary<System.Xml.XmlQualifiedName, System.Runtime.Serialization.DataContract>;
using System.Collections.Generic;
using System.Security;
using System.Runtime.CompilerServices;
#if NET_NATIVE
namespace System.Runtime.Serialization
{
public class XmlObjectSerializerReadContextComplex : XmlObjectSerializerReadContext
{
private static Dictionary<XmlObjectDataContractTypeKey, XmlObjectDataContractTypeInfo> s_dataContractTypeCache = new Dictionary<XmlObjectDataContractTypeKey, XmlObjectDataContractTypeInfo>();
private bool _preserveObjectReferences;
private SerializationMode _mode;
internal XmlObjectSerializerReadContextComplex(DataContractSerializer serializer, DataContract rootTypeDataContract, DataContractResolver dataContractResolver)
: base(serializer, rootTypeDataContract, dataContractResolver)
{
_mode = SerializationMode.SharedContract;
_preserveObjectReferences = serializer.PreserveObjectReferences;
}
internal XmlObjectSerializerReadContextComplex(XmlObjectSerializer serializer, int maxItemsInObjectGraph, StreamingContext streamingContext, bool ignoreExtensionDataObject)
: base(serializer, maxItemsInObjectGraph, streamingContext, ignoreExtensionDataObject)
{
}
internal override SerializationMode Mode
{
get { return _mode; }
}
internal override object InternalDeserialize(XmlReaderDelegator xmlReader, int declaredTypeID, RuntimeTypeHandle declaredTypeHandle, string name, string ns)
{
if (_mode == SerializationMode.SharedContract)
{
//if (dataContractSurrogate == null)
return base.InternalDeserialize(xmlReader, declaredTypeID, declaredTypeHandle, name, ns);
//else
// return InternalDeserializeWithSurrogate(xmlReader, Type.GetTypeFromHandle(declaredTypeHandle), null /*surrogateDataContract*/, name, ns);
}
else
{
return InternalDeserializeInSharedTypeMode(xmlReader, declaredTypeID, Type.GetTypeFromHandle(declaredTypeHandle), name, ns);
}
}
internal override object InternalDeserialize(XmlReaderDelegator xmlReader, Type declaredType, string name, string ns)
{
if (_mode == SerializationMode.SharedContract)
{
//if (dataContractSurrogate == null)
return base.InternalDeserialize(xmlReader, declaredType, name, ns);
//else
// return InternalDeserializeWithSurrogate(xmlReader, declaredType, null /*surrogateDataContract*/, name, ns);
}
else
{
return InternalDeserializeInSharedTypeMode(xmlReader, -1, declaredType, name, ns);
}
}
internal override object InternalDeserialize(XmlReaderDelegator xmlReader, Type declaredType, DataContract dataContract, string name, string ns)
{
if (_mode == SerializationMode.SharedContract)
{
//if (dataContractSurrogate == null)
return base.InternalDeserialize(xmlReader, declaredType, dataContract, name, ns);
//else
// return InternalDeserializeWithSurrogate(xmlReader, declaredType, dataContract, name, ns);
}
else
{
return InternalDeserializeInSharedTypeMode(xmlReader, -1, declaredType, name, ns);
}
}
private object InternalDeserializeInSharedTypeMode(XmlReaderDelegator xmlReader, int declaredTypeID, Type declaredType, string name, string ns)
{
object retObj = null;
if (TryHandleNullOrRef(xmlReader, declaredType, name, ns, ref retObj))
return retObj;
DataContract dataContract;
string assemblyName = attributes.ClrAssembly;
string typeName = attributes.ClrType;
if (assemblyName != null && typeName != null)
{
Assembly assembly;
Type type;
dataContract = ResolveDataContractInSharedTypeMode(assemblyName, typeName, out assembly, out type);
if (dataContract == null)
{
if (assembly == null)
throw XmlObjectSerializer.CreateSerializationException(SR.Format(SR.AssemblyNotFound, assemblyName));
if (type == null)
throw XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ClrTypeNotFound, assembly.FullName, typeName));
}
//Array covariance is not supported in XSD. If declared type is array, data is sent in format of base array
if (declaredType != null && declaredType.IsArray)
dataContract = (declaredTypeID < 0) ? GetDataContract(declaredType) : GetDataContract(declaredTypeID, declaredType.TypeHandle);
}
else
{
if (assemblyName != null)
throw XmlObjectSerializer.CreateSerializationException(XmlObjectSerializer.TryAddLineInfo(xmlReader, SR.Format(SR.AttributeNotFound, Globals.SerializationNamespace, Globals.ClrTypeLocalName, xmlReader.NodeType, xmlReader.NamespaceURI, xmlReader.LocalName)));
else if (typeName != null)
throw XmlObjectSerializer.CreateSerializationException(XmlObjectSerializer.TryAddLineInfo(xmlReader, SR.Format(SR.AttributeNotFound, Globals.SerializationNamespace, Globals.ClrAssemblyLocalName, xmlReader.NodeType, xmlReader.NamespaceURI, xmlReader.LocalName)));
else if (declaredType == null)
throw XmlObjectSerializer.CreateSerializationException(XmlObjectSerializer.TryAddLineInfo(xmlReader, SR.Format(SR.AttributeNotFound, Globals.SerializationNamespace, Globals.ClrTypeLocalName, xmlReader.NodeType, xmlReader.NamespaceURI, xmlReader.LocalName)));
dataContract = (declaredTypeID < 0) ? GetDataContract(declaredType) : GetDataContract(declaredTypeID, declaredType.TypeHandle);
}
return ReadDataContractValue(dataContract, xmlReader);
}
private Type ResolveDataContractTypeInSharedTypeMode(string assemblyName, string typeName, out Assembly assembly)
{
throw new PlatformNotSupportedException();
}
private DataContract ResolveDataContractInSharedTypeMode(string assemblyName, string typeName, out Assembly assembly, out Type type)
{
type = ResolveDataContractTypeInSharedTypeMode(assemblyName, typeName, out assembly);
if (type != null)
{
return GetDataContract(type);
}
return null;
}
protected override DataContract ResolveDataContractFromTypeName()
{
if (_mode == SerializationMode.SharedContract)
{
return base.ResolveDataContractFromTypeName();
}
else
{
if (attributes.ClrAssembly != null && attributes.ClrType != null)
{
Assembly assembly;
Type type;
return ResolveDataContractInSharedTypeMode(attributes.ClrAssembly, attributes.ClrType, out assembly, out type);
}
}
return null;
}
#if USE_REFEMIT
public override int GetArraySize()
#else
internal override int GetArraySize()
#endif
{
return _preserveObjectReferences ? attributes.ArraySZSize : -1;
}
private class XmlObjectDataContractTypeInfo
{
private Assembly _assembly;
private Type _type;
public XmlObjectDataContractTypeInfo(Assembly assembly, Type type)
{
_assembly = assembly;
_type = type;
}
public Assembly Assembly
{
get
{
return _assembly;
}
}
public Type Type
{
get
{
return _type;
}
}
}
private class XmlObjectDataContractTypeKey
{
private string _assemblyName;
private string _typeName;
public XmlObjectDataContractTypeKey(string assemblyName, string typeName)
{
_assemblyName = assemblyName;
_typeName = typeName;
}
public override bool Equals(object obj)
{
if (object.ReferenceEquals(this, obj))
return true;
XmlObjectDataContractTypeKey other = obj as XmlObjectDataContractTypeKey;
if (other == null)
return false;
if (_assemblyName != other._assemblyName)
return false;
if (_typeName != other._typeName)
return false;
return true;
}
public override int GetHashCode()
{
int hashCode = 0;
if (_assemblyName != null)
hashCode = _assemblyName.GetHashCode();
if (_typeName != null)
hashCode ^= _typeName.GetHashCode();
return hashCode;
}
}
}
}
#endif
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using UnityEngine;
namespace HoloToolkit.Unity
{
// The easiest way to use this script is to drop in the HeadsUpDirectionIndicator prefab
// from the HoloToolKit. If you're having issues with the prefab or can't find it,
// you can simply create an empty GameObject and attach this script. You'll need to
// create your own pointer object which can by any 3D game object. You'll need to adjust
// the depth, margin and pivot variables to affect the right appearance. After that you
// simply need to specify the "targetObject" and then you should be set.
//
// This script assumes your point object "aims" along its local up axis and orients the
// object according to that assumption.
public class HeadsUpDirectionIndicator : MonoBehaviour
{
// Use as a named indexer for Unity's frustum planes. The order follows that laid
// out in the API documentation. DO NOT CHANGE ORDER unless a corresponding change
// has been made in the Unity API.
private enum FrustumPlanes
{
Left = 0,
Right,
Bottom,
Top,
Near,
Far
}
[Tooltip("The object the direction indicator will point to.")]
public GameObject TargetObject;
[Tooltip("The camera depth at which the indicator rests.")]
public float Depth;
[Tooltip("The point around which the indicator pivots. Should be placed at the model's 'tip'.")]
public Vector3 Pivot;
[Tooltip("The object used to 'point' at the target.")]
public GameObject PointerPrefab;
[Tooltip("Determines what percentage of the visible field should be margin.")]
[Range(0.0f, 1.0f)]
public float IndicatorMarginPercent;
[Tooltip("Debug draw the planes used to calculate the pointer lock location.")]
public bool DebugDrawPointerOrientationPlanes;
private GameObject pointer;
private static int frustumLastUpdated = -1;
private static Plane[] frustumPlanes;
private static Vector3 cameraForward;
private static Vector3 cameraPosition;
private static Vector3 cameraRight;
private static Vector3 cameraUp;
private Plane[] indicatorVolume;
private void Start()
{
Depth = Mathf.Clamp(Depth, CameraCache.Main.nearClipPlane, CameraCache.Main.farClipPlane);
if (PointerPrefab == null)
{
this.gameObject.SetActive(false);
return;
}
pointer = GameObject.Instantiate(PointerPrefab);
// We create the effect of pivoting rotations by parenting the pointer and
// offsetting its position.
pointer.transform.parent = transform;
pointer.transform.position = -Pivot;
// Allocate the space to hold the indicator volume planes. Later portions of the algorithm take for
// granted that these objects have been initialized.
indicatorVolume = new Plane[]
{
new Plane(),
new Plane(),
new Plane(),
new Plane(),
new Plane(),
new Plane()
};
}
// Update the direction indicator's position and orientation every frame.
private void Update()
{
if (!HasObjectsToTrack()) { return; }
int currentFrameCount = Time.frameCount;
if (currentFrameCount != frustumLastUpdated)
{
// Collect the updated camera information for the current frame
CacheCameraTransform(CameraCache.Main);
frustumLastUpdated = currentFrameCount;
}
UpdatePointerTransform(CameraCache.Main, indicatorVolume, TargetObject.transform.position);
}
private bool HasObjectsToTrack()
{
return TargetObject != null && pointer != null;
}
// Cache data from the camera state that are costly to retrieve.
private void CacheCameraTransform(Camera camera)
{
cameraForward = camera.transform.forward;
cameraPosition = camera.transform.position;
cameraRight = camera.transform.right;
cameraUp = camera.transform.up;
frustumPlanes = GeometryUtility.CalculateFrustumPlanes(camera);
}
// Assuming the target object is outside the view which of the four "wall" planes should
// the pointer snap to.
private FrustumPlanes GetExitPlane(Vector3 targetPosition, Camera camera)
{
// To do this we first create two planes that diagonally bisect the frustum
// These panes create four quadrants. We then infer the exit plane based on
// which quadrant the target position is in.
// Calculate a set of vectors that can be used to build the frustum corners in world
// space.
float aspect = camera.aspect;
float fovy = 0.5f * camera.fieldOfView;
float near = camera.nearClipPlane;
float far = camera.farClipPlane;
float tanFovy = Mathf.Tan(Mathf.Deg2Rad * fovy);
float tanFovx = aspect * tanFovy;
// Calculate the edges of the frustum as world space offsets from the middle of the
// frustum in world space.
Vector3 nearTop = near * tanFovy * cameraUp;
Vector3 nearRight = near * tanFovx * cameraRight;
Vector3 nearBottom = -nearTop;
Vector3 nearLeft = -nearRight;
Vector3 farTop = far * tanFovy * cameraUp;
Vector3 farRight = far * tanFovx * cameraRight;
Vector3 farLeft = -farRight;
// Calculate the center point of the near plane and the far plane as offsets from the
// camera in world space.
Vector3 nearBase = near * cameraForward;
Vector3 farBase = far * cameraForward;
// Calculate the frustum corners needed to create 'd'
Vector3 nearUpperLeft = nearBase + nearTop + nearLeft;
Vector3 nearLowerRight = nearBase + nearBottom + nearRight;
Vector3 farUpperLeft = farBase + farTop + farLeft;
Plane d = new Plane(nearUpperLeft, nearLowerRight, farUpperLeft);
// Calculate the frustum corners needed to create 'e'
Vector3 nearUpperRight = nearBase + nearTop + nearRight;
Vector3 nearLowerLeft = nearBase + nearBottom + nearLeft;
Vector3 farUpperRight = farBase + farTop + farRight;
Plane e = new Plane(nearUpperRight, nearLowerLeft, farUpperRight);
#if UNITY_EDITOR
if (DebugDrawPointerOrientationPlanes)
{
// Debug draw a triangle coplanar with 'd'
Debug.DrawLine(nearUpperLeft, nearLowerRight);
Debug.DrawLine(nearLowerRight, farUpperLeft);
Debug.DrawLine(farUpperLeft, nearUpperLeft);
// Debug draw a triangle coplanar with 'e'
Debug.DrawLine(nearUpperRight, nearLowerLeft);
Debug.DrawLine(nearLowerLeft, farUpperRight);
Debug.DrawLine(farUpperRight, nearUpperRight);
}
#endif
// We're not actually interested in the "distance" to the planes. But the sign
// of the distance tells us which quadrant the target position is in.
float dDistance = d.GetDistanceToPoint(targetPosition);
float eDistance = e.GetDistanceToPoint(targetPosition);
// d e
// +\- +/-
// \ -d +e /
// \ /
// \ /
// \ /
// \ /
// +d +e \/
// /\ -d -e
// / \
// / \
// / \
// / \
// / +d -e \
// +/- +\-
if (dDistance > 0.0f)
{
if (eDistance > 0.0f)
{
return FrustumPlanes.Left;
} else
{
return FrustumPlanes.Bottom;
}
} else
{
if (eDistance > 0.0f)
{
return FrustumPlanes.Top;
} else
{
return FrustumPlanes.Right;
}
}
}
// given a frustum wall we wish to snap the pointer to, this function returns a ray
// along which the pointer should be placed to appear at the appropriate point along
// the edge of the indicator field.
private bool TryGetIndicatorPosition(Vector3 targetPosition, Plane frustumWall, out Ray r)
{
// Think of the pointer as pointing the shortest rotation a user must make to see a
// target. The shortest rotation can be obtained by finding the great circle defined
// be the target, the camera position and the center position of the view. The tangent
// vector of the great circle points the direction of the shortest rotation. This
// great circle and thus any of it's tangent vectors are coplanar with the plane
// defined by these same three points.
Vector3 cameraToTarget = targetPosition - cameraPosition;
Vector3 normal = Vector3.Cross(cameraToTarget.normalized, cameraForward);
// In the case that the three points are colinear we cannot form a plane but we'll
// assume the target is directly behind us and we'll use a pre-chosen plane.
if (normal == Vector3.zero)
{
normal = -Vector3.right;
}
Plane q = new Plane(normal, targetPosition);
return TryIntersectPlanes(frustumWall, q, out r);
}
// Obtain the line of intersection of two planes. This is based on a method
// described in the GPU Gems series.
private bool TryIntersectPlanes(Plane p, Plane q, out Ray intersection)
{
Vector3 rNormal = Vector3.Cross(p.normal, q.normal);
float det = rNormal.sqrMagnitude;
if (det != 0.0f)
{
Vector3 rPoint = ((Vector3.Cross(rNormal, q.normal) * p.distance) +
(Vector3.Cross(p.normal, rNormal) * q.distance)) / det;
intersection = new Ray(rPoint, rNormal);
return true;
} else
{
intersection = new Ray();
return false;
}
}
// Modify the pointer location and orientation to point along the shortest rotation,
// toward tergetPosition, keeping the pointer confined inside the frustum defined by
// planes.
private void UpdatePointerTransform(Camera camera, Plane[] planes, Vector3 targetPosition)
{
// Use the camera information to create the new bounding volume
UpdateIndicatorVolume(camera);
// Start by assuming the pointer should be placed at the target position.
Vector3 indicatorPosition = cameraPosition + Depth * (targetPosition - cameraPosition).normalized;
// Test the target position with the frustum planes except the "far" plane since
// far away objects should be considered in view.
bool pointNotInsideIndicatorField = false;
for (int i = 0; i < 5; ++i)
{
float dot = Vector3.Dot(planes[i].normal, (targetPosition - cameraPosition).normalized);
if (dot <= 0.0f)
{
pointNotInsideIndicatorField = true;
break;
}
}
// if the target object appears outside the indicator area...
if (pointNotInsideIndicatorField)
{
// ...then we need to do some geometry calculations to lock it to the edge.
// used to determine which edge of the screen the indicator vector
// would exit through.
FrustumPlanes exitPlane = GetExitPlane(targetPosition, camera);
Ray r;
if (TryGetIndicatorPosition(targetPosition, planes[(int)exitPlane], out r))
{
indicatorPosition = cameraPosition + Depth * r.direction.normalized;
}
}
this.transform.position = indicatorPosition;
// The pointer's direction should always appear pointing away from the user's center
// of view. Thus we find the center point of the user's view in world space.
// But the pointer should also appear perpendicular to the viewer so we find the
// center position of the view that is on the same plane as the pointer position.
// We do this by projecting the vector from the pointer to the camera onto the
// the camera's forward vector.
Vector3 indicatorFieldOffset = indicatorPosition - cameraPosition;
indicatorFieldOffset = Vector3.Dot(indicatorFieldOffset, cameraForward) * cameraForward;
Vector3 indicatorFieldCenter = cameraPosition + indicatorFieldOffset;
Vector3 pointerDirection = (indicatorPosition - indicatorFieldCenter).normalized;
// Align this object's up vector with the pointerDirection
this.transform.rotation = Quaternion.LookRotation(cameraForward, pointerDirection);
}
// Here we adjust the Camera's frustum planes to place the cursor in a smaller
// volume, thus creating the effect of a "margin"
private void UpdateIndicatorVolume(Camera camera)
{
// The top, bottom and side frustum planes are used to restrict the movement
// of the pointer. These reside at indices 0-3;
for (int i = 0; i < 4; ++i)
{
// We can make the frustum smaller by rotating the walls "in" toward the
// camera's forward vector.
// First find the angle between the Camera's forward and the plane's normal
float angle = Mathf.Acos(Vector3.Dot(frustumPlanes[i].normal.normalized, cameraForward));
// Then we calculate how much we should rotate the plane in based on the
// user's setting. 90 degrees is our maximum as at that point we no longer
// have a valid frustum.
float angleStep = IndicatorMarginPercent * (0.5f * Mathf.PI - angle);
// Because the frustum plane normals face in we must actually rotate away from the forward vector
// to narrow the frustum.
Vector3 normal = Vector3.RotateTowards(frustumPlanes[i].normal, cameraForward, -angleStep, 0.0f);
indicatorVolume[i].normal = normal.normalized;
indicatorVolume[i].distance = frustumPlanes[i].distance;
}
indicatorVolume[4] = frustumPlanes[4];
indicatorVolume[5] = frustumPlanes[5];
}
}
}
| |
using System;
using System.IO;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using RestSharp;
using Infoplus.Client;
using Infoplus.Model;
namespace Infoplus.Api
{
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public interface IOrderInvoiceTemplateLineItemDescriptionEnumApi
{
#region Synchronous Operations
/// <summary>
/// Get an orderInvoiceTemplateLineItemDescriptionEnum by id
/// </summary>
/// <remarks>
/// Returns the orderInvoiceTemplateLineItemDescriptionEnum identified by the specified id.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="orderInvoiceTemplateLineItemDescriptionEnumId">Id of orderInvoiceTemplateLineItemDescriptionEnum to be returned.</param>
/// <returns>OrderInvoiceTemplateLineItemDescriptionEnum</returns>
OrderInvoiceTemplateLineItemDescriptionEnum GetOrderInvoiceTemplateLineItemDescriptionEnumById (string orderInvoiceTemplateLineItemDescriptionEnumId);
/// <summary>
/// Get an orderInvoiceTemplateLineItemDescriptionEnum by id
/// </summary>
/// <remarks>
/// Returns the orderInvoiceTemplateLineItemDescriptionEnum identified by the specified id.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="orderInvoiceTemplateLineItemDescriptionEnumId">Id of orderInvoiceTemplateLineItemDescriptionEnum to be returned.</param>
/// <returns>ApiResponse of OrderInvoiceTemplateLineItemDescriptionEnum</returns>
ApiResponse<OrderInvoiceTemplateLineItemDescriptionEnum> GetOrderInvoiceTemplateLineItemDescriptionEnumByIdWithHttpInfo (string orderInvoiceTemplateLineItemDescriptionEnumId);
/// <summary>
/// Search orderInvoiceTemplateLineItemDescriptionEnums
/// </summary>
/// <remarks>
/// Returns the list of orderInvoiceTemplateLineItemDescriptionEnums that match the given searchText.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="searchText">Search text, used to filter results. (optional)</param>
/// <param name="page">Result page number. Defaults to 1. (optional)</param>
/// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param>
/// <returns>List<OrderInvoiceTemplateLineItemDescriptionEnum></returns>
List<OrderInvoiceTemplateLineItemDescriptionEnum> GetOrderInvoiceTemplateLineItemDescriptionEnumBySearchText (string searchText = null, int? page = null, int? limit = null);
/// <summary>
/// Search orderInvoiceTemplateLineItemDescriptionEnums
/// </summary>
/// <remarks>
/// Returns the list of orderInvoiceTemplateLineItemDescriptionEnums that match the given searchText.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="searchText">Search text, used to filter results. (optional)</param>
/// <param name="page">Result page number. Defaults to 1. (optional)</param>
/// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param>
/// <returns>ApiResponse of List<OrderInvoiceTemplateLineItemDescriptionEnum></returns>
ApiResponse<List<OrderInvoiceTemplateLineItemDescriptionEnum>> GetOrderInvoiceTemplateLineItemDescriptionEnumBySearchTextWithHttpInfo (string searchText = null, int? page = null, int? limit = null);
#endregion Synchronous Operations
#region Asynchronous Operations
/// <summary>
/// Get an orderInvoiceTemplateLineItemDescriptionEnum by id
/// </summary>
/// <remarks>
/// Returns the orderInvoiceTemplateLineItemDescriptionEnum identified by the specified id.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="orderInvoiceTemplateLineItemDescriptionEnumId">Id of orderInvoiceTemplateLineItemDescriptionEnum to be returned.</param>
/// <returns>Task of OrderInvoiceTemplateLineItemDescriptionEnum</returns>
System.Threading.Tasks.Task<OrderInvoiceTemplateLineItemDescriptionEnum> GetOrderInvoiceTemplateLineItemDescriptionEnumByIdAsync (string orderInvoiceTemplateLineItemDescriptionEnumId);
/// <summary>
/// Get an orderInvoiceTemplateLineItemDescriptionEnum by id
/// </summary>
/// <remarks>
/// Returns the orderInvoiceTemplateLineItemDescriptionEnum identified by the specified id.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="orderInvoiceTemplateLineItemDescriptionEnumId">Id of orderInvoiceTemplateLineItemDescriptionEnum to be returned.</param>
/// <returns>Task of ApiResponse (OrderInvoiceTemplateLineItemDescriptionEnum)</returns>
System.Threading.Tasks.Task<ApiResponse<OrderInvoiceTemplateLineItemDescriptionEnum>> GetOrderInvoiceTemplateLineItemDescriptionEnumByIdAsyncWithHttpInfo (string orderInvoiceTemplateLineItemDescriptionEnumId);
/// <summary>
/// Search orderInvoiceTemplateLineItemDescriptionEnums
/// </summary>
/// <remarks>
/// Returns the list of orderInvoiceTemplateLineItemDescriptionEnums that match the given searchText.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="searchText">Search text, used to filter results. (optional)</param>
/// <param name="page">Result page number. Defaults to 1. (optional)</param>
/// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param>
/// <returns>Task of List<OrderInvoiceTemplateLineItemDescriptionEnum></returns>
System.Threading.Tasks.Task<List<OrderInvoiceTemplateLineItemDescriptionEnum>> GetOrderInvoiceTemplateLineItemDescriptionEnumBySearchTextAsync (string searchText = null, int? page = null, int? limit = null);
/// <summary>
/// Search orderInvoiceTemplateLineItemDescriptionEnums
/// </summary>
/// <remarks>
/// Returns the list of orderInvoiceTemplateLineItemDescriptionEnums that match the given searchText.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="searchText">Search text, used to filter results. (optional)</param>
/// <param name="page">Result page number. Defaults to 1. (optional)</param>
/// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param>
/// <returns>Task of ApiResponse (List<OrderInvoiceTemplateLineItemDescriptionEnum>)</returns>
System.Threading.Tasks.Task<ApiResponse<List<OrderInvoiceTemplateLineItemDescriptionEnum>>> GetOrderInvoiceTemplateLineItemDescriptionEnumBySearchTextAsyncWithHttpInfo (string searchText = null, int? page = null, int? limit = null);
#endregion Asynchronous Operations
}
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public class OrderInvoiceTemplateLineItemDescriptionEnumApi : IOrderInvoiceTemplateLineItemDescriptionEnumApi
{
/// <summary>
/// Initializes a new instance of the <see cref="OrderInvoiceTemplateLineItemDescriptionEnumApi"/> class.
/// </summary>
/// <returns></returns>
public OrderInvoiceTemplateLineItemDescriptionEnumApi(String basePath)
{
this.Configuration = new Configuration(new ApiClient(basePath));
// ensure API client has configuration ready
if (Configuration.ApiClient.Configuration == null)
{
this.Configuration.ApiClient.Configuration = this.Configuration;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="OrderInvoiceTemplateLineItemDescriptionEnumApi"/> class
/// using Configuration object
/// </summary>
/// <param name="configuration">An instance of Configuration</param>
/// <returns></returns>
public OrderInvoiceTemplateLineItemDescriptionEnumApi(Configuration configuration = null)
{
if (configuration == null) // use the default one in Configuration
this.Configuration = Configuration.Default;
else
this.Configuration = configuration;
// ensure API client has configuration ready
if (Configuration.ApiClient.Configuration == null)
{
this.Configuration.ApiClient.Configuration = this.Configuration;
}
}
/// <summary>
/// Gets the base path of the API client.
/// </summary>
/// <value>The base path</value>
public String GetBasePath()
{
return this.Configuration.ApiClient.RestClient.BaseUrl.ToString();
}
/// <summary>
/// Sets the base path of the API client.
/// </summary>
/// <value>The base path</value>
[Obsolete("SetBasePath is deprecated, please do 'Configuraiton.ApiClient = new ApiClient(\"http://new-path\")' instead.")]
public void SetBasePath(String basePath)
{
// do nothing
}
/// <summary>
/// Gets or sets the configuration object
/// </summary>
/// <value>An instance of the Configuration</value>
public Configuration Configuration {get; set;}
/// <summary>
/// Gets the default header.
/// </summary>
/// <returns>Dictionary of HTTP header</returns>
[Obsolete("DefaultHeader is deprecated, please use Configuration.DefaultHeader instead.")]
public Dictionary<String, String> DefaultHeader()
{
return this.Configuration.DefaultHeader;
}
/// <summary>
/// Add default header.
/// </summary>
/// <param name="key">Header field name.</param>
/// <param name="value">Header field value.</param>
/// <returns></returns>
[Obsolete("AddDefaultHeader is deprecated, please use Configuration.AddDefaultHeader instead.")]
public void AddDefaultHeader(string key, string value)
{
this.Configuration.AddDefaultHeader(key, value);
}
/// <summary>
/// Get an orderInvoiceTemplateLineItemDescriptionEnum by id Returns the orderInvoiceTemplateLineItemDescriptionEnum identified by the specified id.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="orderInvoiceTemplateLineItemDescriptionEnumId">Id of orderInvoiceTemplateLineItemDescriptionEnum to be returned.</param>
/// <returns>OrderInvoiceTemplateLineItemDescriptionEnum</returns>
public OrderInvoiceTemplateLineItemDescriptionEnum GetOrderInvoiceTemplateLineItemDescriptionEnumById (string orderInvoiceTemplateLineItemDescriptionEnumId)
{
ApiResponse<OrderInvoiceTemplateLineItemDescriptionEnum> localVarResponse = GetOrderInvoiceTemplateLineItemDescriptionEnumByIdWithHttpInfo(orderInvoiceTemplateLineItemDescriptionEnumId);
return localVarResponse.Data;
}
/// <summary>
/// Get an orderInvoiceTemplateLineItemDescriptionEnum by id Returns the orderInvoiceTemplateLineItemDescriptionEnum identified by the specified id.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="orderInvoiceTemplateLineItemDescriptionEnumId">Id of orderInvoiceTemplateLineItemDescriptionEnum to be returned.</param>
/// <returns>ApiResponse of OrderInvoiceTemplateLineItemDescriptionEnum</returns>
public ApiResponse< OrderInvoiceTemplateLineItemDescriptionEnum > GetOrderInvoiceTemplateLineItemDescriptionEnumByIdWithHttpInfo (string orderInvoiceTemplateLineItemDescriptionEnumId)
{
// verify the required parameter 'orderInvoiceTemplateLineItemDescriptionEnumId' is set
if (orderInvoiceTemplateLineItemDescriptionEnumId == null)
throw new ApiException(400, "Missing required parameter 'orderInvoiceTemplateLineItemDescriptionEnumId' when calling OrderInvoiceTemplateLineItemDescriptionEnumApi->GetOrderInvoiceTemplateLineItemDescriptionEnumById");
var localVarPath = "/beta/orderInvoiceTemplateLineItemDescriptionEnum/{orderInvoiceTemplateLineItemDescriptionEnumId}";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (orderInvoiceTemplateLineItemDescriptionEnumId != null) localVarPathParams.Add("orderInvoiceTemplateLineItemDescriptionEnumId", Configuration.ApiClient.ParameterToString(orderInvoiceTemplateLineItemDescriptionEnumId)); // path parameter
// authentication (api_key) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key")))
{
localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (localVarStatusCode >= 400)
throw new ApiException (localVarStatusCode, "Error calling GetOrderInvoiceTemplateLineItemDescriptionEnumById: " + localVarResponse.Content, localVarResponse.Content);
else if (localVarStatusCode == 0)
throw new ApiException (localVarStatusCode, "Error calling GetOrderInvoiceTemplateLineItemDescriptionEnumById: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage);
return new ApiResponse<OrderInvoiceTemplateLineItemDescriptionEnum>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(OrderInvoiceTemplateLineItemDescriptionEnum) Configuration.ApiClient.Deserialize(localVarResponse, typeof(OrderInvoiceTemplateLineItemDescriptionEnum)));
}
/// <summary>
/// Get an orderInvoiceTemplateLineItemDescriptionEnum by id Returns the orderInvoiceTemplateLineItemDescriptionEnum identified by the specified id.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="orderInvoiceTemplateLineItemDescriptionEnumId">Id of orderInvoiceTemplateLineItemDescriptionEnum to be returned.</param>
/// <returns>Task of OrderInvoiceTemplateLineItemDescriptionEnum</returns>
public async System.Threading.Tasks.Task<OrderInvoiceTemplateLineItemDescriptionEnum> GetOrderInvoiceTemplateLineItemDescriptionEnumByIdAsync (string orderInvoiceTemplateLineItemDescriptionEnumId)
{
ApiResponse<OrderInvoiceTemplateLineItemDescriptionEnum> localVarResponse = await GetOrderInvoiceTemplateLineItemDescriptionEnumByIdAsyncWithHttpInfo(orderInvoiceTemplateLineItemDescriptionEnumId);
return localVarResponse.Data;
}
/// <summary>
/// Get an orderInvoiceTemplateLineItemDescriptionEnum by id Returns the orderInvoiceTemplateLineItemDescriptionEnum identified by the specified id.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="orderInvoiceTemplateLineItemDescriptionEnumId">Id of orderInvoiceTemplateLineItemDescriptionEnum to be returned.</param>
/// <returns>Task of ApiResponse (OrderInvoiceTemplateLineItemDescriptionEnum)</returns>
public async System.Threading.Tasks.Task<ApiResponse<OrderInvoiceTemplateLineItemDescriptionEnum>> GetOrderInvoiceTemplateLineItemDescriptionEnumByIdAsyncWithHttpInfo (string orderInvoiceTemplateLineItemDescriptionEnumId)
{
// verify the required parameter 'orderInvoiceTemplateLineItemDescriptionEnumId' is set
if (orderInvoiceTemplateLineItemDescriptionEnumId == null) throw new ApiException(400, "Missing required parameter 'orderInvoiceTemplateLineItemDescriptionEnumId' when calling GetOrderInvoiceTemplateLineItemDescriptionEnumById");
var localVarPath = "/beta/orderInvoiceTemplateLineItemDescriptionEnum/{orderInvoiceTemplateLineItemDescriptionEnumId}";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (orderInvoiceTemplateLineItemDescriptionEnumId != null) localVarPathParams.Add("orderInvoiceTemplateLineItemDescriptionEnumId", Configuration.ApiClient.ParameterToString(orderInvoiceTemplateLineItemDescriptionEnumId)); // path parameter
// authentication (api_key) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key")))
{
localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (localVarStatusCode >= 400)
throw new ApiException (localVarStatusCode, "Error calling GetOrderInvoiceTemplateLineItemDescriptionEnumById: " + localVarResponse.Content, localVarResponse.Content);
else if (localVarStatusCode == 0)
throw new ApiException (localVarStatusCode, "Error calling GetOrderInvoiceTemplateLineItemDescriptionEnumById: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage);
return new ApiResponse<OrderInvoiceTemplateLineItemDescriptionEnum>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(OrderInvoiceTemplateLineItemDescriptionEnum) Configuration.ApiClient.Deserialize(localVarResponse, typeof(OrderInvoiceTemplateLineItemDescriptionEnum)));
}
/// <summary>
/// Search orderInvoiceTemplateLineItemDescriptionEnums Returns the list of orderInvoiceTemplateLineItemDescriptionEnums that match the given searchText.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="searchText">Search text, used to filter results. (optional)</param>
/// <param name="page">Result page number. Defaults to 1. (optional)</param>
/// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param>
/// <returns>List<OrderInvoiceTemplateLineItemDescriptionEnum></returns>
public List<OrderInvoiceTemplateLineItemDescriptionEnum> GetOrderInvoiceTemplateLineItemDescriptionEnumBySearchText (string searchText = null, int? page = null, int? limit = null)
{
ApiResponse<List<OrderInvoiceTemplateLineItemDescriptionEnum>> localVarResponse = GetOrderInvoiceTemplateLineItemDescriptionEnumBySearchTextWithHttpInfo(searchText, page, limit);
return localVarResponse.Data;
}
/// <summary>
/// Search orderInvoiceTemplateLineItemDescriptionEnums Returns the list of orderInvoiceTemplateLineItemDescriptionEnums that match the given searchText.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="searchText">Search text, used to filter results. (optional)</param>
/// <param name="page">Result page number. Defaults to 1. (optional)</param>
/// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param>
/// <returns>ApiResponse of List<OrderInvoiceTemplateLineItemDescriptionEnum></returns>
public ApiResponse< List<OrderInvoiceTemplateLineItemDescriptionEnum> > GetOrderInvoiceTemplateLineItemDescriptionEnumBySearchTextWithHttpInfo (string searchText = null, int? page = null, int? limit = null)
{
var localVarPath = "/beta/orderInvoiceTemplateLineItemDescriptionEnum/search";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (searchText != null) localVarQueryParams.Add("searchText", Configuration.ApiClient.ParameterToString(searchText)); // query parameter
if (page != null) localVarQueryParams.Add("page", Configuration.ApiClient.ParameterToString(page)); // query parameter
if (limit != null) localVarQueryParams.Add("limit", Configuration.ApiClient.ParameterToString(limit)); // query parameter
// authentication (api_key) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key")))
{
localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (localVarStatusCode >= 400)
throw new ApiException (localVarStatusCode, "Error calling GetOrderInvoiceTemplateLineItemDescriptionEnumBySearchText: " + localVarResponse.Content, localVarResponse.Content);
else if (localVarStatusCode == 0)
throw new ApiException (localVarStatusCode, "Error calling GetOrderInvoiceTemplateLineItemDescriptionEnumBySearchText: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage);
return new ApiResponse<List<OrderInvoiceTemplateLineItemDescriptionEnum>>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(List<OrderInvoiceTemplateLineItemDescriptionEnum>) Configuration.ApiClient.Deserialize(localVarResponse, typeof(List<OrderInvoiceTemplateLineItemDescriptionEnum>)));
}
/// <summary>
/// Search orderInvoiceTemplateLineItemDescriptionEnums Returns the list of orderInvoiceTemplateLineItemDescriptionEnums that match the given searchText.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="searchText">Search text, used to filter results. (optional)</param>
/// <param name="page">Result page number. Defaults to 1. (optional)</param>
/// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param>
/// <returns>Task of List<OrderInvoiceTemplateLineItemDescriptionEnum></returns>
public async System.Threading.Tasks.Task<List<OrderInvoiceTemplateLineItemDescriptionEnum>> GetOrderInvoiceTemplateLineItemDescriptionEnumBySearchTextAsync (string searchText = null, int? page = null, int? limit = null)
{
ApiResponse<List<OrderInvoiceTemplateLineItemDescriptionEnum>> localVarResponse = await GetOrderInvoiceTemplateLineItemDescriptionEnumBySearchTextAsyncWithHttpInfo(searchText, page, limit);
return localVarResponse.Data;
}
/// <summary>
/// Search orderInvoiceTemplateLineItemDescriptionEnums Returns the list of orderInvoiceTemplateLineItemDescriptionEnums that match the given searchText.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="searchText">Search text, used to filter results. (optional)</param>
/// <param name="page">Result page number. Defaults to 1. (optional)</param>
/// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param>
/// <returns>Task of ApiResponse (List<OrderInvoiceTemplateLineItemDescriptionEnum>)</returns>
public async System.Threading.Tasks.Task<ApiResponse<List<OrderInvoiceTemplateLineItemDescriptionEnum>>> GetOrderInvoiceTemplateLineItemDescriptionEnumBySearchTextAsyncWithHttpInfo (string searchText = null, int? page = null, int? limit = null)
{
var localVarPath = "/beta/orderInvoiceTemplateLineItemDescriptionEnum/search";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (searchText != null) localVarQueryParams.Add("searchText", Configuration.ApiClient.ParameterToString(searchText)); // query parameter
if (page != null) localVarQueryParams.Add("page", Configuration.ApiClient.ParameterToString(page)); // query parameter
if (limit != null) localVarQueryParams.Add("limit", Configuration.ApiClient.ParameterToString(limit)); // query parameter
// authentication (api_key) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key")))
{
localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (localVarStatusCode >= 400)
throw new ApiException (localVarStatusCode, "Error calling GetOrderInvoiceTemplateLineItemDescriptionEnumBySearchText: " + localVarResponse.Content, localVarResponse.Content);
else if (localVarStatusCode == 0)
throw new ApiException (localVarStatusCode, "Error calling GetOrderInvoiceTemplateLineItemDescriptionEnumBySearchText: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage);
return new ApiResponse<List<OrderInvoiceTemplateLineItemDescriptionEnum>>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(List<OrderInvoiceTemplateLineItemDescriptionEnum>) Configuration.ApiClient.Deserialize(localVarResponse, typeof(List<OrderInvoiceTemplateLineItemDescriptionEnum>)));
}
}
}
| |
// <copyright file="BaggageTests.cs" company="OpenTelemetry Authors">
// Copyright The OpenTelemetry 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.
// </copyright>
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Xunit;
namespace OpenTelemetry.Tests
{
public class BaggageTests
{
private const string K1 = "Key1";
private const string K2 = "Key2";
private const string K3 = "Key3";
private const string V1 = "Value1";
private const string V2 = "Value2";
private const string V3 = "Value3";
[Fact]
public void EmptyTest()
{
Assert.Empty(Baggage.GetBaggage());
Assert.Empty(Baggage.Current.GetBaggage());
}
[Fact]
public void SetAndGetTest()
{
var list = new List<KeyValuePair<string, string>>(2)
{
new KeyValuePair<string, string>(K1, V1),
new KeyValuePair<string, string>(K2, V2),
};
Baggage.SetBaggage(K1, V1);
var baggage = Baggage.Current.SetBaggage(K2, V2);
Baggage.Current = baggage;
Assert.NotEmpty(Baggage.GetBaggage());
Assert.Equal(list, Baggage.GetBaggage(Baggage.Current));
Assert.Equal(V1, Baggage.GetBaggage(K1));
Assert.Equal(V1, Baggage.GetBaggage(K1.ToLower()));
Assert.Equal(V1, Baggage.GetBaggage(K1.ToUpper()));
Assert.Null(Baggage.GetBaggage("NO_KEY"));
Assert.Equal(V2, Baggage.Current.GetBaggage(K2));
Assert.Throws<ArgumentException>(() => Baggage.GetBaggage(null));
}
[Fact]
public void SetExistingKeyTest()
{
var list = new List<KeyValuePair<string, string>>(2)
{
new KeyValuePair<string, string>(K1, V1),
};
Baggage.Current.SetBaggage(new KeyValuePair<string, string>(K1, V1));
var baggage = Baggage.SetBaggage(K1, V1);
Baggage.SetBaggage(new Dictionary<string, string> { [K1] = V1 }, baggage);
Assert.Equal(list, Baggage.GetBaggage());
}
[Fact]
public void SetNullValueTest()
{
var baggage = Baggage.Current;
baggage = Baggage.SetBaggage(K1, V1, baggage);
Assert.Equal(1, Baggage.Current.Count);
Assert.Equal(1, baggage.Count);
Baggage.Current.SetBaggage(K2, null);
Assert.Equal(1, Baggage.Current.Count);
Assert.Empty(Baggage.SetBaggage(K1, null).GetBaggage());
Baggage.SetBaggage(K1, V1);
Baggage.SetBaggage(new Dictionary<string, string>
{
[K1] = null,
[K2] = V2,
});
Assert.Equal(1, Baggage.Current.Count);
Assert.Contains(Baggage.GetBaggage(), kvp => kvp.Key == K2);
}
[Fact]
public void RemoveTest()
{
var empty = Baggage.Current;
var empty2 = Baggage.RemoveBaggage(K1);
Assert.True(empty == empty2);
var baggage = Baggage.SetBaggage(new Dictionary<string, string>
{
[K1] = V1,
[K2] = V2,
[K3] = V3,
});
var baggage2 = Baggage.RemoveBaggage(K1, baggage);
Assert.Equal(3, baggage.Count);
Assert.Equal(2, baggage2.Count);
Assert.DoesNotContain(new KeyValuePair<string, string>(K1, V1), baggage2.GetBaggage());
}
[Fact]
public void ClearTest()
{
var baggage = Baggage.SetBaggage(new Dictionary<string, string>
{
[K1] = V1,
[K2] = V2,
[K3] = V3,
});
Assert.Equal(3, baggage.Count);
Baggage.ClearBaggage();
Assert.Equal(0, Baggage.Current.Count);
}
[Fact]
public void ContextFlowTest()
{
var baggage = Baggage.SetBaggage(K1, V1);
var baggage2 = Baggage.Current.SetBaggage(K2, V2);
Baggage.Current = baggage2;
var baggage3 = Baggage.SetBaggage(K3, V3);
Assert.Equal(1, baggage.Count);
Assert.Equal(2, baggage2.Count);
Assert.Equal(3, baggage3.Count);
Baggage.Current = baggage;
var baggage4 = Baggage.SetBaggage(K3, V3);
Assert.Equal(2, baggage4.Count);
Assert.DoesNotContain(new KeyValuePair<string, string>(K2, V2), baggage4.GetBaggage());
}
[Fact]
public void EnumeratorTest()
{
var list = new List<KeyValuePair<string, string>>(2)
{
new KeyValuePair<string, string>(K1, V1),
new KeyValuePair<string, string>(K2, V2),
};
var baggage = Baggage.SetBaggage(K1, V1);
baggage = Baggage.SetBaggage(K2, V2, baggage);
var enumerator = Baggage.GetEnumerator(baggage);
Assert.True(enumerator.MoveNext());
var tag1 = enumerator.Current;
Assert.True(enumerator.MoveNext());
var tag2 = enumerator.Current;
Assert.False(enumerator.MoveNext());
Assert.Equal(list, new List<KeyValuePair<string, string>> { tag1, tag2 });
Baggage.ClearBaggage();
enumerator = Baggage.GetEnumerator();
Assert.False(enumerator.MoveNext());
}
[Fact]
public void EqualsTest()
{
var bc1 = new Baggage(new Dictionary<string, string>() { [K1] = V1, [K2] = V2 });
var bc2 = new Baggage(new Dictionary<string, string>() { [K1] = V1, [K2] = V2 });
var bc3 = new Baggage(new Dictionary<string, string>() { [K2] = V2, [K1] = V1 });
var bc4 = new Baggage(new Dictionary<string, string>() { [K1] = V1, [K2] = V1 });
var bc5 = new Baggage(new Dictionary<string, string>() { [K1] = V2, [K2] = V1 });
Assert.True(bc1.Equals(bc2));
Assert.False(bc1.Equals(bc3));
Assert.False(bc1.Equals(bc4));
Assert.False(bc2.Equals(bc4));
Assert.False(bc3.Equals(bc4));
Assert.False(bc5.Equals(bc4));
Assert.False(bc4.Equals(bc5));
}
[Fact]
public void CreateBaggageTest()
{
var baggage = Baggage.Create(null);
Assert.Equal(default, baggage);
baggage = Baggage.Create(new Dictionary<string, string>
{
[K1] = V1,
["key2"] = "value2",
["KEY2"] = "VALUE2",
["KEY3"] = "VALUE3",
["Key3"] = null,
});
Assert.Equal(2, baggage.Count);
Assert.Contains(baggage.GetBaggage(), kvp => kvp.Key == K1);
Assert.Equal("VALUE2", Baggage.GetBaggage("key2", baggage));
}
[Fact]
public void EqualityTests()
{
var emptyBaggage = Baggage.Create(null);
var baggage = Baggage.SetBaggage(K1, V1);
Assert.NotEqual(emptyBaggage, baggage);
Assert.True(emptyBaggage != baggage);
baggage = Baggage.ClearBaggage(baggage);
Assert.Equal(emptyBaggage, baggage);
baggage = Baggage.SetBaggage(K1, V1);
var baggage2 = Baggage.SetBaggage(null);
Assert.Equal(baggage, baggage2);
Assert.False(baggage.Equals(this));
Assert.True(baggage.Equals((object)baggage2));
}
[Fact]
public void GetHashCodeTests()
{
var baggage = Baggage.Current;
var emptyBaggage = Baggage.Create(null);
Assert.Equal(emptyBaggage.GetHashCode(), baggage.GetHashCode());
baggage = Baggage.SetBaggage(K1, V1, baggage);
Assert.NotEqual(emptyBaggage.GetHashCode(), baggage.GetHashCode());
var expectedBaggage = Baggage.Create(new Dictionary<string, string> { [K1] = V1 });
Assert.Equal(expectedBaggage.GetHashCode(), baggage.GetHashCode());
}
[Fact]
public async Task AsyncLocalTests()
{
Baggage.SetBaggage("key1", "value1");
await InnerTask().ConfigureAwait(false);
Baggage.SetBaggage("key4", "value4");
Assert.Equal(4, Baggage.Current.Count);
Assert.Equal("value1", Baggage.GetBaggage("key1"));
Assert.Equal("value2", Baggage.GetBaggage("key2"));
Assert.Equal("value3", Baggage.GetBaggage("key3"));
Assert.Equal("value4", Baggage.GetBaggage("key4"));
static async Task InnerTask()
{
Baggage.SetBaggage("key2", "value2");
await Task.Yield();
Baggage.SetBaggage("key3", "value3");
// key2 & key3 changes don't flow backward automatically
}
}
[Fact]
public void ThreadSafetyTest()
{
Baggage.SetBaggage("rootKey", "rootValue"); // Note: Required to establish a root ExecutionContext containing the BaggageHolder we use as a lock
Parallel.For(0, 100, (i) =>
{
Baggage.SetBaggage($"key{i}", $"value{i}");
});
Assert.Equal(101, Baggage.Current.Count);
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// File System.Web.UI.WebControls.BaseDataList.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.Web.UI.WebControls
{
abstract public partial class BaseDataList : WebControl
{
#region Methods and constructors
protected override void AddParsedSubObject(Object obj)
{
}
protected BaseDataList()
{
}
protected internal override void CreateChildControls()
{
}
protected abstract void CreateControlHierarchy(bool useDataSource);
protected virtual new System.Web.UI.DataSourceSelectArguments CreateDataSourceSelectArguments()
{
return default(System.Web.UI.DataSourceSelectArguments);
}
public override void DataBind()
{
}
protected void EnsureDataBound()
{
}
protected virtual new System.Collections.IEnumerable GetData()
{
return default(System.Collections.IEnumerable);
}
public static bool IsBindableType(Type type)
{
return default(bool);
}
protected override void OnDataBinding(EventArgs e)
{
}
protected virtual new void OnDataPropertyChanged()
{
}
protected virtual new void OnDataSourceViewChanged(Object sender, EventArgs e)
{
}
protected internal override void OnInit(EventArgs e)
{
}
protected internal override void OnLoad(EventArgs e)
{
}
protected internal override void OnPreRender(EventArgs e)
{
}
protected virtual new void OnSelectedIndexChanged(EventArgs e)
{
}
protected internal abstract void PrepareControlHierarchy();
protected internal override void Render(System.Web.UI.HtmlTextWriter writer)
{
}
#endregion
#region Properties and indexers
public virtual new string Caption
{
get
{
return default(string);
}
set
{
}
}
public virtual new TableCaptionAlign CaptionAlign
{
get
{
return default(TableCaptionAlign);
}
set
{
}
}
public virtual new int CellPadding
{
get
{
return default(int);
}
set
{
}
}
public virtual new int CellSpacing
{
get
{
return default(int);
}
set
{
}
}
public override System.Web.UI.ControlCollection Controls
{
get
{
return default(System.Web.UI.ControlCollection);
}
}
public virtual new string DataKeyField
{
get
{
return default(string);
}
set
{
}
}
public DataKeyCollection DataKeys
{
get
{
return default(DataKeyCollection);
}
}
protected System.Collections.ArrayList DataKeysArray
{
get
{
return default(System.Collections.ArrayList);
}
}
public string DataMember
{
get
{
return default(string);
}
set
{
}
}
public virtual new Object DataSource
{
get
{
return default(Object);
}
set
{
}
}
public virtual new string DataSourceID
{
get
{
return default(string);
}
set
{
}
}
public virtual new GridLines GridLines
{
get
{
return default(GridLines);
}
set
{
}
}
public virtual new HorizontalAlign HorizontalAlign
{
get
{
return default(HorizontalAlign);
}
set
{
}
}
protected bool Initialized
{
get
{
return default(bool);
}
}
protected bool IsBoundUsingDataSourceID
{
get
{
return default(bool);
}
}
protected bool RequiresDataBinding
{
get
{
return default(bool);
}
set
{
}
}
protected System.Web.UI.DataSourceSelectArguments SelectArguments
{
get
{
return default(System.Web.UI.DataSourceSelectArguments);
}
}
public override bool SupportsDisabledAttribute
{
get
{
return default(bool);
}
}
public virtual new bool UseAccessibleHeader
{
get
{
return default(bool);
}
set
{
}
}
#endregion
#region Events
public event EventHandler SelectedIndexChanged
{
add
{
}
remove
{
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using JRayXLib.Math;
using JRayXLib.Math.intersections;
using JRayXLib.Shapes;
namespace JRayXLib.Struct
{
public class Node
{
public static TreeInsertStrategy Strategy = TreeInsertStrategy.DynamicTest;
public static double MinNodeWidth = Constants.EPS;
public readonly Vect3 Center; //central point of the nodes cube
public readonly double Width; //node reaches from center-width/2 to center+width/2
private readonly Node _parent; //parent node
public List<I3DObject> Content = new List<I3DObject>(); //objects contained in this node
private Node[] _child; //child nodes
public Node(Vect3 center, Node parent, double width)
{
_parent = parent;
Width = width;
Center = center;
if (width < MinNodeWidth)
throw new Exception("Node width too small: " + width);
}
/**
* @param v a <code>Vect3</code> representing a point
* @return true if, and only if, <code>v</code> is enclosed by this subtree.
*/
public bool Encloses(Vect3 v)
{
return PointCube.Encloses(Center, Width/2 + Constants.EPS, v);
}
/**
* Inserts an object into the subtree. The actual algorithms for building the tree are specified by TreeInsertStrategy.
*
* @param o the object to be added.
* @param s the bounding sphere of the object - precomputed for memory and performance reasons
* @return false if the object does not intersect/or is not enclosed by this subtree, true otherwise.
*/
public bool Insert(I3DObject o, Sphere s)
{
if (s == null)
{
//objects without bounding sphere will potentially intersect every ray
Content.Add(o);
return true;
}
switch (Strategy)
{
case TreeInsertStrategy.LeafOnly:
if (!CubeSphere.IsSphereIntersectingCube(Center, Width/2, s))
{
return false;
}
if (_child != null)
{
_child[0].Insert(o, s);
_child[1].Insert(o, s);
_child[2].Insert(o, s);
_child[3].Insert(o, s);
_child[4].Insert(o, s);
_child[5].Insert(o, s);
_child[6].Insert(o, s);
_child[7].Insert(o, s);
}
else
{
Content.Add(o);
}
if (_child == null
&& Content.Count > TreeInsertStrategyConstants.MaxElements
&& Width > TreeInsertStrategyConstants.MinWidth)
{
Split();
}
return true;
case TreeInsertStrategy.FitIntoBox:
if (!o.IsEnclosedByCube(Center, Width/2))
return false;
if (_child != null)
{
if (_child[0].Insert(o, s) ||
_child[1].Insert(o, s) ||
_child[2].Insert(o, s) ||
_child[3].Insert(o, s) ||
_child[4].Insert(o, s) ||
_child[5].Insert(o, s) ||
_child[6].Insert(o, s) ||
_child[7].Insert(o, s))
return true;
}
Content.Add(o);
if (_child == null
&& Content.Count > TreeInsertStrategyConstants.MaxElements
&& Width > TreeInsertStrategyConstants.MinWidth)
{
Split();
}
return true;
case TreeInsertStrategy.Dynamic:
//if sphere is not touching cube -> error
if (!CubeSphere.IsSphereIntersectingCube(Center, Width/2, s))
{
return false;
}
//if object is enclosed by any child, add it there
if (_child != null)
{
foreach (Node n in _child)
{
if (o.IsEnclosedByCube(n.Center, n.Width/2))
return n.Insert(o, s);
}
}
//if object is very small (in relation to the box) - duplicate it to child nodes
//add it to this node otherwise
if (_child != null && s.Radius/Width < TreeInsertStrategyConstants.DynamicDuplicateMaxSizeRatio)
{
_child[0].Insert(o, s);
_child[1].Insert(o, s);
_child[2].Insert(o, s);
_child[3].Insert(o, s);
_child[4].Insert(o, s);
_child[5].Insert(o, s);
_child[6].Insert(o, s);
_child[7].Insert(o, s);
}
else
{
Content.Add(o);
}
//if node too full split it
if (_child == null && Content.Count > 2 /*&&width>TreeInsertStrategy.DYNAMIC_MIN_WIDTH*/)
{
Split();
}
return true;
case TreeInsertStrategy.DynamicTest:
//if sphere is not touching cube -> error
if (!CubeSphere.IsSphereIntersectingCube(Center, Width/2, s))
{
return false;
}
//if object is enclosed by any child, add it there
if (_child != null)
{
foreach (Node n in _child)
{
if (o.IsEnclosedByCube(n.Center, n.Width/2))
return n.Insert(o, s);
}
bool i0 = CubeSphere.IsSphereIntersectingCube(_child[0].Center, _child[0].Width/2, s),
i1 = CubeSphere.IsSphereIntersectingCube(_child[1].Center, _child[1].Width/2, s),
i2 = CubeSphere.IsSphereIntersectingCube(_child[2].Center, _child[2].Width/2, s),
i3 = CubeSphere.IsSphereIntersectingCube(_child[3].Center, _child[3].Width/2, s),
i4 = CubeSphere.IsSphereIntersectingCube(_child[4].Center, _child[4].Width/2, s),
i5 = CubeSphere.IsSphereIntersectingCube(_child[5].Center, _child[5].Width/2, s),
i6 = CubeSphere.IsSphereIntersectingCube(_child[6].Center, _child[6].Width/2, s),
i7 = CubeSphere.IsSphereIntersectingCube(_child[7].Center, _child[7].Width/2, s);
int intersectionCount = 0;
if (i0) intersectionCount++;
if (i1) intersectionCount++;
if (i2) intersectionCount++;
if (i3) intersectionCount++;
if (i4) intersectionCount++;
if (i5) intersectionCount++;
if (i6) intersectionCount++;
if (i7) intersectionCount++;
if (intersectionCount == 1 || intersectionCount*s.Radius/Width < 0.35)
{
if (i0) _child[0].Insert(o, s);
if (i1) _child[1].Insert(o, s);
if (i2) _child[2].Insert(o, s);
if (i3) _child[3].Insert(o, s);
if (i4) _child[4].Insert(o, s);
if (i5) _child[5].Insert(o, s);
if (i6) _child[6].Insert(o, s);
if (i7) _child[7].Insert(o, s);
return true;
}
}
Content.Add(o);
//if node too full split it
if (_child == null && Content.Count > 2)
{
Split();
}
return true;
case TreeInsertStrategy.FastBuildTest:
//if sphere is not touching cube -> error
if (!CubeSphere.IsSphereIntersectingCube(Center, Width/2, s))
{
return false;
}
//if object is enclosed by any child, add it there
if (_child != null)
{
bool i0 = CubeSphere.IsSphereIntersectingCube(_child[0].Center, _child[0].Width/2, s),
i1 = CubeSphere.IsSphereIntersectingCube(_child[1].Center, _child[1].Width/2, s),
i2 = CubeSphere.IsSphereIntersectingCube(_child[2].Center, _child[2].Width/2, s),
i3 = CubeSphere.IsSphereIntersectingCube(_child[3].Center, _child[3].Width/2, s),
i4 = CubeSphere.IsSphereIntersectingCube(_child[4].Center, _child[4].Width/2, s),
i5 = CubeSphere.IsSphereIntersectingCube(_child[5].Center, _child[5].Width/2, s),
i6 = CubeSphere.IsSphereIntersectingCube(_child[6].Center, _child[6].Width/2, s),
i7 = CubeSphere.IsSphereIntersectingCube(_child[7].Center, _child[7].Width/2, s);
int intersectionCount = 0;
if (i0) intersectionCount++;
if (i1) intersectionCount++;
if (i2) intersectionCount++;
if (i3) intersectionCount++;
if (i4) intersectionCount++;
if (i5) intersectionCount++;
if (i6) intersectionCount++;
if (i7) intersectionCount++;
if (intersectionCount == 1 || intersectionCount*s.Radius/Width < 0.5)
{
if (i0) _child[0].Insert(o, s);
if (i1) _child[1].Insert(o, s);
if (i2) _child[2].Insert(o, s);
if (i3) _child[3].Insert(o, s);
if (i4) _child[4].Insert(o, s);
if (i5) _child[5].Insert(o, s);
if (i6) _child[6].Insert(o, s);
if (i7) _child[7].Insert(o, s);
return true;
}
}
Content.Add(o);
//if node too full split it
if (_child == null && Content.Count > TreeInsertStrategyConstants.MaxElements &&
Width > TreeInsertStrategyConstants.DynamicMinWidth)
{
Split();
}
return true;
default:
throw new Exception("Mode not implemented: " + Strategy);
}
}
/**
* Splits this node into 8 child-nodes and re-inserts the content
*/
private void Split()
{
if (_child != null)
throw new Exception("double split detected");
_child = new Node[8];
double w2 = Width/2;
double w4 = Width/4;
_child[0] = new Node(new Vect3 { X = Center.X + w4, Y = Center.Y + w4, Z = Center.Z + w4 }, this, w2);
_child[1] = new Node(new Vect3 { X = Center.X + w4, Y = Center.Y + w4, Z = Center.Z - w4 }, this, w2);
_child[2] = new Node(new Vect3 { X = Center.X + w4, Y = Center.Y - w4, Z = Center.Z + w4 }, this, w2);
_child[3] = new Node(new Vect3 { X = Center.X + w4, Y = Center.Y - w4, Z = Center.Z - w4 }, this, w2);
_child[4] = new Node(new Vect3 { X = Center.X - w4, Y = Center.Y + w4, Z = Center.Z + w4 }, this, w2);
_child[5] = new Node(new Vect3 { X = Center.X - w4, Y = Center.Y + w4, Z = Center.Z - w4 }, this, w2);
_child[6] = new Node(new Vect3 { X = Center.X - w4, Y = Center.Y - w4, Z = Center.Z + w4 }, this, w2);
_child[7] = new Node(new Vect3 { X = Center.X - w4, Y = Center.Y - w4, Z = Center.Z - w4 }, this, w2);
List<I3DObject> oldContent = Content;
Content = new List<I3DObject>();
foreach (I3DObject o in oldContent)
{
if (!Insert(o, o.GetBoundingSphere()))
{
throw new Exception("could not insert: " + o);
}
}
}
/**
* March through Octree checking collisions. Every node on the way (when traversing to leaf direction) is checked for hits.
*
* @param v point to search for
* @param c collision details
* @return smallest node containing v, or null if (and only if) v is not inside the tree
*/
public Node MarchToCheckingCollisions(Vect3 v, CollisionDetails c, Shapes.Ray ray)
{
if (Encloses(v))
{
if (_child == null)
{
return this;
}
foreach (Node n in _child)
{
if (n.Encloses(v))
{
c.CheckCollisionSet(n.Content, ray);
return n.MarchToCheckingCollisions(v, c, ray);
}
}
return this;
}
if (_parent != null)
return _parent.MarchToCheckingCollisions(v, c, ray);
return null;
}
public new String ToString()
{
return Center + "+/-" + Width/2;
}
public void AddStringRep(StringBuilder sb, int layer)
{
for (int i = 0; i < layer; i++)
sb.Append(" ");
sb.Append(ToString());
sb.Append(":");
sb.Append(Content);
sb.Append("\n");
if (_child != null)
foreach (Node n in _child)
{
n.AddStringRep(sb, layer + 1);
}
}
/**
* @return the number of objects stored in this subtree (duplicates are count multiple times)
*/
public int GetSize()
{
int size = Content.Count;
if (_child != null)
size += _child.Sum(n => n.GetSize());
return size;
}
/**
* Calculates: <code>s = sum(layer)</code> where sum is the sum over all objects stored in
* this subtree and layer at which the object is stored (the root has layer 0).
* <p/>
* <code>s/getSize()</code> defines the average layer of the object.
* @param layer
* @return s
*/
public long GetContentDepthSum(int layer)
{
long sum = 0;
sum += Content.Count*(long) layer;
if (_child != null)
sum += _child.Sum(n => n.GetContentDepthSum(layer + 1));
return sum;
}
/**
* Removes child nodes in case none of them has any content
*/
public void Compress()
{
if (GetSize() - Content.Count == 0 && _child != null)
{
_child = null;
}
if (_child != null)
{
foreach (Node n in _child)
n.Compress();
}
}
/**
* @return number of nodes in this subtree
*/
public int GetNodeCount()
{
int nc = 1;
if (_child != null)
nc += _child.Sum(n => n.GetNodeCount());
return nc;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using FlatRedBall.Gui;
using FlatRedBall.Graphics;
using FlatRedBall;
using FlatRedBall.Math;
#if FRB_MDX
using Microsoft.DirectX.Direct3D;
#endif
namespace EditorObjects.Gui
{
public class TextPropertyGrid : PropertyGrid<Text>
{
#region Fields
Button mSetPixelPerfectScaleButton;
public static PositionedObjectList<Camera> ExtraCamerasForScale = new PositionedObjectList<Camera>();
#endregion
#region Properties
public override Text SelectedObject
{
get
{
return base.SelectedObject;
}
set
{
base.SelectedObject = value;
if (!Visible && (SelectedObject != null))
{
GuiManager.BringToFront(this);
}
Visible = (SelectedObject != null);
}
}
public string SetPixelPerfectText
{
get
{
return mSetPixelPerfectScaleButton.Text;
}
set
{
mSetPixelPerfectScaleButton.Text = value;
}
}
#endregion
#region Event Methods
private void SetPixelPerfectScaleClick(Window callingWindow)
{
OkListWindow okListWindow = new OkListWindow("Which camera would you like to scale according to?", "Select Camera");
foreach (Camera camera in SpriteManager.Cameras)
{
okListWindow.AddItem(camera.Name, camera);
}
foreach (Camera camera in ExtraCamerasForScale)
{
okListWindow.AddItem(camera.Name, camera);
}
okListWindow.OkButtonClick += SetPixelPerfectScaleOk;
}
private void SetPixelPerfectScaleOk(Window callingWindow)
{
if (SelectedObject != null)
{
OkListWindow okListWindow = callingWindow as OkListWindow;
Camera camera = okListWindow.GetFirstHighlightedObject() as Camera;
if (camera == null)
{
GuiManager.ShowMessageBox("No Camera was selected, so Scale has not changed", "No Camera");
}
else
{
SelectedObject.SetPixelPerfectScale(camera);
}
}
}
private void FontChanged(Window callingWindow)
{
BitmapFontChangePropertyGrid propertyGrid = (BitmapFontChangePropertyGrid)callingWindow;
BitmapFont oldFont = propertyGrid.LastBitmapFont;
BitmapFont newFont = SelectedObject.Font;
if (oldFont != null && newFont != null)
{
float scaleAmount = newFont.LineHeightInPixels / (float)oldFont.LineHeightInPixels;
SelectedObject.Scale *= scaleAmount;
SelectedObject.Spacing *= scaleAmount;
SelectedObject.NewLineDistance *= scaleAmount;
// Do we want to do anything here?
//if (SelectedObject.AdjustPositionForPixelPerfectDrawing)
//{
// NewLineDistance = (float)System.Math.Round(Scale * 1.5f);
//}
//else
//{
// NewLineDistance = Scale * 1.5f;
//}
}
}
#endregion
#region Methods
public TextPropertyGrid(Cursor cursor)
: base(cursor)
{
MinimumScaleY = 8;
// GuiManager.AddWindow(this);
this.ExcludeAllMembers();
#region Basic
this.IncludeMember("X", "Basic");
this.IncludeMember("Y", "Basic");
this.IncludeMember("Z", "Basic");
this.IncludeMember("RotationZ", "Basic");
this.IncludeMember("Visible", "Basic");
this.IncludeMember("DisplayText", "Basic");
this.IncludeMember("Name", "Basic");
#endregion
#region Alignment
this.IncludeMember("HorizontalAlignment", "Alignment");
this.IncludeMember("VerticalAlignment", "Alignment");
#endregion
#region Color
this.IncludeMember("Red", "Color");
this.IncludeMember("Green", "Color");
this.IncludeMember("Blue", "Color");
this.IncludeMember("ColorOperation", "Color");
#if !FRB_XNA
ComboBox colorOperationComboBox = GetUIElementForMember("ColorOperation") as ComboBox;
for (int i = colorOperationComboBox.Count - 1; i > -1; i--)
{
TextureOperation textureOperation =
((TextureOperation)colorOperationComboBox[i].ReferenceObject);
if (!FlatRedBall.Graphics.GraphicalEnumerations.IsTextureOperationSupportedInFrbXna(
textureOperation))
{
colorOperationComboBox.RemoveAt(i);
}
}
#endif
this.IncludeMember("Alpha", "Color");
this.IncludeMember("BlendOperation", "Color");
#endregion
#region Scale
this.IncludeMember("Scale", "Scale");
this.IncludeMember("Spacing", "Scale");
this.IncludeMember("NewLineDistance", "Scale");
mSetPixelPerfectScaleButton = new Button(cursor);
mSetPixelPerfectScaleButton.Text = "Set Pixel-Perfect\nScale";
mSetPixelPerfectScaleButton.ScaleX = 7.3f;
mSetPixelPerfectScaleButton.ScaleY = 2;
AddWindow(mSetPixelPerfectScaleButton, "Scale");
mSetPixelPerfectScaleButton.Click += SetPixelPerfectScaleClick;
this.IncludeMember("MaxWidth", "Scale");
this.IncludeMember("MaxWidthBehavior", "Scale");
#endregion
this.IncludeMember("Font", "Font");
this.SetMemberChangeEvent("Font", FontChanged);
this.RemoveCategory("Uncategorized");
}
#endregion
}
}
| |
//
// 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.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure;
using Microsoft.Azure.Management.Dns;
using Microsoft.Azure.Management.Dns.Models;
namespace Microsoft.Azure.Management.Dns
{
/// <summary>
/// Client for managing DNS zones and record.
/// </summary>
public static partial class RecordSetOperationsExtensions
{
/// <summary>
/// Creates a RecordSet within a DNS zone.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Dns.IRecordSetOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='zoneName'>
/// Required. The name of the zone without a terminating dot.
/// </param>
/// <param name='relativeRecordSetName'>
/// Required. The name of the RecordSet, relative to the name of the
/// zone.
/// </param>
/// <param name='recordType'>
/// Required. The type of DNS record.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the CreateOrUpdate operation.
/// </param>
/// <param name='ifMatch'>
/// Optional. The etag of RecordSet.
/// </param>
/// <param name='ifNoneMatch'>
/// Optional. Defines the If-None-Match condition. Set to '*' to force
/// Create-If-Not-Exist. Other values will be ignored.
/// </param>
/// <returns>
/// The response to a RecordSet CreateOrUpdate operation.
/// </returns>
public static RecordSetCreateOrUpdateResponse CreateOrUpdate(this IRecordSetOperations operations, string resourceGroupName, string zoneName, string relativeRecordSetName, RecordType recordType, RecordSetCreateOrUpdateParameters parameters, string ifMatch, string ifNoneMatch)
{
return Task.Factory.StartNew((object s) =>
{
return ((IRecordSetOperations)s).CreateOrUpdateAsync(resourceGroupName, zoneName, relativeRecordSetName, recordType, parameters, ifMatch, ifNoneMatch);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Creates a RecordSet within a DNS zone.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Dns.IRecordSetOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='zoneName'>
/// Required. The name of the zone without a terminating dot.
/// </param>
/// <param name='relativeRecordSetName'>
/// Required. The name of the RecordSet, relative to the name of the
/// zone.
/// </param>
/// <param name='recordType'>
/// Required. The type of DNS record.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the CreateOrUpdate operation.
/// </param>
/// <param name='ifMatch'>
/// Optional. The etag of RecordSet.
/// </param>
/// <param name='ifNoneMatch'>
/// Optional. Defines the If-None-Match condition. Set to '*' to force
/// Create-If-Not-Exist. Other values will be ignored.
/// </param>
/// <returns>
/// The response to a RecordSet CreateOrUpdate operation.
/// </returns>
public static Task<RecordSetCreateOrUpdateResponse> CreateOrUpdateAsync(this IRecordSetOperations operations, string resourceGroupName, string zoneName, string relativeRecordSetName, RecordType recordType, RecordSetCreateOrUpdateParameters parameters, string ifMatch, string ifNoneMatch)
{
return operations.CreateOrUpdateAsync(resourceGroupName, zoneName, relativeRecordSetName, recordType, parameters, ifMatch, ifNoneMatch, CancellationToken.None);
}
/// <summary>
/// Removes a RecordSet from a DNS zone.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Dns.IRecordSetOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='zoneName'>
/// Required. The name of the zone without a terminating dot.
/// </param>
/// <param name='relativeRecordSetName'>
/// Required. The name of the RecordSet, relative to the name of the
/// zone.
/// </param>
/// <param name='recordType'>
/// Required. The type of DNS record.
/// </param>
/// <param name='ifMatch'>
/// Optional. Defines the If-Match condition. The delete operation will
/// be performed only if the ETag of the zone on the server matches
/// this value.
/// </param>
/// <param name='ifNoneMatch'>
/// Optional. Defines the If-None-Match condition. The delete operation
/// will be performed only if the ETag of the zone on the server does
/// not match this value.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static AzureOperationResponse Delete(this IRecordSetOperations operations, string resourceGroupName, string zoneName, string relativeRecordSetName, RecordType recordType, string ifMatch, string ifNoneMatch)
{
return Task.Factory.StartNew((object s) =>
{
return ((IRecordSetOperations)s).DeleteAsync(resourceGroupName, zoneName, relativeRecordSetName, recordType, ifMatch, ifNoneMatch);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Removes a RecordSet from a DNS zone.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Dns.IRecordSetOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='zoneName'>
/// Required. The name of the zone without a terminating dot.
/// </param>
/// <param name='relativeRecordSetName'>
/// Required. The name of the RecordSet, relative to the name of the
/// zone.
/// </param>
/// <param name='recordType'>
/// Required. The type of DNS record.
/// </param>
/// <param name='ifMatch'>
/// Optional. Defines the If-Match condition. The delete operation will
/// be performed only if the ETag of the zone on the server matches
/// this value.
/// </param>
/// <param name='ifNoneMatch'>
/// Optional. Defines the If-None-Match condition. The delete operation
/// will be performed only if the ETag of the zone on the server does
/// not match this value.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<AzureOperationResponse> DeleteAsync(this IRecordSetOperations operations, string resourceGroupName, string zoneName, string relativeRecordSetName, RecordType recordType, string ifMatch, string ifNoneMatch)
{
return operations.DeleteAsync(resourceGroupName, zoneName, relativeRecordSetName, recordType, ifMatch, ifNoneMatch, CancellationToken.None);
}
/// <summary>
/// Gets a RecordSet.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Dns.IRecordSetOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='zoneName'>
/// Required. The name of the zone without a terminating dot.
/// </param>
/// <param name='relativeRecordSetName'>
/// Required. The name of the RecordSet, relative to the name of the
/// zone.
/// </param>
/// <param name='recordType'>
/// Required. The type of DNS record.
/// </param>
/// <returns>
/// The response to a RecordSet Get operation.
/// </returns>
public static RecordSetGetResponse Get(this IRecordSetOperations operations, string resourceGroupName, string zoneName, string relativeRecordSetName, RecordType recordType)
{
return Task.Factory.StartNew((object s) =>
{
return ((IRecordSetOperations)s).GetAsync(resourceGroupName, zoneName, relativeRecordSetName, recordType);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets a RecordSet.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Dns.IRecordSetOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='zoneName'>
/// Required. The name of the zone without a terminating dot.
/// </param>
/// <param name='relativeRecordSetName'>
/// Required. The name of the RecordSet, relative to the name of the
/// zone.
/// </param>
/// <param name='recordType'>
/// Required. The type of DNS record.
/// </param>
/// <returns>
/// The response to a RecordSet Get operation.
/// </returns>
public static Task<RecordSetGetResponse> GetAsync(this IRecordSetOperations operations, string resourceGroupName, string zoneName, string relativeRecordSetName, RecordType recordType)
{
return operations.GetAsync(resourceGroupName, zoneName, relativeRecordSetName, recordType, CancellationToken.None);
}
/// <summary>
/// Lists the RecordSets of a specified type in a DNS zone.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Dns.IRecordSetOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group that contains the zone.
/// </param>
/// <param name='zoneName'>
/// Required. The name of the zone from which to enumerate RecordsSets.
/// </param>
/// <param name='recordType'>
/// Required. The type of record sets to enumerate.
/// </param>
/// <param name='parameters'>
/// Optional. Query parameters. If null is passed returns the default
/// number of zones.
/// </param>
/// <returns>
/// The response to a RecordSet List operation.
/// </returns>
public static RecordSetListResponse List(this IRecordSetOperations operations, string resourceGroupName, string zoneName, RecordType recordType, RecordSetListParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IRecordSetOperations)s).ListAsync(resourceGroupName, zoneName, recordType, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Lists the RecordSets of a specified type in a DNS zone.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Dns.IRecordSetOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group that contains the zone.
/// </param>
/// <param name='zoneName'>
/// Required. The name of the zone from which to enumerate RecordsSets.
/// </param>
/// <param name='recordType'>
/// Required. The type of record sets to enumerate.
/// </param>
/// <param name='parameters'>
/// Optional. Query parameters. If null is passed returns the default
/// number of zones.
/// </param>
/// <returns>
/// The response to a RecordSet List operation.
/// </returns>
public static Task<RecordSetListResponse> ListAsync(this IRecordSetOperations operations, string resourceGroupName, string zoneName, RecordType recordType, RecordSetListParameters parameters)
{
return operations.ListAsync(resourceGroupName, zoneName, recordType, parameters, CancellationToken.None);
}
/// <summary>
/// Lists all RecordSets in a DNS zone.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Dns.IRecordSetOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group that contains the zone.
/// </param>
/// <param name='zoneName'>
/// Required. The name of the zone from which to enumerate RecordSets.
/// </param>
/// <param name='parameters'>
/// Optional. Query parameters. If null is passed returns the default
/// number of zones.
/// </param>
/// <returns>
/// The response to a RecordSet List operation.
/// </returns>
public static RecordSetListResponse ListAll(this IRecordSetOperations operations, string resourceGroupName, string zoneName, RecordSetListParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IRecordSetOperations)s).ListAllAsync(resourceGroupName, zoneName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Lists all RecordSets in a DNS zone.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Dns.IRecordSetOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group that contains the zone.
/// </param>
/// <param name='zoneName'>
/// Required. The name of the zone from which to enumerate RecordSets.
/// </param>
/// <param name='parameters'>
/// Optional. Query parameters. If null is passed returns the default
/// number of zones.
/// </param>
/// <returns>
/// The response to a RecordSet List operation.
/// </returns>
public static Task<RecordSetListResponse> ListAllAsync(this IRecordSetOperations operations, string resourceGroupName, string zoneName, RecordSetListParameters parameters)
{
return operations.ListAllAsync(resourceGroupName, zoneName, parameters, CancellationToken.None);
}
/// <summary>
/// Lists RecordSets in a DNS zone. Depending on the previous call, it
/// will list all types or by type.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Dns.IRecordSetOperations.
/// </param>
/// <param name='nextLink'>
/// Required. NextLink from the previous successful call to List
/// operation.
/// </param>
/// <returns>
/// The response to a RecordSet List operation.
/// </returns>
public static RecordSetListResponse ListNext(this IRecordSetOperations operations, string nextLink)
{
return Task.Factory.StartNew((object s) =>
{
return ((IRecordSetOperations)s).ListNextAsync(nextLink);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Lists RecordSets in a DNS zone. Depending on the previous call, it
/// will list all types or by type.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Dns.IRecordSetOperations.
/// </param>
/// <param name='nextLink'>
/// Required. NextLink from the previous successful call to List
/// operation.
/// </param>
/// <returns>
/// The response to a RecordSet List operation.
/// </returns>
public static Task<RecordSetListResponse> ListNextAsync(this IRecordSetOperations operations, string nextLink)
{
return operations.ListNextAsync(nextLink, CancellationToken.None);
}
/// <summary>
/// Creates a RecordSet within a DNS zone.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Dns.IRecordSetOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='zoneName'>
/// Required. The name of the zone without a terminating dot.
/// </param>
/// <param name='relativeRecordSetName'>
/// Required. The name of the RecordSet, relative to the name of the
/// zone.
/// </param>
/// <param name='recordType'>
/// Required. The type of DNS record.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the CreateOrUpdate operation.
/// </param>
/// <param name='ifMatch'>
/// Optional. The etag of Zone.
/// </param>
/// <param name='ifNoneMatch'>
/// Optional. Defines the If-None-Match condition. Set to '*' to force
/// Create-If-Not-Exist. Other values will be ignored.
/// </param>
/// <returns>
/// The response to a RecordSet Update operation.
/// </returns>
public static RecordSetUpdateResponse Update(this IRecordSetOperations operations, string resourceGroupName, string zoneName, string relativeRecordSetName, RecordType recordType, RecordSetUpdateParameters parameters, string ifMatch, string ifNoneMatch)
{
return Task.Factory.StartNew((object s) =>
{
return ((IRecordSetOperations)s).UpdateAsync(resourceGroupName, zoneName, relativeRecordSetName, recordType, parameters, ifMatch, ifNoneMatch);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Creates a RecordSet within a DNS zone.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Dns.IRecordSetOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='zoneName'>
/// Required. The name of the zone without a terminating dot.
/// </param>
/// <param name='relativeRecordSetName'>
/// Required. The name of the RecordSet, relative to the name of the
/// zone.
/// </param>
/// <param name='recordType'>
/// Required. The type of DNS record.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the CreateOrUpdate operation.
/// </param>
/// <param name='ifMatch'>
/// Optional. The etag of Zone.
/// </param>
/// <param name='ifNoneMatch'>
/// Optional. Defines the If-None-Match condition. Set to '*' to force
/// Create-If-Not-Exist. Other values will be ignored.
/// </param>
/// <returns>
/// The response to a RecordSet Update operation.
/// </returns>
public static Task<RecordSetUpdateResponse> UpdateAsync(this IRecordSetOperations operations, string resourceGroupName, string zoneName, string relativeRecordSetName, RecordType recordType, RecordSetUpdateParameters parameters, string ifMatch, string ifNoneMatch)
{
return operations.UpdateAsync(resourceGroupName, zoneName, relativeRecordSetName, recordType, parameters, ifMatch, ifNoneMatch, CancellationToken.None);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Orleans.Configuration;
using Orleans.Hosting;
using Orleans.Runtime;
using Orleans.Runtime.Configuration;
using Orleans.TestingHost;
using TestExtensions;
using UnitTests.GrainInterfaces;
using Xunit;
namespace UnitTests.General
{
[TestCategory("Elasticity"), TestCategory("Placement")]
public class ElasticPlacementTests : TestClusterPerTest
{
private readonly List<IActivationCountBasedPlacementTestGrain> grains = new List<IActivationCountBasedPlacementTestGrain>();
private const int leavy = 300;
private const int perSilo = 1000;
protected override void ConfigureTestCluster(TestClusterBuilder builder)
{
builder.AddSiloBuilderConfigurator<SiloConfigurator>();
}
private class SiloConfigurator : ISiloConfigurator
{
public void Configure(ISiloBuilder hostBuilder)
{
hostBuilder.AddMemoryGrainStorage("MemoryStore")
.AddMemoryGrainStorageAsDefault()
.Configure<LoadSheddingOptions>(options => options.LoadSheddingEnabled = true);
}
}
/// <summary>
/// Test placement behaviour for newly added silos. The grain placement strategy should favor them
/// until they reach a similar load as the other silos.
/// </summary>
[SkippableFact(Skip = "https://github.com/dotnet/orleans/issues/4008"), TestCategory("Functional")]
public async Task ElasticityTest_CatchingUp()
{
logger.Info("\n\n\n----- Phase 1 -----\n\n");
AddTestGrains(perSilo).Wait();
AddTestGrains(perSilo).Wait();
var activationCounts = await GetPerSiloActivationCounts();
LogCounts(activationCounts);
logger.Info("-----------------------------------------------------------------");
AssertIsInRange(activationCounts[this.HostedCluster.Primary], perSilo, leavy);
AssertIsInRange(activationCounts[this.HostedCluster.SecondarySilos.First()], perSilo, leavy);
SiloHandle silo3 = this.HostedCluster.StartAdditionalSilo();
await this.HostedCluster.WaitForLivenessToStabilizeAsync();
logger.Info("\n\n\n----- Phase 2 -----\n\n");
await AddTestGrains(perSilo);
await AddTestGrains(perSilo);
await AddTestGrains(perSilo);
await AddTestGrains(perSilo);
logger.Info("-----------------------------------------------------------------");
activationCounts = await GetPerSiloActivationCounts();
LogCounts(activationCounts);
logger.Info("-----------------------------------------------------------------");
double expected = (6.0 * perSilo) / 3.0;
AssertIsInRange(activationCounts[this.HostedCluster.Primary], expected, leavy);
AssertIsInRange(activationCounts[this.HostedCluster.SecondarySilos.First()], expected, leavy);
AssertIsInRange(activationCounts[silo3], expected, leavy);
logger.Info("\n\n\n----- Phase 3 -----\n\n");
await AddTestGrains(perSilo);
await AddTestGrains(perSilo);
await AddTestGrains(perSilo);
logger.Info("-----------------------------------------------------------------");
activationCounts = await GetPerSiloActivationCounts();
LogCounts(activationCounts);
logger.Info("-----------------------------------------------------------------");
expected = (9.0 * perSilo) / 3.0;
AssertIsInRange(activationCounts[this.HostedCluster.Primary], expected, leavy);
AssertIsInRange(activationCounts[this.HostedCluster.SecondarySilos.First()], expected, leavy);
AssertIsInRange(activationCounts[silo3], expected, leavy);
logger.Info("-----------------------------------------------------------------");
logger.Info("Test finished OK. Expected per silo = {0}", expected);
}
/// <summary>
/// This evaluates the how the placement strategy behaves once silos are stopped: The strategy should
/// balance the activations from the stopped silo evenly among the remaining silos.
/// </summary>
[SkippableFact(Skip = "https://github.com/dotnet/orleans/issues/4008"), TestCategory("Functional")]
public async Task ElasticityTest_StoppingSilos()
{
List<SiloHandle> runtimes = await this.HostedCluster.StartAdditionalSilosAsync(2);
await this.HostedCluster.WaitForLivenessToStabilizeAsync();
int stopLeavy = leavy;
await AddTestGrains(perSilo);
await AddTestGrains(perSilo);
await AddTestGrains(perSilo);
await AddTestGrains(perSilo);
var activationCounts = await GetPerSiloActivationCounts();
logger.Info("-----------------------------------------------------------------");
LogCounts(activationCounts);
logger.Info("-----------------------------------------------------------------");
AssertIsInRange(activationCounts[this.HostedCluster.Primary], perSilo, stopLeavy);
AssertIsInRange(activationCounts[this.HostedCluster.SecondarySilos.First()], perSilo, stopLeavy);
AssertIsInRange(activationCounts[runtimes[0]], perSilo, stopLeavy);
AssertIsInRange(activationCounts[runtimes[1]], perSilo, stopLeavy);
await this.HostedCluster.StopSiloAsync(runtimes[0]);
await this.HostedCluster.WaitForLivenessToStabilizeAsync();
await InvokeAllGrains();
activationCounts = await GetPerSiloActivationCounts();
logger.Info("-----------------------------------------------------------------");
LogCounts(activationCounts);
logger.Info("-----------------------------------------------------------------");
double expected = perSilo * 1.33;
AssertIsInRange(activationCounts[this.HostedCluster.Primary], expected, stopLeavy);
AssertIsInRange(activationCounts[this.HostedCluster.SecondarySilos.First()], expected, stopLeavy);
AssertIsInRange(activationCounts[runtimes[1]], expected, stopLeavy);
logger.Info("-----------------------------------------------------------------");
logger.Info("Test finished OK. Expected per silo = {0}", expected);
}
/// <summary>
/// Do not place activation in case all silos are above 110 CPU utilization.
/// </summary>
[SkippableFact(Skip = "https://github.com/dotnet/orleans/issues/4008"), TestCategory("Functional")]
public async Task ElasticityTest_AllSilosCPUTooHigh()
{
var taintedGrainPrimary = await GetGrainAtSilo(this.HostedCluster.Primary.SiloAddress);
var taintedGrainSecondary = await GetGrainAtSilo(this.HostedCluster.SecondarySilos.First().SiloAddress);
await taintedGrainPrimary.EnableOverloadDetection(false);
await taintedGrainSecondary.EnableOverloadDetection(false);
await taintedGrainPrimary.LatchCpuUsage(110.0f);
await taintedGrainSecondary.LatchCpuUsage(110.0f);
await Assert.ThrowsAsync<OrleansException>(() =>
this.AddTestGrains(1));
}
/// <summary>
/// Do not place activation in case all silos are above 110 CPU utilization or have overloaded flag set.
/// </summary>
[SkippableFact(Skip= "https://github.com/dotnet/orleans/issues/4008"), TestCategory("Functional")]
public async Task ElasticityTest_AllSilosOverloaded()
{
var taintedGrainPrimary = await GetGrainAtSilo(this.HostedCluster.Primary.SiloAddress);
var taintedGrainSecondary = await GetGrainAtSilo(this.HostedCluster.SecondarySilos.First().SiloAddress);
await taintedGrainPrimary.LatchCpuUsage(110.0f);
await taintedGrainSecondary.LatchOverloaded();
// OrleansException or GateWayTooBusyException
var exception = await Assert.ThrowsAnyAsync<Exception>(() =>
this.AddTestGrains(1));
Assert.True(exception is OrleansException || exception is GatewayTooBusyException);
}
[Fact, TestCategory("Functional")]
public async Task LoadAwareGrainShouldNotAttemptToCreateActivationsOnOverloadedSilo()
{
await ElasticityGrainPlacementTest(
g =>
g.LatchOverloaded(),
g =>
g.UnlatchOverloaded(),
"LoadAwareGrainShouldNotAttemptToCreateActivationsOnOverloadedSilo",
"A grain instantiated with the load-aware placement strategy should not attempt to create activations on an overloaded silo.");
}
[Fact, TestCategory("Functional")]
public async Task LoadAwareGrainShouldNotAttemptToCreateActivationsOnBusySilos()
{
// a CPU usage of 110% will disqualify a silo from getting new grains.
const float undesirability = (float)110.0;
await ElasticityGrainPlacementTest(
g =>
g.LatchCpuUsage(undesirability),
g =>
g.UnlatchCpuUsage(),
"LoadAwareGrainShouldNotAttemptToCreateActivationsOnBusySilos",
"A grain instantiated with the load-aware placement strategy should not attempt to create activations on a busy silo.");
}
private async Task<IPlacementTestGrain> GetGrainAtSilo(SiloAddress silo)
{
while (true)
{
IPlacementTestGrain grain = this.GrainFactory.GetGrain<IRandomPlacementTestGrain>(Guid.NewGuid());
SiloAddress address = await grain.GetLocation();
if (address.Equals(silo))
return grain;
}
}
private static void AssertIsInRange(int actual, double expected, int leavy)
{
Assert.True(expected - leavy <= actual && actual <= expected + leavy,
String.Format("Expecting a value in the range between {0} and {1}, but instead got {2} outside the range.",
expected - leavy, expected + leavy, actual));
}
private async Task ElasticityGrainPlacementTest(
Func<IPlacementTestGrain, Task> taint,
Func<IPlacementTestGrain, Task> restore,
string name,
string assertMsg)
{
await this.HostedCluster.WaitForLivenessToStabilizeAsync();
logger.Info("********************** Starting the test {0} ******************************", name);
var taintedSilo = this.HostedCluster.StartAdditionalSilo();
const long sampleSize = 10;
var taintedGrain = await GetGrainAtSilo(taintedSilo.SiloAddress);
var testGrains =
Enumerable.Range(0, (int)sampleSize).
Select(
n =>
this.GrainFactory.GetGrain<IActivationCountBasedPlacementTestGrain>(Guid.NewGuid()));
// make the grain's silo undesirable for new grains.
taint(taintedGrain).Wait();
List<IPEndPoint> actual;
try
{
actual =
testGrains.Select(
g =>
g.GetEndpoint().Result).ToList();
}
finally
{
// i don't know if this necessary but to be safe, i'll restore the silo's desirability.
logger.Info("********************** Finalizing the test {0} ******************************", name);
restore(taintedGrain).Wait();
}
var unexpected = taintedSilo.SiloAddress.Endpoint;
Assert.True(
actual.All(
i =>
!i.Equals(unexpected)),
assertMsg);
}
private Task AddTestGrains(int amount)
{
var promises = new List<Task>();
for (var i = 0; i < amount; i++)
{
IActivationCountBasedPlacementTestGrain grain = this.GrainFactory.GetGrain<IActivationCountBasedPlacementTestGrain>(Guid.NewGuid());
this.grains.Add(grain);
// Make sure we activate grain:
promises.Add(grain.Nop());
}
return Task.WhenAll(promises);
}
private Task InvokeAllGrains()
{
var promises = new List<Task>();
foreach (var grain in grains)
{
promises.Add(grain.Nop());
}
return Task.WhenAll(promises);
}
private async Task<Dictionary<SiloHandle, int>> GetPerSiloActivationCounts()
{
string fullTypeName = "UnitTests.Grains.ActivationCountBasedPlacementTestGrain";
IManagementGrain mgmtGrain = this.GrainFactory.GetGrain<IManagementGrain>(0);
SimpleGrainStatistic[] stats = await mgmtGrain.GetSimpleGrainStatistics();
return this.HostedCluster.GetActiveSilos()
.ToDictionary(
s => s,
s => stats
.Where(stat => stat.SiloAddress.Equals(s.SiloAddress) && stat.GrainType == fullTypeName)
.Select(stat => stat.ActivationCount).SingleOrDefault());
}
private void LogCounts(Dictionary<SiloHandle, int> activationCounts)
{
var sb = new StringBuilder();
foreach (var silo in this.HostedCluster.GetActiveSilos())
{
int count;
activationCounts.TryGetValue(silo, out count);
sb.AppendLine($"{silo.Name}.ActivationCount = {count}");
}
logger.Info(sb.ToString());
}
}
}
| |
using System;
using System.Collections;
using System.Web.UI;
namespace PrimerProObjects
{
/// <summary>
///
/// </summary>
public class Grapheme : System.Object
{
private string m_Symbol;
private string m_UpperCase;
private string m_Key;
private bool m_IsConsonant;
private bool m_IsVowel;
private bool m_IsTone;
private bool m_IsSyllograph;
private bool m_IsSyllabicConsonant;
private bool m_IsComplex;
private ArrayList m_ComplexComponents; //arraylist of strings (symbols)
private int m_CountInWordList;
private int m_CountInTextData;
public enum GraphemeType { None, Consonant, Vowel, Tone, Syllograph };
public Grapheme(string strSymbol)
{
m_Symbol = strSymbol;
m_UpperCase = "";
m_Key = GetKey();
m_IsConsonant = false;
m_IsVowel = false;
m_IsTone = false;
m_IsSyllograph = false;
m_IsSyllabicConsonant = false;
m_IsComplex = false;
m_ComplexComponents = null;
m_CountInWordList = 0;
m_CountInTextData = 0;
}
public string Symbol
{
get {return m_Symbol;}
set {m_Symbol = value;}
}
public string UpperCase
{
get {return m_UpperCase;}
set {m_UpperCase = value;}
}
public string Key
{
get {return m_Key;}
set { m_Key = value; }
}
public bool IsConsonant
{
get {return m_IsConsonant;}
set {m_IsConsonant = value;}
}
public bool IsVowel
{
get {return m_IsVowel;}
set {m_IsVowel= value;}
}
public bool IsTone
{
get {return m_IsTone;}
set {m_IsTone = value;}
}
public bool IsSyllograph
{
get { return m_IsSyllograph; }
set { m_IsSyllograph = value; }
}
public bool IsSyllabicConsonant
{
get { return m_IsSyllabicConsonant; }
set { m_IsSyllabicConsonant = value; }
}
public bool IsComplex
{
get { return m_IsComplex; }
set { m_IsComplex = value; }
}
public ArrayList ComplexComponents
{
get { return m_ComplexComponents; }
set { m_ComplexComponents = value; }
}
public int GetSymbolLength()
{
return m_Symbol.Length;
}
public string GetKey()
{
string strKey = "";
char[] aChar;
if (this.Symbol.Trim() != "")
{
aChar = this.Symbol.ToCharArray();
foreach (char ch in aChar)
strKey = strKey + Convert.ToInt32(ch).ToString().PadLeft(6, '0');
}
return strKey;
}
public GraphemeType GetGraphemeType()
{
GraphemeType type = GraphemeType.None;
if (this.IsConsonant)
type = GraphemeType.Consonant;
else if (this.IsVowel)
type = GraphemeType.Vowel;
else if (this.IsTone)
type = GraphemeType.Tone;
else if (this.IsSyllograph)
type = GraphemeType.Syllograph;
return type;
}
public void SetGraphemeType(GraphemeType type)
{
switch (type)
{
case GraphemeType.Consonant:
this.IsConsonant = true;
break;
case GraphemeType.Vowel:
this.IsVowel = true;
break;
case GraphemeType.Tone:
this.IsTone = true;
break;
case GraphemeType.Syllograph:
this.IsSyllograph = true;
break;
default:
break;
}
}
public int GetCountInWordList()
{
return m_CountInWordList;
}
public void InitCountInWordList()
{
m_CountInWordList = 0;
}
public void IncrCountInWordList()
{
m_CountInWordList++;
}
public int GetCountInTextData()
{
return m_CountInTextData;
}
public void InitCountInTextData()
{
m_CountInTextData = 0;
}
public void IncrCountInTextData()
{
m_CountInTextData++;
}
public bool IsSame(Grapheme grf)
{
bool fReturn = false;
if (grf != null)
{
if ((this.Symbol != "") && (grf.Symbol != ""))
{
if (this.Symbol == grf.Symbol)
fReturn = true;
}
}
return fReturn;
}
public bool IsFoundInWord(string strWord)
{
bool fReturn = false;
if ( strWord.IndexOf(m_Symbol) > 0 )
fReturn = true;
return fReturn;
}
public int GetComplexCount()
{
if (m_ComplexComponents == null)
return 0;
else return m_ComplexComponents.Count;
}
public string GetComplexComponent(int n)
{
if (m_ComplexComponents == null)
return null;
if (m_ComplexComponents.Count > 0)
return m_ComplexComponents[n].ToString();
return null;
}
public void AddComplexComponent(string str)
{
if (m_ComplexComponents == null)
m_ComplexComponents = new ArrayList();
m_ComplexComponents.Add(str);
}
}
}
| |
// ReSharper disable PossibleMultipleEnumeration
namespace Gu.Wpf.DataGrid2D
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
/// <summary>
/// A bindable view of a transposed list.
/// </summary>
#pragma warning disable CA1010 // Collections should implement generic interface WPF needs only IList
public class Lists2DTransposedView : Lists2DViewBase
#pragma warning restore CA1010 // Collections should implement generic interface
{
/// <summary>
/// Initializes a new instance of the <see cref="Lists2DTransposedView"/> class.
/// </summary>
/// <param name="source">The <see cref="IEnumerable{IEnumerable}"/>.</param>
public Lists2DTransposedView(IEnumerable<IEnumerable> source)
: base(source)
{
this.MaxColumnCount = source.Count();
var rowCount = this.MaxColumnCount == 0 ? 0 : source.Max(x => x.Count());
this.ColumnIsReadOnlies = source.Select(x => x.Count() != rowCount)
.ToList();
this.ColumnElementTypes = source.Select(x => x.GetElementType())
.ToList();
this.ResetRows();
}
/// <inheritdoc/>
public override bool IsTransposed => true;
internal IReadOnlyList<Type> ColumnElementTypes { get; }
internal IReadOnlyList<bool> ColumnIsReadOnlies { get; }
internal int MaxColumnCount { get; }
/// <inheritdoc/>
public override bool ReceiveWeakEvent(Type managerType, object sender, EventArgs e)
{
if (e is null)
{
throw new ArgumentNullException(nameof(e));
}
if (managerType != typeof(CollectionChangedEventManager))
{
return false;
}
var ccea = (NotifyCollectionChangedEventArgs)e;
if (this.IsColumnsChange(sender, ccea))
{
this.OnColumnsChanged();
return true;
}
_ = base.ReceiveWeakEvent(managerType, sender, e);
if (ReferenceEquals(sender, this.Source))
{
switch (ccea.Action)
{
case NotifyCollectionChangedAction.Add:
case NotifyCollectionChangedAction.Remove:
throw new InvalidOperationException("Should never get here, this is a columns change.");
case NotifyCollectionChangedAction.Replace:
foreach (var row in this.Rows)
{
row.RaiseColumnsChanged(ccea.NewStartingIndex, 1);
}
break;
case NotifyCollectionChangedAction.Move:
foreach (var row in this.Rows)
{
row.RaiseColumnsChanged(ccea.OldStartingIndex, 1);
row.RaiseColumnsChanged(ccea.NewStartingIndex, 1);
}
break;
case NotifyCollectionChangedAction.Reset:
this.ResetRows();
break;
default:
throw new ArgumentOutOfRangeException(nameof(e));
}
}
else if (this.Source is { } source)
{
var changed = (IEnumerable)sender;
var col = source.IndexOf(changed);
switch (ccea.Action)
{
case NotifyCollectionChangedAction.Add:
for (var i = changed.Count() - ccea.NewItems.Count; i < this.Rows.Count; i++)
{
this.Rows[i].RaiseColumnsChanged(col, 1);
}
break;
case NotifyCollectionChangedAction.Remove:
for (var i = changed.Count() - ccea.OldItems.Count; i < this.Rows.Count; i++)
{
this.Rows[i].RaiseColumnsChanged(col, 1);
}
break;
case NotifyCollectionChangedAction.Replace:
this.Rows[ccea.NewStartingIndex].RaiseColumnsChanged(col, 1);
break;
case NotifyCollectionChangedAction.Move:
this.Rows[ccea.NewStartingIndex].RaiseColumnsChanged(col, 1);
this.Rows[ccea.OldStartingIndex].RaiseColumnsChanged(col, 1);
break;
case NotifyCollectionChangedAction.Reset:
foreach (var row in this.Rows)
{
row.RaiseColumnsChanged(col, 1);
}
break;
default:
throw new ArgumentOutOfRangeException(nameof(e));
}
}
return true;
}
/// <inheritdoc/>
protected override ListRowView CreateRow(int index)
{
var propertyDescriptors = this.Rows.Count == 0
? ListIndexPropertyDescriptor.GetRowPropertyDescriptorCollection(this.ColumnElementTypes, this.ColumnIsReadOnlies, this.MaxColumnCount)
: this.Rows[0].GetProperties();
return new ListRowView(this, index, propertyDescriptors);
}
private bool IsColumnsChange(object sender, NotifyCollectionChangedEventArgs e)
{
switch (e.Action)
{
case NotifyCollectionChangedAction.Add:
case NotifyCollectionChangedAction.Remove:
case NotifyCollectionChangedAction.Reset:
break;
case NotifyCollectionChangedAction.Replace:
case NotifyCollectionChangedAction.Move:
return false;
default:
throw new ArgumentOutOfRangeException(nameof(e));
}
if (ReferenceEquals(sender, this.Source) ||
this.Source is null)
{
return true;
}
var index = 0;
foreach (var row in this.Source)
{
var count = row.Count();
if (count == this.Rows.Count && this.ColumnIsReadOnlies[index])
{
return true;
}
if (count != this.Rows.Count && this.ColumnIsReadOnlies[index] == false)
{
return true;
}
index++;
}
return false;
}
private void ResetRows()
{
var source = this.Source;
this.Rows.Clear();
if (source is null || !source.Any())
{
this.OnCollectionChanged(NotifyCollectionResetEventArgs);
return;
}
var rowCount = source.Max(x => x.Count());
for (var i = 0; i < rowCount; i++)
{
var listRowView = this.CreateRow(i);
this.Rows.Add(listRowView);
}
this.OnPropertyChanged(CountPropertyChangedEventArgs);
this.OnPropertyChanged(IndexerPropertyChangedEventArgs);
this.OnCollectionChanged(NotifyCollectionResetEventArgs);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Akka.Util;
using Docker.DotNet;
using Docker.DotNet.Models;
using Xunit;
namespace Akka.Streams.Kafka.Tests
{
[CollectionDefinition(Name)]
public sealed class KafkaSpecsFixture : ICollectionFixture<KafkaFixture>
{
public const string Name = "KafkaSpecs";
}
public class KafkaFixture : IAsyncLifetime
{
private const string KafkaImageName = "confluentinc/cp-kafka";
private const string KafkaImageTag = "5.3.0";
private const string ZookeeperImageName = "confluentinc/cp-zookeeper";
private const string ZookeeperImageTag = "5.3.0";
private const string KafkaContainerNameBase = "akka.net-kafka-test";
private const string ZookeeperContainerNameBase = "akka.net-zookeeper-test";
private const string NetworkNameBase = "akka.net-network-test";
private readonly string _kafkaContainerName = $"{KafkaContainerNameBase}-{Guid.NewGuid():N}";
private readonly string _zookeeperContainerName = $"{ZookeeperContainerNameBase}-{Guid.NewGuid():N}";
private readonly string _networkName = $"{NetworkNameBase}-{Guid.NewGuid():N}";
private readonly DockerClient _client;
public KafkaFixture()
{
DockerClientConfiguration config;
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
config = new DockerClientConfiguration(new Uri("unix://var/run/docker.sock"));
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
config = new DockerClientConfiguration(new Uri("npipe://./pipe/docker_engine"));
else
throw new NotSupportedException($"Unsupported OS [{RuntimeInformation.OSDescription}]");
_client = config.CreateClient();
if (TestsConfiguration.UseExistingDockerContainer)
{
KafkaPort = 29092;
}
}
public int KafkaPort { get; private set; }
public string KafkaServer => $"127.0.0.1:{KafkaPort}";
public async Task InitializeAsync()
{
if (TestsConfiguration.UseExistingDockerContainer)
{
// When using existing container, no actions should be performed on startup
return;
}
// Load images, if they not exist yet
await EnsureImageExists(ZookeeperImageName, ZookeeperImageTag);
await EnsureImageExists(KafkaImageName, KafkaImageTag);
// Generate random ports for zookeeper and kafka
var zookeeperPort = ThreadLocalRandom.Current.Next(32000, 33000);
KafkaPort = ThreadLocalRandom.Current.Next(28000, 29000);
// Make resources cleanup before allocating new containers/networks
await ResourceCleanup();
// create the containers
await CreateContainer(ZookeeperImageName, ZookeeperImageTag, _zookeeperContainerName, zookeeperPort, new Dictionary<string, string>()
{
["ZOOKEEPER_CLIENT_PORT"] = zookeeperPort.ToString(),
["ZOOKEEPER_TICK_TIME"] = "2000",
});
await CreateContainer(KafkaImageName, KafkaImageTag, _kafkaContainerName, KafkaPort, new Dictionary<string, string>()
{
["KAFKA_BROKER_ID"] = "1",
["KAFKA_NUM_PARTITIONS"] = "3",
["KAFKA_ZOOKEEPER_CONNECT"] = $"{_zookeeperContainerName}:{zookeeperPort}", // referencing zookeeper container directly in common docker network
["KAFKA_LISTENERS"] = $"PLAINTEXT://:{KafkaPort}",
["KAFKA_ADVERTISED_LISTENERS"] = $"PLAINTEXT://127.0.0.1:{KafkaPort}",
["KAFKA_AUTO_CREATE_TOPICS_ENABLE"] = "true",
["KAFKA_DELETE_TOPIC_ENABLE"] = "true",
["KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR"] = "1",
["KAFKA_OPTS"] = "-Djava.net.preferIPv4Stack=True"
});
// Setting up network for containers to communicate
var network = await _client.Networks.CreateNetworkAsync(new NetworksCreateParameters(new NetworkCreate())
{
Name = _networkName
});
await _client.Networks.ConnectNetworkAsync(network.ID, new NetworkConnectParameters()
{
Container = _kafkaContainerName
});
await _client.Networks.ConnectNetworkAsync(network.ID, new NetworkConnectParameters()
{
Container = _zookeeperContainerName
});
// start the containers
await _client.Containers.StartContainerAsync(_zookeeperContainerName, new ContainerStartParameters());
await _client.Containers.StartContainerAsync(_kafkaContainerName, new ContainerStartParameters());
// Provide a 10 second startup delay
await Task.Delay(TimeSpan.FromSeconds(10));
}
public async Task DisposeAsync()
{
if (_client != null)
{
// Shutdown running containers only when we were not using pre-existing container
if (!TestsConfiguration.UseExistingDockerContainer)
{
await ResourceCleanup();
}
_client.Dispose();
}
}
/// <summary>
/// This performs cleanup of allocated containers/networks during tests
/// </summary>
/// <returns></returns>
private async Task ResourceCleanup()
{
if (_client == null)
return;
// This task loads list of containers and stops/removes those which were started during tests
var containerCleanupTask = _client.Containers.ListContainersAsync(new ContainersListParameters()).ContinueWith(
async t =>
{
if (t.IsFaulted)
return;
var containersToStop = t.Result.Where(c => c.Names.Any(name => name.Contains(KafkaContainerNameBase)) ||
c.Names.Any(name => name.Contains(ZookeeperContainerNameBase)));
var stopTasks = containersToStop.Select(async container =>
{
await _client.Containers.StopContainerAsync(container.ID, new ContainerStopParameters());
await _client.Containers.RemoveContainerAsync(container.ID, new ContainerRemoveParameters { Force = true });
});
await Task.WhenAll(stopTasks);
}).Unwrap();
// This tasks loads docker networks and removes those which were started during tests
var networkCleanupTask = _client.Networks.ListNetworksAsync(new NetworksListParameters()).ContinueWith(
async t =>
{
if (t.IsFaulted)
return;
var networksToDelete = t.Result.Where(network => network.Name.Contains(NetworkNameBase));
var deleteTasks = networksToDelete.Select(network => _client.Networks.DeleteNetworkAsync(network.ID));
await Task.WhenAll(deleteTasks);
});
try
{
// Wait until cleanup is finished
await Task.WhenAll(containerCleanupTask, networkCleanupTask);
}
catch { /* If the cleanup failes, this is not the reason to fail tests */ }
}
private async Task CreateContainer(string imageName, string imageTag, string containerName, int portToExpose, Dictionary<string, string> env)
{
await _client.Containers.CreateContainerAsync(new CreateContainerParameters
{
Image = $"{imageName}:{imageTag}",
Name = containerName,
Tty = true,
ExposedPorts = new Dictionary<string, EmptyStruct>
{
{$"{portToExpose}/tcp", new EmptyStruct()}
},
HostConfig = new HostConfig
{
PortBindings = new Dictionary<string, IList<PortBinding>>
{
{
$"{portToExpose}/tcp",
new List<PortBinding>
{
new PortBinding
{
HostPort = $"{portToExpose}"
}
}
}
},
ExtraHosts = new [] { "localhost:127.0.0.1" },
},
Env = env.Select(pair => $"{pair.Key}={pair.Value}").ToArray(),
});
}
private async Task EnsureImageExists(string imageName, string imageTag)
{
var existingImages = await _client.Images.ListImagesAsync(
new ImagesListParameters
{
Filters = new Dictionary<string, IDictionary<string, bool>>
{
{
"reference",
new Dictionary<string, bool>
{
{$"{imageName}:{imageTag}", true}
}
}
}
});
if (existingImages.Count == 0)
{
await _client.Images.CreateImageAsync(
new ImagesCreateParameters { FromImage = imageName, Tag = imageTag }, null,
new Progress<JSONMessage>(message =>
{
Console.WriteLine(!string.IsNullOrEmpty(message.ErrorMessage)
? message.ErrorMessage
: $"{message.ID} {message.Status} {message.ProgressMessage}");
}));
}
}
}
}
| |
namespace SimpleErrorHandler
{
using System;
using ReaderWriterLock = System.Threading.ReaderWriterLock;
using Timeout = System.Threading.Timeout;
using NameObjectCollectionBase = System.Collections.Specialized.NameObjectCollectionBase;
using IList = System.Collections.IList;
using IDictionary = System.Collections.IDictionary;
using CultureInfo = System.Globalization.CultureInfo;
/// <summary>
/// An <see cref="ErrorLog"/> implementation that uses memory as its backing store.
/// </summary>
/// <remarks>
/// All <see cref="MemoryErrorLog"/> instances will share the same memory
/// store that is bound to the application (not an instance of this class).
/// </remarks>
public sealed class MemoryErrorLog : ErrorLog
{
// The collection that provides the actual storage for this log
// implementation and a lock to guarantee concurrency correctness.
private static EntryCollection _entries;
private readonly static ReaderWriterLock _lock = new ReaderWriterLock();
// IMPORTANT! The size must be the same for all instances
// for the entires collection to be intialized correctly.
private int _size;
/// <summary>
/// The maximum number of errors that will ever be allowed to be stored
/// in memory.
/// </summary>
public static readonly int MaximumSize = 500;
/// <summary>
/// The maximum number of errors that will be held in memory by default
/// if no size is specified.
/// </summary>
public static readonly int DefaultSize = 50;
/// <summary>
/// Initializes a new instance of the <see cref="MemoryErrorLog"/> class
/// with a default size for maximum recordable entries.
/// </summary>
public MemoryErrorLog() : this(DefaultSize) { }
/// <summary>
/// Initializes a new instance of the <see cref="MemoryErrorLog"/> class
/// with a specific size for maximum recordable entries.
/// </summary>
public MemoryErrorLog(int size)
{
if (size < 0 || size > MaximumSize) throw new ArgumentOutOfRangeException("size");
_size = size;
}
/// <summary>
/// Initializes a new instance of the <see cref="MemoryErrorLog"/> class
/// using a dictionary of configured settings.
/// </summary>
public MemoryErrorLog(IDictionary config)
{
if (config == null)
{
_size = DefaultSize;
return;
}
string sizeString = (string)config["size"] ?? "";
if (sizeString.Length == 0)
{
_size = DefaultSize;
return;
}
_size = Convert.ToInt32(sizeString, CultureInfo.InvariantCulture);
_size = Math.Max(0, Math.Min(MaximumSize, _size));
}
/// <summary>
/// Gets the name of this error log implementation.
/// </summary>
public override string Name
{
get { return "In-Memory Error Log"; }
}
public override bool DeleteError(string id)
{
throw new NotImplementedException();
}
public override bool ProtectError(string id)
{
throw new NotImplementedException();
}
/// <summary>
/// Logs an error to the application memory.
/// </summary>
/// <remarks>
/// If the log is full then the oldest error entry is removed.
/// </remarks>
public override void Log(Error error)
{
if (error == null) throw new ArgumentNullException("error");
// Make a copy of the error to log since the source is mutable.
error = (Error)((ICloneable)error).Clone();
error.ApplicationName = this.ApplicationName;
Guid newId = Guid.NewGuid();
ErrorLogEntry entry = new ErrorLogEntry(this, newId.ToString(), error);
_lock.AcquireWriterLock(Timeout.Infinite);
try
{
if (_entries == null)
{
_entries = new EntryCollection(_size);
}
_entries.Add(newId, entry);
}
finally
{
_lock.ReleaseWriterLock();
}
}
/// <summary>
/// Returns the specified error from application memory, or null if it does not exist.
/// </summary>
public override ErrorLogEntry GetError(string id)
{
_lock.AcquireReaderLock(Timeout.Infinite);
ErrorLogEntry entry;
try
{
if (_entries == null)
{
return null;
}
entry = _entries[id];
}
finally
{
_lock.ReleaseReaderLock();
}
if (entry == null)
{
return null;
}
// Return a copy that the caller can party on.
Error error = (Error)((ICloneable)entry.Error).Clone();
return new ErrorLogEntry(this, entry.Id, error);
}
/// <summary>
/// Returns a page of errors from the application memory in descending order of logged time.
/// </summary>
public override int GetErrors(int pageIndex, int pageSize, IList errorEntryList)
{
if (pageIndex < 0) throw new ArgumentOutOfRangeException("pageIndex");
if (pageSize < 0) throw new ArgumentOutOfRangeException("pageSite");
//
// To minimize the time for which we hold the lock, we'll first
// grab just references to the entries we need to return. Later,
// we'll make copies and return those to the caller. Since Error
// is mutable, we don't want to return direct references to our
// internal versions since someone could change their state.
//
ErrorLogEntry[] selectedEntries;
int totalCount;
_lock.AcquireReaderLock(Timeout.Infinite);
try
{
if (_entries == null)
{
return 0;
}
int lastIndex = Math.Max(0, _entries.Count - (pageIndex * pageSize)) - 1;
selectedEntries = new ErrorLogEntry[lastIndex + 1];
int sourceIndex = lastIndex;
int targetIndex = 0;
while (sourceIndex >= 0)
{
selectedEntries[targetIndex++] = _entries[sourceIndex--];
}
totalCount = _entries.Count;
}
finally
{
_lock.ReleaseReaderLock();
}
// Return copies of fetched entries. If the Error class would
// be immutable then this step wouldn't be necessary.
foreach (ErrorLogEntry entry in selectedEntries)
{
Error error = (Error)((ICloneable)entry.Error).Clone();
errorEntryList.Add(new ErrorLogEntry(this, entry.Id, error));
}
return totalCount;
}
private class EntryCollection : NameObjectCollectionBase
{
private int _size;
public EntryCollection(int size) : base(size)
{
_size = size;
}
public ErrorLogEntry this[int index]
{
get { return (ErrorLogEntry)BaseGet(index); }
}
public ErrorLogEntry this[Guid id]
{
get { return (ErrorLogEntry)BaseGet(id.ToString()); }
}
public ErrorLogEntry this[string id]
{
get { return this[new Guid(id)]; }
}
public void Add(Guid id, ErrorLogEntry entry)
{
if (this.Count == _size)
{
BaseRemoveAt(0);
}
BaseAdd(entry.Id, entry);
}
}
}
}
| |
// /*
// * Copyright (c) 2016, Alachisoft. 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.
// */
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.ProtocolBuffers;
using pbc = global::Google.ProtocolBuffers.Collections;
using pbd = global::Google.ProtocolBuffers.Descriptors;
using scg = global::System.Collections.Generic;
namespace Alachisoft.NosDB.Common.Protobuf {
namespace Proto {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static partial class DatabaseConfig {
#region Extension registration
public static void RegisterAllExtensions(pb::ExtensionRegistry registry) {
}
#endregion
#region Static variables
internal static pbd::MessageDescriptor internal__static_Alachisoft_NosDB_Common_Protobuf_DatabaseConfig__Descriptor;
internal static pb::FieldAccess.FieldAccessorTable<global::Alachisoft.NosDB.Common.Protobuf.DatabaseConfig, global::Alachisoft.NosDB.Common.Protobuf.DatabaseConfig.Builder> internal__static_Alachisoft_NosDB_Common_Protobuf_DatabaseConfig__FieldAccessorTable;
#endregion
#region Descriptor
public static pbd::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbd::FileDescriptor descriptor;
static DatabaseConfig() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"ChREYXRhYmFzZUNvbmZpZy5wcm90bxIgQWxhY2hpc29mdC5Ob3NEQi5Db21t",
"b24uUHJvdG9idWYaE1N0b3JhZ2VDb25maWcucHJvdG8iYAoORGF0YWJhc2VD",
"b25maWcSDAoEbmFtZRgBIAEoCRJACgdzdG9yYWdlGAIgASgLMi8uQWxhY2hp",
"c29mdC5Ob3NEQi5Db21tb24uUHJvdG9idWYuU3RvcmFnZUNvbmZpZ0I+CiRj",
"b20uYWxhY2hpc29mdC5ub3NkYi5jb21tb24ucHJvdG9idWZCFkRhdGFiYXNl",
"Q29uZmlnUHJvdG9jb2w="));
pbd::FileDescriptor.InternalDescriptorAssigner assigner = delegate(pbd::FileDescriptor root) {
descriptor = root;
internal__static_Alachisoft_NosDB_Common_Protobuf_DatabaseConfig__Descriptor = Descriptor.MessageTypes[0];
internal__static_Alachisoft_NosDB_Common_Protobuf_DatabaseConfig__FieldAccessorTable =
new pb::FieldAccess.FieldAccessorTable<global::Alachisoft.NosDB.Common.Protobuf.DatabaseConfig, global::Alachisoft.NosDB.Common.Protobuf.DatabaseConfig.Builder>(internal__static_Alachisoft_NosDB_Common_Protobuf_DatabaseConfig__Descriptor,
new string[] { "Name", "Storage", });
return null;
};
pbd::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData,
new pbd::FileDescriptor[] {
global::Alachisoft.NosDB.Common.Protobuf.Proto.StorageConfig.Descriptor,
}, assigner);
}
#endregion
}
}
#region Messages
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class DatabaseConfig : pb::GeneratedMessage<DatabaseConfig, DatabaseConfig.Builder> {
private DatabaseConfig() { }
private static readonly DatabaseConfig defaultInstance = new DatabaseConfig().MakeReadOnly();
private static readonly string[] _databaseConfigFieldNames = new string[] { "name", "storage" };
private static readonly uint[] _databaseConfigFieldTags = new uint[] { 10, 18 };
public static DatabaseConfig DefaultInstance {
get { return defaultInstance; }
}
public override DatabaseConfig DefaultInstanceForType {
get { return DefaultInstance; }
}
protected override DatabaseConfig ThisMessage {
get { return this; }
}
public static pbd::MessageDescriptor Descriptor {
get { return global::Alachisoft.NosDB.Common.Protobuf.Proto.DatabaseConfig.internal__static_Alachisoft_NosDB_Common_Protobuf_DatabaseConfig__Descriptor; }
}
protected override pb::FieldAccess.FieldAccessorTable<DatabaseConfig, DatabaseConfig.Builder> InternalFieldAccessors {
get { return global::Alachisoft.NosDB.Common.Protobuf.Proto.DatabaseConfig.internal__static_Alachisoft_NosDB_Common_Protobuf_DatabaseConfig__FieldAccessorTable; }
}
public const int NameFieldNumber = 1;
private bool hasName;
private string name_ = "";
public bool HasName {
get { return hasName; }
}
public string Name {
get { return name_; }
}
public const int StorageFieldNumber = 2;
private bool hasStorage;
private global::Alachisoft.NosDB.Common.Protobuf.StorageConfig storage_;
public bool HasStorage {
get { return hasStorage; }
}
public global::Alachisoft.NosDB.Common.Protobuf.StorageConfig Storage {
get { return storage_ ?? global::Alachisoft.NosDB.Common.Protobuf.StorageConfig.DefaultInstance; }
}
public override bool IsInitialized {
get {
return true;
}
}
public override void WriteTo(pb::ICodedOutputStream output) {
CalcSerializedSize();
string[] field_names = _databaseConfigFieldNames;
if (hasName) {
output.WriteString(1, field_names[0], Name);
}
if (hasStorage) {
output.WriteMessage(2, field_names[1], Storage);
}
UnknownFields.WriteTo(output);
}
private int memoizedSerializedSize = -1;
public override int SerializedSize {
get {
int size = memoizedSerializedSize;
if (size != -1) return size;
return CalcSerializedSize();
}
}
private int CalcSerializedSize() {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
if (hasName) {
size += pb::CodedOutputStream.ComputeStringSize(1, Name);
}
if (hasStorage) {
size += pb::CodedOutputStream.ComputeMessageSize(2, Storage);
}
size += UnknownFields.SerializedSize;
memoizedSerializedSize = size;
return size;
}
public static DatabaseConfig ParseFrom(pb::ByteString data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static DatabaseConfig ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static DatabaseConfig ParseFrom(byte[] data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static DatabaseConfig ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static DatabaseConfig ParseFrom(global::System.IO.Stream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static DatabaseConfig ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
public static DatabaseConfig ParseDelimitedFrom(global::System.IO.Stream input) {
return CreateBuilder().MergeDelimitedFrom(input).BuildParsed();
}
public static DatabaseConfig ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed();
}
public static DatabaseConfig ParseFrom(pb::ICodedInputStream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static DatabaseConfig ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
private DatabaseConfig MakeReadOnly() {
return this;
}
public static Builder CreateBuilder() { return new Builder(); }
public override Builder ToBuilder() { return CreateBuilder(this); }
public override Builder CreateBuilderForType() { return new Builder(); }
public static Builder CreateBuilder(DatabaseConfig prototype) {
return new Builder(prototype);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class Builder : pb::GeneratedBuilder<DatabaseConfig, Builder> {
protected override Builder ThisBuilder {
get { return this; }
}
public Builder() {
result = DefaultInstance;
resultIsReadOnly = true;
}
internal Builder(DatabaseConfig cloneFrom) {
result = cloneFrom;
resultIsReadOnly = true;
}
private bool resultIsReadOnly;
private DatabaseConfig result;
private DatabaseConfig PrepareBuilder() {
if (resultIsReadOnly) {
DatabaseConfig original = result;
result = new DatabaseConfig();
resultIsReadOnly = false;
MergeFrom(original);
}
return result;
}
public override bool IsInitialized {
get { return result.IsInitialized; }
}
protected override DatabaseConfig MessageBeingBuilt {
get { return PrepareBuilder(); }
}
public override Builder Clear() {
result = DefaultInstance;
resultIsReadOnly = true;
return this;
}
public override Builder Clone() {
if (resultIsReadOnly) {
return new Builder(result);
} else {
return new Builder().MergeFrom(result);
}
}
public override pbd::MessageDescriptor DescriptorForType {
get { return global::Alachisoft.NosDB.Common.Protobuf.DatabaseConfig.Descriptor; }
}
public override DatabaseConfig DefaultInstanceForType {
get { return global::Alachisoft.NosDB.Common.Protobuf.DatabaseConfig.DefaultInstance; }
}
public override DatabaseConfig BuildPartial() {
if (resultIsReadOnly) {
return result;
}
resultIsReadOnly = true;
return result.MakeReadOnly();
}
public override Builder MergeFrom(pb::IMessage other) {
if (other is DatabaseConfig) {
return MergeFrom((DatabaseConfig) other);
} else {
base.MergeFrom(other);
return this;
}
}
public override Builder MergeFrom(DatabaseConfig other) {
if (other == global::Alachisoft.NosDB.Common.Protobuf.DatabaseConfig.DefaultInstance) return this;
PrepareBuilder();
if (other.HasName) {
Name = other.Name;
}
if (other.HasStorage) {
MergeStorage(other.Storage);
}
this.MergeUnknownFields(other.UnknownFields);
return this;
}
public override Builder MergeFrom(pb::ICodedInputStream input) {
return MergeFrom(input, pb::ExtensionRegistry.Empty);
}
public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
PrepareBuilder();
pb::UnknownFieldSet.Builder unknownFields = null;
uint tag;
string field_name;
while (input.ReadTag(out tag, out field_name)) {
if(tag == 0 && field_name != null) {
int field_ordinal = global::System.Array.BinarySearch(_databaseConfigFieldNames, field_name, global::System.StringComparer.Ordinal);
if(field_ordinal >= 0)
tag = _databaseConfigFieldTags[field_ordinal];
else {
if (unknownFields == null) {
unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
}
ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
continue;
}
}
switch (tag) {
case 0: {
throw pb::InvalidProtocolBufferException.InvalidTag();
}
default: {
if (pb::WireFormat.IsEndGroupTag(tag)) {
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
if (unknownFields == null) {
unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
}
ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
break;
}
case 10: {
result.hasName = input.ReadString(ref result.name_);
break;
}
case 18: {
global::Alachisoft.NosDB.Common.Protobuf.StorageConfig.Builder subBuilder = global::Alachisoft.NosDB.Common.Protobuf.StorageConfig.CreateBuilder();
if (result.hasStorage) {
subBuilder.MergeFrom(Storage);
}
input.ReadMessage(subBuilder, extensionRegistry);
Storage = subBuilder.BuildPartial();
break;
}
}
}
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
public bool HasName {
get { return result.hasName; }
}
public string Name {
get { return result.Name; }
set { SetName(value); }
}
public Builder SetName(string value) {
pb::ThrowHelper.ThrowIfNull(value, "value");
PrepareBuilder();
result.hasName = true;
result.name_ = value;
return this;
}
public Builder ClearName() {
PrepareBuilder();
result.hasName = false;
result.name_ = "";
return this;
}
public bool HasStorage {
get { return result.hasStorage; }
}
public global::Alachisoft.NosDB.Common.Protobuf.StorageConfig Storage {
get { return result.Storage; }
set { SetStorage(value); }
}
public Builder SetStorage(global::Alachisoft.NosDB.Common.Protobuf.StorageConfig value) {
pb::ThrowHelper.ThrowIfNull(value, "value");
PrepareBuilder();
result.hasStorage = true;
result.storage_ = value;
return this;
}
public Builder SetStorage(global::Alachisoft.NosDB.Common.Protobuf.StorageConfig.Builder builderForValue) {
pb::ThrowHelper.ThrowIfNull(builderForValue, "builderForValue");
PrepareBuilder();
result.hasStorage = true;
result.storage_ = builderForValue.Build();
return this;
}
public Builder MergeStorage(global::Alachisoft.NosDB.Common.Protobuf.StorageConfig value) {
pb::ThrowHelper.ThrowIfNull(value, "value");
PrepareBuilder();
if (result.hasStorage &&
result.storage_ != global::Alachisoft.NosDB.Common.Protobuf.StorageConfig.DefaultInstance) {
result.storage_ = global::Alachisoft.NosDB.Common.Protobuf.StorageConfig.CreateBuilder(result.storage_).MergeFrom(value).BuildPartial();
} else {
result.storage_ = value;
}
result.hasStorage = true;
return this;
}
public Builder ClearStorage() {
PrepareBuilder();
result.hasStorage = false;
result.storage_ = null;
return this;
}
}
static DatabaseConfig() {
object.ReferenceEquals(global::Alachisoft.NosDB.Common.Protobuf.Proto.DatabaseConfig.Descriptor, null);
}
}
#endregion
}
#endregion Designer generated code
| |
/*
Copyright (c) 2004-2006 Tomas Matousek, Ladislav Prosek, Vaclav Novak and Martin Maly.
The use and distribution terms for this software are contained in the file named License.txt,
which can be found in the root of the Phalanger distribution. By using this software
in any fashion, you are agreeing to be bound by the terms of this license.
You must not remove this notice from this software.
*/
using System;
using System.IO;
using System.Diagnostics;
using System.Reflection.Emit;
using PHP.Core.AST;
using PHP.Core.Emit;
using PHP.Core.Parsers;
using PHP.Core.Reflection;
namespace PHP.Core.Compiler.AST
{
partial class NodeCompilers
{
#region StaticFieldUse
[NodeCompiler(typeof(StaticFieldUse))]
abstract class StaticFieldUseCompiler<T> : VariableUseCompiler<T> where T : StaticFieldUse
{
protected DType/*!*/ type;
/// <summary>
/// Points to a method that emits code to be placed after the new static field value has
/// been loaded on the evaluation stack.
/// </summary>
internal AssignmentCallback assignmentCallback;
public override Evaluation Analyze(T node, Analyzer analyzer, ExInfoFromParent info)
{
access = info.Access;
TypeRefHelper.Analyze(node.TypeRef, analyzer);
this.type = TypeRefHelper.ResolvedTypeOrUnknown(node.TypeRef);
analyzer.AnalyzeConstructedType(type);
return new Evaluation(node);
}
#region Emit, EmitAssign, EmitIsset, EmitRead, EmitWrite, EmitEnsure
public override PhpTypeCode Emit(T/*!*/node, CodeGenerator/*!*/codeGenerator)
{
Statistics.AST.AddNode("FieldUse.Static");
ChainBuilder chain = codeGenerator.ChainBuilder;
PhpTypeCode result = PhpTypeCode.Invalid;
switch (codeGenerator.SelectAccess(access))
{
case AccessType.Read:
result = EmitRead(node, codeGenerator, false);
if (chain.IsMember) chain.Lengthen();
break;
case AccessType.ReadUnknown:
result = EmitRead(node, codeGenerator, true);
if (chain.IsMember) chain.Lengthen();
break;
case AccessType.ReadRef:
if (chain.IsMember)
{
chain.Lengthen();
result = EmitRead(node, codeGenerator, false);
}
else
{
result = EmitRead(node, codeGenerator, true);
}
break;
case AccessType.Write:
if (chain.IsMember)
{
result = EmitEnsure(node, codeGenerator, chain);
chain.Lengthen();
}
else
{
assignmentCallback = EmitWrite(node, codeGenerator, false);
result = PhpTypeCode.Unknown;
}
break;
case AccessType.WriteRef:
if (chain.IsMember)
{
result = EmitEnsure(node, codeGenerator, chain);
chain.Lengthen();
}
else
{
assignmentCallback = EmitWrite(node, codeGenerator, true);
result = PhpTypeCode.Unknown;
}
break;
case AccessType.None:
result = PhpTypeCode.Void;
break;
}
return result;
}
internal override PhpTypeCode EmitAssign(T/*!*/node, CodeGenerator codeGenerator)
{
switch (access)
{
case AccessType.Write:
case AccessType.WriteRef:
case AccessType.WriteAndReadRef:
case AccessType.WriteAndReadUnknown:
case AccessType.ReadAndWrite:
case AccessType.ReadAndWriteAndReadRef:
case AccessType.ReadAndWriteAndReadUnknown:
// finish the assignment by invoking the callback obtained in Emit
assignmentCallback(codeGenerator, PhpTypeCode.Object);
break;
default:
Debug.Fail(null);
break;
}
return PhpTypeCode.Void;
}
internal override PhpTypeCode EmitIsset(T/*!*/node, CodeGenerator codeGenerator, bool empty)
{
Debug.Assert(access == AccessType.Read);
// Do not report error messages
codeGenerator.ChainBuilder.QuietRead = true;
// Emit as if the node is read
return this.Emit(node, codeGenerator);
}
internal abstract PhpTypeCode EmitRead(T/*!*/node, CodeGenerator/*!*/ codeGenerator, bool wantRef);
internal abstract AssignmentCallback EmitWrite(T/*!*/node, CodeGenerator/*!*/ codeGenerator, bool writeRef);
internal abstract PhpTypeCode EmitEnsure(T/*!*/node, CodeGenerator/*!*/ codeGenerator, ChainBuilder/*!*/ chain);
#endregion
}
#endregion
#region DirectStFldUse
[NodeCompiler(typeof(DirectStFldUse))]
sealed class DirectStFldUseCompiler : StaticFieldUseCompiler<DirectStFldUse>
{
private DProperty property;
private bool runtimeVisibilityCheck;
public override Evaluation Analyze(DirectStFldUse node, Analyzer analyzer, ExInfoFromParent info)
{
base.Analyze(node, analyzer, info);
property = analyzer.ResolveProperty(type, node.PropertyName, node.Span, true, analyzer.CurrentType, analyzer.CurrentRoutine, out runtimeVisibilityCheck);
return new Evaluation(node);
}
#region EmitRead, EmitWrite, EmitEnsure, EmitUnset
/// <summary>
/// Emits IL instructions that read the value of a static field.
/// </summary>
/// <param name="node">Instance.</param>
/// <param name="codeGenerator">The current <see cref="CodeGenerator"/>.</param>
/// <param name="wantRef">If <B>false</B> the field value should be left on the evaluation stack,
/// if <B>true</B> the <see cref="PhpReference"/> should be left on the evaluation stack.</param>
/// <remarks>
/// Nothing is expected on the evaluation stack. A <see cref="PhpReference"/> (if <paramref name="wantRef"/>
/// is <B>true</B>) or the field value itself (if <paramref name="wantRef"/> is <B>false</B>) is left on the
/// evaluation stack (all PHP static fields are <see cref="PhpReference"/>s).
/// </remarks>
internal override PhpTypeCode EmitRead(DirectStFldUse/*!*/node, CodeGenerator/*!*/ codeGenerator, bool wantRef)
{
return property.EmitGet(codeGenerator, null, wantRef, type as ConstructedType, runtimeVisibilityCheck);
}
/// <summary>
/// Emits IL instructions that write a value to a static field.
/// </summary>
/// <param name="node">Instance.</param>
/// <param name="codeGenerator">The current <see cref="CodeGenerator"/>.</param>
/// <param name="writeRef">If <B>true</B> the value being written is a <see cref="PhpReference"/>
/// instance, if <B>false</B> it is an <see cref="Object"/> instance.</param>
/// <returns>Delegate to a method that emits code to be executed when the actual value has been
/// loaded on the evaluation stack (see <see cref="StaticFieldUseCompiler{T}.EmitAssign"/>).</returns>
internal override AssignmentCallback EmitWrite(DirectStFldUse/*!*/node, CodeGenerator/*!*/ codeGenerator, bool writeRef)
{
return property.EmitSet(codeGenerator, null, writeRef, type as ConstructedType, runtimeVisibilityCheck);
}
internal override PhpTypeCode EmitEnsure(DirectStFldUse/*!*/node, CodeGenerator/*!*/ codeGenerator, ChainBuilder/*!*/ chain)
{
// unknown property of a known type reported as an error during analysis
Debug.Assert(!property.IsUnknown ||
property.DeclaringType.IsUnknown ||
!property.DeclaringType.IsDefinite);
// we're only interested in a directly accessible property
return chain.EmitEnsureStaticProperty((runtimeVisibilityCheck) ? null : property, node.TypeRef, node.PropertyName, chain.IsArrayItem);
}
/// <summary>
/// Emits IL instructions that "unset" a static field.
/// </summary>
/// <remarks>
/// <para>
/// Nothing is expected on the evaluation stack. Nothing is left on the evaluation stack.
/// </para>
/// <para>
/// An error throwing code is always emitted because static fields cannot be unset.
/// </para>
/// </remarks>
internal override void EmitUnset(DirectStFldUse/*!*/node, CodeGenerator/*!*/ codeGenerator)
{
property.EmitUnset(codeGenerator, null, type as ConstructedType, runtimeVisibilityCheck);
}
#endregion
}
#endregion
#region IndirectStFldUse
[NodeCompiler(typeof(IndirectStFldUse))]
sealed class IndirectStFldUseCompiler : StaticFieldUseCompiler<IndirectStFldUse>
{
public override Evaluation Analyze(IndirectStFldUse/*!*/node, Analyzer analyzer, ExInfoFromParent info)
{
base.Analyze(node, analyzer, info);
node.FieldNameExpr = node.FieldNameExpr.Analyze(analyzer, ExInfoFromParent.DefaultExInfo).Literalize();
return new Evaluation(node);
}
#region EmitRead, EmitWrite, EmitEnsure, EmitUnset
/// <summary>
/// Emits IL instructions that read the value of a static field.
/// </summary>
/// <param name="node">Instance.</param>
/// <param name="codeGenerator">The current <see cref="CodeGenerator"/>.</param>
/// <param name="wantRef">If <B>false</B> the field value should be left on the evaluation stack,
/// if <B>true</B> the <see cref="PhpReference"/> should be left on the evaluation stack.</param>
/// <remarks>
/// Nothing is expected on the evaluation stack. A <see cref="PhpReference"/> (if <paramref name="wantRef"/>
/// is <B>true</B>) or the field value itself (if <paramref name="wantRef"/> is <B>false</B>) is left on the
/// evaluation stack (all PHP static fields are <see cref="PhpReference"/>s).
/// </remarks>
internal override PhpTypeCode EmitRead(IndirectStFldUse/*!*/node, CodeGenerator codeGenerator, bool wantRef)
{
return codeGenerator.EmitGetStaticPropertyOperator(type, null, node.FieldNameExpr, wantRef);
}
/// <summary>
/// Emits IL instructions that write the value to a static field.
/// </summary>
/// <param name="node">Instance.</param>
/// <param name="codeGenerator">The current <see cref="CodeGenerator"/>.</param>
/// <param name="writeRef">If <B>true</B> the value being written is a <see cref="PhpReference"/>
/// instance, if <B>false</B> it is an <see cref="Object"/> instance.</param>
/// <returns>Delegate to a method that emits code to be executed when the actual value has been
/// loaded on the evaluation stack (see <see cref="StaticFieldUseCompiler{T}.EmitAssign"/>).</returns>
internal override AssignmentCallback EmitWrite(IndirectStFldUse/*!*/node, CodeGenerator codeGenerator, bool writeRef)
{
return codeGenerator.EmitSetStaticPropertyOperator(type, null, node.FieldNameExpr, writeRef);
// obsolete:
//codeGenerator.IL.Emit(OpCodes.Ldstr, className.QualifiedName.ToString());
//codeGenerator.EmitBoxing(fieldNameExpr.Emit(codeGenerator));
//return delegate(CodeGenerator codeGen)
//{
// codeGen.EmitLoadClassContext();
// codeGen.EmitLoadScriptContext();
// codeGen.EmitLoadNamingContext();
// // invoke the operator
// codeGen.IL.EmitCall(OpCodes.Call, Methods.Operators.SetStaticProperty, null);
//};
}
internal override PhpTypeCode EmitEnsure(IndirectStFldUse/*!*/node, CodeGenerator/*!*/ codeGenerator, ChainBuilder chain)
{
return chain.EmitEnsureStaticProperty(node.TypeRef, null, node.FieldNameExpr, chain.IsArrayItem);
}
/// <summary>
/// Emits IL instructions that "unset" a static field.
/// </summary>
/// <remarks>
/// <para>
/// Nothing is expected on the evaluation stack. Nothing is left on the evaluation stack.
/// </para>
/// <para>
/// Call to the <see cref="Operators.UnsetStaticProperty"/> error throwing operator is always emitted because static
/// fields cannot be unset.
/// </para>
/// </remarks>
internal override void EmitUnset(IndirectStFldUse/*!*/node, CodeGenerator codeGenerator)
{
codeGenerator.EmitUnsetStaticPropertyOperator(type, null, node.FieldNameExpr);
}
#endregion
}
#endregion
}
}
| |
using MS.Utility;
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows;
using SR=MS.Internal.PresentationCore.SR;
using SRID=MS.Internal.PresentationCore.SRID;
namespace MS.Internal.Ink.InkSerializedFormat
{
/// <summary>
/// Summary description for HelperMethods.
/// </summary>
internal static class SerializationHelper
{
/// <summary>
/// returns the no of byte it requires to mutlibyte encode a uint value
/// </summary>
/// <param name="Value"></param>
/// <returns></returns>
public static uint VarSize(uint Value)
{
if (Value < 0x80)
return 1;
else if (Value < 0x4000)
return 2;
else if (Value < 0x200000)
return 3;
else if (Value < 0x10000000)
return 4;
else
return 5;
}
/// <summary>
/// MultiByte Encodes an uint Value into the stream
/// </summary>
/// <param name="strm"></param>
/// <param name="Value"></param>
/// <returns></returns>
public static uint Encode(Stream strm, uint Value)
{
ulong ib = 0;
for (; ; )
{
if (Value < 128)
{
strm.WriteByte((byte)Value);
return (uint)(ib + 1);
}
strm.WriteByte((byte)(0x0080 | (Value & 0x7f)));
Value >>= 7;
ib++;
}
}
/// <summary>
/// Multibyte encodes a unsinged long value in the stream
/// </summary>
/// <param name="strm"></param>
/// <param name="ulValue"></param>
/// <returns></returns>
public static uint EncodeLarge(Stream strm, ulong ulValue)
{
uint ib = 0;
for (; ; )
{
if (ulValue < 128)
{
strm.WriteByte((byte)ulValue);
return ib + 1;
}
strm.WriteByte((byte)(0x0080 | (ulValue & 0x7f)));
ulValue >>= 7;
ib++;
}
}
/// <summary>
/// Multibyte encodes a signed integer value into a stream. Use 1's complement to
/// store signed values. This means both 00 and 01 are actually 0, but we don't
/// need to encode all negative numbers as 64 bit values.
/// </summary>
/// <param name="strm"></param>
/// <param name="Value"></param>
/// <returns></returns>
// Use 1's complement to store signed values. This means both 00 and 01 are
// actually 0, but we don't need to encode all negative numbers as 64 bit values.
public static uint SignEncode(Stream strm, int Value)
{
ulong ull = 0;
// special case LONG_MIN
if (-2147483648 == Value)
{
ull = 0x0000000100000001;
}
else
{
ull = (ulong)Math.Abs(Value);
// multiply by 2
ull <<= 1;
// For -ve nos, add 1
if (Value < 0)
ull |= 1;
}
return EncodeLarge(strm, ull);
}
/// <summary>
/// Decodes a multi byte encoded unsigned integer from the stream
/// </summary>
/// <param name="strm"></param>
/// <param name="dw"></param>
/// <returns></returns>
public static uint Decode(Stream strm, out uint dw)
{
int shift = 0;
byte b = 0;
uint cb = 0;
dw = 0;
do
{
b = (byte)strm.ReadByte();
cb++;
dw += (uint)((int)(b & 0x7f) << shift);
shift += 7;
} while (((b & 0x80) > 0) && (shift < 29));
return cb;
}
/// <summary>
/// Decodes a multibyte encoded unsigned long from the stream
/// </summary>
/// <param name="strm"></param>
/// <param name="ull"></param>
/// <returns></returns>
public static uint DecodeLarge(Stream strm, out ulong ull)
{
long ull1;
int shift = 0;
byte b = 0, a = 0;
uint cb = 0;
ull = 0;
do
{
b = (byte)strm.ReadByte();
cb++;
a = (byte)(b & 0x7f);
ull1 = a;
ull |= (ulong)(ull1 << shift);
shift += 7;
} while (((b & 0x80) > 0) && (shift < 57));
return cb;
}
/// <summary>
/// Decodes a multibyte encoded signed integer from the stream
/// </summary>
/// <param name="strm"></param>
/// <param name="i"></param>
/// <returns></returns>
public static uint SignDecode(Stream strm, out int i)
{
i = 0;
ulong ull = 0;
uint cb = DecodeLarge(strm, out ull);
if (cb > 0)
{
bool fneg = false;
if ((ull & 0x0001) > 0)
fneg = true;
ull = ull >> 1;
long l = (long)ull;
i = (int)(fneg ? -l : l);
}
return cb;
}
/// <summary>
/// Converts the CLR type information into a COM-compatible type enumeration
/// </summary>
/// <param name="type">The CLR type information of the object to convert</param>
/// <param name="throwOnError">Throw an exception if unknown type is used</param>
/// <returns>The COM-compatible type enumeration</returns>
/// <remarks>Only supports the types of data that are supported in ISF ExtendedProperties</remarks>
public static VarEnum ConvertToVarEnum(Type type, bool throwOnError)
{
if (typeof(char) == type)
{
return VarEnum.VT_I1;
}
else if (typeof(char[]) == type)
{
return (VarEnum.VT_ARRAY | VarEnum.VT_I1);
}
else if (typeof(byte) == type)
{
return VarEnum.VT_UI1;
}
else if (typeof(byte[]) == type)
{
return (VarEnum.VT_ARRAY | VarEnum.VT_UI1);
}
else if (typeof(Int16) == type)
{
return VarEnum.VT_I2;
}
else if (typeof(Int16[]) == type)
{
return (VarEnum.VT_ARRAY | VarEnum.VT_I2);
}
else if (typeof(UInt16) == type)
{
return VarEnum.VT_UI2;
}
else if (typeof(UInt16[]) == type)
{
return (VarEnum.VT_ARRAY | VarEnum.VT_UI2);
}
else if (typeof(Int32) == type)
{
return VarEnum.VT_I4;
}
else if (typeof(Int32[]) == type)
{
return (VarEnum.VT_ARRAY | VarEnum.VT_I4);
}
else if (typeof(UInt32) == type)
{
return VarEnum.VT_UI4;
}
else if (typeof(UInt32[]) == type)
{
return (VarEnum.VT_ARRAY | VarEnum.VT_UI4);
}
else if (typeof(Int64) == type)
{
return VarEnum.VT_I8;
}
else if (typeof(Int64[]) == type)
{
return (VarEnum.VT_ARRAY | VarEnum.VT_I8);
}
else if (typeof(UInt64) == type)
{
return VarEnum.VT_UI8;
}
else if (typeof(UInt64[]) == type)
{
return (VarEnum.VT_ARRAY | VarEnum.VT_UI8);
}
else if (typeof(Single) == type)
{
return VarEnum.VT_R4;
}
else if (typeof(Single[]) == type)
{
return (VarEnum.VT_ARRAY | VarEnum.VT_R4);
}
else if (typeof(Double) == type)
{
return VarEnum.VT_R8;
}
else if (typeof(Double[]) == type)
{
return (VarEnum.VT_ARRAY | VarEnum.VT_R8);
}
else if (typeof(DateTime) == type)
{
return VarEnum.VT_DATE;
}
else if (typeof(DateTime[]) == type)
{
return (VarEnum.VT_ARRAY | VarEnum.VT_DATE);
}
else if (typeof(Boolean) == type)
{
return VarEnum.VT_BOOL;
}
else if (typeof(Boolean[]) == type)
{
return (VarEnum.VT_ARRAY | VarEnum.VT_BOOL);
}
else if (typeof(String) == type)
{
return VarEnum.VT_BSTR;
}
else if (typeof(Decimal) == type)
{
return VarEnum.VT_DECIMAL;
}
else if (typeof(Decimal[]) == type)
{
return (VarEnum.VT_ARRAY | VarEnum.VT_DECIMAL);
}
else
{
if (throwOnError)
{
throw new ArgumentException(SR.Get(SRID.InvalidDataTypeForExtendedProperty));
}
else
{
return VarEnum.VT_UNKNOWN;
}
}
}
}
}
| |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Rendering;
#if UNITY_EDITOR
using UnityEditor;
#endif // UNITY_EDITOR
public static class RaymarcherUtils
{
public static Mesh GenerateQuad()
{
Vector3[] vertices = new Vector3[4] {
new Vector3( 1.0f, 1.0f, 0.0f),
new Vector3(-1.0f, 1.0f, 0.0f),
new Vector3(-1.0f,-1.0f, 0.0f),
new Vector3( 1.0f,-1.0f, 0.0f),
};
int[] indices = new int[6] { 0, 1, 2, 2, 3, 0 };
Mesh r = new Mesh();
r.vertices = vertices;
r.triangles = indices;
return r;
}
public static Mesh GenerateDetailedQuad()
{
const int div_x = 325;
const int div_y = 200;
var cell = new Vector2(2.0f / div_x, 2.0f / div_y);
var vertices = new Vector3[65000];
var indices = new int[(div_x-1)*(div_y-1)*6];
for (int iy = 0; iy < div_y; ++iy)
{
for (int ix = 0; ix < div_x; ++ix)
{
int i = div_x * iy + ix;
vertices[i] = new Vector3(cell.x * ix - 1.0f, cell.y * iy - 1.0f, 0.0f);
}
}
for (int iy = 0; iy < div_y-1; ++iy)
{
for (int ix = 0; ix < div_x-1; ++ix)
{
int i = ((div_x-1) * iy + ix)*6;
indices[i + 0] = (div_x * (iy + 1)) + (ix + 1);
indices[i + 1] = (div_x * (iy + 0)) + (ix + 1);
indices[i + 2] = (div_x * (iy + 0)) + (ix + 0);
indices[i + 3] = (div_x * (iy + 0)) + (ix + 0);
indices[i + 4] = (div_x * (iy + 1)) + (ix + 0);
indices[i + 5] = (div_x * (iy + 1)) + (ix + 1);
}
}
Mesh r = new Mesh();
r.vertices = vertices;
r.triangles = indices;
return r;
}
}
[RequireComponent(typeof(Camera))]
[ExecuteInEditMode]
public class Raymarcher : MonoBehaviour
{
public Material m_material;
public bool m_enable_adaptive = true;
public bool m_enable_temporal = true;
public bool m_enable_glowline = true;
public bool m_dbg_show_steps;
public int m_scene;
public Color m_fog_color = new Color(0.16f, 0.13f, 0.20f);
Vector2 m_resolution_prev;
Mesh m_quad;
Mesh m_detailed_quad;
Camera m_camera;
CommandBuffer m_cb_prepass;
CommandBuffer m_cb_raymarch;
CommandBuffer m_cb_show_steps;
bool m_enable_adaptive_prev;
bool m_dbg_show_steps_prev;
void Awake()
{
m_camera = GetComponent<Camera>();
m_enable_adaptive_prev = m_enable_adaptive;
}
void ClearCommandBuffer()
{
if (m_camera != null)
{
if (m_cb_prepass != null)
{
m_camera.RemoveCommandBuffer(CameraEvent.BeforeGBuffer, m_cb_prepass);
}
if (m_cb_raymarch != null)
{
m_camera.RemoveCommandBuffer(CameraEvent.BeforeGBuffer, m_cb_raymarch);
}
if (m_cb_show_steps != null)
{
m_camera.RemoveCommandBuffer(CameraEvent.AfterEverything, m_cb_show_steps);
}
m_cb_prepass = null;
m_cb_raymarch = null;
m_cb_show_steps = null;
}
}
void OnDisable()
{
ClearCommandBuffer();
}
void OnPreRender()
{
m_material.SetInt("g_frame", Time.frameCount);
m_material.SetInt("g_hdr", m_camera.allowHDR ? 1 : 0);
m_material.SetInt("g_scene", m_scene);
m_material.SetInt("g_enable_adaptive", m_enable_adaptive ? 1 : 0);
m_material.SetInt("g_enable_temporal", m_enable_temporal ? 1 : 0);
m_material.SetInt("g_enable_glowline", m_enable_glowline ? 1 : 0);
RenderSettings.fogColor = m_fog_color;
if (m_quad == null)
{
m_quad = RaymarcherUtils.GenerateQuad();
}
if (m_detailed_quad == null)
{
m_detailed_quad = RaymarcherUtils.GenerateDetailedQuad();
}
bool need_to_reflesh_command_buffer = false;
Vector2 reso = new Vector2(m_camera.pixelWidth, m_camera.pixelHeight);
if(m_resolution_prev!=reso)
{
m_resolution_prev = reso;
need_to_reflesh_command_buffer = true;
}
if (m_enable_adaptive_prev != m_enable_adaptive)
{
m_enable_adaptive_prev = m_enable_adaptive;
need_to_reflesh_command_buffer = true;
}
if (m_dbg_show_steps_prev != m_dbg_show_steps)
{
m_dbg_show_steps_prev = m_dbg_show_steps;
need_to_reflesh_command_buffer = true;
}
if (need_to_reflesh_command_buffer)
{
need_to_reflesh_command_buffer = false;
ClearCommandBuffer();
}
if (m_cb_raymarch==null)
{
if (m_enable_adaptive)
{
RenderTargetIdentifier[] rt;
m_cb_prepass = new CommandBuffer();
m_cb_prepass.name = "Raymarcher Adaptive PrePass";
int odepth = Shader.PropertyToID("ODepth");
int odepth_prev = Shader.PropertyToID("ODepthPrev");
int ovelocity = Shader.PropertyToID("OVelocity");
int qdepth = Shader.PropertyToID("QDepth");
int qdepth_prev = Shader.PropertyToID("QDepthPrev");
int hdepth = Shader.PropertyToID("HDepth");
int hdepth_prev = Shader.PropertyToID("HDepthPrev");
int adepth = Shader.PropertyToID("ADepth");
int adepth_prev = Shader.PropertyToID("ADepthPrev");
m_cb_prepass.GetTemporaryRT(odepth, m_camera.pixelWidth / 8, m_camera.pixelHeight / 8, 0, FilterMode.Point, RenderTextureFormat.RFloat);
m_cb_prepass.GetTemporaryRT(odepth_prev,m_camera.pixelWidth / 8, m_camera.pixelHeight / 8, 0, FilterMode.Point, RenderTextureFormat.RFloat);
m_cb_prepass.GetTemporaryRT(ovelocity, m_camera.pixelWidth / 8, m_camera.pixelHeight / 8, 0, FilterMode.Point, RenderTextureFormat.RHalf);
m_cb_prepass.GetTemporaryRT(qdepth, m_camera.pixelWidth / 4, m_camera.pixelHeight / 4, 0, FilterMode.Point, RenderTextureFormat.RFloat);
m_cb_prepass.GetTemporaryRT(qdepth_prev,m_camera.pixelWidth / 4, m_camera.pixelHeight / 4, 0, FilterMode.Point, RenderTextureFormat.RFloat);
m_cb_prepass.GetTemporaryRT(hdepth, m_camera.pixelWidth / 2, m_camera.pixelHeight / 2, 0, FilterMode.Point, RenderTextureFormat.RFloat);
m_cb_prepass.GetTemporaryRT(hdepth_prev,m_camera.pixelWidth / 2, m_camera.pixelHeight / 2, 0, FilterMode.Point, RenderTextureFormat.RFloat);
m_cb_prepass.GetTemporaryRT(adepth, m_camera.pixelWidth / 1, m_camera.pixelHeight / 1, 0, FilterMode.Point, RenderTextureFormat.RFloat);
m_cb_prepass.GetTemporaryRT(adepth_prev,m_camera.pixelWidth / 1, m_camera.pixelHeight / 1, 0, FilterMode.Point, RenderTextureFormat.RFloat);
rt = new RenderTargetIdentifier[2] { odepth, ovelocity };
m_cb_prepass.SetGlobalTexture("g_depth_prev", odepth_prev);
m_cb_prepass.SetRenderTarget(rt, odepth);
m_cb_prepass.DrawMesh(m_quad, Matrix4x4.identity, m_material, 0, 1);
m_cb_prepass.Blit(odepth, odepth_prev);
m_cb_prepass.SetGlobalTexture("g_velocity", ovelocity);
m_cb_prepass.SetRenderTarget(qdepth);
m_cb_prepass.SetGlobalTexture("g_depth", odepth);
m_cb_prepass.SetGlobalTexture("g_depth_prev", qdepth_prev);
m_cb_prepass.DrawMesh(m_quad, Matrix4x4.identity, m_material, 0, 2);
m_cb_prepass.Blit(qdepth, qdepth_prev);
m_cb_prepass.SetRenderTarget(hdepth);
m_cb_prepass.SetGlobalTexture("g_depth", qdepth);
m_cb_prepass.SetGlobalTexture("g_depth_prev", hdepth_prev);
m_cb_prepass.DrawMesh(m_quad, Matrix4x4.identity, m_material, 0, 3);
m_cb_prepass.Blit(hdepth, hdepth_prev);
m_cb_prepass.SetRenderTarget(adepth);
m_cb_prepass.SetGlobalTexture("g_depth", hdepth);
m_cb_prepass.SetGlobalTexture("g_depth_prev", adepth_prev);
m_cb_prepass.DrawMesh(m_quad, Matrix4x4.identity, m_material, 0, 4);
m_cb_prepass.Blit(adepth, adepth_prev);
m_cb_prepass.SetGlobalTexture("g_depth", adepth);
m_camera.AddCommandBuffer(CameraEvent.BeforeGBuffer, m_cb_prepass);
}
m_cb_raymarch = new CommandBuffer();
m_cb_raymarch.name = "Raymarcher";
m_cb_raymarch.DrawMesh(m_quad, Matrix4x4.identity, m_material, 0, 0);
m_camera.AddCommandBuffer(CameraEvent.BeforeGBuffer, m_cb_raymarch);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information.
using System;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Shell;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using System.Collections;
using System.Diagnostics;
using System.Runtime.Serialization;
using System.Reflection;
using IServiceProvider = System.IServiceProvider;
using Microsoft.VisualStudio.OLE.Interop;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using Microsoft.VisualStudio.FSharp.ProjectSystem;
namespace Microsoft.VisualStudio.FSharp.ProjectSystem.Automation
{
/// <summary>
/// Contains all of the properties of a given object that are contained in a generic collection of properties.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[CLSCompliant(false), ComVisible(true)]
public class OAProperties : EnvDTE.Properties
{
private NodeProperties target;
private Dictionary<string, EnvDTE.Property> properties = new Dictionary<string, EnvDTE.Property>(StringComparer.OrdinalIgnoreCase);
/// <summary>
/// Defines the NodeProperties object that contains the defines the properties.
/// </summary>
public NodeProperties Target
{
get
{
return this.target;
}
}
/// <summary>
/// The hierarchy node for the object which properties this item represent
/// </summary>
public HierarchyNode Node
{
get
{
return this.Target.Node;
}
}
/// <summary>
/// Defines a dictionary of the properties contained.
/// </summary>
public Dictionary<string, EnvDTE.Property> Properties
{
get
{
return this.properties;
}
}
internal OAProperties(NodeProperties target)
{
System.Diagnostics.Debug.Assert(target != null);
this.target = target;
this.AddPropertiesFromType(target.GetType());
}
/// <summary>
/// For use by F# tooling only.
/// </summary>
public virtual object Application
{
get { return null; }
}
/// <summary>
/// Gets a value indicating the number of objects in the collection.
/// </summary>
public int Count
{
get { return properties.Count; }
}
/// <summary>
/// Gets the top-level extensibility object.
/// </summary>
public virtual EnvDTE.DTE DTE
{
get
{
return UIThread.DoOnUIThread(delegate() {
if (this.target == null || this.target.Node == null || this.target.Node.ProjectMgr == null || this.target.Node.ProjectMgr.IsClosed ||
this.target.Node.ProjectMgr.Site == null)
{
throw new InvalidOperationException();
}
return this.target.Node.ProjectMgr.Site.GetService(typeof(EnvDTE.DTE)) as EnvDTE.DTE;
});
}
}
/// <summary>
/// Gets an enumeration for items in a collection.
/// </summary>
/// <returns>An enumerator. </returns>
public IEnumerator GetEnumerator()
{
if (this.properties == null)
{
yield return null;
yield break;
}
if (this.properties.Count == 0)
{
yield return new OANullProperty(this);
}
IEnumerator enumerator = this.properties.Values.GetEnumerator();
while (enumerator.MoveNext())
{
yield return enumerator.Current;
}
}
/// <summary>
/// Returns an indexed member of a Properties collection.
/// </summary>
/// <param name="index">The index at which to return a mamber.</param>
/// <returns>A Property object.</returns>
public virtual EnvDTE.Property Item(object index)
{
if (index is string)
{
string indexAsString = (string)index;
if (this.properties.ContainsKey(indexAsString))
{
return (EnvDTE.Property)this.properties[indexAsString];
}
}
else if (index is int)
{
int realIndex = (int)index - 1;
if (realIndex >= 0 && realIndex < this.properties.Count)
{
IEnumerator enumerator = this.properties.Values.GetEnumerator();
int i = 0;
while (enumerator.MoveNext())
{
if (i++ == realIndex)
{
return (EnvDTE.Property)enumerator.Current;
}
}
}
}
throw new ArgumentException(SR.GetString(SR.InvalidParameter, CultureInfo.CurrentUICulture), "index");
}
public virtual object Parent
{
get { return null; }
}
/// <summary>
/// Add properties to the collection of properties filtering only those properties which are com-visible and AutomationBrowsable
/// </summary>
/// <param name="targetType">The type of NodeProperties the we should filter on</param>
public void AddPropertiesFromType(Type targetType)
{
Debug.Assert(targetType != null);
// If the type is not COM visible, we do not expose any of the properties
if (!IsComVisible(targetType))
return;
// Add all properties being ComVisible and AutomationVisible
PropertyInfo[] propertyInfos = targetType.GetProperties();
foreach (PropertyInfo propertyInfo in propertyInfos)
{
if (!IsInMap(propertyInfo) && IsComVisible(propertyInfo) && IsAutomationVisible(propertyInfo))
{
AddProperty(propertyInfo);
}
}
}
/// <summary>
/// Creates a new OAProperty object and adds it to the current list of properties
/// </summary>
/// <param name="propertyInfo">The property to be associated with an OAProperty object</param>
public virtual void AddProperty(PropertyInfo propertyInfo)
{
this.properties.Add(propertyInfo.Name, new OAProperty(this, propertyInfo));
}
private bool IsInMap(PropertyInfo propertyInfo)
{
return this.properties.ContainsKey(propertyInfo.Name);
}
private bool IsAutomationVisible(PropertyInfo propertyInfo)
{
object[] customAttributesOnProperty = propertyInfo.GetCustomAttributes(typeof(AutomationBrowsableAttribute), true);
foreach (AutomationBrowsableAttribute attr in customAttributesOnProperty)
{
if (!attr.Browsable)
{
return false;
}
}
return true;
}
private bool IsComVisible(Type targetType)
{
object[] customAttributesOnProperty = targetType.GetCustomAttributes(typeof(ComVisibleAttribute), true);
foreach (ComVisibleAttribute attr in customAttributesOnProperty)
{
if (!attr.Value)
{
return false;
}
}
return true;
}
private bool IsComVisible(PropertyInfo propertyInfo)
{
object[] customAttributesOnProperty = propertyInfo.GetCustomAttributes(typeof(ComVisibleAttribute), true);
foreach (ComVisibleAttribute attr in customAttributesOnProperty)
{
if (!attr.Value)
{
return false;
}
}
return true;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Network
{
using Azure;
using Management;
using Rest;
using Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// VirtualNetworkPeeringsOperations operations.
/// </summary>
internal partial class VirtualNetworkPeeringsOperations : IServiceOperations<NetworkManagementClient>, IVirtualNetworkPeeringsOperations
{
/// <summary>
/// Initializes a new instance of the VirtualNetworkPeeringsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal VirtualNetworkPeeringsOperations(NetworkManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the NetworkManagementClient
/// </summary>
public NetworkManagementClient Client { get; private set; }
/// <summary>
/// Deletes the specified virtual network peering.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='virtualNetworkPeeringName'>
/// The name of the virtual network peering.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string virtualNetworkPeeringName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, virtualNetworkPeeringName, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the specified virtual network peering.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='virtualNetworkPeeringName'>
/// The name of the virtual network peering.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<VirtualNetworkPeering>> GetWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string virtualNetworkPeeringName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (virtualNetworkName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkName");
}
if (virtualNetworkPeeringName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkPeeringName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2017-03-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("virtualNetworkName", virtualNetworkName);
tracingParameters.Add("virtualNetworkPeeringName", virtualNetworkPeeringName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/virtualNetworkPeerings/{virtualNetworkPeeringName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{virtualNetworkName}", System.Uri.EscapeDataString(virtualNetworkName));
_url = _url.Replace("{virtualNetworkPeeringName}", System.Uri.EscapeDataString(virtualNetworkPeeringName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<VirtualNetworkPeering>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<VirtualNetworkPeering>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates or updates a peering in the specified virtual network.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='virtualNetworkPeeringName'>
/// The name of the peering.
/// </param>
/// <param name='virtualNetworkPeeringParameters'>
/// Parameters supplied to the create or update virtual network peering
/// operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<VirtualNetworkPeering>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string virtualNetworkPeeringName, VirtualNetworkPeering virtualNetworkPeeringParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send Request
AzureOperationResponse<VirtualNetworkPeering> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, virtualNetworkPeeringName, virtualNetworkPeeringParameters, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets all virtual network peerings in a virtual network.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<VirtualNetworkPeering>>> ListWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (virtualNetworkName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2017-03-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("virtualNetworkName", virtualNetworkName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/virtualNetworkPeerings").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{virtualNetworkName}", System.Uri.EscapeDataString(virtualNetworkName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<VirtualNetworkPeering>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<VirtualNetworkPeering>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Deletes the specified virtual network peering.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='virtualNetworkPeeringName'>
/// The name of the virtual network peering.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string virtualNetworkPeeringName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (virtualNetworkName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkName");
}
if (virtualNetworkPeeringName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkPeeringName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2017-03-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("virtualNetworkName", virtualNetworkName);
tracingParameters.Add("virtualNetworkPeeringName", virtualNetworkPeeringName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/virtualNetworkPeerings/{virtualNetworkPeeringName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{virtualNetworkName}", System.Uri.EscapeDataString(virtualNetworkName));
_url = _url.Replace("{virtualNetworkPeeringName}", System.Uri.EscapeDataString(virtualNetworkPeeringName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("DELETE");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 204 && (int)_statusCode != 202)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates or updates a peering in the specified virtual network.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='virtualNetworkPeeringName'>
/// The name of the peering.
/// </param>
/// <param name='virtualNetworkPeeringParameters'>
/// Parameters supplied to the create or update virtual network peering
/// operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<VirtualNetworkPeering>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string virtualNetworkPeeringName, VirtualNetworkPeering virtualNetworkPeeringParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (virtualNetworkName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkName");
}
if (virtualNetworkPeeringName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkPeeringName");
}
if (virtualNetworkPeeringParameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkPeeringParameters");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2017-03-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("virtualNetworkName", virtualNetworkName);
tracingParameters.Add("virtualNetworkPeeringName", virtualNetworkPeeringName);
tracingParameters.Add("virtualNetworkPeeringParameters", virtualNetworkPeeringParameters);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/virtualNetworkPeerings/{virtualNetworkPeeringName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{virtualNetworkName}", System.Uri.EscapeDataString(virtualNetworkName));
_url = _url.Replace("{virtualNetworkPeeringName}", System.Uri.EscapeDataString(virtualNetworkPeeringName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(virtualNetworkPeeringParameters != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(virtualNetworkPeeringParameters, Client.SerializationSettings);
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 201)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<VirtualNetworkPeering>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<VirtualNetworkPeering>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<VirtualNetworkPeering>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets all virtual network peerings in a virtual network.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<VirtualNetworkPeering>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<VirtualNetworkPeering>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<VirtualNetworkPeering>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Net;
using FluentAssertions.Extensions;
using Xunit;
using Xunit.Sdk;
namespace FluentAssertions.Equivalency.Specs
{
public class BasicSpecs
{
[Fact]
public void When_expectation_is_null_it_should_throw()
{
// Arrange
var subject = new { };
// Act
Action act = () => subject.Should().BeEquivalentTo<object>(null);
// Assert
act.Should().Throw<XunitException>().WithMessage(
"Expected subject to be <null>, but found { }*");
}
[Fact]
public void When_comparing_nested_collection_with_a_null_value_it_should_fail_with_the_correct_message()
{
// Arrange
var subject = new[] { new MyClass { Items = new[] { "a" } } };
var expectation = new[] { new MyClass() };
// Act
Action act = () => subject.Should().BeEquivalentTo(expectation);
// Assert
act.Should().Throw<XunitException>().WithMessage(
"Expected*subject[0].Items*null*, but found*\"a\"*");
}
public class MyClass
{
public IEnumerable<string> Items { get; set; }
}
[Fact]
public void When_subject_is_null_it_should_throw()
{
// Arrange
SomeDto subject = null;
// Act
Action act = () => subject.Should().BeEquivalentTo(new { });
// Assert
act.Should().Throw<XunitException>().WithMessage(
"Expected subject*to be*, but found <null>*");
}
[Fact]
public void When_subject_and_expectation_are_null_it_should_not_throw()
{
// Arrange
SomeDto subject = null;
// Act
Action act = () => subject.Should().BeEquivalentTo<object>(null);
// Assert
act.Should().NotThrow();
}
[Fact]
public void When_subject_and_expectation_are_compared_for_equivalence_it_should_allow_chaining()
{
// Arrange
SomeDto subject = null;
// Act
Action act = () => subject.Should().BeEquivalentTo<object>(null)
.And.BeNull();
// Assert
act.Should().NotThrow();
}
[Fact]
public void When_subject_and_expectation_are_compared_for_equivalence_with_config_it_should_allow_chaining()
{
// Arrange
SomeDto subject = null;
// Act
Action act = () => subject.Should().BeEquivalentTo<object>(null, opt => opt)
.And.BeNull();
// Assert
act.Should().NotThrow();
}
[Fact]
public void When_subject_and_expectation_are_compared_for_non_equivalence_it_should_allow_chaining()
{
// Arrange
SomeDto subject = null;
// Act
Action act = () => subject.Should().NotBeEquivalentTo<object>(new { })
.And.BeNull();
// Assert
act.Should().NotThrow();
}
[Fact]
public void When_subject_and_expectation_are_compared_for_non_equivalence_with_config_it_should_allow_chaining()
{
// Arrange
SomeDto subject = null;
// Act
Action act = () => subject.Should().NotBeEquivalentTo<object>(new { }, opt => opt)
.And.BeNull();
// Assert
act.Should().NotThrow();
}
[Fact]
public void When_asserting_equivalence_on_a_value_type_from_system_it_should_not_do_a_structural_comparision()
{
// Arrange
// DateTime is used as an example because the current implementation
// would hit the recursion-depth limit if structural equivalence were attempted.
var date1 = new { Property = 1.January(2011) };
var date2 = new { Property = 1.January(2011) };
// Act
Action act = () => date1.Should().BeEquivalentTo(date2);
// Assert
act.Should().NotThrow();
}
[Fact]
public void When_an_object_hides_object_equals_it_should_be_compared_using_its_members()
{
// Arrange
var actual = new VirtualClassOverride { Property = "Value", OtherProperty = "Actual" };
var expected = new VirtualClassOverride { Property = "Value", OtherProperty = "Expected" };
// Act
Action act = () => actual.Should().BeEquivalentTo(expected);
// Assert
act.Should().Throw<XunitException>("*OtherProperty*Expected*Actual*");
}
public class VirtualClass
{
public string Property { get; set; }
public new virtual bool Equals(object obj)
{
return (obj is VirtualClass other) && other.Property == Property;
}
}
public class VirtualClassOverride : VirtualClass
{
public string OtherProperty { get; set; }
}
[Fact]
public void When_treating_a_value_type_in_a_collection_as_a_complex_type_it_should_compare_them_by_members()
{
// Arrange
var subject = new[] { new ClassWithValueSemanticsOnSingleProperty { Key = "SameKey", NestedProperty = "SomeValue" } };
var expected = new[]
{
new ClassWithValueSemanticsOnSingleProperty { Key = "SameKey", NestedProperty = "OtherValue" }
};
// Act
Action act = () => subject.Should().BeEquivalentTo(expected,
options => options.ComparingByMembers<ClassWithValueSemanticsOnSingleProperty>());
// Assert
act.Should().Throw<XunitException>().WithMessage("*NestedProperty*OtherValue*SomeValue*");
}
[Fact]
public void When_treating_a_value_type_as_a_complex_type_it_should_compare_them_by_members()
{
// Arrange
var subject = new ClassWithValueSemanticsOnSingleProperty { Key = "SameKey", NestedProperty = "SomeValue" };
var expected = new ClassWithValueSemanticsOnSingleProperty { Key = "SameKey", NestedProperty = "OtherValue" };
// Act
Action act = () => subject.Should().BeEquivalentTo(expected,
options => options.ComparingByMembers<ClassWithValueSemanticsOnSingleProperty>());
// Assert
act.Should().Throw<XunitException>().WithMessage("*NestedProperty*OtherValue*SomeValue*");
}
[Fact]
public void When_treating_a_type_as_value_type_but_it_was_already_marked_as_reference_type_it_should_throw()
{
// Arrange
var subject = new ClassWithValueSemanticsOnSingleProperty { Key = "Don't care" };
var expected = new ClassWithValueSemanticsOnSingleProperty { Key = "Don't care" };
// Act
Action act = () => subject.Should().BeEquivalentTo(expected, options => options
.ComparingByMembers<ClassWithValueSemanticsOnSingleProperty>()
.ComparingByValue<ClassWithValueSemanticsOnSingleProperty>());
// Assert
act.Should().Throw<InvalidOperationException>().WithMessage(
$"*compare {nameof(ClassWithValueSemanticsOnSingleProperty)}*value*already*members*");
}
[Fact]
public void When_treating_a_type_as_reference_type_but_it_was_already_marked_as_value_type_it_should_throw()
{
// Arrange
var subject = new ClassWithValueSemanticsOnSingleProperty { Key = "Don't care" };
var expected = new ClassWithValueSemanticsOnSingleProperty { Key = "Don't care" };
// Act
Action act = () => subject.Should().BeEquivalentTo(expected, options => options
.ComparingByValue<ClassWithValueSemanticsOnSingleProperty>()
.ComparingByMembers<ClassWithValueSemanticsOnSingleProperty>());
// Assert
act.Should().Throw<InvalidOperationException>().WithMessage(
$"*compare {nameof(ClassWithValueSemanticsOnSingleProperty)}*members*already*value*");
}
[Fact]
public void When_treating_a_complex_type_in_a_collection_as_a_value_type_it_should_compare_them_by_value()
{
// Arrange
var subject = new[] { new { Address = IPAddress.Parse("1.2.3.4"), Word = "a" } };
var expected = new[] { new { Address = IPAddress.Parse("1.2.3.4"), Word = "a" } };
// Act
Action act = () => subject.Should().BeEquivalentTo(expected,
options => options.ComparingByValue<IPAddress>());
// Assert
act.Should().NotThrow();
}
[Fact]
public void When_treating_a_complex_type_as_a_value_type_it_should_compare_them_by_value()
{
// Arrange
var subject = new { Address = IPAddress.Parse("1.2.3.4"), Word = "a" };
var expected = new { Address = IPAddress.Parse("1.2.3.4"), Word = "a" };
// Act
Action act = () => subject.Should().BeEquivalentTo(expected,
options => options.ComparingByValue<IPAddress>());
// Assert
act.Should().NotThrow();
}
[Fact]
public void When_treating_a_null_type_as_value_type_it_should_throw()
{
// Arrange
var subject = new object();
var expected = new object();
// Act
Action act = () => subject.Should().BeEquivalentTo(expected, opt => opt
.ComparingByValue(null));
// Assert
act.Should().Throw<ArgumentNullException>()
.WithParameterName("type");
}
[Fact]
public void When_treating_a_null_type_as_reference_type_it_should_throw()
{
// Arrange
var subject = new object();
var expected = new object();
// Act
Action act = () => subject.Should().BeEquivalentTo(expected, opt => opt
.ComparingByMembers(null));
// Assert
act.Should().Throw<ArgumentNullException>()
.WithParameterName("type");
}
[Fact]
public void When_comparing_an_open_type_by_members_it_should_succeed()
{
// Arrange
var subject = new Option<int[]>(new[] { 1, 3, 2 });
var expected = new Option<int[]>(new[] { 1, 2, 3 });
// Act
Action act = () => subject.Should().BeEquivalentTo(expected, opt => opt
.ComparingByMembers(typeof(Option<>)));
// Assert
act.Should().NotThrow();
}
[Fact]
public void When_threating_open_type_as_reference_type_and_a_closed_type_as_value_type_it_should_compare_by_value()
{
// Arrange
var subject = new Option<int[]>(new[] { 1, 3, 2 });
var expected = new Option<int[]>(new[] { 1, 2, 3 });
// Act
Action act = () => subject.Should().BeEquivalentTo(expected, opt => opt
.ComparingByMembers(typeof(Option<>))
.ComparingByValue<Option<int[]>>());
// Assert
act.Should().Throw<XunitException>();
}
[Fact]
public void When_threating_open_type_as_value_type_and_a_closed_type_as_reference_type_it_should_compare_by_members()
{
// Arrange
var subject = new Option<int[]>(new[] { 1, 3, 2 });
var expected = new Option<int[]>(new[] { 1, 2, 3 });
// Act
Action act = () => subject.Should().BeEquivalentTo(expected, opt => opt
.ComparingByValue(typeof(Option<>))
.ComparingByMembers<Option<int[]>>());
// Assert
act.Should().NotThrow();
}
private struct Option<T> : IEquatable<Option<T>>
where T : class
{
public T Value { get; }
public Option(T value)
{
Value = value;
}
public bool Equals(Option<T> other) =>
EqualityComparer<T>.Default.Equals(Value, other.Value);
public override bool Equals(object obj) =>
obj is Option<T> other && Equals(other);
public override int GetHashCode() => Value?.GetHashCode() ?? 0;
}
[Fact]
public void When_threating_any_type_as_reference_type_it_should_exclude_primitive_types()
{
// Arrange
var subject = new { Value = 1 };
var expected = new { Value = 2 };
// Act
Action act = () => subject.Should().BeEquivalentTo(expected, opt => opt
.ComparingByMembers<object>());
// Assert
act.Should().Throw<XunitException>()
.WithMessage("*be 2*found 1*");
}
[Fact]
public void When_threating_an_open_type_as_reference_type_it_should_exclude_primitive_types()
{
// Arrange
var subject = new { Value = 1 };
var expected = new { Value = 2 };
// Act
Action act = () => subject.Should().BeEquivalentTo(expected, opt => opt
.ComparingByMembers(typeof(IEquatable<>)));
// Assert
act.Should().Throw<XunitException>()
.WithMessage("*be 2*found 1*");
}
[Fact]
public void When_threating_a_primitive_type_as_a_reference_type_it_should_throw()
{
// Arrange
var subject = new { Value = 1 };
var expected = new { Value = 2 };
// Act
Action act = () => subject.Should().BeEquivalentTo(expected, opt => opt
.ComparingByMembers<int>());
// Assert
act.Should().Throw<InvalidOperationException>()
.WithMessage("*Cannot compare a primitive type*Int32*");
}
[Fact]
public void When_a_type_originates_from_the_System_namespace_it_should_be_treated_as_a_value_type()
{
// Arrange
var subject = new { UriBuilder = new UriBuilder("http://localhost:9001/api"), };
var expected = new { UriBuilder = new UriBuilder("https://localhost:9002/bapi"), };
// Act
Action act = () => subject.Should().BeEquivalentTo(expected);
// Assert
act.Should().Throw<XunitException>()
.WithMessage("Expected*UriBuilder* to be https://localhost:9002/bapi, but found http://localhost:9001/api*");
}
[Fact]
public void When_asserting_equivalence_on_a_string_it_should_use_string_specific_failure_messages()
{
// Arrange
string s1 = "hello";
string s2 = "good-bye";
// Act
Action act = () => s1.Should().BeEquivalentTo(s2);
// Assert
act.Should().Throw<XunitException>()
.WithMessage("*to be*\"good-bye\" with a length of 8, but \"hello\" has a length of 5*");
}
[Fact]
public void When_asserting_equivalence_of_strings_typed_as_objects_it_should_compare_them_as_strings()
{
// Arrange
// The convoluted construction is so the compiler does not optimize the two objects to be the same.
object s1 = new string('h', 2);
object s2 = "hh";
// Act
Action act = () => s1.Should().BeEquivalentTo(s2);
// Assert
act.Should().NotThrow();
}
[Fact]
public void When_asserting_equivalence_of_ints_typed_as_objects_it_should_use_the_runtime_type()
{
// Arrange
object s1 = 1;
object s2 = 1;
// Act
Action act = () => s1.Should().BeEquivalentTo(s2);
// Assert
act.Should().NotThrow();
}
[Fact]
public void When_all_field_of_the_object_are_equal_equivalency_should_pass()
{
// Arrange
var object1 = new ClassWithOnlyAField { Value = 1 };
var object2 = new ClassWithOnlyAField { Value = 1 };
// Act
Action act = () => object1.Should().BeEquivalentTo(object2);
// Assert
act.Should().NotThrow();
}
[Fact]
public void When_number_values_are_convertible_it_should_treat_them_as_equivalent()
{
// Arrange
var actual = new Dictionary<string, long> { ["001"] = 1L, ["002"] = 2L };
var expected = new Dictionary<string, int> { ["001"] = 1, ["002"] = 2 };
// Act
Action act = () => actual.Should().BeEquivalentTo(expected);
// Assert
act.Should().NotThrow();
}
[Fact]
public void When_all_field_of_the_object_are_not_equal_equivalency_should_fail()
{
// Arrange
var object1 = new ClassWithOnlyAField { Value = 1 };
var object2 = new ClassWithOnlyAField { Value = 101 };
// Act
Action act = () => object1.Should().BeEquivalentTo(object2);
// Assert
act.Should().Throw<XunitException>();
}
[Fact]
public void When_a_field_on_the_subject_matches_a_property_the_members_should_match_for_equivalence()
{
// Arrange
var onlyAField = new ClassWithOnlyAField { Value = 1 };
var onlyAProperty = new ClassWithOnlyAProperty { Value = 101 };
// Act
Action act = () => onlyAField.Should().BeEquivalentTo(onlyAProperty);
// Assert
act.Should().Throw<XunitException>().WithMessage("Expected property onlyAField.Value*to be 101, but found 1.*");
}
[Fact]
public void When_asserting_equivalence_including_only_fields_it_should_not_match_properties()
{
// Arrange
var onlyAField = new ClassWithOnlyAField { Value = 1 };
object onlyAProperty = new ClassWithOnlyAProperty { Value = 101 };
// Act
Action act = () => onlyAProperty.Should().BeEquivalentTo(onlyAField, opts => opts.ExcludingProperties());
// Assert
act.Should().Throw<XunitException>()
.WithMessage("Expectation has field onlyAProperty.Value that the other object does not have.*");
}
[Fact]
public void When_asserting_equivalence_including_only_properties_it_should_not_match_fields()
{
// Arrange
var onlyAField = new ClassWithOnlyAField { Value = 1 };
var onlyAProperty = new ClassWithOnlyAProperty { Value = 101 };
// Act
Action act = () => onlyAField.Should().BeEquivalentTo(onlyAProperty, opts => opts.IncludingAllDeclaredProperties());
// Assert
act.Should().Throw<XunitException>()
.WithMessage("Expectation has property onlyAField.Value that the other object does not have*");
}
[Fact]
public void
When_asserting_equivalence_of_objects_including_enumerables_it_should_print_the_failure_message_only_once()
{
// Arrange
var record = new { Member1 = "", Member2 = new[] { "", "" } };
var record2 = new { Member1 = "different", Member2 = new[] { "", "" } };
// Act
Action act = () => record.Should().BeEquivalentTo(record2);
// Assert
act.Should().Throw<XunitException>().WithMessage(
@"Expected property record.Member1* to be*""different"" with a length of 9, but*"""" has a length of 0*");
}
[Fact]
public void When_asserting_object_equivalence_against_a_null_value_it_should_properly_throw()
{
// Act
Action act = () => ((object)null).Should().BeEquivalentTo("foo");
// Assert
act.Should().Throw<XunitException>().WithMessage("*foo*null*");
}
[Fact]
public void When_the_graph_contains_guids_it_should_properly_format_them()
{
// Arrange
var actual =
new[] { new { Id = Guid.NewGuid(), Name = "Name" } };
var expected =
new[] { new { Id = Guid.NewGuid(), Name = "Name" } };
// Act
Action act = () => actual.Should().BeEquivalentTo(expected);
// Assert
act.Should().Throw<XunitException>().WithMessage("Expected property actual[0].Id*to be *-*, but found *-*");
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
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 DistanceCalculator.WebApiService.Areas.HelpPage.ModelDescriptions;
using DistanceCalculator.WebApiService.Areas.HelpPage.Models;
namespace DistanceCalculator.WebApiService.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;
}
if (complexTypeDescription != null)
{
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 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);
}
}
}
}
| |
// 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.PortsTests;
using System.Text;
using System.Threading;
using Legacy.Support;
using Xunit;
using Xunit.NetCore.Extensions;
using ThreadState = System.Threading.ThreadState;
namespace System.IO.Ports.Tests
{
public class Write_byte_int_int_generic : PortsTest
{
//Set bounds fore random timeout values.
//If the min is to low write will not timeout accurately and the testcase will fail
private const int minRandomTimeout = 250;
//If the max is to large then the testcase will take forever to run
private const int maxRandomTimeout = 2000;
//If the percentage difference between the expected timeout and the actual timeout
//found through Stopwatch is greater then 10% then the timeout value was not correctly
//to the write method and the testcase fails.
private const double maxPercentageDifference = .15;
//The byte size used when veryifying exceptions that write will throw
private const int BYTE_SIZE_EXCEPTION = 4;
//The byte size used when veryifying timeout
private const int BYTE_SIZE_TIMEOUT = 4;
//The byte size used when veryifying BytesToWrite
private const int BYTE_SIZE_BYTES_TO_WRITE = 4;
//The bytes size used when veryifying Handshake
private const int BYTE_SIZE_HANDSHAKE = 8;
private const int NUM_TRYS = 5;
#region Test Cases
[Fact]
public void WriteWithoutOpen()
{
using (SerialPort com = new SerialPort())
{
Debug.WriteLine("Verifying write method throws exception without a call to Open()");
VerifyWriteException(com, typeof(InvalidOperationException));
}
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void WriteAfterFailedOpen()
{
using (SerialPort com = new SerialPort("BAD_PORT_NAME"))
{
Debug.WriteLine("Verifying write method throws exception with a failed call to Open()");
//Since the PortName is set to a bad port name Open will thrown an exception
//however we don't care what it is since we are verfifying a write method
Assert.ThrowsAny<Exception>(() => com.Open());
VerifyWriteException(com, typeof(InvalidOperationException));
}
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void WriteAfterClose()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
Debug.WriteLine("Verifying write method throws exception after a call to Cloes()");
com.Open();
com.Close();
VerifyWriteException(com, typeof(InvalidOperationException));
}
}
[ConditionalFact(nameof(HasNullModem))]
public void Timeout()
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
Random rndGen = new Random(-55);
byte[] XOffBuffer = new byte[1];
XOffBuffer[0] = 19;
com1.WriteTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout);
com1.Handshake = Handshake.XOnXOff;
Debug.WriteLine("Verifying WriteTimeout={0}", com1.WriteTimeout);
com1.Open();
com2.Open();
com2.Write(XOffBuffer, 0, 1);
Thread.Sleep(250);
com2.Close();
VerifyTimeout(com1);
}
}
[Trait(XunitConstants.Category, XunitConstants.IgnoreForCI)] // Timing-sensitive
[ConditionalFact(nameof(HasOneSerialPort), nameof(HasHardwareFlowControl))]
public void SuccessiveReadTimeout()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
Random rndGen = new Random(-55);
com.WriteTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout);
com.Handshake = Handshake.RequestToSendXOnXOff;
com.Encoding = Encoding.Unicode;
Debug.WriteLine("Verifying WriteTimeout={0} with successive call to write method", com.WriteTimeout);
com.Open();
try
{
com.Write(new byte[BYTE_SIZE_TIMEOUT], 0, BYTE_SIZE_TIMEOUT);
}
catch (TimeoutException)
{
}
VerifyTimeout(com);
}
}
[ConditionalFact(nameof(HasNullModem), nameof(HasHardwareFlowControl))]
public void SuccessiveReadTimeoutWithWriteSucceeding()
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
Random rndGen = new Random(-55);
AsyncEnableRts asyncEnableRts = new AsyncEnableRts();
Thread t = new Thread(asyncEnableRts.EnableRTS);
int waitTime;
com1.WriteTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout);
com1.Handshake = Handshake.RequestToSend;
com1.Encoding = new UTF8Encoding();
Debug.WriteLine("Verifying WriteTimeout={0} with successive call to write method with the write succeeding sometime before its timeout", com1.WriteTimeout);
com1.Open();
//Call EnableRTS asynchronously this will enable RTS in the middle of the following write call allowing it to succeed
//before the timeout is reached
t.Start();
waitTime = 0;
while (t.ThreadState == ThreadState.Unstarted && waitTime < 2000)
{
//Wait for the thread to start
Thread.Sleep(50);
waitTime += 50;
}
try
{
com1.Write(new byte[BYTE_SIZE_TIMEOUT], 0, BYTE_SIZE_TIMEOUT);
}
catch (TimeoutException)
{
}
asyncEnableRts.Stop();
while (t.IsAlive)
Thread.Sleep(100);
VerifyTimeout(com1);
}
}
[ConditionalFact(nameof(HasNullModem), nameof(HasHardwareFlowControl))]
public void BytesToWrite()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
AsyncWriteRndByteArray asyncWriteRndByteArray = new AsyncWriteRndByteArray(com, BYTE_SIZE_BYTES_TO_WRITE);
Thread t = new Thread(asyncWriteRndByteArray.WriteRndByteArray);
int waitTime;
Debug.WriteLine("Verifying BytesToWrite with one call to Write");
com.Handshake = Handshake.RequestToSend;
com.Open();
com.WriteTimeout = 500;
//Write a random byte[] asynchronously so we can verify some things while the write call is blocking
t.Start();
waitTime = 0;
while (t.ThreadState == ThreadState.Unstarted && waitTime < 2000)
{ //Wait for the thread to start
Thread.Sleep(50);
waitTime += 50;
}
TCSupport.WaitForExactWriteBufferLoad(com, BYTE_SIZE_BYTES_TO_WRITE);
//Wait for write method to timeout
while (t.IsAlive)
Thread.Sleep(100);
}
}
[ConditionalFact(nameof(HasNullModem), nameof(HasHardwareFlowControl))]
public void BytesToWriteSuccessive()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
AsyncWriteRndByteArray asyncWriteRndByteArray = new AsyncWriteRndByteArray(com, BYTE_SIZE_BYTES_TO_WRITE);
Thread t1 = new Thread(asyncWriteRndByteArray.WriteRndByteArray);
Thread t2 = new Thread(asyncWriteRndByteArray.WriteRndByteArray);
int waitTime;
Debug.WriteLine("Verifying BytesToWrite with successive calls to Write");
com.Handshake = Handshake.RequestToSend;
com.Open();
com.WriteTimeout = 1000;
//Write a random byte[] asynchronously so we can verify some things while the write call is blocking
t1.Start();
waitTime = 0;
while (t1.ThreadState == ThreadState.Unstarted && waitTime < 2000)
{ //Wait for the thread to start
Thread.Sleep(50);
waitTime += 50;
}
TCSupport.WaitForExactWriteBufferLoad(com, BYTE_SIZE_BYTES_TO_WRITE);
//Write a random byte[] asynchronously so we can verify some things while the write call is blocking
t2.Start();
waitTime = 0;
while (t2.ThreadState == ThreadState.Unstarted && waitTime < 2000)
{ //Wait for the thread to start
Thread.Sleep(50);
waitTime += 50;
}
TCSupport.WaitForExactWriteBufferLoad(com, BYTE_SIZE_BYTES_TO_WRITE * 2);
//Wait for both write methods to timeout
while (t1.IsAlive || t2.IsAlive)
Thread.Sleep(100);
}
}
[ConditionalFact(nameof(HasNullModem))]
public void Handshake_None()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
AsyncWriteRndByteArray asyncWriteRndByteArray = new AsyncWriteRndByteArray(com, BYTE_SIZE_HANDSHAKE);
Thread t = new Thread(asyncWriteRndByteArray.WriteRndByteArray);
int waitTime;
//Write a random byte[] asynchronously so we can verify some things while the write call is blocking
Debug.WriteLine("Verifying Handshake=None");
com.Open();
t.Start();
waitTime = 0;
while (t.ThreadState == ThreadState.Unstarted && waitTime < 2000)
{ //Wait for the thread to start
Thread.Sleep(50);
waitTime += 50;
}
//Wait for write method to timeout
while (t.IsAlive)
Thread.Sleep(100);
if (0 != com.BytesToWrite)
{
Fail("ERROR!!! Expcted BytesToWrite=0 actual {0}", com.BytesToWrite);
}
}
}
[ConditionalFact(nameof(HasNullModem), nameof(HasHardwareFlowControl))]
public void Handshake_RequestToSend()
{
Verify_Handshake(Handshake.RequestToSend);
}
[ConditionalFact(nameof(HasNullModem))]
public void Handshake_XOnXOff()
{
Verify_Handshake(Handshake.XOnXOff);
}
[ConditionalFact(nameof(HasNullModem), nameof(HasHardwareFlowControl))]
public void Handshake_RequestToSendXOnXOff()
{
Verify_Handshake(Handshake.RequestToSendXOnXOff);
}
private class AsyncEnableRts
{
private bool _stop;
public void EnableRTS()
{
lock (this)
{
using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
Random rndGen = new Random(-55);
int sleepPeriod = rndGen.Next(minRandomTimeout, maxRandomTimeout / 2);
//Sleep some random period with of a maximum duration of half the largest possible timeout value for a write method on COM1
Thread.Sleep(sleepPeriod);
com2.Open();
com2.RtsEnable = true;
while (!_stop)
Monitor.Wait(this);
com2.RtsEnable = false;
}
}
}
public void Stop()
{
lock (this)
{
_stop = true;
Monitor.Pulse(this);
}
}
}
private class AsyncWriteRndByteArray
{
private readonly SerialPort _com;
private readonly int _byteLength;
public AsyncWriteRndByteArray(SerialPort com, int byteLength)
{
_com = com;
_byteLength = byteLength;
}
public void WriteRndByteArray()
{
byte[] buffer = new byte[_byteLength];
Random rndGen = new Random(-55);
for (int i = 0; i < buffer.Length; i++)
{
buffer[i] = (byte)rndGen.Next(0, 256);
}
try
{
_com.Write(buffer, 0, buffer.Length);
}
catch (TimeoutException)
{
}
}
}
#endregion
#region Verification for Test Cases
private static void VerifyWriteException(SerialPort com, Type expectedException)
{
Assert.Throws(expectedException, () => com.Write(new byte[BYTE_SIZE_EXCEPTION], 0, BYTE_SIZE_EXCEPTION));
}
private void VerifyTimeout(SerialPort com)
{
Stopwatch timer = new Stopwatch();
int expectedTime = com.WriteTimeout;
int actualTime = 0;
double percentageDifference;
try
{
com.Write(new byte[BYTE_SIZE_TIMEOUT], 0, BYTE_SIZE_TIMEOUT); //Warm up write method
}
catch (TimeoutException) { }
Thread.CurrentThread.Priority = ThreadPriority.Highest;
for (int i = 0; i < NUM_TRYS; i++)
{
timer.Start();
try
{
com.Write(new byte[BYTE_SIZE_TIMEOUT], 0, BYTE_SIZE_TIMEOUT);
}
catch (TimeoutException) { }
timer.Stop();
actualTime += (int)timer.ElapsedMilliseconds;
timer.Reset();
}
Thread.CurrentThread.Priority = ThreadPriority.Normal;
actualTime /= NUM_TRYS;
percentageDifference = Math.Abs((expectedTime - actualTime) / (double)expectedTime);
//Verify that the percentage difference between the expected and actual timeout is less then maxPercentageDifference
if (maxPercentageDifference < percentageDifference)
{
Fail("ERROR!!!: The write method timedout in {0} expected {1} percentage difference: {2}", actualTime, expectedTime, percentageDifference);
}
}
private void Verify_Handshake(Handshake handshake)
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
AsyncWriteRndByteArray asyncWriteRndByteArray = new AsyncWriteRndByteArray(com1, BYTE_SIZE_HANDSHAKE);
Thread t = new Thread(asyncWriteRndByteArray.WriteRndByteArray);
byte[] XOffBuffer = new byte[1];
byte[] XOnBuffer = new byte[1];
int waitTime;
XOffBuffer[0] = 19;
XOnBuffer[0] = 17;
Debug.WriteLine("Verifying Handshake={0}", handshake);
com1.Handshake = handshake;
com1.Open();
com2.Open();
//Setup to ensure write will bock with type of handshake method being used
if (Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake)
{
com2.RtsEnable = false;
}
if (Handshake.XOnXOff == handshake || Handshake.RequestToSendXOnXOff == handshake)
{
com2.Write(XOffBuffer, 0, 1);
Thread.Sleep(250);
}
//Write a random byte asynchronously so we can verify some things while the write call is blocking
t.Start();
waitTime = 0;
while (t.ThreadState == ThreadState.Unstarted && waitTime < 2000)
{
//Wait for the thread to start
Thread.Sleep(50);
waitTime += 50;
}
waitTime = 0;
TCSupport.WaitForExactWriteBufferLoad(com1, BYTE_SIZE_HANDSHAKE);
//Verify that CtsHolding is false if the RequestToSend or RequestToSendXOnXOff handshake method is used
if ((Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake) && com1.CtsHolding)
{
Fail("ERROR!!! Expcted CtsHolding={0} actual {1}", false, com1.CtsHolding);
}
//Setup to ensure write will succeed
if (Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake)
{
com2.RtsEnable = true;
}
if (Handshake.XOnXOff == handshake || Handshake.RequestToSendXOnXOff == handshake)
{
com2.Write(XOnBuffer, 0, 1);
}
//Wait till write finishes
while (t.IsAlive)
Thread.Sleep(100);
Assert.Equal(0, com1.BytesToWrite);
//Verify that CtsHolding is true if the RequestToSend or RequestToSendXOnXOff handshake method is used
if ((Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake) &&
!com1.CtsHolding)
{
Fail("ERROR!!! Expcted CtsHolding={0} actual {1}", true, com1.CtsHolding);
}
}
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Axiom.Compiler.Framework;
using NUnit.Framework;
namespace Axiom.Compiler.Framework.Unit_Tests
{
[TestFixture]
public class PrologCodeParserTest
{
private ArrayList filesToDelete = new ArrayList();
[SetUp]
public void TestSetup()
{
}
[TearDown]
public void TestEnd()
{
}
private void Write(string filename, string s)
{
Console.WriteLine(s);
StreamWriter sw = new StreamWriter("C:\\" + filename, false);
sw.WriteLine(s);
sw.Close();
}
[Test]
public void Parse_Fact_no_Args()
{
// Try to parse 'predicate.'
Write("factnoargs.txt", "predicate.");
StreamReader sr = new StreamReader("C:\\factnoargs.txt");
PrologCodeParser parser = new PrologCodeParser();
parser.Scanner = new PrologScanner(sr);
BinaryTree ast = parser.Term(1200);
sr.Close();
// Expect: BinaryTree("predicate", null, null, null);
Assert.AreEqual("predicate", ast.Name);
Assert.IsNull(ast.Left);
Assert.IsNull(ast.Right);
Assert.IsNull(ast.Arguments);
}
[Test]
public void Parse_Fact_with_Atom_Arg()
{
// Try to parse 'predicate.'
Write("factnoargs.txt", "predicate(ali).");
StreamReader sr = new StreamReader("C:\\factnoargs.txt");
PrologCodeParser parser = new PrologCodeParser();
parser.Scanner = new PrologScanner(sr);
BinaryTree ast = parser.Term(1200);
sr.Close();
// Expect: BinaryTree("predicate", null, null, null);
Assert.AreEqual("predicate", ast.Name);
Assert.IsNull(ast.Left);
Assert.IsNull(ast.Right);
ArrayList args = new ArrayList();
ast.Flatten((BinaryTree)ast.Arguments[0], ref args);
Assert.AreEqual(1, args.Count);
}
[Test]
public void Parse_Fact_with_Variable_Arg()
{
// Try to parse 'predicate.'
Write("factnoargs.txt", "predicate(X).");
StreamReader sr = new StreamReader("C:\\factnoargs.txt");
PrologCodeParser parser = new PrologCodeParser();
parser.Scanner = new PrologScanner(sr);
BinaryTree ast = parser.Term(1200);
sr.Close();
// Expect: BinaryTree("predicate", null, null, null);
Assert.AreEqual("predicate", ast.Name);
Assert.IsNull(ast.Left);
Assert.IsNull(ast.Right);
ArrayList args = new ArrayList();
ast.Flatten((BinaryTree)ast.Arguments[0], ref args);
Assert.AreEqual(1, args.Count);
}
[Test]
public void Parse_Fact_with_2_Args()
{
// Try to parse 'predicate.'
Write("factnoargs.txt", "predicate(X,X).");
StreamReader sr = new StreamReader("C:\\factnoargs.txt");
PrologCodeParser parser = new PrologCodeParser();
parser.Scanner = new PrologScanner(sr);
BinaryTree ast = parser.Term(1200);
sr.Close();
// Expect: BinaryTree("predicate", null, null, null);
Assert.AreEqual("predicate", ast.Name);
Assert.IsNull(ast.Left);
Assert.IsNull(ast.Right);
ArrayList args = new ArrayList();
ast.Flatten((BinaryTree)ast.Arguments[0], ref args);
Assert.AreEqual(2, args.Count);
}
[Test]
public void Parse_Fact_with_3_Args()
{
// Try to parse 'predicate.'
Write("factnoargs.txt", "predicate(X,X,X).");
StreamReader sr = new StreamReader("C:\\factnoargs.txt");
PrologCodeParser parser = new PrologCodeParser();
parser.Scanner = new PrologScanner(sr);
BinaryTree ast = parser.Term(1200);
sr.Close();
// Expect: BinaryTree("predicate", null, null, null);
Assert.AreEqual("predicate", ast.Name);
Assert.IsNull(ast.Left);
Assert.IsNull(ast.Right);
ArrayList args = new ArrayList();
ast.Flatten((BinaryTree)ast.Arguments[0], ref args);
Assert.AreEqual(3, args.Count);
}
[Test]
public void Parse_Fact_with_Mixed_Args()
{
BinaryTree ast = PrologTerm("predicate(ali,X,s(X)).");
Assert.AreEqual("predicate", ast.Name);
Assert.IsNull(ast.Left);
Assert.IsNull(ast.Right);
ArrayList args = new ArrayList();
ast.Flatten((BinaryTree)ast.Arguments[0], ref args);
Assert.AreEqual(3, args.Count);
}
[Test]
public void Parse_Fact_with_ListArg()
{
BinaryTree ast = PrologTerm("predicate([X]).");
Assert.AreEqual("predicate", ast.Name);
Assert.IsNull(ast.Left);
Assert.IsNull(ast.Right);
ArrayList args = new ArrayList();
ast.Flatten((BinaryTree)ast.Arguments[0], ref args);
Assert.AreEqual(1, args.Count);
}
[Test]
public void Parse_Clause_1_Goal_Arity0()
{
BinaryTree ast = PrologTerm("ali :- samir.");
Assert.AreEqual(":-", ast.Name);
Assert.AreEqual("ali", ast.Left.Name);
Assert.AreEqual("samir", ast.Right.Name);
}
[Test]
public void Parse_Clause_1_Goal_Arity1()
{
BinaryTree ast = PrologTerm("ali(X) :- samir.");
Assert.AreEqual(":-", ast.Name);
Assert.AreEqual("ali", ast.Left.Name);
Assert.AreEqual("samir", ast.Right.Name);
Assert.AreEqual(1, ast.Left.Arguments.Count);
Assert.AreEqual("X", ((BinaryTree)ast.Left.Arguments[0]).Name);
}
[Test]
public void TestPredicate()
{
BinaryTree ast = PrologTerm("ali(X) :- samir.");
Assert.AreEqual(":-", ast.Name);
Assert.AreEqual("ali", ast.Left.Name);
Assert.AreEqual("samir", ast.Right.Name);
Assert.AreEqual(1, ast.Left.Arguments.Count);
Assert.AreEqual("X", ((BinaryTree)ast.Left.Arguments[0]).Name);
}
[Test]
public void Parse_Clause_1_Goal_Arity2()
{
BinaryTree ast = PrologTerm("ali(X,Y) :- samir.");
Assert.AreEqual(":-", ast.Name);
Assert.AreEqual("ali", ast.Left.Name);
Assert.AreEqual("samir", ast.Right.Name);
Assert.AreEqual(1, ast.Left.Arguments.Count);
BinaryTree args = (BinaryTree)ast.Left.Arguments[0];
Assert.AreEqual(",", args.Name);
Assert.AreEqual("X", args.Left.Name);
Assert.AreEqual("Y", args.Right.Name);
}
[Test]
public void Parse_Clause_1_Goal_Arity3()
{
BinaryTree ast = PrologTerm("ali(X,Y,Z) :- samir.");
Assert.AreEqual(":-", ast.Name);
Assert.AreEqual("ali", ast.Left.Name);
Assert.AreEqual("samir", ast.Right.Name);
Assert.AreEqual(1, ast.Left.Arguments.Count);
BinaryTree args = (BinaryTree)ast.Left.Arguments[0];
Assert.AreEqual(",", args.Name);
Assert.AreEqual("X", args.Left.Name);
Assert.AreEqual(",", args.Right.Name);
BinaryTree rightArgs = (BinaryTree)args.Right;
Assert.AreEqual("Y", rightArgs.Left.Name);
Assert.AreEqual("Z", rightArgs.Right.Name);
}
[Test]
public void Parse_Clause_1_Goal_Arity4()
{
BinaryTree ast = PrologTerm("ali(X1,X2,X3,X4) :- samir.");
ArrayList args = new ArrayList();
ast.Flatten((BinaryTree)ast.Left.Arguments[0], ref args);
Assert.AreEqual(4, args.Count);
}
[Test]
public void Parse_Clause_1_Goal_Arity5()
{
BinaryTree ast = PrologTerm("ali(X1,X2,X3,X4,X5) :- samir.");
ArrayList args = new ArrayList();
ast.Flatten((BinaryTree)ast.Left.Arguments[0], ref args);
Assert.AreEqual(5, args.Count);
}
private BinaryTree PrologTerm(string s)
{
// Try to parse 'predicate.'
Write("parsertest.txt", s);
StreamReader sr = new StreamReader("C:\\parsertest.txt");
PrologCodeParser parser = new PrologCodeParser();
parser.Scanner = new PrologScanner(sr);
BinaryTree ast = parser.Term(1200);
sr.Close();
File.Delete("C:\\parsertest.txt");
return ast;
}
}
}
| |
//
// FileSystemContentDirectory.cs
//
// Author:
// Scott Thomas <lunchtimemama@gmail.com>
//
// Copyright (c) 2009 Scott Thomas
//
// 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.IO;
using System.Net;
using Mono.Upnp.Control;
using Mono.Upnp.Dcp.MediaServer1.ContentDirectory1;
using Mono.Upnp.Dcp.MediaServer1.ContentDirectory1.AV;
using Mono.Upnp.Internal;
using Mono.Upnp.Xml;
using Object = Mono.Upnp.Dcp.MediaServer1.ContentDirectory1.Object;
using Mono.Upnp.Dcp.MediaServer1.ConnectionManager1;
namespace Mono.Upnp.Dcp.MediaServer1.FileSystem
{
public class FileSystemContentDirectory : ObjectBasedContentDirectory
{
const int file_buffer_size = 8192;
readonly Uri url;
HttpListener listener;
IDictionary<string, ObjectInfo> objects;
IDictionary<string, ContainerInfo> containers;
public FileSystemContentDirectory (Uri url,
IDictionary<string, ObjectInfo> objects,
IDictionary<string, ContainerInfo> containers)
{
if (url == null) {
throw new ArgumentNullException ("url");
} else if (objects == null) {
throw new ArgumentNullException ("objects");
} else if (containers == null) {
throw new ArgumentNullException ("containers");
}
this.url = url;
this.objects = objects;
this.containers = containers;
this.listener = new HttpListener ();
listener.Prefixes.Add (url.ToString ());
Log.Information (string.Format ("FileSystemContentDirectory created at {0}.", url));
}
public override void Start ()
{
CheckDisposed ();
if (IsStarted) {
return;
}
listener.Start ();
listener.BeginGetContext (OnGetContext, null);
base.Start ();
}
public override void Stop ()
{
CheckDisposed ();
if (!IsStarted) {
return;
}
base.Stop ();
lock (listener) {
listener.Stop ();
}
}
protected override void Dispose (bool disposing)
{
if (IsDisposed) {
return;
}
base.Dispose (disposing);
if (disposing) {
Stop ();
listener.Close ();
}
listener = null;
}
public bool IsDisposed {
get { return listener == null; }
}
void CheckDisposed ()
{
if (IsDisposed) {
throw new ObjectDisposedException (ToString ());
}
}
protected override Object GetObject (string objectId)
{
ObjectInfo @object;
if (!objects.TryGetValue (objectId, out @object)) {
throw new UpnpControlException (
Error.NoSuchObject (), string.Format (@"The object ""{0}"" does not exist.", objectId));
}
return @object.Object;
}
protected override int VisitChildren (Action<Object> consumer,
string objectId,
int startIndex,
int requestCount,
string sortCriteria,
out int totalMatches)
{
var children = GetChildren (objectId);
totalMatches = children.Count;
return VisitResults (consumer, children, startIndex, requestCount);
}
protected static int VisitResults<T> (Action<T> consumer, IList<T> objects, int startIndex, int requestCount)
{
if (consumer == null) {
throw new ArgumentNullException ("consumer");
} else if (objects == null) {
throw new ArgumentNullException ("objects");
}
var endIndex = requestCount > 0 ? System.Math.Min (startIndex + requestCount, objects.Count) : objects.Count;
for (var i = startIndex; i < endIndex; i++) {
consumer (objects[i]);
}
return endIndex - startIndex;
}
protected IList<Object> GetChildren (string containerId)
{
ContainerInfo container;
if (!containers.TryGetValue (containerId, out container)) {
throw new UpnpControlException (
Error.NoSuchContainer (), string.Format (@"The container ""{0}"" does not exist.", containerId));
}
return container.Children;
}
void OnGetContext (IAsyncResult result)
{
lock (listener) {
if (!listener.IsListening) {
return;
}
var context = listener.EndGetContext (result);
Log.Information (string.Format ("Got request from {0} for {1}.",
context.Request.RemoteEndPoint, context.Request.Url));
var url = this.url.MakeRelativeUri (context.Request.Url);
GetFile (context.Response, url.ToString ());
/*if (query.StartsWith ("?id=") && query.Length > 4) {
GetFile (context.Response, query.Substring (4));
} else if (query.StartsWith ("?art=")) {
//GetArtwork (context.Response, query);
} else {
context.Response.StatusCode = 404;
}*/
listener.BeginGetContext (OnGetContext, null);
}
}
void GetFile (HttpListenerResponse response, string id)
{
using (response) {
ObjectInfo object_info;
if (!objects.TryGetValue (id, out object_info) || object_info.Path == null) {
Log.Error (string.Format ("The requested object {0} does not exist.", id));
response.StatusCode = 404;
return;
}
Log.Information (string.Format ("Serving file {0}.", object_info.Path));
using (var reader = System.IO.File.OpenRead (object_info.Path)) {
response.ContentType = object_info.Object.Resources[0].ProtocolInfo.ContentFormat;
response.ContentLength64 = reader.Length;
try {
using (var writer = new BinaryWriter (response.OutputStream)) {
var buffer = new byte[file_buffer_size];
int read;
do {
read = reader.Read (buffer, 0, buffer.Length);
writer.Write (buffer, 0, read);
} while (IsStarted && read > 0);
}
} catch (Exception e) {
Log.Exception (string.Format ("Failed while serving file {0}.", object_info.Path), e);
}
}
}
}
/*void GetArtwork (HttpListenerResponse response, string query)
{
using (response) {
if (query.Length < 5) {
response.StatusCode = 404;
return;
}
int id;
if (!int.TryParse (query.Substring (4), out id)) {
response.StatusCode = 404;
return;
}
Console.WriteLine ("Serving artwork for: {0}", object_cache[id].Path);
if (id >= object_cache.Count) {
response.StatusCode = 404;
return;
}
var picture = GetAlbumArt (object_cache[id].Path);
if (picture == null)
{
response.StatusCode = 404;
return;
}
try {
using (var reader = new BinaryReader (new MemoryStream (picture.Data.Data))) {
response.ContentType = picture.MimeType;
response.ContentLength64 = picture.Data.Data.Length;
using (var stream = response.OutputStream) {
using (var writer = new BinaryWriter (stream)) {
var buffer = new byte[8192];
int read;
do {
read = reader.Read (buffer, 0, buffer.Length);
writer.Write (buffer, 0, read);
} while (started && read > 0);
}
}
}
} catch {
}
}
}*/
protected override string SearchCapabilities {
get { return string.Empty; }
}
protected override string SortCapabilities {
get { return string.Empty; }
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
/// <summary>
/// Array.Sort<Tkey,Tvalue>(Tkey[],Tvalue[],System.Int32,System.Int32,IComparer)
/// </summary>
public class ArraySort14
{
#region Public Methods
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
retVal = NegTest4() && retVal;
retVal = NegTest5() && retVal;
//DevDiv Bug 385712: Won't fix
//retVal = NegTest6() && retVal;
retVal = NegTest7() && retVal;
return retVal;
}
#region Positive Test Cases
public bool PosTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest1: Sort a string array using comparer ");
try
{
string[] s1 = new string[6]{"Jack",
"Mary",
"Mike",
"Peter",
"Tom",
"Allin"};
int[] i1 = new int[6] { 24, 30, 28, 26, 32, 23 };
string[] s2 = new string[6]{"Jack",
"Mary",
"Mike",
"Allin",
"Peter",
"Tom"};
int[] i2 = new int[6] { 24, 30, 28, 23, 26, 32 };
A a1 = new A();
Array.Sort<string, int>(s1, i1, 3, 3, a1);
for (int i = 0; i < 6; i++)
{
if (s1[i] != s2[i])
{
TestLibrary.TestFramework.LogError("001", "The result is not the value as expected");
retVal = false;
}
if (i1[i] != i2[i])
{
TestLibrary.TestFramework.LogError("002", "The result is not the value as expected");
retVal = false;
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("003", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest2: Sort an int32 array using comparer ");
try
{
int length = TestLibrary.Generator.GetByte(-55);
int[] i1 = new int[length];
int[] i2 = new int[length];
for (int i = 0; i < length; i++)
{
int value = TestLibrary.Generator.GetInt32(-55);
i1[i] = value;
i2[i] = value;
}
IComparer<int> b1 = new B<int>();
int startIdx = GetInt(0, length - 1);
int endIdx = GetInt(startIdx, length - 1);
int count = endIdx - startIdx + 1;
Array.Sort<int, int>(i1, i2, startIdx, count, b1);
for (int i = 0; i < length; i++)
{
if (i1[i] != i2[i])
{
TestLibrary.TestFramework.LogError("004", "The result is not the value as expected");
retVal = false;
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("005", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest3: Sort a char array using reverse comparer ");
try
{
char[] c1 = new char[10] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j' };
char[] d1 = new char[10] { 'a', 'e', 'd', 'c', 'b', 'f', 'g', 'h', 'i', 'j' };
int[] a1 = new int[10] { 2, 3, 4, 1, 0, 2, 12, 52, 31, 0 };
int[] b1 = new int[10] { 2, 0, 1, 4, 3, 2, 12, 52, 31, 0 };
IComparer<char> b2 = new B<char>();
Array.Sort<char, int>(c1, a1, 1, 4, b2);
for (int i = 0; i < 10; i++)
{
if (c1[i] != d1[i])
{
TestLibrary.TestFramework.LogError("006", "The result is not the value as expected");
retVal = false;
}
if (a1[i] != b1[i])
{
TestLibrary.TestFramework.LogError("007", "The result is not the value as expected");
retVal = false;
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest4: Sort an int array and the items array is null ");
try
{
int length = TestLibrary.Generator.GetInt16(-55);
int[] i1 = new int[length];
int[] i2 = new int[length];
for (int i = 0; i < length; i++)
{
int value = TestLibrary.Generator.GetByte(-55);
i1[i] = value;
i2[i] = value;
}
int startIdx = GetInt(0, length - 2);
int endIdx = GetInt(startIdx, length - 1);
int count = endIdx - startIdx + 1;
for (int i = startIdx; i < endIdx; i++) //manually quich sort
{
for (int j = i + 1; j <= endIdx; j++)
{
if (i2[i] > i2[j])
{
int temp = i2[i];
i2[i] = i2[j];
i2[j] = temp;
}
}
}
Array.Sort<int, int>(i1, null, startIdx, count, new B<int>());
for (int i = 0; i < length; i++)
{
if (i1[i] != i2[i])
{
TestLibrary.TestFramework.LogError("009", "The result is not the value as expected");
retVal = false;
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("010", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
#endregion
#region Nagetive Test Cases
public bool NegTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest1: The first argument is null reference ");
try
{
string[] s1 = null;
int[] i1 = { 1, 2, 3, 4, 5 };
Array.Sort<string, int>(s1, i1, 0, 2, new B<string>());
TestLibrary.TestFramework.LogError("101", "The ArgumentNullException is not throw as expected ");
retVal = false;
}
catch (ArgumentNullException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("102", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest2: The start index is less than the minimal bound of the array");
try
{
string[] s1 = new string[6]{"Jack",
"Mary",
"Peter",
"Mike",
"Tom",
"Allin"};
int[] i1 = new int[6] { 1, 2, 3, 4, 5, 6 };
Array.Sort<string, int>(s1, i1, -1, 4, new B<string>());
TestLibrary.TestFramework.LogError("103", "The ArgumentOutOfRangeException is not throw as expected ");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("104", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest3: Length is less than zero");
try
{
string[] s1 = new string[6]{"Jack",
"Mary",
"Peter",
"Mike",
"Tom",
"Allin"};
int[] i1 = new int[6] { 1, 2, 3, 4, 5, 6 };
Array.Sort<string, int>(s1, i1, 3, -3, new B<string>());
TestLibrary.TestFramework.LogError("105", "The ArgumentOutOfRangeException is not throw as expected ");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("106", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest4: The start index is greater than the maximal index of the array");
try
{
int length = TestLibrary.Generator.GetByte(-55);
string[] s1 = new string[length];
for (int i = 0; i < length; i++)
{
string value = TestLibrary.Generator.GetString(-55, false, 0, 10);
s1[i] = value;
}
int[] i1 = new int[6] { 1, 2, 3, 4, 5, 6 };
int startIdx = GetInt(1, Byte.MaxValue);
int increment = length;
Array.Sort<string, int>(s1, i1, startIdx + increment, 0, new B<string>());
TestLibrary.TestFramework.LogError("107", "The ArgumentException is not throw as expected ");
retVal = false;
}
catch (ArgumentException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("108", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest5()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest5: The start index is valid, but the length is too large for that index");
try
{
int length = TestLibrary.Generator.GetByte(-55);
string[] s1 = new string[length];
for (int i = 0; i < length; i++)
{
string value = TestLibrary.Generator.GetString(-55, false, 0, 10);
s1[i] = value;
}
int[] i1 = new int[6] { 1, 2, 3, 4, 5, 6 };
int startIdx = GetInt(1, length - 1);
int count = length;
Array.Sort<string, int>(s1, i1, startIdx, count);
TestLibrary.TestFramework.LogError("109", "The ArgumentException is not throw as expected ");
retVal = false;
}
catch (ArgumentException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("110", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest6()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest6:The implementation of comparer caused an error during the sort");
try
{
string[] s1 = new string[9]{"Jack",
"Mary",
"Peter",
"Mike",
"Tom",
"Allin",
"Kelly",
"Agassi",
"Koter"};
int[] i1 = new int[9] { 2, 34, 56, 87, 34, 23, 209, 34, 87 };
IComparer<string> d1 = new D<string>();
Array.Sort<string, int>(s1, i1, 0, 9, d1);
TestLibrary.TestFramework.LogError("111", "The ArgumentException is not throw as expected ");
retVal = false;
}
catch (ArgumentException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("112", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest7()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest7: The keys array does not implement the IComparable interface ");
try
{
E d1 = new E();
E d2 = new E();
E d3 = new E();
E d4 = new E();
int[] i2 = { 1, 2, 3, 4 };
E[] e = new E[4] { d1, d2, d3, d4 };
Array.Sort<E, int>(e, i2, null);
TestLibrary.TestFramework.LogError("113", "The InvalidOperationException is not throw as expected ");
retVal = false;
}
catch (InvalidOperationException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("114", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
#endregion
#endregion
public static int Main()
{
ArraySort14 test = new ArraySort14();
TestLibrary.TestFramework.BeginTestCase("ArraySort14");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
class A : IComparer<string>
{
#region IComparer<string> Members
public int Compare(string x, string y)
{
return x.CompareTo(y);
}
#endregion
}
class B<T> : IComparer<T> where T : IComparable
{
#region IComparer<T> Members
public int Compare(T x, T y)
{
if (typeof(T) == typeof(char))
{
return -x.CompareTo(y);
}
return x.CompareTo(y);
}
#endregion
}
class D<T> : IComparer<T> where T : IComparable
{
#region IComparer<T> Members
public int Compare(T x, T y)
{
if (x.CompareTo(x) == 0)
return -1;
return 1;
}
#endregion
}
class E
{
public E()
{
}
}
#region Help method for geting test data
private Int32 GetInt(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;
using System.Web.UI;
using System.Web.UI.WebControls;
using umbraco.BusinessLogic;
using umbraco.DataLayer;
using Umbraco.Core;
namespace umbraco.editorControls.tinymce
{
[Obsolete("IDataType and all other references to the legacy property editors are no longer used this will be removed from the codebase in future versions")]
public class tinyMCEPreValueConfigurator : System.Web.UI.WebControls.PlaceHolder, interfaces.IDataPrevalue
{
// UI controls
private CheckBoxList _editorButtons;
private CheckBox _enableRightClick;
private DropDownList _dropdownlist;
private CheckBoxList _advancedUsersList;
private CheckBoxList _stylesheetList;
private TextBox _width = new TextBox();
private TextBox _height = new TextBox();
private TextBox _maxImageWidth = new TextBox();
private CheckBox _fullWidth = new CheckBox();
private CheckBox _showLabel = new CheckBox();
private RegularExpressionValidator _widthValidator = new RegularExpressionValidator();
private RegularExpressionValidator _heightValidator = new RegularExpressionValidator();
private RegularExpressionValidator _maxImageWidthValidator = new RegularExpressionValidator();
// referenced datatype
private cms.businesslogic.datatype.BaseDataType _datatype;
private string _selectedButtons = "";
private string _advancedUsers = "";
private string _stylesheets = "";
/// <summary>
/// Unused, please do not use
/// </summary>
[Obsolete("Obsolete, For querying the database use the new UmbracoDatabase object ApplicationContext.Current.DatabaseContext.Database", false)]
public static ISqlHelper SqlHelper
{
get { return Application.SqlHelper; }
}
public tinyMCEPreValueConfigurator(cms.businesslogic.datatype.BaseDataType DataType)
{
// state it knows its datatypedefinitionid
_datatype = DataType;
setupChildControls();
}
private void setupChildControls()
{
_dropdownlist = new DropDownList();
_dropdownlist.ID = "dbtype";
_dropdownlist.Items.Add(DBTypes.Date.ToString());
_dropdownlist.Items.Add(DBTypes.Integer.ToString());
_dropdownlist.Items.Add(DBTypes.Ntext.ToString());
_dropdownlist.Items.Add(DBTypes.Nvarchar.ToString());
_editorButtons = new CheckBoxList();
_editorButtons.ID = "editorButtons";
_editorButtons.RepeatColumns = 4;
_editorButtons.CellPadding = 3;
_enableRightClick = new CheckBox();
_enableRightClick.ID = "enableRightClick";
_advancedUsersList = new CheckBoxList();
_advancedUsersList.ID = "advancedUsersList";
_stylesheetList = new CheckBoxList();
_stylesheetList.ID = "stylesheetList";
_showLabel = new CheckBox();
_showLabel.ID = "showLabel";
_maxImageWidth = new TextBox();
_maxImageWidth.ID = "maxImageWidth";
// put the childcontrols in context - ensuring that
// the viewstate is persisted etc.
Controls.Add(_dropdownlist);
Controls.Add(_enableRightClick);
Controls.Add(_editorButtons);
Controls.Add(_advancedUsersList);
Controls.Add(_stylesheetList);
Controls.Add(_width);
Controls.Add(_widthValidator);
Controls.Add(_height);
Controls.Add(_heightValidator);
Controls.Add(_showLabel);
Controls.Add(_maxImageWidth);
Controls.Add(_maxImageWidthValidator);
// Controls.Add(_fullWidth);
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
// add ids to controls
_width.ID = "width";
_height.ID = "height";
// initialize validators
_widthValidator.ValidationExpression = "0*[1-9][0-9]*";
_widthValidator.ErrorMessage = ui.Text("errorHandling", "errorIntegerWithoutTab", ui.Text("width"), new BasePages.BasePage().getUser());
_widthValidator.Display = ValidatorDisplay.Dynamic;
_widthValidator.ControlToValidate = _width.ID;
_heightValidator.ValidationExpression = "0*[1-9][0-9]*";
_heightValidator.ErrorMessage = ui.Text("errorHandling", "errorIntegerWithoutTab", ui.Text("height"), new BasePages.BasePage().getUser());
_heightValidator.ControlToValidate = _height.ID;
_heightValidator.Display = ValidatorDisplay.Dynamic;
_maxImageWidthValidator.ValidationExpression = "0*[1-9][0-9]*";
_maxImageWidthValidator.ErrorMessage = ui.Text("errorHandling", "errorIntegerWithoutTab", "'" + ui.Text("rteMaximumDefaultImgSize") + "'", new BasePages.BasePage().getUser());
_maxImageWidthValidator.ControlToValidate = _maxImageWidth.ID;
_maxImageWidthValidator.Display = ValidatorDisplay.Dynamic;
if (!Page.IsPostBack)
{
if (Configuration != null)
{
string[] config = Configuration.Split("|".ToCharArray());
if (config.Length > 0)
{
_selectedButtons = config[0];
if (config.Length > 1)
if (config[1] == "1")
_enableRightClick.Checked = true;
if (config.Length > 2)
_advancedUsers = config[2];
if (config.Length > 4 && config[4].Split(',').Length > 1)
{
// if (config[3] == "1")
// _fullWidth.Checked = true;
// else
// {
_width.Text = config[4].Split(',')[0];
_height.Text = config[4].Split(',')[1];
// }
}
// if width and height are empty or lower than 0 then set default sizes:
int tempWidth, tempHeight;
int.TryParse(_width.Text, out tempWidth);
int.TryParse(_height.Text, out tempHeight);
if (_width.Text.Trim() == "" || tempWidth < 1)
_width.Text = "500";
if (_height.Text.Trim() == "" || tempHeight < 1)
_height.Text = "400";
if (config.Length > 5)
_stylesheets = config[5];
if (config.Length > 6 && config[6] != "")
_showLabel.Checked = bool.Parse(config[6]);
if (config.Length > 7 && config[7] != "")
_maxImageWidth.Text = config[7];
else
_maxImageWidth.Text = "500";
}
// add editor buttons
IDictionaryEnumerator ide = tinyMCEConfiguration.SortedCommands.GetEnumerator();
while (ide.MoveNext())
{
tinyMCECommand cmd = (tinyMCECommand)ide.Value;
ListItem li =
new ListItem(
string.Format("<img src=\"{0}\" class=\"tinymceIcon\" alt=\"{1}\" /> ", cmd.Icon,
cmd.Alias), cmd.Alias);
if (_selectedButtons.IndexOf(cmd.Alias) > -1)
li.Selected = true;
_editorButtons.Items.Add(li);
}
// add users
var userService = ApplicationContext.Current.Services.UserService;
foreach (var ug in userService.GetAllUserGroups())
{
ListItem li = new ListItem(ug.Name, ug.Id.ToString());
if (("," + _advancedUsers + ",").IndexOf("," + ug.Id + ",") > -1)
li.Selected = true;
_advancedUsersList.Items.Add(li);
}
// add stylesheets
foreach (cms.businesslogic.web.StyleSheet st in cms.businesslogic.web.StyleSheet.GetAll())
{
ListItem li = new ListItem(st.Text, st.Id.ToString());
if (("," + _stylesheets + ",").IndexOf("," + st.Id.ToString() + ",") > -1)
li.Selected = true;
_stylesheetList.Items.Add(li);
}
}
// Mark the current db type
_dropdownlist.SelectedValue = _datatype.DBType.ToString();
}
}
public Control Editor
{
get
{
return this;
}
}
public virtual void Save()
{
_datatype.DBType = (cms.businesslogic.datatype.DBTypes)Enum.Parse(typeof(cms.businesslogic.datatype.DBTypes), _dropdownlist.SelectedValue, true);
// Generate data-string
string data = ",";
foreach (ListItem li in _editorButtons.Items)
if (li.Selected)
data += li.Value + ",";
data += "|";
if (_enableRightClick.Checked)
data += "1";
else
data += "0";
data += "|";
foreach (ListItem li in _advancedUsersList.Items)
if (li.Selected)
data += li.Value + ",";
data += "|";
data += "0|";
data += _width.Text + "," + _height.Text + "|";
foreach (ListItem li in _stylesheetList.Items)
if (li.Selected)
data += li.Value + ",";
data += "|";
data += _showLabel.Checked.ToString() + "|";
data += _maxImageWidth.Text + "|";
using (var sqlHelper = Application.SqlHelper)
{
// If the add new prevalue textbox is filled out - add the value to the collection.
IParameter[] SqlParams = new IParameter[] {
sqlHelper.CreateParameter("@value",data),
sqlHelper.CreateParameter("@dtdefid",_datatype.DataTypeDefinitionId)};
sqlHelper.ExecuteNonQuery("delete from cmsDataTypePreValues where datatypenodeid = @dtdefid", SqlParams);
// we need to populate the parameters again due to an issue with SQL CE
SqlParams = new IParameter[] {
sqlHelper.CreateParameter("@value",data),
sqlHelper.CreateParameter("@dtdefid",_datatype.DataTypeDefinitionId)};
sqlHelper.ExecuteNonQuery("insert into cmsDataTypePreValues (datatypenodeid,[value],sortorder,alias) values (@dtdefid,@value,0,'')", SqlParams);
}
}
protected override void Render(HtmlTextWriter writer)
{
writer.WriteLine("<table>");
writer.WriteLine("<tr><th>" + ui.Text("editdatatype", "dataBaseDatatype") + ":</th><td>");
_dropdownlist.RenderControl(writer);
writer.Write("</td></tr>");
writer.Write("<tr><th>" + ui.Text("editdatatype", "rteButtons") + ":</th><td>");
_editorButtons.RenderControl(writer);
writer.Write("</td></tr>");
writer.Write("<tr><th>" + ui.Text("editdatatype", "rteRelatedStylesheets") + ":</th><td>");
_stylesheetList.RenderControl(writer);
writer.Write("</td></tr>");
writer.Write("<tr><th>" + ui.Text("editdatatype", "rteEnableContextMenu") + ":</th><td>");
_enableRightClick.RenderControl(writer);
writer.Write("</td></tr>");
writer.Write("<tr><th>" + ui.Text("editdatatype", "rteEnableAdvancedSettings") + ":</th><td>");
_advancedUsersList.RenderControl(writer);
writer.Write("</td></tr>");
writer.Write("<tr><th>");
//"Size:</th><td>Maximum width and height: ");
// _fullWidth.RenderControl(writer);
writer.Write(ui.Text("editdatatype", "rteWidthAndHeight") + ":</th><td>");
_width.RenderControl(writer);
_widthValidator.RenderControl(writer);
writer.Write(" x ");
_height.RenderControl(writer);
_heightValidator.RenderControl(writer);
writer.Write("</td></tr>");
writer.Write("<tr><th>");
writer.Write(ui.Text("editdatatype", "rteMaximumDefaultImgSize") + ":</th><td>");
_maxImageWidth.RenderControl(writer);
_maxImageWidthValidator.RenderControl(writer);
writer.Write("</td></tr>");
writer.Write("<tr><th>" + ui.Text("editdatatype", "rteShowLabel") + ":</th><td>");
_showLabel.RenderControl(writer);
writer.Write("</td></tr>");
writer.Write("</table>");
}
public string Configuration
{
get
{
try
{
using (var sqlHelper = Application.SqlHelper)
return sqlHelper.ExecuteScalar<string>("select value from cmsDataTypePreValues where datatypenodeid = @datatypenodeid", sqlHelper.CreateParameter("@datatypenodeid", _datatype.DataTypeDefinitionId));
}
catch
{
return "";
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using GeoJSON.Net.Converters;
using GeoJSON.Net.Geometry;
using Newtonsoft.Json;
using NUnit.Framework;
namespace GeoJSON.Net.Tests.Geometry
{
[TestFixture]
public class GeometryTests : TestBase
{
public static IEnumerable<IGeometryObject> Geometries
{
get
{
var point = new Point(new Position(1, 2, 3));
var multiPoint = new MultiPoint(new List<Point>
{
new Point(new Position(52.379790828551016, 5.3173828125)),
new Point(new Position(52.36721467920585, 5.456085205078125)),
new Point(new Position(52.303440474272755, 5.386047363281249, 4.23))
});
var lineString = new LineString(new List<IPosition>
{
new Position(52.379790828551016, 5.3173828125),
new Position(52.36721467920585, 5.456085205078125),
new Position(52.303440474272755, 5.386047363281249, 4.23)
});
var multiLineString = new MultiLineString(new List<LineString>
{
new LineString(new List<IPosition>
{
new Position(52.379790828551016, 5.3173828125),
new Position(52.36721467920585, 5.456085205078125),
new Position(52.303440474272755, 5.386047363281249, 4.23)
}),
new LineString(new List<IPosition>
{
new Position(52.379790828551016, 5.3273828125),
new Position(52.36721467920585, 5.486085205078125),
new Position(52.303440474272755, 5.426047363281249, 4.23)
})
});
var polygon = new Polygon(new List<LineString>
{
new LineString(new List<IPosition>
{
new Position(52.379790828551016, 5.3173828125),
new Position(52.36721467920585, 5.456085205078125),
new Position(52.303440474272755, 5.386047363281249, 4.23),
new Position(52.379790828551016, 5.3173828125)
})
});
var multiPolygon = new MultiPolygon(new List<Polygon>
{
new Polygon(new List<LineString>
{
new LineString(new List<IPosition>
{
new Position(52.959676831105995, -2.6797102391514338),
new Position(52.9608756693609, -2.6769029474483279),
new Position(52.908449372833715, -2.6079763270327119),
new Position(52.891287242948195, -2.5815104708998668),
new Position(52.875476700983896, -2.5851645010668989),
new Position(52.882954723868622, -2.6050779098387191),
new Position(52.875255907042678, -2.6373482332006359),
new Position(52.878791122091066, -2.6932445076063951),
new Position(52.89564268523565, -2.6931334629377890),
new Position(52.930592009390175, -2.6548779332193022),
new Position(52.959676831105995, -2.6797102391514338)
})
}),
new Polygon(new List<LineString>
{
new LineString(new List<IPosition>
{
new Position(52.89610842810761, -2.69628632041613),
new Position(52.8894641454077, -2.75901233808515),
new Position(52.89938894657412, -2.7663172788742449),
new Position(52.90253773227807, -2.804554822840895),
new Position(52.929801009654575, -2.83848602260174),
new Position(52.94013913205788, -2.838979264607087),
new Position(52.937353122653533, -2.7978187468478741),
new Position(52.920394929466184, -2.772273870352612),
new Position(52.926572918779222, -2.6996509024137052),
new Position(52.89610842810761, -2.69628632041613)
})
})
});
yield return point;
yield return multiPoint;
yield return lineString;
yield return multiLineString;
yield return polygon;
yield return multiPolygon;
yield return new GeometryCollection(new List<IGeometryObject>
{
point,
multiPoint,
lineString,
multiLineString,
polygon,
multiPolygon
});
}
}
[Test]
[TestCaseSource(typeof(GeometryTests), nameof(Geometries))]
public void Can_Serialize_And_Deserialize_Geometry(IGeometryObject geometry)
{
var json = JsonConvert.SerializeObject(geometry);
var deserializedGeometry = JsonConvert.DeserializeObject<IGeometryObject>(json, new GeometryConverter());
Assert.AreEqual(geometry, deserializedGeometry);
}
[Test]
[TestCaseSource(typeof(GeometryTests), nameof(Geometries))]
public void Serialization_Observes_Indenting_Setting_Of_Serializer(IGeometryObject geometry)
{
var json = JsonConvert.SerializeObject(geometry, Formatting.Indented);
Assert.IsTrue(json.Contains(Environment.NewLine));
}
[Test]
[TestCaseSource(typeof(GeometryTests), nameof(Geometries))]
public void Serialization_Observes_No_Indenting_Setting_Of_Serializer(IGeometryObject geometry)
{
var json = JsonConvert.SerializeObject(geometry, Formatting.None);
Assert.IsFalse(json.Contains(Environment.NewLine));
Assert.IsFalse(json.Contains(" "));
}
[Test]
[TestCaseSource(typeof(GeometryTests), nameof(Geometries))]
public void Can_Serialize_And_Deserialize_Geometry_As_Object_Property(IGeometryObject geometry)
{
var classWithGeometry = new ClassWithGeometryProperty(geometry);
var json = JsonConvert.SerializeObject(classWithGeometry);
var deserializedClassWithGeometry = JsonConvert.DeserializeObject<ClassWithGeometryProperty>(json);
Assert.AreEqual(classWithGeometry, deserializedClassWithGeometry);
}
[Test]
[TestCaseSource(typeof(GeometryTests), nameof(Geometries))]
public void Serialized_And_Deserialized_Equals_And_Share_HashCode(IGeometryObject geometry)
{
var classWithGeometry = new ClassWithGeometryProperty(geometry);
var json = JsonConvert.SerializeObject(classWithGeometry);
var deserializedClassWithGeometry = JsonConvert.DeserializeObject<ClassWithGeometryProperty>(json);
var actual = classWithGeometry;
var expected = deserializedClassWithGeometry;
Assert.IsTrue(actual.Equals(expected));
Assert.IsTrue(actual.Equals(actual));
Assert.IsTrue(expected.Equals(actual));
Assert.IsTrue(expected.Equals(expected));
Assert.IsTrue(classWithGeometry == deserializedClassWithGeometry);
Assert.IsTrue(deserializedClassWithGeometry == classWithGeometry);
Assert.AreEqual(actual.GetHashCode(), expected.GetHashCode());
}
internal class ClassWithGeometryProperty
{
public ClassWithGeometryProperty(IGeometryObject geometry)
{
Geometry = geometry;
}
[JsonConverter(typeof(GeometryConverter))]
public IGeometryObject Geometry { get; set; }
/// <summary>
/// Determines whether the specified <see cref="T:System.Object" /> is equal to the current
/// <see cref="T:System.Object" />.
/// </summary>
/// <returns>
/// true if the specified object is equal to the current object; otherwise, false.
/// </returns>
/// <param name="obj">The object to compare with the current object. </param>
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
{
return false;
}
if (ReferenceEquals(this, obj))
{
return true;
}
if (obj.GetType() != GetType())
{
return false;
}
return Equals((ClassWithGeometryProperty)obj);
}
/// <summary>
/// Serves as a hash function for a particular type.
/// </summary>
/// <returns>
/// A hash code for the current <see cref="T:System.Object" />.
/// </returns>
public override int GetHashCode()
{
return Geometry.GetHashCode();
}
public static bool operator ==(ClassWithGeometryProperty left, ClassWithGeometryProperty right)
{
return Equals(left, right);
}
public static bool operator !=(ClassWithGeometryProperty left, ClassWithGeometryProperty right)
{
return !Equals(left, right);
}
private bool Equals(ClassWithGeometryProperty other)
{
return Geometry.Equals(other.Geometry);
}
}
}
}
| |
/* ====================================================================
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.EventUserModel
{
using System;
using System.Text;
using NPOI.HSSF.Record;
using NPOI.HSSF.EventUserModel;
using NPOI.HSSF.EventUserModel.DummyRecord;
/// <summary>
/// A HSSFListener which tracks rows and columns, and will
/// trigger your HSSFListener for all rows and cells,
/// even the ones that aren't actually stored in the file.
/// This allows your code to have a more "Excel" like
/// view of the data in the file, and not have to worry
/// (as much) about if a particular row/cell Is in the
/// file, or was skipped from being written as it was
/// blank.
/// </summary>
internal class MissingRecordAwareHSSFListener : HSSFListener
{
private HSSFListener childListener;
// Need to have different counters for cell rows and
// row rows, as you sometimes get a RowRecord in the
// middle of some cells, and that'd break everything
private int lastRowRow;
private int lastCellRow;
private int lastCellColumn;
/// <summary>
/// Constructs a new MissingRecordAwareHSSFListener, which
/// will fire ProcessRecord on the supplied child
/// HSSFListener for all Records, and missing records.
/// </summary>
/// <param name="listener">The HSSFListener to pass records on to</param>
public MissingRecordAwareHSSFListener(HSSFListener listener)
{
ResetCounts();
childListener = listener;
}
/// <summary>
/// Process an HSSF Record. Called when a record occurs in an HSSF file.
/// </summary>
/// <param name="record"></param>
public void ProcessRecord(Record record)
{
int thisRow;
int thisColumn;
CellValueRecordInterface[] expandedRecords = null;
if (record is CellValueRecordInterface)
{
CellValueRecordInterface valueRec = (CellValueRecordInterface)record;
thisRow = valueRec.Row;
thisColumn = valueRec.Column;
}
else
{
thisRow = -1;
thisColumn = -1;
switch (record.Sid)
{
// the BOFRecord can represent either the beginning of a sheet or the workbook
case BOFRecord.sid:
BOFRecord bof = (BOFRecord)record;
if (bof.Type == BOFRecord.TYPE_WORKBOOK || bof.Type == BOFRecord.TYPE_WORKSHEET)
{
// Reset the row and column counts - new workbook / worksheet
ResetCounts();
}
break;
case RowRecord.sid:
RowRecord rowrec = (RowRecord)record;
//Console.WriteLine("Row " + rowrec.RowNumber + " found, first column at "
// + rowrec.GetFirstCol() + " last column at " + rowrec.GetLastCol());
// If there's a jump in rows, fire off missing row records
if (lastRowRow + 1 < rowrec.RowNumber)
{
for (int i = (lastRowRow + 1); i < rowrec.RowNumber; i++)
{
MissingRowDummyRecord dr = new MissingRowDummyRecord(i);
childListener.ProcessRecord(dr);
}
}
// Record this as the last row we saw
lastRowRow = rowrec.RowNumber;
break;
case SharedFormulaRecord.sid:
// SharedFormulaRecord occurs after the first FormulaRecord of the cell range.
// There are probably (but not always) more cell records after this
// - so don't fire off the LastCellOfRowDummyRecord yet
childListener.ProcessRecord(record);
return;
case MulBlankRecord.sid:
// These appear in the middle of the cell records, to
// specify that the next bunch are empty but styled
// Expand this out into multiple blank cells
MulBlankRecord mbr = (MulBlankRecord)record;
expandedRecords = RecordFactory.ConvertBlankRecords(mbr);
break;
case MulRKRecord.sid:
// This is multiple consecutive number cells in one record
// Exand this out into multiple regular number cells
MulRKRecord mrk = (MulRKRecord)record;
expandedRecords = RecordFactory.ConvertRKRecords(mrk);
break;
case NoteRecord.sid:
NoteRecord nrec = (NoteRecord)record;
thisRow = nrec.Row;
thisColumn = nrec.Column;
break;
default:
//Console.WriteLine(record.GetClass());
break;
}
}
// First part of expanded record handling
if (expandedRecords != null && expandedRecords.Length > 0)
{
thisRow = expandedRecords[0].Row;
thisColumn = expandedRecords[0].Column;
}
// If we're on cells, and this cell isn't in the same
// row as the last one, then fire the
// dummy end-of-row records
if (thisRow != lastCellRow && lastCellRow > -1)
{
for (int i = lastCellRow; i < thisRow; i++)
{
int cols = -1;
if (i == lastCellRow)
{
cols = lastCellColumn;
}
childListener.ProcessRecord(new LastCellOfRowDummyRecord(i, cols));
}
}
// If we've just finished with the cells, then fire the
// final dummy end-of-row record
if (lastCellRow != -1 && lastCellColumn != -1 && thisRow == -1)
{
childListener.ProcessRecord(new LastCellOfRowDummyRecord(lastCellRow, lastCellColumn));
lastCellRow = -1;
lastCellColumn = -1;
}
// If we've moved onto a new row, the ensure we re-set
// the column counter
if (thisRow != lastCellRow)
{
lastCellColumn = -1;
}
// If there's a gap in the cells, then fire
// the dummy cell records
if (lastCellColumn != thisColumn - 1)
{
for (int i = lastCellColumn + 1; i < thisColumn; i++)
{
childListener.ProcessRecord(new MissingCellDummyRecord(thisRow, i));
}
}
// Next part of expanded record handling
if (expandedRecords != null && expandedRecords.Length > 0)
{
thisColumn = expandedRecords[expandedRecords.Length - 1].Column;
}
// Update cell and row counts as needed
if (thisColumn != -1)
{
lastCellColumn = thisColumn;
lastCellRow = thisRow;
}
// Pass along the record(s)
if (expandedRecords != null && expandedRecords.Length > 0)
{
foreach (CellValueRecordInterface r in expandedRecords)
{
childListener.ProcessRecord((Record)r);
}
}
else
{
childListener.ProcessRecord(record);
}
}
private void ResetCounts()
{
lastRowRow = -1;
lastCellRow = -1;
lastCellColumn = -1;
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Reflection;
using Nini.Config;
using OpenSim.Framework;
using OpenSim.Server.Base;
using OpenSim.Services.Interfaces;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Server.Handlers.Base;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
using log4net;
using Nwc.XmlRpc;
using OpenMetaverse;
namespace OpenSim.Server.Handlers.Hypergrid
{
public class UserAgentServerConnector : ServiceConnector
{
// private static readonly ILog m_log =
// LogManager.GetLogger(
// MethodBase.GetCurrentMethod().DeclaringType);
private IUserAgentService m_HomeUsersService;
public IUserAgentService HomeUsersService
{
get { return m_HomeUsersService; }
}
private string[] m_AuthorizedCallers;
private bool m_VerifyCallers = false;
public UserAgentServerConnector(IConfigSource config, IHttpServer server) :
this(config, server, (IFriendsSimConnector)null)
{
}
public UserAgentServerConnector(IConfigSource config, IHttpServer server, string configName) :
this(config, server)
{
}
public UserAgentServerConnector(IConfigSource config, IHttpServer server, IFriendsSimConnector friendsConnector) :
base(config, server, String.Empty)
{
IConfig gridConfig = config.Configs["UserAgentService"];
if (gridConfig != null)
{
string serviceDll = gridConfig.GetString("LocalServiceModule", string.Empty);
Object[] args = new Object[] { config, friendsConnector };
m_HomeUsersService = ServerUtils.LoadPlugin<IUserAgentService>(serviceDll, args);
}
if (m_HomeUsersService == null)
throw new Exception("UserAgent server connector cannot proceed because of missing service");
string loginServerIP = gridConfig.GetString("LoginServerIP", "127.0.0.1");
bool proxy = gridConfig.GetBoolean("HasProxy", false);
m_VerifyCallers = gridConfig.GetBoolean("VerifyCallers", false);
string csv = gridConfig.GetString("AuthorizedCallers", "127.0.0.1");
csv = csv.Replace(" ", "");
m_AuthorizedCallers = csv.Split(',');
server.AddXmlRPCHandler("agent_is_coming_home", AgentIsComingHome, false);
server.AddXmlRPCHandler("get_home_region", GetHomeRegion, false);
server.AddXmlRPCHandler("verify_agent", VerifyAgent, false);
server.AddXmlRPCHandler("verify_client", VerifyClient, false);
server.AddXmlRPCHandler("logout_agent", LogoutAgent, false);
server.AddXmlRPCHandler("status_notification", StatusNotification, false);
server.AddXmlRPCHandler("get_online_friends", GetOnlineFriends, false);
server.AddXmlRPCHandler("get_user_info", GetUserInfo, false);
server.AddXmlRPCHandler("get_server_urls", GetServerURLs, false);
server.AddXmlRPCHandler("locate_user", LocateUser, false);
server.AddXmlRPCHandler("get_uui", GetUUI, false);
server.AddXmlRPCHandler("get_uuid", GetUUID, false);
server.AddStreamHandler(new HomeAgentHandler(m_HomeUsersService, loginServerIP, proxy));
}
public XmlRpcResponse GetHomeRegion(XmlRpcRequest request, IPEndPoint remoteClient)
{
Hashtable requestData = (Hashtable)request.Params[0];
//string host = (string)requestData["host"];
//string portstr = (string)requestData["port"];
string userID_str = (string)requestData["userID"];
UUID userID = UUID.Zero;
UUID.TryParse(userID_str, out userID);
Vector3 position = Vector3.UnitY, lookAt = Vector3.UnitY;
GridRegion regInfo = m_HomeUsersService.GetHomeRegion(userID, out position, out lookAt);
Hashtable hash = new Hashtable();
if (regInfo == null)
hash["result"] = "false";
else
{
hash["result"] = "true";
hash["uuid"] = regInfo.RegionID.ToString();
hash["x"] = regInfo.RegionLocX.ToString();
hash["y"] = regInfo.RegionLocY.ToString();
hash["region_name"] = regInfo.RegionName;
hash["hostname"] = regInfo.ExternalHostName;
hash["http_port"] = regInfo.HttpPort.ToString();
hash["internal_port"] = regInfo.InternalEndPoint.Port.ToString();
hash["position"] = position.ToString();
hash["lookAt"] = lookAt.ToString();
}
XmlRpcResponse response = new XmlRpcResponse();
response.Value = hash;
return response;
}
public XmlRpcResponse AgentIsComingHome(XmlRpcRequest request, IPEndPoint remoteClient)
{
Hashtable requestData = (Hashtable)request.Params[0];
//string host = (string)requestData["host"];
//string portstr = (string)requestData["port"];
string sessionID_str = (string)requestData["sessionID"];
UUID sessionID = UUID.Zero;
UUID.TryParse(sessionID_str, out sessionID);
string gridName = (string)requestData["externalName"];
bool success = m_HomeUsersService.IsAgentComingHome(sessionID, gridName);
Hashtable hash = new Hashtable();
hash["result"] = success.ToString();
XmlRpcResponse response = new XmlRpcResponse();
response.Value = hash;
return response;
}
public XmlRpcResponse VerifyAgent(XmlRpcRequest request, IPEndPoint remoteClient)
{
Hashtable requestData = (Hashtable)request.Params[0];
//string host = (string)requestData["host"];
//string portstr = (string)requestData["port"];
string sessionID_str = (string)requestData["sessionID"];
UUID sessionID = UUID.Zero;
UUID.TryParse(sessionID_str, out sessionID);
string token = (string)requestData["token"];
bool success = m_HomeUsersService.VerifyAgent(sessionID, token);
Hashtable hash = new Hashtable();
hash["result"] = success.ToString();
XmlRpcResponse response = new XmlRpcResponse();
response.Value = hash;
return response;
}
public XmlRpcResponse VerifyClient(XmlRpcRequest request, IPEndPoint remoteClient)
{
Hashtable requestData = (Hashtable)request.Params[0];
//string host = (string)requestData["host"];
//string portstr = (string)requestData["port"];
string sessionID_str = (string)requestData["sessionID"];
UUID sessionID = UUID.Zero;
UUID.TryParse(sessionID_str, out sessionID);
string token = (string)requestData["token"];
bool success = m_HomeUsersService.VerifyClient(sessionID, token);
Hashtable hash = new Hashtable();
hash["result"] = success.ToString();
XmlRpcResponse response = new XmlRpcResponse();
response.Value = hash;
return response;
}
public XmlRpcResponse LogoutAgent(XmlRpcRequest request, IPEndPoint remoteClient)
{
Hashtable requestData = (Hashtable)request.Params[0];
//string host = (string)requestData["host"];
//string portstr = (string)requestData["port"];
string sessionID_str = (string)requestData["sessionID"];
UUID sessionID = UUID.Zero;
UUID.TryParse(sessionID_str, out sessionID);
string userID_str = (string)requestData["userID"];
UUID userID = UUID.Zero;
UUID.TryParse(userID_str, out userID);
m_HomeUsersService.LogoutAgent(userID, sessionID);
Hashtable hash = new Hashtable();
hash["result"] = "true";
XmlRpcResponse response = new XmlRpcResponse();
response.Value = hash;
return response;
}
[Obsolete]
public XmlRpcResponse StatusNotification(XmlRpcRequest request, IPEndPoint remoteClient)
{
Hashtable hash = new Hashtable();
hash["result"] = "false";
Hashtable requestData = (Hashtable)request.Params[0];
//string host = (string)requestData["host"];
//string portstr = (string)requestData["port"];
if (requestData.ContainsKey("userID") && requestData.ContainsKey("online"))
{
string userID_str = (string)requestData["userID"];
UUID userID = UUID.Zero;
UUID.TryParse(userID_str, out userID);
List<string> ids = new List<string>();
foreach (object key in requestData.Keys)
{
if (key is string && ((string)key).StartsWith("friend_") && requestData[key] != null)
ids.Add(requestData[key].ToString());
}
bool online = false;
bool.TryParse(requestData["online"].ToString(), out online);
// let's spawn a thread for this, because it may take a long time...
List<UUID> friendsOnline = m_HomeUsersService.StatusNotification(ids, userID, online);
if (friendsOnline.Count > 0)
{
int i = 0;
foreach (UUID id in friendsOnline)
{
hash["friend_" + i.ToString()] = id.ToString();
i++;
}
}
else
hash["result"] = "No Friends Online";
}
XmlRpcResponse response = new XmlRpcResponse();
response.Value = hash;
return response;
}
[Obsolete]
public XmlRpcResponse GetOnlineFriends(XmlRpcRequest request, IPEndPoint remoteClient)
{
Hashtable hash = new Hashtable();
Hashtable requestData = (Hashtable)request.Params[0];
//string host = (string)requestData["host"];
//string portstr = (string)requestData["port"];
if (requestData.ContainsKey("userID"))
{
string userID_str = (string)requestData["userID"];
UUID userID = UUID.Zero;
UUID.TryParse(userID_str, out userID);
List<string> ids = new List<string>();
foreach (object key in requestData.Keys)
{
if (key is string && ((string)key).StartsWith("friend_") && requestData[key] != null)
ids.Add(requestData[key].ToString());
}
//List<UUID> online = m_HomeUsersService.GetOnlineFriends(userID, ids);
//if (online.Count > 0)
//{
// int i = 0;
// foreach (UUID id in online)
// {
// hash["friend_" + i.ToString()] = id.ToString();
// i++;
// }
//}
//else
// hash["result"] = "No Friends Online";
}
XmlRpcResponse response = new XmlRpcResponse();
response.Value = hash;
return response;
}
public XmlRpcResponse GetUserInfo(XmlRpcRequest request, IPEndPoint remoteClient)
{
Hashtable hash = new Hashtable();
Hashtable requestData = (Hashtable)request.Params[0];
// This needs checking!
if (requestData.ContainsKey("userID"))
{
string userID_str = (string)requestData["userID"];
UUID userID = UUID.Zero;
UUID.TryParse(userID_str, out userID);
//int userFlags = m_HomeUsersService.GetUserFlags(userID);
Dictionary<string,object> userInfo = m_HomeUsersService.GetUserInfo(userID);
if (userInfo.Count > 0)
{
foreach (KeyValuePair<string, object> kvp in userInfo)
{
hash[kvp.Key] = kvp.Value;
}
}
else
{
hash["result"] = "failure";
}
}
XmlRpcResponse response = new XmlRpcResponse();
response.Value = hash;
return response;
}
public XmlRpcResponse GetServerURLs(XmlRpcRequest request, IPEndPoint remoteClient)
{
Hashtable hash = new Hashtable();
Hashtable requestData = (Hashtable)request.Params[0];
//string host = (string)requestData["host"];
//string portstr = (string)requestData["port"];
if (requestData.ContainsKey("userID"))
{
string userID_str = (string)requestData["userID"];
UUID userID = UUID.Zero;
UUID.TryParse(userID_str, out userID);
Dictionary<string, object> serverURLs = m_HomeUsersService.GetServerURLs(userID);
if (serverURLs.Count > 0)
{
foreach (KeyValuePair<string, object> kvp in serverURLs)
hash["SRV_" + kvp.Key] = kvp.Value.ToString();
}
else
hash["result"] = "No Service URLs";
}
XmlRpcResponse response = new XmlRpcResponse();
response.Value = hash;
return response;
}
/// <summary>
/// Locates the user.
/// This is a sensitive operation, only authorized IP addresses can perform it.
/// </summary>
/// <param name="request"></param>
/// <param name="remoteClient"></param>
/// <returns></returns>
public XmlRpcResponse LocateUser(XmlRpcRequest request, IPEndPoint remoteClient)
{
Hashtable hash = new Hashtable();
bool authorized = true;
if (m_VerifyCallers)
{
authorized = false;
foreach (string s in m_AuthorizedCallers)
if (s == remoteClient.Address.ToString())
{
authorized = true;
break;
}
}
if (authorized)
{
Hashtable requestData = (Hashtable)request.Params[0];
//string host = (string)requestData["host"];
//string portstr = (string)requestData["port"];
if (requestData.ContainsKey("userID"))
{
string userID_str = (string)requestData["userID"];
UUID userID = UUID.Zero;
UUID.TryParse(userID_str, out userID);
string url = m_HomeUsersService.LocateUser(userID);
if (url != string.Empty)
hash["URL"] = url;
else
hash["result"] = "Unable to locate user";
}
}
XmlRpcResponse response = new XmlRpcResponse();
response.Value = hash;
return response;
}
/// <summary>
/// Returns the UUI of a user given a UUID.
/// </summary>
/// <param name="request"></param>
/// <param name="remoteClient"></param>
/// <returns></returns>
public XmlRpcResponse GetUUI(XmlRpcRequest request, IPEndPoint remoteClient)
{
Hashtable hash = new Hashtable();
Hashtable requestData = (Hashtable)request.Params[0];
//string host = (string)requestData["host"];
//string portstr = (string)requestData["port"];
if (requestData.ContainsKey("userID") && requestData.ContainsKey("targetUserID"))
{
string userID_str = (string)requestData["userID"];
UUID userID = UUID.Zero;
UUID.TryParse(userID_str, out userID);
string tuserID_str = (string)requestData["targetUserID"];
UUID targetUserID = UUID.Zero;
UUID.TryParse(tuserID_str, out targetUserID);
string uui = m_HomeUsersService.GetUUI(userID, targetUserID);
if (uui != string.Empty)
hash["UUI"] = uui;
else
hash["result"] = "User unknown";
}
XmlRpcResponse response = new XmlRpcResponse();
response.Value = hash;
return response;
}
/// <summary>
/// Gets the UUID of a user given First name, Last name.
/// </summary>
/// <param name="request"></param>
/// <param name="remoteClient"></param>
/// <returns></returns>
public XmlRpcResponse GetUUID(XmlRpcRequest request, IPEndPoint remoteClient)
{
Hashtable hash = new Hashtable();
Hashtable requestData = (Hashtable)request.Params[0];
//string host = (string)requestData["host"];
//string portstr = (string)requestData["port"];
if (requestData.ContainsKey("first") && requestData.ContainsKey("last"))
{
string first = (string)requestData["first"];
string last = (string)requestData["last"];
UUID uuid = m_HomeUsersService.GetUUID(first, last);
hash["UUID"] = uuid.ToString();
}
XmlRpcResponse response = new XmlRpcResponse();
response.Value = hash;
return response;
}
}
}
| |
#region Apache License
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to you under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
// MONO 1.0 Beta mcs does not like #if !A && !B && !C syntax
// .NET Compact Framework 1.0 has no support for Win32 Console API's
#if !NETCF
// .Mono 1.0 has no support for Win32 Console API's
#if !MONO
// SSCLI 1.0 has no support for Win32 Console API's
#if !SSCLI
// We don't want framework or platform specific code in the CLI version of log4net
#if !CLI_1_0
using System;
using System.Globalization;
using System.Runtime.InteropServices;
using log4net.Layout;
using log4net.Util;
namespace log4net.Appender
{
/// <summary>
/// Appends logging events to the console.
/// </summary>
/// <remarks>
/// <para>
/// ColoredConsoleAppender appends log events to the standard output stream
/// or the error output stream using a layout specified by the
/// user. It also allows the color of a specific type of message to be set.
/// </para>
/// <para>
/// By default, all output is written to the console's standard output stream.
/// The <see cref="Target"/> property can be set to direct the output to the
/// error stream.
/// </para>
/// <para>
/// NOTE: This appender writes directly to the application's attached console
/// not to the <c>System.Console.Out</c> or <c>System.Console.Error</c> <c>TextWriter</c>.
/// The <c>System.Console.Out</c> and <c>System.Console.Error</c> streams can be
/// programmatically redirected (for example NUnit does this to capture program output).
/// This appender will ignore these redirections because it needs to use Win32
/// API calls to colorize the output. To respect these redirections the <see cref="ConsoleAppender"/>
/// must be used.
/// </para>
/// <para>
/// When configuring the colored console appender, mapping should be
/// specified to map a logging level to a color. For example:
/// </para>
/// <code lang="XML" escaped="true">
/// <mapping>
/// <level value="ERROR" />
/// <foreColor value="White" />
/// <backColor value="Red, HighIntensity" />
/// </mapping>
/// <mapping>
/// <level value="DEBUG" />
/// <backColor value="Green" />
/// </mapping>
/// </code>
/// <para>
/// The Level is the standard log4net logging level and ForeColor and BackColor can be any
/// combination of the following values:
/// <list type="bullet">
/// <item><term>Blue</term><description></description></item>
/// <item><term>Green</term><description></description></item>
/// <item><term>Red</term><description></description></item>
/// <item><term>White</term><description></description></item>
/// <item><term>Yellow</term><description></description></item>
/// <item><term>Purple</term><description></description></item>
/// <item><term>Cyan</term><description></description></item>
/// <item><term>HighIntensity</term><description></description></item>
/// </list>
/// </para>
/// </remarks>
/// <author>Rick Hobbs</author>
/// <author>Nicko Cadell</author>
public class ColoredConsoleAppender : AppenderSkeleton
{
#region Colors Enum
/// <summary>
/// The enum of possible color values for use with the color mapping method
/// </summary>
/// <remarks>
/// <para>
/// The following flags can be combined together to
/// form the colors.
/// </para>
/// </remarks>
/// <seealso cref="ColoredConsoleAppender" />
[Flags]
public enum Colors : int
{
/// <summary>
/// color is blue
/// </summary>
Blue = 0x0001,
/// <summary>
/// color is green
/// </summary>
Green = 0x0002,
/// <summary>
/// color is red
/// </summary>
Red = 0x0004,
/// <summary>
/// color is white
/// </summary>
White = Blue | Green | Red,
/// <summary>
/// color is yellow
/// </summary>
Yellow = Red | Green,
/// <summary>
/// color is purple
/// </summary>
Purple = Red | Blue,
/// <summary>
/// color is cyan
/// </summary>
Cyan = Green | Blue,
/// <summary>
/// color is intensified
/// </summary>
HighIntensity = 0x0008,
}
#endregion // Colors Enum
#region Public Instance Constructors
/// <summary>
/// Initializes a new instance of the <see cref="ColoredConsoleAppender" /> class.
/// </summary>
/// <remarks>
/// The instance of the <see cref="ColoredConsoleAppender" /> class is set up to write
/// to the standard output stream.
/// </remarks>
public ColoredConsoleAppender()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ColoredConsoleAppender" /> class
/// with the specified layout.
/// </summary>
/// <param name="layout">the layout to use for this appender</param>
/// <remarks>
/// The instance of the <see cref="ColoredConsoleAppender" /> class is set up to write
/// to the standard output stream.
/// </remarks>
[Obsolete("Instead use the default constructor and set the Layout property. Scheduled removal in v10.0.0.")]
public ColoredConsoleAppender(ILayout layout) : this(layout, false)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ColoredConsoleAppender" /> class
/// with the specified layout.
/// </summary>
/// <param name="layout">the layout to use for this appender</param>
/// <param name="writeToErrorStream">flag set to <c>true</c> to write to the console error stream</param>
/// <remarks>
/// When <paramref name="writeToErrorStream" /> is set to <c>true</c>, output is written to
/// the standard error output stream. Otherwise, output is written to the standard
/// output stream.
/// </remarks>
[Obsolete("Instead use the default constructor and set the Layout & Target properties. Scheduled removal in v10.0.0.")]
public ColoredConsoleAppender(ILayout layout, bool writeToErrorStream)
{
Layout = layout;
m_writeToErrorStream = writeToErrorStream;
}
#endregion // Public Instance Constructors
#region Public Instance Properties
/// <summary>
/// Target is the value of the console output stream.
/// This is either <c>"Console.Out"</c> or <c>"Console.Error"</c>.
/// </summary>
/// <value>
/// Target is the value of the console output stream.
/// This is either <c>"Console.Out"</c> or <c>"Console.Error"</c>.
/// </value>
/// <remarks>
/// <para>
/// Target is the value of the console output stream.
/// This is either <c>"Console.Out"</c> or <c>"Console.Error"</c>.
/// </para>
/// </remarks>
virtual public string Target
{
get { return m_writeToErrorStream ? ConsoleError : ConsoleOut; }
set
{
string v = value.Trim();
if (string.Compare(ConsoleError, v, true, CultureInfo.InvariantCulture) == 0)
{
m_writeToErrorStream = true;
}
else
{
m_writeToErrorStream = false;
}
}
}
/// <summary>
/// Add a mapping of level to color - done by the config file
/// </summary>
/// <param name="mapping">The mapping to add</param>
/// <remarks>
/// <para>
/// Add a <see cref="LevelColors"/> mapping to this appender.
/// Each mapping defines the foreground and background colors
/// for a level.
/// </para>
/// </remarks>
public void AddMapping(LevelColors mapping)
{
m_levelMapping.Add(mapping);
}
#endregion // Public Instance Properties
#region Override implementation of AppenderSkeleton
/// <summary>
/// This method is called by the <see cref="M:AppenderSkeleton.DoAppend(log4net.Core.LoggingEvent)"/> method.
/// </summary>
/// <param name="loggingEvent">The event to log.</param>
/// <remarks>
/// <para>
/// Writes the event to the console.
/// </para>
/// <para>
/// The format of the output will depend on the appender's layout.
/// </para>
/// </remarks>
#if NET_4_0 || MONO_4_0
[System.Security.SecuritySafeCritical]
#endif
[System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, UnmanagedCode = true)]
override protected void Append(log4net.Core.LoggingEvent loggingEvent)
{
if (m_consoleOutputWriter != null)
{
IntPtr consoleHandle = IntPtr.Zero;
if (m_writeToErrorStream)
{
// Write to the error stream
consoleHandle = GetStdHandle(STD_ERROR_HANDLE);
}
else
{
// Write to the output stream
consoleHandle = GetStdHandle(STD_OUTPUT_HANDLE);
}
// Default to white on black
ushort colorInfo = (ushort)Colors.White;
// see if there is a specified lookup
LevelColors levelColors = m_levelMapping.Lookup(loggingEvent.Level) as LevelColors;
if (levelColors != null)
{
colorInfo = levelColors.CombinedColor;
}
// Render the event to a string
string strLoggingMessage = RenderLoggingEvent(loggingEvent);
// get the current console color - to restore later
CONSOLE_SCREEN_BUFFER_INFO bufferInfo;
GetConsoleScreenBufferInfo(consoleHandle, out bufferInfo);
// set the console colors
SetConsoleTextAttribute(consoleHandle, colorInfo);
// Using WriteConsoleW seems to be unreliable.
// If a large buffer is written, say 15,000 chars
// Followed by a larger buffer, say 20,000 chars
// then WriteConsoleW will fail, last error 8
// 'Not enough storage is available to process this command.'
//
// Although the documentation states that the buffer must
// be less that 64KB (i.e. 32,000 WCHARs) the longest string
// that I can write out a the first call to WriteConsoleW
// is only 30,704 chars.
//
// Unlike the WriteFile API the WriteConsoleW method does not
// seem to be able to partially write out from the input buffer.
// It does have a lpNumberOfCharsWritten parameter, but this is
// either the length of the input buffer if any output was written,
// or 0 when an error occurs.
//
// All results above were observed on Windows XP SP1 running
// .NET runtime 1.1 SP1.
//
// Old call to WriteConsoleW:
//
// WriteConsoleW(
// consoleHandle,
// strLoggingMessage,
// (UInt32)strLoggingMessage.Length,
// out (UInt32)ignoreWrittenCount,
// IntPtr.Zero);
//
// Instead of calling WriteConsoleW we use WriteFile which
// handles large buffers correctly. Because WriteFile does not
// handle the codepage conversion as WriteConsoleW does we
// need to use a System.IO.StreamWriter with the appropriate
// Encoding. The WriteFile calls are wrapped up in the
// System.IO.__ConsoleStream internal class obtained through
// the System.Console.OpenStandardOutput method.
//
// See the ActivateOptions method below for the code that
// retrieves and wraps the stream.
// The windows console uses ScrollConsoleScreenBuffer internally to
// scroll the console buffer when the display buffer of the console
// has been used up. ScrollConsoleScreenBuffer fills the area uncovered
// by moving the current content with the background color
// currently specified on the console. This means that it fills the
// whole line in front of the cursor position with the current
// background color.
// This causes an issue when writing out text with a non default
// background color. For example; We write a message with a Blue
// background color and the scrollable area of the console is full.
// When we write the newline at the end of the message the console
// needs to scroll the buffer to make space available for the new line.
// The ScrollConsoleScreenBuffer internals will fill the newly created
// space with the current background color: Blue.
// We then change the console color back to default (White text on a
// Black background). We write some text to the console, the text is
// written correctly in White with a Black background, however the
// remainder of the line still has a Blue background.
//
// This causes a disjointed appearance to the output where the background
// colors change.
//
// This can be remedied by restoring the console colors before causing
// the buffer to scroll, i.e. before writing the last newline. This does
// assume that the rendered message will end with a newline.
//
// Therefore we identify a trailing newline in the message and don't
// write this to the output, then we restore the console color and write
// a newline. Note that we must AutoFlush before we restore the console
// color otherwise we will have no effect.
//
// There will still be a slight artefact for the last line of the message
// will have the background extended to the end of the line, however this
// is unlikely to cause any user issues.
//
// Note that none of the above is visible while the console buffer is scrollable
// within the console window viewport, the effects only arise when the actual
// buffer is full and needs to be scrolled.
char[] messageCharArray = strLoggingMessage.ToCharArray();
int arrayLength = messageCharArray.Length;
bool appendNewline = false;
// Trim off last newline, if it exists
if (arrayLength > 1 && messageCharArray[arrayLength-2] == '\r' && messageCharArray[arrayLength-1] == '\n')
{
arrayLength -= 2;
appendNewline = true;
}
// Write to the output stream
m_consoleOutputWriter.Write(messageCharArray, 0, arrayLength);
// Restore the console back to its previous color scheme
SetConsoleTextAttribute(consoleHandle, bufferInfo.wAttributes);
if (appendNewline)
{
// Write the newline, after changing the color scheme
m_consoleOutputWriter.Write(s_windowsNewline, 0, 2);
}
}
}
private static readonly char[] s_windowsNewline = {'\r', '\n'};
/// <summary>
/// This appender requires a <see cref="Layout"/> to be set.
/// </summary>
/// <value><c>true</c></value>
/// <remarks>
/// <para>
/// This appender requires a <see cref="Layout"/> to be set.
/// </para>
/// </remarks>
override protected bool RequiresLayout
{
get { return true; }
}
/// <summary>
/// Initialize the options for this appender
/// </summary>
/// <remarks>
/// <para>
/// Initialize the level to color mappings set on this appender.
/// </para>
/// </remarks>
#if NET_4_0 || MONO_4_0
[System.Security.SecuritySafeCritical]
#endif
[System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, UnmanagedCode=true)]
public override void ActivateOptions()
{
base.ActivateOptions();
m_levelMapping.ActivateOptions();
System.IO.Stream consoleOutputStream = null;
// Use the Console methods to open a Stream over the console std handle
if (m_writeToErrorStream)
{
// Write to the error stream
consoleOutputStream = Console.OpenStandardError();
}
else
{
// Write to the output stream
consoleOutputStream = Console.OpenStandardOutput();
}
// Lookup the codepage encoding for the console
System.Text.Encoding consoleEncoding = System.Text.Encoding.GetEncoding(GetConsoleOutputCP());
// Create a writer around the console stream
m_consoleOutputWriter = new System.IO.StreamWriter(consoleOutputStream, consoleEncoding, 0x100);
m_consoleOutputWriter.AutoFlush = true;
// SuppressFinalize on m_consoleOutputWriter because all it will do is flush
// and close the file handle. Because we have set AutoFlush the additional flush
// is not required. The console file handle should not be closed, so we don't call
// Dispose, Close or the finalizer.
GC.SuppressFinalize(m_consoleOutputWriter);
}
#endregion // Override implementation of AppenderSkeleton
#region Public Static Fields
/// <summary>
/// The <see cref="ColoredConsoleAppender.Target"/> to use when writing to the Console
/// standard output stream.
/// </summary>
/// <remarks>
/// <para>
/// The <see cref="ColoredConsoleAppender.Target"/> to use when writing to the Console
/// standard output stream.
/// </para>
/// </remarks>
public const string ConsoleOut = "Console.Out";
/// <summary>
/// The <see cref="ColoredConsoleAppender.Target"/> to use when writing to the Console
/// standard error output stream.
/// </summary>
/// <remarks>
/// <para>
/// The <see cref="ColoredConsoleAppender.Target"/> to use when writing to the Console
/// standard error output stream.
/// </para>
/// </remarks>
public const string ConsoleError = "Console.Error";
#endregion // Public Static Fields
#region Private Instances Fields
/// <summary>
/// Flag to write output to the error stream rather than the standard output stream
/// </summary>
private bool m_writeToErrorStream = false;
/// <summary>
/// Mapping from level object to color value
/// </summary>
private LevelMapping m_levelMapping = new LevelMapping();
/// <summary>
/// The console output stream writer to write to
/// </summary>
/// <remarks>
/// <para>
/// This writer is not thread safe.
/// </para>
/// </remarks>
private System.IO.StreamWriter m_consoleOutputWriter = null;
#endregion // Private Instances Fields
#region Win32 Methods
[DllImport("Kernel32.dll", SetLastError=true, CharSet=CharSet.Auto)]
private static extern int GetConsoleOutputCP();
[DllImport("Kernel32.dll", SetLastError=true, CharSet=CharSet.Auto)]
private static extern bool SetConsoleTextAttribute(
IntPtr consoleHandle,
ushort attributes);
[DllImport("Kernel32.dll", SetLastError=true, CharSet=CharSet.Auto)]
private static extern bool GetConsoleScreenBufferInfo(
IntPtr consoleHandle,
out CONSOLE_SCREEN_BUFFER_INFO bufferInfo);
// [DllImport("Kernel32.dll", SetLastError=true, CharSet=CharSet.Unicode)]
// private static extern bool WriteConsoleW(
// IntPtr hConsoleHandle,
// [MarshalAs(UnmanagedType.LPWStr)] string strBuffer,
// UInt32 bufferLen,
// out UInt32 written,
// IntPtr reserved);
//private const UInt32 STD_INPUT_HANDLE = unchecked((UInt32)(-10));
private const UInt32 STD_OUTPUT_HANDLE = unchecked((UInt32)(-11));
private const UInt32 STD_ERROR_HANDLE = unchecked((UInt32)(-12));
[DllImport("Kernel32.dll", SetLastError=true, CharSet=CharSet.Auto)]
private static extern IntPtr GetStdHandle(
UInt32 type);
[StructLayout(LayoutKind.Sequential)]
private struct COORD
{
public UInt16 x;
public UInt16 y;
}
[StructLayout(LayoutKind.Sequential)]
private struct SMALL_RECT
{
public UInt16 Left;
public UInt16 Top;
public UInt16 Right;
public UInt16 Bottom;
}
[StructLayout(LayoutKind.Sequential)]
private struct CONSOLE_SCREEN_BUFFER_INFO
{
public COORD dwSize;
public COORD dwCursorPosition;
public ushort wAttributes;
public SMALL_RECT srWindow;
public COORD dwMaximumWindowSize;
}
#endregion // Win32 Methods
#region LevelColors LevelMapping Entry
/// <summary>
/// A class to act as a mapping between the level that a logging call is made at and
/// the color it should be displayed as.
/// </summary>
/// <remarks>
/// <para>
/// Defines the mapping between a level and the color it should be displayed in.
/// </para>
/// </remarks>
public class LevelColors : LevelMappingEntry
{
private Colors m_foreColor;
private Colors m_backColor;
private ushort m_combinedColor = 0;
/// <summary>
/// The mapped foreground color for the specified level
/// </summary>
/// <remarks>
/// <para>
/// Required property.
/// The mapped foreground color for the specified level.
/// </para>
/// </remarks>
public Colors ForeColor
{
get { return m_foreColor; }
set { m_foreColor = value; }
}
/// <summary>
/// The mapped background color for the specified level
/// </summary>
/// <remarks>
/// <para>
/// Required property.
/// The mapped background color for the specified level.
/// </para>
/// </remarks>
public Colors BackColor
{
get { return m_backColor; }
set { m_backColor = value; }
}
/// <summary>
/// Initialize the options for the object
/// </summary>
/// <remarks>
/// <para>
/// Combine the <see cref="ForeColor"/> and <see cref="BackColor"/> together.
/// </para>
/// </remarks>
public override void ActivateOptions()
{
base.ActivateOptions();
m_combinedColor = (ushort)( (int)m_foreColor + (((int)m_backColor) << 4) );
}
/// <summary>
/// The combined <see cref="ForeColor"/> and <see cref="BackColor"/> suitable for
/// setting the console color.
/// </summary>
internal ushort CombinedColor
{
get { return m_combinedColor; }
}
}
#endregion // LevelColors LevelMapping Entry
}
}
#endif // !CLI_1_0
#endif // !SSCLI
#endif // !MONO
#endif // !NETCF
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* 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 DivideDouble()
{
var test = new SimpleBinaryOpTest__DivideDouble();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__DivideDouble
{
private const int VectorSize = 16;
private const int ElementCount = VectorSize / sizeof(Double);
private static Double[] _data1 = new Double[ElementCount];
private static Double[] _data2 = new Double[ElementCount];
private static Vector128<Double> _clsVar1;
private static Vector128<Double> _clsVar2;
private Vector128<Double> _fld1;
private Vector128<Double> _fld2;
private SimpleBinaryOpTest__DataTable<Double> _dataTable;
static SimpleBinaryOpTest__DivideDouble()
{
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); _data2[i] = (double)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data2[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data1[0]), VectorSize);
}
public SimpleBinaryOpTest__DivideDouble()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); _data2[i] = (double)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); _data2[i] = (double)(random.NextDouble()); }
_dataTable = new SimpleBinaryOpTest__DataTable<Double>(_data1, _data2, new Double[ElementCount], VectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse2.Divide(
Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Sse2.Divide(
Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse2.Divide(
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.Divide), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.Divide), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.Divide), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Sse2.Divide(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr);
var result = Sse2.Divide(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr));
var result = Sse2.Divide(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr));
var result = Sse2.Divide(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__DivideDouble();
var result = Sse2.Divide(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Sse2.Divide(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<Double> left, Vector128<Double> right, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[ElementCount];
Double[] inArray2 = new Double[ElementCount];
Double[] outArray = new Double[ElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[ElementCount];
Double[] inArray2 = new Double[ElementCount];
Double[] outArray = new Double[ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Double[] left, Double[] right, Double[] result, [CallerMemberName] string method = "")
{
if (BitConverter.DoubleToInt64Bits(left[0] / right[0]) != BitConverter.DoubleToInt64Bits(result[0]))
{
Succeeded = false;
}
else
{
for (var i = 1; i < left.Length; i++)
{
if (BitConverter.DoubleToInt64Bits(left[i] / right[i]) != BitConverter.DoubleToInt64Bits(result[i]))
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Sse2)}.{nameof(Sse2.Divide)}<Double>: {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Bond.IO
{
using System;
using System.Runtime.CompilerServices;
/// <summary>
/// Helper methods for encoding and decoding integer values.
/// </summary>
internal static class IntegerHelper
{
public const int MaxBytesVarInt16 = 3;
public const int MaxBytesVarInt32 = 5;
public const int MaxBytesVarInt64 = 10;
public static int GetVarUInt16Length(ushort value)
{
if (value < (1 << 7))
{
return 1;
}
else if (value < (1 << 14))
{
return 2;
}
else
{
return 3;
}
}
public static int EncodeVarUInt16(byte[] data, ushort value, int index)
{
// byte 0
if (value >= 0x80)
{
data[index++] = (byte)(value | 0x80);
value >>= 7;
// byte 1
if (value >= 0x80)
{
data[index++] = (byte)(value | 0x80);
value >>= 7;
}
}
// byte 2
data[index++] = (byte)value;
return index;
}
public static int GetVarUInt32Length(uint value)
{
if (value < (1 << 7))
{
return 1;
}
else if (value < (1 << 14))
{
return 2;
}
else if (value < (1 << 21))
{
return 3;
}
else if (value < (1 << 28))
{
return 4;
}
else
{
return 5;
}
}
public static int EncodeVarUInt32(byte[] data, uint value, int index)
{
// byte 0
if (value >= 0x80)
{
data[index++] = (byte)(value | 0x80);
value >>= 7;
// byte 1
if (value >= 0x80)
{
data[index++] = (byte)(value | 0x80);
value >>= 7;
// byte 2
if (value >= 0x80)
{
data[index++] = (byte)(value | 0x80);
value >>= 7;
// byte 3
if (value >= 0x80)
{
data[index++] = (byte)(value | 0x80);
value >>= 7;
}
}
}
}
// last byte
data[index++] = (byte)value;
return index;
}
public static int GetVarUInt64Length(ulong value)
{
if (value < (1UL << 7))
{
return 1;
}
else if (value < (1UL << 14))
{
return 2;
}
else if (value < (1UL << 21))
{
return 3;
}
else if (value < (1UL << 28))
{
return 4;
}
else if (value < (1UL << 35))
{
return 5;
}
else if (value < (1UL << 42))
{
return 6;
}
else if (value < (1UL << 49))
{
return 7;
}
else if (value < (1UL << 56))
{
return 8;
}
else if (value < (1UL << 63))
{
return 9;
}
else
{
return 10;
}
}
public static int EncodeVarUInt64(byte[] data, ulong value, int index)
{
// byte 0
if (value >= 0x80)
{
data[index++] = (byte)(value | 0x80);
value >>= 7;
// byte 1
if (value >= 0x80)
{
data[index++] = (byte)(value | 0x80);
value >>= 7;
// byte 2
if (value >= 0x80)
{
data[index++] = (byte)(value | 0x80);
value >>= 7;
// byte 3
if (value >= 0x80)
{
data[index++] = (byte)(value | 0x80);
value >>= 7;
// byte 4
if (value >= 0x80)
{
data[index++] = (byte)(value | 0x80);
value >>= 7;
// byte 5
if (value >= 0x80)
{
data[index++] = (byte)(value | 0x80);
value >>= 7;
// byte 6
if (value >= 0x80)
{
data[index++] = (byte)(value | 0x80);
value >>= 7;
// byte 7
if (value >= 0x80)
{
data[index++] = (byte)(value | 0x80);
value >>= 7;
// byte 8
if (value >= 0x80)
{
data[index++] = (byte)(value | 0x80);
value >>= 7;
}
}
}
}
}
}
}
}
}
// last byte
data[index++] = (byte)value;
return index;
}
public static ushort DecodeVarUInt16(byte[] data, ref int index)
{
var i = index;
// byte 0
uint result = data[i++];
if (0x80u <= result)
{
// byte 1
uint raw = data[i++];
result = (result & 0x7Fu) | ((raw & 0x7Fu) << 7);
if (0x80u <= raw)
{
// byte 2
raw = data[i++];
result |= raw << 14;
}
}
index = i;
return (ushort) result;
}
public static uint DecodeVarUInt32(byte[] data, ref int index)
{
var i = index;
// byte 0
uint result = data[i++];
if (0x80u <= result)
{
// byte 1
uint raw = data[i++];
result = (result & 0x7Fu) | ((raw & 0x7Fu) << 7);
if (0x80u <= raw)
{
// byte 2
raw = data[i++];
result |= (raw & 0x7Fu) << 14;
if (0x80u <= raw)
{
// byte 3
raw = data[i++];
result |= (raw & 0x7Fu) << 21;
if (0x80u <= raw)
{
// byte 4
raw = data[i++];
result |= raw << 28;
}
}
}
}
index = i;
return result;
}
public static ulong DecodeVarUInt64(byte[] data, ref int index)
{
var i = index;
// byte 0
ulong result = data[i++];
if (0x80u <= result)
{
// byte 1
ulong raw = data[i++];
result = (result & 0x7Fu) | ((raw & 0x7Fu) << 7);
if (0x80u <= raw)
{
// byte 2
raw = data[i++];
result |= (raw & 0x7Fu) << 14;
if (0x80u <= raw)
{
// byte 3
raw = data[i++];
result |= (raw & 0x7Fu) << 21;
if (0x80u <= raw)
{
// byte 4
raw = data[i++];
result |= (raw & 0x7Fu) << 28;
if (0x80u <= raw)
{
// byte 5
raw = data[i++];
result |= (raw & 0x7Fu) << 35;
if (0x80u <= raw)
{
// byte 6
raw = data[i++];
result |= (raw & 0x7Fu) << 42;
if (0x80u <= raw)
{
// byte 7
raw = data[i++];
result |= (raw & 0x7Fu) << 49;
if (0x80u <= raw)
{
// byte 8
raw = data[i++];
result |= raw << 56;
if (0x80u <= raw)
{
// byte 9
i++;
}
}
}
}
}
}
}
}
}
index = i;
return result;
}
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public static UInt16 EncodeZigzag16(Int16 value)
{
return (UInt16)((value << 1) ^ (value >> (sizeof(Int16) * 8 - 1)));
}
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public static UInt32 EncodeZigzag32(Int32 value)
{
return (UInt32)((value << 1) ^ (value >> (sizeof(Int32) * 8 - 1)));
}
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public static UInt64 EncodeZigzag64(Int64 value)
{
return (UInt64)((value << 1) ^ (value >> (sizeof(Int64) * 8 - 1)));
}
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public static Int16 DecodeZigzag16(UInt16 value)
{
return (Int16)((value >> 1) ^ (-(value & 1)));
}
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public static Int32 DecodeZigzag32(UInt32 value)
{
return (Int32)((value >> 1) ^ (-(value & 1)));
}
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public static Int64 DecodeZigzag64(UInt64 value)
{
return (Int64)((value >> 1) ^ (UInt64)(-(Int64)(value & 1)));
}
}
}
| |
/// Copyright (C) 2012-2014 Soomla Inc.
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
using UnityEngine;
using System;
using System.Runtime.InteropServices;
namespace Soomla.Store
{
/// <summary>
/// This class will help you do your day to day virtual economy operations easily.
/// You can give or take items from your users. You can buy items or upgrade them.
/// You can also check their equipping status and change it.
/// </summary>
public class StoreInventory
{
protected const string TAG = "SOOMLA StoreInventory";
static StoreInventory _instance = null;
static StoreInventory instance {
get {
if(_instance == null) {
#if UNITY_ANDROID && !UNITY_EDITOR
_instance = new StoreInventoryAndroid();
#elif UNITY_IOS && !UNITY_EDITOR
_instance = new StoreInventoryIOS();
#else
_instance = new StoreInventory();
#endif
}
return _instance;
}
}
/// <summary>
/// Buys the item with the given <c>itemId</c>.
/// </summary>
/// <param name="itemId">id of item to be bought</param>
/// <exception cref="VirtualItemNotFoundException">Thrown if the item to be bought is not found.</exception>
/// <exception cref="InsufficientFundsException">Thrown if the user does not have enough funds.</exception>
public static void BuyItem(string itemId) {
BuyItem(itemId, "");
}
/// <summary>
/// Buys the item with the given <c>itemId</c>.
/// </summary>
/// <param name="itemId">id of item to be bought</param>
/// <param name="payload">a string you want to be assigned to the purchase. This string
/// is saved in a static variable and will be given bacl to you when the purchase is completed.</param>
/// <exception cref="VirtualItemNotFoundException">Thrown if the item to be bought is not found.</exception>
/// <exception cref="InsufficientFundsException">Thrown if the user does not have enough funds.</exception>
public static void BuyItem(string itemId, string payload) {
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY Calling BuyItem with: " + itemId);
instance._buyItem(itemId, payload);
}
virtual protected void _buyItem(string itemId, string payload) {
}
/** VIRTUAL ITEMS **/
/// <summary>
/// Retrieves the balance of the virtual item with the given <c>itemId</c>.
/// </summary>
/// <param name="itemId">Id of the virtual item to be fetched.</param>
/// <returns>Balance of the virtual item with the given item id.</returns>
/// <exception cref="VirtualItemNotFoundException">Thrown if the item is not found.</exception>
public static int GetItemBalance(string itemId) {
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY Calling GetItemBalance with: " + itemId);
return instance._getItemBalance(itemId);
}
/// <summary>
/// Gives your user the given amount of the virtual item with the given <c>itemId</c>.
/// For example, when your user plays your game for the first time you GIVE him/her 1000 gems.
///
/// NOTE: This action is different than buy -
/// You use <c>give(int amount)</c> to give your user something for free.
/// You use <c>buy()</c> to give your user something and you get something in return.
/// </summary>
/// <param name="itemId">Id of the item to be given.</param>
/// <param name="amount">Amount of the item to be given.</param>
/// <exception cref="VirtualItemNotFoundException">Thrown if the item is not found.</exception>
public static void GiveItem(string itemId, int amount) {
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY Calling GiveItem with itemId: " + itemId + " and amount: " + amount);
instance._giveItem(itemId, amount);
}
/// <summary>
/// Takes from your user the given amount of the virtual item with the given <c>itemId</c>.
/// For example, when your user requests a refund, you need to TAKE the item he/she is returning from him/her.
/// </summary>
/// <param name="itemId">Item identifier.</param>
/// <param name="amount">Amount.</param>
/// <exception cref="VirtualItemNotFoundException">Thrown if the item is not found.</exception>
public static void TakeItem(string itemId, int amount) {
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY Calling TakeItem with itemId: " + itemId + " and amount: " + amount);
instance._takeItem(itemId, amount);
}
virtual protected int _getItemBalance(string itemId) {
return 0;
}
virtual protected void _giveItem(string itemId, int amount) {
}
virtual protected void _takeItem(string itemId, int amount) {
}
/** VIRTUAL GOODS **/
/// <summary>
/// Equips the virtual good with the given <c>goodItemId</c>.
/// Equipping means that the user decides to currently use a specific virtual good.
/// For more details and examples <see cref="com.soomla.store.domain.virtualGoods.EquippableVG"/>.
/// </summary>
/// <param name="goodItemId">Id of the good to be equipped.</param>
/// <exception cref="VirtualItemNotFoundException">Thrown if the item is not found.</exception>
/// <exception cref="NotEnoughGoodsException"></exception>
public static void EquipVirtualGood(string goodItemId) {
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY Calling EquipVirtualGood with: " + goodItemId);
instance._equipVirtualGood(goodItemId);
}
/// <summary>
/// Unequips the virtual good with the given <c>goodItemId</c>. Unequipping means that the
/// user decides to stop using the virtual good he/she is currently using.
/// For more details and examples <see cref="com.soomla.store.domain.virtualGoods.EquippableVG"/>.
/// </summary>
/// <param name="goodItemId">Id of the good to be unequipped.</param>
/// <exception cref="VirtualItemNotFoundException">Thrown if the item is not found.</exception>
public static void UnEquipVirtualGood(string goodItemId) {
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY Calling UnEquipVirtualGood with: " + goodItemId);
instance._unEquipVirtualGood(goodItemId);
}
/// <summary>
/// Checks if the virtual good with the given <c>goodItemId</c> is currently equipped.
/// </summary>
/// <param name="goodItemId">Id of the virtual good who we want to know if is equipped.</param>
/// <returns>True if the virtual good is equipped, false otherwise.</returns>
/// <exception cref="VirtualItemNotFoundException">Thrown if the item is not found.</exception>
public static bool IsVirtualGoodEquipped(string goodItemId) {
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY Calling IsVirtualGoodEquipped with: " + goodItemId);
return instance._isVertualGoodEquipped(goodItemId);
}
/// <summary>
/// Retrieves the upgrade level of the virtual good with the given <c>goodItemId</c>.
/// For Example:
/// Let's say there's a strength attribute to one of the characters in your game and you provide
/// your users with the ability to upgrade that strength on a scale of 1-3.
/// This is what you've created:
/// 1. <c>SingleUseVG</c> for "strength".
/// 2. <c>UpgradeVG</c> for strength 'level 1'.
/// 3. <c>UpgradeVG</c> for strength 'level 2'.
/// 4. <c>UpgradeVG</c> for strength 'level 3'.
/// In the example, this function will retrieve the upgrade level for "strength" (1, 2, or 3).
/// </summary>
/// <param name="goodItemId">Good item identifier.</param>
/// <returns>The good upgrade level.</returns>
/// <exception cref="VirtualItemNotFoundException">Thrown if the item is not found.</exception>
public static int GetGoodUpgradeLevel(string goodItemId) {
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY Calling GetGoodUpgradeLevel with: " + goodItemId);
return instance._getGoodUpgradeLevel(goodItemId);
}
/// <summary>
/// Retrieves the current upgrade of the good with the given id.
/// </summary>
/// <param name="goodItemId">Id of the good whose upgrade we want to fetch. </param>
/// <returns>The good's current upgrade.</returns>
/// <exception cref="VirtualItemNotFoundException">Thrown if the item is not found.</exception>
public static string GetGoodCurrentUpgrade(string goodItemId) {
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY Calling GetGoodCurrentUpgrade with: " + goodItemId);
return instance._getGoodCurrentUpgrade(goodItemId);
}
/// <summary>
/// Upgrades the virtual good with the given <c>goodItemId</c> by doing the following:
/// 1. Checks if the good is currently upgraded or if this is the first time being upgraded.
/// 2. If the good is currently upgraded, upgrades to the next upgrade in the series.
/// In case there are no more upgrades available(meaning the current upgrade is the last available),
/// the function returns.
/// 3. If the good has never been upgraded before, the function upgrades it to the first
/// available upgrade with the first upgrade of the series.
/// </summary>
/// <param name="goodItemId">Good item identifier.</param>
/// <exception cref="VirtualItemNotFoundException">Thrown if the item is not found.</exception>
public static void UpgradeGood(string goodItemId) {
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY Calling UpgradeGood with: " + goodItemId);
instance._upgradeGood(goodItemId);
}
/// <summary>
/// Removes all upgrades from the virtual good with the given <c>goodItemId</c>.
/// </summary>
/// <param name="goodItemId">Id of the good whose upgrades are to be removed.</param>
/// <exception cref="VirtualItemNotFoundException">Thrown if the item is not found.</exception>
public static void RemoveGoodUpgrades(string goodItemId) {
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY Calling RemoveGoodUpgrades with: " + goodItemId);
instance._removeGoodUpgrades(goodItemId);
}
virtual protected void _equipVirtualGood(string goodItemId) {
}
virtual protected void _unEquipVirtualGood(string goodItemId) {
}
virtual protected bool _isVertualGoodEquipped(string goodItemId) {
return false;
}
virtual protected int _getGoodUpgradeLevel(string goodItemId) {
return 0;
}
virtual protected string _getGoodCurrentUpgrade(string goodItemId) {
return null;
}
virtual protected void _upgradeGood(string goodItemId) {
}
virtual protected void _removeGoodUpgrades(string goodItemId) {
}
/** NON-CONSUMABLES **/
/// <summary>
/// Checks if the non-consumable with the given <c>nonConsItemId</c> exists.
/// </summary>
/// <param name="nonConsItemId">Id of the item to check if exists.</param>
/// <returns>True if non-consumable item with nonConsItemId exists, false otherwise.</returns>
/// <exception cref="VirtualItemNotFoundException">Thrown if the item is not found.</exception>
public static bool NonConsumableItemExists(string nonConsItemId) {
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY Calling NonConsumableItemExists with: " + nonConsItemId);
return instance._nonConsumableItemExists(nonConsItemId);
}
/// <summary>
/// Adds the non-consumable item with the given <c>nonConsItemId</c> to the non-consumable items storage.
/// </summary>
/// <param name="nonConsItemId">Id of the item to be added.</param>
/// <exception cref="VirtualItemNotFoundException">Thrown if the item is not found.</exception>
public static void AddNonConsumableItem(string nonConsItemId) {
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY Calling AddNonConsumableItem with: " + nonConsItemId);
instance._addNonConsumableItem(nonConsItemId);
}
/// <summary>
/// Removes the non-consumable item with the given <c>nonConsItemId</c> from the non-consumable
/// items storage.
/// </summary>
/// <param name="nonConsItemId">Id of the item to be removed.</param>
/// <exception cref="VirtualItemNotFoundException">Thrown if the item is not found.</exception>
public static void RemoveNonConsumableItem(string nonConsItemId) {
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY Calling RemoveNonConsumableItem with: " + nonConsItemId);
instance._removeNonConsumableItem(nonConsItemId);
}
virtual protected bool _nonConsumableItemExists(string nonConsItemId) {
return false;
}
virtual protected void _addNonConsumableItem(string nonConsItemId) {
}
virtual protected void _removeNonConsumableItem(string nonConsItemId) {
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="LegacyPageAsyncTask.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.UI {
using System;
using System.Collections;
using System.Security;
using System.Security.Permissions;
using System.Threading;
using System.Web;
using System.Web.UI;
using System.Web.Util;
// Represents an asynchronous task that uses the old asynchronous patterns and the legacy synchronization systems
internal sealed class LegacyPageAsyncTask {
private BeginEventHandler _beginHandler;
private EndEventHandler _endHandler;
private EndEventHandler _timeoutHandler;
private Object _state;
private bool _executeInParallel;
private LegacyPageAsyncTaskManager _taskManager;
private int _completionMethodLock;
private bool _started;
private bool _completed;
private bool _completedSynchronously;
private AsyncCallback _completionCallback;
private IAsyncResult _asyncResult;
private Exception _error;
internal LegacyPageAsyncTask(BeginEventHandler beginHandler, EndEventHandler endHandler, EndEventHandler timeoutHandler, Object state, bool executeInParallel) {
// Parameter checking is done by the public PageAsyncTask constructor
_beginHandler = beginHandler;
_endHandler = endHandler;
_timeoutHandler = timeoutHandler;
_state = state;
_executeInParallel = executeInParallel;
}
public BeginEventHandler BeginHandler {
get { return _beginHandler; }
}
public EndEventHandler EndHandler {
get { return _endHandler; }
}
public EndEventHandler TimeoutHandler {
get { return _timeoutHandler; }
}
public Object State {
get { return _state; }
}
public bool ExecuteInParallel {
get { return _executeInParallel; }
}
internal bool Started {
get { return _started; }
}
internal bool CompletedSynchronously {
get { return _completedSynchronously; }
}
internal bool Completed {
get { return _completed; }
}
internal IAsyncResult AsyncResult {
get { return _asyncResult; }
}
internal Exception Error {
get { return _error; }
}
internal void Start(LegacyPageAsyncTaskManager manager, Object source, EventArgs args) {
Debug.Assert(!_started);
_taskManager = manager;
_completionCallback = new AsyncCallback(this.OnAsyncTaskCompletion);
_started = true;
Debug.Trace("Async", "Start task");
try {
IAsyncResult ar = _beginHandler(source, args, _completionCallback, _state);
if (ar == null) {
throw new InvalidOperationException(SR.GetString(SR.Async_null_asyncresult));
}
if (_asyncResult == null) {
// _asyncResult could be not null if already completed
_asyncResult = ar;
}
}
catch (Exception e) {
Debug.Trace("Async", "Task failed to start");
_error = e;
_completed = true;
_completedSynchronously = true;
_taskManager.TaskCompleted(true /*onCallerThread*/); // notify TaskManager
// it is ok to say false (onCallerThread) above because this kind of
// error completion will never be the last in ResumeTasks()
}
}
private void OnAsyncTaskCompletion(IAsyncResult ar) {
Debug.Trace("Async", "Task completed, CompletedSynchronously=" + ar.CompletedSynchronously);
if (_asyncResult == null) {
// _asyncResult could be null if the code not yet returned from begin method
_asyncResult = ar;
}
CompleteTask(false /*timedOut*/);
}
internal void ForceTimeout(bool syncCaller) {
Debug.Trace("Async", "Task timed out");
CompleteTask(true /*timedOut*/, syncCaller /*syncTimeoutCaller*/);
}
private void CompleteTask(bool timedOut) {
CompleteTask(timedOut, false /*syncTimeoutCaller*/);
}
private void CompleteTask(bool timedOut, bool syncTimeoutCaller) {
if (Interlocked.Exchange(ref _completionMethodLock, 1) != 0) {
return;
}
bool needSetupThreadContext;
bool responseEnded = false;
if (timedOut) {
needSetupThreadContext = !syncTimeoutCaller;
}
else {
_completedSynchronously = _asyncResult.CompletedSynchronously;
needSetupThreadContext = !_completedSynchronously;
}
// call the completion or timeout handler
// when neeeded setup the thread context and lock
// catch and remember all exceptions
HttpApplication app = _taskManager.Application;
try {
if (needSetupThreadContext) {
using (app.Context.SyncContext.AcquireThreadLock()) {
ThreadContext threadContext = null;
try {
threadContext = app.OnThreadEnter();
if (timedOut) {
if (_timeoutHandler != null) {
_timeoutHandler(_asyncResult);
}
}
else {
_endHandler(_asyncResult);
}
}
finally {
if (threadContext != null) {
threadContext.DisassociateFromCurrentThread();
}
}
}
}
else {
if (timedOut) {
if (_timeoutHandler != null) {
_timeoutHandler(_asyncResult);
}
}
else {
_endHandler(_asyncResult);
}
}
}
catch (ThreadAbortException e) {
_error = e;
HttpApplication.CancelModuleException exceptionState = e.ExceptionState as HttpApplication.CancelModuleException;
// Is this from Response.End()
if (exceptionState != null && !exceptionState.Timeout) {
// Mark the request as completed
using (app.Context.SyncContext.AcquireThreadLock()) {
// Handle response end once. Skip if already initiated (previous AsyncTask)
if (!app.IsRequestCompleted) {
responseEnded = true;
app.CompleteRequest();
}
}
// Clear the error for Response.End
_error = null;
}
// ---- the exception. Async completion required (DDB 140655)
Thread.ResetAbort();
}
catch (Exception e) {
_error = e;
}
// Complete the current async task
_completed = true;
_taskManager.TaskCompleted(_completedSynchronously /*onCallerThread*/); // notify TaskManager
// Wait for pending AsyncTasks (DDB 140655)
if (responseEnded) {
_taskManager.CompleteAllTasksNow(false /*syncCaller*/);
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using OleConstants = Microsoft.VisualStudio.OLE.Interop.Constants;
using VsCommands = Microsoft.VisualStudio.VSConstants.VSStd97CmdID;
using VsCommands2K = Microsoft.VisualStudio.VSConstants.VSStd2KCmdID;
namespace Microsoft.VisualStudioTools.Project
{
internal class FileNode : HierarchyNode, IDiskBasedNode
{
private bool _isLinkFile;
private uint _docCookie;
private static readonly string[] _defaultOpensWithDesignViewExtensions = new[] { ".aspx", ".ascx", ".asax", ".asmx", ".xsd", ".resource", ".xaml" };
private static readonly string[] _supportsDesignViewExtensions = new[] { ".aspx", ".ascx", ".asax", ".asmx" };
private static readonly string[] _supportsDesignViewSubTypes = new[] { ProjectFileAttributeValue.Code, ProjectFileAttributeValue.Form, ProjectFileAttributeValue.UserControl, ProjectFileAttributeValue.Component, ProjectFileAttributeValue.Designer };
private string _caption;
#region overriden Properties
public override bool DefaultOpensWithDesignView
{
get
{
// ASPX\ASCX files support design view but should be opened by default with
// LOGVIEWID_Primary - this is because they support design and html view which
// is a tools option setting for them. If we force designview this option
// gets bypassed. We do a similar thing for asax/asmx/xsd. By doing so, we don't force
// the designer to be invoked when double-clicking on the - it will now go through the
// shell's standard open mechanism.
var extension = Path.GetExtension(this.Url);
return !_defaultOpensWithDesignViewExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase) &&
!this.IsCodeBehindFile &&
this.SupportsDesignView;
}
}
public override bool SupportsDesignView
{
get
{
if (this.ItemNode != null && !this.ItemNode.IsExcluded)
{
var extension = Path.GetExtension(this.Url);
if (_supportsDesignViewExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase) ||
this.IsCodeBehindFile)
{
return true;
}
else
{
var subType = this.ItemNode.GetMetadata("SubType");
if (subType != null && _supportsDesignViewExtensions.Contains(subType, StringComparer.OrdinalIgnoreCase))
{
return true;
}
}
}
return false;
}
}
public override bool IsNonMemberItem => this.ItemNode is AllFilesProjectElement;
/// <summary>
/// overwrites of the generic hierarchyitem.
/// </summary>
[System.ComponentModel.BrowsableAttribute(false)]
public override string Caption => this._caption;
private void UpdateCaption()
{
// Use LinkedIntoProjectAt property if available
var caption = this.ItemNode.GetMetadata(ProjectFileConstants.LinkedIntoProjectAt);
if (caption == null || caption.Length == 0)
{
// Otherwise use filename
caption = this.ItemNode.GetMetadata(ProjectFileConstants.Include);
caption = Path.GetFileName(caption);
}
this._caption = caption;
}
public override string GetEditLabel()
{
if (this.IsLinkFile)
{
// cannot rename link files
return null;
}
return base.GetEditLabel();
}
public uint DocCookie
{
get
{
return this._docCookie;
}
set
{
this._docCookie = value;
}
}
public override bool IsLinkFile => this._isLinkFile;
internal void SetIsLinkFile(bool value)
{
this._isLinkFile = value;
}
protected override VSOVERLAYICON OverlayIconIndex
{
get
{
if (this.IsLinkFile)
{
return VSOVERLAYICON.OVERLAYICON_SHORTCUT;
}
return VSOVERLAYICON.OVERLAYICON_NONE;
}
}
public override Guid ItemTypeGuid => VSConstants.GUID_ItemType_PhysicalFile;
public override int MenuCommandId => VsMenus.IDM_VS_CTXT_ITEMNODE;
public override string Url => this.ItemNode.Url;
#endregion
#region ctor
/// <summary>
/// Constructor for the FileNode
/// </summary>
/// <param name="root">Root of the hierarchy</param>
/// <param name="e">Associated project element</param>
public FileNode(ProjectNode root, ProjectElement element)
: base(root, element)
{
UpdateCaption();
}
#endregion
#region overridden methods
protected override NodeProperties CreatePropertiesObject()
{
if (this.IsLinkFile)
{
return new LinkFileNodeProperties(this);
}
else if (this.IsNonMemberItem)
{
return new ExcludedFileNodeProperties(this);
}
return new IncludedFileNodeProperties(this);
}
/// <summary>
/// Get an instance of the automation object for a FileNode
/// </summary>
/// <returns>An instance of the Automation.OAFileNode if succeeded</returns>
public override object GetAutomationObject()
{
if (this.ProjectMgr == null || this.ProjectMgr.IsClosed)
{
return null;
}
return new Automation.OAFileItem(this.ProjectMgr.GetAutomationObject() as Automation.OAProject, this);
}
/// <summary>
/// Renames a file node.
/// </summary>
/// <param name="label">The new name.</param>
/// <returns>An errorcode for failure or S_OK.</returns>
/// <exception cref="InvalidOperationException" if the file cannot be validated>
/// <devremark>
/// We are going to throw instead of showing messageboxes, since this method is called from various places where a dialog box does not make sense.
/// For example the FileNodeProperties are also calling this method. That should not show directly a messagebox.
/// Also the automation methods are also calling SetEditLabel
/// </devremark>
public override int SetEditLabel(string label)
{
// IMPORTANT NOTE: This code will be called when a parent folder is renamed. As such, it is
// expected that we can be called with a label which is the same as the current
// label and this should not be considered a NO-OP.
if (this.ProjectMgr == null || this.ProjectMgr.IsClosed)
{
return VSConstants.E_FAIL;
}
// Validate the filename.
if (string.IsNullOrEmpty(label))
{
throw new InvalidOperationException(SR.GetString(SR.ErrorInvalidFileName, label));
}
else if (label.Length > NativeMethods.MAX_PATH)
{
throw new InvalidOperationException(SR.GetString(SR.PathTooLong, label));
}
else if (Utilities.IsFileNameInvalid(label))
{
throw new InvalidOperationException(SR.GetString(SR.ErrorInvalidFileName, label));
}
for (var n = this.Parent.FirstChild; n != null; n = n.NextSibling)
{
// TODO: Distinguish between real Urls and fake ones (eg. "References")
if (n != this && StringComparer.OrdinalIgnoreCase.Equals(n.GetItemName(), label))
{
//A file or folder with the name '{0}' already exists on disk at this location. Please choose another name.
//If this file or folder does not appear in the Solution Explorer, then it is not currently part of your project. To view files which exist on disk, but are not in the project, select Show All Files from the Project menu.
throw new InvalidOperationException(SR.GetString(SR.FileOrFolderAlreadyExists, label));
}
}
var fileName = Path.GetFileNameWithoutExtension(label);
// Verify that the file extension is unchanged
var strRelPath = Path.GetFileName(this.ItemNode.GetMetadata(ProjectFileConstants.Include));
if (!Utilities.IsInAutomationFunction(this.ProjectMgr.Site) &&
!StringComparer.OrdinalIgnoreCase.Equals(Path.GetExtension(strRelPath), Path.GetExtension(label)))
{
// Prompt to confirm that they really want to change the extension of the file
var message = SR.GetString(SR.ConfirmExtensionChange, label);
var shell = this.ProjectMgr.Site.GetService(typeof(SVsUIShell)) as IVsUIShell;
Utilities.CheckNotNull(shell, "Could not get the UI shell from the project");
if (!VsShellUtilities.PromptYesNo(message, null, OLEMSGICON.OLEMSGICON_INFO, shell))
{
// The user cancelled the confirmation for changing the extension.
// Return S_OK in order not to show any extra dialog box
return VSConstants.S_OK;
}
}
// Build the relative path by looking at folder names above us as one scenarios
// where we get called is when a folder above us gets renamed (in which case our path is invalid)
var parent = this.Parent;
while (parent != null && (parent is FolderNode))
{
strRelPath = Path.Combine(parent.GetItemName(), strRelPath);
parent = parent.Parent;
}
return SetEditLabel(label, strRelPath);
}
public override string GetMkDocument()
{
Debug.Assert(!string.IsNullOrEmpty(this.Url), "No url specified for this node");
Debug.Assert(Path.IsPathRooted(this.Url), "Url should not be a relative path");
return this.Url;
}
/// <summary>
/// Delete the item corresponding to the specified path from storage.
/// </summary>
/// <param name="path"></param>
protected internal override void DeleteFromStorage(string path)
{
if (File.Exists(path))
{
File.SetAttributes(path, FileAttributes.Normal); // make sure it's not readonly.
File.Delete(path);
}
}
/// <summary>
/// Rename the underlying document based on the change the user just made to the edit label.
/// </summary>
protected internal override int SetEditLabel(string label, string relativePath)
{
var returnValue = VSConstants.S_OK;
var oldId = this.ID;
var strSavePath = Path.GetDirectoryName(relativePath);
strSavePath = CommonUtils.GetAbsoluteDirectoryPath(this.ProjectMgr.ProjectHome, strSavePath);
var newName = Path.Combine(strSavePath, label);
if (StringComparer.OrdinalIgnoreCase.Equals(newName, this.Url))
{
// This is really a no-op (including changing case), so there is nothing to do
return VSConstants.S_FALSE;
}
else if (StringComparer.OrdinalIgnoreCase.Equals(newName, this.Url))
{
// This is a change of file casing only.
}
else
{
// If the renamed file already exists then quit (unless it is the result of the parent having done the move).
if (IsFileOnDisk(newName)
&& (IsFileOnDisk(this.Url)
|| !StringComparer.OrdinalIgnoreCase.Equals(Path.GetFileName(newName), Path.GetFileName(this.Url))))
{
throw new InvalidOperationException(SR.GetString(SR.FileCannotBeRenamedToAnExistingFile, label));
}
else if (newName.Length > NativeMethods.MAX_PATH)
{
throw new InvalidOperationException(SR.GetString(SR.PathTooLong, label));
}
}
var oldName = this.Url;
// must update the caption prior to calling RenameDocument, since it may
// cause queries of that property (such as from open editors).
var oldrelPath = this.ItemNode.GetMetadata(ProjectFileConstants.Include);
try
{
if (!RenameDocument(oldName, newName))
{
this.ItemNode.Rename(oldrelPath);
}
if (this is DependentFileNode)
{
this.ProjectMgr.OnInvalidateItems(this.Parent);
}
}
catch (Exception e)
{
// Just re-throw the exception so we don't get duplicate message boxes.
Trace.WriteLine("Exception : " + e.Message);
this.RecoverFromRenameFailure(newName, oldrelPath);
returnValue = Marshal.GetHRForException(e);
throw;
}
// Return S_FALSE if the hierarchy item id has changed. This forces VS to flush the stale
// hierarchy item id.
if (returnValue == (int)VSConstants.S_OK || returnValue == (int)VSConstants.S_FALSE || returnValue == VSConstants.OLE_E_PROMPTSAVECANCELLED)
{
return (oldId == this.ID) ? VSConstants.S_OK : (int)VSConstants.S_FALSE;
}
return returnValue;
}
/// <summary>
/// Returns a specific Document manager to handle files
/// </summary>
/// <returns>Document manager object</returns>
protected internal override DocumentManager GetDocumentManager()
{
return new FileDocumentManager(this);
}
public override int QueryService(ref Guid guidService, out object result)
{
if (guidService == typeof(EnvDTE.Project).GUID)
{
result = this.ProjectMgr.GetAutomationObject();
return VSConstants.S_OK;
}
else if (guidService == typeof(EnvDTE.ProjectItem).GUID)
{
result = GetAutomationObject();
return VSConstants.S_OK;
}
return base.QueryService(ref guidService, out result);
}
/// <summary>
/// Called by the drag&drop implementation to ask the node
/// which is being dragged/droped over which nodes should
/// process the operation.
/// This allows for dragging to a node that cannot contain
/// items to let its parent accept the drop, while a reference
/// node delegate to the project and a folder/project node to itself.
/// </summary>
/// <returns></returns>
protected internal override HierarchyNode GetDragTargetHandlerNode()
{
Debug.Assert(this.ProjectMgr != null, " The project manager is null for the filenode");
HierarchyNode handlerNode = this;
while (handlerNode != null && !(handlerNode is ProjectNode || handlerNode is FolderNode))
handlerNode = handlerNode.Parent;
if (handlerNode == null)
handlerNode = this.ProjectMgr;
return handlerNode;
}
internal override int ExecCommandOnNode(Guid cmdGroup, uint cmd, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut)
{
if (this.ProjectMgr == null || this.ProjectMgr.IsClosed)
{
return (int)OleConstants.OLECMDERR_E_NOTSUPPORTED;
}
// Exec on special filenode commands
if (cmdGroup == VsMenus.guidStandardCommandSet97)
{
IVsWindowFrame windowFrame = null;
switch ((VsCommands)cmd)
{
case VsCommands.ViewCode:
return ((FileDocumentManager)this.GetDocumentManager()).Open(false, false, VSConstants.LOGVIEWID_Code, out windowFrame, WindowFrameShowAction.Show);
case VsCommands.ViewForm:
return ((FileDocumentManager)this.GetDocumentManager()).Open(false, false, VSConstants.LOGVIEWID_Designer, out windowFrame, WindowFrameShowAction.Show);
case VsCommands.Open:
return ((FileDocumentManager)this.GetDocumentManager()).Open(false, false, WindowFrameShowAction.Show);
case VsCommands.OpenWith:
return ((FileDocumentManager)this.GetDocumentManager()).Open(false, true, VSConstants.LOGVIEWID_UserChooseView, out windowFrame, WindowFrameShowAction.Show);
}
}
return base.ExecCommandOnNode(cmdGroup, cmd, nCmdexecopt, pvaIn, pvaOut);
}
internal override int QueryStatusOnNode(Guid cmdGroup, uint cmd, IntPtr pCmdText, ref QueryStatusResult result)
{
if (cmdGroup == VsMenus.guidStandardCommandSet97)
{
switch ((VsCommands)cmd)
{
case VsCommands.Copy:
case VsCommands.Paste:
case VsCommands.Cut:
case VsCommands.Rename:
result |= QueryStatusResult.SUPPORTED | QueryStatusResult.ENABLED;
return VSConstants.S_OK;
case VsCommands.ViewCode:
//case VsCommands.Delete: goto case VsCommands.OpenWith;
case VsCommands.Open:
case VsCommands.OpenWith:
result |= QueryStatusResult.SUPPORTED | QueryStatusResult.ENABLED;
return VSConstants.S_OK;
}
}
else if (cmdGroup == VsMenus.guidStandardCommandSet2K)
{
if ((VsCommands2K)cmd == VsCommands2K.EXCLUDEFROMPROJECT)
{
result |= QueryStatusResult.SUPPORTED | QueryStatusResult.ENABLED;
return VSConstants.S_OK;
}
}
return base.QueryStatusOnNode(cmdGroup, cmd, pCmdText, ref result);
}
protected override void DoDefaultAction()
{
var manager = this.GetDocumentManager() as FileDocumentManager;
Utilities.CheckNotNull(manager, "Could not get the FileDocumentManager");
manager.Open(false, false, WindowFrameShowAction.Show);
}
/// <summary>
/// Performs a SaveAs operation of an open document. Called from SaveItem after the running document table has been updated with the new doc data.
/// </summary>
/// <param name="docData">A pointer to the document in the rdt</param>
/// <param name="newFilePath">The new file path to the document</param>
/// <returns></returns>
internal override int AfterSaveItemAs(IntPtr docData, string newFilePath)
{
Utilities.ArgumentNotNullOrEmpty("newFilePath", newFilePath);
var returnCode = VSConstants.S_OK;
newFilePath = newFilePath.Trim();
//Identify if Path or FileName are the same for old and new file
var newDirectoryName = CommonUtils.NormalizeDirectoryPath(Path.GetDirectoryName(newFilePath));
var oldDirectoryName = CommonUtils.NormalizeDirectoryPath(Path.GetDirectoryName(this.GetMkDocument()));
var isSamePath = CommonUtils.IsSameDirectory(newDirectoryName, oldDirectoryName);
var isSameFile = CommonUtils.IsSamePath(newFilePath, this.Url);
//Get target container
HierarchyNode targetContainer = null;
var isLink = false;
if (isSamePath)
{
targetContainer = this.Parent;
}
else if (!CommonUtils.IsSubpathOf(this.ProjectMgr.ProjectHome, newDirectoryName))
{
targetContainer = this.Parent;
isLink = true;
}
else if (CommonUtils.IsSameDirectory(this.ProjectMgr.ProjectHome, newDirectoryName))
{
//the projectnode is the target container
targetContainer = this.ProjectMgr;
}
else
{
//search for the target container among existing child nodes
targetContainer = this.ProjectMgr.FindNodeByFullPath(newDirectoryName);
if (targetContainer != null && (targetContainer is FileNode))
{
// We already have a file node with this name in the hierarchy.
throw new InvalidOperationException(SR.GetString(SR.FileAlreadyExistsAndCannotBeRenamed, Path.GetFileName(newFilePath)));
}
}
if (targetContainer == null)
{
// Add a chain of subdirectories to the project.
var relativeUri = CommonUtils.GetRelativeDirectoryPath(this.ProjectMgr.ProjectHome, newDirectoryName);
targetContainer = this.ProjectMgr.CreateFolderNodes(relativeUri);
}
Utilities.CheckNotNull(targetContainer, "Could not find a target container");
//Suspend file changes while we rename the document
var oldrelPath = this.ItemNode.GetMetadata(ProjectFileConstants.Include);
var oldName = CommonUtils.GetAbsoluteFilePath(this.ProjectMgr.ProjectHome, oldrelPath);
var sfc = new SuspendFileChanges(this.ProjectMgr.Site, oldName);
sfc.Suspend();
try
{
// Rename the node.
DocumentManager.UpdateCaption(this.ProjectMgr.Site, Path.GetFileName(newFilePath), docData);
// Check if the file name was actually changed.
// In same cases (e.g. if the item is a file and the user has changed its encoding) this function
// is called even if there is no real rename.
if (!isSameFile || (this.Parent.ID != targetContainer.ID))
{
// The path of the file is changed or its parent is changed; in both cases we have
// to rename the item.
if (isLink != this.IsLinkFile)
{
if (isLink)
{
var newPath = CommonUtils.GetRelativeFilePath(
this.ProjectMgr.ProjectHome,
Path.Combine(Path.GetDirectoryName(this.Url), Path.GetFileName(newFilePath))
);
this.ItemNode.SetMetadata(ProjectFileConstants.Link, newPath);
}
else
{
this.ItemNode.SetMetadata(ProjectFileConstants.Link, null);
}
SetIsLinkFile(isLink);
}
RenameFileNode(oldName, newFilePath, targetContainer);
this.ProjectMgr.OnInvalidateItems(this.Parent);
}
}
catch (Exception e)
{
Trace.WriteLine("Exception : " + e.Message);
this.RecoverFromRenameFailure(newFilePath, oldrelPath);
throw;
}
finally
{
sfc.Resume();
}
return returnCode;
}
/// <summary>
/// Determines if this is node a valid node for painting the default file icon.
/// </summary>
/// <returns></returns>
protected override bool CanShowDefaultIcon()
{
var moniker = this.GetMkDocument();
return File.Exists(moniker);
}
#endregion
#region virtual methods
public override object GetProperty(int propId)
{
switch ((__VSHPROPID)propId)
{
case __VSHPROPID.VSHPROPID_ItemDocCookie:
if (this.DocCookie != 0)
return (IntPtr)this.DocCookie; //cast to IntPtr as some callers expect VT_INT
break;
}
return base.GetProperty(propId);
}
public virtual string FileName
{
get
{
return this.GetItemName();
}
set
{
this.SetEditLabel(value);
}
}
/// <summary>
/// Determine if this item is represented physical on disk and shows a messagebox in case that the file is not present and a UI is to be presented.
/// </summary>
/// <param name="showMessage">true if user should be presented for UI in case the file is not present</param>
/// <returns>true if file is on disk</returns>
internal protected virtual bool IsFileOnDisk(bool showMessage)
{
var fileExist = IsFileOnDisk(this.Url);
if (!fileExist && showMessage && !Utilities.IsInAutomationFunction(this.ProjectMgr.Site))
{
var message = SR.GetString(SR.ItemDoesNotExistInProjectDirectory, GetItemName());
var title = string.Empty;
var icon = OLEMSGICON.OLEMSGICON_CRITICAL;
var buttons = OLEMSGBUTTON.OLEMSGBUTTON_OK;
var defaultButton = OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST;
Utilities.ShowMessageBox(this.ProjectMgr.Site, title, message, icon, buttons, defaultButton);
}
return fileExist;
}
/// <summary>
/// Determine if the file represented by "path" exist in storage.
/// Override this method if your files are not persisted on disk.
/// </summary>
/// <param name="path">Url representing the file</param>
/// <returns>True if the file exist</returns>
internal protected virtual bool IsFileOnDisk(string path)
{
return File.Exists(path);
}
/// <summary>
/// Renames the file in the hierarchy by removing old node and adding a new node in the hierarchy.
/// </summary>
/// <param name="oldFileName">The old file name.</param>
/// <param name="newFileName">The new file name</param>
/// <param name="newParentId">The new parent id of the item.</param>
/// <returns>The newly added FileNode.</returns>
/// <remarks>While a new node will be used to represent the item, the underlying MSBuild item will be the same and as a result file properties saved in the project file will not be lost.</remarks>
internal FileNode RenameFileNode(string oldFileName, string newFileName, HierarchyNode newParent)
{
if (CommonUtils.IsSamePath(oldFileName, newFileName))
{
// We do not want to rename the same file
return null;
}
//If we are included in the project and our parent isn't then
//we need to bring our parent into the project
if (!this.IsNonMemberItem && newParent.IsNonMemberItem)
{
ErrorHandler.ThrowOnFailure(newParent.IncludeInProject(false));
}
// Retrieve child nodes to add later.
var childNodes = this.GetChildNodes();
FileNode renamedNode;
using (this.ProjectMgr.ExtensibilityEventsDispatcher.Suspend())
{
// Remove this from its parent.
this.ProjectMgr.OnItemDeleted(this);
this.Parent.RemoveChild(this);
// Update name in MSBuild
this.ItemNode.Rename(CommonUtils.GetRelativeFilePath(this.ProjectMgr.ProjectHome, newFileName));
// Request a new file node be made. This is used to replace the old file node. This way custom
// derived FileNode types will be used and correctly associated on rename. This is useful for things
// like .txt -> .js where the file would now be able to be a startup project/file.
renamedNode = this.ProjectMgr.CreateFileNode(this.ItemNode);
renamedNode.ItemNode.RefreshProperties();
renamedNode.UpdateCaption();
newParent.AddChild(renamedNode);
renamedNode.Parent = newParent;
}
UpdateCaption();
this.ProjectMgr.ReDrawNode(renamedNode, UIHierarchyElement.Caption);
renamedNode.ProjectMgr.ExtensibilityEventsDispatcher.FireItemRenamed(this, oldFileName);
//Update the new document in the RDT.
DocumentManager.RenameDocument(renamedNode.ProjectMgr.Site, oldFileName, newFileName, renamedNode.ID);
//Select the new node in the hierarchy
renamedNode.ExpandItem(EXPANDFLAGS.EXPF_SelectItem);
// Add children to new node and rename them appropriately.
childNodes.ForEach(x => renamedNode.AddChild(x));
RenameChildNodes(renamedNode);
return renamedNode;
}
/// <summary>
/// Rename all childnodes
/// </summary>
/// <param name="newFileNode">The newly added Parent node.</param>
protected virtual void RenameChildNodes(FileNode parentNode)
{
foreach (var childNode in GetChildNodes().OfType<FileNode>())
{
string newfilename;
if (childNode.HasParentNodeNameRelation)
{
var relationalName = childNode.Parent.GetRelationalName();
var extension = childNode.GetRelationNameExtension();
newfilename = relationalName + extension;
newfilename = CommonUtils.GetAbsoluteFilePath(Path.GetDirectoryName(childNode.Parent.GetMkDocument()), newfilename);
}
else
{
newfilename = CommonUtils.GetAbsoluteFilePath(Path.GetDirectoryName(childNode.Parent.GetMkDocument()), childNode.GetItemName());
}
childNode.RenameDocument(childNode.GetMkDocument(), newfilename);
//We must update the DependsUpon property since the rename operation will not do it if the childNode is not renamed
//which happens if the is no name relation between the parent and the child
var dependentOf = childNode.ItemNode.GetMetadata(ProjectFileConstants.DependentUpon);
if (!string.IsNullOrEmpty(dependentOf))
{
childNode.ItemNode.SetMetadata(ProjectFileConstants.DependentUpon, childNode.Parent.ItemNode.GetMetadata(ProjectFileConstants.Include));
}
}
}
/// <summary>
/// Tries recovering from a rename failure.
/// </summary>
/// <param name="fileThatFailed"> The file that failed to be renamed.</param>
/// <param name="originalFileName">The original filenamee</param>
protected virtual void RecoverFromRenameFailure(string fileThatFailed, string originalFileName)
{
if (this.ItemNode != null && !string.IsNullOrEmpty(originalFileName))
{
this.ItemNode.Rename(originalFileName);
}
}
internal override bool CanDeleteItem(__VSDELETEITEMOPERATION deleteOperation)
{
if (deleteOperation == __VSDELETEITEMOPERATION.DELITEMOP_DeleteFromStorage)
{
return this.ProjectMgr.CanProjectDeleteItems;
}
return false;
}
/// <summary>
/// This should be overriden for node that are not saved on disk
/// </summary>
/// <param name="oldName">Previous name in storage</param>
/// <param name="newName">New name in storage</param>
internal virtual void RenameInStorage(string oldName, string newName)
{
// Make a few attempts over a short time period
for (var retries = 4; retries > 0; --retries)
{
try
{
File.Move(oldName, newName);
return;
}
catch (IOException)
{
System.Threading.Thread.Sleep(50);
}
}
// Final attempt has no handling so exception propagates
File.Move(oldName, newName);
}
/// <summary>
/// This method should be overridden to provide the list of special files and associated flags for source control.
/// </summary>
/// <param name="sccFile">One of the file associated to the node.</param>
/// <param name="files">The list of files to be placed under source control.</param>
/// <param name="flags">The flags that are associated to the files.</param>
protected internal override void GetSccSpecialFiles(string sccFile, IList<string> files, IList<tagVsSccFilesFlags> flags)
{
if (this.ExcludeNodeFromScc)
{
return;
}
Utilities.ArgumentNotNull("files", files);
Utilities.ArgumentNotNull("flags", flags);
foreach (var node in this.GetChildNodes())
{
files.Add(node.GetMkDocument());
}
}
#endregion
#region Helper methods
/// <summary>
/// Gets called to rename the eventually running document this hierarchyitem points to
/// </summary>
/// returns FALSE if the doc can not be renamed
internal bool RenameDocument(string oldName, string newName)
{
var pRDT = this.GetService(typeof(IVsRunningDocumentTable)) as IVsRunningDocumentTable;
if (pRDT == null)
return false;
var docData = IntPtr.Zero;
IVsHierarchy pIVsHierarchy;
uint itemId;
uint uiVsDocCookie;
SuspendFileChanges sfc = null;
if (File.Exists(oldName))
{
sfc = new SuspendFileChanges(this.ProjectMgr.Site, oldName);
sfc.Suspend();
}
try
{
// Suspend ms build since during a rename operation no msbuild re-evaluation should be performed until we have finished.
// Scenario that could fail if we do not suspend.
// We have a project system relying on MPF that triggers a Compile target build (re-evaluates itself) whenever the project changes. (example: a file is added, property changed.)
// 1. User renames a file in the above project sytem relying on MPF
// 2. Our rename funstionality implemented in this method removes and readds the file and as a post step copies all msbuild entries from the removed file to the added file.
// 3. The project system mentioned will trigger an msbuild re-evaluate with the new item, because it was listening to OnItemAdded.
// The problem is that the item at the "add" time is only partly added to the project, since the msbuild part has not yet been copied over as mentioned in part 2 of the last step of the rename process.
// The result is that the project re-evaluates itself wrongly.
var renameflag = VSRENAMEFILEFLAGS.VSRENAMEFILEFLAGS_NoFlags;
ErrorHandler.ThrowOnFailure(pRDT.FindAndLockDocument((uint)_VSRDTFLAGS.RDT_NoLock, oldName, out pIVsHierarchy, out itemId, out docData, out uiVsDocCookie));
if (pIVsHierarchy != null && !Utilities.IsSameComObject(pIVsHierarchy, this.ProjectMgr))
{
// Don't rename it if it wasn't opened by us.
return false;
}
// ask other potentially running packages
if (!this.ProjectMgr.Tracker.CanRenameItem(oldName, newName, renameflag))
{
return false;
}
if (IsFileOnDisk(oldName))
{
RenameInStorage(oldName, newName);
}
// For some reason when ignoreFileChanges is called in Resume, we get an ArgumentException because
// Somewhere a required fileWatcher is null. This issue only occurs when you copy and rename a typescript file,
// Calling Resume here prevents said fileWatcher from being null. Don't know why it works, but it does.
// Also fun! This is the only location it can go (between RenameInStorage and RenameFileNode)
// So presumably there is some condition that is no longer met once both of these methods are called with a ts file.
// https://nodejstools.codeplex.com/workitem/1510
if (sfc != null)
{
sfc.Resume();
sfc.Suspend();
}
if (!CommonUtils.IsSamePath(oldName, newName))
{
// Check out the project file if necessary.
if (!this.ProjectMgr.QueryEditProjectFile(false))
{
throw Marshal.GetExceptionForHR(VSConstants.OLE_E_PROMPTSAVECANCELLED);
}
this.RenameFileNode(oldName, newName);
}
else
{
this.RenameCaseOnlyChange(oldName, newName);
}
DocumentManager.UpdateCaption(this.ProjectMgr.Site, this.Caption, docData);
// changed from MPFProj:
// http://mpfproj10.codeplex.com/WorkItem/View.aspx?WorkItemId=8231
this.ProjectMgr.Tracker.OnItemRenamed(oldName, newName, renameflag);
}
finally
{
if (sfc != null)
{
sfc.Resume();
}
if (docData != IntPtr.Zero)
{
Marshal.Release(docData);
}
}
return true;
}
internal virtual FileNode RenameFileNode(string oldFileName, string newFileName)
{
var newFolder = Path.GetDirectoryName(newFileName) + Path.DirectorySeparatorChar;
var parentFolder = this.ProjectMgr.FindNodeByFullPath(newFolder);
if (parentFolder == null)
{
Debug.Assert(newFolder == this.ProjectMgr.ProjectHome);
parentFolder = this.ProjectMgr;
}
return this.RenameFileNode(oldFileName, newFileName, parentFolder);
}
/// <summary>
/// Renames the file node for a case only change.
/// </summary>
/// <param name="newFileName">The new file name.</param>
private void RenameCaseOnlyChange(string oldName, string newName)
{
//Update the include for this item.
var relName = CommonUtils.GetRelativeFilePath(this.ProjectMgr.ProjectHome, newName);
Debug.Assert(StringComparer.OrdinalIgnoreCase.Equals(this.ItemNode.GetMetadata(ProjectFileConstants.Include), relName), "Not just changing the filename case");
this.ItemNode.Rename(relName);
this.ItemNode.RefreshProperties();
UpdateCaption();
this.ProjectMgr.ReDrawNode(this, UIHierarchyElement.Caption);
this.RenameChildNodes(this);
// Refresh the property browser.
var shell = this.ProjectMgr.Site.GetService(typeof(SVsUIShell)) as IVsUIShell;
Utilities.CheckNotNull(shell, "Could not get the UI shell from the project");
ErrorHandler.ThrowOnFailure(shell.RefreshPropertyBrowser(0));
//Select the new node in the hierarchy
ExpandItem(EXPANDFLAGS.EXPF_SelectItem);
}
#endregion
#region helpers
/// <summary>
/// Update the ChildNodes after the parent node has been renamed
/// </summary>
/// <param name="newFileNode">The new FileNode created as part of the rename of this node</param>
private void SetNewParentOnChildNodes(FileNode newFileNode)
{
foreach (var childNode in GetChildNodes())
{
childNode.Parent = newFileNode;
}
}
private List<HierarchyNode> GetChildNodes()
{
var childNodes = new List<HierarchyNode>();
var childNode = this.FirstChild;
while (childNode != null)
{
childNodes.Add(childNode);
childNode = childNode.NextSibling;
}
return childNodes;
}
#endregion
void IDiskBasedNode.RenameForDeferredSave(string basePath, string baseNewPath)
{
var oldLoc = CommonUtils.GetAbsoluteFilePath(basePath, this.ItemNode.GetMetadata(ProjectFileConstants.Include));
var newLoc = CommonUtils.GetAbsoluteFilePath(baseNewPath, this.ItemNode.GetMetadata(ProjectFileConstants.Include));
this.ProjectMgr.UpdatePathForDeferredSave(oldLoc, newLoc);
// make sure the directory is there
Directory.CreateDirectory(Path.GetDirectoryName(newLoc));
if (File.Exists(oldLoc))
{
File.Move(oldLoc, newLoc);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.MSBuild;
using Roslynator;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
using INamedTypeSymbol = Microsoft.CodeAnalysis.INamedTypeSymbol;
namespace Scriban.AsyncCodeGen
{
/// <summary>
/// Add support for async/await code for Scriban automatically from existing synchronous code
/// </summary>
class Program
{
private static INamedTypeSymbol _scriptNodeType;
private static INamedTypeSymbol _scriptListType;
static async Task Main(string[] args)
{
Microsoft.Build.Locator.MSBuildLocator.RegisterDefaults();
var workspace = MSBuildWorkspace.Create(new Dictionary<string, string>()
{
{"TargetFramework", "netstandard2.0"},
{"DefineConstants", "SCRIBAN_NO_ASYNC" }
});
var solution = await workspace.OpenSolutionAsync(Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, @"../../../../Scriban.sln")), new ConsoleProgressReporter());
var project = solution.Projects.First(x => x.Name == "Scriban");
var compilation = await project.GetCompilationAsync();
var errors = compilation.GetDiagnostics().Where(diagnostic => diagnostic.Severity == DiagnosticSeverity.Error).ToList();
if (errors.Count > 0)
{
Console.WriteLine("Compilation errors:");
foreach (var error in errors)
{
Console.WriteLine(error);
}
Console.WriteLine("Error, Exiting.");
Environment.Exit(1);
return;
}
_scriptNodeType = compilation.GetTypeByMetadataName("Scriban.Syntax.ScriptNode");
_scriptListType = compilation.GetTypeByMetadataName("Scriban.Syntax.ScriptList");
var models = compilation.SyntaxTrees.Select(tree => compilation.GetSemanticModel(tree)).ToList();
var methods = new Stack<IMethodSymbol>();
var visited = new HashSet<IMethodSymbol>();
// ----------------------------------------------------------------------------------
// 1) Collect origin methods from IScriptOutput.Write and all ScriptNode.Evaluate methods
// ----------------------------------------------------------------------------------
foreach (var model in models)
{
foreach (var methodDeclaration in model.SyntaxTree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>())
{
if (methodDeclaration.Parent is InterfaceDeclarationSyntax)
{
var interfaceDecl = (InterfaceDeclarationSyntax) methodDeclaration.Parent;
var interfaceType = model.GetDeclaredSymbol(interfaceDecl);
if (interfaceType != null && interfaceType.ContainingNamespace.Name == "Runtime" && (interfaceType.Name == "IScriptOutput" || interfaceType.Name == "IScriptCustomFunction" || (interfaceType.Name == "ITemplateLoader" && methodDeclaration.Identifier.Text == "Load")))
{
var method = model.GetDeclaredSymbol(methodDeclaration);
// Convert only IScriptCustomFunction.Invoke
if (interfaceType.Name == "IScriptCustomFunction" && method.Name != "Invoke") continue;
if (visited.Add(method))
{
methods.Push(method);
}
}
}
else
{
var methodModel = model.GetDeclaredSymbol(methodDeclaration);
if (!methodModel.IsStatic && (methodModel.Name == "Evaluate" || methodModel.Name == "EvaluateImpl") && methodModel.Parameters.Length == 1 && methodModel.Parameters[0].Type.Name == "TemplateContext" && InheritFrom(methodModel.ReceiverType, "Syntax", "ScriptNode"))
{
while (methodModel != null)
{
if (visited.Add(methodModel))
{
methods.Push(methodModel);
}
methodModel = methodModel.OverriddenMethod;
}
}
}
}
}
var originalMethods = new List<IMethodSymbol>(methods);
// ----------------------------------------------------------------------------------
// 2) Collect method graph calls
// ----------------------------------------------------------------------------------
var methodGraph = new Dictionary<IMethodSymbol, HashSet<ITypeSymbol>>();
var classGraph = new Dictionary<ITypeSymbol, ClassToTransform>();
visited.Clear();
while (methods.Count > 0)
{
var method = methods.Pop();
if (!visited.Add(method))
{
continue;
}
HashSet<ITypeSymbol> callerTypes;
if (!methodGraph.TryGetValue(method, out callerTypes))
{
callerTypes = new HashSet<ITypeSymbol>();
methodGraph.Add(method, callerTypes);
}
var finds = await SymbolFinder.FindCallersAsync(method, solution);
foreach (var referencer in finds.Where(f => f.IsDirect))
{
var doc =solution.GetDocument(referencer.Locations.First().SourceTree);
if (doc.Project != project)
{
continue;
}
var callingMethodSymbol = (IMethodSymbol)referencer.CallingSymbol;
if (callingMethodSymbol.MethodKind == MethodKind.StaticConstructor || callingMethodSymbol.MethodKind == MethodKind.Constructor)
{
continue;
}
// Skip methods over than Evaluate for ScriptNode
// Skip also entirely any methods related to ScriptVisitor
if (callingMethodSymbol.Name == "ToString" ||
(callingMethodSymbol.OverriddenMethod != null && callingMethodSymbol.OverriddenMethod.ContainingType.Name == "ScriptNode" && callingMethodSymbol.Name != "Evaluate") ||
InheritFrom(callingMethodSymbol.ContainingType, "Syntax", "ScriptVisitor") ||
InheritFrom(callingMethodSymbol.ContainingType, "Runtime", "ScriptObject"))
{
continue;
}
methods.Push(callingMethodSymbol);
// Push the method overriden
var methodOverride = callingMethodSymbol;
while (methodOverride != null && methodOverride.IsOverride && methodOverride.OverriddenMethod != null)
{
methods.Push(methodOverride.OverriddenMethod);
methodOverride = methodOverride.OverriddenMethod;
}
var callingSyntax = referencer.CallingSymbol.DeclaringSyntaxReferences[0].GetSyntax();
var callingMethod = (MethodDeclarationSyntax)callingSyntax;
foreach (var invokeLocation in referencer.Locations)
{
var invoke = callingMethod.FindNode(invokeLocation.SourceSpan);
while (invoke != null && !(invoke is InvocationExpressionSyntax))
{
invoke = invoke.Parent;
}
Debug.Assert(invoke is InvocationExpressionSyntax);
var declaredSymbol = callingMethodSymbol.ReceiverType;
if (declaredSymbol.Name != "ScriptPrinter" && callingMethodSymbol.Parameters.All(x => x.Type.Name != "ScriptPrinter" && x.Type.Name != "ScriptPrinterOptions")
&& (declaredSymbol.BaseType.Name != "DynamicCustomFunction" || declaredSymbol.Name == "GenericFunctionWrapper"))
{
ClassToTransform classToTransform;
if (!classGraph.TryGetValue(callingMethodSymbol.ReceiverType, out classToTransform))
{
classToTransform = new ClassToTransform(callingMethodSymbol.ReceiverType);
classGraph.Add(callingMethodSymbol.ReceiverType, classToTransform);
callerTypes.Add(callingMethodSymbol.ReceiverType);
}
// Find an existing method to transform
var methodToTransform = classToTransform.MethodCalls.FirstOrDefault(x => x.MethodSymbol.Equals(callingMethodSymbol));
if (methodToTransform == null)
{
methodToTransform = new MethodCallToTransform(callingMethodSymbol, callingMethod);
classToTransform.MethodCalls.Add(methodToTransform);
}
// Add a call site
methodToTransform.CallSites.Add((InvocationExpressionSyntax)invoke);
}
}
}
}
// ----------------------------------------------------------------------------------
// 3) Generate Async Methods
// ----------------------------------------------------------------------------------
methods.Clear();
methods = new Stack<IMethodSymbol>(originalMethods);
visited.Clear();
var cu = (CompilationUnitSyntax)ParseSyntaxTree(@"
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using Scriban.Helpers;
using Scriban.Parsing;
using Scriban.Runtime;
using Scriban.Syntax;
using System.Numerics;
").GetRoot();
solution = project.Solution;
// Create namespaces
var namespaces = new Dictionary<string, NamespaceDeclarationSyntax>();
foreach (var classToTransform in classGraph.Values)
{
NamespaceDeclarationSyntax nsDecl;
if (!namespaces.TryGetValue(classToTransform.Namespace, out nsDecl))
{
nsDecl = NamespaceDeclaration(ParseName(classToTransform.Namespace)).NormalizeWhitespace()
.WithLeadingTrivia(LineFeed)
.WithTrailingTrivia(LineFeed);
namespaces.Add(classToTransform.Namespace, nsDecl);
}
}
var typeTransformed = new HashSet<ITypeSymbol>();
while (methods.Count > 0)
{
var methodSymbol = methods.Pop();
if (!visited.Add(methodSymbol))
{
continue;
}
var asyncTypes = methodGraph[methodSymbol];
foreach (var asyncTypeSymbol in asyncTypes)
{
// The type has been already transformed, don't try to transform it
if (!typeTransformed.Add(asyncTypeSymbol))
{
continue;
}
var callingClass = classGraph[asyncTypeSymbol];
var typeDecl = (TypeDeclarationSyntax)asyncTypeSymbol.DeclaringSyntaxReferences[0].GetSyntax();
// TODO: Doesn't support nested classes
if (typeDecl.Modifiers.All(x => x.Text != "partial"))
{
var rootSyntax = typeDecl.SyntaxTree.GetRoot();
var originalDoc = solution.GetDocument(rootSyntax.SyntaxTree);
if (originalDoc != null)
{
var previousDecl = typeDecl;
typeDecl = typeDecl.WithModifiers(typeDecl.Modifiers.Add(Token(SyntaxKind.PartialKeyword).WithTrailingTrivia(Space)));
rootSyntax = rootSyntax.ReplaceNode(previousDecl, typeDecl);
originalDoc = originalDoc.WithSyntaxRoot(rootSyntax);
solution = originalDoc.Project.Solution;
}
}
typeDecl = typeDecl.RemoveNodes(typeDecl.ChildNodes().ToList(), SyntaxRemoveOptions.KeepNoTrivia);
// Remove if/endif directive
typeDecl = typeDecl.WithCloseBraceToken(Token(RemoveIfDef(typeDecl.CloseBraceToken.LeadingTrivia), SyntaxKind.CloseBraceToken, typeDecl.CloseBraceToken.TrailingTrivia));
foreach (var callingMethod in callingClass.MethodCalls)
{
var methodModel = callingMethod.MethodSymbol;
var method = callingMethod.CallerMethod;
//Console.WriteLine(method.ToFullString());
//Console.Out.Flush();
//method = method.TrackNodes(callingMethod.CallSites);
//var originalMethod = method;
bool addCancellationToken = false;
method = method.ReplaceNodes(callingMethod.CallSites, (callSite, r) =>
{
var leadingTrivia = callSite.GetLeadingTrivia();
var newCallSite = callSite.WithLeadingTrivia(Space);
switch (newCallSite.Expression)
{
case MemberBindingExpressionSyntax m:
{
var newExpression = m.WithName(IdentifierName(m.Name.ToString() + "Async"));
newCallSite = newCallSite.WithExpression(newExpression);
break;
}
case IdentifierNameSyntax m:
{
var newExpression = m.WithIdentifier(Identifier(m.Identifier.Text.ToString() + "Async"));
newCallSite = newCallSite.WithExpression(newExpression);
break;
}
case MemberAccessExpressionSyntax m:
{
var newExpression = m.WithName(IdentifierName(m.Name.ToString() + "Async"));
newCallSite = newCallSite.WithExpression(newExpression);
var sm = compilation.GetSemanticModel(callSite.SyntaxTree.GetRoot().SyntaxTree);
var originalMember = ((MemberAccessExpressionSyntax) callSite.Expression).Expression;
var symbol = sm.GetSymbolInfo(originalMember).Symbol;
if (symbol != null)
{
if (symbol is IPropertySymbol)
{
var prop = (IPropertySymbol) symbol;
if (prop.Type.Name == "IScriptOutput")
{
newCallSite = newCallSite.WithArgumentList(newCallSite.ArgumentList.AddArguments(Argument(IdentifierName("CancellationToken").WithLeadingTrivia(Space))));
}
}
else if (symbol is IParameterSymbol)
{
var param = (IParameterSymbol) symbol;
if (param.Type.Name == "IScriptOutput")
{
addCancellationToken = true;
newCallSite = newCallSite.WithArgumentList(newCallSite.ArgumentList.AddArguments(Argument(IdentifierName("cancellationToken").WithLeadingTrivia(Space))));
}
}
}
//if (.ReceiverType.Name == "IScriptOutput" || methodModel.ReceiverType.Name == "ScriptOutputExtensions")
//{
// var existingArguments = newCallSite.ArgumentList;
// existingArguments = existingArguments.AddArguments(Argument(IdentifierName("CancellationToken")));
// newCallSite = newCallSite.WithArgumentList(existingArguments);
//}
break;
}
default:
throw new NotSupportedException($"Expression not supported: {newCallSite.Expression}");
}
var awaitCall = AwaitExpression(InvocationExpression(
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
newCallSite,
IdentifierName("ConfigureAwait")))
.WithArgumentList(
ArgumentList(
SingletonSeparatedList<ArgumentSyntax>(
Argument(
LiteralExpression(
SyntaxKind.FalseLiteralExpression))))))
.WithAwaitKeyword(Token(leadingTrivia, SyntaxKind.AwaitKeyword, TriviaList(Space)));
return awaitCall;
});
if (addCancellationToken)
{
method = method.WithParameterList(method.ParameterList.AddParameters(
Parameter(Identifier("cancellationToken")).WithType(IdentifierName("CancellationToken")).NormalizeWhitespace()
));
}
TypeSyntax asyncReturnType;
if (methodModel.ReturnsVoid)
{
asyncReturnType = IdentifierName("ValueTask").WithTrailingTrivia(Space);
}
else
{
var trailingTrivia = method.ReturnType.GetTrailingTrivia();
asyncReturnType = GenericName(
Identifier("ValueTask"))
.WithTypeArgumentList(
TypeArgumentList(
SingletonSeparatedList(method.ReturnType.WithoutTrailingTrivia()))).WithTrailingTrivia(trailingTrivia);
}
method = method.WithReturnType(asyncReturnType);
// Rename method with `Async` postfix
method = method.WithIdentifier(Identifier(method.Identifier.Text + "Async"));
// Add async keyword to the method
method = method.WithModifiers(method.Modifiers.Add(Token(SyntaxKind.AsyncKeyword).WithTrailingTrivia(Space)));
// Remove any if/def
method = method.WithLeadingTrivia(RemoveIfDef(method.GetLeadingTrivia()));
typeDecl = typeDecl.AddMembers(method);
methods.Push(callingMethod.MethodSymbol);
}
//Debug.Assert(typeDecl.Members.All(x => x is MethodDeclarationSyntax));
// Order members
var orderedMembers = typeDecl.Members.OfType<MemberDeclarationSyntax>().OrderBy(m =>
{
if (m is PropertyDeclarationSyntax prop) return prop.Identifier.Text;
else
{
return ((MethodDeclarationSyntax) m).Identifier.Text;
}
}).ToArray();
typeDecl = typeDecl.WithMembers(new SyntaxList<MemberDeclarationSyntax>(orderedMembers));
// Update namespace
namespaces[callingClass.Namespace] = namespaces[callingClass.Namespace].AddMembers(typeDecl);
// work on method transforms
}
//methodSymbol.ContainingType.
}
// Reorder members
var nsList = namespaces.Values.OrderBy(ns => ns.Name.ToString()).ToList();
for (var i = 0; i < nsList.Count; i++)
{
nsList[i] = ReorderNsMembers(nsList[i]);
}
// Add #endif at the end
var lastns = nsList[nsList.Count - 1];
nsList[nsList.Count - 1] = lastns.WithCloseBraceToken(lastns.CloseBraceToken.WithTrailingTrivia(Trivia(EndIfDirectiveTrivia(true)))).NormalizeWhitespace();
var triviaList = cu.GetLeadingTrivia();
triviaList = triviaList.Insert(0, Trivia(
IfDirectiveTrivia(
IdentifierName("!SCRIBAN_NO_ASYNC"),
true,
false,
false)));
cu = cu.WithLeadingTrivia(triviaList).NormalizeWhitespace();
cu = cu.AddMembers(nsList.ToArray());
cu = (CompilationUnitSyntax)Formatter.Format(cu, workspace);
// ----------------------------------------------------------------------------------
// 4) Generate ScriptNodes (visitor, accept methods, children, rewriter...)
// ----------------------------------------------------------------------------------
var cuNodes = (CompilationUnitSyntax)ParseSyntaxTree(@"
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Scriban.Helpers;
using Scriban.Parsing;
using Scriban.Runtime;
using Scriban.Syntax;
using System.Numerics;
").GetRoot();
var scriptSyntaxNs = NamespaceDeclaration(
QualifiedName(
IdentifierName("Scriban"),
IdentifierName("Syntax")));
var allScriptNodeTypes = await SymbolFinder.FindDerivedClassesAsync(_scriptNodeType, solution, true, new[] {project}.ToImmutableHashSet());
var listOfScriptNodes = allScriptNodeTypes.OrderBy(x => x.Name).ToList();
listOfScriptNodes = listOfScriptNodes.Where(x => (x.DeclaredAccessibility & Accessibility.Public) != 0 && !x.IsAbstract && x.Name != "ScriptList").ToList();
foreach (var scriptNodeDerivedType in listOfScriptNodes)
{
var typeDecl = GenerateChildrenCountAndGetChildrenImplMethods(scriptNodeDerivedType);
scriptSyntaxNs = scriptSyntaxNs.AddMembers(typeDecl);
}
// Generate visitors and rewriters
var newMembers = GenerateVisitors(listOfScriptNodes);
newMembers.AddRange(GenerateRewriters(listOfScriptNodes));
scriptSyntaxNs = scriptSyntaxNs.AddMembers(newMembers.ToArray());
scriptSyntaxNs = ReorderNsMembers(scriptSyntaxNs);
cuNodes = cuNodes.AddMembers(scriptSyntaxNs);
cuNodes = (CompilationUnitSyntax)Formatter.Format(cuNodes, workspace);
// ----------------------------------------------------------------------------------
// 5) Output codegen
// ----------------------------------------------------------------------------------
//var document = project.AddDocument("ScribanAsync.generated.cs", sourceText, null, "ScribanAsync.generated.cs");
var projectPath = Path.GetDirectoryName(project.FilePath);
WriteCu(cu, Path.Combine(projectPath, "ScribanAsync.generated.cs"));
WriteCu(cuNodes, Path.Combine(projectPath, "ScribanVisitors.generated.cs"));
// Applies changes for partial classes
workspace.TryApplyChanges(solution);
}
private static void WriteCu(CompilationUnitSyntax cu, string path)
{
var text = $@"//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Date:{DateTime.Now.ToString(CultureInfo.InvariantCulture.DateTimeFormat)}
// Runtime Version:{Environment.Version}
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
{cu.ToFullString()}";
// Normalize NewLine
text = text.Replace("\r\n", "\n").Replace("\n", Environment.NewLine);
File.WriteAllText(path, text, Encoding.UTF8);
}
private static bool IsScriptNode(ITypeSymbol typeSymbol)
{
return ReferenceEquals(typeSymbol, _scriptNodeType) || typeSymbol.InheritsFrom(_scriptNodeType);
}
private static bool IsScriptList(ITypeSymbol typeSymbol)
{
return typeSymbol.InheritsFrom(_scriptListType);
}
private static NamespaceDeclarationSyntax ReorderNsMembers(NamespaceDeclarationSyntax ns)
{
Debug.Assert(ns.Members.All(m => m is TypeDeclarationSyntax));
var types = ns.Members.OfType<TypeDeclarationSyntax>().OrderBy(t => t.Identifier.Text).ToList();
ns = ns.WithMembers(new SyntaxList<MemberDeclarationSyntax>(types));
return ns;
}
private static TypeDeclarationSyntax GenerateChildrenCountAndGetChildrenImplMethods(INamedTypeSymbol typeSymbol)
{
var properties = GetScriptProperties(typeSymbol, false);
// Generate implementation for ScriptNode.GetChildrenImpl
// protected override ScriptNode GetChildrenImpl(int index) => null;
var getChildrenImplDecl = MethodDeclaration(
IdentifierName("ScriptNode"),
Identifier("GetChildrenImpl"))
.WithModifiers(
TokenList(
new[]
{
Token(SyntaxKind.ProtectedKeyword),
Token(SyntaxKind.OverrideKeyword)
}))
.WithParameterList(
ParameterList(
SingletonSeparatedList<ParameterSyntax>(
Parameter(
Identifier("index"))
.WithType(
PredefinedType(
Token(SyntaxKind.IntKeyword))))));
if (properties.Count == 0)
{
// protected override ScriptNode GetChildrenImpl(int index) => null;
getChildrenImplDecl = getChildrenImplDecl.WithExpressionBody(
ArrowExpressionClause(
LiteralExpression(
SyntaxKind.NullLiteralExpression))).WithSemicolonToken(
Token(SyntaxKind.SemicolonToken));
}
else if (properties.Count == 1)
{
// protected override ScriptNode GetChildrenImpl(int index) => Statements;
getChildrenImplDecl = getChildrenImplDecl.WithExpressionBody(
ArrowExpressionClause(
IdentifierName(properties[0].Name)))
.WithSemicolonToken(
Token(SyntaxKind.SemicolonToken));
}
else
{
// protected override ScriptNode GetChildrenImpl(int index)
// {
// return index switch
// {
// 0 => Left,
// 1 => OperatorToken,
// 2 => Right,
// _ => null
// };
// }
var listTokens = new List<SyntaxNodeOrToken>();
for (var i = 0; i < properties.Count; i++)
{
var prop = properties[i];
listTokens.Add(
SwitchExpressionArm(
ConstantPattern(
LiteralExpression(
SyntaxKind.NumericLiteralExpression,
Literal(i))),
IdentifierName(prop.Name)));
listTokens.Add(Token(SyntaxKind.CommaToken));
}
listTokens.Add(SwitchExpressionArm(
DiscardPattern(),
LiteralExpression(
SyntaxKind.NullLiteralExpression)));
getChildrenImplDecl = getChildrenImplDecl.WithBody(
Block(
SingletonList<StatementSyntax>(
ReturnStatement(
SwitchExpression(
IdentifierName("index"))
.WithArms(
SeparatedList<SwitchExpressionArmSyntax>(listTokens))))));
}
var childrenCountDecl = PropertyDeclaration(
PredefinedType(
Token(SyntaxKind.IntKeyword)),
Identifier("ChildrenCount"))
.WithModifiers(
TokenList(
new[]
{
Token(SyntaxKind.PublicKeyword),
Token(SyntaxKind.OverrideKeyword)
}))
.WithExpressionBody(
ArrowExpressionClause(
LiteralExpression(
SyntaxKind.NumericLiteralExpression,
Literal(properties.Count))))
.WithSemicolonToken(Token(SyntaxKind.SemicolonToken));
//public override void Accept(ScriptVisitor visitor) => visitor.Visit(this);
var acceptMethod = MethodDeclaration(
PredefinedType(
Token(SyntaxKind.VoidKeyword)),
Identifier("Accept"))
.WithModifiers(
TokenList(
new[]
{
Token(SyntaxKind.PublicKeyword),
Token(SyntaxKind.OverrideKeyword)
}))
.WithParameterList(
ParameterList(
SingletonSeparatedList<ParameterSyntax>(
Parameter(
Identifier("visitor"))
.WithType(
IdentifierName("ScriptVisitor")))))
.WithExpressionBody(
ArrowExpressionClause(
InvocationExpression(
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName("visitor"),
IdentifierName("Visit")))
.WithArgumentList(
ArgumentList(
SingletonSeparatedList<ArgumentSyntax>(
Argument(
ThisExpression()))))))
.WithSemicolonToken(
Token(SyntaxKind.SemicolonToken));
//public override TResult Accept<TResult>(ScriptVisitor<TResult> visitor) => visitor.Visit(this);
var acceptGenericMethod = MethodDeclaration(
IdentifierName("TResult"),
Identifier("Accept"))
.WithModifiers(
TokenList(
new[]
{
Token(SyntaxKind.PublicKeyword),
Token(SyntaxKind.OverrideKeyword)
}))
.WithTypeParameterList(
TypeParameterList(
SingletonSeparatedList<TypeParameterSyntax>(
TypeParameter(
Identifier("TResult")))))
.WithParameterList(
ParameterList(
SingletonSeparatedList<ParameterSyntax>(
Parameter(
Identifier("visitor"))
.WithType(
GenericName(
Identifier("ScriptVisitor"))
.WithTypeArgumentList(
TypeArgumentList(
SingletonSeparatedList<TypeSyntax>(
IdentifierName("TResult"))))))))
.WithExpressionBody(
ArrowExpressionClause(
InvocationExpression(
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName("visitor"),
IdentifierName("Visit")))
.WithArgumentList(
ArgumentList(
SingletonSeparatedList<ArgumentSyntax>(
Argument(
ThisExpression()))))))
.WithSemicolonToken(
Token(SyntaxKind.SemicolonToken));
return ClassDeclaration(typeSymbol.Name)
.WithModifiers(
TokenList(
new[]
{
Token(SyntaxKind.PublicKeyword),
Token(SyntaxKind.PartialKeyword)
})).WithMembers(
List(new MemberDeclarationSyntax[]
{
childrenCountDecl,
getChildrenImplDecl,
acceptMethod,
acceptGenericMethod
}));
}
private static List<MemberDeclarationSyntax> GenerateVisitors(List<INamedTypeSymbol> scriptNodeTypes)
{
var members = new List<MemberDeclarationSyntax>();
foreach (var scriptNodeType in scriptNodeTypes)
{
// public virtual void Visit(ScriptTableRowStatement node) => DefaultVisit(node);
var method = MethodDeclaration(
PredefinedType(
Token(SyntaxKind.VoidKeyword)),
Identifier("Visit"))
.WithModifiers(
TokenList(
new[]
{
Token(SyntaxKind.PublicKeyword),
Token(SyntaxKind.VirtualKeyword)
}))
.WithParameterList(
ParameterList(
SingletonSeparatedList<ParameterSyntax>(
Parameter(
Identifier("node"))
.WithType(
IdentifierName(scriptNodeType.Name)))))
.WithExpressionBody(
ArrowExpressionClause(
InvocationExpression(
IdentifierName("DefaultVisit"))
.WithArgumentList(
ArgumentList(
SingletonSeparatedList<ArgumentSyntax>(
Argument(
IdentifierName("node")))))))
.WithSemicolonToken(
Token(SyntaxKind.SemicolonToken));
members.Add(method);
}
var scriptVisitor = ClassDeclaration("ScriptVisitor")
.WithModifiers(
TokenList(
new[]
{
Token(SyntaxKind.PublicKeyword),
Token(SyntaxKind.AbstractKeyword),
Token(SyntaxKind.PartialKeyword)
})).WithMembers(new SyntaxList<MemberDeclarationSyntax>(members));
members.Clear();
foreach (var scriptNodeType in scriptNodeTypes)
{
// public virtual void Visit(ScriptTableRowStatement node) => DefaultVisit(node);
var method = MethodDeclaration(
IdentifierName("TResult"),
Identifier("Visit"))
.WithModifiers(
TokenList(
new[]
{
Token(SyntaxKind.PublicKeyword),
Token(SyntaxKind.VirtualKeyword)
}))
.WithParameterList(
ParameterList(
SingletonSeparatedList<ParameterSyntax>(
Parameter(
Identifier("node"))
.WithType(
IdentifierName(scriptNodeType.Name)))))
.WithExpressionBody(
ArrowExpressionClause(
InvocationExpression(
IdentifierName("DefaultVisit"))
.WithArgumentList(
ArgumentList(
SingletonSeparatedList<ArgumentSyntax>(
Argument(
IdentifierName("node")))))))
.WithSemicolonToken(
Token(SyntaxKind.SemicolonToken));
members.Add(method);
}
var scriptVisitorTResult = ClassDeclaration("ScriptVisitor")
.WithModifiers(
TokenList(
new[]
{
Token(SyntaxKind.PublicKeyword),
Token(SyntaxKind.AbstractKeyword),
Token(SyntaxKind.PartialKeyword)
}))
.WithTypeParameterList(
TypeParameterList(
SingletonSeparatedList<TypeParameterSyntax>(
TypeParameter(
Identifier("TResult"))))).WithMembers(new SyntaxList<MemberDeclarationSyntax>(members));
members.Clear();
members.Add(scriptVisitor);
members.Add(scriptVisitorTResult);
return members;
}
private static List<IPropertySymbol> GetScriptProperties(INamedTypeSymbol typeSymbol, bool includeNonScriptNode)
{
var types = new Stack<ITypeSymbol>();
var typeToFetch = typeSymbol;
while (typeToFetch != null)
{
types.Push(typeToFetch);
typeToFetch = typeToFetch.BaseType;
if (typeToFetch.Name == "ScriptNode")
{
break;
}
}
var properties = new List<IPropertySymbol>();
foreach (var type in types)
{
var localProperties = type.GetMembers().OfType<IPropertySymbol>().Where(prop =>
prop.Name != "Trivias" &&
!prop.IsReadOnly &&
(prop.SetMethod != null && prop.SetMethod.DeclaredAccessibility == Accessibility.Public) &&
(IsScriptNode(prop.Type) || includeNonScriptNode)
).ToList();
properties.AddRange(localProperties);
}
return properties;
}
private static List<MemberDeclarationSyntax> GenerateRewriters(List<INamedTypeSymbol> scriptNodeTypes)
{
var members = new List<MemberDeclarationSyntax>();
foreach (var scriptNodeType in scriptNodeTypes)
{
var properties = GetScriptProperties(scriptNodeType, true);
var statements = new List<StatementSyntax>();
var assignExpressions = new List<SyntaxNodeOrToken>();
switch (scriptNodeType.Name)
{
case "ScriptVariableGlobal":
case "ScriptVariableLocal":
case "ScriptVariableLoop":
continue;
}
foreach (var prop in properties)
{
if (assignExpressions.Count > 0)
{
assignExpressions.Add(Token(SyntaxKind.CommaToken));
}
if (!IsScriptNode(prop.Type))
{
// XXX = node.XXX
assignExpressions.Add(AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
IdentifierName(prop.Name),
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName("node"),
IdentifierName(prop.Name)))
);
continue;
}
LocalDeclarationStatementSyntax localVar;
// XXX = newXXX
assignExpressions.Add(AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
IdentifierName(prop.Name),
IdentifierName($"new{prop.Name}"))
);
if (IsScriptList(prop.Type))
{
// var newXXX = VisitAll(node.XXX);
localVar = LocalDeclarationStatement(
VariableDeclaration(
IdentifierName("var"))
.WithVariables(
SingletonSeparatedList<VariableDeclaratorSyntax>(
VariableDeclarator(
Identifier($"new{prop.Name}"))
.WithInitializer(
EqualsValueClause(
InvocationExpression(
IdentifierName("VisitAll"))
.WithArgumentList(
ArgumentList(
SingletonSeparatedList<ArgumentSyntax>(
Argument(
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName("node"),
IdentifierName(prop.Name)))))))))));
}
else
{
// var newXXX = (XXXType) Visit((ScriptNode)node.XXX);
localVar = LocalDeclarationStatement(
VariableDeclaration(
IdentifierName("var"))
.WithVariables(
SingletonSeparatedList<VariableDeclaratorSyntax>(
VariableDeclarator(
Identifier($"new{prop.Name}"))
.WithInitializer(
EqualsValueClause(
CastExpression(
IdentifierName(prop.Type.Name),
InvocationExpression(
IdentifierName("Visit"))
.WithArgumentList(
ArgumentList(
SingletonSeparatedList<ArgumentSyntax>(
Argument(
CastExpression(
IdentifierName(_scriptNodeType.Name),
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName("node"),
IdentifierName(prop.Name)))))))))))));
}
statements.Add(localVar);
}
statements.Add(ReturnStatement(ObjectCreationExpression(
IdentifierName(scriptNodeType.Name))
.WithArgumentList(
ArgumentList())
.WithInitializer(
InitializerExpression(
SyntaxKind.ObjectInitializerExpression,
SeparatedList<ExpressionSyntax>(assignExpressions))))
);
members.Add(
MethodDeclaration(
IdentifierName("ScriptNode"),
Identifier("Visit"))
.WithModifiers(
TokenList(
new[]
{
Token(SyntaxKind.PublicKeyword),
Token(SyntaxKind.OverrideKeyword)
}))
.WithParameterList(
ParameterList(
SingletonSeparatedList<ParameterSyntax>(
Parameter(
Identifier("node"))
.WithType(
IdentifierName(scriptNodeType.Name)))))
.WithBody(
Block(statements))
);
}
var scriptRewriterType = ClassDeclaration("ScriptRewriter")
.WithModifiers(
TokenList(
new[]
{
Token(SyntaxKind.PublicKeyword),
Token(SyntaxKind.AbstractKeyword),
Token(SyntaxKind.PartialKeyword)
}))
.WithMembers(new SyntaxList<MemberDeclarationSyntax>(members));
members.Clear();
members.Add(scriptRewriterType);
return members;
}
private static SyntaxNode GetDeclaredSyntax(ISymbol symbol, Solution solution)
{
var typeRefDeclList = symbol.DeclaringSyntaxReferences.Where(x => !solution.GetDocument(x.SyntaxTree).FilePath.Contains(".generated")).ToList();
if (typeRefDeclList.Count != 1) throw new InvalidOperationException($"Invalid number {typeRefDeclList.Count} of syntax references for {symbol.MetadataName}. Expecting only 1.");
return typeRefDeclList[0].GetSyntax();
}
private static Solution ModifyProperties(INamedTypeSymbol typeSymbol, Solution solution)
{
var typeSyntax = (TypeDeclarationSyntax)GetDeclaredSyntax(typeSymbol, solution);
var properties = typeSymbol.GetMembers().OfType<IPropertySymbol>().Where(x => IsScriptNode(x.Type)).ToList();
Console.WriteLine($"{typeSymbol.MetadataName} {typeSyntax.Identifier.Text}");
foreach (var prop in properties)
{
var propertyDecls = (PropertyDeclarationSyntax)GetDeclaredSyntax(prop, solution);
Console.WriteLine($" => {propertyDecls.Type} {propertyDecls.Identifier.Text}");
}
//var typeDecl = (TypeDeclarationSyntax)typeSymbol.DeclaringSyntaxReferences[0].GetSyntax();
//// TODO: Doesn't support nested classes
//if (typeDecl.Modifiers.All(x => x.Text != "partial"))
//{
// var rootSyntax = typeDecl.SyntaxTree.GetRoot();
// var originalDoc = solution.GetDocument(rootSyntax.SyntaxTree);
// var previousDecl = typeDecl;
// typeDecl = typeDecl.WithModifiers(typeDecl.Modifiers.Add(Token(SyntaxKind.PartialKeyword).WithTrailingTrivia(Space)));
// rootSyntax = rootSyntax.ReplaceNode(previousDecl, typeDecl);
// originalDoc = originalDoc.WithSyntaxRoot(rootSyntax);
// solution = originalDoc.Project.Solution;
//}
return solution;
}
public static string GetNamespace(ISymbol symbol)
{
if (string.IsNullOrEmpty(symbol.ContainingNamespace?.Name))
{
return null;
}
var restOfResult = GetNamespace(symbol.ContainingNamespace);
var result = symbol.ContainingNamespace.Name;
if (restOfResult != null)
result = restOfResult + '.' + result;
return result;
}
public static SyntaxTriviaList RemoveIfDef(SyntaxTriviaList trivia)
{
int inDirective = 0;
for (int i = 0; i < trivia.Count; i++)
{
if (trivia[i].Kind() == SyntaxKind.IfDirectiveTrivia)
{
trivia = trivia.RemoveAt(i);
i--;
inDirective++;
}
else if (trivia[i].Kind() == SyntaxKind.EndIfDirectiveTrivia)
{
trivia = trivia.RemoveAt(i);
i--;
inDirective--;
}
else if (inDirective > 0)
{
trivia = trivia.RemoveAt(i);
i--;
}
}
return trivia;
}
public static bool InheritFrom(ITypeSymbol type, string nameSpace, string typeName)
{
while (type != null)
{
if (type.Name == typeName && type.ContainingNamespace.Name == nameSpace)
{
return true;
}
else
{
type = type.BaseType;
}
}
return false;
}
[DebuggerDisplay("{TypeSymbol}")]
class ClassToTransform
{
public ClassToTransform(ITypeSymbol typeSymbol)
{
TypeSymbol = typeSymbol;
MethodCalls = new List<MethodCallToTransform>();
Namespace = GetNamespace(typeSymbol);
}
public ITypeSymbol TypeSymbol { get; }
public string Namespace { get; }
public TypeDeclarationSyntax AsyncDeclarationTypeSyntax { get; set; }
public List<MethodCallToTransform> MethodCalls { get; }
}
[DebuggerDisplay("{MethodSymbol} CallSites: {CallSites.Count}")]
class MethodCallToTransform
{
public MethodCallToTransform(IMethodSymbol methodSymbol, MethodDeclarationSyntax callerMethod)
{
MethodSymbol = methodSymbol;
CallerMethod = callerMethod;
CallSites = new List<InvocationExpressionSyntax>();
}
public IMethodSymbol MethodSymbol { get; }
public MethodDeclarationSyntax CallerMethod { get; }
public MethodDeclarationSyntax AsyncCalleeMethod { get; set; }
public List<InvocationExpressionSyntax> CallSites { get; }
}
private class ConsoleProgressReporter : IProgress<ProjectLoadProgress>
{
public void Report(ProjectLoadProgress loadProgress)
{
var projectDisplay = Path.GetFileName(loadProgress.FilePath);
if (loadProgress.TargetFramework != null)
{
projectDisplay += $" ({loadProgress.TargetFramework})";
}
Console.WriteLine($"{loadProgress.Operation,-15} {loadProgress.ElapsedTime,-15:m\\:ss\\.fffffff} {projectDisplay}");
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Orleans.Configuration;
using Orleans.Providers;
using Orleans.Runtime.Versions;
using Orleans.Runtime.Versions.Compatibility;
using Orleans.Runtime.Versions.Selector;
using Orleans.Statistics;
using Orleans.Versions.Compatibility;
using Orleans.Versions.Selector;
namespace Orleans.Runtime
{
internal class SiloControl : SystemTarget, ISiloControl
{
private readonly ILogger logger;
private readonly ILocalSiloDetails localSiloDetails;
private readonly DeploymentLoadPublisher deploymentLoadPublisher;
private readonly Catalog catalog;
private readonly CachedVersionSelectorManager cachedVersionSelectorManager;
private readonly CompatibilityDirectorManager compatibilityDirectorManager;
private readonly VersionSelectorManager selectorManager;
private readonly ActivationCollector _activationCollector;
private readonly ActivationDirectory activationDirectory;
private readonly IActivationWorkingSet activationWorkingSet;
private readonly IAppEnvironmentStatistics appEnvironmentStatistics;
private readonly IHostEnvironmentStatistics hostEnvironmentStatistics;
private readonly IOptions<LoadSheddingOptions> loadSheddingOptions;
private readonly GrainCountStatistics _grainCountStatistics;
private readonly Dictionary<Tuple<string,string>, IControllable> controllables;
public SiloControl(
ILocalSiloDetails localSiloDetails,
DeploymentLoadPublisher deploymentLoadPublisher,
Catalog catalog,
CachedVersionSelectorManager cachedVersionSelectorManager,
CompatibilityDirectorManager compatibilityDirectorManager,
VersionSelectorManager selectorManager,
IServiceProvider services,
ILoggerFactory loggerFactory,
IMessageCenter messageCenter,
ActivationCollector activationCollector,
ActivationDirectory activationDirectory,
IActivationWorkingSet activationWorkingSet,
IAppEnvironmentStatistics appEnvironmentStatistics,
IHostEnvironmentStatistics hostEnvironmentStatistics,
IOptions<LoadSheddingOptions> loadSheddingOptions,
GrainCountStatistics grainCountStatistics)
: base(Constants.SiloControlType, localSiloDetails.SiloAddress, loggerFactory)
{
this.localSiloDetails = localSiloDetails;
this.logger = loggerFactory.CreateLogger<SiloControl>();
this.deploymentLoadPublisher = deploymentLoadPublisher;
this.catalog = catalog;
this.cachedVersionSelectorManager = cachedVersionSelectorManager;
this.compatibilityDirectorManager = compatibilityDirectorManager;
this.selectorManager = selectorManager;
_activationCollector = activationCollector;
this.activationDirectory = activationDirectory;
this.activationWorkingSet = activationWorkingSet;
this.appEnvironmentStatistics = appEnvironmentStatistics;
this.hostEnvironmentStatistics = hostEnvironmentStatistics;
this.loadSheddingOptions = loadSheddingOptions;
_grainCountStatistics = grainCountStatistics;
this.controllables = new Dictionary<Tuple<string, string>, IControllable>();
IEnumerable<IKeyedServiceCollection<string, IControllable>> namedIControllableCollections = services.GetServices<IKeyedServiceCollection<string, IControllable>>();
foreach (IKeyedService<string, IControllable> keyedService in namedIControllableCollections.SelectMany(c => c.GetServices(services)))
{
IControllable controllable = keyedService.GetService(services);
if(controllable != null)
{
this.controllables.Add(Tuple.Create(controllable.GetType().FullName, keyedService.Key), controllable);
}
}
}
public Task Ping(string message)
{
logger.Info("Ping");
return Task.CompletedTask;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods", MessageId = "System.GC.Collect")]
public Task ForceGarbageCollection()
{
logger.Info("ForceGarbageCollection");
GC.Collect();
return Task.CompletedTask;
}
public Task ForceActivationCollection(TimeSpan ageLimit)
{
logger.Info("ForceActivationCollection");
return _activationCollector.CollectActivations(ageLimit);
}
public Task ForceRuntimeStatisticsCollection()
{
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("ForceRuntimeStatisticsCollection");
return this.deploymentLoadPublisher.RefreshStatistics();
}
public Task<SiloRuntimeStatistics> GetRuntimeStatistics()
{
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("GetRuntimeStatistics");
var activationCount = this.activationDirectory.Count;
var stats = new SiloRuntimeStatistics(
activationCount,
activationWorkingSet.Count,
this.appEnvironmentStatistics,
this.hostEnvironmentStatistics,
this.loadSheddingOptions,
DateTime.UtcNow);
return Task.FromResult(stats);
}
public Task<List<Tuple<GrainId, string, int>>> GetGrainStatistics()
{
logger.Info("GetGrainStatistics");
return Task.FromResult(this.catalog.GetGrainStatistics());
}
public Task<List<DetailedGrainStatistic>> GetDetailedGrainStatistics(string[] types=null)
{
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("GetDetailedGrainStatistics");
return Task.FromResult(this.catalog.GetDetailedGrainStatistics(types));
}
public Task<SimpleGrainStatistic[]> GetSimpleGrainStatistics()
{
logger.Info("GetSimpleGrainStatistics");
return Task.FromResult( _grainCountStatistics.GetSimpleGrainStatistics().Select(p =>
new SimpleGrainStatistic { SiloAddress = this.localSiloDetails.SiloAddress, GrainType = p.Key, ActivationCount = (int)p.Value }).ToArray());
}
public Task<DetailedGrainReport> GetDetailedGrainReport(GrainId grainId)
{
logger.Info("DetailedGrainReport for grain id {0}", grainId);
return Task.FromResult( this.catalog.GetDetailedGrainReport(grainId));
}
public Task<int> GetActivationCount()
{
return Task.FromResult(this.catalog.ActivationCount);
}
public Task<object> SendControlCommandToProvider(string providerTypeFullName, string providerName, int command, object arg)
{
IControllable controllable;
if(!this.controllables.TryGetValue(Tuple.Create(providerTypeFullName, providerName), out controllable))
{
string error = $"Could not find a controllable service for type {providerTypeFullName} and name {providerName}.";
logger.Error(ErrorCode.Provider_ProviderNotFound, error);
throw new ArgumentException(error);
}
return controllable.ExecuteCommand(command, arg);
}
public Task SetCompatibilityStrategy(CompatibilityStrategy strategy)
{
this.compatibilityDirectorManager.SetStrategy(strategy);
this.cachedVersionSelectorManager.ResetCache();
return Task.CompletedTask;
}
public Task SetSelectorStrategy(VersionSelectorStrategy strategy)
{
this.selectorManager.SetSelector(strategy);
this.cachedVersionSelectorManager.ResetCache();
return Task.CompletedTask;
}
public Task SetCompatibilityStrategy(GrainInterfaceType interfaceId, CompatibilityStrategy strategy)
{
this.compatibilityDirectorManager.SetStrategy(interfaceId, strategy);
this.cachedVersionSelectorManager.ResetCache();
return Task.CompletedTask;
}
public Task SetSelectorStrategy(GrainInterfaceType interfaceType, VersionSelectorStrategy strategy)
{
this.selectorManager.SetSelector(interfaceType, strategy);
this.cachedVersionSelectorManager.ResetCache();
return Task.CompletedTask;
}
public Task<List<GrainId>> GetActiveGrains(GrainType grainType)
{
var results = new List<GrainId>();
activationDirectory.ForEachGrainId(AddIfMatch, (grainType, results));
return Task.FromResult(results);
static void AddIfMatch((GrainType Type, List<GrainId> Result) context, GrainId id)
{
if (id.Type.Equals(context.Type))
{
context.Result.Add(id);
}
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using Should.Core.Exceptions;
namespace Should.Core.Assertions
{
/// <summary>
/// Contains various static methods that are used to verify that conditions are met during the
/// process of running tests.
/// </summary>
public class Assert
{
/// <summary>
/// Used by the Throws and DoesNotThrow methods.
/// </summary>
public delegate void ThrowsDelegate();
/// <summary>
/// Used by the Throws and DoesNotThrow methods.
/// </summary>
public delegate object ThrowsDelegateWithReturn();
/// <summary>
/// Initializes a new instance of the <see cref="Assert"/> class.
/// </summary>
protected Assert() { }
/// <summary>
/// Verifies that a collection contains a given object.
/// </summary>
/// <typeparam name="T">The type of the object to be verified</typeparam>
/// <param name="expected">The object expected to be in the collection</param>
/// <param name="collection">The collection to be inspected</param>
/// <exception cref="ContainsException">Thrown when the object is not present in the collection</exception>
public static void Contains<T>(T expected,
IEnumerable<T> collection)
{
Contains(expected, collection, GetEqualityComparer<T>());
}
/// <summary>
/// Verifies that a collection contains a given object, using an equality comparer.
/// </summary>
/// <typeparam name="T">The type of the object to be verified</typeparam>
/// <param name="expected">The object expected to be in the collection</param>
/// <param name="collection">The collection to be inspected</param>
/// <param name="comparer">The comparer used to equate objects in the collection with the expected object</param>
/// <exception cref="ContainsException">Thrown when the object is not present in the collection</exception>
public static void Contains<T>(T expected, IEnumerable<T> collection, IEqualityComparer<T> comparer)
{
foreach (T item in collection)
if (comparer.Equals(expected, item))
return;
throw new ContainsException(expected);
}
/// <summary>
/// Verifies that a string contains a given sub-string, using the current culture.
/// </summary>
/// <param name="expectedSubString">The sub-string expected to be in the string</param>
/// <param name="actualString">The string to be inspected</param>
/// <exception cref="ContainsException">Thrown when the sub-string is not present inside the string</exception>
public static int Contains(string expectedSubString,
string actualString)
{
return Contains(expectedSubString, actualString, StringComparison.CurrentCulture);
}
/// <summary>
/// Verifies that a string contains a given sub-string, using the given comparison type.
/// </summary>
/// <param name="expectedSubString">The sub-string expected to be in the string</param>
/// <param name="actualString">The string to be inspected</param>
/// <param name="comparisonType">The type of string comparison to perform</param>
/// <exception cref="ContainsException">Thrown when the sub-string is not present inside the string</exception>
public static int Contains(string expectedSubString,
string actualString,
StringComparison comparisonType)
{
int indexOf = actualString.IndexOf(expectedSubString, comparisonType);
if (indexOf < 0)
throw new ContainsException(expectedSubString);
return indexOf;
}
/// <summary>
///
/// </summary>
/// <param name="expectedStartString"></param>
/// <param name="actualString"></param>
/// <exception cref="StartsWithException">Thrown when the sub-string is not present at the start of the string</exception>
public static void StartsWith(string expectedStartString, string actualString)
{
if (actualString.StartsWith(expectedStartString) == false)
throw new StartsWithException(expectedStartString, actualString);
}
/// <summary>
/// Verifies that a collection does not contain a given object.
/// </summary>
/// <typeparam name="T">The type of the object to be compared</typeparam>
/// <param name="expected">The object that is expected not to be in the collection</param>
/// <param name="collection">The collection to be inspected</param>
/// <exception cref="DoesNotContainException">Thrown when the object is present inside the container</exception>
public static void DoesNotContain<T>(T expected,
IEnumerable<T> collection)
{
DoesNotContain(expected, collection, GetEqualityComparer<T>());
}
/// <summary>
/// Verifies that a collection does not contain a given object, using an equality comparer.
/// </summary>
/// <typeparam name="T">The type of the object to be compared</typeparam>
/// <param name="expected">The object that is expected not to be in the collection</param>
/// <param name="collection">The collection to be inspected</param>
/// <param name="comparer">The comparer used to equate objects in the collection with the expected object</param>
/// <exception cref="DoesNotContainException">Thrown when the object is present inside the container</exception>
public static void DoesNotContain<T>(T expected, IEnumerable<T> collection, IEqualityComparer<T> comparer)
{
foreach (T item in collection)
if (comparer.Equals(expected, item))
throw new DoesNotContainException(expected);
}
/// <summary>
/// Verifies that a string does not contain a given sub-string, using the current culture.
/// </summary>
/// <param name="expectedSubString">The sub-string which is expected not to be in the string</param>
/// <param name="actualString">The string to be inspected</param>
/// <exception cref="DoesNotContainException">Thrown when the sub-string is present inside the string</exception>
public static void DoesNotContain(string expectedSubString,
string actualString)
{
DoesNotContain(expectedSubString, actualString, StringComparison.CurrentCulture);
}
/// <summary>
/// Verifies that a string does not contain a given sub-string, using the current culture.
/// </summary>
/// <param name="expectedSubString">The sub-string which is expected not to be in the string</param>
/// <param name="actualString">The string to be inspected</param>
/// <param name="comparisonType">The type of string comparison to perform</param>
/// <exception cref="DoesNotContainException">Thrown when the sub-string is present inside the given string</exception>
public static void DoesNotContain(string expectedSubString,
string actualString,
StringComparison comparisonType)
{
if (actualString.IndexOf(expectedSubString, comparisonType) >= 0)
throw new DoesNotContainException(expectedSubString);
}
///// <summary>
///// Verifies that a block of code does not throw any exceptions.
///// </summary>
///// <param name="testCode">A delegate to the code to be tested</param>
//public static void DoesNotThrow(ThrowsDelegate testCode)
//{
// Exception ex = Record.Exception(testCode);
// if (ex != null)
// throw new DoesNotThrowException(ex);
//}
/// <summary>
/// Verifies that a collection is empty.
/// </summary>
/// <param name="collection">The collection to be inspected</param>
/// <exception cref="ArgumentNullException">Thrown when the collection is null</exception>
/// <exception cref="EmptyException">Thrown when the collection is not empty</exception>
public static void Empty(IEnumerable collection)
{
if (collection == null) throw new ArgumentNullException("collection", "cannot be null");
#pragma warning disable 168
foreach (object @object in collection)
throw new EmptyException();
#pragma warning restore 168
}
/// <summary>
/// Verifies that two objects are equal, using a default comparer.
/// </summary>
/// <typeparam name="T">The type of the objects to be compared</typeparam>
/// <param name="expected">The expected value</param>
/// <param name="actual">The value to be compared against</param>
/// <exception cref="EqualException">Thrown when the objects are not equal</exception>
public static void Equal<T>(T expected,
T actual)
{
Equal(expected, actual, GetEqualityComparer<T>());
}
/// <summary>
/// Verifies that two objects are equal, using a default comparer.
/// </summary>
/// <typeparam name="T">The type of the objects to be compared</typeparam>
/// <param name="expected">The expected value</param>
/// <param name="actual">The value to be compared against</param>
/// <param name="userMessage">The user message to be shown on failure</param>
/// <exception cref="EqualException">Thrown when the objects are not equal</exception>
public static void Equal<T>(T expected,
T actual,
string userMessage)
{
Equal(expected, actual, GetEqualityComparer<T>(), userMessage);
}
/// <summary>
/// Verifies that two objects are equal, using a custom comparer.
/// </summary>
/// <typeparam name="T">The type of the objects to be compared</typeparam>
/// <param name="expected">The expected value</param>
/// <param name="actual">The value to be compared against</param>
/// <param name="comparer">The comparer used to compare the two objects</param>
/// <exception cref="EqualException">Thrown when the objects are not equal</exception>
public static void Equal<T>(T expected,
T actual,
IEqualityComparer<T> comparer)
{
if (!comparer.Equals(expected, actual))
throw new EqualException(expected, actual);
}
/// <summary>
/// Verifies that two objects are equal, using a custom comparer.
/// </summary>
/// <typeparam name="T">The type of the objects to be compared</typeparam>
/// <param name="expected">The expected value</param>
/// <param name="actual">The value to be compared against</param>
/// <param name="comparer">The comparer used to compare the two objects</param>
/// <exception cref="EqualException">Thrown when the objects are not equal</exception>
public static void Equal<T>(T expected,
T actual,
IEqualityComparer<T> comparer,
string userMessage)
{
if (!comparer.Equals(expected, actual))
throw new EqualException(expected, actual, userMessage);
}
/// <summary>
/// Verifies that two doubles are equal within a tolerance range.
/// </summary>
/// <param name="expected">The expected value</param>
/// <param name="actual">The value to compare against</param>
/// <param name="tolerance">The +/- value for where the expected and actual are considered to be equal</param>
public static void Equal(double expected, double actual, double tolerance)
{
var difference = Math.Abs(actual - expected);
if (difference > tolerance)
throw new EqualException(expected + " +/- " + tolerance, actual);
}
/// <summary>
/// Verifies that two doubles are equal within a tolerance range.
/// </summary>
/// <param name="expected">The expected value</param>
/// <param name="actual">The value to compare against</param>
/// <param name="tolerance">The +/- value for where the expected and actual are considered to be equal</param>
/// <param name="userMessage">The user message to be shown on failure</param>
public static void Equal(double expected, double actual, double tolerance, string userMessage)
{
var difference = Math.Abs(actual - expected);
if (difference > tolerance)
throw new EqualException(expected + " +/- " + tolerance, actual, userMessage);
}
/// <summary>
/// Verifies that two values are not equal, using a default comparer.
/// </summary>
/// <param name="expected">The expected value</param>
/// <param name="actual">The actual value</param>
/// <param name="tolerance">The +/- value for where the expected and actual are considered to be equal</param>
/// <exception cref="NotEqualException">Thrown when the objects are equal</exception>
public static void NotEqual(double expected, double actual, double tolerance)
{
var difference = Math.Abs(actual - expected);
if (difference <= tolerance)
throw new NotEqualException(expected + " +/- " + tolerance, actual);
}
/// <summary>
/// Verifies that two values are not equal, using a default comparer.
/// </summary>
/// <param name="expected">The expected value</param>
/// <param name="actual">The actual value</param>
/// <param name="tolerance">The +/- value for where the expected and actual are considered to be equal</param>
/// <param name="userMessage">The user message to be shown on failure</param>
/// <exception cref="NotEqualException">Thrown when the objects are equal</exception>
public static void NotEqual(double expected, double actual, double tolerance, string userMessage)
{
var difference = Math.Abs(actual - expected);
if (difference <= tolerance)
throw new NotEqualException(expected + " +/- " + tolerance, actual, userMessage);
}
/// <summary>
/// Verifies that two dates are equal within a tolerance range.
/// </summary>
/// <param name="expected">The expected value</param>
/// <param name="actual">The value to compare against</param>
/// <param name="tolerance">The +/- value for where the expected and actual are considered to be equal</param>
public static void Equal(DateTime expected, DateTime actual, TimeSpan tolerance)
{
var difference = Math.Abs((actual - expected).Ticks);
if (difference > tolerance.Ticks)
throw new EqualException(expected + " +/- " + tolerance, actual);
}
/// <summary>
/// Verifies that two dates are not equal within a tolerance range.
/// </summary>
/// <param name="expected">The expected value</param>
/// <param name="actual">The value to compare against</param>
/// <param name="tolerance">The +/- value for where the expected and actual are considered to be equal</param>
public static void NotEqual(DateTime expected, DateTime actual, TimeSpan tolerance)
{
var difference = Math.Abs((actual - expected).Ticks);
if (difference <= tolerance.Ticks)
throw new NotEqualException(expected + " +/- " + tolerance, actual);
}
/// <summary>
/// Verifies that two dates are equal within a tolerance range.
/// </summary>
/// <param name="expected">The expected value</param>
/// <param name="actual">The value to compare against</param>
/// <param name="precision">The level of precision to use when making the comparison</param>
public static void Equal(DateTime expected, DateTime actual, DatePrecision precision)
{
if (precision.Truncate(expected) != precision.Truncate(actual))
throw new EqualException(precision.Truncate(actual), precision.Truncate(actual));
}
/// <summary>
/// Verifies that two doubles are not equal within a tolerance range.
/// </summary>
/// <param name="expected">The expected value</param>
/// <param name="actual">The value to compare against</param>
/// <param name="precision">The level of precision to use when making the comparison</param>
public static void NotEqual(DateTime expected, DateTime actual, DatePrecision precision)
{
if (precision.Truncate(expected) == precision.Truncate(actual))
throw new NotEqualException(precision.Truncate(actual), precision.Truncate(actual));
}
/// <summary>Do not call this method.</summary>
[Obsolete("This is an override of Object.Equals(). Call Assert.Equal() instead.", true)]
public new static bool Equals(object a,
object b)
{
throw new InvalidOperationException("Assert.Equals should not be used");
}
/// <summary>
/// Verifies that the condition is false.
/// </summary>
/// <param name="condition">The condition to be tested</param>
/// <exception cref="FalseException">Thrown if the condition is not false</exception>
public static void False(bool condition)
{
False(condition, null);
}
/// <summary>
/// Verifies that the condition is false.
/// </summary>
/// <param name="condition">The condition to be tested</param>
/// <param name="userMessage">The message to show when the condition is not false</param>
/// <exception cref="FalseException">Thrown if the condition is not false</exception>
public static void False(bool condition,
string userMessage)
{
if (condition)
throw new FalseException(userMessage);
}
static IEqualityComparer<T> GetEqualityComparer<T>()
{
return new AssertEqualityComparer<T>();
}
static IComparer<T> GetComparer<T>()
{
return new AssertComparer<T>();
}
/// <summary>Verifies that an object is greater than the exclusive minimum value.</summary>
/// <typeparam name="T">The type of the objects to be compared.</typeparam>
/// <param name="left">The object to be evaluated.</param>
/// <param name="right">An object representing the exclusive minimum value of paramref name="value"/>.</param>
public static void GreaterThan<T>(T left, T right)
{
GreaterThan(left, right, GetComparer<T>());
}
/// <summary>Verifies that an object is greater than the exclusive minimum value.</summary>
/// <typeparam name="T">The type of the objects to be compared.</typeparam>
/// <param name="left">The object to be evaluated.</param>
/// <param name="right">An object representing the exclusive minimum value of paramref name="value"/>.</param>
/// <param name="comparer">An <see cref="IComparer{T}"/> used to compare the objects.</param>
public static void GreaterThan<T>(T left, T right, IComparer<T> comparer)
{
if (comparer.Compare(left, right) <= 0)
throw new GreaterThanException(left, right);
}
/// <summary>Verifies that an object is greater than the inclusive minimum value.</summary>
/// <typeparam name="T">The type of the objects to be compared.</typeparam>
/// <param name="left">The object to be evaluated.</param>
/// <param name="right">An object representing the inclusive minimum value of paramref name="value"/>.</param>
public static void GreaterThanOrEqual<T>(T left, T right)
{
GreaterThanOrEqual(left, right, GetComparer<T>());
}
/// <summary>Verifies that an object is greater than the inclusive minimum value.</summary>
/// <typeparam name="T">The type of the objects to be compared.</typeparam>
/// <param name="left">The object to be evaluated.</param>
/// <param name="right">An object representing the inclusive minimum value of paramref name="value"/>.</param>
/// <param name="comparer">An <see cref="IComparer{T}"/> used to compare the objects.</param>
public static void GreaterThanOrEqual<T>(T left, T right, IComparer<T> comparer)
{
if (comparer.Compare(left, right) < 0)
throw new GreaterThanOrEqualException(left, right);
}
/// <summary>
/// Verifies that a value is within a given range.
/// </summary>
/// <typeparam name="T">The type of the value to be compared</typeparam>
/// <param name="actual">The actual value to be evaluated</param>
/// <param name="low">The (inclusive) low value of the range</param>
/// <param name="high">The (inclusive) high value of the range</param>
/// <exception cref="InRangeException">Thrown when the value is not in the given range</exception>
public static void InRange<T>(T actual,
T low,
T high)
{
InRange(actual, low, high, GetComparer<T>());
}
/// <summary>
/// Verifies that a value is within a given range, using a comparer.
/// </summary>
/// <typeparam name="T">The type of the value to be compared</typeparam>
/// <param name="actual">The actual value to be evaluated</param>
/// <param name="low">The (inclusive) low value of the range</param>
/// <param name="high">The (inclusive) high value of the range</param>
/// <param name="comparer">The comparer used to evaluate the value's range</param>
/// <exception cref="InRangeException">Thrown when the value is not in the given range</exception>
public static void InRange<T>(T actual,
T low,
T high,
IComparer<T> comparer)
{
if (comparer.Compare(low, actual) > 0 || comparer.Compare(actual, high) > 0)
throw new InRangeException(actual, low, high);
}
/// <summary>
/// Verifies that an object is of the given type or a derived type.
/// </summary>
/// <typeparam name="T">The type the object should be</typeparam>
/// <param name="object">The object to be evaluated</param>
/// <returns>The object, casted to type T when successful</returns>
/// <exception cref="IsAssignableFromException">Thrown when the object is not the given type</exception>
public static T IsAssignableFrom<T>(object @object)
{
IsAssignableFrom(typeof(T), @object);
return (T)@object;
}
/// <summary>
/// Verifies that an object is of the given type or a derived type.
/// </summary>
/// <param name="expectedType">The type the object should be</param>
/// <param name="object">The object to be evaluated</param>
/// <exception cref="IsAssignableFromException">Thrown when the object is not the given type</exception>
public static void IsAssignableFrom(Type expectedType, object @object)
{
if (@object == null || !expectedType.IsAssignableFrom(@object.GetType()))
throw new IsAssignableFromException(expectedType, @object);
}
/// <summary>
/// Verifies that an object is of the given type or a derived type.
/// </summary>
/// <typeparam name="T">The type the object should be</typeparam>
/// <param name="object">The object to be evaluated</param>
/// <param name="userMessage">The user message to show on failure</param>
/// <returns>The object, casted to type T when successful</returns>
/// <exception cref="IsAssignableFromException">Thrown when the object is not the given type</exception>
public static T IsAssignableFrom<T>(object @object, string userMessage)
{
IsAssignableFrom(typeof(T), @object, userMessage);
return (T)@object;
}
/// <summary>
/// Verifies that an object is of the given type or a derived type.
/// </summary>
/// <param name="expectedType">The type the object should be</param>
/// <param name="userMessage">The user message to show on failure</param>
/// <param name="object">The object to be evaluated</param>
/// <exception cref="IsAssignableFromException">Thrown when the object is not the given type</exception>
public static void IsAssignableFrom(Type expectedType, object @object, string userMessage)
{
if (@object == null || !expectedType.IsAssignableFrom(@object.GetType()))
throw new IsAssignableFromException(expectedType, @object, userMessage);
}
/// <summary>
/// Verifies that an object is not exactly the given type.
/// </summary>
/// <typeparam name="T">The type the object should not be</typeparam>
/// <param name="object">The object to be evaluated</param>
/// <exception cref="IsNotTypeException">Thrown when the object is the given type</exception>
public static void IsNotType<T>(object @object)
{
IsNotType(typeof(T), @object);
}
/// <summary>
/// Verifies that an object is not exactly the given type.
/// </summary>
/// <param name="expectedType">The type the object should not be</param>
/// <param name="object">The object to be evaluated</param>
/// <exception cref="IsNotTypeException">Thrown when the object is the given type</exception>
public static void IsNotType(Type expectedType,
object @object)
{
if (expectedType.Equals(@object.GetType()))
throw new IsNotTypeException(expectedType, @object);
}
/// <summary>
/// Verifies that an object is exactly the given type (and not a derived type).
/// </summary>
/// <typeparam name="T">The type the object should be</typeparam>
/// <param name="object">The object to be evaluated</param>
/// <returns>The object, casted to type T when successful</returns>
/// <exception cref="IsTypeException">Thrown when the object is not the given type</exception>
public static T IsType<T>(object @object)
{
IsType(typeof(T), @object);
return (T)@object;
}
/// <summary>
/// Verifies that an object is exactly the given type (and not a derived type).
/// </summary>
/// <param name="expectedType">The type the object should be</param>
/// <param name="object">The object to be evaluated</param>
/// <exception cref="IsTypeException">Thrown when the object is not the given type</exception>
public static void IsType(Type expectedType,
object @object)
{
if (@object == null || !expectedType.Equals(@object.GetType()))
throw new IsTypeException(expectedType, @object);
}
/// <summary>Verifies that an object is less than the exclusive maximum value.</summary>
/// <typeparam name="T">The type of the objects to be compared.</typeparam>
/// <param name="left">The object to be evaluated.</param>
/// <param name="right">An object representing the exclusive maximum value of paramref name="value"/>.</param>
public static void LessThan<T>(T left, T right)
{
LessThan(left, right, GetComparer<T>());
}
/// <summary>Verifies that an object is less than the exclusive maximum value.</summary>
/// <typeparam name="T">The type of the objects to be compared.</typeparam>
/// <param name="left">The object to be evaluated.</param>
/// <param name="right">An object representing the exclusive maximum value of paramref name="value"/>.</param>
/// <param name="comparer">An <see cref="IComparer{T}"/> used to compare the objects.</param>
public static void LessThan<T>(T left, T right, IComparer<T> comparer)
{
if (comparer.Compare(left, right) >= 0)
throw new LessThanException(left, right);
}
/// <summary>Verifies that an object is less than the inclusive maximum value.</summary>
/// <typeparam name="T">The type of the objects to be compared.</typeparam>
/// <param name="left">The object to be evaluated.</param>
/// <param name="right">An object representing the inclusive maximum value of paramref name="value"/>.</param>
public static void LessThanOrEqual<T>(T left, T right)
{
LessThanOrEqual(left, right, GetComparer<T>());
}
/// <summary>Verifies that an object is less than the inclusive maximum value.</summary>
/// <typeparam name="T">The type of the objects to be compared.</typeparam>
/// <param name="left">The object to be evaluated.</param>
/// <param name="right">An object representing the inclusive maximum value of paramref name="value"/>.</param>
/// <param name="comparer">An <see cref="IComparer{T}"/> used to compare the objects.</param>
public static void LessThanOrEqual<T>(T left, T right, IComparer<T> comparer)
{
if (comparer.Compare(left, right) > 0)
throw new LessThanOrEqualException(left, right);
}
/// <summary>
/// Verifies that a collection is not empty.
/// </summary>
/// <param name="collection">The collection to be inspected</param>
/// <exception cref="ArgumentNullException">Thrown when a null collection is passed</exception>
/// <exception cref="NotEmptyException">Thrown when the collection is empty</exception>
public static void NotEmpty(IEnumerable collection)
{
if (collection == null) throw new ArgumentNullException("collection", "cannot be null");
#pragma warning disable 168
foreach (object @object in collection)
return;
#pragma warning restore 168
throw new NotEmptyException();
}
/// <summary>
/// Verifies that two objects are not equal, using a default comparer.
/// </summary>
/// <typeparam name="T">The type of the objects to be compared</typeparam>
/// <param name="expected">The expected object</param>
/// <param name="actual">The actual object</param>
/// <exception cref="NotEqualException">Thrown when the objects are equal</exception>
public static void NotEqual<T>(T expected,
T actual)
{
NotEqual(expected, actual, GetEqualityComparer<T>());
}
/// <summary>
/// Verifies that two objects are not equal, using a custom comparer.
/// </summary>
/// <typeparam name="T">The type of the objects to be compared</typeparam>
/// <param name="expected">The expected object</param>
/// <param name="actual">The actual object</param>
/// <param name="comparer">The comparer used to examine the objects</param>
/// <exception cref="NotEqualException">Thrown when the objects are equal</exception>
public static void NotEqual<T>(T expected,
T actual,
IEqualityComparer<T> comparer)
{
if (comparer.Equals(expected, actual))
throw new NotEqualException(expected, actual);
}
/// <summary>
/// Verifies that a value is not within a given range, using the default comparer.
/// </summary>
/// <typeparam name="T">The type of the value to be compared</typeparam>
/// <param name="actual">The actual value to be evaluated</param>
/// <param name="low">The (inclusive) low value of the range</param>
/// <param name="high">The (inclusive) high value of the range</param>
/// <exception cref="NotInRangeException">Thrown when the value is in the given range</exception>
public static void NotInRange<T>(T actual,
T low,
T high)
{
NotInRange(actual, low, high, GetComparer<T>());
}
/// <summary>
/// Verifies that a value is not within a given range, using a comparer.
/// </summary>
/// <typeparam name="T">The type of the value to be compared</typeparam>
/// <param name="actual">The actual value to be evaluated</param>
/// <param name="low">The (inclusive) low value of the range</param>
/// <param name="high">The (inclusive) high value of the range</param>
/// <param name="comparer">The comparer used to evaluate the value's range</param>
/// <exception cref="NotInRangeException">Thrown when the value is in the given range</exception>
public static void NotInRange<T>(T actual,
T low,
T high,
IComparer<T> comparer)
{
if (comparer.Compare(low, actual) <= 0 && comparer.Compare(actual, high) <= 0)
throw new NotInRangeException(actual, low, high);
}
/// <summary>
/// Verifies that an object reference is not null.
/// </summary>
/// <param name="object">The object to be validated</param>
/// <exception cref="NotNullException">Thrown when the object is not null</exception>
public static void NotNull(object @object)
{
if (@object == null)
throw new NotNullException();
}
/// <summary>
/// Verifies that an object reference is not null.
/// </summary>
/// <param name="object">The object to be validated</param>
/// <exception cref="NotNullException">Thrown when the object is not null</exception>
public static void NotNull(object @object, string message)
{
if (@object == null)
throw new NotNullException(message);
}
/// <summary>
/// Verifies that two objects are not the same instance.
/// </summary>
/// <param name="expected">The expected object instance</param>
/// <param name="actual">The actual object instance</param>
/// <exception cref="NotSameException">Thrown when the objects are the same instance</exception>
public static void NotSame(object expected,
object actual)
{
if (object.ReferenceEquals(expected, actual))
throw new NotSameException();
}
/// <summary>
/// Verifies that an object reference is null.
/// </summary>
/// <param name="object">The object to be inspected</param>
/// <exception cref="NullException">Thrown when the object reference is not null</exception>
public static void Null(object @object)
{
if (@object != null)
throw new NullException(@object);
}
/// <summary>
/// Verifies that two objects are the same instance.
/// </summary>
/// <param name="expected">The expected object instance</param>
/// <param name="actual">The actual object instance</param>
/// <exception cref="SameException">Thrown when the objects are not the same instance</exception>
public static void Same(object expected,
object actual)
{
if (!object.ReferenceEquals(expected, actual))
throw new SameException(expected, actual);
}
/// <summary>
/// Verifies that the given collection contains only a single
/// element of the given type.
/// </summary>
/// <param name="collection">The collection.</param>
/// <returns>The single item in the collection.</returns>
/// <exception cref="SingleException">Thrown when the collection does not contain
/// exactly one element.</exception>
public static object Single(IEnumerable collection)
{
if (collection == null)
throw new ArgumentNullException("collection");
int count = 0;
object result = null;
foreach (object item in collection)
{
result = item;
++count;
}
if (count != 1)
throw new SingleException(count);
return result;
}
/// <summary>
/// Verifies that the given collection contains only a single
/// element of the given type.
/// </summary>
/// <typeparam name="T">The collection type.</typeparam>
/// <param name="collection">The collection.</param>
/// <returns>The single item in the collection.</returns>
/// <exception cref="SingleException">Thrown when the collection does not contain
/// exactly one element.</exception>
public static T Single<T>(IEnumerable<T> collection)
{
if (collection == null)
throw new ArgumentNullException("collection");
int count = 0;
T result = default(T);
foreach (T item in collection)
{
result = item;
++count;
}
if (count != 1)
throw new SingleException(count);
return result;
}
/// <summary>
/// Verifies that the exact exception is thrown (and not a derived exception type).
/// </summary>
/// <typeparam name="T">The type of the exception expected to be thrown</typeparam>
/// <param name="testCode">A delegate to the code to be tested</param>
/// <returns>The exception that was thrown, when successful</returns>
/// <exception cref="ThrowsException">Thrown when an exception was not thrown, or when an exception of the incorrect type is thrown</exception>
public static T Throws<T>(ThrowsDelegate testCode)
where T : Exception
{
return (T)Throws(typeof(T), testCode);
}
/// <summary>
/// Verifies that the exact exception is thrown (and not a derived exception type).
/// </summary>
/// <typeparam name="T">The type of the exception expected to be thrown</typeparam>
/// <param name="userMessage">The message to be shown if the test fails</param>
/// <param name="testCode">A delegate to the code to be tested</param>
/// <returns>The exception that was thrown, when successful</returns>
/// <exception cref="ThrowsException">Thrown when an exception was not thrown, or when an exception of the incorrect type is thrown</exception>
public static T Throws<T>(string userMessage,
ThrowsDelegate testCode)
where T : Exception
{
return (T)Throws(typeof(T), testCode);
}
/// <summary>
/// Verifies that the exact exception is thrown (and not a derived exception type).
/// Generally used to test property accessors.
/// </summary>
/// <typeparam name="T">The type of the exception expected to be thrown</typeparam>
/// <param name="testCode">A delegate to the code to be tested</param>
/// <returns>The exception that was thrown, when successful</returns>
/// <exception cref="ThrowsException">Thrown when an exception was not thrown, or when an exception of the incorrect type is thrown</exception>
public static T Throws<T>(ThrowsDelegateWithReturn testCode)
where T : Exception
{
return (T)Throws(typeof(T), testCode);
}
/// <summary>
/// Verifies that the exact exception is thrown (and not a derived exception type).
/// Generally used to test property accessors.
/// </summary>
/// <typeparam name="T">The type of the exception expected to be thrown</typeparam>
/// <param name="userMessage">The message to be shown if the test fails</param>
/// <param name="testCode">A delegate to the code to be tested</param>
/// <returns>The exception that was thrown, when successful</returns>
/// <exception cref="ThrowsException">Thrown when an exception was not thrown, or when an exception of the incorrect type is thrown</exception>
public static T Throws<T>(string userMessage,
ThrowsDelegateWithReturn testCode)
where T : Exception
{
return (T)Throws(typeof(T), testCode);
}
/// <summary>
/// Verifies that the exact exception is thrown (and not a derived exception type).
/// </summary>
/// <param name="exceptionType">The type of the exception expected to be thrown</param>
/// <param name="testCode">A delegate to the code to be tested</param>
/// <returns>The exception that was thrown, when successful</returns>
/// <exception cref="ThrowsException">Thrown when an exception was not thrown, or when an exception of the incorrect type is thrown</exception>
public static Exception Throws(Type exceptionType,
ThrowsDelegate testCode)
{
Exception exception = Record.Exception(testCode);
if (exception == null)
throw new ThrowsException(exceptionType);
if (!exceptionType.Equals(exception.GetType()))
throw new ThrowsException(exceptionType, exception);
return exception;
}
/// <summary>
/// Verifies that the exact exception is thrown (and not a derived exception type).
/// Generally used to test property accessors.
/// </summary>
/// <param name="exceptionType">The type of the exception expected to be thrown</param>
/// <param name="testCode">A delegate to the code to be tested</param>
/// <returns>The exception that was thrown, when successful</returns>
/// <exception cref="ThrowsException">Thrown when an exception was not thrown, or when an exception of the incorrect type is thrown</exception>
public static Exception Throws(Type exceptionType,
ThrowsDelegateWithReturn testCode)
{
Exception exception = Record.Exception(testCode);
if (exception == null)
throw new ThrowsException(exceptionType);
if (!exceptionType.Equals(exception.GetType()))
throw new ThrowsException(exceptionType, exception);
return exception;
}
/// <summary>
/// Verifies that a block of code does not throw any exceptions.
/// </summary>
/// <param name="testCode">A delegate to the code to be tested</param>
public static void DoesNotThrow(ThrowsDelegate testCode)
{
Exception ex = Record.Exception(testCode);
if (ex != null)
throw new DoesNotThrowException(ex);
}
/// <summary>
/// Verifies that an expression is true.
/// </summary>
/// <param name="condition">The condition to be inspected</param>
/// <exception cref="TrueException">Thrown when the condition is false</exception>
public static void True(bool condition)
{
True(condition, null);
}
/// <summary>
/// Verifies that an expression is true.
/// </summary>
/// <param name="condition">The condition to be inspected</param>
/// <param name="userMessage">The message to be shown when the condition is false</param>
/// <exception cref="TrueException">Thrown when the condition is false</exception>
public static void True(bool condition,
string userMessage)
{
if (!condition)
throw new TrueException(userMessage);
}
}
}
| |
// 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 gcsv = Google.Cloud.SecurityCenter.V1;
using sys = System;
namespace Google.Cloud.SecurityCenter.V1
{
/// <summary>Resource name for the <c>Asset</c> resource.</summary>
public sealed partial class AssetName : gax::IResourceName, sys::IEquatable<AssetName>
{
/// <summary>The possible contents of <see cref="AssetName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>A resource name with pattern <c>organizations/{organization}/assets/{asset}</c>.</summary>
OrganizationAsset = 1,
/// <summary>A resource name with pattern <c>folders/{folder}/assets/{asset}</c>.</summary>
FolderAsset = 2,
/// <summary>A resource name with pattern <c>projects/{project}/assets/{asset}</c>.</summary>
ProjectAsset = 3,
}
private static gax::PathTemplate s_organizationAsset = new gax::PathTemplate("organizations/{organization}/assets/{asset}");
private static gax::PathTemplate s_folderAsset = new gax::PathTemplate("folders/{folder}/assets/{asset}");
private static gax::PathTemplate s_projectAsset = new gax::PathTemplate("projects/{project}/assets/{asset}");
/// <summary>Creates a <see cref="AssetName"/> 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="AssetName"/> containing the provided <paramref name="unparsedResourceName"/>.
/// </returns>
public static AssetName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new AssetName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="AssetName"/> with the pattern <c>organizations/{organization}/assets/{asset}</c>.
/// </summary>
/// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="assetId">The <c>Asset</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="AssetName"/> constructed from the provided ids.</returns>
public static AssetName FromOrganizationAsset(string organizationId, string assetId) =>
new AssetName(ResourceNameType.OrganizationAsset, organizationId: gax::GaxPreconditions.CheckNotNullOrEmpty(organizationId, nameof(organizationId)), assetId: gax::GaxPreconditions.CheckNotNullOrEmpty(assetId, nameof(assetId)));
/// <summary>
/// Creates a <see cref="AssetName"/> with the pattern <c>folders/{folder}/assets/{asset}</c>.
/// </summary>
/// <param name="folderId">The <c>Folder</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="assetId">The <c>Asset</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="AssetName"/> constructed from the provided ids.</returns>
public static AssetName FromFolderAsset(string folderId, string assetId) =>
new AssetName(ResourceNameType.FolderAsset, folderId: gax::GaxPreconditions.CheckNotNullOrEmpty(folderId, nameof(folderId)), assetId: gax::GaxPreconditions.CheckNotNullOrEmpty(assetId, nameof(assetId)));
/// <summary>
/// Creates a <see cref="AssetName"/> with the pattern <c>projects/{project}/assets/{asset}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="assetId">The <c>Asset</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="AssetName"/> constructed from the provided ids.</returns>
public static AssetName FromProjectAsset(string projectId, string assetId) =>
new AssetName(ResourceNameType.ProjectAsset, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), assetId: gax::GaxPreconditions.CheckNotNullOrEmpty(assetId, nameof(assetId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="AssetName"/> with pattern
/// <c>organizations/{organization}/assets/{asset}</c>.
/// </summary>
/// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="assetId">The <c>Asset</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="AssetName"/> with pattern
/// <c>organizations/{organization}/assets/{asset}</c>.
/// </returns>
public static string Format(string organizationId, string assetId) => FormatOrganizationAsset(organizationId, assetId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="AssetName"/> with pattern
/// <c>organizations/{organization}/assets/{asset}</c>.
/// </summary>
/// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="assetId">The <c>Asset</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="AssetName"/> with pattern
/// <c>organizations/{organization}/assets/{asset}</c>.
/// </returns>
public static string FormatOrganizationAsset(string organizationId, string assetId) =>
s_organizationAsset.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(organizationId, nameof(organizationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(assetId, nameof(assetId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="AssetName"/> with pattern
/// <c>folders/{folder}/assets/{asset}</c>.
/// </summary>
/// <param name="folderId">The <c>Folder</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="assetId">The <c>Asset</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="AssetName"/> with pattern <c>folders/{folder}/assets/{asset}</c>
/// .
/// </returns>
public static string FormatFolderAsset(string folderId, string assetId) =>
s_folderAsset.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(folderId, nameof(folderId)), gax::GaxPreconditions.CheckNotNullOrEmpty(assetId, nameof(assetId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="AssetName"/> with pattern
/// <c>projects/{project}/assets/{asset}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="assetId">The <c>Asset</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="AssetName"/> with pattern <c>projects/{project}/assets/{asset}</c>
/// .
/// </returns>
public static string FormatProjectAsset(string projectId, string assetId) =>
s_projectAsset.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(assetId, nameof(assetId)));
/// <summary>Parses the given resource name string into a new <see cref="AssetName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>organizations/{organization}/assets/{asset}</c></description></item>
/// <item><description><c>folders/{folder}/assets/{asset}</c></description></item>
/// <item><description><c>projects/{project}/assets/{asset}</c></description></item>
/// </list>
/// </remarks>
/// <param name="assetName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="AssetName"/> if successful.</returns>
public static AssetName Parse(string assetName) => Parse(assetName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="AssetName"/> 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>organizations/{organization}/assets/{asset}</c></description></item>
/// <item><description><c>folders/{folder}/assets/{asset}</c></description></item>
/// <item><description><c>projects/{project}/assets/{asset}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="assetName">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="AssetName"/> if successful.</returns>
public static AssetName Parse(string assetName, bool allowUnparsed) =>
TryParse(assetName, allowUnparsed, out AssetName 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="AssetName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>organizations/{organization}/assets/{asset}</c></description></item>
/// <item><description><c>folders/{folder}/assets/{asset}</c></description></item>
/// <item><description><c>projects/{project}/assets/{asset}</c></description></item>
/// </list>
/// </remarks>
/// <param name="assetName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="AssetName"/>, 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 assetName, out AssetName result) => TryParse(assetName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="AssetName"/> 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>organizations/{organization}/assets/{asset}</c></description></item>
/// <item><description><c>folders/{folder}/assets/{asset}</c></description></item>
/// <item><description><c>projects/{project}/assets/{asset}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="assetName">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="AssetName"/>, 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 assetName, bool allowUnparsed, out AssetName result)
{
gax::GaxPreconditions.CheckNotNull(assetName, nameof(assetName));
gax::TemplatedResourceName resourceName;
if (s_organizationAsset.TryParseName(assetName, out resourceName))
{
result = FromOrganizationAsset(resourceName[0], resourceName[1]);
return true;
}
if (s_folderAsset.TryParseName(assetName, out resourceName))
{
result = FromFolderAsset(resourceName[0], resourceName[1]);
return true;
}
if (s_projectAsset.TryParseName(assetName, out resourceName))
{
result = FromProjectAsset(resourceName[0], resourceName[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(assetName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private AssetName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string assetId = null, string folderId = null, string organizationId = null, string projectId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
AssetId = assetId;
FolderId = folderId;
OrganizationId = organizationId;
ProjectId = projectId;
}
/// <summary>
/// Constructs a new instance of a <see cref="AssetName"/> class from the component parts of pattern
/// <c>organizations/{organization}/assets/{asset}</c>
/// </summary>
/// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="assetId">The <c>Asset</c> ID. Must not be <c>null</c> or empty.</param>
public AssetName(string organizationId, string assetId) : this(ResourceNameType.OrganizationAsset, organizationId: gax::GaxPreconditions.CheckNotNullOrEmpty(organizationId, nameof(organizationId)), assetId: gax::GaxPreconditions.CheckNotNullOrEmpty(assetId, nameof(assetId)))
{
}
/// <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>Asset</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance.
/// </summary>
public string AssetId { get; }
/// <summary>
/// The <c>Folder</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance.
/// </summary>
public string FolderId { get; }
/// <summary>
/// The <c>Organization</c> ID. May be <c>null</c>, depending on which resource name is contained by this
/// instance.
/// </summary>
public string OrganizationId { get; }
/// <summary>
/// The <c>Project</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance.
/// </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.OrganizationAsset: return s_organizationAsset.Expand(OrganizationId, AssetId);
case ResourceNameType.FolderAsset: return s_folderAsset.Expand(FolderId, AssetId);
case ResourceNameType.ProjectAsset: return s_projectAsset.Expand(ProjectId, AssetId);
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 AssetName);
/// <inheritdoc/>
public bool Equals(AssetName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(AssetName a, AssetName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(AssetName a, AssetName b) => !(a == b);
}
public partial class Asset
{
/// <summary>
/// <see cref="gcsv::AssetName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcsv::AssetName AssetName
{
get => string.IsNullOrEmpty(Name) ? null : gcsv::AssetName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
| |
// Copyright 2017, Google LLC 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.
// Generated code. DO NOT EDIT!
using Google.Api.Gax;
using Google.Api.Gax.Grpc;
using Google.LongRunning;
using Google.Protobuf;
using Google.Protobuf.WellKnownTypes;
using Grpc.Core;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace Google.LongRunning.Snippets
{
/// <summary>Generated snippets</summary>
public class GeneratedOperationsClientSnippets
{
/// <summary>Snippet for GetOperationAsync</summary>
public async Task GetOperationAsync()
{
// Snippet: GetOperationAsync(string,CallSettings)
// Additional: GetOperationAsync(string,CancellationToken)
// Create client
OperationsClient operationsClient = await OperationsClient.CreateAsync();
// Initialize request argument(s)
string name = "";
// Make the request
Operation response = await operationsClient.GetOperationAsync(name);
// End snippet
}
/// <summary>Snippet for GetOperation</summary>
public void GetOperation()
{
// Snippet: GetOperation(string,CallSettings)
// Create client
OperationsClient operationsClient = OperationsClient.Create();
// Initialize request argument(s)
string name = "";
// Make the request
Operation response = operationsClient.GetOperation(name);
// End snippet
}
/// <summary>Snippet for GetOperationAsync</summary>
public async Task GetOperationAsync_RequestObject()
{
// Snippet: GetOperationAsync(GetOperationRequest,CallSettings)
// Create client
OperationsClient operationsClient = await OperationsClient.CreateAsync();
// Initialize request argument(s)
GetOperationRequest request = new GetOperationRequest
{
Name = "",
};
// Make the request
Operation response = await operationsClient.GetOperationAsync(request);
// End snippet
}
/// <summary>Snippet for GetOperation</summary>
public void GetOperation_RequestObject()
{
// Snippet: GetOperation(GetOperationRequest,CallSettings)
// Create client
OperationsClient operationsClient = OperationsClient.Create();
// Initialize request argument(s)
GetOperationRequest request = new GetOperationRequest
{
Name = "",
};
// Make the request
Operation response = operationsClient.GetOperation(request);
// End snippet
}
/// <summary>Snippet for ListOperationsAsync</summary>
public async Task ListOperationsAsync()
{
// Snippet: ListOperationsAsync(string,string,string,int?,CallSettings)
// Create client
OperationsClient operationsClient = await OperationsClient.CreateAsync();
// Initialize request argument(s)
string name = "";
string filter = "";
// Make the request
PagedAsyncEnumerable<ListOperationsResponse, Operation> response =
operationsClient.ListOperationsAsync(name, filter);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Operation item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListOperationsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Operation item in page)
{
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Operation> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Operation item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListOperations</summary>
public void ListOperations()
{
// Snippet: ListOperations(string,string,string,int?,CallSettings)
// Create client
OperationsClient operationsClient = OperationsClient.Create();
// Initialize request argument(s)
string name = "";
string filter = "";
// Make the request
PagedEnumerable<ListOperationsResponse, Operation> response =
operationsClient.ListOperations(name, filter);
// Iterate over all response items, lazily performing RPCs as required
foreach (Operation item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListOperationsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Operation item in page)
{
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Operation> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Operation item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListOperationsAsync</summary>
public async Task ListOperationsAsync_RequestObject()
{
// Snippet: ListOperationsAsync(ListOperationsRequest,CallSettings)
// Create client
OperationsClient operationsClient = await OperationsClient.CreateAsync();
// Initialize request argument(s)
ListOperationsRequest request = new ListOperationsRequest
{
Name = "",
Filter = "",
};
// Make the request
PagedAsyncEnumerable<ListOperationsResponse, Operation> response =
operationsClient.ListOperationsAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Operation item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListOperationsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Operation item in page)
{
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Operation> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Operation item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListOperations</summary>
public void ListOperations_RequestObject()
{
// Snippet: ListOperations(ListOperationsRequest,CallSettings)
// Create client
OperationsClient operationsClient = OperationsClient.Create();
// Initialize request argument(s)
ListOperationsRequest request = new ListOperationsRequest
{
Name = "",
Filter = "",
};
// Make the request
PagedEnumerable<ListOperationsResponse, Operation> response =
operationsClient.ListOperations(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (Operation item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListOperationsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Operation item in page)
{
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Operation> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Operation item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for CancelOperationAsync</summary>
public async Task CancelOperationAsync()
{
// Snippet: CancelOperationAsync(string,CallSettings)
// Additional: CancelOperationAsync(string,CancellationToken)
// Create client
OperationsClient operationsClient = await OperationsClient.CreateAsync();
// Initialize request argument(s)
string name = "";
// Make the request
await operationsClient.CancelOperationAsync(name);
// End snippet
}
/// <summary>Snippet for CancelOperation</summary>
public void CancelOperation()
{
// Snippet: CancelOperation(string,CallSettings)
// Create client
OperationsClient operationsClient = OperationsClient.Create();
// Initialize request argument(s)
string name = "";
// Make the request
operationsClient.CancelOperation(name);
// End snippet
}
/// <summary>Snippet for CancelOperationAsync</summary>
public async Task CancelOperationAsync_RequestObject()
{
// Snippet: CancelOperationAsync(CancelOperationRequest,CallSettings)
// Create client
OperationsClient operationsClient = await OperationsClient.CreateAsync();
// Initialize request argument(s)
CancelOperationRequest request = new CancelOperationRequest
{
Name = "",
};
// Make the request
await operationsClient.CancelOperationAsync(request);
// End snippet
}
/// <summary>Snippet for CancelOperation</summary>
public void CancelOperation_RequestObject()
{
// Snippet: CancelOperation(CancelOperationRequest,CallSettings)
// Create client
OperationsClient operationsClient = OperationsClient.Create();
// Initialize request argument(s)
CancelOperationRequest request = new CancelOperationRequest
{
Name = "",
};
// Make the request
operationsClient.CancelOperation(request);
// End snippet
}
/// <summary>Snippet for DeleteOperationAsync</summary>
public async Task DeleteOperationAsync()
{
// Snippet: DeleteOperationAsync(string,CallSettings)
// Additional: DeleteOperationAsync(string,CancellationToken)
// Create client
OperationsClient operationsClient = await OperationsClient.CreateAsync();
// Initialize request argument(s)
string name = "";
// Make the request
await operationsClient.DeleteOperationAsync(name);
// End snippet
}
/// <summary>Snippet for DeleteOperation</summary>
public void DeleteOperation()
{
// Snippet: DeleteOperation(string,CallSettings)
// Create client
OperationsClient operationsClient = OperationsClient.Create();
// Initialize request argument(s)
string name = "";
// Make the request
operationsClient.DeleteOperation(name);
// End snippet
}
/// <summary>Snippet for DeleteOperationAsync</summary>
public async Task DeleteOperationAsync_RequestObject()
{
// Snippet: DeleteOperationAsync(DeleteOperationRequest,CallSettings)
// Create client
OperationsClient operationsClient = await OperationsClient.CreateAsync();
// Initialize request argument(s)
DeleteOperationRequest request = new DeleteOperationRequest
{
Name = "",
};
// Make the request
await operationsClient.DeleteOperationAsync(request);
// End snippet
}
/// <summary>Snippet for DeleteOperation</summary>
public void DeleteOperation_RequestObject()
{
// Snippet: DeleteOperation(DeleteOperationRequest,CallSettings)
// Create client
OperationsClient operationsClient = OperationsClient.Create();
// Initialize request argument(s)
DeleteOperationRequest request = new DeleteOperationRequest
{
Name = "",
};
// Make the request
operationsClient.DeleteOperation(request);
// End snippet
}
}
}
| |
// 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.IConvertible.ToSingle(System.IFormatProvider)
/// </summary>
public class DoubleIConvertibleToSingle
{
#region Public Methods
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;
//
// TODO: Add your negative test cases here
//
// TestLibrary.TestFramework.LogInformation("[Negative]");
// retVal = NegTest1() && retVal;
return retVal;
}
#region Positive Test Cases
public bool PosTest1()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest1: Convert a random positive Double to single");
try
{
Single s = TestLibrary.Generator.GetSingle(-55);
Double i1 = (Double)s;
IConvertible Icon1 = (IConvertible)i1;
if (Icon1.ToSingle(null) != s)
{
TestLibrary.TestFramework.LogError("001.1", "The result is not the value as expected");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("001.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest2: Convert a random negtive Double to single");
try
{
Single s = -TestLibrary.Generator.GetSingle(-55);
Double i1 = (Double)s;
IConvertible Icon1 = (IConvertible)i1;
if (Icon1.ToSingle(null) != s)
{
TestLibrary.TestFramework.LogError("002.1", "The result is not the value as expected");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest4: Convert zero to single ");
try
{
Double i1 = 0;
IConvertible Icon1 = (IConvertible)i1;
if (Icon1.ToSingle(null) != 0)
{
TestLibrary.TestFramework.LogError("003.1", "The result is not zero as expected");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("003.2", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest4: Convert (double)Single.MaxValue to single.");
try
{
Double i1 = (Double)Single.MaxValue;
IConvertible Icon1 = (IConvertible)i1;
if (Icon1.ToSingle(null) != Single.MaxValue)
{
TestLibrary.TestFramework.LogError("004.1", "The result is not expected");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004.2", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest5()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest5: Convert (double)Single.MinValue to single.");
try
{
Double i1 = (Double)Single.MinValue;
IConvertible Icon1 = (IConvertible)i1;
if (Icon1.ToSingle(null) != Single.MinValue)
{
TestLibrary.TestFramework.LogError("005.1", "The result is not expected");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("005.2", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
#endregion
#region Nagetive Test Cases
//public bool NegTest1()
//{
// bool retVal = true;
// TestLibrary.TestFramework.BeginScenario("NegTest1: ");
// try
// {
// //
// // Add your test logic here
// //
// }
// catch (Exception e)
// {
// TestLibrary.TestFramework.LogError("101", "Unexpected exception: " + e);
// TestLibrary.TestFramework.LogInformation(e.StackTrace);
// retVal = false;
// }
// return retVal;
//}
#endregion
#endregion
public static int Main()
{
DoubleIConvertibleToSingle test = new DoubleIConvertibleToSingle();
TestLibrary.TestFramework.BeginTestCase("DoubleIConvertibleToSingle");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="XmlCharCheckingWriter.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
//------------------------------------------------------------------------------
using System;
using System.IO;
using System.Text;
using System.Xml.Schema;
using System.Collections;
using System.Diagnostics;
namespace System.Xml {
//
// XmlCharCheckingWriter
//
internal partial class XmlCharCheckingWriter : XmlWrappingWriter {
//
// Fields
//
bool checkValues;
bool checkNames;
bool replaceNewLines;
string newLineChars;
XmlCharType xmlCharType;
//
// Constructor
//
internal XmlCharCheckingWriter( XmlWriter baseWriter, bool checkValues, bool checkNames, bool replaceNewLines, string newLineChars )
: base( baseWriter ) {
Debug.Assert( checkValues || replaceNewLines );
this.checkValues = checkValues;
this.checkNames = checkNames;
this.replaceNewLines = replaceNewLines;
this.newLineChars = newLineChars;
if ( checkValues ) {
xmlCharType = XmlCharType.Instance;
}
}
//
// XmlWriter implementation
//
public override XmlWriterSettings Settings {
get {
XmlWriterSettings s = base.writer.Settings;
s = ( s != null) ? (XmlWriterSettings)s.Clone() : new XmlWriterSettings();
if ( checkValues ) {
s.CheckCharacters = true;
}
if ( replaceNewLines ) {
s.NewLineHandling = NewLineHandling.Replace;
s.NewLineChars = newLineChars;
}
s.ReadOnly = true;
return s;
}
}
public override void WriteDocType( string name, string pubid, string sysid, string subset ) {
if ( checkNames ) {
ValidateQName( name );
}
if ( checkValues ) {
if ( pubid != null ) {
int i;
if ( ( i = xmlCharType.IsPublicId( pubid ) ) >= 0 ) {
throw XmlConvert.CreateInvalidCharException( pubid, i );
}
}
if ( sysid != null ) {
CheckCharacters( sysid );
}
if ( subset != null ) {
CheckCharacters( subset );
}
}
if ( replaceNewLines ) {
sysid = ReplaceNewLines( sysid );
pubid = ReplaceNewLines( pubid );
subset = ReplaceNewLines( subset );
}
writer.WriteDocType( name, pubid, sysid, subset );
}
public override void WriteStartElement( string prefix, string localName, string ns ) {
if ( checkNames ) {
if ( localName == null || localName.Length == 0 ) {
throw new ArgumentException( Res.GetString( Res.Xml_EmptyLocalName ) );
}
ValidateNCName( localName );
if ( prefix != null && prefix.Length > 0 ) {
ValidateNCName( prefix );
}
}
writer.WriteStartElement( prefix, localName, ns );
}
public override void WriteStartAttribute( string prefix, string localName, string ns ) {
if ( checkNames ) {
if ( localName == null || localName.Length == 0 ) {
throw new ArgumentException( Res.GetString( Res.Xml_EmptyLocalName ) );
}
ValidateNCName( localName );
if ( prefix != null && prefix.Length > 0 ) {
ValidateNCName( prefix );
}
}
writer.WriteStartAttribute( prefix, localName, ns );
}
public override void WriteCData( string text ) {
if ( text != null ) {
if ( checkValues ) {
CheckCharacters( text );
}
if ( replaceNewLines ) {
text = ReplaceNewLines( text );
}
int i;
while ( ( i = text.IndexOf( "]]>", StringComparison.Ordinal ) ) >= 0 ) {
writer.WriteCData( text.Substring( 0, i + 2 ) );
text = text.Substring( i + 2 );
}
}
writer.WriteCData( text );
}
public override void WriteComment( string text ) {
if ( text != null ) {
if ( checkValues ) {
CheckCharacters( text );
text = InterleaveInvalidChars( text, '-', '-' );
}
if ( replaceNewLines ) {
text = ReplaceNewLines( text );
}
}
writer.WriteComment( text );
}
public override void WriteProcessingInstruction( string name, string text ) {
if ( checkNames ) {
ValidateNCName( name );
}
if ( text != null ) {
if ( checkValues ) {
CheckCharacters( text );
text = InterleaveInvalidChars( text, '?', '>' );
}
if ( replaceNewLines ) {
text = ReplaceNewLines( text );
}
}
writer.WriteProcessingInstruction( name, text );
}
public override void WriteEntityRef( string name ) {
if ( checkNames ) {
ValidateQName( name );
}
writer.WriteEntityRef( name );
}
public override void WriteWhitespace( string ws ) {
if ( ws == null ) {
ws = string.Empty;
}
// "checkNames" is intentional here; if false, the whitespaces are checked in XmlWellformedWriter
if ( checkNames ) {
int i;
if ( ( i = xmlCharType.IsOnlyWhitespaceWithPos( ws ) ) != -1 ) {
throw new ArgumentException( Res.GetString( Res.Xml_InvalidWhitespaceCharacter, XmlException.BuildCharExceptionArgs( ws, i ) ) );
}
}
if ( replaceNewLines ) {
ws = ReplaceNewLines( ws );
}
writer.WriteWhitespace( ws );
}
public override void WriteString( string text ) {
if ( text != null ) {
if ( checkValues ) {
CheckCharacters( text );
}
if ( replaceNewLines && WriteState != WriteState.Attribute ) {
text = ReplaceNewLines( text );
}
}
writer.WriteString( text );
}
public override void WriteSurrogateCharEntity( char lowChar, char highChar ) {
writer.WriteSurrogateCharEntity( lowChar, highChar );
}
public override void WriteChars( char[] buffer, int index, int count ) {
if (buffer == null) {
throw new ArgumentNullException("buffer");
}
if (index < 0) {
throw new ArgumentOutOfRangeException("index");
}
if (count < 0) {
throw new ArgumentOutOfRangeException("count");
}
if (count > buffer.Length - index) {
throw new ArgumentOutOfRangeException("count");
}
if (checkValues) {
CheckCharacters( buffer, index, count );
}
if ( replaceNewLines && WriteState != WriteState.Attribute ) {
string text = ReplaceNewLines( buffer, index, count );
if ( text != null ) {
WriteString( text );
return;
}
}
writer.WriteChars( buffer, index, count );
}
public override void WriteNmToken( string name ) {
if ( checkNames ) {
if ( name == null || name.Length == 0 ) {
throw new ArgumentException( Res.GetString( Res.Xml_EmptyName ) );
}
XmlConvert.VerifyNMTOKEN( name );
}
writer.WriteNmToken( name );
}
public override void WriteName( string name ) {
if ( checkNames ) {
XmlConvert.VerifyQName( name, ExceptionType.XmlException );
}
writer.WriteName( name );
}
public override void WriteQualifiedName( string localName, string ns ) {
if ( checkNames ) {
ValidateNCName( localName );
}
writer.WriteQualifiedName( localName, ns );
}
//
// Private methods
//
private void CheckCharacters( string str ) {
XmlConvert.VerifyCharData( str, ExceptionType.ArgumentException );
}
private void CheckCharacters( char[] data, int offset, int len ) {
XmlConvert.VerifyCharData( data, offset, len, ExceptionType.ArgumentException );
}
private void ValidateNCName( string ncname ) {
if ( ncname.Length == 0 ) {
throw new ArgumentException( Res.GetString( Res.Xml_EmptyName ) );
}
int len = ValidateNames.ParseNCName( ncname, 0 );
if ( len != ncname.Length ) {
throw new ArgumentException(Res.GetString(len == 0 ? Res.Xml_BadStartNameChar : Res.Xml_BadNameChar, XmlException.BuildCharExceptionArgs(ncname, len)));
}
}
private void ValidateQName( string name ) {
if ( name.Length == 0 ) {
throw new ArgumentException( Res.GetString( Res.Xml_EmptyName ) );
}
int colonPos;
int len = ValidateNames.ParseQName( name, 0, out colonPos );
if ( len != name.Length ) {
string res = ( len == 0 || ( colonPos > -1 && len == colonPos + 1 ) ) ? Res.Xml_BadStartNameChar : Res.Xml_BadNameChar;
throw new ArgumentException( Res.GetString( res, XmlException.BuildCharExceptionArgs( name, len ) ) );
}
}
private string ReplaceNewLines( string str ) {
if ( str == null ) {
return null;
}
StringBuilder sb = null;
int start = 0;
int i;
for ( i = 0; i < str.Length; i++ ) {
char ch;
if ( ( ch = str[i] ) >= 0x20 ) {
continue;
}
if ( ch == '\n' ) {
if ( newLineChars == "\n" ) {
continue;
}
if ( sb == null ) {
sb = new StringBuilder( str.Length + 5 );
}
sb.Append( str, start, i - start );
}
else if ( ch == '\r' ) {
if ( i + 1 < str.Length && str[i+1] == '\n' ) {
if ( newLineChars == "\r\n" ) {
i++;
continue;
}
if ( sb == null ) {
sb = new StringBuilder( str.Length + 5 );
}
sb.Append( str, start, i - start );
i++;
}
else {
if ( newLineChars == "\r" ) {
continue;
}
if ( sb == null ) {
sb = new StringBuilder( str.Length + 5 );
}
sb.Append( str, start, i - start );
}
}
else {
continue;
}
sb.Append( newLineChars );
start = i + 1;
}
if ( sb == null ) {
return str;
}
else {
sb.Append( str, start, i - start );
return sb.ToString();
}
}
private string ReplaceNewLines( char[] data, int offset, int len ) {
if ( data == null ) {
return null;
}
StringBuilder sb = null;
int start = offset;
int endPos = offset + len;
int i;
for ( i = offset; i < endPos; i++ ) {
char ch;
if ( ( ch = data[i] ) >= 0x20 ) {
continue;
}
if ( ch == '\n' ) {
if ( newLineChars == "\n" ) {
continue;
}
if ( sb == null ) {
sb = new StringBuilder( len + 5 );
}
sb.Append( data, start, i - start );
}
else if ( ch == '\r' ) {
if ( i + 1 < endPos && data[i+1] == '\n' ) {
if ( newLineChars == "\r\n" ) {
i++;
continue;
}
if ( sb == null ) {
sb = new StringBuilder( len + 5 );
}
sb.Append( data, start, i - start );
i++;
}
else {
if ( newLineChars == "\r" ) {
continue;
}
if ( sb == null ) {
sb = new StringBuilder( len + 5 );
}
sb.Append( data, start, i - start );
}
}
else {
continue;
}
sb.Append( newLineChars );
start = i + 1;
}
if ( sb == null ) {
return null;
}
else {
sb.Append( data, start, i - start );
return sb.ToString();
}
}
// Interleave 2 adjacent invalid chars with a space. This is used for fixing invalid values of comments and PIs.
// Any "--" in comment must be replaced with "- -" and any "-" at the end must be appended with " ".
// Any "?>" in PI value must be replaced with "? >".
// This code has a bug SQL BU Defect Tracking #480848, which was triaged as Won't Fix because it is a breaking change
private string InterleaveInvalidChars( string text, char invChar1, char invChar2 ) {
StringBuilder sb = null;
int start = 0;
int i;
for ( i = 0; i < text.Length; i++ ) {
if ( text[i] != invChar2 ) {
continue;
}
if ( i > 0 && text[i-1] == invChar1 ) {
if ( sb == null ) {
sb = new StringBuilder( text.Length + 5 );
}
sb.Append( text, start, i - start );
sb.Append( ' ' );
start = i;
}
}
// check last char & return
if ( sb == null ) {
return (i == 0 || text[i - 1] != invChar1) ? text : (text + ' ');
}
else {
sb.Append( text, start, i - start );
if (i > 0 && text[i - 1] == invChar1) {
sb.Append(' ');
}
return sb.ToString();
}
}
}
}
| |
//---------------------------------------------------------------------------
//
// File: NativeRecognizer.cs
//
// Description:
// A wrapper class which interoperates with the unmanaged recognition APIS
// in mshwgst.dll
//
// Features:
//
// History:
// 01/14/2005 waynezen: Created
//
// Copyright (C) 2001 by Microsoft Corporation. All rights reserved.
//
//---------------------------------------------------------------------------
using Microsoft.Win32;
using MS.Win32;
using System;
using System.Security;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Runtime.ConstrainedExecution;
using System.Security.Permissions;
using System.Text;
using System.Windows.Media;
using System.Windows.Ink;
using System.Windows.Input;
using MS.Internal.PresentationCore;
using MS.Utility;
using SR = MS.Internal.PresentationCore.SR;
using SRID = MS.Internal.PresentationCore.SRID;
#pragma warning disable 1634, 1691 // suppressing PreSharp warnings
namespace MS.Internal.Ink.GestureRecognition
{
/// <summary>
/// NativeRecognizer class
/// </summary>
internal sealed class NativeRecognizer : IDisposable
{
//-------------------------------------------------------------------------------
//
// Constructors
//
//-------------------------------------------------------------------------------
#region Constructors
/// <summary>
/// Static constructor
/// </summary>
/// <SecurityNote>
/// Critical: Calls a SecurityCritical methods
/// LoadRecognizerDll();
/// </SecurityNote>
[SecurityCritical]
static NativeRecognizer()
{
s_isSupported = LoadRecognizerDll();
}
/// <summary>
/// Private constructor
/// </summary>
/// <SecurityNote>
/// Critical: Calls a SecurityCritical method
/// NativeRecognizer.UnsafeNativeMethods.CreateContext()
/// Accesses the SecurityCritical member
/// _hContext
/// </SecurityNote>
[SecurityCritical]
private NativeRecognizer()
{
Debug.Assert(NativeRecognizer.RecognizerHandleSingleton != null);
int hr = MS.Win32.Recognizer.UnsafeNativeMethods.CreateContext(NativeRecognizer.RecognizerHandleSingleton,
out _hContext);
if (HRESULT.Failed(hr))
{
//don't throw a com exception here, we don't need to pass out any details
throw new InvalidOperationException(SR.Get(SRID.UnspecifiedGestureConstructionException));
}
// We add a reference of the recognizer to the context handle.
// The context will dereference the recognizer reference when it gets disposed.
// This trick will prevent the GC from disposing the recognizer before all contexts.
_hContext.AddReferenceOnRecognizer(NativeRecognizer.RecognizerHandleSingleton);
}
#endregion Constructors
//-------------------------------------------------------------------------------
//
// Internal Methods
//
//-------------------------------------------------------------------------------
#region Internal Methods
/// <summary>
/// Create an Instance of the NativeRecognizer.
/// </summary>
/// <returns>null if it fails</returns>
/// <SecurityNote>
/// Critical: Calls a SecurityCritical method
/// NativeRecognizer();
/// TreatAsSafe: The method is safe because no arguments are passed.
/// The NativeRecognizer return value is protected with SecurityCritical
/// attributes
/// </SecurityNote>
[SecurityCritical, SecurityTreatAsSafe]
internal static NativeRecognizer CreateInstance()
{
if (NativeRecognizer.RecognizerHandleSingleton != null)
{
return new NativeRecognizer();
}
else
{
return null;
}
}
/// <summary>
/// Set the enabled gestures
/// </summary>
/// <param name="applicationGestures"></param>
/// <SecurityNote>
/// Critical: Handles _hContext, which is SecurityCritical
/// TreatAsSafe: The method is safe because argument passed can not be
/// used maliciously. And we verify the length of the passed in array.
/// </SecurityNote>
[SecurityCritical, SecurityTreatAsSafe]
internal ApplicationGesture[] SetEnabledGestures(IEnumerable<ApplicationGesture> applicationGestures)
{
if (_disposed)
{
throw new ObjectDisposedException("NativeRecognizer");
}
//validate and get an array out
ApplicationGesture[] enabledGestures =
GetApplicationGestureArrayAndVerify(applicationGestures);
// Set enabled Gestures.
int hr = SetEnabledGestures(_hContext, enabledGestures);
if (HRESULT.Failed(hr))
{
//don't throw a com exception here, we don't need to pass out any details
throw new InvalidOperationException(SR.Get(SRID.UnspecifiedSetEnabledGesturesException));
}
return enabledGestures;
}
/// <summary>
/// Recognize the strokes.
/// </summary>
/// <param name="strokes"></param>
/// <returns></returns>
/// <SecurityNote>
/// Critical: Calls a SecurityCritical method
/// NativeRecognizer.UnsafeNativeMethods.ResetContext,
/// AddStrokes,
/// NativeRecognizer.UnsafeNativeMethods.Process
/// InvokeGetAlternateList
/// InvokeGetLatticePtr
/// </SecurityNote>
[SecurityCritical]
internal GestureRecognitionResult[] Recognize(StrokeCollection strokes)
{
if (_disposed)
{
throw new ObjectDisposedException("NativeRecognizer");
}
//
// note that we validate this argument from GestureRecognizer
// but since this is marked TAS, we want to do it here as well
//
if (strokes == null)
{
throw new ArgumentNullException("strokes"); // Null is not allowed as the argument value
}
if (strokes.Count > 2)
{
throw new ArgumentException(SR.Get(SRID.StrokeCollectionCountTooBig), "strokes");
}
// Create an empty result.
GestureRecognitionResult[] recResults = new GestureRecognitionResult[]{};
if ( strokes.Count == 0 )
{
return recResults;
}
int hr = 0;
try
{
// Reset the context
hr = MS.Win32.Recognizer.UnsafeNativeMethods.ResetContext(_hContext);
if (HRESULT.Failed(hr))
{
//finally block will clean up and throw
return recResults;
}
// Add strokes
hr = AddStrokes(_hContext, strokes);
if (HRESULT.Failed(hr))
{
//AddStrokes's finally block will clean up this finally block will throw
return recResults;
}
// recognize the ink
bool bIncremental;
hr = MS.Win32.Recognizer.UnsafeNativeMethods.Process(_hContext, out bIncremental);
if (HRESULT.Succeeded(hr))
{
if ( s_GetAlternateListExists )
{
recResults = InvokeGetAlternateList();
}
else
{
recResults = InvokeGetLatticePtr();
}
}
}
finally
{
// Check if we should report any error.
if ( HRESULT.Failed(hr) )
{
//don't throw a com exception here, we don't need to pass out any details
throw new InvalidOperationException(SR.Get(SRID.UnspecifiedGestureException));
}
}
return recResults;
}
internal static ApplicationGesture[] GetApplicationGestureArrayAndVerify(IEnumerable<ApplicationGesture> applicationGestures)
{
if (applicationGestures == null)
{
// Null is not allowed as the argument value
throw new ArgumentNullException("applicationGestures");
}
uint count = 0;
//we need to make a disconnected copy
ICollection<ApplicationGesture> collection = applicationGestures as ICollection<ApplicationGesture>;
if (collection != null)
{
count = (uint)collection.Count;
}
else
{
foreach (ApplicationGesture gesture in applicationGestures)
{
count++;
}
}
// Cannot be empty
if (count == 0)
{
// An empty array is not allowed.
throw new ArgumentException(SR.Get(SRID.ApplicationGestureArrayLengthIsZero), "applicationGestures");
}
bool foundAllGestures = false;
List<ApplicationGesture> gestures = new List<ApplicationGesture>();
foreach (ApplicationGesture gesture in applicationGestures)
{
if (!ApplicationGestureHelper.IsDefined(gesture))
{
throw new ArgumentException(SR.Get(SRID.ApplicationGestureIsInvalid), "applicationGestures");
}
//check for allgestures
if (gesture == ApplicationGesture.AllGestures)
{
foundAllGestures = true;
}
//check for dupes
if (gestures.Contains(gesture))
{
throw new ArgumentException(SR.Get(SRID.DuplicateApplicationGestureFound), "applicationGestures");
}
gestures.Add(gesture);
}
// AllGesture cannot be specified with other gestures
if (foundAllGestures && gestures.Count != 1)
{
// no dupes allowed
throw new ArgumentException(SR.Get(SRID.AllGesturesMustExistAlone), "applicationGestures");
}
return gestures.ToArray();
}
#endregion Internal Methods
//-------------------------------------------------------------------------------
//
// IDisposable
//
//-------------------------------------------------------------------------------
#region IDisposable
/// <summary>
/// A simple pattern of the dispose implementation.
/// There is no finalizer since the SafeHandle will take care of releasing the context.
/// </summary>
/// <SecurityNote>
/// Critical: Calls a SecurityCritical method and the SecurityCritical handle
/// _hContext.Dispose()
/// TreatAsSafe: The method is safe because no arguments are passed. We guard
/// against dispose being called twice.
/// </SecurityNote>
[SecurityCritical, SecurityTreatAsSafe]
public void Dispose()
{
if (_disposed)
{
return;
}
_hContext.Dispose();
_disposed = true;
}
#endregion IDisposable
//-------------------------------------------------------------------------------
//
// Private Methods
//
//-------------------------------------------------------------------------------
#region Private Methods
/// <summary>
/// Load the mshwgst.dll from the path in the registry. Make sure this loading action prior to invoking
/// any native functions marked with DllImport in mshwgst.dll
/// This method is called from the NativeRecognizer's static construtor.
/// </summary>
/// <SecurityNote>
/// Critical: Requires read registry and unmanaged code access
/// </SecurityNote>
[SecurityCritical]
private static bool LoadRecognizerDll()
{
// ISSUE-2005/01/14-WAYNEZEN,
// We may hit the problem when an application already load mshwgst.dll from somewhere rather than the
// directory we are looking for. The options to resolve this -
// 1. We fail the recognition functionality.
// 2. We unload the previous mshwgst.dll
// 3. We switch the DllImport usage to the new dynamic PInvoke mechanism in Whidbey. Please refer to the blog
// http://blogs.msdn.com/junfeng/archive/2004/07/14/181932.aspx. Then we don't have to unload the existing
// mshwgst.dll.
String path = null;
System.Security.PermissionSet permissionSet = new PermissionSet(null);
permissionSet.AddPermission(new RegistryPermission(RegistryPermissionAccess.Read,
System.Security.AccessControl.AccessControlActions.View,
GestureRecognizerFullPath));
permissionSet.AddPermission(new EnvironmentPermission(PermissionState.Unrestricted));
permissionSet.Assert(); // BlessedAssert:
try
{
RegistryKey regkey = Registry.LocalMachine;
RegistryKey recognizerKey = regkey.OpenSubKey(GestureRecognizerPath);
if (recognizerKey != null)
{
try
{
// Try to read the recognizer path subkey
path = recognizerKey.GetValue(GestureRecognizerValueName) as string;
if (path == null)
{
return false;
}
}
finally
{
recognizerKey.Close();
}
}
else
{
// we couldn't find the path in the registry
// no key to close
return false;
}
}
finally
{
CodeAccessPermission.RevertAssert();
}
if (path != null)
{
IntPtr hModule = MS.Win32.UnsafeNativeMethods.LoadLibrary(path);
// Check whether GetAlternateList exists in the loaded Dll.
s_GetAlternateListExists = false;
if ( hModule != IntPtr.Zero )
{
s_GetAlternateListExists = MS.Win32.UnsafeNativeMethods.GetProcAddressNoThrow(
new HandleRef(null, hModule), "GetAlternateList") != IntPtr.Zero ?
true : false;
}
return hModule != IntPtr.Zero ? true : false;
}
return false; //path was null
}
/// <summary>
/// Set the enabled gestures.
/// This method is called from the internal SetEnabledGestures method.
/// </summary>
/// <SecurityNote>
/// Critical: Calls a critical pinvoke
/// NativeRecognizer.UnsafeNativeMethods.SetEnabledUnicodeRanges
/// </SecurityNote>
[SecurityCritical]
private int SetEnabledGestures(MS.Win32.Recognizer.ContextSafeHandle recContext, ApplicationGesture[] enabledGestures)
{
Debug.Assert(recContext != null && !recContext.IsInvalid);
// NOTICE-2005/01/11-WAYNEZEN,
// The following usage was copied from drivers\tablet\recognition\ink\core\twister\src\wispapis.c
// SetEnabledUnicodeRanges
// Set ranges of gestures enabled in this recognition context
// The behavior of this function is the following:
// (a) (A part of) One of the requested ranges lies outside
// gesture interval---currently [GESTURE_NULL, GESTURE_NULL + 255)
// return E_UNEXPECTED and keep the previously set ranges
// (b) All requested ranges are within the gesture interval but
// some of them are not supported:
// return S_TRUNCATED and set those requested gestures that are
// supported (possibly an empty set)
// (c) All requested gestures are supported
// return S_OK and set all requested gestures.
// Note: An easy way to set all supported gestures as enabled is to use
// SetEnabledUnicodeRanges() with one range=(GESTURE_NULL,255).
// Enabel gestures
uint cRanges = (uint)( enabledGestures.Length );
MS.Win32.Recognizer.CHARACTER_RANGE[] charRanges = new MS.Win32.Recognizer.CHARACTER_RANGE[cRanges];
if ( cRanges == 1 && enabledGestures[0] == ApplicationGesture.AllGestures )
{
charRanges[0].cChars = MAX_GESTURE_COUNT;
charRanges[0].wcLow = GESTURE_NULL;
}
else
{
for ( int i = 0; i < cRanges; i++ )
{
charRanges[i].cChars = 1;
charRanges[i].wcLow = (ushort)( enabledGestures[i] );
}
}
int hr = MS.Win32.Recognizer.UnsafeNativeMethods.SetEnabledUnicodeRanges(recContext, cRanges, charRanges);
return hr;
}
/// <summary>
/// Add the strokes to the recoContext.
/// The method is called from the internal Recognize method.
/// </summary>
/// <SecurityNote>
/// Critical: Calls a critical PInvoke
/// GetPacketData,
/// NativeRecognizer.UnsafeNativeMethods.AddStroke,
/// ReleaseResourcesinPacketDescription
/// </SecurityNote>
[SecurityCritical]
private int AddStrokes(MS.Win32.Recognizer.ContextSafeHandle recContext, StrokeCollection strokes)
{
Debug.Assert(recContext != null && !recContext.IsInvalid);
int hr;
foreach ( Stroke stroke in strokes )
{
MS.Win32.Recognizer.PACKET_DESCRIPTION packetDescription =
new MS.Win32.Recognizer.PACKET_DESCRIPTION();
IntPtr packets = IntPtr.Zero;
try
{
int countOfBytes;
NativeMethods.XFORM xForm;
GetPacketData(stroke, out packetDescription, out countOfBytes, out packets, out xForm);
if (packets == IntPtr.Zero)
{
return -2147483640; //E_FAIL - 0x80000008. We never raise this in an exception
}
hr = MS.Win32.Recognizer.UnsafeNativeMethods.AddStroke(recContext, ref packetDescription, (uint)countOfBytes, packets, xForm);
if ( HRESULT.Failed(hr) )
{
// Return from here. The finally block will free the memory and report the error properly.
return hr;
}
}
finally
{
// Release the resources in the finally block
ReleaseResourcesinPacketDescription(packetDescription, packets);
}
}
return MS.Win32.Recognizer.UnsafeNativeMethods.EndInkInput(recContext);
}
/// <summary>
/// Retrieve the packet description, packets data and XFORM which is the information the native recognizer needs.
/// The method is called from AddStrokes.
/// </summary>
/// <SecurityNote>
/// Critical: Contains unsafe code
/// </SecurityNote>
[SecurityCritical]
private void GetPacketData
(
Stroke stroke,
out MS.Win32.Recognizer.PACKET_DESCRIPTION packetDescription,
out int countOfBytes,
out IntPtr packets,
out NativeMethods.XFORM xForm
)
{
int i;
countOfBytes = 0;
packets = IntPtr.Zero;
packetDescription = new MS.Win32.Recognizer.PACKET_DESCRIPTION();
Matrix matrix = Matrix.Identity;
xForm = new NativeMethods.XFORM((float)(matrix.M11), (float)(matrix.M12), (float)(matrix.M21),
(float)(matrix.M22), (float)(matrix.OffsetX), (float)(matrix.OffsetY));
StylusPointCollection stylusPoints = stroke.StylusPoints;
if (stylusPoints.Count == 0)
{
return; //we'll fail when the calling routine sees that packets is IntPtr.Zer
}
if (stylusPoints.Description.PropertyCount > StylusPointDescription.RequiredCountOfProperties)
{
//
// reformat to X, Y, P
//
StylusPointDescription reformatDescription
= new StylusPointDescription(
new StylusPointPropertyInfo[]{
new StylusPointPropertyInfo(StylusPointProperties.X),
new StylusPointPropertyInfo(StylusPointProperties.Y),
stylusPoints.Description.GetPropertyInfo(StylusPointProperties.NormalPressure)});
stylusPoints = stylusPoints.Reformat(reformatDescription);
}
//
// now make sure we only take a finite amount of data for the stroke
//
if (stylusPoints.Count > MaxStylusPoints)
{
stylusPoints = stylusPoints.Clone(MaxStylusPoints);
}
Guid[] propertyGuids = new Guid[]{ StylusPointPropertyIds.X, //required index for SPD
StylusPointPropertyIds.Y, //required index for SPD
StylusPointPropertyIds.NormalPressure}; //required index for SPD
Debug.Assert(stylusPoints != null);
Debug.Assert(propertyGuids.Length == StylusPointDescription.RequiredCountOfProperties);
// Get the packet description
packetDescription.cbPacketSize = (uint)(propertyGuids.Length * Marshal.SizeOf(typeof(Int32)));
packetDescription.cPacketProperties = (uint)propertyGuids.Length;
//
// use X, Y defaults for metrics, sometimes mouse metrics can be bogus
// always use NormalPressure metrics, though.
//
StylusPointPropertyInfo[] infosToUse = new StylusPointPropertyInfo[StylusPointDescription.RequiredCountOfProperties];
infosToUse[StylusPointDescription.RequiredXIndex] = StylusPointPropertyInfoDefaults.X;
infosToUse[StylusPointDescription.RequiredYIndex] = StylusPointPropertyInfoDefaults.Y;
infosToUse[StylusPointDescription.RequiredPressureIndex] =
stylusPoints.Description.GetPropertyInfo(StylusPointProperties.NormalPressure);
MS.Win32.Recognizer.PACKET_PROPERTY[] packetProperties =
new MS.Win32.Recognizer.PACKET_PROPERTY[packetDescription.cPacketProperties];
StylusPointPropertyInfo propertyInfo;
for ( i = 0; i < packetDescription.cPacketProperties; i++ )
{
packetProperties[i].guid = propertyGuids[i];
propertyInfo = infosToUse[i];
MS.Win32.Recognizer.PROPERTY_METRICS propertyMetrics = new MS.Win32.Recognizer.PROPERTY_METRICS( );
propertyMetrics.nLogicalMin = propertyInfo.Minimum;
propertyMetrics.nLogicalMax = propertyInfo.Maximum;
propertyMetrics.Units = (int)(propertyInfo.Unit);
propertyMetrics.fResolution = propertyInfo.Resolution;
packetProperties[i].PropertyMetrics = propertyMetrics;
}
unsafe
{
int allocationSize = (int)(Marshal.SizeOf(typeof(MS.Win32.Recognizer.PACKET_PROPERTY)) * packetDescription.cPacketProperties);
packetDescription.pPacketProperties = Marshal.AllocCoTaskMem(allocationSize);
MS.Win32.Recognizer.PACKET_PROPERTY* pPacketProperty =
(MS.Win32.Recognizer.PACKET_PROPERTY*)(packetDescription.pPacketProperties.ToPointer());
MS.Win32.Recognizer.PACKET_PROPERTY* pElement = pPacketProperty;
for ( i = 0 ; i < packetDescription.cPacketProperties ; i ++ )
{
Marshal.StructureToPtr(packetProperties[i], new IntPtr(pElement), false);
pElement++;
}
}
// Get packet data
int[] rawPackets = stylusPoints.ToHiMetricArray();
int packetCount = rawPackets.Length;
if (packetCount != 0)
{
countOfBytes = packetCount * Marshal.SizeOf(typeof(Int32));
packets = Marshal.AllocCoTaskMem(countOfBytes);
Marshal.Copy(rawPackets, 0, packets, packetCount);
}
}
/// <summary>
/// Release the memory blocks which has been created for mashalling purpose.
/// The method is called from AddStrokes.
/// </summary>
/// <SecurityNote>
/// Critical: Calls unsafe code, requires UnmanageCode permission
/// </SecurityNote>
[SecurityCritical]
private void ReleaseResourcesinPacketDescription(MS.Win32.Recognizer.PACKET_DESCRIPTION pd, IntPtr packets)
{
if ( pd.pPacketProperties != IntPtr.Zero )
{
unsafe
{
MS.Win32.Recognizer.PACKET_PROPERTY* pPacketProperty =
(MS.Win32.Recognizer.PACKET_PROPERTY*)( pd.pPacketProperties.ToPointer( ) );
MS.Win32.Recognizer.PACKET_PROPERTY* pElement = pPacketProperty;
for ( int i = 0; i < pd.cPacketProperties; i++ )
{
Marshal.DestroyStructure(new IntPtr(pElement), typeof(MS.Win32.Recognizer.PACKET_PROPERTY));
pElement++;
}
}
Marshal.FreeCoTaskMem(pd.pPacketProperties);
pd.pPacketProperties = IntPtr.Zero;
}
if ( pd.pguidButtons != IntPtr.Zero )
{
Marshal.FreeCoTaskMem(pd.pguidButtons);
pd.pguidButtons = IntPtr.Zero;
}
if ( packets != IntPtr.Zero )
{
Marshal.FreeCoTaskMem(packets);
packets = IntPtr.Zero;
}
}
/// <summary>
/// Invokes GetAlternateList in the native dll
/// </summary>
/// <returns></returns>
/// <SecurityNote>
/// Critical: Calls the native methods
/// NativeRecognizer.UnsafeNativeMethods.GetAlternateList
/// NativeRecognizer.UnsafeNativeMethods.GetString
/// NativeRecognizer.UnsafeNativeMethods.GetConfidenceLevel
/// NativeRecognizer.UnsafeNativeMethods.DestroyAlternate
/// </SecurityNote>
[SecurityCritical]
private GestureRecognitionResult[] InvokeGetAlternateList()
{
GestureRecognitionResult[] recResults = new GestureRecognitionResult[] { };
int hr = 0;
MS.Win32.Recognizer.RECO_RANGE recoRange;
recoRange.iwcBegin = 0;
recoRange.cCount = 1;
uint countOfAlternates = IRAS_DefaultCount;
IntPtr[] pRecoAlternates = new IntPtr[IRAS_DefaultCount];
try
{
hr = MS.Win32.Recognizer.UnsafeNativeMethods.GetAlternateList(_hContext, ref recoRange, ref countOfAlternates, pRecoAlternates, MS.Win32.Recognizer.ALT_BREAKS.ALT_BREAKS_SAME);
if ( HRESULT.Succeeded(hr) && countOfAlternates != 0 )
{
List<GestureRecognitionResult> resultList = new List<GestureRecognitionResult>();
for ( int i = 0; i < countOfAlternates; i++ )
{
uint size = 1; // length of string == 1 since gesture id is a single WCHAR
StringBuilder recoString = new StringBuilder(1);
RecognitionConfidence confidenceLevel;
if ( HRESULT.Failed(MS.Win32.Recognizer.UnsafeNativeMethods.GetString(pRecoAlternates[i], out recoRange, ref size, recoString))
|| HRESULT.Failed(MS.Win32.Recognizer.UnsafeNativeMethods.GetConfidenceLevel(pRecoAlternates[i], out recoRange, out confidenceLevel)) )
{
// Fail to retrieve the reco result, skip this one
continue;
}
ApplicationGesture gesture = (ApplicationGesture)recoString[0];
Debug.Assert(ApplicationGestureHelper.IsDefined(gesture));
if (ApplicationGestureHelper.IsDefined(gesture))
{
resultList.Add(new GestureRecognitionResult(confidenceLevel, gesture));
}
}
recResults = resultList.ToArray();
}
}
finally
{
// Destroy the alternates
for ( int i = 0; i < countOfAlternates; i++ )
{
if (pRecoAlternates[i] != IntPtr.Zero)
{
#pragma warning suppress 6031, 56031 // Return value ignored on purpose.
MS.Win32.Recognizer.UnsafeNativeMethods.DestroyAlternate(pRecoAlternates[i]);
pRecoAlternates[i] = IntPtr.Zero;
}
}
}
return recResults;
}
/// <summary>
/// Invokes GetLatticePtr in the native dll
/// </summary>
/// <returns></returns>
/// <SecurityNote>
/// Critical: Calls the native methods
/// NativeRecognizer.UnsafeNativeMethods.GetLatticePtr
/// And uses unsafe code
/// </SecurityNote>
[SecurityCritical]
private GestureRecognitionResult[] InvokeGetLatticePtr()
{
GestureRecognitionResult[] recResults = new GestureRecognitionResult[] { };
// int hr = 0;
IntPtr ptr = IntPtr.Zero;
// NOTICE-2005/07/11-WAYNEZEN,
// There is no need to free the returned the structure.
// The memory will be released when ResetContext, which is invoked in the callee - Recognize, is called.
if ( HRESULT.Succeeded(
MS.Win32.Recognizer.UnsafeNativeMethods.GetLatticePtr(
_hContext, ref ptr)) )
{
unsafe
{
MS.Win32.Recognizer.RECO_LATTICE* pRecoLattice = (MS.Win32.Recognizer.RECO_LATTICE*)ptr;
uint bestResultColumnCount = pRecoLattice->ulBestResultColumnCount;
Debug.Assert(!(bestResultColumnCount != 0 && pRecoLattice->pLatticeColumns == IntPtr.Zero), "Invalid results!");
if ( bestResultColumnCount > 0 && pRecoLattice->pLatticeColumns != IntPtr.Zero )
{
List<GestureRecognitionResult> resultList = new List<GestureRecognitionResult>();
MS.Win32.Recognizer.RECO_LATTICE_COLUMN* pLatticeColumns =
(MS.Win32.Recognizer.RECO_LATTICE_COLUMN*)(pRecoLattice->pLatticeColumns);
ulong* pulBestResultColumns = (ulong*)(pRecoLattice->pulBestResultColumns);
for ( uint i = 0; i < bestResultColumnCount; i++ )
{
ulong column = pulBestResultColumns[i];
MS.Win32.Recognizer.RECO_LATTICE_COLUMN recoColumn = pLatticeColumns[column];
Debug.Assert(0 < recoColumn.cLatticeElements, "Invalid results!");
for ( int j = 0; j < recoColumn.cLatticeElements; j++ )
{
MS.Win32.Recognizer.RECO_LATTICE_ELEMENT recoElement =
((MS.Win32.Recognizer.RECO_LATTICE_ELEMENT*)(recoColumn.pLatticeElements))[j];
Debug.Assert((RECO_TYPE)(recoElement.type) == RECO_TYPE.RECO_TYPE_WCHAR, "The Application gesture has to be WCHAR type" );
if ( (RECO_TYPE)(recoElement.type) == RECO_TYPE.RECO_TYPE_WCHAR )
{
// Retrieve the confidence lever
RecognitionConfidence confidenceLevel = RecognitionConfidence.Poor;
MS.Win32.Recognizer.RECO_LATTICE_PROPERTIES recoProperties = recoElement.epProp;
uint propertyCount = recoProperties.cProperties;
MS.Win32.Recognizer.RECO_LATTICE_PROPERTY** apProps =
(MS.Win32.Recognizer.RECO_LATTICE_PROPERTY**)recoProperties.apProps;
for ( int k = 0; k < propertyCount; k++ )
{
MS.Win32.Recognizer.RECO_LATTICE_PROPERTY* pProps = apProps[k];
if ( pProps->guidProperty == GUID_CONFIDENCELEVEL )
{
Debug.Assert(pProps->cbPropertyValue == sizeof(uint) / sizeof(byte));
RecognitionConfidence level = (RecognitionConfidence)(((uint*)pProps->pPropertyValue))[0];
if ( level >= RecognitionConfidence.Strong && level <= RecognitionConfidence.Poor )
{
confidenceLevel = level;
}
break;
}
}
ApplicationGesture gesture = (ApplicationGesture)((char)(recoElement.pData));
Debug.Assert(ApplicationGestureHelper.IsDefined(gesture));
if (ApplicationGestureHelper.IsDefined(gesture))
{
// Get the gesture result
resultList.Add(new GestureRecognitionResult(confidenceLevel,gesture));
}
}
}
}
recResults = (GestureRecognitionResult[])(resultList.ToArray());
}
}
}
return recResults;
}
#endregion Private Methods
/// <summary>
/// RecognizerHandle is a static property. But it's a SafeHandle.
/// So, we don't have to worry about releasing the handle since RecognizerSafeHandle when there is no reference on it.
/// </summary>
/// <SecurityNote>
/// Critical: Calls a SecurityCritical pinvoke and accesses SecurityCritical fields
/// </SecurityNote>
private static MS.Win32.Recognizer.RecognizerSafeHandle RecognizerHandleSingleton
{
[SecurityCritical]
get
{
if (s_isSupported && s_hRec == null)
{
lock (_syncRoot)
{
if (s_isSupported && s_hRec == null)
{
if (HRESULT.Failed(MS.Win32.Recognizer.UnsafeNativeMethods.CreateRecognizer(ref s_Gesture, out s_hRec)))
{
s_hRec = null;
}
}
}
}
return s_hRec;
}
}
enum RECO_TYPE : ushort
{
RECO_TYPE_WSTRING = 0,
RECO_TYPE_WCHAR = 1
}
private const string GestureRecognizerPath = @"SOFTWARE\MICROSOFT\TPG\SYSTEM RECOGNIZERS\{BED9A940-7D48-48E3-9A68-F4887A5A1B2E}";
private const string GestureRecognizerFullPath = "HKEY_LOCAL_MACHINE" + @"\" + GestureRecognizerPath;
private const string GestureRecognizerValueName = "RECOGNIZER DLL";
private const string GestureRecognizerGuid = "{BED9A940-7D48-48E3-9A68-F4887A5A1B2E}";
// This constant is an identical value as the one in drivers\tablet\recognition\ink\core\common\inc\gesture\gesturedefs.h
private const ushort MAX_GESTURE_COUNT = 256;
// This constant is an identical value as the one in drivers\tablet\include\sdk\recdefs.h
private const ushort GESTURE_NULL = 0xf000;
// This constant is an identical value as the one in public\internal\drivers\inc\msinkaut.h
private const ushort IRAS_DefaultCount = 10;
private const ushort MaxStylusPoints = 10000;
// The GUID has been copied from public\internal\drivers\inc\tpcguid.h
//// {7DFE11A7-FB5D-4958-8765-154ADF0D833F}
//DEFINE_GUID(GUID_CONFIDENCELEVEL, 0x7dfe11a7, 0xfb5d, 0x4958, 0x87, 0x65, 0x15, 0x4a, 0xdf, 0xd, 0x83, 0x3f);
private static readonly Guid GUID_CONFIDENCELEVEL = new Guid("{7DFE11A7-FB5D-4958-8765-154ADF0D833F}");
/// <summary>
/// IDisposable support
/// </summary>
private bool _disposed = false;
/// <summary>
/// Each NativeRecognizer instance has it's own recognizer context
/// </summary>
/// <SecurityNote>
/// Critical: The SecurityCritical handle
/// </SecurityNote>
[SecurityCritical]
private MS.Win32.Recognizer.ContextSafeHandle _hContext;
/// <summary>
/// Used to lock for instancing the native recognizer handle
/// </summary>
private static object _syncRoot = new object();
/// <summary>
/// All NativeRecognizer share a single handle to the recognizer
/// </summary>
/// <SecurityNote>
/// Critical: The SecurityCritical handle
/// </SecurityNote>
[SecurityCritical]
private static MS.Win32.Recognizer.RecognizerSafeHandle s_hRec;
/// <summary>
/// The Guid of the GestureRecognizer used for registry lookup
/// </summary>
private static Guid s_Gesture = new Guid(GestureRecognizerGuid);
/// <summary>
/// can we load the recognizer?
/// </summary>
private static readonly bool s_isSupported;
/// <summary>
/// A flag indicates whether we can find the entry point of
/// GetAlternateList function in mshwgst.dll
/// </summary>
private static bool s_GetAlternateListExists;
}
}
| |
// Copyright (c) DotSpatial Team. All rights reserved.
// Licensed under the MIT license. See License.txt file in the project root for full license information.
using System;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Globalization;
using System.IO;
namespace DotSpatial.Data
{
/// <summary>
/// WorldFiles complement images, giving georeference information for those images. The basic idea is to calculate
/// everything based on the top left corner of the image.
/// </summary>
public class WorldFile
{
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="WorldFile"/> class.
/// </summary>
public WorldFile()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="WorldFile"/> class based on the specified image fileName.
/// </summary>
/// <param name="imageFilename">Attempts to open the fileName for the world file for the image if it exists.</param>
public WorldFile(string imageFilename)
{
Filename = GenerateFilename(imageFilename);
if (File.Exists(imageFilename))
{
Open();
}
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the coordinates in the Affine order:
/// X' = [0] + [1] X + [2] Y
/// Y' = [3] + [4] X + [5] Y
/// </summary>
public double[] Affine { get; set; }
/// <summary>
/// Gets or sets the cell height.
/// </summary>
public double CellHeight
{
get
{
return Affine[5];
}
set
{
Affine[5] = value;
}
}
/// <summary>
/// Gets or sets the cell width.
/// </summary>
public double CellWidth
{
get
{
return Affine[1];
}
set
{
Affine[1] = value;
}
}
/// <summary>
/// Gets a string list of file extensions that might apply to world files.
/// </summary>
public string DialogFilter
{
get
{
return "generic (*.wld)|*.wld|Bitmap (*.bpw)|*.bpw|EMF (*.efw)|*efw|Exif (*.exw)|GIF (*.gif)|*.gif|Icon (*.iow)|*.iow|JPEG (*.jgw)|*.jgw|Memory Bitmap (*.mpw)|*.mpw|PNG (*.pgw)|*.pgw|Tif (*.tfw)|*.tfw|WMF (*.wfw)|*.wfw";
}
}
/// <summary>
/// Gets or sets the fileName to use for this world file.
/// </summary>
public string Filename { get; set; }
/// <summary>
/// Gets or sets how much the longitude or X position of a cell in the image depends on the row position of the cell.
/// </summary>
public double HorizontalSkew
{
get
{
return Affine[2];
}
set
{
Affine[2] = value;
}
}
/// <summary>
/// Gets or sets longitude or X position corresponding to the center of the cell in the top left corner of the image
/// </summary>
public double TopLeftX
{
get
{
return Affine[0];
}
set
{
Affine[0] = value;
}
}
/// <summary>
/// Gets or sets the latitude or Y position corresponding to the center of the cell in the top left corner of the image
/// </summary>
public double TopLeftY
{
get
{
return Affine[3];
}
set
{
Affine[3] = value;
}
}
/// <summary>
/// Gets or sets how much the latitude or Y position of a cell in the image depends on the column position of the cell.
/// </summary>
public double VerticalSkew
{
get
{
return Affine[4];
}
set
{
Affine[4] = value;
}
}
#endregion
#region Methods
/// <summary>
/// Given the fileName of an image, this creates a new fileName with the appropriate extension.
/// This will also set the fileName of this world file to that extension.
/// </summary>
/// <param name="imageFilename">The fileName of the image</param>
/// <returns>the fileName of the world file</returns>
public static string GenerateFilename(string imageFilename)
{
string result = ".wld";
string ext = Path.GetExtension(imageFilename)?.ToLower();
switch (ext)
{
case ".bmp":
result = ".bpw";
break;
case ".emf":
result = ".efw";
break;
case ".exf":
result = ".exw";
break;
case ".gif":
result = ".gfw";
break;
case ".ico":
result = ".iow";
break;
case ".jpg":
result = ".jgw";
break;
case ".mbp":
result = ".mww";
break;
case ".png":
result = ".pgw";
break;
case ".tif":
result = ".tfw";
break;
case ".wmf":
result = ".wft";
break;
}
return Path.ChangeExtension(imageFilename, result);
}
/// <summary>
/// Returns the string extensions that accompanies one of the dot net image formats.
/// </summary>
/// <param name="format">The Imaging.ImageFormat for the image itself</param>
/// <returns>The string extension</returns>
public string GetExtension(ImageFormat format)
{
if (format == ImageFormat.Bmp) return ".bpw";
if (format == ImageFormat.Emf) return ".efw";
if (format == ImageFormat.Exif) return ".exw";
if (format == ImageFormat.Gif) return ".gfw";
if (format == ImageFormat.Icon) return ".iow";
if (format == ImageFormat.Jpeg) return ".jgw";
if (format == ImageFormat.MemoryBmp) return ".mpw";
if (format == ImageFormat.Png) return ".pgw";
if (format == ImageFormat.Tiff) return ".tfw";
if (format == ImageFormat.Wmf) return ".wfw";
return ".wld";
}
/// <summary>
/// Opens the worldfile specified by the Filename property and loads the values
/// </summary>
public void Open()
{
if (File.Exists(Filename))
{
using (var sr = new StreamReader(Filename))
{
Affine = new double[6];
Affine[1] = NextValue(sr); // Dx
Affine[2] = NextValue(sr); // Skew X
Affine[4] = NextValue(sr); // Skew Y
Affine[5] = NextValue(sr); // Dy
Affine[0] = NextValue(sr); // Top Left X
Affine[3] = NextValue(sr); // Top Left Y
}
}
}
/// <summary>
/// Opens an existing worldfile based on the specified fileName.
/// </summary>
/// <param name="fileName">File name of the worldfile that should be opened.</param>
public void Open(string fileName)
{
Filename = fileName;
Open();
}
/// <summary>
/// Saves the current affine coordinates to the current fileName
/// </summary>
public void Save()
{
if (File.Exists(Filename)) File.Delete(Filename);
StreamWriter sw = new StreamWriter(Filename);
sw.WriteLine(Affine[1].ToString(CultureInfo.InvariantCulture)); // Dx
sw.WriteLine(Affine[2].ToString(CultureInfo.InvariantCulture)); // Skew X
sw.WriteLine(Affine[4].ToString(CultureInfo.InvariantCulture)); // Skew Y
sw.WriteLine(Affine[5].ToString(CultureInfo.InvariantCulture)); // Dy
sw.WriteLine(Affine[0].ToString(CultureInfo.InvariantCulture)); // Top Left X
sw.WriteLine(Affine[3].ToString(CultureInfo.InvariantCulture)); // Top Left Y
sw.Close();
}
/// <summary>
/// Saves the current coordinates to a file
/// </summary>
/// <param name="fileName">Gets or sets the fileName to use for an image</param>
public void SaveAs(string fileName)
{
Filename = fileName;
Save();
}
/// <summary>
/// Creates a Matrix that is in float coordinates that represents this world file
/// </summary>
/// <returns>A Matrix that transforms an image to the geographic coordinates</returns>
public Matrix ToMatrix()
{
float m11 = Convert.ToSingle(Affine[1]);
float m12 = Convert.ToSingle(Affine[2]);
float m21 = Convert.ToSingle(Affine[4]);
float m22 = Convert.ToSingle(Affine[5]);
float dx = Convert.ToSingle(Affine[0]);
float dy = Convert.ToSingle(Affine[3]);
return new Matrix(m11, m12, m21, m22, dx, dy);
}
private static double NextValue(StreamReader sr)
{
string nextLine;
while ((nextLine = sr.ReadLine()) == string.Empty && !sr.EndOfStream)
{
// Skip any blank lines
}
if (nextLine != null) return double.Parse(nextLine, CultureInfo.InvariantCulture);
return 0;
}
#endregion
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
namespace System.Text
{
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Text;
using System;
using System.Diagnostics.Contracts;
// A Decoder is used to decode a sequence of blocks of bytes into a
// sequence of blocks of characters. Following instantiation of a decoder,
// sequential blocks of bytes are converted into blocks of characters through
// calls to the GetChars method. The decoder maintains state between the
// conversions, allowing it to correctly decode byte sequences that span
// adjacent blocks.
//
// Instances of specific implementations of the Decoder abstract base
// class are typically obtained through calls to the GetDecoder method
// of Encoding objects.
//
[Serializable]
internal class DecoderNLS : Decoder, ISerializable
{
// Remember our encoding
protected Encoding m_encoding;
[NonSerialized] protected bool m_mustFlush;
[NonSerialized] internal bool m_throwOnOverflow;
[NonSerialized] internal int m_bytesUsed;
#region Serialization
// Constructor called by serialization. called during deserialization.
internal DecoderNLS(SerializationInfo info, StreamingContext context)
{
throw new NotSupportedException(
String.Format(
System.Globalization.CultureInfo.CurrentCulture,
Environment.GetResourceString("NotSupported_TypeCannotDeserialized"), this.GetType()));
}
#if FEATURE_SERIALIZATION
// ISerializable implementation. called during serialization.
[System.Security.SecurityCritical] // auto-generated_required
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
SerializeDecoder(info);
info.AddValue("encoding", this.m_encoding);
info.SetType(typeof(Encoding.DefaultDecoder));
}
#endif
#endregion Serialization
internal DecoderNLS( Encoding encoding )
{
this.m_encoding = encoding;
this.m_fallback = this.m_encoding.DecoderFallback;
this.Reset();
}
// This is used by our child deserializers
internal DecoderNLS( )
{
this.m_encoding = null;
this.Reset();
}
public override void Reset()
{
if (m_fallbackBuffer != null)
m_fallbackBuffer.Reset();
}
public override unsafe int GetCharCount(byte[] bytes, int index, int count)
{
return GetCharCount(bytes, index, count, false);
}
[System.Security.SecuritySafeCritical] // auto-generated
public override unsafe int GetCharCount(byte[] bytes, int index, int count, bool flush)
{
// Validate Parameters
if (bytes == null)
throw new ArgumentNullException("bytes",
Environment.GetResourceString("ArgumentNull_Array"));
if (index < 0 || count < 0)
throw new ArgumentOutOfRangeException((index<0 ? "index" : "count"),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (bytes.Length - index < count)
throw new ArgumentOutOfRangeException("bytes",
Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
Contract.EndContractBlock();
// Avoid null fixed problem
if (bytes.Length == 0)
bytes = new byte[1];
// Just call pointer version
fixed (byte* pBytes = bytes)
return GetCharCount(pBytes + index, count, flush);
}
[System.Security.SecurityCritical] // auto-generated
public unsafe override int GetCharCount(byte* bytes, int count, bool flush)
{
// Validate parameters
if (bytes == null)
throw new ArgumentNullException("bytes",
Environment.GetResourceString("ArgumentNull_Array"));
if (count < 0)
throw new ArgumentOutOfRangeException("count",
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
// Remember the flush
this.m_mustFlush = flush;
this.m_throwOnOverflow = true;
// By default just call the encoding version, no flush by default
return m_encoding.GetCharCount(bytes, count, this);
}
public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount,
char[] chars, int charIndex)
{
return GetChars(bytes, byteIndex, byteCount, chars, charIndex, false);
}
[System.Security.SecuritySafeCritical] // auto-generated
public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount,
char[] chars, int charIndex, bool flush)
{
// Validate Parameters
if (bytes == null || chars == null)
throw new ArgumentNullException(bytes == null ? "bytes" : "chars",
Environment.GetResourceString("ArgumentNull_Array"));
if (byteIndex < 0 || byteCount < 0)
throw new ArgumentOutOfRangeException((byteIndex<0 ? "byteIndex" : "byteCount"),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if ( bytes.Length - byteIndex < byteCount)
throw new ArgumentOutOfRangeException("bytes",
Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
if (charIndex < 0 || charIndex > chars.Length)
throw new ArgumentOutOfRangeException("charIndex",
Environment.GetResourceString("ArgumentOutOfRange_Index"));
Contract.EndContractBlock();
// Avoid empty input fixed problem
if (bytes.Length == 0)
bytes = new byte[1];
int charCount = chars.Length - charIndex;
if (chars.Length == 0)
chars = new char[1];
// Just call pointer version
fixed (byte* pBytes = bytes)
fixed (char* pChars = chars)
// Remember that charCount is # to decode, not size of array
return GetChars(pBytes + byteIndex, byteCount,
pChars + charIndex, charCount, flush);
}
[System.Security.SecurityCritical] // auto-generated
public unsafe override int GetChars(byte* bytes, int byteCount,
char* chars, int charCount, bool flush)
{
// Validate parameters
if (chars == null || bytes == null)
throw new ArgumentNullException((chars == null ? "chars" : "bytes"),
Environment.GetResourceString("ArgumentNull_Array"));
if (byteCount < 0 || charCount < 0)
throw new ArgumentOutOfRangeException((byteCount<0 ? "byteCount" : "charCount"),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
// Remember our flush
m_mustFlush = flush;
m_throwOnOverflow = true;
// By default just call the encoding's version
return m_encoding.GetChars(bytes, byteCount, chars, charCount, this);
}
// This method is used when the output buffer might not be big enough.
// Just call the pointer version. (This gets chars)
[System.Security.SecuritySafeCritical] // auto-generated
public override unsafe void Convert(byte[] bytes, int byteIndex, int byteCount,
char[] chars, int charIndex, int charCount, bool flush,
out int bytesUsed, out int charsUsed, out bool completed)
{
// Validate parameters
if (bytes == null || chars == null)
throw new ArgumentNullException((bytes == null ? "bytes" : "chars"),
Environment.GetResourceString("ArgumentNull_Array"));
if (byteIndex < 0 || byteCount < 0)
throw new ArgumentOutOfRangeException((byteIndex<0 ? "byteIndex" : "byteCount"),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (charIndex < 0 || charCount < 0)
throw new ArgumentOutOfRangeException((charIndex<0 ? "charIndex" : "charCount"),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (bytes.Length - byteIndex < byteCount)
throw new ArgumentOutOfRangeException("bytes",
Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
if (chars.Length - charIndex < charCount)
throw new ArgumentOutOfRangeException("chars",
Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
Contract.EndContractBlock();
// Avoid empty input problem
if (bytes.Length == 0)
bytes = new byte[1];
if (chars.Length == 0)
chars = new char[1];
// Just call the pointer version (public overrides can't do this)
fixed (byte* pBytes = bytes)
{
fixed (char* pChars = chars)
{
Convert(pBytes + byteIndex, byteCount, pChars + charIndex, charCount, flush,
out bytesUsed, out charsUsed, out completed);
}
}
}
// This is the version that used pointers. We call the base encoding worker function
// after setting our appropriate internal variables. This is getting chars
[System.Security.SecurityCritical] // auto-generated
public unsafe override void Convert(byte* bytes, int byteCount,
char* chars, int charCount, bool flush,
out int bytesUsed, out int charsUsed, out bool completed)
{
// Validate input parameters
if (chars == null || bytes == null)
throw new ArgumentNullException(chars == null ? "chars" : "bytes",
Environment.GetResourceString("ArgumentNull_Array"));
if (byteCount < 0 || charCount < 0)
throw new ArgumentOutOfRangeException((byteCount<0 ? "byteCount" : "charCount"),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
// We don't want to throw
this.m_mustFlush = flush;
this.m_throwOnOverflow = false;
this.m_bytesUsed = 0;
// Do conversion
charsUsed = this.m_encoding.GetChars(bytes, byteCount, chars, charCount, this);
bytesUsed = this.m_bytesUsed;
// Its completed if they've used what they wanted AND if they didn't want flush or if we are flushed
completed = (bytesUsed == byteCount) && (!flush || !this.HasState) &&
(m_fallbackBuffer == null || m_fallbackBuffer.Remaining == 0);
// Our data thingys are now full, we can return
}
public bool MustFlush
{
get
{
return m_mustFlush;
}
}
// Anything left in our decoder?
internal virtual bool HasState
{
get
{
return false;
}
}
// Allow encoding to clear our must flush instead of throwing (in ThrowCharsOverflow)
internal void ClearMustFlush()
{
m_mustFlush = false;
}
}
}
| |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// Template Source: Templates\CSharp\Requests\EntityRequest.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Linq.Expressions;
/// <summary>
/// The type ContractRequest.
/// </summary>
public partial class ContractRequest : BaseRequest, IContractRequest
{
/// <summary>
/// Constructs a new ContractRequest.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
/// <param name="options">Query and header option name value pairs for the request.</param>
public ContractRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Creates the specified Contract using POST.
/// </summary>
/// <param name="contractToCreate">The Contract to create.</param>
/// <returns>The created Contract.</returns>
public System.Threading.Tasks.Task<Contract> CreateAsync(Contract contractToCreate)
{
return this.CreateAsync(contractToCreate, CancellationToken.None);
}
/// <summary>
/// Creates the specified Contract using POST.
/// </summary>
/// <param name="contractToCreate">The Contract to create.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created Contract.</returns>
public async System.Threading.Tasks.Task<Contract> CreateAsync(Contract contractToCreate, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "POST";
var newEntity = await this.SendAsync<Contract>(contractToCreate, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(newEntity);
return newEntity;
}
/// <summary>
/// Deletes the specified Contract.
/// </summary>
/// <returns>The task to await.</returns>
public System.Threading.Tasks.Task DeleteAsync()
{
return this.DeleteAsync(CancellationToken.None);
}
/// <summary>
/// Deletes the specified Contract.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The task to await.</returns>
public async System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken)
{
this.Method = "DELETE";
await this.SendAsync<Contract>(null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the specified Contract.
/// </summary>
/// <returns>The Contract.</returns>
public System.Threading.Tasks.Task<Contract> GetAsync()
{
return this.GetAsync(CancellationToken.None);
}
/// <summary>
/// Gets the specified Contract.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The Contract.</returns>
public async System.Threading.Tasks.Task<Contract> GetAsync(CancellationToken cancellationToken)
{
this.Method = "GET";
var retrievedEntity = await this.SendAsync<Contract>(null, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(retrievedEntity);
return retrievedEntity;
}
/// <summary>
/// Updates the specified Contract using PATCH.
/// </summary>
/// <param name="contractToUpdate">The Contract to update.</param>
/// <returns>The updated Contract.</returns>
public System.Threading.Tasks.Task<Contract> UpdateAsync(Contract contractToUpdate)
{
return this.UpdateAsync(contractToUpdate, CancellationToken.None);
}
/// <summary>
/// Updates the specified Contract using PATCH.
/// </summary>
/// <param name="contractToUpdate">The Contract to update.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The updated Contract.</returns>
public async System.Threading.Tasks.Task<Contract> UpdateAsync(Contract contractToUpdate, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "PATCH";
var updatedEntity = await this.SendAsync<Contract>(contractToUpdate, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(updatedEntity);
return updatedEntity;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public IContractRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="expandExpression">The expression from which to calculate the expand value.</param>
/// <returns>The request object to send.</returns>
public IContractRequest Expand(Expression<Func<Contract, object>> expandExpression)
{
if (expandExpression == null)
{
throw new ArgumentNullException(nameof(expandExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(expandExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$expand", value));
}
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public IContractRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="selectExpression">The expression from which to calculate the select value.</param>
/// <returns>The request object to send.</returns>
public IContractRequest Select(Expression<Func<Contract, object>> selectExpression)
{
if (selectExpression == null)
{
throw new ArgumentNullException(nameof(selectExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(selectExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$select", value));
}
return this;
}
/// <summary>
/// Initializes any collection properties after deserialization, like next requests for paging.
/// </summary>
/// <param name="contractToInitialize">The <see cref="Contract"/> with the collection properties to initialize.</param>
private void InitializeCollectionProperties(Contract contractToInitialize)
{
}
}
}
| |
// Copyright (c) 2015, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Web;
using System.Web.UI.WebControls;
using WebsitePanel.EnterpriseServer;
namespace WebsitePanel.Portal
{
public partial class HostingPlansEditPlan : WebsitePanelModuleBase
{
protected bool ShouldCopyCurrentHostingPlan()
{
return (HttpContext.Current.Request["TargetAction"] == "Copy");
}
protected void Page_Load(object sender, EventArgs e)
{
btnDelete.Visible = (PanelRequest.PlanID > 0) && (!ShouldCopyCurrentHostingPlan());
if (!IsPostBack)
{
try
{
BindPlan();
}
catch (Exception ex)
{
ShowErrorMessage("PLAN_GET_PLAN", ex);
return;
}
}
}
private void BindServers()
{
ddlServer.DataSource = ES.Services.Servers.GetRawAllServers();
ddlServer.DataBind();
ddlServer.Items.Insert(0, new ListItem("<Select Server>", ""));
}
private void BindSpaces()
{
ddlSpace.DataSource = ES.Services.Packages.GetMyPackages(PanelSecurity.SelectedUserId);
ddlSpace.DataBind();
ddlSpace.Items.Insert(0, new ListItem("<Select Space>", ""));
}
private void BindPlan()
{
// hide "target server" section for non-admins
bool isUserAdmin = PanelSecurity.SelectedUser.Role == UserRole.Administrator;
rowTargetServer.Visible = isUserAdmin;
rowTargetSpace.Visible = !isUserAdmin;
if(isUserAdmin)
BindServers();
else
BindSpaces();
if (PanelRequest.PlanID == 0)
{
// new plan
BindQuotas();
return;
}
HostingPlanInfo plan = ES.Services.Packages.GetHostingPlan(PanelRequest.PlanID);
if (plan == null)
// plan not found
RedirectBack();
if (ShouldCopyCurrentHostingPlan())
{
plan.PlanId = 0;
plan.PlanName = "Copy of " + plan.PlanName;
}
// bind plan
txtPlanName.Text = PortalAntiXSS.DecodeOld(plan.PlanName);
txtPlanDescription.Text = PortalAntiXSS.DecodeOld(plan.PlanDescription);
//chkAvailable.Checked = plan.Available;
//txtSetupPrice.Text = plan.SetupPrice.ToString("0.00");
//txtRecurringPrice.Text = plan.RecurringPrice.ToString("0.00");
//txtRecurrenceLength.Text = plan.RecurrenceLength.ToString();
//Utils.SelectListItem(ddlRecurrenceUnit, plan.RecurrenceUnit);
Utils.SelectListItem(ddlServer, plan.ServerId);
Utils.SelectListItem(ddlSpace, plan.PackageId);
// bind quotas
BindQuotas();
}
private void BindQuotas()
{
int serverId = Utils.ParseInt(ddlServer.SelectedValue, 0);
int packageId = Utils.ParseInt(ddlSpace.SelectedValue, -1);
hostingPlansQuotas.BindPlanQuotas(packageId, PanelRequest.PlanID, serverId);
}
private void SavePlan()
{
if (!Page.IsValid)
return;
// gather form info
HostingPlanInfo plan = new HostingPlanInfo();
plan.UserId = PanelSecurity.SelectedUserId;
plan.PlanId = PanelRequest.PlanID;
plan.IsAddon = false;
plan.PlanName = txtPlanName.Text;
plan.PlanDescription = txtPlanDescription.Text;
plan.Available = true; // always available
plan.SetupPrice = 0;
plan.RecurringPrice = 0;
plan.RecurrenceLength = 1;
plan.RecurrenceUnit = 2; // month
plan.PackageId = Utils.ParseInt(ddlSpace.SelectedValue, 0);
plan.ServerId = Utils.ParseInt(ddlServer.SelectedValue, 0);
// if this is non-admin
// get server info from parent package
if (PanelSecurity.EffectiveUser.Role != UserRole.Administrator)
{
try
{
PackageInfo package = ES.Services.Packages.GetPackage(plan.PackageId);
if (package != null)
plan.ServerId = package.ServerId;
}
catch (Exception ex)
{
ShowErrorMessage("PACKAGE_GET_PACKAGE", ex);
return;
}
}
plan.Groups = hostingPlansQuotas.Groups;
plan.Quotas = hostingPlansQuotas.Quotas;
int planId = PanelRequest.PlanID;
if ((PanelRequest.PlanID == 0) || ShouldCopyCurrentHostingPlan())
{
// new plan
try
{
planId = ES.Services.Packages.AddHostingPlan(plan);
if (planId < 0)
{
ShowResultMessage(planId);
return;
}
}
catch (Exception ex)
{
ShowErrorMessage("PLAN_ADD_PLAN", ex);
return;
}
}
else
{
// update plan
try
{
PackageResult result = ES.Services.Packages.UpdateHostingPlan(plan);
if (result.Result < 0)
{
ShowResultMessage(result.Result);
lblMessage.Text = PortalAntiXSS.Encode(GetExceedingQuotasMessage(result.ExceedingQuotas));
return;
}
}
catch (Exception ex)
{
ShowErrorMessage("PLAN_UPDATE_PLAN", ex);
return;
}
}
// redirect
RedirectBack();
}
private void DeletePlan()
{
try
{
int result = ES.Services.Packages.DeleteHostingPlan(PanelRequest.PlanID);
if (result < 0)
{
ShowResultMessage(result);
return;
}
}
catch (Exception ex)
{
ShowErrorMessage("PLAN_DELETE_PLAN", ex);
return;
}
// redirect
RedirectBack();
}
protected void btnSave_Click(object sender, EventArgs e)
{
SavePlan();
}
protected void btnCancel_Click(object sender, EventArgs e)
{
RedirectBack();
}
protected void btnDelete_Click(object sender, EventArgs e)
{
DeletePlan();
}
protected void planTarget_SelectedIndexChanged(object sender, EventArgs e)
{
BindQuotas();
}
private void RedirectBack()
{
Response.Redirect(NavigateURL(PortalUtils.USER_ID_PARAM, PanelSecurity.SelectedUserId.ToString()));
}
}
}
| |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Linq.Expressions;
/// <summary>
/// The type WorkbookChartLegendFormatRequest.
/// </summary>
public partial class WorkbookChartLegendFormatRequest : BaseRequest, IWorkbookChartLegendFormatRequest
{
/// <summary>
/// Constructs a new WorkbookChartLegendFormatRequest.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
/// <param name="options">Query and header option name value pairs for the request.</param>
public WorkbookChartLegendFormatRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Creates the specified WorkbookChartLegendFormat using POST.
/// </summary>
/// <param name="workbookChartLegendFormatToCreate">The WorkbookChartLegendFormat to create.</param>
/// <returns>The created WorkbookChartLegendFormat.</returns>
public System.Threading.Tasks.Task<WorkbookChartLegendFormat> CreateAsync(WorkbookChartLegendFormat workbookChartLegendFormatToCreate)
{
return this.CreateAsync(workbookChartLegendFormatToCreate, CancellationToken.None);
}
/// <summary>
/// Creates the specified WorkbookChartLegendFormat using POST.
/// </summary>
/// <param name="workbookChartLegendFormatToCreate">The WorkbookChartLegendFormat to create.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created WorkbookChartLegendFormat.</returns>
public async System.Threading.Tasks.Task<WorkbookChartLegendFormat> CreateAsync(WorkbookChartLegendFormat workbookChartLegendFormatToCreate, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "POST";
var newEntity = await this.SendAsync<WorkbookChartLegendFormat>(workbookChartLegendFormatToCreate, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(newEntity);
return newEntity;
}
/// <summary>
/// Deletes the specified WorkbookChartLegendFormat.
/// </summary>
/// <returns>The task to await.</returns>
public System.Threading.Tasks.Task DeleteAsync()
{
return this.DeleteAsync(CancellationToken.None);
}
/// <summary>
/// Deletes the specified WorkbookChartLegendFormat.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The task to await.</returns>
public async System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken)
{
this.Method = "DELETE";
await this.SendAsync<WorkbookChartLegendFormat>(null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the specified WorkbookChartLegendFormat.
/// </summary>
/// <returns>The WorkbookChartLegendFormat.</returns>
public System.Threading.Tasks.Task<WorkbookChartLegendFormat> GetAsync()
{
return this.GetAsync(CancellationToken.None);
}
/// <summary>
/// Gets the specified WorkbookChartLegendFormat.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The WorkbookChartLegendFormat.</returns>
public async System.Threading.Tasks.Task<WorkbookChartLegendFormat> GetAsync(CancellationToken cancellationToken)
{
this.Method = "GET";
var retrievedEntity = await this.SendAsync<WorkbookChartLegendFormat>(null, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(retrievedEntity);
return retrievedEntity;
}
/// <summary>
/// Updates the specified WorkbookChartLegendFormat using PATCH.
/// </summary>
/// <param name="workbookChartLegendFormatToUpdate">The WorkbookChartLegendFormat to update.</param>
/// <returns>The updated WorkbookChartLegendFormat.</returns>
public System.Threading.Tasks.Task<WorkbookChartLegendFormat> UpdateAsync(WorkbookChartLegendFormat workbookChartLegendFormatToUpdate)
{
return this.UpdateAsync(workbookChartLegendFormatToUpdate, CancellationToken.None);
}
/// <summary>
/// Updates the specified WorkbookChartLegendFormat using PATCH.
/// </summary>
/// <param name="workbookChartLegendFormatToUpdate">The WorkbookChartLegendFormat to update.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The updated WorkbookChartLegendFormat.</returns>
public async System.Threading.Tasks.Task<WorkbookChartLegendFormat> UpdateAsync(WorkbookChartLegendFormat workbookChartLegendFormatToUpdate, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "PATCH";
var updatedEntity = await this.SendAsync<WorkbookChartLegendFormat>(workbookChartLegendFormatToUpdate, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(updatedEntity);
return updatedEntity;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookChartLegendFormatRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="expandExpression">The expression from which to calculate the expand value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookChartLegendFormatRequest Expand(Expression<Func<WorkbookChartLegendFormat, object>> expandExpression)
{
if (expandExpression == null)
{
throw new ArgumentNullException(nameof(expandExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(expandExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$expand", value));
}
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookChartLegendFormatRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="selectExpression">The expression from which to calculate the select value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookChartLegendFormatRequest Select(Expression<Func<WorkbookChartLegendFormat, object>> selectExpression)
{
if (selectExpression == null)
{
throw new ArgumentNullException(nameof(selectExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(selectExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$select", value));
}
return this;
}
/// <summary>
/// Initializes any collection properties after deserialization, like next requests for paging.
/// </summary>
/// <param name="workbookChartLegendFormatToInitialize">The <see cref="WorkbookChartLegendFormat"/> with the collection properties to initialize.</param>
private void InitializeCollectionProperties(WorkbookChartLegendFormat workbookChartLegendFormatToInitialize)
{
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsHttp
{
using Microsoft.Rest;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// HttpFailure operations.
/// </summary>
public partial class HttpFailure : IServiceOperations<AutoRestHttpInfrastructureTestService>, IHttpFailure
{
/// <summary>
/// Initializes a new instance of the HttpFailure class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public HttpFailure(AutoRestHttpInfrastructureTestService client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the AutoRestHttpInfrastructureTestService
/// </summary>
public AutoRestHttpInfrastructureTestService Client { get; private set; }
/// <summary>
/// Get empty error form server
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<bool?>> GetEmptyErrorWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetEmptyError", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/failure/emptybody/error").ToString();
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<bool?>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<bool?>(_responseContent, Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get empty error form server
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<bool?>> GetNoModelErrorWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetNoModelError", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/failure/nomodel/error").ToString();
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<bool?>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<bool?>(_responseContent, Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get empty response from server
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<bool?>> GetNoModelEmptyWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetNoModelEmpty", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/failure/nomodel/empty").ToString();
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<bool?>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<bool?>(_responseContent, Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
//
// ScrollbarBackend.cs
//
// Author:
// Lluis Sanchez <lluis@xamarin.com>
//
// Copyright (c) 2013 Xamarin 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 AppKit;
using CoreGraphics;
using Xwt.Backends;
namespace Xwt.Mac
{
public class ScrollbarBackend: ViewBackend<NSScroller,IWidgetEventSink>, IScrollbarBackend
{
public ScrollbarBackend ()
{
}
public void Initialize (Orientation dir)
{
CGRect r;
if (dir == Orientation.Horizontal)
r = new CGRect (0, 0, NSScroller.ScrollerWidth + 1, NSScroller.ScrollerWidth);
else
r = new CGRect (0, 0, NSScroller.ScrollerWidth, NSScroller.ScrollerWidth + 1);
ViewObject = new CustomScroller (r);
}
public IScrollAdjustmentBackend CreateAdjustment ()
{
return (CustomScroller) Widget;
}
}
class CustomScroller: NSScroller, IScrollAdjustmentBackend, IViewObject
{
IScrollAdjustmentEventSink eventSink;
double value;
double lowerValue;
double upperValue;
//double pageIncrement;
double stepIncrement;
double pageSize;
NSView IViewObject.View {
get {
return this;
}
}
ViewBackend IViewObject.Backend { get; set; }
public CustomScroller (CGRect r): base (r)
{
}
public override void ScrollWheel(NSEvent theEvent) {
base.ScrollWheel(theEvent);
value += theEvent.ScrollingDeltaY;
if(value < lowerValue)
value = lowerValue;
if(value > upperValue - pageSize)
value = upperValue - pageSize;
UpdateValue();
eventSink.OnValueChanged ();
}
public void Initialize (IScrollAdjustmentEventSink eventSink)
{
this.eventSink = eventSink;
KnobStyle = NSScrollerKnobStyle.Default;
ScrollerStyle = NSScrollerStyle.Legacy;
ControlSize = NSControlSize.Regular;
Enabled = true;
}
void HandleActivated (object sender, EventArgs e)
{
value = lowerValue + (DoubleValue * (upperValue - lowerValue - pageSize));
switch (HitPart) {
case NSScrollerPart.DecrementPage:
value -= pageSize;
if (value < lowerValue)
value = lowerValue;
UpdateValue ();
break;
case NSScrollerPart.IncrementPage:
value += pageSize;
if (value + pageSize > upperValue)
value = upperValue - pageSize;
if (value < lowerValue)
value = lowerValue;
UpdateValue ();
break;
case NSScrollerPart.DecrementLine:
value -= stepIncrement;
if (value < lowerValue)
value = lowerValue;
UpdateValue ();
break;
case NSScrollerPart.IncrementLine:
value += stepIncrement;
if (value + pageSize > upperValue)
value = upperValue - pageSize;
if (value < lowerValue)
value = lowerValue;
UpdateValue ();
break;
}
eventSink.OnValueChanged ();
}
public double Value {
get {
return value;
}
set {
this.value = value;
UpdateValue ();
}
}
public void SetRange (double lowerValue, double upperValue, double pageSize, double pageIncrement, double stepIncrement, double value)
{
this.lowerValue = lowerValue;
this.upperValue = upperValue;
this.pageSize = pageSize;
//this.pageIncrement = pageIncrement;
this.stepIncrement = stepIncrement;
this.value = value;
UpdateValue ();
UpdateKnobProportion ();
}
public void InitializeBackend (object frontend, ApplicationContext context)
{
}
public void EnableEvent (object eventId)
{
if (((ScrollAdjustmentEvent)eventId) == ScrollAdjustmentEvent.ValueChanged)
Activated += HandleActivated;
}
public void DisableEvent (object eventId)
{
if (((ScrollAdjustmentEvent)eventId) == ScrollAdjustmentEvent.ValueChanged)
Activated -= HandleActivated;
}
void UpdateValue ()
{
if (lowerValue >= upperValue) {
DoubleValue = 0.5;
return;
}
var val = value;
if (val < lowerValue)
val = lowerValue;
if (val + pageSize > upperValue) {
val = upperValue - pageSize;
if (val < lowerValue) {
DoubleValue = 0.5;
return;
}
}
DoubleValue = (val - lowerValue) / (upperValue - lowerValue - pageSize);
}
void UpdateKnobProportion ()
{
if (pageSize == 0 || lowerValue >= upperValue || pageSize >= (upperValue - lowerValue))
KnobProportion = 1;
else {
KnobProportion = (float)(pageSize / (upperValue - lowerValue));
}
}
}
}
| |
// 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.
// </copyright>
namespace System.DirectoryServices.ActiveDirectory
{
using System;
using System.Net;
using System.Runtime.InteropServices;
using System.Security.Authentication;
using System.Text;
using System.Collections;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Globalization;
public class SyncFromAllServersErrorInformation
{
private SyncFromAllServersErrorCategory _category;
private int _errorCode;
private string _errorMessage = null;
private string _sourceServer = null;
private string _targetServer = null;
internal SyncFromAllServersErrorInformation(SyncFromAllServersErrorCategory category, int errorCode, string errorMessage, string sourceServer, string targetServer)
{
_category = category;
_errorCode = errorCode;
_errorMessage = errorMessage;
_sourceServer = sourceServer;
_targetServer = targetServer;
}
public SyncFromAllServersErrorCategory ErrorCategory
{
get
{
return _category;
}
}
public int ErrorCode
{
get
{
return _errorCode;
}
}
public string ErrorMessage
{
get
{
return _errorMessage;
}
}
public string TargetServer
{
get
{
return _targetServer;
}
}
public string SourceServer
{
get
{
return _sourceServer;
}
}
}
[Serializable]
public class ActiveDirectoryObjectNotFoundException : Exception, ISerializable
{
private Type _objectType;
private string _name = null;
public ActiveDirectoryObjectNotFoundException(string message, Type type, string name) : base(message)
{
_objectType = type;
_name = name;
}
public ActiveDirectoryObjectNotFoundException(string message, Exception inner) : base(message, inner) { }
public ActiveDirectoryObjectNotFoundException(string message) : base(message) { }
public ActiveDirectoryObjectNotFoundException() : base() { }
protected ActiveDirectoryObjectNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) { }
public Type Type
{
get
{
return _objectType;
}
}
public string Name
{
get
{
return _name;
}
}
[SecurityPermissionAttribute(SecurityAction.LinkDemand, SerializationFormatter = true)]
public override void GetObjectData(SerializationInfo serializationInfo, StreamingContext streamingContext)
{
base.GetObjectData(serializationInfo, streamingContext);
}
}
[Serializable]
public class ActiveDirectoryOperationException : Exception, ISerializable
{
private int _errorCode = 0;
public ActiveDirectoryOperationException(string message, Exception inner, int errorCode) : base(message, inner)
{
_errorCode = errorCode;
}
public ActiveDirectoryOperationException(string message, int errorCode) : base(message)
{
_errorCode = errorCode;
}
public ActiveDirectoryOperationException(string message, Exception inner) : base(message, inner) { }
public ActiveDirectoryOperationException(string message) : base(message) { }
public ActiveDirectoryOperationException() : base(SR.DSUnknownFailure) { }
protected ActiveDirectoryOperationException(SerializationInfo info, StreamingContext context) : base(info, context) { }
public int ErrorCode
{
get
{
return _errorCode;
}
}
[SecurityPermissionAttribute(SecurityAction.LinkDemand, SerializationFormatter = true)]
public override void GetObjectData(SerializationInfo serializationInfo, StreamingContext streamingContext)
{
base.GetObjectData(serializationInfo, streamingContext);
}
}
[Serializable]
public class ActiveDirectoryServerDownException : Exception, ISerializable
{
private int _errorCode = 0;
private string _name = null;
public ActiveDirectoryServerDownException(string message, Exception inner, int errorCode, string name) : base(message, inner)
{
_errorCode = errorCode;
_name = name;
}
public ActiveDirectoryServerDownException(string message, int errorCode, string name) : base(message)
{
_errorCode = errorCode;
_name = name;
}
public ActiveDirectoryServerDownException(string message, Exception inner) : base(message, inner) { }
public ActiveDirectoryServerDownException(string message) : base(message) { }
public ActiveDirectoryServerDownException() : base() { }
protected ActiveDirectoryServerDownException(SerializationInfo info, StreamingContext context) : base(info, context) { }
public int ErrorCode
{
get
{
return _errorCode;
}
}
public string Name
{
get
{
return _name;
}
}
public override String Message
{
get
{
String s = base.Message;
if (!((_name == null) ||
(_name.Length == 0)))
return s + Environment.NewLine + String.Format(CultureInfo.CurrentCulture, SR.Name , _name) + Environment.NewLine;
else
return s;
}
}
[SecurityPermissionAttribute(SecurityAction.LinkDemand, SerializationFormatter = true)]
public override void GetObjectData(SerializationInfo serializationInfo, StreamingContext streamingContext)
{
base.GetObjectData(serializationInfo, streamingContext);
}
}
[Serializable]
public class ActiveDirectoryObjectExistsException : Exception
{
public ActiveDirectoryObjectExistsException(string message, Exception inner) : base(message, inner) { }
public ActiveDirectoryObjectExistsException(string message) : base(message) { }
public ActiveDirectoryObjectExistsException() : base() { }
protected ActiveDirectoryObjectExistsException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
[Serializable]
public class SyncFromAllServersOperationException : ActiveDirectoryOperationException, ISerializable
{
private SyncFromAllServersErrorInformation[] _errors = null;
public SyncFromAllServersOperationException(string message, Exception inner, SyncFromAllServersErrorInformation[] errors) : base(message, inner)
{
_errors = errors;
}
public SyncFromAllServersOperationException(string message, Exception inner) : base(message, inner) { }
public SyncFromAllServersOperationException(string message) : base(message) { }
public SyncFromAllServersOperationException() : base(SR.DSSyncAllFailure) { }
protected SyncFromAllServersOperationException(SerializationInfo info, StreamingContext context) : base(info, context) { }
public SyncFromAllServersErrorInformation[] ErrorInformation
{
get
{
if (_errors == null)
return new SyncFromAllServersErrorInformation[0];
SyncFromAllServersErrorInformation[] tempError = new SyncFromAllServersErrorInformation[_errors.Length];
for (int i = 0; i < _errors.Length; i++)
tempError[i] = new SyncFromAllServersErrorInformation(_errors[i].ErrorCategory, _errors[i].ErrorCode, _errors[i].ErrorMessage, _errors[i].SourceServer, _errors[i].TargetServer);
return tempError;
}
}
[SecurityPermissionAttribute(SecurityAction.LinkDemand, SerializationFormatter = true)]
public override void GetObjectData(SerializationInfo serializationInfo, StreamingContext streamingContext)
{
base.GetObjectData(serializationInfo, streamingContext);
}
}
[Serializable]
public class ForestTrustCollisionException : ActiveDirectoryOperationException, ISerializable
{
private ForestTrustRelationshipCollisionCollection _collisions = new ForestTrustRelationshipCollisionCollection();
public ForestTrustCollisionException(string message, Exception inner, ForestTrustRelationshipCollisionCollection collisions) : base(message, inner)
{
_collisions = collisions;
}
public ForestTrustCollisionException(string message, Exception inner) : base(message, inner) { }
public ForestTrustCollisionException(string message) : base(message) { }
public ForestTrustCollisionException() : base(SR.ForestTrustCollision) { }
protected ForestTrustCollisionException(SerializationInfo info, StreamingContext context) : base(info, context) { }
public ForestTrustRelationshipCollisionCollection Collisions
{
get
{
return _collisions;
}
}
[SecurityPermissionAttribute(SecurityAction.LinkDemand, SerializationFormatter = true)]
public override void GetObjectData(SerializationInfo serializationInfo, StreamingContext streamingContext)
{
base.GetObjectData(serializationInfo, streamingContext);
}
}
internal class ExceptionHelper
{
private static int s_ERROR_NOT_ENOUGH_MEMORY = 8; // map to outofmemory exception
private static int s_ERROR_OUTOFMEMORY = 14; // map to outofmemory exception
private static int s_ERROR_DS_DRA_OUT_OF_MEM = 8446; // map to outofmemory exception
private static int s_ERROR_NO_SUCH_DOMAIN = 1355; // map to ActiveDirectoryServerDownException
private static int s_ERROR_ACCESS_DENIED = 5; // map to UnauthorizedAccessException
private static int s_ERROR_NO_LOGON_SERVERS = 1311; // map to ActiveDirectoryServerDownException
private static int s_ERROR_DS_DRA_ACCESS_DENIED = 8453; // map to UnauthorizedAccessException
private static int s_RPC_S_OUT_OF_RESOURCES = 1721; // map to outofmemory exception
internal static int RPC_S_SERVER_UNAVAILABLE = 1722; // map to ActiveDirectoryServerDownException
internal static int RPC_S_CALL_FAILED = 1726; // map to ActiveDirectoryServerDownException
private static int s_ERROR_CANCELLED = 1223;
internal static int ERROR_DS_DRA_BAD_DN = 8439;
internal static int ERROR_DS_NAME_UNPARSEABLE = 8350;
internal static int ERROR_DS_UNKNOWN_ERROR = 8431;
//
// This method maps some common COM Hresults to
// existing clr exceptions
//
internal static Exception GetExceptionFromCOMException(COMException e)
{
return GetExceptionFromCOMException(null, e);
}
internal static Exception GetExceptionFromCOMException(DirectoryContext context, COMException e)
{
Exception exception;
int errorCode = e.ErrorCode;
string errorMessage = e.Message;
//
// Check if we can throw a more specific exception
//
if (errorCode == unchecked((int)0x80070005))
{
//
// Access Denied
//
exception = new UnauthorizedAccessException(errorMessage, e);
}
else if (errorCode == unchecked((int)0x8007052e))
{
//
// Logon Failure
//
exception = new AuthenticationException(errorMessage, e);
}
else if (errorCode == unchecked((int)0x8007202f))
{
//
// Constraint Violation
//
exception = new InvalidOperationException(errorMessage, e);
}
else if (errorCode == unchecked((int)0x80072035))
{
//
// Unwilling to perform
//
exception = new InvalidOperationException(errorMessage, e);
}
else if (errorCode == unchecked((int)0x80071392))
{
//
// Object already exists
//
exception = new ActiveDirectoryObjectExistsException(errorMessage, e);
}
else if (errorCode == unchecked((int)0x80070008))
{
//
// No Memory
//
exception = new OutOfMemoryException();
}
else if ((errorCode == unchecked((int)0x8007203a)) || (errorCode == unchecked((int)0x8007200e)) || (errorCode == unchecked((int)0x8007200f)))
{
//
// ServerDown/Unavailable/Busy
//
if (context != null)
{
exception = new ActiveDirectoryServerDownException(errorMessage, e, errorCode, context.GetServerName());
}
else
{
exception = new ActiveDirectoryServerDownException(errorMessage, e, errorCode, null);
}
}
else
{
//
// Wrap the exception in a generic OperationException
//
exception = new ActiveDirectoryOperationException(errorMessage, e, errorCode);
}
return exception;
}
internal static Exception GetExceptionFromErrorCode(int errorCode)
{
return GetExceptionFromErrorCode(errorCode, null);
}
internal static Exception GetExceptionFromErrorCode(int errorCode, string targetName)
{
string errorMsg = GetErrorMessage(errorCode, false);
if ((errorCode == s_ERROR_ACCESS_DENIED) || (errorCode == s_ERROR_DS_DRA_ACCESS_DENIED))
return new UnauthorizedAccessException(errorMsg);
else if ((errorCode == s_ERROR_NOT_ENOUGH_MEMORY) || (errorCode == s_ERROR_OUTOFMEMORY) || (errorCode == s_ERROR_DS_DRA_OUT_OF_MEM) || (errorCode == s_RPC_S_OUT_OF_RESOURCES))
return new OutOfMemoryException();
else if ((errorCode == s_ERROR_NO_LOGON_SERVERS) || (errorCode == s_ERROR_NO_SUCH_DOMAIN) || (errorCode == RPC_S_SERVER_UNAVAILABLE) || (errorCode == RPC_S_CALL_FAILED))
return new ActiveDirectoryServerDownException(errorMsg, errorCode, targetName);
else
return new ActiveDirectoryOperationException(errorMsg, errorCode);
}
internal static string GetErrorMessage(int errorCode, bool hresult)
{
uint temp = (uint)errorCode;
if (!hresult)
{
temp = ((((temp) & 0x0000FFFF) | (7 << 16) | 0x80000000));
}
string errorMsg = "";
StringBuilder sb = new StringBuilder(256);
int result = UnsafeNativeMethods.FormatMessageW(UnsafeNativeMethods.FORMAT_MESSAGE_IGNORE_INSERTS |
UnsafeNativeMethods.FORMAT_MESSAGE_FROM_SYSTEM |
UnsafeNativeMethods.FORMAT_MESSAGE_ARGUMENT_ARRAY,
0, (int)temp, 0, sb, sb.Capacity + 1, 0);
if (result != 0)
{
errorMsg = sb.ToString(0, result);
}
else
{
errorMsg = String.Format(CultureInfo.CurrentCulture, SR.DSUnknown , Convert.ToString(temp, 16));
}
return errorMsg;
}
internal static SyncFromAllServersOperationException CreateSyncAllException(IntPtr errorInfo, bool singleError)
{
if (errorInfo == (IntPtr)0)
return new SyncFromAllServersOperationException();
if (singleError)
{
// single error
DS_REPSYNCALL_ERRINFO error = new DS_REPSYNCALL_ERRINFO();
Marshal.PtrToStructure(errorInfo, error);
string message = GetErrorMessage(error.dwWin32Err, false);
string source = Marshal.PtrToStringUni(error.pszSrcId);
string target = Marshal.PtrToStringUni(error.pszSvrId);
if (error.dwWin32Err == s_ERROR_CANCELLED)
{
// this is a special case. the failure is because user specifies SyncAllOptions.CheckServerAlivenessOnly, ignore it here
return null;
}
else
{
SyncFromAllServersErrorInformation managedError = new SyncFromAllServersErrorInformation(error.error, error.dwWin32Err, message, source, target);
return new SyncFromAllServersOperationException(SR.DSSyncAllFailure, null, new SyncFromAllServersErrorInformation[] { managedError });
}
}
else
{
// it is a NULL terminated array of DS_REPSYNCALL_ERRINFO
IntPtr tempPtr = Marshal.ReadIntPtr(errorInfo);
ArrayList errorList = new ArrayList();
int i = 0;
while (tempPtr != (IntPtr)0)
{
DS_REPSYNCALL_ERRINFO error = new DS_REPSYNCALL_ERRINFO();
Marshal.PtrToStructure(tempPtr, error);
// this is a special case. the failure is because user specifies SyncAllOptions.CheckServerAlivenessOnly, ignore it here
if (error.dwWin32Err != s_ERROR_CANCELLED)
{
string message = GetErrorMessage(error.dwWin32Err, false);
string source = Marshal.PtrToStringUni(error.pszSrcId);
string target = Marshal.PtrToStringUni(error.pszSvrId);
SyncFromAllServersErrorInformation managedError = new SyncFromAllServersErrorInformation(error.error, error.dwWin32Err, message, source, target);
errorList.Add(managedError);
}
i++;
tempPtr = Marshal.ReadIntPtr(errorInfo, i * IntPtr.Size);
}
// no error information, so we should not throw exception.
if (errorList.Count == 0)
return null;
SyncFromAllServersErrorInformation[] info = new SyncFromAllServersErrorInformation[errorList.Count];
for (int j = 0; j < errorList.Count; j++)
{
SyncFromAllServersErrorInformation tmp = (SyncFromAllServersErrorInformation)errorList[j];
info[j] = new SyncFromAllServersErrorInformation(tmp.ErrorCategory, tmp.ErrorCode, tmp.ErrorMessage, tmp.SourceServer, tmp.TargetServer);
}
return new SyncFromAllServersOperationException(SR.DSSyncAllFailure, null, info);
}
}
internal static Exception CreateForestTrustCollisionException(IntPtr collisionInfo)
{
ForestTrustRelationshipCollisionCollection collection = new ForestTrustRelationshipCollisionCollection();
LSA_FOREST_TRUST_COLLISION_INFORMATION collision = new LSA_FOREST_TRUST_COLLISION_INFORMATION();
Marshal.PtrToStructure(collisionInfo, collision);
int count = collision.RecordCount;
IntPtr addr = (IntPtr)0;
for (int i = 0; i < count; i++)
{
addr = Marshal.ReadIntPtr(collision.Entries, i * IntPtr.Size);
LSA_FOREST_TRUST_COLLISION_RECORD record = new LSA_FOREST_TRUST_COLLISION_RECORD();
Marshal.PtrToStructure(addr, record);
ForestTrustCollisionType type = record.Type;
string recordName = Marshal.PtrToStringUni(record.Name.Buffer, record.Name.Length / 2);
TopLevelNameCollisionOptions TLNFlag = TopLevelNameCollisionOptions.None;
DomainCollisionOptions domainFlag = DomainCollisionOptions.None;
if (type == ForestTrustCollisionType.TopLevelName)
{
TLNFlag = (TopLevelNameCollisionOptions)record.Flags;
}
else if (type == ForestTrustCollisionType.Domain)
{
domainFlag = (DomainCollisionOptions)record.Flags;
}
ForestTrustRelationshipCollision tmp = new ForestTrustRelationshipCollision(type, TLNFlag, domainFlag, recordName);
collection.Add(tmp);
}
ForestTrustCollisionException exception = new ForestTrustCollisionException(SR.ForestTrustCollision, null, collection);
return exception;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Insights
{
using Azure;
using Rest;
using Rest.Azure;
using Rest.Serialization;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
/// <summary>
/// Composite Swagger for Monitor Client
/// </summary>
public partial class MonitorClient : ServiceClient<MonitorClient>, IMonitorClient, IAzureClient
{
/// <summary>
/// The base URI of the service.
/// </summary>
public System.Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Credentials needed for the client to connect to Azure.
/// </summary>
public ServiceClientCredentials Credentials { get; private set; }
/// <summary>
/// The Azure subscription Id.
/// </summary>
public string SubscriptionId { get; set; }
/// <summary>
/// Gets or sets the preferred language for the response.
/// </summary>
public string AcceptLanguage { get; set; }
/// <summary>
/// Gets or sets the retry timeout in seconds for Long Running Operations.
/// Default value is 30.
/// </summary>
public int? LongRunningOperationRetryTimeout { get; set; }
/// <summary>
/// When set to true a unique x-ms-client-request-id value is generated and
/// included in each request. Default is true.
/// </summary>
public bool? GenerateClientRequestId { get; set; }
/// <summary>
/// Gets the IUsageMetricsOperations.
/// </summary>
public virtual IUsageMetricsOperations UsageMetrics { get; private set; }
/// <summary>
/// Gets the IEventCategoriesOperations.
/// </summary>
public virtual IEventCategoriesOperations EventCategories { get; private set; }
/// <summary>
/// Gets the IActivityLogsOperations.
/// </summary>
public virtual IActivityLogsOperations ActivityLogs { get; private set; }
/// <summary>
/// Gets the ITenantActivityLogsOperations.
/// </summary>
public virtual ITenantActivityLogsOperations TenantActivityLogs { get; private set; }
/// <summary>
/// Gets the IMetricDefinitionsOperations.
/// </summary>
public virtual IMetricDefinitionsOperations MetricDefinitions { get; private set; }
/// <summary>
/// Gets the IMetricsOperations.
/// </summary>
public virtual IMetricsOperations Metrics { get; private set; }
/// <summary>
/// Initializes a new instance of the MonitorClient class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected MonitorClient(params System.Net.Http.DelegatingHandler[] handlers) : base(handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the MonitorClient class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected MonitorClient(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the MonitorClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected MonitorClient(System.Uri baseUri, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the MonitorClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected MonitorClient(System.Uri baseUri, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the MonitorClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public MonitorClient(ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the MonitorClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public MonitorClient(ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the MonitorClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public MonitorClient(System.Uri baseUri, ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
BaseUri = baseUri;
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the MonitorClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public MonitorClient(System.Uri baseUri, ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
BaseUri = baseUri;
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// An optional partial-method to perform custom initialization.
/// </summary>
partial void CustomInitialize();
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
UsageMetrics = new UsageMetricsOperations(this);
EventCategories = new EventCategoriesOperations(this);
ActivityLogs = new ActivityLogsOperations(this);
TenantActivityLogs = new TenantActivityLogsOperations(this);
MetricDefinitions = new MetricDefinitionsOperations(this);
Metrics = new MetricsOperations(this);
BaseUri = new System.Uri("https://management.azure.com");
AcceptLanguage = "en-US";
LongRunningOperationRetryTimeout = 30;
GenerateClientRequestId = true;
SerializationSettings = new JsonSerializerSettings
{
Formatting = Formatting.Indented,
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
DeserializationSettings = new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
CustomInitialize();
DeserializationSettings.Converters.Add(new CloudErrorJsonConverter());
}
}
}
| |
using System.Collections.Generic;
using Avalonia.Input;
using Avalonia.Win32.Interop;
namespace Avalonia.Win32.Input
{
static class KeyInterop
{
private static readonly Dictionary<Key, int> s_virtualKeyFromKey = new Dictionary<Key, int>
{
{ Key.None, 0 },
{ Key.Cancel, 3 },
{ Key.Back, 8 },
{ Key.Tab, 9 },
{ Key.LineFeed, 0 },
{ Key.Clear, 12 },
{ Key.Return, 13 },
{ Key.Pause, 19 },
{ Key.Capital, 20 },
{ Key.KanaMode, 21 },
{ Key.JunjaMode, 23 },
{ Key.FinalMode, 24 },
{ Key.HanjaMode, 25 },
{ Key.Escape, 27 },
{ Key.ImeConvert, 28 },
{ Key.ImeNonConvert, 29 },
{ Key.ImeAccept, 30 },
{ Key.ImeModeChange, 31 },
{ Key.Space, 32 },
{ Key.PageUp, 33 },
{ Key.Next, 34 },
{ Key.End, 35 },
{ Key.Home, 36 },
{ Key.Left, 37 },
{ Key.Up, 38 },
{ Key.Right, 39 },
{ Key.Down, 40 },
{ Key.Select, 41 },
{ Key.Print, 42 },
{ Key.Execute, 43 },
{ Key.Snapshot, 44 },
{ Key.Insert, 45 },
{ Key.Delete, 46 },
{ Key.Help, 47 },
{ Key.D0, 48 },
{ Key.D1, 49 },
{ Key.D2, 50 },
{ Key.D3, 51 },
{ Key.D4, 52 },
{ Key.D5, 53 },
{ Key.D6, 54 },
{ Key.D7, 55 },
{ Key.D8, 56 },
{ Key.D9, 57 },
{ Key.A, 65 },
{ Key.B, 66 },
{ Key.C, 67 },
{ Key.D, 68 },
{ Key.E, 69 },
{ Key.F, 70 },
{ Key.G, 71 },
{ Key.H, 72 },
{ Key.I, 73 },
{ Key.J, 74 },
{ Key.K, 75 },
{ Key.L, 76 },
{ Key.M, 77 },
{ Key.N, 78 },
{ Key.O, 79 },
{ Key.P, 80 },
{ Key.Q, 81 },
{ Key.R, 82 },
{ Key.S, 83 },
{ Key.T, 84 },
{ Key.U, 85 },
{ Key.V, 86 },
{ Key.W, 87 },
{ Key.X, 88 },
{ Key.Y, 89 },
{ Key.Z, 90 },
{ Key.LWin, 91 },
{ Key.RWin, 92 },
{ Key.Apps, 93 },
{ Key.Sleep, 95 },
{ Key.NumPad0, 96 },
{ Key.NumPad1, 97 },
{ Key.NumPad2, 98 },
{ Key.NumPad3, 99 },
{ Key.NumPad4, 100 },
{ Key.NumPad5, 101 },
{ Key.NumPad6, 102 },
{ Key.NumPad7, 103 },
{ Key.NumPad8, 104 },
{ Key.NumPad9, 105 },
{ Key.Multiply, 106 },
{ Key.Add, 107 },
{ Key.Separator, 108 },
{ Key.Subtract, 109 },
{ Key.Decimal, 110 },
{ Key.Divide, 111 },
{ Key.F1, 112 },
{ Key.F2, 113 },
{ Key.F3, 114 },
{ Key.F4, 115 },
{ Key.F5, 116 },
{ Key.F6, 117 },
{ Key.F7, 118 },
{ Key.F8, 119 },
{ Key.F9, 120 },
{ Key.F10, 121 },
{ Key.F11, 122 },
{ Key.F12, 123 },
{ Key.F13, 124 },
{ Key.F14, 125 },
{ Key.F15, 126 },
{ Key.F16, 127 },
{ Key.F17, 128 },
{ Key.F18, 129 },
{ Key.F19, 130 },
{ Key.F20, 131 },
{ Key.F21, 132 },
{ Key.F22, 133 },
{ Key.F23, 134 },
{ Key.F24, 135 },
{ Key.NumLock, 144 },
{ Key.Scroll, 145 },
{ Key.LeftShift, 160 },
{ Key.RightShift, 161 },
{ Key.LeftCtrl, 162 },
{ Key.RightCtrl, 163 },
{ Key.LeftAlt, 164 },
{ Key.RightAlt, 165 },
{ Key.BrowserBack, 166 },
{ Key.BrowserForward, 167 },
{ Key.BrowserRefresh, 168 },
{ Key.BrowserStop, 169 },
{ Key.BrowserSearch, 170 },
{ Key.BrowserFavorites, 171 },
{ Key.BrowserHome, 172 },
{ Key.VolumeMute, 173 },
{ Key.VolumeDown, 174 },
{ Key.VolumeUp, 175 },
{ Key.MediaNextTrack, 176 },
{ Key.MediaPreviousTrack, 177 },
{ Key.MediaStop, 178 },
{ Key.MediaPlayPause, 179 },
{ Key.LaunchMail, 180 },
{ Key.SelectMedia, 181 },
{ Key.LaunchApplication1, 182 },
{ Key.LaunchApplication2, 183 },
{ Key.Oem1, 186 },
{ Key.OemPlus, 187 },
{ Key.OemComma, 188 },
{ Key.OemMinus, 189 },
{ Key.OemPeriod, 190 },
{ Key.OemQuestion, 191 },
{ Key.Oem3, 192 },
{ Key.AbntC1, 193 },
{ Key.AbntC2, 194 },
{ Key.OemOpenBrackets, 219 },
{ Key.Oem5, 220 },
{ Key.Oem6, 221 },
{ Key.OemQuotes, 222 },
{ Key.Oem8, 223 },
{ Key.OemBackslash, 226 },
{ Key.ImeProcessed, 229 },
{ Key.System, 0 },
{ Key.OemAttn, 240 },
{ Key.OemFinish, 241 },
{ Key.OemCopy, 242 },
{ Key.DbeSbcsChar, 243 },
{ Key.OemEnlw, 244 },
{ Key.OemBackTab, 245 },
{ Key.DbeNoRoman, 246 },
{ Key.DbeEnterWordRegisterMode, 247 },
{ Key.DbeEnterImeConfigureMode, 248 },
{ Key.EraseEof, 249 },
{ Key.Play, 250 },
{ Key.DbeNoCodeInput, 251 },
{ Key.NoName, 252 },
{ Key.Pa1, 253 },
{ Key.OemClear, 254 },
{ Key.DeadCharProcessed, 0 },
};
private static readonly Dictionary<int, Key> s_keyFromVirtualKey = new Dictionary<int, Key>
{
{ 0, Key.None },
{ 3, Key.Cancel },
{ 8, Key.Back },
{ 9, Key.Tab },
{ 12, Key.Clear },
{ 13, Key.Return },
{ 16, Key.LeftShift},
{ 17, Key.LeftCtrl},
{ 18, Key.LeftAlt },
{ 19, Key.Pause },
{ 20, Key.Capital },
{ 21, Key.KanaMode },
{ 23, Key.JunjaMode },
{ 24, Key.FinalMode },
{ 25, Key.HanjaMode },
{ 27, Key.Escape },
{ 28, Key.ImeConvert },
{ 29, Key.ImeNonConvert },
{ 30, Key.ImeAccept },
{ 31, Key.ImeModeChange },
{ 32, Key.Space },
{ 33, Key.PageUp },
{ 34, Key.PageDown },
{ 35, Key.End },
{ 36, Key.Home },
{ 37, Key.Left },
{ 38, Key.Up },
{ 39, Key.Right },
{ 40, Key.Down },
{ 41, Key.Select },
{ 42, Key.Print },
{ 43, Key.Execute },
{ 44, Key.Snapshot },
{ 45, Key.Insert },
{ 46, Key.Delete },
{ 47, Key.Help },
{ 48, Key.D0 },
{ 49, Key.D1 },
{ 50, Key.D2 },
{ 51, Key.D3 },
{ 52, Key.D4 },
{ 53, Key.D5 },
{ 54, Key.D6 },
{ 55, Key.D7 },
{ 56, Key.D8 },
{ 57, Key.D9 },
{ 65, Key.A },
{ 66, Key.B },
{ 67, Key.C },
{ 68, Key.D },
{ 69, Key.E },
{ 70, Key.F },
{ 71, Key.G },
{ 72, Key.H },
{ 73, Key.I },
{ 74, Key.J },
{ 75, Key.K },
{ 76, Key.L },
{ 77, Key.M },
{ 78, Key.N },
{ 79, Key.O },
{ 80, Key.P },
{ 81, Key.Q },
{ 82, Key.R },
{ 83, Key.S },
{ 84, Key.T },
{ 85, Key.U },
{ 86, Key.V },
{ 87, Key.W },
{ 88, Key.X },
{ 89, Key.Y },
{ 90, Key.Z },
{ 91, Key.LWin },
{ 92, Key.RWin },
{ 93, Key.Apps },
{ 95, Key.Sleep },
{ 96, Key.NumPad0 },
{ 97, Key.NumPad1 },
{ 98, Key.NumPad2 },
{ 99, Key.NumPad3 },
{ 100, Key.NumPad4 },
{ 101, Key.NumPad5 },
{ 102, Key.NumPad6 },
{ 103, Key.NumPad7 },
{ 104, Key.NumPad8 },
{ 105, Key.NumPad9 },
{ 106, Key.Multiply },
{ 107, Key.Add },
{ 108, Key.Separator },
{ 109, Key.Subtract },
{ 110, Key.Decimal },
{ 111, Key.Divide },
{ 112, Key.F1 },
{ 113, Key.F2 },
{ 114, Key.F3 },
{ 115, Key.F4 },
{ 116, Key.F5 },
{ 117, Key.F6 },
{ 118, Key.F7 },
{ 119, Key.F8 },
{ 120, Key.F9 },
{ 121, Key.F10 },
{ 122, Key.F11 },
{ 123, Key.F12 },
{ 124, Key.F13 },
{ 125, Key.F14 },
{ 126, Key.F15 },
{ 127, Key.F16 },
{ 128, Key.F17 },
{ 129, Key.F18 },
{ 130, Key.F19 },
{ 131, Key.F20 },
{ 132, Key.F21 },
{ 133, Key.F22 },
{ 134, Key.F23 },
{ 135, Key.F24 },
{ 144, Key.NumLock },
{ 145, Key.Scroll },
{ 160, Key.LeftShift },
{ 161, Key.RightShift },
{ 162, Key.LeftCtrl },
{ 163, Key.RightCtrl },
{ 164, Key.LeftAlt },
{ 165, Key.RightAlt },
{ 166, Key.BrowserBack },
{ 167, Key.BrowserForward },
{ 168, Key.BrowserRefresh },
{ 169, Key.BrowserStop },
{ 170, Key.BrowserSearch },
{ 171, Key.BrowserFavorites },
{ 172, Key.BrowserHome },
{ 173, Key.VolumeMute },
{ 174, Key.VolumeDown },
{ 175, Key.VolumeUp },
{ 176, Key.MediaNextTrack },
{ 177, Key.MediaPreviousTrack },
{ 178, Key.MediaStop },
{ 179, Key.MediaPlayPause },
{ 180, Key.LaunchMail },
{ 181, Key.SelectMedia },
{ 182, Key.LaunchApplication1 },
{ 183, Key.LaunchApplication2 },
{ 186, Key.Oem1 },
{ 187, Key.OemPlus },
{ 188, Key.OemComma },
{ 189, Key.OemMinus },
{ 190, Key.OemPeriod },
{ 191, Key.OemQuestion },
{ 192, Key.Oem3 },
{ 193, Key.AbntC1 },
{ 194, Key.AbntC2 },
{ 219, Key.OemOpenBrackets },
{ 220, Key.Oem5 },
{ 221, Key.Oem6 },
{ 222, Key.OemQuotes },
{ 223, Key.Oem8 },
{ 226, Key.OemBackslash },
{ 229, Key.ImeProcessed },
{ 240, Key.OemAttn },
{ 241, Key.OemFinish },
{ 242, Key.OemCopy },
{ 243, Key.DbeSbcsChar },
{ 244, Key.OemEnlw },
{ 245, Key.OemBackTab },
{ 246, Key.DbeNoRoman },
{ 247, Key.DbeEnterWordRegisterMode },
{ 248, Key.DbeEnterImeConfigureMode },
{ 249, Key.EraseEof },
{ 250, Key.Play },
{ 251, Key.DbeNoCodeInput },
{ 252, Key.NoName },
{ 253, Key.Pa1 },
{ 254, Key.OemClear },
};
/// <summary>
/// Indicates whether the key is an extended key, such as the right-hand ALT and CTRL keys.
/// According to https://docs.microsoft.com/en-us/windows/win32/inputdev/wm-keydown.
/// </summary>
private static bool IsExtended(int keyData)
{
const int extendedMask = 1 << 24;
return (keyData & extendedMask) != 0;
}
private static int GetVirtualKey(int virtualKey, int keyData)
{
// Adapted from https://github.com/dotnet/wpf/blob/master/src/Microsoft.DotNet.Wpf/src/PresentationCore/System/Windows/InterOp/HwndKeyboardInputProvider.cs.
if (virtualKey == (int)UnmanagedMethods.VirtualKeyStates.VK_SHIFT)
{
// Bits from 16 to 23 represent scan code.
const int scanCodeMask = 0xFF0000;
var scanCode = (keyData & scanCodeMask) >> 16;
virtualKey = (int)UnmanagedMethods.MapVirtualKey((uint)scanCode, (uint)UnmanagedMethods.MapVirtualKeyMapTypes.MAPVK_VSC_TO_VK_EX);
if (virtualKey == 0)
{
virtualKey = (int)UnmanagedMethods.VirtualKeyStates.VK_LSHIFT;
}
}
if (virtualKey == (int)UnmanagedMethods.VirtualKeyStates.VK_MENU)
{
bool isRight = IsExtended(keyData);
if (isRight)
{
virtualKey = (int)UnmanagedMethods.VirtualKeyStates.VK_RMENU;
}
else
{
virtualKey = (int)UnmanagedMethods.VirtualKeyStates.VK_LMENU;
}
}
if (virtualKey == (int)UnmanagedMethods.VirtualKeyStates.VK_CONTROL)
{
bool isRight = IsExtended(keyData);
if (isRight)
{
virtualKey = (int)UnmanagedMethods.VirtualKeyStates.VK_RCONTROL;
}
else
{
virtualKey = (int)UnmanagedMethods.VirtualKeyStates.VK_LCONTROL;
}
}
return virtualKey;
}
public static Key KeyFromVirtualKey(int virtualKey, int keyData)
{
virtualKey = GetVirtualKey(virtualKey, keyData);
s_keyFromVirtualKey.TryGetValue(virtualKey, out var result);
return result;
}
public static int VirtualKeyFromKey(Key key)
{
s_virtualKeyFromKey.TryGetValue(key, out var result);
return result;
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="TemplateControlCodeDomTreeGenerator.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.Compilation {
using System;
using System.Collections;
using System.Reflection;
using System.ComponentModel;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Globalization;
using System.Web.UI;
using System.Web.Util;
using Debug=System.Web.Util.Debug;
internal abstract class TemplateControlCodeDomTreeGenerator : BaseTemplateCodeDomTreeGenerator {
private const string stringResourcePointerName = "__stringResource";
private TemplateControlParser _tcParser;
private TemplateControlParser Parser { get { return _tcParser; } }
private const string literalMemoryBlockName = "__literals";
// This is used to detect incorrect base class in code beside scenarios. See usage for details.
internal const int badBaseClassLineMarker = 912304;
internal TemplateControlCodeDomTreeGenerator(TemplateControlParser tcParser) : base(tcParser) {
_tcParser = tcParser;
}
/*
* Build the default constructor
*/
protected override void BuildInitStatements(CodeStatementCollection trueStatements, CodeStatementCollection topLevelStatements) {
base.BuildInitStatements(trueStatements, topLevelStatements);
if (_stringResourceBuilder.HasStrings) {
// e.g. private static object __stringResource;
CodeMemberField stringResourcePointer = new CodeMemberField(typeof(Object), stringResourcePointerName);
stringResourcePointer.Attributes |= MemberAttributes.Static;
_sourceDataClass.Members.Add(stringResourcePointer);
// e.g. __stringResource = TemplateControl.ReadStringResource(typeof(__GeneratedType));
CodeAssignStatement readResource = new CodeAssignStatement();
readResource.Left = new CodeFieldReferenceExpression(_classTypeExpr,
stringResourcePointerName);
CodeMethodInvokeExpression methCallExpression = new CodeMethodInvokeExpression();
methCallExpression.Method.TargetObject = new CodeThisReferenceExpression();
methCallExpression.Method.MethodName = "ReadStringResource";
readResource.Right = methCallExpression;
trueStatements.Add(readResource);
}
//
// Set the AppRelativeVirtualPath
// e.g. ((System.Web.UI.Page)(this)).AppRelativeVirtualPath = "~/foo.aspx";
// Note that we generate an artificial cast to cause a compile error if the base class
// is incorrect (see below).
//
// Make sure the BuildAppRelativeVirtualPathProperty property is app independent, since
// in precompilation scenarios, we can't make an assumption on the app name.
// Use global:: to resolve types to avoid naming conflicts when user uses a class name
// in the global namespace that already exists, such as Login or ReportViewer (DevDiv 79336)
CodeTypeReference classTypeRef = CodeDomUtility.BuildGlobalCodeTypeReference(Parser.BaseType);
CodeAssignStatement setProp = new CodeAssignStatement(
new CodePropertyReferenceExpression(new CodeCastExpression(classTypeRef, new CodeThisReferenceExpression()), "AppRelativeVirtualPath"),
new CodePrimitiveExpression(Parser.CurrentVirtualPath.AppRelativeVirtualPathString));
// This line will fail to compile if the base class in the code beside is missing. Set
// a special line number on it to improve error handling (VSWhidbey 376977/468830)
if (!_designerMode && Parser.CodeFileVirtualPath != null) {
setProp.LinePragma = CreateCodeLinePragmaHelper(
Parser.CodeFileVirtualPath.VirtualPathString, badBaseClassLineMarker);
}
topLevelStatements.Add(setProp);
}
/*
* Build various properties, fields, methods
*/
protected override void BuildMiscClassMembers() {
base.BuildMiscClassMembers();
// Build the automatic event hookup code
if (!_designerMode)
BuildAutomaticEventHookup();
// Build the ApplicationInstance property
BuildApplicationInstanceProperty();
if (_designerMode) {
GenerateDummyBindMethodsAtDesignTime();
}
BuildSourceDataTreeFromBuilder(Parser.RootBuilder,
false /*fInTemplate*/, false /*topLevelTemplate*/, null /*pse*/);
if (!_designerMode)
BuildFrameworkInitializeMethod();
}
/*
* Build the strongly typed new property
*/
// e.g. public new {propertyType} Master { get { return ({propertyType})base.Master; } }
internal void BuildStronglyTypedProperty(string propertyName, Type propertyType) {
// VSWhidbey 321818.
// overriding method with same name is not allowed using J#.
if (_usingVJSCompiler) {
return;
}
CodeMemberProperty prop = new CodeMemberProperty();
prop.Attributes &= ~MemberAttributes.AccessMask;
prop.Attributes &= ~MemberAttributes.ScopeMask;
prop.Attributes |= MemberAttributes.Final | MemberAttributes.New | MemberAttributes.Public;
prop.Name = propertyName;
prop.Type = new CodeTypeReference(propertyType);
CodePropertyReferenceExpression propRef = new CodePropertyReferenceExpression(
new CodeBaseReferenceExpression(), propertyName);
prop.GetStatements.Add(new CodeMethodReturnStatement(new CodeCastExpression(propertyType, propRef)));
_intermediateClass.Members.Add(prop);
}
private void GenerateDummyBindMethodsAtDesignTime() {
// public string Bind(string expression,string format) {return String.Empty;}
GenerateBindMethod(addFormatParameter: true);
// public string Bind(string expression) {return String.Empty;}
GenerateBindMethod(addFormatParameter: false);
}
private void GenerateBindMethod(bool addFormatParameter) {
if (_sourceDataClass == null) {
return;
}
CodeMemberMethod bindMethod = new CodeMemberMethod();
bindMethod.Name = "Bind";
bindMethod.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "expression"));
if (addFormatParameter) {
bindMethod.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "format"));
}
bindMethod.ReturnType = new CodeTypeReference(typeof(string));
bindMethod.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(String.Empty)));
_sourceDataClass.Members.Add(bindMethod);
}
/*
* Build the data tree for the FrameworkInitialize method
*/
private void BuildFrameworkInitializeMethod() {
// Skip if we're only generating the intermediate class
if (_sourceDataClass == null)
return;
CodeMemberMethod method = new CodeMemberMethod();
AddDebuggerNonUserCodeAttribute(method);
method.Attributes &= ~MemberAttributes.AccessMask;
method.Attributes &= ~MemberAttributes.ScopeMask;
method.Attributes |= MemberAttributes.Override | MemberAttributes.Family;
method.Name = "FrameworkInitialize";
BuildFrameworkInitializeMethodContents(method);
// This line will fail to compile if the base class in the code beside is incorrect. Set
// a special line number on it to improve error handling (VSWhidbey 376977/468830)
if (!_designerMode && Parser.CodeFileVirtualPath != null) {
method.LinePragma = CreateCodeLinePragmaHelper(
Parser.CodeFileVirtualPath.VirtualPathString, badBaseClassLineMarker);
}
_sourceDataClass.Members.Add(method);
}
/*
* Build the contents of the FrameworkInitialize method
*/
protected virtual void BuildFrameworkInitializeMethodContents(CodeMemberMethod method) {
// Call the base FrameworkInitialize
CodeMethodInvokeExpression baseCallExpression = new CodeMethodInvokeExpression(
new CodeBaseReferenceExpression(), method.Name);
method.Statements.Add(new CodeExpressionStatement(baseCallExpression));
// No strings: don't do anything
if (_stringResourceBuilder.HasStrings) {
// e.g. SetStringResourcePointer(__stringResource, 0);
CodeMethodInvokeExpression methCallExpression = new CodeMethodInvokeExpression(
new CodeThisReferenceExpression(), "SetStringResourcePointer");
methCallExpression.Parameters.Add(new CodeFieldReferenceExpression(
_classTypeExpr, stringResourcePointerName));
// Pass 0 for the maxResourceOffset, since it's being ignored
methCallExpression.Parameters.Add(new CodePrimitiveExpression(0));
method.Statements.Add(new CodeExpressionStatement(methCallExpression));
}
CodeMethodInvokeExpression call = new CodeMethodInvokeExpression();
call.Method.TargetObject = new CodeThisReferenceExpression();
call.Method.MethodName = "__BuildControlTree";
call.Parameters.Add(new CodeThisReferenceExpression());
method.Statements.Add(new CodeExpressionStatement(call));
}
/*
* Build the automatic event hookup code
*/
private void BuildAutomaticEventHookup() {
// Skip if we're only generating the intermediate class
if (_sourceDataClass == null)
return;
CodeMemberProperty prop;
// If FAutoEventWireup is turned off, generate a SupportAutoEvents prop that
// returns false.
if (!Parser.FAutoEventWireup) {
prop = new CodeMemberProperty();
prop.Attributes &= ~MemberAttributes.AccessMask;
prop.Attributes &= ~MemberAttributes.ScopeMask;
prop.Attributes |= MemberAttributes.Override | MemberAttributes.Family;
prop.Name = "SupportAutoEvents";
prop.Type = new CodeTypeReference(typeof(bool));
prop.GetStatements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(false)));
_sourceDataClass.Members.Add(prop);
return;
}
}
/*
* Build the ApplicationInstance property
*/
private void BuildApplicationInstanceProperty() {
CodeMemberProperty prop;
Type appType = BuildManager.GetGlobalAsaxType();
prop = new CodeMemberProperty();
prop.Attributes &= ~MemberAttributes.AccessMask;
prop.Attributes &= ~MemberAttributes.ScopeMask;
prop.Attributes |= MemberAttributes.Final | MemberAttributes.Family;
if (_designerMode) {
ApplyEditorBrowsableCustomAttribute(prop);
}
prop.Name = "ApplicationInstance";
prop.Type = new CodeTypeReference(appType);
CodePropertyReferenceExpression propRef = new CodePropertyReferenceExpression(
new CodeThisReferenceExpression(), "Context");
propRef = new CodePropertyReferenceExpression(propRef, "ApplicationInstance");
prop.GetStatements.Add(new CodeMethodReturnStatement(new CodeCastExpression(
appType, propRef)));
_intermediateClass.Members.Add(prop);
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Impl.Binary
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Common;
using Apache.Ignite.Core.Impl.Binary.IO;
using Apache.Ignite.Core.Impl.Binary.Structure;
using Apache.Ignite.Core.Impl.Common;
/// <summary>
/// Binary reader implementation.
/// </summary>
internal class BinaryReader : IBinaryReader, IBinaryRawReader
{
/** Marshaller. */
private readonly Marshaller _marsh;
/** Parent builder. */
private readonly BinaryObjectBuilder _builder;
/** Handles. */
private BinaryReaderHandleDictionary _hnds;
/** Detach flag. */
private bool _detach;
/** Binary read mode. */
private BinaryMode _mode;
/** Current frame. */
private Frame _frame;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="marsh">Marshaller.</param>
/// <param name="stream">Input stream.</param>
/// <param name="mode">The mode.</param>
/// <param name="builder">Builder.</param>
public BinaryReader
(Marshaller marsh,
IBinaryStream stream,
BinaryMode mode,
BinaryObjectBuilder builder)
{
_marsh = marsh;
_mode = mode;
_builder = builder;
_frame.Pos = stream.Position;
Stream = stream;
}
/// <summary>
/// Gets the marshaller.
/// </summary>
public Marshaller Marshaller
{
get { return _marsh; }
}
/// <summary>
/// Gets the mode.
/// </summary>
public BinaryMode Mode
{
get { return _mode; }
}
/** <inheritdoc /> */
public IBinaryRawReader GetRawReader()
{
MarkRaw();
return this;
}
/** <inheritdoc /> */
public bool ReadBoolean(string fieldName)
{
return ReadField(fieldName, r => r.ReadBoolean(), BinaryTypeId.Bool);
}
/** <inheritdoc /> */
public bool ReadBoolean()
{
return Stream.ReadBool();
}
/** <inheritdoc /> */
public bool[] ReadBooleanArray(string fieldName)
{
return ReadField(fieldName, BinaryUtils.ReadBooleanArray, BinaryTypeId.ArrayBool);
}
/** <inheritdoc /> */
public bool[] ReadBooleanArray()
{
return Read(BinaryUtils.ReadBooleanArray, BinaryTypeId.ArrayBool);
}
/** <inheritdoc /> */
public byte ReadByte(string fieldName)
{
return ReadField(fieldName, ReadByte, BinaryTypeId.Byte);
}
/** <inheritdoc /> */
public byte ReadByte()
{
return Stream.ReadByte();
}
/** <inheritdoc /> */
public byte[] ReadByteArray(string fieldName)
{
return ReadField(fieldName, BinaryUtils.ReadByteArray, BinaryTypeId.ArrayByte);
}
/** <inheritdoc /> */
public byte[] ReadByteArray()
{
return Read(BinaryUtils.ReadByteArray, BinaryTypeId.ArrayByte);
}
/** <inheritdoc /> */
public short ReadShort(string fieldName)
{
return ReadField(fieldName, ReadShort, BinaryTypeId.Short);
}
/** <inheritdoc /> */
public short ReadShort()
{
return Stream.ReadShort();
}
/** <inheritdoc /> */
public short[] ReadShortArray(string fieldName)
{
return ReadField(fieldName, BinaryUtils.ReadShortArray, BinaryTypeId.ArrayShort);
}
/** <inheritdoc /> */
public short[] ReadShortArray()
{
return Read(BinaryUtils.ReadShortArray, BinaryTypeId.ArrayShort);
}
/** <inheritdoc /> */
public char ReadChar(string fieldName)
{
return ReadField(fieldName, ReadChar, BinaryTypeId.Char);
}
/** <inheritdoc /> */
public char ReadChar()
{
return Stream.ReadChar();
}
/** <inheritdoc /> */
public char[] ReadCharArray(string fieldName)
{
return ReadField(fieldName, BinaryUtils.ReadCharArray, BinaryTypeId.ArrayChar);
}
/** <inheritdoc /> */
public char[] ReadCharArray()
{
return Read(BinaryUtils.ReadCharArray, BinaryTypeId.ArrayChar);
}
/** <inheritdoc /> */
public int ReadInt(string fieldName)
{
return ReadField(fieldName, ReadInt, BinaryTypeId.Int);
}
/** <inheritdoc /> */
public int ReadInt()
{
return Stream.ReadInt();
}
/** <inheritdoc /> */
public int[] ReadIntArray(string fieldName)
{
return ReadField(fieldName, BinaryUtils.ReadIntArray, BinaryTypeId.ArrayInt);
}
/** <inheritdoc /> */
public int[] ReadIntArray()
{
return Read(BinaryUtils.ReadIntArray, BinaryTypeId.ArrayInt);
}
/** <inheritdoc /> */
public long ReadLong(string fieldName)
{
return ReadField(fieldName, ReadLong, BinaryTypeId.Long);
}
/** <inheritdoc /> */
public long ReadLong()
{
return Stream.ReadLong();
}
/** <inheritdoc /> */
public long[] ReadLongArray(string fieldName)
{
return ReadField(fieldName, BinaryUtils.ReadLongArray, BinaryTypeId.ArrayLong);
}
/** <inheritdoc /> */
public long[] ReadLongArray()
{
return Read(BinaryUtils.ReadLongArray, BinaryTypeId.ArrayLong);
}
/** <inheritdoc /> */
public float ReadFloat(string fieldName)
{
return ReadField(fieldName, ReadFloat, BinaryTypeId.Float);
}
/** <inheritdoc /> */
public float ReadFloat()
{
return Stream.ReadFloat();
}
/** <inheritdoc /> */
public float[] ReadFloatArray(string fieldName)
{
return ReadField(fieldName, BinaryUtils.ReadFloatArray, BinaryTypeId.ArrayFloat);
}
/** <inheritdoc /> */
public float[] ReadFloatArray()
{
return Read(BinaryUtils.ReadFloatArray, BinaryTypeId.ArrayFloat);
}
/** <inheritdoc /> */
public double ReadDouble(string fieldName)
{
return ReadField(fieldName, ReadDouble, BinaryTypeId.Double);
}
/** <inheritdoc /> */
public double ReadDouble()
{
return Stream.ReadDouble();
}
/** <inheritdoc /> */
public double[] ReadDoubleArray(string fieldName)
{
return ReadField(fieldName, BinaryUtils.ReadDoubleArray, BinaryTypeId.ArrayDouble);
}
/** <inheritdoc /> */
public double[] ReadDoubleArray()
{
return Read(BinaryUtils.ReadDoubleArray, BinaryTypeId.ArrayDouble);
}
/** <inheritdoc /> */
public decimal? ReadDecimal(string fieldName)
{
return ReadField(fieldName, BinaryUtils.ReadDecimal, BinaryTypeId.Decimal);
}
/** <inheritdoc /> */
public decimal? ReadDecimal()
{
return Read(BinaryUtils.ReadDecimal, BinaryTypeId.Decimal);
}
/** <inheritdoc /> */
public decimal?[] ReadDecimalArray(string fieldName)
{
return ReadField(fieldName, BinaryUtils.ReadDecimalArray, BinaryTypeId.ArrayDecimal);
}
/** <inheritdoc /> */
public decimal?[] ReadDecimalArray()
{
return Read(BinaryUtils.ReadDecimalArray, BinaryTypeId.ArrayDecimal);
}
/** <inheritdoc /> */
public DateTime? ReadTimestamp(string fieldName)
{
return ReadField(fieldName, BinaryUtils.ReadTimestamp, BinaryTypeId.Timestamp);
}
/** <inheritdoc /> */
public DateTime? ReadTimestamp()
{
return Read(BinaryUtils.ReadTimestamp, BinaryTypeId.Timestamp);
}
/** <inheritdoc /> */
public DateTime?[] ReadTimestampArray(string fieldName)
{
return ReadField(fieldName, BinaryUtils.ReadTimestampArray, BinaryTypeId.ArrayTimestamp);
}
/** <inheritdoc /> */
public DateTime?[] ReadTimestampArray()
{
return Read(BinaryUtils.ReadTimestampArray, BinaryTypeId.ArrayTimestamp);
}
/** <inheritdoc /> */
public string ReadString(string fieldName)
{
return ReadField(fieldName, BinaryUtils.ReadString, BinaryTypeId.String);
}
/** <inheritdoc /> */
public string ReadString()
{
return Read(BinaryUtils.ReadString, BinaryTypeId.String);
}
/** <inheritdoc /> */
public string[] ReadStringArray(string fieldName)
{
return ReadField(fieldName, r => BinaryUtils.ReadArray<string>(r, false), BinaryTypeId.ArrayString);
}
/** <inheritdoc /> */
public string[] ReadStringArray()
{
return Read(r => BinaryUtils.ReadArray<string>(r, false), BinaryTypeId.ArrayString);
}
/** <inheritdoc /> */
public Guid? ReadGuid(string fieldName)
{
return ReadField<Guid?>(fieldName, r => BinaryUtils.ReadGuid(r), BinaryTypeId.Guid);
}
/** <inheritdoc /> */
public Guid? ReadGuid()
{
return Read<Guid?>(r => BinaryUtils.ReadGuid(r), BinaryTypeId.Guid);
}
/** <inheritdoc /> */
public Guid?[] ReadGuidArray(string fieldName)
{
return ReadField(fieldName, r => BinaryUtils.ReadArray<Guid?>(r, false), BinaryTypeId.ArrayGuid);
}
/** <inheritdoc /> */
public Guid?[] ReadGuidArray()
{
return Read(r => BinaryUtils.ReadArray<Guid?>(r, false), BinaryTypeId.ArrayGuid);
}
/** <inheritdoc /> */
public T ReadEnum<T>(string fieldName)
{
return SeekField(fieldName) ? ReadEnum<T>() : default(T);
}
/** <inheritdoc /> */
public T ReadEnum<T>()
{
var hdr = ReadByte();
switch (hdr)
{
case BinaryUtils.HdrNull:
return default(T);
case BinaryTypeId.Enum:
return ReadEnum0<T>(this, _mode == BinaryMode.ForceBinary);
case BinaryTypeId.BinaryEnum:
return ReadEnum0<T>(this, _mode != BinaryMode.Deserialize);
case BinaryUtils.HdrFull:
// Unregistered enum written as serializable
Stream.Seek(-1, SeekOrigin.Current);
return ReadObject<T>();
default:
throw new BinaryObjectException(string.Format(
"Invalid header on enum deserialization. Expected: {0} or {1} or {2} but was: {3}",
BinaryTypeId.Enum, BinaryTypeId.BinaryEnum, BinaryUtils.HdrFull, hdr));
}
}
/** <inheritdoc /> */
public T[] ReadEnumArray<T>(string fieldName)
{
return ReadField(fieldName, r => BinaryUtils.ReadArray<T>(r, true), BinaryTypeId.ArrayEnum);
}
/** <inheritdoc /> */
public T[] ReadEnumArray<T>()
{
return Read(r => BinaryUtils.ReadArray<T>(r, true), BinaryTypeId.ArrayEnum);
}
/** <inheritdoc /> */
public T ReadObject<T>(string fieldName)
{
if (_frame.Raw)
throw new BinaryObjectException("Cannot read named fields after raw data is read.");
if (SeekField(fieldName))
return Deserialize<T>();
return default(T);
}
/** <inheritdoc /> */
public T ReadObject<T>()
{
return Deserialize<T>();
}
/** <inheritdoc /> */
public T[] ReadArray<T>(string fieldName)
{
return ReadField(fieldName, r => BinaryUtils.ReadArray<T>(r, true), BinaryTypeId.Array);
}
/** <inheritdoc /> */
public T[] ReadArray<T>()
{
return Read(r => BinaryUtils.ReadArray<T>(r, true), BinaryTypeId.Array);
}
/** <inheritdoc /> */
public ICollection ReadCollection(string fieldName)
{
return ReadCollection(fieldName, null, null);
}
/** <inheritdoc /> */
public ICollection ReadCollection()
{
return ReadCollection(null, null);
}
/** <inheritdoc /> */
public ICollection ReadCollection(string fieldName, Func<int, ICollection> factory,
Action<ICollection, object> adder)
{
return ReadField(fieldName, r => BinaryUtils.ReadCollection(r, factory, adder), BinaryTypeId.Collection);
}
/** <inheritdoc /> */
public ICollection ReadCollection(Func<int, ICollection> factory, Action<ICollection, object> adder)
{
return Read(r => BinaryUtils.ReadCollection(r, factory, adder), BinaryTypeId.Collection);
}
/** <inheritdoc /> */
public IDictionary ReadDictionary(string fieldName)
{
return ReadDictionary(fieldName, null);
}
/** <inheritdoc /> */
public IDictionary ReadDictionary()
{
return ReadDictionary((Func<int, IDictionary>) null);
}
/** <inheritdoc /> */
public IDictionary ReadDictionary(string fieldName, Func<int, IDictionary> factory)
{
return ReadField(fieldName, r => BinaryUtils.ReadDictionary(r, factory), BinaryTypeId.Dictionary);
}
/** <inheritdoc /> */
public IDictionary ReadDictionary(Func<int, IDictionary> factory)
{
return Read(r => BinaryUtils.ReadDictionary(r, factory), BinaryTypeId.Dictionary);
}
/// <summary>
/// Enable detach mode for the next object read.
/// </summary>
public BinaryReader DetachNext()
{
_detach = true;
return this;
}
/// <summary>
/// Deserialize object.
/// </summary>
/// <param name="typeOverride">The type override.
/// There can be multiple versions of the same type when peer assembly loading is enabled.
/// Only first one is registered in Marshaller.
/// This parameter specifies exact type to be instantiated.</param>
/// <returns>Deserialized object.</returns>
public T Deserialize<T>(Type typeOverride = null)
{
T res;
// ReSharper disable once CompareNonConstrainedGenericWithNull
if (!TryDeserialize(out res, typeOverride) && default(T) != null)
throw new BinaryObjectException(string.Format("Invalid data on deserialization. " +
"Expected: '{0}' But was: null", typeof (T)));
return res;
}
/// <summary>
/// Deserialize object.
/// </summary>
/// <param name="res">Deserialized object.</param>
/// <param name="typeOverride">The type override.
/// There can be multiple versions of the same type when peer assembly loading is enabled.
/// Only first one is registered in Marshaller.
/// This parameter specifies exact type to be instantiated.</param>
/// <returns>
/// Deserialized object.
/// </returns>
public bool TryDeserialize<T>(out T res, Type typeOverride = null)
{
int pos = Stream.Position;
byte hdr = Stream.ReadByte();
var doDetach = _detach; // save detach flag into a var and reset so it does not go deeper
_detach = false;
switch (hdr)
{
case BinaryUtils.HdrNull:
res = default(T);
return false;
case BinaryUtils.HdrHnd:
res = ReadHandleObject<T>(pos, typeOverride);
return true;
case BinaryUtils.HdrFull:
res = ReadFullObject<T>(pos, typeOverride);
return true;
case BinaryTypeId.Binary:
res = ReadBinaryObject<T>(doDetach);
return true;
case BinaryTypeId.Enum:
res = ReadEnum0<T>(this, _mode == BinaryMode.ForceBinary);
return true;
case BinaryTypeId.BinaryEnum:
res = ReadEnum0<T>(this, _mode != BinaryMode.Deserialize);
return true;
}
if (BinarySystemHandlers.TryReadSystemType(hdr, this, out res))
return true;
throw new BinaryObjectException("Invalid header on deserialization [pos=" + pos + ", hdr=" + hdr + ']');
}
/// <summary>
/// Gets the flag indicating that there is custom type information in raw region.
/// </summary>
public bool GetCustomTypeDataFlag()
{
return _frame.Hdr.IsCustomDotNetType;
}
/// <summary>
/// Reads the binary object.
/// </summary>
private T ReadBinaryObject<T>(bool doDetach)
{
var len = Stream.ReadInt();
var binaryBytesPos = Stream.Position;
if (_mode != BinaryMode.Deserialize)
return TypeCaster<T>.Cast(ReadAsBinary(binaryBytesPos, len, doDetach));
Stream.Seek(len, SeekOrigin.Current);
var offset = Stream.ReadInt();
var retPos = Stream.Position;
Stream.Seek(binaryBytesPos + offset, SeekOrigin.Begin);
_mode = BinaryMode.KeepBinary;
try
{
return Deserialize<T>();
}
finally
{
_mode = BinaryMode.Deserialize;
Stream.Seek(retPos, SeekOrigin.Begin);
}
}
/// <summary>
/// Reads the binary object in binary form.
/// </summary>
private BinaryObject ReadAsBinary(int binaryBytesPos, int dataLen, bool doDetach)
{
try
{
Stream.Seek(dataLen + binaryBytesPos, SeekOrigin.Begin);
var offs = Stream.ReadInt(); // offset inside data
var pos = binaryBytesPos + offs;
var hdr = BinaryObjectHeader.Read(Stream, pos);
if (!doDetach && Stream.CanGetArray)
{
return new BinaryObject(_marsh, Stream.GetArray(), pos, hdr);
}
Stream.Seek(pos, SeekOrigin.Begin);
return new BinaryObject(_marsh, Stream.ReadByteArray(hdr.Length), 0, hdr);
}
finally
{
Stream.Seek(binaryBytesPos + dataLen + 4, SeekOrigin.Begin);
}
}
/// <summary>
/// Reads the full object.
/// </summary>
/// <param name="pos">The position.</param>
/// <param name="typeOverride">The type override.
/// There can be multiple versions of the same type when peer assembly loading is enabled.
/// Only first one is registered in Marshaller.
/// This parameter specifies exact type to be instantiated.</param>
/// <returns>Resulting object</returns>
[SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "hashCode")]
private T ReadFullObject<T>(int pos, Type typeOverride)
{
var hdr = BinaryObjectHeader.Read(Stream, pos);
// Validate protocol version.
BinaryUtils.ValidateProtocolVersion(hdr.Version);
try
{
// Already read this object?
object hndObj;
if (_hnds != null && _hnds.TryGetValue(pos, out hndObj))
return (T) hndObj;
if (hdr.IsUserType && _mode == BinaryMode.ForceBinary)
{
BinaryObject portObj;
if (_detach || !Stream.CanGetArray)
{
Stream.Seek(pos, SeekOrigin.Begin);
portObj = new BinaryObject(_marsh, Stream.ReadByteArray(hdr.Length), 0, hdr);
}
else
{
portObj = new BinaryObject(_marsh, Stream.GetArray(), pos, hdr);
}
T obj = _builder == null ? TypeCaster<T>.Cast(portObj) : TypeCaster<T>.Cast(_builder.Child(portObj));
AddHandle(pos, obj);
return obj;
}
else
{
// Find descriptor.
var desc = hdr.TypeId == BinaryTypeId.Unregistered
? _marsh.GetDescriptor(ReadUnregisteredType(typeOverride))
: _marsh.GetDescriptor(hdr.IsUserType, hdr.TypeId, true, null, typeOverride);
if (desc == null)
{
throw new BinaryObjectException(string.Format(
"No matching type found for object [typeId={0}, userType={1}].",
hdr.TypeId, hdr.IsUserType));
}
if (desc.Type == null)
{
throw new BinaryObjectException(string.Format(
"No matching type found for object [typeId={0}, typeName={1}]. " +
"This usually indicates that assembly with specified type is not loaded on a node. " +
"When using Apache.Ignite.exe, make sure to load assemblies with -assembly parameter. " +
"Alternatively, set IgniteConfiguration.PeerAssemblyLoadingMode to CurrentAppDomain.",
desc.TypeId, desc.TypeName));
}
// Preserve old frame.
var oldFrame = _frame;
// Set new frame.
_frame.Hdr = hdr;
_frame.Pos = pos;
SetCurSchema(desc);
_frame.Struct = new BinaryStructureTracker(desc, desc.ReaderTypeStructure);
_frame.Raw = false;
// Read object.
var obj = desc.Serializer.ReadBinary<T>(this, desc, pos, typeOverride);
_frame.Struct.UpdateReaderStructure();
// Restore old frame.
_frame = oldFrame;
return obj;
}
}
finally
{
// Advance stream pointer.
Stream.Seek(pos + hdr.Length, SeekOrigin.Begin);
}
}
/// <summary>
/// Reads the unregistered type.
/// </summary>
private Type ReadUnregisteredType(Type knownType)
{
var typeName = ReadString(); // Must read always.
var type = knownType ?? Marshaller.ResolveType(typeName);
if (type == null)
{
throw new IgniteException("Could not resolve unregistered type " + typeName);
}
return type;
}
/// <summary>
/// Sets the current schema.
/// </summary>
private void SetCurSchema(IBinaryTypeDescriptor desc)
{
_frame.SchemaMap = null;
if (_frame.Hdr.HasSchema)
{
_frame.Schema = desc.Schema.Get(_frame.Hdr.SchemaId);
if (_frame.Schema == null)
{
_frame.Schema =
BinaryObjectSchemaSerializer.GetFieldIds(_frame.Hdr, Marshaller.Ignite, Stream, _frame.Pos);
desc.Schema.Add(_frame.Hdr.SchemaId, _frame.Schema);
}
}
else
{
_frame.Schema = null;
}
}
/// <summary>
/// Reads the handle object.
/// </summary>
private T ReadHandleObject<T>(int pos, Type typeOverride)
{
// Get handle position.
int hndPos = pos - Stream.ReadInt();
int retPos = Stream.Position;
try
{
object hndObj;
if (_builder == null || !_builder.TryGetCachedField(hndPos, out hndObj))
{
if (_hnds == null || !_hnds.TryGetValue(hndPos, out hndObj))
{
// No such handler, i.e. we trying to deserialize inner object before deserializing outer.
Stream.Seek(hndPos, SeekOrigin.Begin);
hndObj = Deserialize<T>(typeOverride);
}
// Notify builder that we deserialized object on other location.
if (_builder != null)
_builder.CacheField(hndPos, hndObj);
}
return (T) hndObj;
}
finally
{
// Position stream to correct place.
Stream.Seek(retPos, SeekOrigin.Begin);
}
}
/// <summary>
/// Adds a handle to the dictionary.
/// </summary>
/// <param name="pos">Position.</param>
/// <param name="obj">Object.</param>
internal void AddHandle(int pos, object obj)
{
if (_hnds == null)
_hnds = new BinaryReaderHandleDictionary(pos, obj);
else
_hnds.Add(pos, obj);
}
/// <summary>
/// Underlying stream.
/// </summary>
public IBinaryStream Stream
{
get;
private set;
}
/// <summary>
/// Gets the schema for the current object, if any.
/// </summary>
public int[] Schema
{
get { return _frame.Schema; }
}
/// <summary>
/// Seeks to raw data.
/// </summary>
internal void SeekToRaw()
{
Stream.Seek(_frame.Pos + _frame.Hdr.GetRawOffset(Stream, _frame.Pos), SeekOrigin.Begin);
}
/// <summary>
/// Mark current output as raw.
/// </summary>
private void MarkRaw()
{
if (!_frame.Raw)
{
_frame.Raw = true;
SeekToRaw();
}
}
/// <summary>
/// Seeks the field by name.
/// </summary>
private bool SeekField(string fieldName)
{
if (_frame.Raw)
throw new BinaryObjectException("Cannot read named fields after raw data is read.");
if (!_frame.Hdr.HasSchema)
return false;
var actionId = _frame.Struct.CurStructAction;
var fieldId = _frame.Struct.GetFieldId(fieldName);
if (_frame.Schema == null || actionId >= _frame.Schema.Length || fieldId != _frame.Schema[actionId])
{
_frame.SchemaMap = _frame.SchemaMap ?? BinaryObjectSchemaSerializer.ReadSchema(Stream, _frame.Pos,
_frame.Hdr, () => _frame.Schema).ToDictionary();
_frame.Schema = null; // read order is different, ignore schema for future reads
int pos;
if (_frame.SchemaMap == null || !_frame.SchemaMap.TryGetValue(fieldId, out pos))
return false;
Stream.Seek(pos + _frame.Pos, SeekOrigin.Begin);
}
return true;
}
/// <summary>
/// Seeks specified field and invokes provided func.
/// </summary>
private T ReadField<T>(string fieldName, Func<IBinaryStream, T> readFunc, byte expHdr)
{
return SeekField(fieldName) ? Read(readFunc, expHdr) : default(T);
}
/// <summary>
/// Seeks specified field and invokes provided func.
/// </summary>
private T ReadField<T>(string fieldName, Func<BinaryReader, T> readFunc, byte expHdr)
{
return SeekField(fieldName) ? Read(readFunc, expHdr) : default(T);
}
/// <summary>
/// Seeks specified field and invokes provided func.
/// </summary>
private T ReadField<T>(string fieldName, Func<T> readFunc, byte expHdr)
{
return SeekField(fieldName) ? Read(readFunc, expHdr) : default(T);
}
/// <summary>
/// Reads header and invokes specified func if the header is not null.
/// </summary>
private T Read<T>(Func<BinaryReader, T> readFunc, byte expHdr)
{
return Read(() => readFunc(this), expHdr);
}
/// <summary>
/// Reads header and invokes specified func if the header is not null.
/// </summary>
private T Read<T>(Func<IBinaryStream, T> readFunc, byte expHdr)
{
return Read(() => readFunc(Stream), expHdr);
}
/// <summary>
/// Reads header and invokes specified func if the header is not null.
/// </summary>
private T Read<T>(Func<T> readFunc, byte expHdr)
{
var hdr = ReadByte();
if (hdr == BinaryUtils.HdrNull)
return default(T);
if (hdr == BinaryUtils.HdrHnd)
return ReadHandleObject<T>(Stream.Position - 1, null);
if (expHdr != hdr)
throw new BinaryObjectException(string.Format("Invalid header on deserialization. " +
"Expected: {0} but was: {1}", expHdr, hdr));
return readFunc();
}
/// <summary>
/// Reads the enum.
/// </summary>
private static T ReadEnum0<T>(BinaryReader reader, bool keepBinary)
{
var enumType = reader.ReadInt();
var enumValue = reader.ReadInt();
if (!keepBinary)
{
return BinaryUtils.GetEnumValue<T>(enumValue, enumType, reader.Marshaller);
}
return TypeCaster<T>.Cast(new BinaryEnum(enumType, enumValue, reader.Marshaller));
}
/// <summary>
/// Stores current reader stack frame.
/// </summary>
private struct Frame
{
/** Current position. */
public int Pos;
/** Current raw flag. */
public bool Raw;
/** Current type structure tracker. */
public BinaryStructureTracker Struct;
/** Current schema. */
public int[] Schema;
/** Current schema with positions. */
public Dictionary<int, int> SchemaMap;
/** Current header. */
public BinaryObjectHeader Hdr;
}
}
}
| |
using System;
using System.ComponentModel.Composition;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
using NuGet.Common;
namespace NuGet.Commands
{
[Export(typeof(HelpCommand))]
[Command(typeof(NuGetCommandResourceType), "help", "HelpCommandDescription", AltName = "?", MaxArgs = 1,
UsageSummaryResourceName = "HelpCommandUsageSummary", UsageDescriptionResourceName = "HelpCommandUsageDescription",
UsageExampleResourceName = "HelpCommandUsageExamples")]
public class HelpCommand : Command
{
private readonly string _commandExe;
private readonly ICommandManager _commandManager;
private readonly string _helpUrl;
private readonly string _productName;
private string CommandName
{
get
{
if (Arguments != null && Arguments.Count > 0)
{
return Arguments[0];
}
return null;
}
}
[Option(typeof(NuGetCommandResourceType), "HelpCommandAll")]
public bool All { get; set; }
[Option(typeof(NuGetCommandResourceType), "HelpCommandMarkdown")]
public bool Markdown { get; set; }
[ImportingConstructor]
public HelpCommand(ICommandManager commandManager)
: this(commandManager, Assembly.GetExecutingAssembly().GetName().Name, Assembly.GetExecutingAssembly().GetName().Name, CommandLineConstants.NuGetDocsCommandLineReference)
{
}
[SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "3#",
Justification = "We don't use the Url for anything besides printing, so it's ok to represent it as a string.")]
public HelpCommand(ICommandManager commandManager, string commandExe, string productName, string helpUrl)
{
_commandManager = commandManager;
_commandExe = commandExe;
_productName = productName;
_helpUrl = helpUrl;
}
public override void ExecuteCommand()
{
if (!String.IsNullOrEmpty(CommandName))
{
ViewHelpForCommand(CommandName);
}
else if (All && Markdown)
{
ViewMarkdownHelp();
}
else if (All)
{
ViewHelpForAllCommands();
}
else
{
ViewHelp();
}
}
public void ViewHelp()
{
Console.WriteLine("{0} Version: {1}", _productName, this.GetType().Assembly.GetName().Version);
Console.WriteLine("usage: {0} <command> [args] [options] ", _commandExe);
Console.WriteLine("Type '{0} help <command>' for help on a specific command.", _commandExe);
Console.WriteLine();
Console.WriteLine("Available commands:");
Console.WriteLine();
var commands = from c in _commandManager.GetCommands()
orderby c.CommandAttribute.CommandName
select c.CommandAttribute;
// Padding for printing
int maxWidth = commands.Max(c => c.CommandName.Length + GetAltText(c.AltName).Length);
foreach (var command in commands)
{
PrintCommand(maxWidth, command);
Console.WriteLine();
}
if (_helpUrl != null)
{
Console.WriteLine(string.Format(CultureInfo.InvariantCulture,
LocalizedResourceManager.GetString("HelpCommandForMoreInfo"),
_helpUrl));
}
}
private void PrintCommand(int maxWidth, CommandAttribute commandAttribute)
{
// Write out the command name left justified with the max command's width's padding
Console.Write(" {0, -" + maxWidth + "} ", GetCommandText(commandAttribute));
// Starting index of the description
int descriptionPadding = maxWidth + 4;
Console.PrintJustified(descriptionPadding, commandAttribute.Description);
}
private static string GetCommandText(CommandAttribute commandAttribute)
{
return commandAttribute.CommandName + GetAltText(commandAttribute.AltName);
}
public void ViewHelpForCommand(string commandName)
{
ICommand command = _commandManager.GetCommand(commandName);
CommandAttribute attribute = command.CommandAttribute;
Console.WriteLine("usage: {0} {1} {2}", _commandExe, attribute.CommandName, attribute.UsageSummary);
Console.WriteLine();
if (!String.IsNullOrEmpty(attribute.AltName))
{
Console.WriteLine("alias: {0}", attribute.AltName);
Console.WriteLine();
}
Console.WriteLine(attribute.Description);
Console.WriteLine();
if (attribute.UsageDescription != null)
{
const int padding = 5;
Console.PrintJustified(padding, attribute.UsageDescription);
Console.WriteLine();
}
var options = _commandManager.GetCommandOptions(command);
if (options.Count > 0)
{
Console.WriteLine("options:");
Console.WriteLine();
// Get the max option width. +2 for showing + against multivalued properties
int maxOptionWidth = options.Max(o => o.Value.Name.Length) + 2;
// Get the max altname option width
int maxAltOptionWidth = options.Max(o => (o.Key.AltName ?? String.Empty).Length);
foreach (var o in options)
{
Console.Write(" -{0, -" + (maxOptionWidth + 2) + "}", o.Value.Name +
(TypeHelper.IsMultiValuedProperty(o.Value) ? " +" : String.Empty));
Console.Write(" {0, -" + (maxAltOptionWidth + 4) + "}", GetAltText(o.Key.AltName));
Console.PrintJustified((10 + maxAltOptionWidth + maxOptionWidth), o.Key.Description);
}
if (_helpUrl != null)
{
Console.WriteLine();
Console.WriteLine(string.Format(CultureInfo.InvariantCulture,
LocalizedResourceManager.GetString("HelpCommandForMoreInfo"),
_helpUrl));
}
Console.WriteLine();
}
}
private void ViewHelpForAllCommands()
{
var commands = from c in _commandManager.GetCommands()
orderby c.CommandAttribute.CommandName
select c.CommandAttribute;
TextInfo info = CultureInfo.CurrentCulture.TextInfo;
foreach (var command in commands)
{
Console.WriteLine(info.ToTitleCase(command.CommandName) + " Command");
ViewHelpForCommand(command.CommandName);
}
}
/// <summary>
/// Prints help for all commands in markdown format.
/// </summary>
private void ViewMarkdownHelp()
{
var commands = from c in _commandManager.GetCommands()
orderby c.CommandAttribute.CommandName
select c;
foreach (var command in commands)
{
var template = new HelpCommandMarkdownTemplate
{
CommandAttribute = command.CommandAttribute,
Options = from item in _commandManager.GetCommandOptions(command)
select new { Name = item.Value.Name, Description = item.Key.Description }
};
Console.WriteLine(template.TransformText());
}
}
private static string GetAltText(string altNameText)
{
if (String.IsNullOrEmpty(altNameText))
{
return String.Empty;
}
return String.Format(CultureInfo.CurrentCulture, " ({0})", altNameText);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
namespace Unity.Appodeal.Xcode.PBX
{
internal class GUIDToCommentMap
{
private Dictionary<string, string> m_Dict = new Dictionary<string, string>();
public string this[string guid]
{
get {
if (m_Dict.ContainsKey(guid))
return m_Dict[guid];
return null;
}
}
public void Add(string guid, string comment)
{
if (m_Dict.ContainsKey(guid))
return;
m_Dict.Add(guid, comment);
}
public void Remove(string guid)
{
m_Dict.Remove(guid);
}
public string Write(string guid)
{
string comment = this[guid];
if (comment == null)
return guid;
return String.Format("{0} /* {1} */", guid, comment);
}
public void WriteStringBuilder(StringBuilder sb, string guid)
{
string comment = this[guid];
if (comment == null)
sb.Append(guid);
else
{
// {0} /* {1} */
sb.Append(guid).Append(" /* ").Append(comment).Append(" */");
}
}
}
internal class PBXGUID
{
internal delegate string GuidGenerator();
// We allow changing Guid generator to make testing of PBXProject possible
private static GuidGenerator guidGenerator = DefaultGuidGenerator;
internal static string DefaultGuidGenerator()
{
return Guid.NewGuid().ToString("N").Substring(8).ToUpper();
}
internal static void SetGuidGenerator(GuidGenerator generator)
{
guidGenerator = generator;
}
// Generates a GUID.
public static string Generate()
{
return guidGenerator();
}
}
internal class PBXRegex
{
public static string GuidRegexString = "[A-Fa-f0-9]{24}";
}
internal class PBXStream
{
static bool DontNeedQuotes(string src)
{
// using a regex instead of explicit matching slows down common cases by 40%
if (src.Length == 0)
return false;
bool hasSlash = false;
for (int i = 0; i < src.Length; ++i)
{
char c = src[i];
if (Char.IsLetterOrDigit(c) || c == '.' || c == '*' || c == '_')
continue;
if (c == '/')
{
hasSlash = true;
continue;
}
return false;
}
if (hasSlash)
{
if (src.Contains("//") || src.Contains("/*") || src.Contains("*/"))
return false;
}
return true;
}
// Quotes the given string if it contains special characters. Note: if the string already
// contains quotes, then they are escaped and the entire string quoted again
public static string QuoteStringIfNeeded(string src)
{
if (DontNeedQuotes(src))
return src;
return "\"" + src.Replace("\\", "\\\\").Replace("\"", "\\\"").Replace("\n", "\\n") + "\"";
}
// If the given string is quoted, removes the quotes and unescapes any quotes within the string
public static string UnquoteString(string src)
{
if (!src.StartsWith("\"") || !src.EndsWith("\""))
return src;
return src.Substring(1, src.Length - 2).Replace("\\\\", "\u569f").Replace("\\\"", "\"")
.Replace("\\n", "\n").Replace("\u569f", "\\"); // U+569f is a rarely used Chinese character
}
}
internal enum PBXFileType
{
NotBuildable,
Framework,
Source,
Resource,
CopyFile
}
internal class FileTypeUtils
{
internal class FileTypeDesc
{
public FileTypeDesc(string typeName, PBXFileType type)
{
this.name = typeName;
this.type = type;
this.isExplicit = false;
}
public FileTypeDesc(string typeName, PBXFileType type, bool isExplicit)
{
this.name = typeName;
this.type = type;
this.isExplicit = isExplicit;
}
public string name;
public PBXFileType type;
public bool isExplicit;
}
private static readonly Dictionary<string, FileTypeDesc> types =
new Dictionary<string, FileTypeDesc>
{
{ ".a", new FileTypeDesc("archive.ar", PBXFileType.Framework) },
{ ".app", new FileTypeDesc("wrapper.application", PBXFileType.NotBuildable, true) },
{ ".appex", new FileTypeDesc("wrapper.app-extension", PBXFileType.CopyFile) },
{ ".bin", new FileTypeDesc("archive.macbinary", PBXFileType.Resource) },
{ ".s", new FileTypeDesc("sourcecode.asm", PBXFileType.Source) },
{ ".c", new FileTypeDesc("sourcecode.c.c", PBXFileType.Source) },
{ ".cc", new FileTypeDesc("sourcecode.cpp.cpp", PBXFileType.Source) },
{ ".cpp", new FileTypeDesc("sourcecode.cpp.cpp", PBXFileType.Source) },
{ ".swift", new FileTypeDesc("sourcecode.swift", PBXFileType.Source) },
{ ".dll", new FileTypeDesc("file", PBXFileType.NotBuildable) },
{ ".framework", new FileTypeDesc("wrapper.framework", PBXFileType.Framework) },
{ ".h", new FileTypeDesc("sourcecode.c.h", PBXFileType.NotBuildable) },
{ ".pch", new FileTypeDesc("sourcecode.c.h", PBXFileType.NotBuildable) },
{ ".icns", new FileTypeDesc("image.icns", PBXFileType.Resource) },
{ ".xcassets", new FileTypeDesc("folder.assetcatalog", PBXFileType.Resource) },
{ ".inc", new FileTypeDesc("sourcecode.inc", PBXFileType.NotBuildable) },
{ ".m", new FileTypeDesc("sourcecode.c.objc", PBXFileType.Source) },
{ ".mm", new FileTypeDesc("sourcecode.cpp.objcpp", PBXFileType.Source ) },
{ ".nib", new FileTypeDesc("wrapper.nib", PBXFileType.Resource) },
{ ".plist", new FileTypeDesc("text.plist.xml", PBXFileType.Resource) },
{ ".png", new FileTypeDesc("image.png", PBXFileType.Resource) },
{ ".rtf", new FileTypeDesc("text.rtf", PBXFileType.Resource) },
{ ".tiff", new FileTypeDesc("image.tiff", PBXFileType.Resource) },
{ ".txt", new FileTypeDesc("text", PBXFileType.Resource) },
{ ".json", new FileTypeDesc("text.json", PBXFileType.Resource) },
{ ".xcodeproj", new FileTypeDesc("wrapper.pb-project", PBXFileType.NotBuildable) },
{ ".xib", new FileTypeDesc("file.xib", PBXFileType.Resource) },
{ ".strings", new FileTypeDesc("text.plist.strings", PBXFileType.Resource) },
{ ".storyboard",new FileTypeDesc("file.storyboard", PBXFileType.Resource) },
{ ".bundle", new FileTypeDesc("wrapper.plug-in", PBXFileType.Resource) },
{ ".dylib", new FileTypeDesc("compiled.mach-o.dylib", PBXFileType.Framework) },
{ ".tbd", new FileTypeDesc("sourcecode.text-based-dylib-definition", PBXFileType.Framework) }
};
public static bool IsKnownExtension(string ext)
{
return types.ContainsKey(ext);
}
internal static bool IsFileTypeExplicit(string ext)
{
if (types.ContainsKey(ext))
return types[ext].isExplicit;
return false;
}
public static PBXFileType GetFileType(string ext, bool isFolderRef)
{
if (isFolderRef)
return PBXFileType.Resource;
if (!types.ContainsKey(ext))
return PBXFileType.Resource;
return types[ext].type;
}
public static string GetTypeName(string ext)
{
if (types.ContainsKey(ext))
return types[ext].name;
// Xcode actually checks the file contents to determine the file type.
// Text files have "text" type and all other files have "file" type.
// Since we can't reasonably determine whether the file in question is
// a text file, we just take the safe route and return "file" type.
return "file";
}
public static bool IsBuildableFile(string ext)
{
if (!types.ContainsKey(ext))
return true;
if (types[ext].type != PBXFileType.NotBuildable)
return true;
return false;
}
public static bool IsBuildable(string ext, bool isFolderReference)
{
if (isFolderReference)
return true;
return IsBuildableFile(ext);
}
private static readonly Dictionary<PBXSourceTree, string> sourceTree = new Dictionary<PBXSourceTree, string>
{
{ PBXSourceTree.Absolute, "<absolute>" },
{ PBXSourceTree.Group, "<group>" },
{ PBXSourceTree.Build, "BUILT_PRODUCTS_DIR" },
{ PBXSourceTree.Developer, "DEVELOPER_DIR" },
{ PBXSourceTree.Sdk, "SDKROOT" },
{ PBXSourceTree.Source, "SOURCE_ROOT" },
};
private static readonly Dictionary<string, PBXSourceTree> stringToSourceTreeMap = new Dictionary<string, PBXSourceTree>
{
{ "<absolute>", PBXSourceTree.Absolute },
{ "<group>", PBXSourceTree.Group },
{ "BUILT_PRODUCTS_DIR", PBXSourceTree.Build },
{ "DEVELOPER_DIR", PBXSourceTree.Developer },
{ "SDKROOT", PBXSourceTree.Sdk },
{ "SOURCE_ROOT", PBXSourceTree.Source },
};
internal static string SourceTreeDesc(PBXSourceTree tree)
{
return sourceTree[tree];
}
// returns PBXSourceTree.Source on error
internal static PBXSourceTree ParseSourceTree(string tree)
{
if (stringToSourceTreeMap.ContainsKey(tree))
return stringToSourceTreeMap[tree];
return PBXSourceTree.Source;
}
internal static List<PBXSourceTree> AllAbsoluteSourceTrees()
{
return new List<PBXSourceTree>{PBXSourceTree.Absolute, PBXSourceTree.Build,
PBXSourceTree.Developer, PBXSourceTree.Sdk, PBXSourceTree.Source};
}
}
internal class Utils
{
/// Replaces '\' with '/'. We need to apply this function to all paths that come from the user
/// of the API because we store paths to pbxproj and on windows we may get path with '\' slashes
/// instead of '/' slashes
public static string FixSlashesInPath(string path)
{
if (path == null)
return null;
return path.Replace('\\', '/');
}
public static void CombinePaths(string path1, PBXSourceTree tree1, string path2, PBXSourceTree tree2,
out string resPath, out PBXSourceTree resTree)
{
if (tree2 == PBXSourceTree.Group)
{
resPath = CombinePaths(path1, path2);
resTree = tree1;
return;
}
resPath = path2;
resTree = tree2;
}
public static string CombinePaths(string path1, string path2)
{
if (path2.StartsWith("/"))
return path2;
if (path1.EndsWith("/"))
return path1 + path2;
if (path1 == "")
return path2;
if (path2 == "")
return path1;
return path1 + "/" + path2;
}
public static string GetDirectoryFromPath(string path)
{
int pos = path.LastIndexOf('/');
if (pos == -1)
return "";
else
return path.Substring(0, pos);
}
public static string GetFilenameFromPath(string path)
{
int pos = path.LastIndexOf('/');
if (pos == -1)
return path;
else
return path.Substring(pos + 1);
}
public static string[] SplitPath(string path)
{
if (string.IsNullOrEmpty(path))
return new string[]{};
return path.Split(new[]{'/'}, StringSplitOptions.RemoveEmptyEntries);
}
}
} // Unity.Appodeal.Xcode
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.